file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
view_test.go
); err != nil { e.tb.Fatal("Error:", err) } if err := e.Core.Compilers.Sync(ctx); err != nil { e.tb.Fatal("Error:", err) } if err := e.Core.Settings.Sync(ctx); err != nil { e.tb.Fatal("Error:", err) } } func (e *TestEnv) CreateUserRoles(login string, roles ...string) error { for _, role := range roles { ...
e.tb.Fatal("Error:", err) } return &TestUser{ User: user, Password: password, env: e, } } type testCheckState struct { tb testing.TB checks []json.RawMessage pos int reset bool path string } func (s *testCheckState) Check(data any) { raw, err := json.MarshalIndent(data, "", " ") ...
random_line_split
view_test.go
_ = db.ApplyMigrations(ctx, env.Core.DB, "solve_data", migrations.Data, db.WithZeroMigration) if err := db.ApplyMigrations(ctx, env.Core.DB, "solve", migrations.Schema); err != nil { tb.Fatal("Error:", err) } if err := db.ApplyMigrations(ctx, env.Core.DB, "solve_data", migrations.Data); err != nil { tb.Fatal("E...
TestHealth
identifier_name
client.go
.org/x/net/context" ) // Client used to communicate with Cloud Foundry type Client struct { Config Config Endpoint Endpoints } type Endpoints struct { Links Links `json:"links"` } type Links struct { AuthEndpoint EndpointUrl `json:"login"` TokenEndpoint EndpointUrl `json:"uaa"` } type EndpointUrl struct { ...
} // Create the HTTP Request
random_line_split
client.go
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY,...
func getClientAuth(ctx context.Context, config Config, endpoints *Endpoints) Config { authConfig := &clientcredentials.Config{ ClientID: config.ClientID, ClientSecret: config.ClientSecret, TokenURL: endpoints.Links.TokenEndpoint.URL + "/oauth/token", } config.TokenSource = authConfig.TokenSource(ctx...
{ authConfig := &oauth2.Config{ ClientID: "cf", Scopes: []string{""}, Endpoint: oauth2.Endpoint{ AuthURL: endpoints.Links.AuthEndpoint.URL + "/oauth/auth", TokenURL: endpoints.Links.TokenEndpoint.URL + "/oauth/token", }, } // Token is expected to have no "bearer" prefix token := &oauth2.Token{ A...
identifier_body
client.go
kipSslValidation bool `json:"skip_ssl_validation"` HttpClient *http.Client Token string `json:"auth_token"` TokenSource oauth2.TokenSource tokenSourceDeadline *time.Time UserAgent string `json:"user_agent"` Origin string `json:"-"` } type LoginHint struct...
{ return resp, CloudFoundryHTTPError{ StatusCode: resp.StatusCode, Status: resp.Status, Body: body, } }
conditional_block
client.go
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY,...
() *http.Transport { defaultTransport := http.DefaultTransport.(*http.Transport) return &http.Transport{ Proxy: defaultTransport.Proxy, TLSHandshakeTimeout: defaultTransport.TLSHandshakeTimeout, ExpectContinueTimeout: defaultTransport.ExpectContinueTimeout, } } // decodeBody is used to JSON ...
shallowDefaultTransport
identifier_name
room_model.rs
) -> anyhow::Result<&mut Room> { let res = self.get_rooms_mut().get_mut(room_id); if res.is_none() { let s = format!("this room is not exit!room_id:{}", room_id); anyhow::bail!(s) } Ok(res.unwrap()) } ///根据房间id获得房间的只读指针 fn get_ref_room_by_room_id(&mut...
ex < 0 { return; }
identifier_body
room_model.rs
(res.unwrap()) } ///根据房间id获得房间的只读指针 fn get_ref_room_by_room_id(&mut self, room_id: &u32) -> anyhow::Result<&Room> { let res = self.get_rooms_mut().get(room_id); if res.is_none() { anyhow::bail!("this room is not exit,room_id:{}", room_id) } Ok(res.unwrap()) }...
let room
identifier_name
room_model.rs
Type::try_from(rs_pt.battle_type as u8).unwrap(); let is_open_ai = rs_pt.is_open_ai; let victory_condition = rs_pt.victory_condition; let turn_limit_time = rs_pt.turn_limit_time; let season_id = rs_pt.season_id; let rs = RoomSetting { battle_type, turn_lim...
}
random_line_split
room_model.rs
res } pub fn into_u32(self) -> u32 { let res: u8 = self.into(); res as u32 } } ///房间设置 #[derive(Debug, Copy, Clone, Default)] pub struct RoomSetting { pub battle_type: BattleType, //战斗类型 pub turn_limit_time: u32, //回合限制时间 pub season_id: u32, //赛季id pub i...
leave( &mut self, battle_type: BattleType, room_id: u32, user_id: &u32, ) -> anyhow::Result<u32> { let match_room = self.match_rooms.get_mut(&battle_type.into_u8()); if match_room.is_none() { let str = format!("there is no battle_type:{:?}!", battle_type);...
_id); } } ///离开房间,离线也好,主动离开也好 pub fn
conditional_block
Console.py
spice-usbredir-auto-redirect-filter='-1,-1,-1-1,1' --spice-usbredir-redirect-on-connect='-1,-1,-1,-1,1' " else: arg_usb = "--spice-disable-usbredir" if broadcast: arg_bro = " --teacher " else: arg_bro = "" try: if len(Main.get_device_...
identifier_body
Console.py
spice-usbredir-auto-redirect-filter='-1,-1,-1-1,1' --spice-usbredir-redirect-on-connect='-1,-1,-1,-1,1' " else: arg_usb = "--spice-disable-usbredir" if broadcast: arg_bro = " --teacher " else: arg_bro = "" try: if len(Main.get_device_...
identifier_name
Console.py
%s was not allowed screen_broadcast by server", self.vm.name) if usb: arg_usb = " --spice-usbredir-auto-redirect-filter='-1,-1,-1-1,1' --spice-usbredir-redirect-on-connect='-1,-1,-1,-1,1' " else: arg_usb = "--spice-disable-usbredir" if broadcast: arg_br...
random_line_split
Console.py
接字失败", u"发送失败", u"接收失败", u"SSL过程失败", u"内存不足", u"代理超时", u"代理错误", u"版本匹配失败", u"权限不足", u"无效的参数", u"命令行错误", ) CA_D...
try: count = 0 win = self.window wx.CallAfter(win.Update, 1, u'更新桌面云状态...') if self.cancel: return if self.Type == 'JSP' or self.Type == 'UNKNOWN': #import pdb #pdb.set_trace() ...
#pdb.set_trace()
conditional_block
products.js
with a spare strap. " ); let p6 = new Product( "Tommy Hilfiger", 1595, "<img src='./../img/tommyblack.jpg'/>", "Make a premium mark of style on your outfit with a timeless Tommy Hilfiger watch. Whether you're looking for classic leather, smart stainless steel or dressy silver watch, why not indulge in our rang...
} }
random_line_split
products.js
src='./../img/timexbrown.jpg'/>", "Metropolitan R has all the functionality you need including up to 2 weeks of battery life. This sleek design boasts an impressive AMOLED display that you can customize with over 20+ dial designs. Plus, 24/7 activity and sleep tracking for your health and fitness goals, on-board GPS...
.attr("id", "atag") .text("Read More") .appendTo(container); $("<p>") .addClass("description") .html(product.description) .appendTo(container); let addToCartButtons = $("<button>Add to Cart</button>") .addClass("AddToCartButton") .appendTo(container); addToCar...
list = document.getElementById("product-container"); productlist.innerHTML = ""; $.each(products, (i, product) => { let container = $("<div>").addClass("product").attr("id", product.id); $("<div>").addClass("image").html(product.image).appendTo(container); $("<h3>").html(product.name).appendTo(contai...
identifier_body
products.js
Race is a curated collection of the finest timepieces designed in Auckland, New Zealand by father and son team Scott and Jack Ramsay. Scott has over thirty years experience in the watch industry and ensures that their watches are of the highest quality, along with providing a very professional back up service. The wa...
ct(cartProduct) {
identifier_name
products.js
", 2495, "<img src='./../img/huntersbrown.jpg'/>", "Hunters Race is a curated collection of the finest timepieces designed in Auckland, New Zealand by father and son team Scott and Jack Ramsay. Scott has over thirty years experience in the watch industry and ensures that their watches are of the highest quality,...
ducts.splice(i, 1); cartProduct.product.inCart = false; } createShop
conditional_block
cli.py
from six.moves import configparser from six.moves import input from tqdm import tqdm from .api import OSF from .exceptions import UnauthorizedException from .utils import norm_remote_path, split_storage, makedirs, checksum def config_from_file(): if os.path.exists(".osfcli.config"): config_ = configpa...
(args, config): if args.username is None: username = config.get('username') else: username = args.username return username def _setup_osf(args): # Command line options have precedence over environment variables, # which have precedence over the config file. config = config_from...
_get_username
identifier_name
cli.py
from six.moves import configparser from six.moves import input from tqdm import tqdm from .api import OSF from .exceptions import UnauthorizedException from .utils import norm_remote_path, split_storage, makedirs, checksum def config_from_file(): if os.path.exists(".osfcli.config"): config_ = configpa...
@might_need_auth def fetch(args): """Fetch an individual file from a project. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. The local path defaults to the name of the remote file. If the project ...
prefix = os.path.join(output_dir, store.name) for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] path = os.path.join(prefix, path) if os.path.exists(path) and args.update: ...
conditional_block
cli.py
from six.moves import configparser from six.moves import input from tqdm import tqdm from .api import OSF from .exceptions import UnauthorizedException from .utils import norm_remote_path, split_storage, makedirs, checksum def config_from_file(): if os.path.exists(".osfcli.config"): config_ = configpa...
@might_need_auth def upload(args): """Upload a new file to an existing project. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. If the project is private you need to specify a username. To upload a...
"""List all files from all storages for project. If the project is private you need to specify a username. """ osf = _setup_osf(args) project = osf.project(args.project) for store in project.storages: prefix = store.name for file_ in store.files: path = file_.path ...
identifier_body
cli.py
from six.moves import configparser from six.moves import input from tqdm import tqdm from .api import OSF from .exceptions import UnauthorizedException from .utils import norm_remote_path, split_storage, makedirs, checksum def config_from_file(): if os.path.exists(".osfcli.config"): config_ = configpa...
If args.update is True, overwrite any existing local files only if local and remote files differ. """ osf = _setup_osf(args) project = osf.project(args.project) output_dir = args.project if args.output is not None: output_dir = args.output with tqdm(unit='files') as pbar: ...
The output directory defaults to the current directory. If the project is private you need to specify a username.
random_line_split
jax_sinusoid.py
self.validation_block_sizes = block_sizes MAML.__init__(self, params) def _get_model(self): """ Return jax network initialisation and forward method. """ layers = [] # inner / hidden network layers + non-linearities for l in self.network_layers: ...
self.device = device self.task_type = params.get('task_type') # extract relevant task-specific parameters self.amplitude_bounds = params.get(['sin2d', 'amplitude_bounds']) self.domain_bounds = params.get(['sin2d', 'domain_bounds']) degree_phase_bounds = params.get(['sin2d', 'pha...
identifier_body
jax_sinusoid.py
# output layer (no non-linearity) layers.append(Dense(self.output_dimension)) # make jax stax object model = stax.serial(*layers) return model def _get_optimiser(self): """ Return jax optimiser: initialisation, update method and parameter getter...
:param batch_size: number of tasks to sample :param validate: whether or not tasks are being used for validation :param step_count: step count during training :return tasks: batch of tasks :return task_indices: indices of priority queue associated with batch of tasks :...
random_line_split
jax_sinusoid.py
# output layer (no non-linearity) layers.append(Dense(self.output_dimension)) # make jax stax object model = stax.serial(*layers) return model def _get_optimiser(self): """ Return jax optimiser: initialisation, update method and parameter getter method...
# compute metrics for tb logging queue_count_loss_correlation = self.priority_queue.compute_count_loss_correlation() queue_mean = np.mean(self.priority_queue.get_queue()) queue_std = np.std(self.priority_queue.get_queue()) # write to tenso...
if self.priority_sample and not validate: # query queue for next task parameters max_indices, task_parameters, task_probability = self.priority_queue.query(step=step_count) all_max_indices.append(max_indices) task_probabilities.append(task_probability) ...
conditional_block
jax_sinusoid.py
# output layer (no non-linearity) layers.append(Dense(self.output_dimension)) # make jax stax object model = stax.serial(*layers) return model def _get_optimiser(self): """ Return jax optimiser: initialisation, update method and parameter getter method...
(self, parameters: List) -> Any: """ Return sine function defined by parameters given :param parameters: parameters defining the specific sin task in the distribution :return modified_sin: sin function (method differs from _sample_task in that it is not a random sample but ...
_get_task_from_params
identifier_name
wsrest_face_detect_kinect.py
.http_get_token_in_header(web)) # resposta. if server_timeout<=0 or client_timeout<=0: web.ctx.status='401 Unauthorized' return t0 = int(time.time() * 1000) # Chamada get sem parametro. if not name: web.header('Content-Type', 'applicatio...
# web.debug('detect draw total time: ' + str(t0) + " ms") resource_result['response_time'] = t0
random_line_split
wsrest_face_detect_kinect.py
, flags=CV_HAAR_DO_CANNY_PRUNING, # min_size=<minimum possible face size min_size = cvSize(20,20) image_scale = 1.3 haar_scale = 1.2 min_neighbors = 2 haar_flags = CV_HAAR_DO_CANNY_PRUNING #0 init_opencv = True urls = ( '/(.*)', 'index' ) web.config.debug = True # Debug true causa problema quando...
req.add_header("Authenticate",("token="+global_data.access_token)) file=urllib2.urlopen(req) # file = urllib.urlopen(self.url_wsr_kinect_rgb) # close? # urllib2 module sends HTTP/1.1 requests with Connection:close header included. # Convertendo para formato PIL ...
t0 = int(time.time() * 1000) global init_opencv, cascade, capture, storage if init_opencv: init_opencv = False # the OpenCV API says this function is obsolete, but we can't # cast the output of cvLoad to a HaarClassifierCascade, so use this anyways # the ...
identifier_body
wsrest_face_detect_kinect.py
, flags=CV_HAAR_DO_CANNY_PRUNING, # min_size=<minimum possible face size min_size = cvSize(20,20) image_scale = 1.3 haar_scale = 1.2 min_neighbors = 2 haar_flags = CV_HAAR_DO_CANNY_PRUNING #0 init_opencv = True urls = ( '/(.*)', 'index' ) web.config.debug = True # Debug true causa problema quando...
faces_dict[face_name+"_x"]=str(x1+dx1) faces_dict[face_name+"_y"]=str(y1+dy1) faces_dict[face_name+"_sx"]=str(int(x2+dx2-(x1+dx1))) faces_dict[face_name+"_sy"]=str(int(y2+dy2-(y1+dy1))) # sub-image ...
for r in faces: # pt1 = cvPoint( int(r.x*image_scale), int(r.y*image_scale)) # pt2 = cvPoint( int((r.x+r.width)*image_scale), int((r.y+r.height)*image_scale) ) x1 = int(r.x*image_scale) x2 = int((r.x+r.width)*image_scale) ...
conditional_block
wsrest_face_detect_kinect.py
, flags=CV_HAAR_DO_CANNY_PRUNING, # min_size=<minimum possible face size min_size = cvSize(20,20) image_scale = 1.3 haar_scale = 1.2 min_neighbors = 2 haar_flags = CV_HAAR_DO_CANNY_PRUNING #0 init_opencv = True urls = ( '/(.*)', 'index' ) web.config.debug = True # Debug true causa problema quando...
: # ========== Inicializacao unica por classe ================= # Variaveis declaradas aqui sao usadas na classe usando self. url_wsr_kinect_rgb = "http://localhost:8094/rgb_image/" # # Conectando com o BD. # db = db_util.connect() # ============ Final da Inicializacao unica por classe =======...
index
identifier_name
platformAccessory.ts
.config.updateInterval !== undefined) { this.updateInterval = this.platform.config.updateInterval * 1000; } this.accessory.getService(this.platform.Service.AccessoryInformation)! .setCharacteristic(this.platform.Characteristic.Manufacturer, 'Extron, Inc.') .setCharacteristic(this.platform.Cha...
this.lockService.getCharacteristic(this.platform.Characteristic.LockTargetState) .onSet(this.setTargetLockState.bind(this)) .onGet(this.getCurrentLockState.bind(this)); this.updateLockStatus(); // Set interval to keep HomeKit updated on the current state of power, input states, // and lock...
random_line_split
platformAccessory.ts
.updateInterval !== undefined) { this.updateInterval = this.platform.config.updateInterval * 1000; } this.accessory.getService(this.platform.Service.AccessoryInformation)! .setCharacteristic(this.platform.Characteristic.Manufacturer, 'Extron, Inc.') .setCharacteristic(this.platform.Characteri...
(): Promise<number> { const muteResponse = await this.telnetCommand('WVM' + String.fromCharCode(13)); this.platform.log.debug('GET: Getting status of unit: %s', muteResponse); // All zeroes indicates there are not active mutes; otherwise, mutes are in effect. // Hence, if there are any other values in ...
getOnOffState
identifier_name
platformAccessory.ts
this.getOnOffState(); this.updatePresetStatus(); this.avService.getCharacteristic(this.platform.Characteristic.ActiveIdentifier) .onSet(async (value) => { // the value will be the value you set for the Identifier Characteristic // on the Input Source service that was selected - see i...
{ this.lockService.updateCharacteristic(this.platform.Characteristic.LockCurrentState, this.platform.Characteristic.LockCurrentState.UNKNOWN); this.platform.log.debug('Locking response was %s, Expected Exe%s', response, this.lockingCode[0]); }
conditional_block
registry.ts
configuration * * Throws an error in case the configuration is incorrect * FIXME(tonyo): rewrite this with JSON schemas * * @param checksums Raw configuration */ protected castChecksums(checksums: any): ChecksumEntry[] { if (!checksums) { return []; } if (!(checksums instanceof Ar...
/** * Adds file URLs to the manifest * * URL template is taken from "urlTemplate" configuration argument * * FIXME(tonyo): LEGACY function, left for compatibility, replaced by addFilesData * * @param manifest Package manifest * @param version The new version * @param revision Git commit S...
{ if (this.registryConfig.type === RegistryPackageType.SDK) { return this.getSdkPackagePath(registryDir, canonical); } else if (this.registryConfig.type === RegistryPackageType.APP) { return this.getAppPackagePath(registryDir, canonical); } else { throw new ConfigurationError( `Unk...
identifier_body
registry.ts
configuration * * Throws an error in case the configuration is incorrect * FIXME(tonyo): rewrite this with JSON schemas * * @param checksums Raw configuration */ protected
(checksums: any): ChecksumEntry[] { if (!checksums) { return []; } if (!(checksums instanceof Array)) { throw new ConfigurationError( 'Invalid type of "checksums": should be an array' ); } const resultChecksums: ChecksumEntry[] = []; checksums.forEach(item => { if...
castChecksums
identifier_name
registry.ts
configuration * * Throws an error in case the configuration is incorrect * FIXME(tonyo): rewrite this with JSON schemas * * @param checksums Raw configuration */ protected castChecksums(checksums: any): ChecksumEntry[] { if (!checksums) { return []; } if (!(checksums instanceof Ar...
let urlTemplate; if (registryType === RegistryPackageType.APP) { urlTemplate = this.config.urlTemplate; if (urlTemplate && typeof urlTemplate !== 'string') { throw new ConfigurationError( `Invalid "urlTemplate" specified: ${urlTemplate}` ); } } const releas...
{ throw new ConfigurationError( `Invalid registry type specified: "${registryType}"` ); }
conditional_block
registry.ts
s configuration * * Throws an error in case the configuration is incorrect * FIXME(tonyo): rewrite this with JSON schemas * * @param checksums Raw configuration */ protected castChecksums(checksums: any): ChecksumEntry[] { if (!checksums) { return []; } if (!(checksums instanceof A...
`Invalid checksum type: ${JSON.stringify(item)}` ); } // FIXME(tonyo): this is ugly as hell :( // This all has to be replaced with JSON schema if ( !(Object as any).values(HashAlgorithm).includes(item.algorithm) || !(Object as any).values(HashOutputFormat).inclu...
random_line_split
Ngrams.py
_twitter_rw(question): import re twitter_rw = ['rt', 'dm'] cleansed_question = ' ' + question + ' ' for rw in twitter_rw: cleansed_question = re.sub(r'\W(?:%s)\W' % rw, ' ', cleansed_question, flags=re.IGNORECASE) return cleansed_question.strip() def _remove_urls(question): import re ...
while content[end-1] in [',', '.', ';', ':', '?']: end -= 1 yield (current, end) current = end current = content.find(scheme, current) class SmileyParser: def __init__(self): import re western_smileys = [ # from http://en.wikipedia.org/wiki/List_of_e...
ntent.find('\n', current) if end == -1: end = len(content)
conditional_block
Ngrams.py
(question): import re twitter_rw = ['rt', 'dm'] cleansed_question = ' ' + question + ' ' for rw in twitter_rw: cleansed_question = re.sub(r'\W(?:%s)\W' % rw, ' ', cleansed_question, flags=re.IGNORECASE) return cleansed_question.strip() def _remove_urls(question): import re cleansed_...
_remove_twitter_rw
identifier_name
Ngrams.py
', '>;]+', '*-)+', '*)+', ';-]+', ';]+', ';^)+', '>:P', ':-P', ':P', 'X-P', ':-p', '=p', ':-Þ', ':Þ', ':-b', '>:o', '>:O', ':-O', '°o°', '°O°', 'o_O', 'o.O', '8-0', 'o_O', 'x)+', '^^+', ':=)', '((?::|;|=)(?:-)?(?:\)|D|P))'] regex = '|'.join(['(\s%s\s)' % i for i in [re.escape(smiley) f...
output.append(invert[c]) else: return None return ''.join(output)
random_line_split
Ngrams.py
regex = '|'.join(['(\s%s\s)' % i for i in [re.escape(smiley) for smiley in smileys]]) cleansed_question = re.sub(regex, ' ', question, flags=re.MULTILINE|re.I) return cleansed_question.strip() def _remove_hashtags(question): import re question = question.strip() hash_tags = [tag for tag in que...
self._regex.finditer(content): start, end = i.span() yield (start, end) def _
identifier_body
index.d.ts
{ constructor(authTlsOpts: { certificatePath: string; privateKeyPath: string }); certificatePath: string; privateKeyPath: string; } export class AuthenticationToken { constructor(authTokenOpts: { token: string }); token: string; } export interface ClientOpts { /** * The connection URL fo...
AuthenticationTls
identifier_name
index.d.ts
, at which point the operation will fail. * Default: 30 */ operationTimeoutSeconds?: number; /** * The number of threads to use for handling connections to Pulsar brokers. * Default: 1 */ ioThreads?: number; /** * The number of threads used by message listeners (consumers...
/** * Interval between each stat info. Stats is activated with positive statsInterval. The value should be set to >= 1 second. * Default: 600 */ statsIntervalInSeconds?: number; } export class Client { constructor(opts: ClientOpts); createProducer(data: ProducerOpts): Promise<Producer>...
*/ tlsAllowInsecureConnection?: boolean;
random_line_split
main.rs
calculate_hash_proof( self.index.clone(), self.previus_hash.clone(), self.timestamp.clone(), self.data.clone(), PROOF.clone(), ) .0 } } #[derive(Serialize, Deserialize, Debug, Clone)] struct Transaction { sender: String, rec...
if y.reciver == wallet.pub_key { let amount = y.amount as u128; balance += amount; } } } println!("{}", balance); balance } } impl Display for Block { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::R...
{ let amount = y.amount as u128; balance += amount; }
conditional_block
main.rs
calculate_hash_proof( self.index.clone(), self.previus_hash.clone(), self.timestamp.clone(), self.data.clone(), PROOF.clone(), ) .0 } } #[derive(Serialize, Deserialize, Debug, Clone)] struct
{ sender: String, reciver: String, amount: u64, hash: Option<String>, } impl Transaction { fn new(sender: Wallet, reciver: Wallet, amount: u64) -> Transaction { let sender = sender.pub_key.clone(); let reciver = reciver.pub_key.clone(); let x = Transaction { send...
Transaction
identifier_name
main.rs
{ calculate_hash_proof( self.index.clone(), self.previus_hash.clone(), self.timestamp.clone(), self.data.clone(), PROOF.clone(), ) .0 } } #[derive(Serialize, Deserialize, Debug, Clone)] struct Transaction { sender: String, ...
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{} {:?} {:?} {:?} {:?}", self.index, self.previus_hash, self.timestamp, self.data, self.hash ) } } fn calculate_hash_proof( index: u64, previus_hash: String, timestamp: String,...
random_line_split
main.rs
calculate_hash_proof( self.index.clone(), self.previus_hash.clone(), self.timestamp.clone(), self.data.clone(), PROOF.clone(), ) .0 } } #[derive(Serialize, Deserialize, Debug, Clone)] struct Transaction { sender: String, rec...
} trait Createblock { fn new( index: u64, previus_hash: String, timestamp: String, data: Vec<Transaction>, hash: String, proof: u128, ) -> Self; } impl Createblock for Block { fn new( index: u64, previus_hash: String, timestamp: Strin...
{ write!(f, "{:?}-{:?}-{}", self.sender, self.reciver, self.amount) }
identifier_body
workloads.go
Ports represents open ports for a service running on a workload type OpenServicePorts struct { Address string `json:"address,omitempty"` Package string `json:"package,omitempty"` Port int `json:"port,omitempty"` ProcessName string `json:"process_name,omitempty"` Protocol int ...
// Call the API workloadJSON, err := json.Marshal(workload) if err != nil { return newWL, api, fmt.Errorf("create workload - %s", err) } api, err = apicall("POST", apiURL.String(), pce, workloadJSON, false) if err != nil { return newWL, api, fmt.Errorf("create workload - %s", err) } // Marshal JSON json....
}
random_line_split
workloads.go
represents open ports for a service running on a workload type OpenServicePorts struct { Address string `json:"address,omitempty"` Package string `json:"package,omitempty"` Port int `json:"port,omitempty"` ProcessName string `json:"process_name,omitempty"` Protocol int `json...
workload.SanitizePut() // Call the API workloadJSON, err := json.Marshal(workload) if err != nil { return api, fmt.Errorf("update workload - %s", err) } api, err = apicall("PUT", apiURL.String(), pce, workloadJSON, false) if err != nil { return api, fmt.Errorf("update workload - %s", err) } return api...
{ return api, fmt.Errorf("update workload - %s", err) }
conditional_block
workloads.go
err) } json.Unmarshal([]byte(api.RespBody), &workloads) // If length is 500, re-run with async if len(workloads) >= 500 { api, err = apicall("GET", apiURL.String(), pce, nil, true) if err != nil { return nil, api, fmt.Errorf("get all workloads - %s", err) } // Unmarshal response to struct json.Unma...
{ w.SanitizeBulkUpdate() w.Href = "" }
identifier_body
workloads.go
Ports represents open ports for a service running on a workload type OpenServicePorts struct { Address string `json:"address,omitempty"` Package string `json:"package,omitempty"` Port int `json:"port,omitempty"` ProcessName string `json:"process_name,omitempty"` Protocol int ...
(pce PCE, workload Workload) (Workload, APIResponse, error) { var newWL Workload var api APIResponse var err error // Build the API URL apiURL, err := url.Parse("https://" + pceSanitization(pce.FQDN) + ":" + strconv.Itoa(pce.Port) + "/api/v2/orgs/" + strconv.Itoa(pce.Org) + "/workloads") if err != nil { return...
CreateWorkload
identifier_name
Context.js
extends Component { state = { dateToday: getDateToday(), siteData: SiteData, catData: CatData, items: [], filterIsActive: false, categoryName: null, categoryNameDefault: 'Live', categoryArr: {}, brandArr: [], sortedItems: [], featuredItems: [], featuredItemsArchive: [], loading...
ItemProvider
identifier_name
Context.js
let itemsArchive = this.formatData(dataArchive); let itemsOther = this.formatData(dataOther); // ConsoleLog("[Context] getData > items..." + items); ////////////// // FEATURED // ////////////// // Featured items [Live] let featuredItems = items.slice(0, SiteData.featuredItems.itemCount)...
const dataArchive = await fetch(CatData.Archive.apiFeatured).then((dataArchive) => dataArchive.json()); const dataOther = await fetch(CatData.General.apiFeatured).then((dataOther) => dataOther.json()); let items = this.formatData(data);
random_line_split
WikitudePlugin.js
/** * Callbacks that are used during device compatibilty checks. */ this._onDeviceSupportedCallback = null; this._onDeviceNotSupportedCallback = null; /** * Callbacks that are used if an ARchitect World was launched successfully or not. */ this._onARchitectWorldLaunchedCallback = null...
random_line_split
WikitudePlugin.js
KEY-HERE"; /** * This variable represents if the current device is capable of running ARchitect Worlds. */ this._isDeviceSupported = false; /** * The Wikitude SDK can run in different modes. * * Geo means, that objects are placed at latitude/longitude positions. * * IR m...
}; /** * This function gets called if the Wikitude Plugin reports that the device is not able of starting the Wikitude SDK. */ WikitudePlugin.prototype.deviceIsNotARchitectReady = function() { // Keep track of the device status module.exports._isDeviceSupported = false; // if the developer ...
{ module.exports._onDeviceSupportedCallback(); }
conditional_block
actions_linux.go
func convertImage(filename string, unsquashfsPath string) (string, error) { img, err := image.Init(filename, false) if err != nil { return "", fmt.Errorf("could not open image %s: %s", filename, err) } defer img.File.Close() if !img.HasRootFs() { return "", fmt.Errorf("no root filesystem found in %s", filen...
{ if os.Geteuid() != 0 { if len(args) >= 1 && len(args[0]) > 0 { // The first argument is the context sylog.Fatalf("command '%s %s' requires root privileges", args[0], cmd.Name()) } else { sylog.Fatalf("command %s requires root privileges", cmd.Name()) } } }
identifier_body
actions_linux.go
.AddProcessEnv("SINGULARITY_CONTAINER", abspath) generator.AddProcessEnv("SINGULARITY_NAME", filepath.Base(abspath)) if err != nil { sylog.Fatalf("Failed to determine image absolute path for %s: %s", image, err) } engineConfig.SetImage(abspath) } if !NoNvidia && (Nvidia || engineConfig.File.AlwaysUseNv) {...
{ unsquashfsPath := "" if engineConfig.File.MksquashfsPath != "" { d := filepath.Dir(engineConfig.File.MksquashfsPath) unsquashfsPath = filepath.Join(d, "unsquashfs") } sylog.Verbosef("User namespace requested, convert image %s to sandbox", image) sylog.Infof("Convert SIF file to sandbox...") dir, err...
conditional_block
actions_linux.go
filesystem") } // create a reader for rootfs partition reader, err := image.NewPartitionReader(img, "", 0) if err != nil { return "", fmt.Errorf("could not extract root filesystem: %s", err) } s := unpacker.NewSquashfs() if !s.HasUnsquashfs() && unsquashfsPath != "" { s.UnsquashfsPath = unsquashfsPath } ...
engineConfig.SetHomeDest(homeSlice[0])
engineConfig.SetHomeSource(homeSlice[0]) if len(homeSlice) == 1 {
random_line_split
actions_linux.go
(cmd *cobra.Command, args []string) { if os.Geteuid() != 0 { if len(args) >= 1 && len(args[0]) > 0 { // The first argument is the context sylog.Fatalf("command '%s %s' requires root privileges", args[0], cmd.Name()) } else { sylog.Fatalf("command %s requires root privileges", cmd.Name()) } } } func co...
EnsureRootPriv
identifier_name
plugin.py
_outcomes def logsdir(self): ldir = self._logsdir if ldir: return ldir logger_logsdir = self._config.getoption('logger_logsdir') if not logger_logsdir: logger_logsdir = self._config.getini('logger_logsdir') if not logger_logsdir: logger_lo...
(self, config): """ called after cmdline options parsing. If implemented, symlink to logs directory will be created. :arg config: pytest config object, holds e.g. options :return string: Absolute path of requested link to logs directory. """ @pytest.hookspec(firstresult=Tr...
pytest_logger_logdirlink
identifier_name
plugin.py
come_outcomes def logsdir(self): ldir = self._logsdir if ldir: return ldir logger_logsdir = self._config.getoption('logger_logsdir') if not logger_logsdir: logger_logsdir = self._config.getini('logger_logsdir') if not logger_logsdir: logge...
""" Sets default value of `log` option.""" self._log_option_default = value def split_by_outcome(self, outcomes=None, subdir='by_outcome'): """Makes a directory inside main logdir where logs are further split by test outcome :param outcomes: list of test outcomes to be handled (fai...
self._formatter_class = formatter_class def set_log_option_default(self, value):
random_line_split
plugin.py
: ldir = _make_logsdir_dir(logger_logsdir) else: ldir = _make_logsdir_tmpdir(self._config._tmpdirhandler) self._logsdir = ldir for link in self._logdirlinks: _refresh_link(str(ldir), link) return ldir def pytest_runtest_setup(self, item): ...
return level
conditional_block
plugin.py
_outcomes def logsdir(self): ldir = self._logsdir if ldir: return ldir logger_logsdir = self._config.getoption('logger_logsdir') if not logger_logsdir: logger_logsdir = self._config.getini('logger_logsdir') if not logger_logsdir: logger_lo...
class Loggers(object): def __init__(self, stdout, file_): self.stdout = stdout self.file = file_ def __bool__(self): return bool(self.stdout) or bool(self.file) class LoggerConfig(object): """Configuration of logging to stdout and filesystem.""" def __init__(self): ...
def __init__(self, enabled): self._enabled = enabled self._root_level = logging.root.level def enable(self): if self._enabled: self._root_level = logging.root.level logging.root.setLevel(logging.NOTSET) # stops root logger from blocking logs def disable(self): ...
identifier_body
main.go
= kingpin.Flag("out", "write the ansible inventory to this file - if unset, print to stdout").String() timeout = kingpin.Flag("timeout", "timeout for total runtime of the command, defaults to 2m").Default("2m").Duration() ) var doRegions = []string{"ams1", "ams2", "ams3", "blr1", "fra1", "lon1", "n...
listDroplets
identifier_name
main.go
-port", "default ssh port").Int() tag = kingpin.Flag("tag", "filter droplets by tag").String() ignore = kingpin.Flag("ignore", "ignore a Droplet by name, can be specified multiple times").Strings() groupByRegion = kingpin.Flag("group-by-region", "group hosts by region, defaults to true").Default(...
// skip droplets that aren't included in the inventory droplet, exists := dropletsByID[idInt] if !exists { continue } dropletsByProject[project.Name] = append(dropletsByProject[project.Name], droplet) } } for project, droplets := range dropletsByProject { project = sanitizeAnsible...
{ ll.WithError(err).WithField("urn", r.URN).Error("parsing droplet ID, skipping") continue }
conditional_block
main.go
-port", "default ssh port").Int() tag = kingpin.Flag("tag", "filter droplets by tag").String() ignore = kingpin.Flag("ignore", "ignore a Droplet by name, can be specified multiple times").Strings() groupByRegion = kingpin.Flag("group-by-region", "group hosts by region, defaults to true").Default(...
func removeIgnored(droplets []godo
{ // replace invalid characters s = strings.NewReplacer( " ", "_", "-", "_", ":", "_", ).Replace(s) // group names cannot start with a digit if '0' <= s[0] && s[0] <= '9' { s = "_" + s } return s }
identifier_body
main.go
-port", "default ssh port").Int() tag = kingpin.Flag("tag", "filter droplets by tag").String() ignore = kingpin.Flag("ignore", "ignore a Droplet by name, can be specified multiple times").Strings() groupByRegion = kingpin.Flag("group-by-region", "group hosts by region, defaults to true").Default(...
// get droplets if *tag != "" { log.WithField("tag", *tag).Info("only selecting tagged Droplets") } log.Info("listing Droplets") droplets, err := listDroplets(ctx, client, *tag) if err != nil { log.WithError(err).Fatal("couldn't fetch Droplets") } // filter out ignored droplets droplets = removeIgnored(d...
defer cancel() client := godo.NewFromToken(*doToken)
random_line_split
disk.py
(object): def __init__(self): self.model = "" self.vendor = "" self.fw = "" self.sn = "" self.wwn = "" self.hctl = "" self.dev_name = "" self.smart = "" self.type = "" self.smart_attr = {} self.age = {} self.flash = False @staticmethod def map_disk_wwn_hctl(diskname): """ map wwn and H:C:T...
Disk
identifier_name
disk.py
# } # 'Spin_Up_Time': { # ...(According to the following form) # } # } # SATA smart form: # ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE # 1 Raw_Read_Error_Rate 0x000f 074 063 044 Pre-fail Always - 26816470 # ...
def __init__(self, sn, name): super(DiskFromLsiSas2, self).__init__(sn, name)
identifier_body
disk.py
_oj): """ return True if smart info of disk_oj has error, else return False """ if "SAS" in disk_oj.smart: if int(disk_oj.smart_attr["channel0Error"]["Invalid DWORD count"]) > 0 or \ int(disk_oj.smart_attr["channel0Error"]["Running disparity error count"]) > 0 or \ int(disk_oj.smart_attr["channel0E...
# } # # SATA disk # smart_attr: { # 'Raw_Read_Error_Rate': { # 'ID': '1', # 'FLAG': '0x000f', # 'VALUE': '074', # 'WORST': '063', # 'THRESH': '044', # 'TYPE': 'Pre-fail', # 'UPDATED': 'Always', # 'WHEN_FAILED': '-', # 'RAW_VALUE': '2681...
# 'errorEccFast': '0', # 'totalErrorsCorrected': '8', # 'totalUncorrectedError': '0' # }
random_line_split
disk.py
j): """ return True if smart info of disk_oj has error, else return False """ if "SAS" in disk_oj.smart:
if "SATA" in disk_oj.smart: if "No Errors Logged" not in disk_oj.smart: return False for attr_ in SATA_SMART_ERROR_LIST: if disk_oj.smart_attr[attr_]["RAW_VALUE"] > 0: return False return True @staticmethod def get_over_agelimit_disks(disk_list): """ return sas and sata disk list witch sta...
if int(disk_oj.smart_attr["channel0Error"]["Invalid DWORD count"]) > 0 or \ int(disk_oj.smart_attr["channel0Error"]["Running disparity error count"]) > 0 or \ int(disk_oj.smart_attr["channel0Error"]["Loss of DWORD synchronization"]) > 0 or \ int(disk_oj.smart_attr["channel0Error"]["Phy reset proble...
conditional_block
load_drives.py
793 bmean = 54.14884297660608 rstd = 57.696159704394354 gstd = 53.739380109203445 bstd = 47.66536771313241 #print( "Default normalization" ) images[:,:,:,0] -= rmean images[:,:,:,1] -= gmean images[:,:,:,2] -= bmean images[:,:,:,0] /= rstd ...
(Sequence): """ Loads MaLPi drive data From: https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly.html""" def __init__(self, filelist, image_size=(120,120), batch_size=32, shuffle=True, max_load=30000, auxName=None, images_only=False ): """ Input a list of drive directories....
DriveDataGenerator
identifier_name
load_drives.py
793 bmean = 54.14884297660608 rstd = 57.696159704394354 gstd = 53.739380109203445 bstd = 47.66536771313241 #print( "Default normalization" ) images[:,:,:,0] -= rmean images[:,:,:,1] -= gmean images[:,:,:,2] -= bmean images[:,:,:,0] /= rstd ...
self.actions = [] self.current_start = 0 self.categorical = None self.input_dim = None self.num_actions = None self.batch_shape = (self.batch_size,) + self.size + (3,) print( "Batch shape: {}".format( self.batch_shape ) ) self.count = self.__count() ...
""" Loads MaLPi drive data From: https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly.html""" def __init__(self, filelist, image_size=(120,120), batch_size=32, shuffle=True, max_load=30000, auxName=None, images_only=False ): """ Input a list of drive directories. Pre...
identifier_body
load_drives.py
793 bmean = 54.14884297660608 rstd = 57.696159704394354 gstd = 53.739380109203445 bstd = 47.66536771313241 #print( "Default normalization" ) images[:,:,:,0] -= rmean images[:,:,:,1] -= gmean images[:,:,:,2] -= bmean images[:,:,:,0] /= rstd ...
else: emb.append( prev_act ) except Exception as ex: print( ex ) print( act ) return emb class DriveDataGenerator(Sequence): """ Loads MaLPi drive data From: https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly.html""" ...
prev_act = embedding[act] if prev_act is None: print( "Invalid action: {}".format( act ) ) raise ValueError("Invalid action: " + str(act) ) emb.append( embedding[act] )
conditional_block
load_drives.py
793 bmean = 54.14884297660608 rstd = 57.696159704394354 gstd = 53.739380109203445 bstd = 47.66536771313241 #print( "Default normalization" ) images[:,:,:,0] -= rmean images[:,:,:,1] -= gmean images[:,:,:,2] -= bmean images[:,:,:,0] /= rstd ...
def embedActions( actions ): embedding = { "stop":0, "forward":1, "left":2, "right":3, "backward":4 } emb = [] prev_act = 0 for act in actions: try: if not act.startswith("speed"): prev_act = embedding[act] if prev_act is None: pri...
random_line_split
run.go
{ case 0: cmdData.DockerCommand = args[doubleDashInd:] case 1: cmdData.ImageName = args[0] cmdData.DockerCommand = args[doubleDashInd:] default: return fmt.Errorf("unsupported position args format") } } else { switch len(args) { case 0: case 1: cmdData.ImageName = args[0] default: re...
{ return fmt.Errorf("unable to check container %s existence: %w", containerName, err) }
conditional_block
run.go
command $ werf run --docker-options="-d -p 5000:5000 --restart=always --name registry" -- /app/run.sh # Print a resulting docker run command $ werf run --shell --dry-run docker run -ti --rm image-stage-test:1ffe83860127e68e893b6aece5b0b7619f903f8492a285c6410371c87018c6a0 /bin/sh`, Annotations: map[string]st...
case 0: case 1: cmdData.ImageName = args[0] default: return fmt.Errorf("unsupported position args format") } } return nil } func checkDetachDockerOption() error { for _, value := range cmdData.DockerOptions { if value == "-d" || value == "--detach" { return nil } } return fmt.Errorf("the c...
{ doubleDashInd := cmd.ArgsLenAtDash() doubleDashExist := cmd.ArgsLenAtDash() != -1 if doubleDashExist { if doubleDashInd == len(args) { return fmt.Errorf("unsupported position args format") } switch doubleDashInd { case 0: cmdData.DockerCommand = args[doubleDashInd:] case 1: cmdData.ImageName =...
identifier_body
run.go
command $ werf run --docker-options="-d -p 5000:5000 --restart=always --name registry" -- /app/run.sh # Print a resulting docker run command $ werf run --shell --dry-run docker run -ti --rm image-stage-test:1ffe83860127e68e893b6aece5b0b7619f903f8492a285c6410371c87018c6a0 /bin/sh`, Annotations: map[string]st...
() string { for ind, value := range cmdData.DockerOptions { if value == "--name" { if ind+1 < len(cmdData.DockerOptions) { return cmdData.DockerOptions[ind+1] } } else if strings.HasPrefix(value, "--name=") { return strings.TrimPrefix(value, "--name=") } } return "" } func runMain(ctx context.Co...
getContainerName
identifier_name
run.go
000 --restart=always --name registry" -- /app/run.sh # Print a resulting docker run command $ werf run --shell --dry-run docker run -ti --rm image-stage-test:1ffe83860127e68e893b6aece5b0b7619f903f8492a285c6410371c87018c6a0 /bin/sh`, Annotations: map[string]string{ common.DisableOptionsInUseLineAnno: "1", ...
_, _ = fmt.Fprintln(os.Stderr, "WARNING:", err) }
random_line_split
lib.rs
/index.html): //! //! ``` //! use parkour::prelude::*; //! ``` //! //! First, create a struct containing all the data you want to parse. For //! example: //! //! ``` //! struct Command { //! color: Option<bool>, //! show: Option<Show>, //! } //! //! struct Show { //! pos1: String, //! out: ColorSpace, /...
//! # impl FromInput<'static> for Show { //! # type Context = (); //! # fn from_input(input: &mut ArgsInput, _: &()) -> parkour::Result<Self> { //! # todo!() //! # } //! # } //! # //! struct Command { //! color: Option<bool>, //! show: Option<Show>, //! } //! //! impl FromInput<'static> for ...
//! # color_space: ColorSpace, //! # size: u8, //! # }
random_line_split
lib.rs
, cmyk, hsv, hsl or cielab //! ``` //! //! Now let's implement `Show` as a subcommand. Unfortunately, there's no //! convenient derive macro (yet): //! //! ``` //! # use parkour::prelude::*; //! # #[derive(FromInputValue)] //! # enum ColorSpace { Rgb, Cmy, Cmyk, Hsv, Hsl, CieLab } //! # //! struct Show { //! pos1: ...
parser
identifier_name
lib.rs
//! ``` //! //! Now let's implement `Show` as a subcommand. Unfortunately, there's no //! convenient derive macro (yet): //! //! ``` //! # use parkour::prelude::*; //! # #[derive(FromInputValue)] //! # enum ColorSpace { Rgb, Cmy, Cmyk, Hsv, Hsl, CieLab } //! # //! struct Show { //! pos1: String, //! color_spac...
{ ArgsInput::from_args() }
identifier_body
wikipedia.py
fsan Sarikaya. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense,...
self.title = str(temp_name) self.writer = list(row[2].split(',')) self.producers = row[3:-1] self.length = get_track_length(row[-1]) self.artist = None self.artist_id = None self.media = None self.medium_total = None self.artist_sort = None ...
if(i != '"'): temp_name += i
conditional_block
wikipedia.py
an Sarikaya. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, a...
(self): super(Wikipedia, self).__init__() self.config.add({ 'source_weight': 0.50 }) # ---------------------------------------------- """ Track_distance item --> track to be matched(Item Object) info is the TrackInfo object that proposed as a match s...
__init__
identifier_name
wikipedia.py
fsan Sarikaya. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense,...
Returns the album distance. """ dist = Distance() if (album_info.data_source == 'Wikipedia'): dist.add('
"""
random_line_split
wikipedia.py
fsan Sarikaya. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense,...
def get_producers(self): return self.producers def get_length(self): return self.length class Wikipedia(BeetsPlugin): def __init__(self): super(Wikipedia, self).__init__() self.config.add({ 'source_weight': 0.50 }) # -----------------------------...
return self.writer
identifier_body
import-docs.py
8') rowTrm = rowStr.strip() rowLwr = rowTrm.lower() gold_actions.append(rowLwr) gold_initiators = [] for row in C[1:]: rowStr = row.encode('utf-8') try: rowNme,rowCOW = rowStr.split('(') except: rowNme = rowStr rowTrm = rowNme.stri...
(file): raw = file.readline() if not raw: raise EOFError() if raw.find('-------------------------------------------------')>=0: raise ValueError() return raw.decode(fileencoding) file = open(in_file, 'r') readdocs = [] count = 0 while file: meta = {} try: while T...
nextline
identifier_name
import-docs.py
8') rowTrm = rowStr.strip() rowLwr = rowTrm.lower() gold_actions.append(rowLwr) gold_initiators = [] for row in C[1:]: rowStr = row.encode('utf-8') try: rowNme,rowCOW = rowStr.split('(') except: rowNme = rowStr rowTrm = rowNme.stri...
meta['text'] = text # get NER and NELL-CAT from pipeline data # open pipeline data file (HTML version) # store the frequency of each NELL-CAT / NER location in document #try: locFreq = {} counted = [False]*len(text) with open('/data/mid/docs/' + meta[...
t = nextline(file) if t.find('<<<<<<<<<<<<<<<')>=0: break t = t.replace('\r\n','\n').replace('\r','\n').rstrip() text += t + u"\n"
conditional_block
import-docs.py
8') rowTrm = rowStr.strip() rowLwr = rowTrm.lower() gold_actions.append(rowLwr) gold_initiators = [] for row in C[1:]: rowStr = row.encode('utf-8') try: rowNme,rowCOW = rowStr.split('(') except: rowNme = rowStr rowTrm = rowNme.stri...
file = open(in_file, 'r') readdocs = [] count = 0 while file: meta = {} try: while True: # read meta-data dataline = nextline(file).rstrip() if '>>>>>>>' in dataline: break elif ':' in dataline: # split at the first col...
raw = file.readline() if not raw: raise EOFError() if raw.find('-------------------------------------------------')>=0: raise ValueError() return raw.decode(fileencoding)
identifier_body
import-docs.py
_actions = {} gs_initiators = {} gs_targets = {} gs_stdates = {} # loop through the spreadsheet columns, selecting the highest MID for each doc for i in range(0,len(gold_actions)): thisAction = gold_actions[i] if (gold_actions[i] is not None) and (gold_actions[i] is not ""): ...
meta['gsInitiatorISO'] = isoDict[ini] else: print "ISO for " + ini + " not found."
random_line_split
auth.controllers.js
*/ let refreshTokensByID = {}; // { manager_id: refreshToken } // cookie setting w/ access token const accessCookieOptions = { // cookie expires after 90 mins from the time it is set. expires: new Date( Date.now() + process.env.JWT_COOKIE_ACCESS_EXPIRES * 60 * 1000 ), httpOnly: true, // for security reason...
statusCode: 403, }); // if refresh token expires if (refresh) { try { const decoded = Utils.verifyJWT(refresh); // { // exp: 1626825599, // data: 6, // iat: 1626500973, // aud: 'jwt-node', // iss: 'jwt-node', // sub: 'jwt-node' // } ...
random_line_split
auth.controllers.js
*/ let refreshTokensByID = {}; // { manager_id: refreshToken } // cookie setting w/ access token const accessCookieOptions = { // cookie expires after 90 mins from the time it is set. expires: new Date( Date.now() + process.env.JWT_COOKIE_ACCESS_EXPIRES * 60 * 1000 ), httpOnly: true, // for security reason...
if (Validation.isEmpty(password) || !Validation.validatePassword(password)) { return Response.sendErrorResponse({ res, message: "Password is missing.", statusCode: 400, }); } authDB .adminLogin(req, res, username) .then(async (results) => { console.log("auth.controllers ...
{ return Response.sendErrorResponse({ res, message: "Username is missing.", statusCode: 400, }); }
conditional_block
main.py
H:%M:%S',time.localtime(time.time())) self.textinput_action=TextInput(multiline=False) self.layout_num.add_widget(self.textinput_num) self.layout_time.add_widget(self.textinput_time) self.layout_action.add_widget(self.textinput_action) self.add_widget(self.layout_num) s...
ut): def __init__(self,**kwargs): super().__init__(**kwargs) self.cols = 7 self.month_=Months()# In order to get current month and day
identifier_body
main.py
self.layout_4=BoxLayout(size_hint=(1,.1)) self.layout_4.add_widget(self.status_) self.add_widget(self.layout_1) self.add_widget(self.layout_2) self.add_widget(self.layout_4) # ---------------------------------------------------------------------------------------------...
def __init__(self,**kwargs): super().__init__(**kwargs) self.orientation='horizontal' self.layout_num=BoxLayout(orientation='vertical',size_hint=(1,1)) self.layout_time=BoxLayout(orientation='vertical',size_hint=(1,1)) self.layout_action=BoxLayout(orientation='vertic...
class Content(BoxLayout):
random_line_split
main.py
# class for select.kv file class Select(BoxLayout): lbl_ = ObjectProperty(None) def __init__(self,**kwargs): super().__init__(**kwargs) self.lbl_.text='通力电梯公司维保可视化产品' self.lbl_.font_name=font_name # class for Reminder in Dates class Reminder(BoxLayout): def __init__(sel...
on_release=self.on_release,text = '{j}'.format(j=j),font_size='20sp',color=(0,0,0,1))) def on_dismiss(self, arg): # Do something on close of popup print('Popup dismiss') pass def on_release(self,event): event.background_color = 154/256,226/256,248/256,1 def on...
conditional_block
main.py
font_name,font_size='20sp')) self.textinput_num=TextInput(multiline=False) self.textinput_time=TextInput(multiline=False) self.textinput_time.text=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) self.textinput_action=TextInput(multiline=False) self.layout_num.add...
s.kv fil
identifier_name
gossip.rs
Gossip for GossipServer { fn exchange(&mut self, ctx: RpcContext, req: GossipData, sink: UnarySink<GossipData>) { ctx.spawn( self.sender .clone() .send(GossipEvent::GossipReceived(req)) .map(|_| ()) .map_err(|_| error!("Failed to u...
(&self, address: &str) { self.publish_event(GossipEvent::NewPeerDiscovered(address.to_string())); } fn update_meta_leader(&mut self, node_id: u64) { self.current.set_meta_leader_id(node_id); } fn meta_leader_id(&self) -> Option<u64> { if self.current.meta_leader_id != 0 { ...
publish_peer_discovered
identifier_name
gossip.rs
Gossip for GossipServer { fn exchange(&mut self, ctx: RpcContext, req: GossipData, sink: UnarySink<GossipData>) { ctx.spawn( self.sender .clone() .send(GossipEvent::GossipReceived(req)) .map(|_| ()) .map_err(|_| error!("Failed to u...
pub fn build_service(&self) -> Service { create_gossip(self.clone()) } pub fn state(&self) -> GossipState { self.state.clone() } pub fn update_meta_leader(&self, id: u64) -> impl Future<Item = (), Error = ()> { self.event(GossipEvent::MetaLeaderChanged(id)) } pub...
{ let (sender, receiver) = mpsc::channel(32); let state = GossipState::new(node_id, self_address, bootstrap, sender.clone(), clock); run_gossip_event_handler(receiver, state.new_ref(), node_id); GossipServer { state, sender } }
identifier_body
gossip.rs
Gossip for GossipServer { fn exchange(&mut self, ctx: RpcContext, req: GossipData, sink: UnarySink<GossipData>) { ctx.spawn( self.sender .clone() .send(GossipEvent::GossipReceived(req)) .map(|_| ()) .map_err(|_| error!("Failed to u...
gossip .get_node_liveness() .values() .for_each(|peer| self.update_node_liveness(peer)); gossip .get_peer_addresses() .iter() .filter(|(id, _)| !self.peers.contains_key(id)) .for_each(|(_, address)| self.publish_peer_d...
{ let address = gossip.get_address(); current_addrs.insert(peer_id, address.to_string()); self.publish_peer_discovered(address); }
conditional_block
gossip.rs
Gossip for GossipServer { fn exchange(&mut self, ctx: RpcContext, req: GossipData, sink: UnarySink<GossipData>) { ctx.spawn( self.sender .clone() .send(GossipEvent::GossipReceived(req)) .map(|_| ()) .map_err(|_| error!("Failed to u...
peers: HashMap::new(), }; inner.publish_peer_discovered(self_address); bootstrap .iter() .for_each(|address| inner.publish_peer_discovered(address)); Self { inner: Arc::new(RwLock::new(inner)), } } fn get_current(&self) -> ...
event_emitter, clock, connections: HashMap::new(), clients: HashMap::new(),
random_line_split