Cnblog 代码段 指定一种语言 测试
AppleScript:applescript
set myName to "John" -- set objectVar to "string"
copy 33 to myAge -- copy inVar to "outVar"
tell application "Finder"
set savedName to name of front window --将当前窗口finder的名称赋值给savename
close window savedName --关闭上一步保存的窗口名
end tell
property defaultClientName : "Mary Smith" --property:属性
--需要传值的函数
on greetClient(nameOfClient)
display dialog ("Hello " & nameOfClient & "!")
end greetClient
-- 不需要传值的函数
script testGreet
greetClient(defaultClientName)
end script
run testGreet --result: "Hello Mary Smith!"
greetClient("Joe Jones") --result: "Hello Joe Jones!"
ActionScript 3.0:actionscript3 , as3
package
{
import flash.display.Sprite;
public class test extends Sprite
{
public function test()
{
var v8;
trace(v8);
var v9:String;
trace(v9);
var v10:Array = [2,3,4,5];
trace(v10);
var v11:Object = {id:3, name:"ZhangSan",age:18};
trace("Hello world!");
}
}
}
//定义一个字符串str,其值为Hello world
var str:String="Hello world";
//定义一个函数,为clickEvent
var clickEvent:Function=function(){
//此函数触发之后,把Label1的文本改成str
Label1.text= str;
//然后向控制台输出str
trace(str);
}
//之后为Button1添加点击事件的监听器,为clickEvent这个函数
Button1.addEventListener("click",clickEvent);
Shell:bash , shell
?var=123
user*name=runoob
funWithReturn(){
echo "这个函数会对输入的两个数字进行相加运算..."
echo "输入第一个数字: "
read aNum
echo "输入第二个数字: "
read anotherNum
echo "两个数字分别为 $aNum 和 $anotherNum !"
return $(($aNum+$anotherNum))
}
funWithReturn
echo "输入的两个数字之和为 $? !"
ColdFusion:coldfusion , cf
<cfcomponent accessors="true">
<cfproperty name="mongoConfig">
<cfproperty name="mongoFactory">
<cfproperty name="mongoUtil">
<cfscript>
//slightly different implementation for arrays
public any function _filterArray(string predicate, array collection, array accumulator){
for(item in collection){
if( isCollection(item) ) arrayAppend(accumulator, filter(predicate, item, accumulator) );
else if(refindnocase(predicate, item)) arrayAppend(accumulator, item);
}
return accumulator;
}
C:cpp , c
#include <stdio.h>
int main(int argc, char *argv[])
{
long a,b,c,d,e,x;
scanf("%ld",&x);
a=x/10000;
b=x%10000/1000;
c=x%1000/100;
d=x%100/10;
e=x%10;
if(a!=0)
printf ("there are 5 %ld,%ld,%ld,%ld,%ld\n",e,d,c,b,a);
else if(b!=0)
printf ("there are 4 %ld,%ld,%ld,%ld\n",e,d,c,b);
else if(c!=0)
printf ("there are 3 %ld,%ld,%ld\n",e,d,c);
else if(b!=0)
printf ("there are 2 %ld,%ld\n",e,d);
else if(a!=0)
printf ("there are 1 %ld\n",e);
return 0;
}
C#:c# , c-sharp , csharp
public class Program
{
public static void Main()
{
var people = GenerateListOfPeople();
// Write your code here
}
public static List<Person> GenerateListOfPeople()
{
var people = new List<Person>();
people.Add(new Person { FirstName = "Eric", LastName = "Fleming", Occupation = "Dev", Age = 24 });
people.Add(new Person { FirstName = "Steve", LastName = "Smith", Occupation = "Manager", Age = 40 });
people.Add(new Person { FirstName = "Brendan", LastName = "Enrick", Occupation = "Dev", Age = 30 });
people.Add(new Person { FirstName = "Jane", LastName = "Doe", Occupation = "Dev", Age = 35 });
people.Add(new Person { FirstName = "Samantha", LastName = "Jones", Occupation = "Dev", Age = 24 });
return people;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Occupation { get; set; }
public int Age { get; set; }
}
CSS:css
/* Attention seekers */
@import 'attention_seekers/bounce.css';
@import 'attention_seekers/flash.css';
@import 'attention_seekers/pulse.css';
@keyframes flip {
from {
transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0) rotate3d(0, 1, 0, -360deg);
animation-timing-function: ease-out;
}
40% {
transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 150px)
rotate3d(0, 1, 0, -190deg);
animation-timing-function: ease-out;
}
80% {
transform: perspective(400px) scale3d(0.95, 0.95, 0.95) translate3d(0, 0, 0)
rotate3d(0, 1, 0, 0deg);
animation-timing-function: ease-in;
}
to {
transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0) rotate3d(0, 1, 0, 0deg);
animation-timing-function: ease-in;
}
}
.animated.flip {
backface-visibility: visible;
animation-name: flip;
}
.row {
--bs-gutter-x: 1.5rem;
--bs-gutter-y: 0;
display: flex;
flex-wrap: wrap;
margin-top: calc(var(--bs-gutter-y) * -1);
margin-right: calc(var(--bs-gutter-x) / -2);
margin-left: calc(var(--bs-gutter-x) / -2);
}
Delphi:delphi , pascal , pas
unit CollectionTest;
interface
uses
System.Classes;
type
TMyItem = class(TCollectionItem)
end;
TMyCollection = class(TOwnedCollection)
end;
TMyProperty = class(TPersistent)
private
FOwner : TComponent;
FMyCollection: TMyCollection;
procedure SetMyCollection(Value: TMyCollection);
protected
function GetOwner: TPersistent; override; // Required by TCollectionProperty
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
published
property MyCollection: TMyCollection read FMyCollection write SetMyCollection;
end;
TMyComponent = class(TComponent)
private
FMyProperty: TMyProperty;
FMyCollection: TMyCollection;
// procedure SetMyProperty(Value: TMyProperty);
procedure SetMyCollection(Value: TMyCollection);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property MyProperty: TMyProperty read FMyProperty{ write SetMyProperty};
property MyCollection: TMyCollection read FMyCollection write SetMyCollection;
end;
diff&patch:diff patch
import DiffPatcher from './diffpatcher';
export DiffPatcher from './diffpatcher';
export * as formatters from './formatters/index';
export * as console from './formatters/console';
export function create(options) {
return new DiffPatcher(options);
}
class Pipe {
constructor(name) {
this.name = name;
this.filters = [];
}
log(msg) {
console.log(`[jsondiffpatch] ${this.name} pipe, ${msg}`);
}
append(...args) {
this.filters.push(...args);
return this;
}
prepend(...args) {
this.filters.unshift(...args);
return this;
}
}
Erlang:erl , erlang
{application, book_store,
[{description, "exercism.io - book-store"},
{vsn, "0.0.1"},
{modules, []},
{registered, []},
{applications, [kernel,
stdlib]},
{env, []}
]}.
-module(clock).
-export([create/2, is_equal/2, minutes_add/2, to_string/1]).
create(_Hour, _Minute) -> undefined.
is_equal(_Clock1, _Clock2) -> undefined.
minutes_add(_Clock, _Minutes) -> undefined.
to_string(_Clock) -> undefined.
-module(book_store).
-export([total/1]).
total(_Basket) -> undefined.
Groovy:groovy
import geb.buildadapter.BuildAdapterFactory
import static org.testcontainers.containers.BrowserWebDriverContainer.getImageForCapabilities
testValue = true // used in a test in geb-core
String getForkIndex(int total) {
String workerName = System.getProperty('org.gradle.test.worker')
int workerNumber = workerName ? ((workerName =~ /[^\d]*([\d]+)/)[0][1]).toInteger() : 0
(workerNumber % total).toString()
}
void setPortIndexProperty(String index) {
System.setProperty('geb.port.index', index)
}
BrowserWebDriverContainer containerForDriver(String driverName) {
def container
switch (driverName) {
case "chrome":
container = containerForCapabilities(new ChromeOptions())
break
default:
throw new Exception("Unsupported dockerized driver: $driverName")
}
container.withRecordingMode(BrowserWebDriverContainer.VncRecordingMode.SKIP, null)
.start()
ResourceReaper.instance().registerContainerForCleanup(container.containerId, container.dockerImageName)
container
}
driver = "htmlunit"
if (!BuildAdapterFactory.getBuildAdapter(this.class.classLoader).reportsDir) {
reportsDir = "build/geb"
}
def sauceLabsBrowser = System.getProperty("geb.saucelabs.browser")
if (sauceLabsBrowser) {
setPortIndexProperty(getForkIndex(5))
driver = {
new SauceLabsDriverFactory().create()
}
}
Java:java
package Maths;
import java.util.Random;
public class Ceil {
public static void main(String[] args) {
Random random = new Random();
for (int i = 1; i <= 1000; ++i) {
double randomNumber = random.nextDouble();
assert ceil(randomNumber) == Math.ceil(randomNumber);
}
}
/**
* Returns the smallest (closest to negative infinity)
*
* @param number the number
* @return the smallest (closest to negative infinity) of given {@code number}
*/
public static double ceil(double number) {
if (number - (int) number == 0) {
return number;
} else if (number - (int) number > 0) {
return (int) (number + 1);
} else {
return (int) number;
}
}
}
JavaFX:jfx , javafx
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return firstName + " " + lastName;
}
}
JavaScript:js , jscript , javascript
lass DoubleLinkedListNode {
// Double Linked List Node built specifically for LFU Cache
constructor (key, val) {
this.key = key
this.val = val
}
}
class DoubleLinkedList {
// Double Linked List built specifically for LFU Cache
constructor () {
this.head = new DoubleLinkedListNode(null, null)
}
_positionNode (node) {
// Helper function to position a node based on the frequency of the key
while (node.prev.key && node.prev.freq > node.freq) {
}
}
add (node) {
// Adds the given node to the end of the list (before rear) and positions it based on frequency
const temp = this.rear.prev
}
remove (node) {
// Removes and returns the given node from the list
const tempLast = node.prev
return node
}
}
class LFUCache {
// LFU Cache to store a given capacity of data
constructor (capacity) {
this.list = new DoubleLinkedList()
}
cacheInfo () {
// Return the details for the cache instance [hits, misses, capacity, current_size]
return `CacheInfo(hits=${this.hits}, misses=${this.miss}, capacity=${this.capacity}, current size=${this.numKeys})`
}
set (key, value) {
// Sets the value for the input key and updates the Double Linked List
if (!(key in this.cache)) {
if (this.numKeys >= this.capacity) {
const keyToDelete = this.list.head.next.key
delete this.cache[keyToDelete]
this.numKeys -= 1
}
this.cache[key] = new DoubleLinkedListNode(key, value)
this.list.add(this.cache[key])
this.numKeys += 1
} else {
const node = this.list.remove(this.cache[key])
node.val = value
this.list.add(node)
}
}
get (key) {
// Returns the value for the input key and updates the Double Linked List. Returns null if key is not present in cache
if (key in this.cache) {
this.hits += 1
this.list.add(this.list.remove(this.cache[key]))
return this.cache[key].val
}
this.miss += 1
return null
}
}
function main () {
// Example 1 (Small Cache)
const cache = new LFUCache(2)
cache.set(1, 1)
cache.set(2, 2)
console.log(cache.get(1))
cache.set(3, 3)
console.log(cache.get(2)) // cache miss
cache.set(4, 4)
console.log(cache.get(1)) // cache miss
console.log(cache.get(3))
console.log(cache.get(4))
console.log('Example Cache: ', cache.cacheInfo(), '\n')
// Example 2 (Computing Fibonacci Series - 100 terms)
function fib (num, cache = null) {
if (cache) {
const value = cache.get(num)
if (value) { return value }
}
if (num === 1 || num === 2) { return 1 }
const result = fib(num - 1, cache) + fib(num - 2, cache)
if (cache) { cache.set(num, result) }
return result
}
const fibCache = new LFUCache(100)
for (let i = 1; i <= 100; i++) { fib(i, fibCache) }
console.log('Fibonacci Series Cache: ', fibCache.cacheInfo(), '\n')
}
main()
Perl:perl , pl , Perl
#
# A simple HTTP proxy server for debugging
#
# $ HTTP_PROXY=http://127.0.0.1:3000 mojo get http://mojolicious.org
#
use Mojolicious::Lite -signatures;
any '/*whatever' => {whatever => ''} => sub ($c) {
my $req = $c->req;
my $method = $req->method;
my $url = $req->url->to_abs;
my $headers = $req->headers->clone->dehop->to_hash;
$c->app->log->debug(qq{Forwarding "$method $url"});
$c->proxy->start_p($c->ua->build_tx($method, $url, $headers))->catch(sub ($err) {
$c->render(data => $err, status => 400);
});
};
app->start;
PHP:php
<?php
namespace PhpOffice\PhpSpreadsheet\Helper;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
* Helper class to be used in sample code.
*/
class Sample
{
public function isCli()
{
return PHP_SAPI === 'cli';
}
/** Return the filename currently being executed. @return string */
public function getScriptFilename()
{
return basename($_SERVER['SCRIPT_FILENAME'], '.php');
}
public function isIndex()
{
return $this->getScriptFilename() === 'index';
}
public function getPageHeading()
{
return $this->isIndex() ? '' : '<h1>' . str_replace('_', ' ', $this->getScriptFilename()) . '</h1>';
}
public function getSamples()
{
// Populate samples
$baseDir = realpath(__DIR__ . '/../../../samples');
$regex = new RegexIterator($iterator, '/^.+\.php$/', RecursiveRegexIterator::GET_MATCH);
$files = [];
foreach ($regex as $file) {
$file = str_replace(str_replace('\\', '/', $baseDir) . '/', '', str_replace('\\', '/', $file[0]));
if (!in_array($category, ['.', 'boostrap', 'templates'])) { }
}
// Sort everything
ksort($files);
foreach ($files as &$f) {
asort($f);
}
return $files;
}
public function write(Spreadsheet $spreadsheet, $filename, array $writers = ['Xlsx', 'Xls']): void
{
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$spreadsheet->setActiveSheetIndex(0);
foreach ($writers as $writerType) {
$path = $this->getFilename($filename, mb_strtolower($writerType));
}
$this->logEndingNotes();
}
protected function isDirOrMkdir(string $folder): bool
{
return \is_dir($folder) || \mkdir($folder);
}
/**
* Log a line about the read operation.
* @param float $callStartTime
*/
public function logRead($format, $path, $callStartTime): void
{
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
$message = "Read {$format} format from <code>{$path}</code> in " . sprintf('%.4f', $callTime) . ' seconds';
$this->log($message);
}
}
text:text , plain
2021-04-01 14:07:37.333 - ShareX starting.
2021-04-01 14:07:37.340 - Version: 13.3 Portable
2021-04-01 14:07:37.340 - Build: Release
2021-04-01 14:07:37.340 - Command line: "D:\APP\ShareX-portable\ShareX.exe" -silent
2021-04-01 14:07:37.340 - Personal path: D:\APP\ShareX-portable\ShareX
2021-04-01 14:07:37.340 - Personal path detection method: Portable file (D:\APP\ShareX-portable\Portable)
2021-04-01 14:07:37.340 - Operating system: Windows 10 Pro (64-bit)
2021-04-01 14:07:37.340 - Running as elevated process: False
2021-04-01 14:07:37.355 - Flags: Portable, SilentRun
2021-04-01 14:07:37.549 - ApplicationConfig load started: D:\APP\ShareX-portable\ShareX\ApplicationConfig.json
2021-04-01 14:07:40.411 - ApplicationConfig load finished: D:\APP\ShareX-portable\ShareX\ApplicationConfig.json
2021-04-01 14:07:40.427 - MainForm init started.
2021-04-01 14:07:40.427 - UploadersConfig load started: D:\APP\ShareX-portable\ShareX\UploadersConfig.json
2021-04-01 14:07:40.833 - UploadersConfig load finished: D:\APP\ShareX-portable\ShareX\UploadersConfig.json
2021-04-01 14:07:40.848 - HotkeysConfig load started: D:\APP\ShareX-portable\ShareX\HotkeysConfig.json
2021-04-01 14:07:41.122 - HotkeysConfig load finished: D:\APP\ShareX-portable\ShareX\HotkeysConfig.json
2021-04-01 14:07:42.292 - MainForm init finished.
Python:py , python
#!/usr/bin/env python3
from .number_theory.prime_numbers import next_prime
class HashTable:
"""
Basic Hash Table example with open addressing and linear probing
"""
def __init__(self, size_table, charge_factor=None, lim_charge=None):
self.size_table = size_table
self.values = [None] * self.size_table
self.lim_charge = 0.75 if lim_charge is None else lim_charge
self.charge_factor = 1 if charge_factor is None else charge_factor
self.__aux_list = []
self._keys = {}
def keys(self):
return self._keys
def balanced_factor(self):
return sum([1 for slot in self.values if slot is not None]) / (
self.size_table * self.charge_factor
)
def hash_function(self, key):
return key % self.size_table
def _step_by_step(self, step_ord):
print(f"step {step_ord}")
print([i for i in range(len(self.values))])
print(self.values)
def bulk_insert(self, values):
i = 1
self.__aux_list = values
for value in values:
self.insert_data(value)
self._step_by_step(i)
i += 1
def _set_value(self, key, data):
self.values[key] = data
self._keys[key] = data
def _collision_resolution(self, key, data=None):
new_key = self.hash_function(key + 1)
while self.values[new_key] is not None and self.values[new_key] != key:
if self.values.count(None) > 0:
new_key = self.hash_function(new_key + 1)
else:
new_key = None
break
return new_key
def rehashing(self):
survivor_values = [value for value in self.values if value is not None]
self.size_table = next_prime(self.size_table, factor=2)
self._keys.clear()
self.values = [None] * self.size_table # hell's pointers D: don't DRY ;/
for value in survivor_values:
self.insert_data(value)
def insert_data(self, data):
key = self.hash_function(data)
if self.values[key] is None:
self._set_value(key, data)
elif self.values[key] == data:
pass
else:
collision_resolution = self._collision_resolution(key, data)
if collision_resolution is not None:
self._set_value(collision_resolution, data)
else:
self.rehashing()
self.insert_data(data)
Ruby:ruby , rails , ror , rb
#!/usr/bin/env ruby
require 'logger'
log = Logger.new(STDERR)
def do_log(log)
log.debug('do_log1') { "debug" }
log.info('do_log2') { "info" }
log.warn('do_log3') { "warn" }
log.error('do_log4') { "error" }
log.fatal('do_log6') { "fatal" }
log.unknown('do_log7') { "unknown" }
end
log.level = Logger::DEBUG # Default.
do_log(log)
puts "Set severity threshold 'WARN'."
log.level = Logger::WARN
do_log(log)
puts "Change datetime format. Thanks to Daniel Berger."
log.datetime_format = "%d-%b-%Y@%H:%M:%S"
do_log(log)
SASS&SCSS:sass , scss
/**
* Set up a decent box model on the root element
*/
html {
box-sizing: border-box;
}
/**
* Make all elements from the DOM inherit from the parent box-sizing
* Since `*` has a specificity of 0, it does not override the `html` value
* making all elements inheriting from the root box-sizing value
* See: https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/
*/
*,
*::before,
*::after {
box-sizing: inherit;
}
/**
* Basic styles for links
*/
a {
color: $brand-color;
text-decoration: none;
@include on-event {
color: $text-color;
text-decoration: underline;
}
}
/**
* Clear inner floats
*/
.clearfix::after {
clear: both;
content: '';
display: table;
}
.hide-text {
overflow: hidden;
padding: 0; /* 1 */
text-indent: 101%;
white-space: nowrap;
}
Scala:scala
package scala.tools.scalap
import scala.tools.scalap.scalax.rules.scalasig._
import ClassFileParser.{ ConstValueIndex, Annotation }
import Main.{ SCALA_SIG_ANNOTATION, BYTES_VALUE }
/** Temporary decoder. This would be better off in the scala.tools.nsc
* but right now the compiler won't acknowledge scala.tools.scalap
* when it's bootstrapping, so the reference has to go from here to there.
*/
object Decode {
private def getAliasSymbol(t: Type): Symbol = t match {
case TypeRefType(_, s, _) => s
case PolyType(typeRef, _) => getAliasSymbol(typeRef)
case _ => NoSymbol
}
def scalaSigBytes(name: String): Option[Array[Byte]] = scalaSigBytes(name, appLoader)
def scalaSigBytes(name: String, classLoader: ScalaClassLoader): Option[Array[Byte]] = {
val bytes = classLoader.classBytes(name)
val reader = new ByteArrayReader(bytes)
val cf = new Classfile(reader)
cf.scalaSigAttribute map (_.data)
}
/** Return the bytes representing the annotation
*/
def scalaSigAnnotationBytes(name: String): Option[Array[Byte]] = scalaSigAnnotationBytes(name, appLoader)
def scalaSigAnnotationBytes(name: String, classLoader: ScalaClassLoader): Option[Array[Byte]] = {
val bytes = classLoader.classBytes(name)
val byteCode = ByteCode(bytes)
val classFile = ClassFileParser.parse(byteCode)
import classFile._
classFile annotation SCALA_SIG_ANNOTATION map { case Annotation(_, els) =>
val bytesElem = els.find(x => constant(x.elementNameIndex) == BYTES_VALUE).orNull
val _bytes = bytesElem.elementValue match { case ConstValueIndex(x) => constantWrapped(x) case x => throw new MatchError(x) }
val bytes = _bytes.asInstanceOf[StringBytesPair].bytes
val length = ByteCodecs.decode(bytes)
bytes take length
}
}
private[scala] def caseParamNames(path: String): Option[List[String]] = {
val (outer, inner) = (path indexOf '$') match {
case -1 => (path, "")
case x => (path take x, path drop (x + 1))
}
for {
clazz <- appLoader.tryToLoadClass[AnyRef](outer)
ssig <- ScalaSigParser.parse(clazz)
}
yield {
val f: PartialFunction[Symbol, List[String]] =
if (inner == "") {
case x: MethodSymbol if x.isCaseAccessor && (x.name endsWith " ") => List(x.name dropRight 1)
}
else {
case x: ClassSymbol if x.name == inner =>
val xs = x.children filter (child => child.isCaseAccessor && (child.name endsWith " "))
xs.toList map (_.name dropRight 1)
}
(ssig.symbols collect f).flatten.toList
}
}
private[scala] def typeAliases(pkg: String) = {
for {
clazz <- appLoader.tryToLoadClass[AnyRef](pkg + ".package")
ssig <- ScalaSigParser.parse(clazz)
}
yield {
val typeAliases = ssig.symbols collect { case x: AliasSymbol => x }
Map(typeAliases map (x => (x.name, getAliasSymbol(x.infoType).path)): _*)
}
}
}
SQL:sql
if OBJECT_ID(N'GlueWaterMaster',N'U') is not null
BEGIN
print '表GlueWaterMaster 存在!'
END
else
BEGIN
--创建胶水Master表
create table GlueWaterMaster
(
[UID] int identity(1,1)primary key, --主键
[Item_No] varchar(40), --部品番号
[Item_Name] varchar(40), --部品名称
[CWSJ_NeedMinMinute] int, --常温时间需要多久 分钟
[TPSJ_NeedMinMinute] int, --脱泡时间需要多久 分钟
[HWSJ_NeedMinMinute] int, --恒温时间需要多久
[HWSJ_NeedMaxMinute] int, --恒温时间最长允许多久 分钟
[IsDefoaming] bit, --是否脱泡处理
[Create_User] varchar(40), --创建人
[Create_Date] datetime, --创建日期
[OpenValidDays] int, --开封后有效时间(以天计)
[Update_User] varchar(40), --更行人
[Update_Date] datetime, --更新时间
[IsValid] bit --数据是否有效
)
print '表GlueWaterMaster 不存在,已重新创建!'
END
go
-------------------------------------------------------------------------
--Title:查询胶水管理Master
--Autho:WK
--Remark: 查询胶水管理master表的维护的规则
-------------------------------------------------------------------------
alter proc GWM_QueryTheMaster
@ItemNO varchar(40)
as
begin
select * from dbo.GlueWaterMaster
where IsValid = 0 and Item_No like '%' + @ItemNO + '%'
end
go
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建时间' ,
@level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE',
@level1name=N'Manager_Approvalauthority', @level2type=N'COLUMN', @level2name=N'Create_Date'
With CTE_DelUsers as( --找到要删除人员的规则,等级
select Del.UID DelUID, TRule.ApprovalRuleCode, TRule.GroupLevel
from @DeleteUID Del join dbo.Manager_Approvalauthority TRule on Del.UID = TRule.UID
where TRule.IsValid = 0
)
select * from CTE_DelUsers
Visual Basic:vb , vbnet
Imports System.IO
Imports System.Reflection
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Public Class BuildSource
Sub New()
End Sub
Sub New(rootNamespace As String)
_RootNamespace = rootNamespace
End Sub
Public Property References As ICollection(Of BuildReference) = New List(Of BuildReference) From
{
BuildReference.ByName("System.Runtime"),
BuildReference.ByName("netstandard"),
BuildReference.ByName("System.Collections"),
BuildReference.ByName("System.ComponentModel.Annotations"),
BuildReference.ByName("System.Data.Common"),
BuildReference.ByName("System.Linq.Expressions"),
BuildReference.ByName("System.Runtime"),
BuildReference.ByName("System.Text.RegularExpressions")
}
Public Property TargetDir As String
Public Property Sources As ICollection(Of String) = New List(Of String)
Private _RootNamespace As String = Nothing
Public Function BuildInMemory() As Assembly
Dim projectName = Path.GetRandomFileName()
Dim refs = New List(Of MetadataReference)
For Each reference In References
refs.AddRange(reference.References)
Next
Dim compilation = VisualBasicCompilation.Create(
assemblyName:=projectName,
syntaxTrees:=Sources.Select(Function(s) SyntaxFactory.ParseSyntaxTree(s)),
references:=refs,
New VisualBasicCompilationOptions(
outputKind:=OutputKind.DynamicallyLinkedLibrary,
rootNamespace:=_RootNamespace))
Dim asm As Assembly
Using memStream = New MemoryStream()
Dim result = compilation.Emit(memStream)
If Not result.Success Then
Throw New InvalidOperationException(
$"Build failed. Diagnostics: {String.Join(Environment.NewLine, result.Diagnostics)}")
End If
asm = Assembly.Load(memStream.ToArray())
End Using
Return asm
End Function
End Class
XML:xml , xhtml , xslt , html
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp3.1;net40;net46</TargetFrameworks>
<LangVersion>8.0</LangVersion>
<Version>0.95.4</Version>
<NoWarn>$(NoWarn);NU1605</NoWarn>
<Configurations>Debug;Release</Configurations>
<AssemblyName>ClosedXML.Sandbox</AssemblyName>
<RootNamespace>ClosedXML.Sandbox</RootNamespace>
</PropertyGroup>
Html
<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
<tr>
<td align="center" class="biaoti" height="60">受理员业务统计表</td>
</tr>
<tr>
<td align="right" height="25">2017-01-02---2017-05-02</td>
</tr>
</table>
<table width="100%" border="0" cellspacing="1" cellpadding="4" bgcolor="#cccccc" class="tabtop13" align="center">
<tr>
<td colspan="2" class="btbg font-center titfont" rowspan="2">受理员</td>
<td width="10%" class="btbg font-center titfont" rowspan="2">受理数</td>
<td width="10%" class="btbg font-center titfont" rowspan="2">自办数</td>
<td width="10%" class="btbg font-center titfont" rowspan="2">直接解答</td>
<td colspan="2" class="btbg font-center titfont">拟办意见</td>
<td colspan="2" class="btbg font-center titfont">返回修改</td>
<td colspan="3" class="btbg font-center titfont">工单类型</td>
</tr>
<tr>
<td width="8%" class="btbg font-center">同意</td>
<td width="8%" class="btbg font-center">比例</td>
<td width="8%" class="btbg font-center">数量</td>
<td width="8%" class="btbg font-center">比例</td>
<td width="8%" class="btbg font-center">建议件</td>
<td width="8%" class="btbg font-center">诉求件</td>
<td width="8%" class="btbg font-center">咨询件</td>
</tr>
<tr>
<td width="7%" rowspan="8" class="btbg1 font-center">受理处</td>
<td width="7%" class="btbg2">王艳</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
XAML
<UniformGrid VerticalAlignment="Top">
<WrapPanel Margin="8,2">
<Button Content="新出库申请" Click="Button_Click_1"/>
<Button Content="一期申请" Click="Button_Click_2"/>
<Button Content="部品类别" Click="Button_Click_3"/>
<Button Content="制造查看出库" Click="Button_Click_4"/>
<Button Content="一般贸易报废查询" Click="Button_Click_46"/>
</WrapPanel>
<WrapPanel Margin="8,2">
<Button Content="呆滞品" Click="Button_Click_5"/>
<Button Content="Lot追溯" Click="Button_Click_6"/>
<Button Content="AC部品分类管理报表" Click="Button_Click_7"/>
<Button Content="转仓" Click="Button_Click_8"/>
<Button Content="转仓List" Click="Button_Click_9"/>
</WrapPanel>
<UniformGrid/>
Objective C:objc , obj-c
#import <Foundation/Foundation.h>
#import "Person.h"
//类别与继承:
//相同目的:无法满足需求时,需要更新属性或方法拓展
//不同点:继承既能够扩展成员变量也能够拓展成员方法;类别只能够添加方法
//不同点:继承添加的新方法和新属性都只能在子类对象中调用;类别添加的新方法可以用父类对象调用
#import <Foundation/Foundation.h>
#import "XiaoMing.h"
#import "Person.h"
#import "Person+Extension.h"
#import "NSString+Extension.h"
@interface Person : NSObject
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign)int age;
-(void)run;
-(void)study;
-(void)sleep;
@end
@interface XiaoMing : Person
@property(nonatomic,assign)float height;//继承可以实现
-(void)eat;
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
XiaoMing *xiaoming = [[XiaoMing alloc]init];
xiaoming.age = 17;
xiaoming.name = @"";
xiaoming.height = 180;
Person *person = [[Person alloc]init];
person.age = 80;
person.name = @"xiaoming";
//person.height,是错误的
[person eat];
NSString *cString = [NSString returnAConstSting];
NSLog(@"常量字符串是:%@",cString);
}
return 0;
}
F#:f# f-sharp , fsharp
let makeGame target =
// Build a lambda expression that is the function that plays the game.
let game = fun guess ->
if guess = target then
System.Console.WriteLine("You win!")
else
System.Console.WriteLine("Wrong. Try again.")
// Now just return it.
game
let playGame = makeGame 7
// Send in some guesses.
playGame 2
playGame 9
playGame 7
let compose4curried =
fun op1 ->
fun op2 ->
fun n -> op1 (op2 n)
let makeGame2 target guess =
if guess = target then
System.Console.WriteLine("You win!")
else
System.Console.WriteLine("Wrong. Try again.")
let playGame2 = makeGame2 7
playGame2 2
playGame2 9
playGame2 7
let alphaGame2 = makeGame2 'q'
alphaGame2 'c'
alphaGame2 'r'
alphaGame2 'j'
alphaGame2 'q'
open System
open System.IO
let printTotalFileBytes path =
async {
let! bytes = File.ReadAllBytesAsync(path) |> Async.AwaitTask
let fileName = Path.GetFileName(path)
printfn $"File {fileName} has %d{bytes.Length} bytes"
}
[<EntryPoint>]
let main argv =
argv
|> Seq.map printTotalFileBytes
|> Async.Parallel
|> Async.Ignore
|> Async.RunSynchronously
0
R:r , s , splus
Fact <- function(n){
if(n < 0) print("warning: your input is wrong!")
else if(n == 0 | n == 1) print(1)
else {
s <- numeric()
s[1] = 1
for(i in 2 : n){
s[i] = i * s[i - 1]
}
return(s[n])
}
}
Fact(5)
Fact(6)
# Quick sort in R:
quick.sort <- function(elements.vec) {
if(length(elements.vec) <= 1) {
return(elements.vec)
}
pivot <- elements.vec[1]
non.pivot <- elements.vec[-1]
pivot_less <- quick.sort(non.pivot[non.pivot < pivot])
pivot_greater <- quick.sort(non.pivot[non.pivot >= pivot])
return(c(pivot_less, pivot, pivot_greater))
}
# Stooge sort in R:
stooge.sort <- function(elements.vec) {
i = 1
j = length(elements.vec)
if (elements.vec[j] < elements.vec[i]) elements.vec[c(j, i)] = elements.vec[c(i, j)]
if (j - i > 1) {
t = (j - i + 1) %/% 3
elements.vec[i:(j - t)] = stooge.sort(elements.vec[i:(j - t)])
elements.vec[(i + t):j] = stooge.sort(elements.vec[(i + t):j])
elements.vec[i:(j - t)] = stooge.sort(elements.vec[i:(j - t)])
}
elements.vec
}
matlab:matlab
function formatWhitespace(filename)
% FORMATWHITESPACE Formats whitespace and indentation of a document
import matlab.desktop.editor.*
if nargin < 1, filename = ''; end
d = getDoc(filename);
oldLines = textToLines(d.Text);
% Smart indent as AllFunctionIndent
% Using undocumented feature from http://undocumentedmatlab.com/blog/changing-system-preferences-programmatically
editorProp = 'EditorMFunctionIndentType';
oldVal = com.mathworks.services.Prefs.getStringPref(editorProp);
com.mathworks.services.Prefs.setStringPref(editorProp, 'AllFunctionIndent');
restoreSettings = onCleanup(@() com.mathworks.services.Prefs.setStringPref(editorProp, oldVal));
d.smartIndentContents()
% Preserve crafted continuations of line
lines = textToLines(d.Text);
iContinuation = ~cellfun('isempty',strfind(lines, '...'));
iComment = ~cellfun('isempty',regexp(lines, '^ *%([^%]|$)','once'));
pAfterDots = find(iContinuation & ~iComment)+1;
for ii = 1:numel(pAfterDots)
% Carry over the change in space due to smart-indenting from the
% first continuation line to the last
p = pAfterDots(ii);
nWhiteBefore = find(~isspace(oldLines{p-1}),1,'first');
nWhiteAfter = find(~isspace(lines{p-1}),1,'first');
df = nWhiteAfter - nWhiteBefore;
if df > 0
lines{p} = [blanks(df) oldLines{p}];
elseif df < 0
df = min(abs(df)+1, find(~isspace(oldLines{p}),1,'first'));
lines{p} = oldLines{p}(df:end);
else
lines{p} = oldLines{p};
end
end
% Remove whitespace lines
idx = cellfun('isempty',regexp(lines, '[^ \t\n]','once'));
lines(idx) = {''};
d.Text = linesToText(lines);
end
function d = getDoc(filename)
import matlab.desktop.editor.*
if ~ischar(filename)
error('formatWhitespace:charFilename','The FILENAME should be a char.')
end
try
isEditorAvailable();
catch
error('formatWhitespace:noEditorApi','Check that the Editor API is available.')
end
if isempty(filename)
d = getActive();
else
% TODO: open file if it isn't open in the editor already
d = findOpenDocument(filename);
try
[~,filenameFound] = fileparts(d.Filename);
catch
filenameFound = '';
end
isExactMatch = strcmp(filename, filenameFound);
if ~isExactMatch
error('formatWhitespace:filenameNotFound','Filename "%s" not found in the editor.', filename)
end
end
end
swift:swift
import Foundation
#if canImport(Darwin)
import Darwin
private let globFunction = Darwin.glob
#elseif canImport(Glibc)
import Glibc
private let globFunction = Glibc.glob
#else
#error("Unsupported platform")
#endif
struct Glob {
static func resolveGlob(_ pattern: String) -> [String] {
let globCharset = CharacterSet(charactersIn: "*?[]")
guard pattern.rangeOfCharacter(from: globCharset) != nil else {
return [pattern]
}
var globResult = glob_t()
defer { globfree(&globResult) }
let flags = GLOB_TILDE | GLOB_BRACE | GLOB_MARK
guard globFunction(pattern.cString(using: .utf8)!, flags, nil, &globResult) == 0 else {
return []
}
#if os(Linux)
let matchCount = globResult.gl_pathc
#else
let matchCount = globResult.gl_matchc
#endif
return (0..<Int(matchCount)).compactMap { index in
return globResult.gl_pathv[index].flatMap { String(validatingUTF8: $0) }
}
}
}
GO:go , golang
package errors
// New returns an error that formats as the given text.
// Each call to New returns a distinct error value even if the text is identical.
func New(text string) error {
return &errorString{text}
}
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
ackage errors_test
import (
"fmt"
"time"
)
// MyError is an error implementation that includes a time and message.
type MyError struct {
When time.Time
What string
}
func (e MyError) Error() string {
return fmt.Sprintf("%v: %v", e.When, e.What)
}
func oops() error {
return MyError{
time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC),
"the file system has gone away",
}
}
func Example() {
if err := oops(); err != nil {
fmt.Println(err)
}
// Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away
}
type poser struct {
msg string
f func(error) bool
}
var poserPathErr = &fs.PathError{Op: "poser"}
func (p *poser) Error() string { return p.msg }
func (p *poser) Is(err error) bool { return p.f(err) }
func (p *poser) As(err interface{}) bool {
switch x := err.(type) {
case **poser:
*x = p
case *errorT:
*x = errorT{"poser"}
case **fs.PathError:
*x = poserPathErr
default:
return false
}
return true
}
转载保留源出处即可,商业使用请自行鉴别,使用本博客中公开内容做任何违法犯罪于本作者无关