file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
create-path.ts
import { parse, posix } from "path" export function createPath( filePath: string, // TODO(v5): Set this default to false withTrailingSlash: boolean = true, usePathBase: boolean = false ): string
{ const { dir, name, base } = parse(filePath) // When a collection route also has client-only routes (e.g. {Product.name}/[...sku]) // The "name" would be .. and "ext" .sku -- that's why "base" needs to be used instead // to get [...sku]. usePathBase is set to "true" in collection-route-builder and gatsbyPath ...
identifier_body
create-path.ts
import { parse, posix } from "path" export function
( filePath: string, // TODO(v5): Set this default to false withTrailingSlash: boolean = true, usePathBase: boolean = false ): string { const { dir, name, base } = parse(filePath) // When a collection route also has client-only routes (e.g. {Product.name}/[...sku]) // The "name" would be .. and "ext" .sku ...
createPath
identifier_name
create-path.ts
import { parse, posix } from "path" export function createPath( filePath: string,
withTrailingSlash: boolean = true, usePathBase: boolean = false ): string { const { dir, name, base } = parse(filePath) // When a collection route also has client-only routes (e.g. {Product.name}/[...sku]) // The "name" would be .. and "ext" .sku -- that's why "base" needs to be used instead // to get [...s...
// TODO(v5): Set this default to false
random_line_split
basic_example.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# Flush write operations, if failures occur, print them. try: session.flush() except kudu.KuduBadStatus: print(session.get_pending_errors()) # Create a scanner and add a predicate. scanner = table.scanner() scanner.add_predicate(table['ts_val'] == datetime(2017, 1, 1)) # Open scanner and print all tuples. # Note...
session.apply(op) # Delete a row. op = table.new_delete({'key': 2}) session.apply(op)
random_line_split
basic_example.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# Create a new table. client.create_table('python-example', schema, partitioning) # Open a table. table = client.table('python-example') # Create a new session so that we can apply write operations. session = client.new_session() # Insert a row. op = table.new_insert({'key': 1, 'ts_val': datetime.utcnow()}) sessio...
client.delete_table('python-example')
conditional_block
script.py
# coding=utf8 import random import logging import json import time from httplib2 import Http from logging import handlers LOG_FILE = '../logs/WSCN_client.log' handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5) # 实例化handler handler.setFormatter(logging.Formatter('%(asctime)...
return str(random.randrange(1, 100, 1)) def random_price(): return str(round(random.uniform(90.00, 110.00), 2)) if __name__ == '__main__': for i in range(0, 1000): send() time.sleep(0.230)
_amount():
identifier_name
script.py
# coding=utf8 import random import logging import json import time from httplib2 import Http from logging import handlers LOG_FILE = '../logs/WSCN_client.log' handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5) # 实例化handler handler.setFormatter(logging.Formatter('%(asctime)...
r, c = h.request("http://127.0.0.1:4000/trade.do", "POST", "{\"symbol\": \"WSCN\", \"type\": \"" + exchange_type + "\", \"amount\": " + random_amount() + ", \"price\": " + random_price() + "}", {"Content-Type": "text/json"}) if exchange_type == "buy" or exchange_type ==...
h = Http() def send(): exchange_type = random_type()
random_line_split
script.py
# coding=utf8 import random import logging import json import time from httplib2 import Http from logging import handlers LOG_FILE = '../logs/WSCN_client.log' handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5) # 实例化handler handler.setFormatter(logging.Formatter('%(asctime)...
in range(0, 1000): send() time.sleep(0.230)
conditional_block
script.py
# coding=utf8 import random import logging import json import time from httplib2 import Http from logging import handlers LOG_FILE = '../logs/WSCN_client.log' handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5) # 实例化handler handler.setFormatter(logging.Formatter('%(asctime)...
random_type(): return str(random.choice(["buy", "sell", "buy_market", "sell_market"])) def random_amount(): return str(random.randrange(1, 100, 1)) def random_price(): return str(round(random.uniform(90.00, 110.00), 2)) if __name__ == '__main__': for i in range(0, 1000): send() tim...
ge_type = random_type() r, c = h.request("http://127.0.0.1:4000/trade.do", "POST", "{\"symbol\": \"WSCN\", \"type\": \"" + exchange_type + "\", \"amount\": " + random_amount() + ", \"price\": " + random_price() + "}", {"Content-Type": "text/json"}) if exchange_type == "...
identifier_body
karma.local.conf.js
'use strict'; module.exports = function(config) { config.set({ files: [ 'https://code.jquery.com/jquery-3.1.1.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.min.js', 'https://cdnjs.c...
port: 9876, browsers: ['Chrome'], proxies: { '/templates/': 'http://localhost:9876/base/bin/templates/' } }); };
{pattern: './bin/templates/*.html', included: false, served: true} ], frameworks: ['mocha', 'chai'],
random_line_split
PlainObjectProvider.ts
import { baseSet as set, baseGet as get, castPath, followRef } from './utils'; import { IPathObjectBinder, Path } from './DataBinding'; /** It wraps getting and setting object properties by setting path expression (dotted path - e.g. "Data.Person.FirstName", "Data.Person.LastName") */ export default class PathObjectB...
public setValue(path: Path, value: any) { if (path === undefined) return; var cursorPath = castPath(path); if (cursorPath.length === 0) return; var parent = this.getParent(cursorPath); if (parent === undefined) return; var property = cursorPath[cursorPath.length - ...
{ if (path === undefined) return this.source; var cursorPath = castPath(path); if (cursorPath.length === 0) return this.source; var parent = this.getParent(cursorPath); if (parent === undefined) return; var property = cursorPath[cursorPath.length - 1]; return par...
identifier_body
PlainObjectProvider.ts
import { baseSet as set, baseGet as get, castPath, followRef } from './utils'; import { IPathObjectBinder, Path } from './DataBinding'; /** It wraps getting and setting object properties by setting path expression (dotted path - e.g. "Data.Person.FirstName", "Data.Person.LastName") */ export default class PathObjectB...
}
}
random_line_split
PlainObjectProvider.ts
import { baseSet as set, baseGet as get, castPath, followRef } from './utils'; import { IPathObjectBinder, Path } from './DataBinding'; /** It wraps getting and setting object properties by setting path expression (dotted path - e.g. "Data.Person.FirstName", "Data.Person.LastName") */ export default class PathObjectB...
(updateFce) { // this.freezer.on('update',function(state,prevState){ // if (updateFce!==undefined) updateFce(state,prevState)} // ); } public createNew(path: Path, newItem?: any): IPathObjectBinder { //var item = followRef(this.root, newItem || this.getValue(path)); ...
subscribe
identifier_name
add-vmware-template.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { v4 as uuid } from 'uuid'; import { Server } from '../../../../models/server'; import { VmwareTemplate } from '../../../....
}
{ if (!this.templateNameForm.invalid) { this.vmwareTemplate.name = this.selectedVM.vmname; this.vmwareTemplate.vmx_path = this.selectedVM.vmx_path; this.vmwareTemplate.template_id = uuid(); this.vmwareService.addTemplate(this.server, this.vmwareTemplate).subscribe(() => { this.goBac...
identifier_body
add-vmware-template.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { v4 as uuid } from 'uuid'; import { Server } from '../../../../models/server';
import { VmwareVm } from '../../../../models/vmware/vmware-vm'; import { ServerService } from '../../../../services/server.service'; import { TemplateMocksService } from '../../../../services/template-mocks.service'; import { ToasterService } from '../../../../services/toaster.service'; import { VmwareService } from '....
import { VmwareTemplate } from '../../../../models/templates/vmware-template';
random_line_split
add-vmware-template.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { v4 as uuid } from 'uuid'; import { Server } from '../../../../models/server'; import { VmwareTemplate } from '../../../....
implements OnInit { server: Server; virtualMachines: VmwareVm[]; selectedVM: VmwareVm; vmwareTemplate: VmwareTemplate; templateNameForm: FormGroup; constructor( private route: ActivatedRoute, private serverService: ServerService, private vmwareService: VmwareService, private toasterService...
AddVmwareTemplateComponent
identifier_name
add-vmware-template.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { v4 as uuid } from 'uuid'; import { Server } from '../../../../models/server'; import { VmwareTemplate } from '../../../....
} }
{ this.toasterService.error(`Fill all required fields`); }
conditional_block
thermal_monitor.py
#!/usr/bin/python # vim: ai:ts=4:sw=4:sts=4:et:fileencoding=utf-8 # # Thermal monitor # # Copyright 2013 Michal Belica <devel@beli.sk> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either ve...
def start(self): self.running = True next = time.time() sent = False while self.running: try: line = self.ser.readline() except select.error as e: if e[0] == 4: # interrupted system call continue ...
self.running = False self.data = dict() self.register_signals() self.parse_options() self.open_serial() self.cre = re.compile(r"R=(?P<addr>\w+)\s+T=(?P<temp>[.0-9]+)\r?$")
identifier_body
thermal_monitor.py
#!/usr/bin/python # vim: ai:ts=4:sw=4:sts=4:et:fileencoding=utf-8 # # Thermal monitor # # Copyright 2013 Michal Belica <devel@beli.sk> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either ve...
m = self.cre.search(line) if m: # line matched pattern addr = m.group('addr') temp = float(m.group('temp')) if addr not in self.data or self.data[addr] is None: # address not yet collected in this cycle ...
continue
conditional_block
thermal_monitor.py
#!/usr/bin/python # vim: ai:ts=4:sw=4:sts=4:et:fileencoding=utf-8 # # Thermal monitor # # Copyright 2013 Michal Belica <devel@beli.sk> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either ve...
(self): self.running = False self.data = dict() self.register_signals() self.parse_options() self.open_serial() self.cre = re.compile(r"R=(?P<addr>\w+)\s+T=(?P<temp>[.0-9]+)\r?$") def start(self): self.running = True next = time.time() sent =...
__init__
identifier_name
thermal_monitor.py
#!/usr/bin/python # vim: ai:ts=4:sw=4:sts=4:et:fileencoding=utf-8 # # Thermal monitor # # Copyright 2013 Michal Belica <devel@beli.sk> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either ve...
def sighandler_terminate(self, signum, frame): self.running = False def register_signals(self, ignore=[], terminate=[signal.SIGINT, signal.SIGTERM, signal.SIGHUP]): for sig in ignore: signal.signal(sig, signal.SIG_IGN) for sig in terminate: signal.sig...
random_line_split
logging.js
/** @license * @pnp/logging v1.0.3 - pnp - light-weight, subscribable logging framework * MIT (https://github.com/pnp/pnp/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: http://officedev.github.io/PnP-JS-Core * source: https://github.com/pnp/pnp * bugs: https://github.com/pnp/pnp/issues */ /** * Cl...
const msg = this.format(entry); switch (entry.level) { case 0 /* Verbose */: case 1 /* Info */: console.log(msg); break; case 2 /* Warning */: console.warn(msg); break; case 3 /* Erro...
*/ log(entry) {
random_line_split
logging.js
/** @license * @pnp/logging v1.0.3 - pnp - light-weight, subscribable logging framework * MIT (https://github.com/pnp/pnp/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: http://officedev.github.io/PnP-JS-Core * source: https://github.com/pnp/pnp * bugs: https://github.com/pnp/pnp/issues */ /** * Cl...
{ constructor(activeLogLevel = 2 /* Warning */, subscribers = []) { this.activeLogLevel = activeLogLevel; this.subscribers = subscribers; } subscribe(listener) { this.subscribers.push(listener); } clearSubscribers() { const s = this.subscribers.slice(0); ...
LoggerImpl
identifier_name
logging.js
/** @license * @pnp/logging v1.0.3 - pnp - light-weight, subscribable logging framework * MIT (https://github.com/pnp/pnp/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: http://officedev.github.io/PnP-JS-Core * source: https://github.com/pnp/pnp * bugs: https://github.com/pnp/pnp/issues */ /** * Cl...
return Logger._instance; } /** * Adds ILogListener instances to the set of subscribed listeners * * @param listeners One or more listeners to subscribe to this log */ static subscribe(...listeners) { listeners.map(listener => Logger.instance.subscribe(listener))...
{ Logger._instance = new LoggerImpl(); }
conditional_block
config_handler.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI...
} /// Extra configuration options intended for developers. #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] pub struct DevConfig { /// Switch off mutations limit in mock-vault. pub mock_unlimited_coins: bool, /// Use memory store instead of file store in mock-vault. pub mock_in_...
{ // First we read the default configuration file, and use a slightly modified default config // if there is none. let mut config: QuicP2pConfig = { match read_config_file(dirs()?, CONFIG_FILE) { Err(CoreError::IoError(ref err)) if err.kind() == io::ErrorKind::NotFoun...
identifier_body
config_handler.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI...
Err(error) => { trace!("Not available: {}", path.display()); return Err(error.into()); } }; let reader = BufReader::new(file); serde_json::from_reader(reader).map_err(|err| { info!("Could not parse: {} ({:?})", err, err); err.into() }) } /// Writ...
{ trace!("Reading: {}", path.display()); file }
conditional_block
config_handler.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI...
{ /// QuicP2p options. pub quic_p2p: QuicP2pConfig, /// Developer options. pub dev: Option<DevConfig>, } #[cfg(any(target_os = "android", target_os = "androideabi", target_os = "ios"))] fn check_config_path_set() -> Result<(), CoreError> { if unwrap!(CONFIG_DIR_PATH.lock()).is_none() { Err...
Config
identifier_name
app.js
(function(){ 'use strict';
} ); var genres = ['fable', 'fantasy', 'fiction', 'folklore', 'horror', 'humor', 'legend', 'metafiction', 'mystery', 'mythology', 'non-fiction', 'poetry'] var books = [ { title: 'A Game of Thrones: A Song of Ice and Fire', author: 'George R.R. Martin', isbn: '0553593714', review: ...
var app = angular.module('readingList', []); app.controller = ('ReadingListController', function(){ this.books = books; this.genres = genres;
random_line_split
TestFastLength.rs
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by app...
float __attribute__((kernel)) testFastLengthFloat2Float(float2 inV) { return fast_length(inV); } float __attribute__((kernel)) testFastLengthFloat3Float(float3 inV) { return fast_length(inV); } float __attribute__((kernel)) testFastLengthFloat4Float(float4 inV) { return fast_length(inV); }
random_line_split
functions_e.js
var searchData= [ ['randomdouble',['randomDouble',['../namespace_num_utils.html#a402b26db626888d32e79bfab0e6ba5c2',1,'NumUtils']]], ['randomint',['randomInt',['../namespace_num_utils.html#abb2bad9628db7cd63498680a6f84e13c',1,'NumUtils']]], ['read_5fkernels_5ffrom_5ffile',['read_kernels_from_file',['../class_c_l_h...
['removecharfromstr',['removeCharFromStr',['../namespace_str_utils.html#a1d9112fe1be09aeafa3539fb771dd7c8',1,'StrUtils']]], ['resumetimer',['resumeTimer',['../class_timer.html#ade1f50ac610d5fe49228f4e6dc3d4774',1,'Timer']]] ];
random_line_split
cron_servlet.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import posixpath import traceback from app_yaml_helper import AppYamlHelper from appengine_wrappers import IsDeadlineExceededError, logservic...
except Exception as e: _cronlog.error(error_message(traceback.format_exc())) failure_count += 1 if IsDeadlineExceededError(e): raise finally: _cronlog.info('%s: rendered %s of %s with %s failures in %s', title, success_count, len(items), failure_count, timer.Stop().F...
_cronlog.error(error_message('response status %s' % response.status)) failure_count += 1
conditional_block
cron_servlet.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import posixpath import traceback from app_yaml_helper import AppYamlHelper from appengine_wrappers import IsDeadlineExceededError, logservic...
(self, msg, *args): self._log(logging.error, msg, args) def _log(self, logfn, msg, args): try: logfn('cron: %s' % msg, *args) finally: logservice.flush() _cronlog = _CronLogger() def _RequestEachItem(title, items, request_callback): '''Runs a task |request_callback| named |title| for each i...
error
identifier_name
cron_servlet.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import posixpath import traceback from app_yaml_helper import AppYamlHelper from appengine_wrappers import IsDeadlineExceededError, logservic...
_cronlog = _CronLogger() def _RequestEachItem(title, items, request_callback): '''Runs a task |request_callback| named |title| for each item in |items|. |request_callback| must take an item and return a servlet response. Returns true if every item was successfully run, false if any return a non-200 response ...
try: logfn('cron: %s' % msg, *args) finally: logservice.flush()
identifier_body
cron_servlet.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import posixpath import traceback from app_yaml_helper import AppYamlHelper from appengine_wrappers import IsDeadlineExceededError, logservic...
# ServerInstance. # # TODO(kalman): IMPORTANT. This sometimes throws an exception, breaking # everything. Need retry logic at the fetcher level. server_instance = self._GetSafeServerInstance() trunk_fs = server_instance.host_file_system_provider.GetTrunk() def render(path): request = ...
# This is returned every time RenderServlet wants to create a new
random_line_split
disttest.py
# Copyright (c) 2014 Christian Schmitz <tynn.dev@gmail.com> # # 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, modi...
if not self.dry_run : unittest.TextTestRunner().run(tests) sys.path.remove(self.build_dir) def load_tests (self, tests) : if isinstance(tests, (unittest.TestCase, unittest.TestSuite)) : return tests if isinstance(tests, str) : try : tests = _import_module(tests) except : tests = _load_source(t...
tests.addTest(self.load_tests(_tests))
conditional_block
disttest.py
# Copyright (c) 2014 Christian Schmitz <tynn.dev@gmail.com> # # 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, modi...
def _extend_setup (_setup = setup, _Distribution = Distribution) : """ Extend the default or any other compatible distutils setup function. The Distribution class used with setup must be supplied, if setup does not distutils.dist.Distribution as default. """ def setup (**attrs) : """Extended setup functi...
if isinstance(tests, (unittest.TestCase, unittest.TestSuite)) : return tests if isinstance(tests, str) : try : tests = _import_module(tests) except : tests = _load_source(tests) if inspect.ismodule(tests) : return self.loader.loadTestsFromModule(tests) raise ValueError('Not a test suite: {}'.format...
identifier_body
disttest.py
# Copyright (c) 2014 Christian Schmitz <tynn.dev@gmail.com> # # 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, modi...
def setup (**attrs) : """Extended setup function""" if 'cmdclass' not in attrs : attrs['cmdclass'] = {'test': test} elif 'test' not in attrs['cmdclass'] : attrs['cmdclass']['test'] = test if 'distclass' not in attrs : attrs['distclass'] = type('Distribution', (_Distribution, object), {"test_suite":...
""" Extend the default or any other compatible distutils setup function. The Distribution class used with setup must be supplied, if setup does not distutils.dist.Distribution as default. """
random_line_split
disttest.py
# Copyright (c) 2014 Christian Schmitz <tynn.dev@gmail.com> # # 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, modi...
(path) : pathname = os.path.abspath(path) name = 'disttest._' + os.path.splitext(os.path.split(pathname)[1])[0] try : try : from importlib.machinery import SourceFileLoader except : return _load_source_imp(name, pathname) return SourceFileLoader(name, pathname).load_module() except : raise ImportError("No mo...
_load_source
identifier_name
binary.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed ...
(data: &[u8]) -> String { let mut s = String::new(); for (i, &byte) in data.iter().enumerate() { if i % 16 == 0 { write!(&mut s, "\n").unwrap(); } else if i % 8 == 0 { write!(&mut s, " ").unwrap(); } write!(&mut s, "{:02X} ", byte).unwrap(); } s } ...
to_string
identifier_name
binary.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed ...
else if i % 8 == 0 { write!(&mut s, " ").unwrap(); } write!(&mut s, "{:02X} ", byte).unwrap(); } s } // only compare the data part for fat pointers (ignore the vtable part) // for some (buggy) reason, the vtable part may be different even if the data reference the same // object //...
{ write!(&mut s, "\n").unwrap(); }
conditional_block
binary.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed ...
write!(&mut s, "{:02X} ", byte).unwrap(); } s } // only compare the data part for fat pointers (ignore the vtable part) // for some (buggy) reason, the vtable part may be different even if the data reference the same // object // See <https://github.com/Genymobile/gnirehtet/issues/61#issuecomment-37093...
random_line_split
binary.rs
/* * Copyright (C) 2017 Genymobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed ...
pub fn to_string(data: &[u8]) -> String { let mut s = String::new(); for (i, &byte) in data.iter().enumerate() { if i % 16 == 0 { write!(&mut s, "\n").unwrap(); } else if i % 8 == 0 { write!(&mut s, " ").unwrap(); } write!(&mut s, "{:02X} ", byte).unwrap...
{ let mut raw = [0u8; 4]; BigEndian::write_u32(&mut raw, value); raw }
identifier_body
borrowck-overloaded-index-autoderef.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } fn test1(mut f: Box<Foo>, s: String) { let p = &mut f[&s]; let q = &f[&s]; //~ ERROR cannot borrow p.use_mut(); } fn test2(mut f: Box<Foo>, s: String) { let p = &mut f[&s]; let q = &mut f[&s]; //~ ERROR cannot borrow p.use_mut(); } struct Bar { foo: Foo } fn test3(mut f: Box<Bar...
{ &mut self.y }
conditional_block
borrowck-overloaded-index-autoderef.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(mut f: Box<Bar>, s: String) { let p = &mut f.foo[&s]; let q = &mut f.foo[&s]; //~ ERROR cannot borrow p.use_mut(); } fn test4(mut f: Box<Bar>, s: String) { let p = &f.foo[&s]; let q = &f.foo[&s]; p.use_ref(); } fn test5(mut f: Box<Bar>, s: String) { let p = &f.foo[&s]; let q = &mut f....
test3
identifier_name
borrowck-overloaded-index-autoderef.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} else { &mut self.y } } } fn test1(mut f: Box<Foo>, s: String) { let p = &mut f[&s]; let q = &f[&s]; //~ ERROR cannot borrow p.use_mut(); } fn test2(mut f: Box<Foo>, s: String) { let p = &mut f[&s]; let q = &mut f[&s]; //~ ERROR cannot borrow p.use_mut(); } st...
fn index_mut(&mut self, z: &String) -> &mut isize { if *z == "x" { &mut self.x
random_line_split
Storage_IOCP.py
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
(self, df, file_set): failure = None done = False filenames = self.open_file_to_handles.keys() for filename in filenames: if filename not in file_set: continue handles = self.open_file_to_handles.poprow(filename) for handle in handles:...
_close_files
identifier_name
Storage_IOCP.py
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
return r def _file_op(self, filename, pos, param, write): begin, end = self.get_byte_range_for_filename(filename) length = end - begin hdf = self.filepool.acquire_handle(filename, for_write=write, length=length) def op(h): ...
if begin >= stop: break r.append((filename, max(pos, begin) - begin, min(end, stop) - begin))
conditional_block
Storage_IOCP.py
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
def opComplete(self, df, bytes, buffer): raise NotImplementedError class ReadFileOp(OverlappedOp): op = reactor.issueReadFile def opComplete(self, df, bytes, buffer): df.callback(buffer[:bytes]) class WriteFileOp(OverlappedOp): op = reactor.issueWriteFile def opComp...
df = self.df del self.df if ret or not bytes: try: raise ctypes.WinError() except: df.errback(Failure()) else: self.opComplete(df, bytes, buffer)
identifier_body
Storage_IOCP.py
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
# it would be nice to wait on the deferred for the outstanding ops self.add_task(0.5, self._close_files, df, file_set) else: df.callback(True) def set_max_files_open(self, max_files_open): if max_files_open <= 0: max_files_open = 1e100 self.ma...
if failure is not None: df.errback(failure) if not done:
random_line_split
fastTabSwitch.ts
describe('fast tab switch', () => { let assert = chai.assert; window.HTMLImports.whenReady(() => { let tb = d3.select('tf-tensorboard');
// This test will select the events tab. Once the events tab // renders, will select the graph tab, and immediately select // the images tab wihout waiting for the graph tab to finish // rendering. Finally, it finishes when the images tab // has rendered and no errors were thrown. let eventsTabI...
var tabs = (<any>tb.node()).$.tabs;
random_line_split
test_bm_interface.py
# Copyright (c) 2012 NTT DOCOMO, INC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
from nova.tests.baremetal.db import base from nova.virt.baremetal import db class BareMetalInterfaceTestCase(base.BMDBTestCase): def test_unique_address(self): pif1_id = db.bm_interface_create(self.context, 1, '11:11:11:11:11:11', '0x1', 1) self.assertRais...
from nova import exception
random_line_split
test_bm_interface.py
# Copyright (c) 2012 NTT DOCOMO, INC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
def test_unique_address(self): pif1_id = db.bm_interface_create(self.context, 1, '11:11:11:11:11:11', '0x1', 1) self.assertRaises(exception.DBError, db.bm_interface_create, self.context, 2, '11:11:11:11:11:11', ...
identifier_body
test_bm_interface.py
# Copyright (c) 2012 NTT DOCOMO, INC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
(self): pif_id = db.bm_interface_create(self.context, 1, '11:11:11:11:11:11', '0x1', 1) self.assertRaises(exception.NovaException, db.bm_interface_set_vif_uuid, self.context, pif_id + 1, 'AAAA')
test_vif_not_found
identifier_name
generator.rs
// a lot of the source of this file is the same as main.rs // but instead of tweeting, it just prints to stdout extern crate rand; use rand::{thread_rng, ThreadRng}; // these files are paths to plain-text lists of the various word types // these paths assume you're running with *cargo run* from the root of the crate...
() { // TemplateManager::new returns a Result because it will fail if there's a problem loading any of the files match TemplateManager::new( TEMPLATE_FILENAME, NOUNS_FILENAME, ADJECTIVES_FILENAME, ADVERBS_FILENAME, ABSTRACTS_FILENAME ) { Ok(manager) => { ...
main
identifier_name
generator.rs
// a lot of the source of this file is the same as main.rs // but instead of tweeting, it just prints to stdout extern crate rand; use rand::{thread_rng, ThreadRng}; // these files are paths to plain-text lists of the various word types // these paths assume you're running with *cargo run* from the root of the crate...
, } }, Err(err) => { println!("Failed to create a TemplateManager with err: {}", err); }, } }
{ println!("Couldn't generate a tweet"); }
conditional_block
generator.rs
// a lot of the source of this file is the same as main.rs // but instead of tweeting, it just prints to stdout extern crate rand; use rand::{thread_rng, ThreadRng}; // these files are paths to plain-text lists of the various word types // these paths assume you're running with *cargo run* from the root of the crate...
{ // TemplateManager::new returns a Result because it will fail if there's a problem loading any of the files match TemplateManager::new( TEMPLATE_FILENAME, NOUNS_FILENAME, ADJECTIVES_FILENAME, ADVERBS_FILENAME, ABSTRACTS_FILENAME ) { Ok(manager) => { ...
identifier_body
generator.rs
// a lot of the source of this file is the same as main.rs // but instead of tweeting, it just prints to stdout extern crate rand; use rand::{thread_rng, ThreadRng}; // these files are paths to plain-text lists of the various word types // these paths assume you're running with *cargo run* from the root of the crate...
println!("Failed to create a TemplateManager with err: {}", err); }, } }
random_line_split
wizard-base.component.ts
// ============================================================================ // Wizard Base - COMPONENT // // This component creates the Wizard landing page // ============================================================================ // ----------------------------------------------------------------------------...
import { ConfigService } from "../../shared/config/config.service"; import { DavisService } from "../../shared/davis.service"; import * as _ from "lodash"; // ---------------------------------------------------------------------------- // Class // --...
import { Component, OnInit } from "@angular/core"; // Services
random_line_split
wizard-base.component.ts
// ============================================================================ // Wizard Base - COMPONENT // // This component creates the Wizard landing page // ============================================================================ // ----------------------------------------------------------------------------...
ngOnInit() { this.iDavis.isBreadcrumbsVisible = true; this.iConfig.getDavisConfiguration() .then(response => { if (!response.success) { throw new Error(response.message); } this.iConfig.values.dynatrace.url = response.config.dynatrace.url; this.iConfig.value...
{}
identifier_body
wizard-base.component.ts
// ============================================================================ // Wizard Base - COMPONENT // // This component creates the Wizard landing page // ============================================================================ // ----------------------------------------------------------------------------...
() { this.iDavis.isBreadcrumbsVisible = true; this.iConfig.getDavisConfiguration() .then(response => { if (!response.success) { throw new Error(response.message); } this.iConfig.values.dynatrace.url = response.config.dynatrace.url; this.iConfig.values.dynatrace....
ngOnInit
identifier_name
wizard-base.component.ts
// ============================================================================ // Wizard Base - COMPONENT // // This component creates the Wizard landing page // ============================================================================ // ----------------------------------------------------------------------------...
this.iConfig.values.dynatrace.url = response.config.dynatrace.url; this.iConfig.values.dynatrace.token = response.config.dynatrace.token; this.iConfig.values.slack.clientId = response.config.slack.clientId; this.iConfig.values.slack.clientSecret = response.config.slack.clientSecret; ...
{ throw new Error(response.message); }
conditional_block
derive_input_object.rs
use fnv::FnvHashMap; use juniper::{ marker, DefaultScalarValue, FromInputValue, GraphQLInputObject, GraphQLType, GraphQLValue, InputValue, Registry, ToInputValue, }; #[derive(GraphQLInputObject, Debug, PartialEq)] #[graphql( name = "MyInput", description = "input descr", scalar = DefaultScalarValue...
() { let mut registry: Registry = Registry::new(FnvHashMap::default()); let meta = DocComment::meta(&(), &mut registry); assert_eq!(meta.description(), Some(&"Object comment.".to_string())); } #[test] fn test_multi_doc_comment() { let mut registry: Registry = Registry::new(FnvHashMap::default()); l...
test_doc_comment
identifier_name
derive_input_object.rs
use fnv::FnvHashMap; use juniper::{ marker, DefaultScalarValue, FromInputValue, GraphQLInputObject, GraphQLType, GraphQLValue, InputValue, Registry, ToInputValue, }; #[derive(GraphQLInputObject, Debug, PartialEq)] #[graphql( name = "MyInput", description = "input descr", scalar = DefaultScalarValue...
}
random_line_split
MessageQueueBackend.py
""" Message Queue wrapper """ __RCSID__ = "$Id$" from DIRAC.FrameworkSystem.private.standardLogging.Handler.MessageQueueHandler import MessageQueueHandler from DIRAC.Resources.LogBackends.AbstractBackend import AbstractBackend from DIRAC.FrameworkSystem.private.standardLogging.Formatter.JsonFormatter import JsonForma...
def setLevel(self, level): """ No possibility to set the level of the MessageQueue handler. It is not set by default so it can send all Log Records of all levels to the MessageQueue. """ pass
""" Each backend can initialize its attributes and create its handler with them. :params parameters: dictionary of parameters. ex: {'FileName': file.log} """ if parameters is not None: self.__queue = parameters.get("MsgQueue", self.__queue) self._handler = MessageQueueHandler(self.__queue)
identifier_body
MessageQueueBackend.py
""" Message Queue wrapper """ __RCSID__ = "$Id$" from DIRAC.FrameworkSystem.private.standardLogging.Handler.MessageQueueHandler import MessageQueueHandler from DIRAC.Resources.LogBackends.AbstractBackend import AbstractBackend from DIRAC.FrameworkSystem.private.standardLogging.Formatter.JsonFormatter import JsonForma...
:params parameters: dictionary of parameters. ex: {'FileName': file.log} """ if parameters is not None: self.__queue = parameters.get("MsgQueue", self.__queue) self._handler = MessageQueueHandler(self.__queue) def setLevel(self, level): """ No possibility to set the level of the Message...
Each backend can initialize its attributes and create its handler with them.
random_line_split
MessageQueueBackend.py
""" Message Queue wrapper """ __RCSID__ = "$Id$" from DIRAC.FrameworkSystem.private.standardLogging.Handler.MessageQueueHandler import MessageQueueHandler from DIRAC.Resources.LogBackends.AbstractBackend import AbstractBackend from DIRAC.FrameworkSystem.private.standardLogging.Formatter.JsonFormatter import JsonForma...
(self): """ Initialization of the MessageQueueBackend """ super(MessageQueueBackend, self).__init__(None, JsonFormatter) self.__queue = '' def createHandler(self, parameters=None): """ Each backend can initialize its attributes and create its handler with them. :params parameters: di...
__init__
identifier_name
MessageQueueBackend.py
""" Message Queue wrapper """ __RCSID__ = "$Id$" from DIRAC.FrameworkSystem.private.standardLogging.Handler.MessageQueueHandler import MessageQueueHandler from DIRAC.Resources.LogBackends.AbstractBackend import AbstractBackend from DIRAC.FrameworkSystem.private.standardLogging.Formatter.JsonFormatter import JsonForma...
self._handler = MessageQueueHandler(self.__queue) def setLevel(self, level): """ No possibility to set the level of the MessageQueue handler. It is not set by default so it can send all Log Records of all levels to the MessageQueue. """ pass
self.__queue = parameters.get("MsgQueue", self.__queue)
conditional_block
stdio.py
# Twisted, the Framework of Your Internet # Copyright (C) 2001 Matthew W. Lefkowitz # # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in t...
(abstract.FileDescriptor): connected = 1 ic = 0 def __init__(self): abstract.FileDescriptor.__init__(self) self.fileno = sys.__stdout__.fileno fdesc.setNonBlocking(self.fileno()) def writeSomeData(self, data): try: return os.write(self.fileno(), data) ...
StandardIOWriter
identifier_name
stdio.py
# Twisted, the Framework of Your Internet # Copyright (C) 2001 Matthew W. Lefkowitz # # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in t...
elif io.args[0] == errno.EPERM: return 0 return CONNECTION_LOST except OSError, ose: if ose.errno == errno.EPIPE: return CONNECTION_LOST if ose.errno == errno.EAGAIN: return 0 raise def connectionLo...
return 0
conditional_block
stdio.py
# Twisted, the Framework of Your Internet # Copyright (C) 2001 Matthew W. Lefkowitz # # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in t...
def doRead(self): """Some data's readable from standard input. """ return fdesc.readFromFD(self.fileno(), self.protocol.dataReceived) def closeStdin(self): """Close standard input. """ self.writer.loseConnection() def connectionLost(self, reason): ...
""" self.writer.write(data)
random_line_split
stdio.py
# Twisted, the Framework of Your Internet # Copyright (C) 2001 Matthew W. Lefkowitz # # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in t...
def writeSomeData(self, data): try: return os.write(self.fileno(), data) return rv except IOError, io: if io.args[0] == errno.EAGAIN: return 0 elif io.args[0] == errno.EPERM: return 0 return CONNECTION_...
abstract.FileDescriptor.__init__(self) self.fileno = sys.__stdout__.fileno fdesc.setNonBlocking(self.fileno())
identifier_body
BaseAssignmentDataList.js
define([ 'underscore', 'shared/views/BaseView', 'shared/views/datalist/DeadSimpleDataList' ], function (_, BaseView, DeadSimpleDataList) { var DoneButton = BaseView.extend({ className: 'simplemodal-button-bar o-form-button-bar', template: '<input type="button" data-type="close" \ ...
}, balance: _.debounce(function () { DeadSimpleDataList.prototype.balance.apply(this, arguments); this.trigger('resize'); }, this.debounceTime) }); });
{ assignment.set('__isAssigned__', true); }
conditional_block
BaseAssignmentDataList.js
define([ 'underscore', 'shared/views/BaseView', 'shared/views/datalist/DeadSimpleDataList' ], function (_, BaseView, DeadSimpleDataList) { var DoneButton = BaseView.extend({ className: 'simplemodal-button-bar o-form-button-bar', template: '<input type="button" data-type="close" \ ...
}, balance: _.debounce(function () { DeadSimpleDataList.prototype.balance.apply(this, arguments); this.trigger('resize'); }, this.debounceTime) }); });
assignment.set('__isAssigned__', true); }
random_line_split
builtin-superkinds-self-type.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl <T: Sync> Foo for T { } //~^ ERROR the parameter type `T` may not live long enough fn main() { let (tx, rx) = channel(); 1193182is.foo(tx); assert!(rx.recv() == 1193182is); }
{ }
identifier_body
builtin-superkinds-self-type.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// option. This file may not be copied, modified, or distributed // except according to those terms. // Tests (negatively) the ability for the Self type in default methods // to use capabilities granted by builtin kinds as supertraits. use std::sync::mpsc::{channel, Sender}; trait Foo : Sync+'static { fn foo(sel...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
builtin-superkinds-self-type.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(self, mut chan: Sender<Self>) { } } impl <T: Sync> Foo for T { } //~^ ERROR the parameter type `T` may not live long enough fn main() { let (tx, rx) = channel(); 1193182is.foo(tx); assert!(rx.recv() == 1193182is); }
foo
identifier_name
Searchbar.ts
/// <reference path="../launchpad/notice/notice.ts" /> /// <reference path="../basecontroller.ts" /> module sap.sbo.ng4c.header { import BaseController = sap.sbo.ng4c.BaseController; import Notice = sap.sbo.ng4c.launchpad.notice.Notice; export interface SearchbarScope extends Scope { meta: Searchb...
scope: Scope, $element: JQuery, $attrs: ng.IAttributes) { super($scope, $element, $attrs, "sap.sbo.ng4c.header.Searchbar"); this.scope = <SearchbarScope>this.$scope; this.scope.meta = { placeholder: "Look up data", search: false }; this.scope.extendSearch = $.proxy(thi...
nstructor($
identifier_name
Searchbar.ts
/// <reference path="../launchpad/notice/notice.ts" /> /// <reference path="../basecontroller.ts" /> module sap.sbo.ng4c.header { import BaseController = sap.sbo.ng4c.BaseController; import Notice = sap.sbo.ng4c.launchpad.notice.Notice; export interface SearchbarScope extends Scope { meta: Searchb...
export class Searchbar extends BaseController { private scope: SearchbarScope; public constructor($scope: Scope, $element: JQuery, $attrs: ng.IAttributes) { super($scope, $element, $attrs, "sap.sbo.ng4c.header.Searchbar"); this.scope = <SearchbarScope>this.$scope; ...
}
random_line_split
Searchbar.ts
/// <reference path="../launchpad/notice/notice.ts" /> /// <reference path="../basecontroller.ts" /> module sap.sbo.ng4c.header { import BaseController = sap.sbo.ng4c.BaseController; import Notice = sap.sbo.ng4c.launchpad.notice.Notice; export interface SearchbarScope extends Scope { meta: Searchb...
} } }
this.scope.meta.search = false; }
conditional_block
DefaultFormatter.ts
import { AbstractFormatter } from './AbstractFormatter'; import * as vscode from 'vscode'; import { FileCoverage } from 'istanbul-lib-coverage'; import { isValidLocation } from './helpers'; const uncoveredBranch = vscode.window.createTextEditorDecorationType({ backgroundColor: 'rgba(216,134,123,0.4)', overviewRule...
(editor: vscode.TextEditor) { editor.setDecorations(uncoveredLine, []); editor.setDecorations(uncoveredBranch, []); } }
clear
identifier_name
DefaultFormatter.ts
import { AbstractFormatter } from './AbstractFormatter'; import * as vscode from 'vscode'; import { FileCoverage } from 'istanbul-lib-coverage'; import { isValidLocation } from './helpers'; const uncoveredBranch = vscode.window.createTextEditorDecorationType({ backgroundColor: 'rgba(216,134,123,0.4)', overviewRule...
this.formatBranches(editor, fileCoverage); this.formatUncoveredLines(editor, fileCoverage); } formatBranches(editor: vscode.TextEditor, fileCoverage: FileCoverage) { const ranges = []; Object.keys(fileCoverage.b).forEach((branchIndex) => { fileCoverage.b[branchIndex].forEach((hitCount, loc...
{ return; }
conditional_block
DefaultFormatter.ts
import { AbstractFormatter } from './AbstractFormatter'; import * as vscode from 'vscode'; import { FileCoverage } from 'istanbul-lib-coverage'; import { isValidLocation } from './helpers'; const uncoveredBranch = vscode.window.createTextEditorDecorationType({ backgroundColor: 'rgba(216,134,123,0.4)', overviewRule...
branch.start.line - 1, branch.start.column, branch.end.line - 1, endColumn ) ); }); }); editor.setDecorations(uncoveredBranch, ranges); } formatUncoveredLines(editor: vscode.TextEditor, fileCoverage: FileCoverage) { const lines = ...
const endColumn = branch.end.column || 0; ranges.push( new vscode.Range(
random_line_split
__init__.py
import platform import glob from .io import DxlIO, Dxl320IO, DxlError from .error import BaseErrorHandler from .controller import BaseDxlController from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor from ..robot import Robot def _get_available_ports(): """ Tries to find the available usb2serial port on ...
def autodetect_robot(): """ Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """ motor_controllers = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): dxl_io = DxlIOCls(port) ids = dxl_io.scan() ...
""" Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to the same list of motor ids the first ...
identifier_body
__init__.py
import platform import glob from .io import DxlIO, Dxl320IO, DxlError from .error import BaseErrorHandler from .controller import BaseDxlController from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor from ..robot import Robot def _get_available_ports(): """ Tries to find the available usb2serial port on ...
raise IndexError('No suitable port found for ids {}!'.format(ids)) def autodetect_robot(): """ Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """ motor_controllers = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): ...
if not strict and founds >= len(ids) / 2: return port except DxlError: continue
random_line_split
__init__.py
import platform import glob from .io import DxlIO, Dxl320IO, DxlError from .error import BaseErrorHandler from .controller import BaseDxlController from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor from ..robot import Robot def _get_available_ports(): """ Tries to find the available usb2serial port on ...
return [] def get_available_ports(only_free=False): ports = _get_available_ports() if only_free: ports = list(set(ports) - set(DxlIO.get_used_ports())) return ports def find_port(ids, strict=True): """ Find the port with the specified attached motor ids. :param list ids: lis...
try: ports.append(str(_winreg.EnumValue(key, i)[1])) except WindowsError: return ports
conditional_block
__init__.py
import platform import glob from .io import DxlIO, Dxl320IO, DxlError from .error import BaseErrorHandler from .controller import BaseDxlController from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor from ..robot import Robot def _get_available_ports(): """ Tries to find the available usb2serial port on ...
(): """ Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """ motor_controllers = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): dxl_io = DxlIOCls(port) ids = dxl_io.scan() if not ids: ...
autodetect_robot
identifier_name
file_to_gcs.py
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software ...
(self, context): """ Uploads the file to Google cloud storage """ hook = GoogleCloudStorageHook( google_cloud_storage_conn_id=self.google_cloud_storage_conn_id, delegate_to=self.delegate_to) hook.upload( bucket=self.bucket, ...
execute
identifier_name
file_to_gcs.py
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software ...
from airflow.utils.decorators import apply_defaults class FileToGoogleCloudStorageOperator(BaseOperator): """ Uploads a file to Google Cloud Storage :param src: Path to the local file :type src: string :param dst: Destination path within the specified bucket :type dst: string :param bucke...
# limitations under the License. # from airflow.contrib.hooks.gcs_hook import GoogleCloudStorageHook from airflow.models import BaseOperator
random_line_split
file_to_gcs.py
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software ...
""" Uploads the file to Google cloud storage """ hook = GoogleCloudStorageHook( google_cloud_storage_conn_id=self.google_cloud_storage_conn_id, delegate_to=self.delegate_to) hook.upload( bucket=self.bucket, object=self.dst, ...
identifier_body
SimplePrompt.tsx
import * as React from 'react'; import '../App.css'; import * as jsutil from '../../../shared/src/util/jsutil'; import { SimplePromptModel } from '../models/SimplePromptModel'; import { Modal, ModalHeader, ModalBody, ModalTitle, ModalFooter, Button, FormGroup, FormControl, ControlLab...
</div>*/} } }
<button type="button" className="btn btn-default" data-dismiss="modal">Close</button> <button type="button" className="btn btn-primary">Save changes</button> </div> </div> </div>
random_line_split
SimplePrompt.tsx
import * as React from 'react'; import '../App.css'; import * as jsutil from '../../../shared/src/util/jsutil'; import { SimplePromptModel } from '../models/SimplePromptModel'; import { Modal, ModalHeader, ModalBody, ModalTitle, ModalFooter, Button, FormGroup, FormControl, ControlLab...
() { this.props.okCallback(this.state.currentValue); } onClickCancel() { this.props.cancelCallback(); } onTextChange(value: string) { this.setState({ currentValue: value }); } render() { // SPROMPT : add some markup for validation message return ( ...
onClickSubmit
identifier_name
euler50.rs
pub fn main() { let primes = || (2..).filter(|&n| (2..(n as f32).sqrt() as u32 + 1).all(|i| n % i != 0)); let isprime = |n: &u32| (2..(*n as f32).sqrt() as u32 + 1).all(|i| n % i != 0); let mut sum = 0; let mut primesums = Vec::new(); for p in primes() { sum += p; if sum > 1_000_000...
} } println!("{}", max); }
{ max = candidate; }
conditional_block
euler50.rs
let isprime = |n: &u32| (2..(*n as f32).sqrt() as u32 + 1).all(|i| n % i != 0); let mut sum = 0; let mut primesums = Vec::new(); for p in primes() { sum += p; if sum > 1_000_000 { break; }; primesums.push(sum); } let mut max = 0; for &n in &primes...
pub fn main() { let primes = || (2..).filter(|&n| (2..(n as f32).sqrt() as u32 + 1).all(|i| n % i != 0));
random_line_split
euler50.rs
pub fn
() { let primes = || (2..).filter(|&n| (2..(n as f32).sqrt() as u32 + 1).all(|i| n % i != 0)); let isprime = |n: &u32| (2..(*n as f32).sqrt() as u32 + 1).all(|i| n % i != 0); let mut sum = 0; let mut primesums = Vec::new(); for p in primes() { sum += p; if sum > 1_000_000 { ...
main
identifier_name
euler50.rs
pub fn main()
{ let primes = || (2..).filter(|&n| (2..(n as f32).sqrt() as u32 + 1).all(|i| n % i != 0)); let isprime = |n: &u32| (2..(*n as f32).sqrt() as u32 + 1).all(|i| n % i != 0); let mut sum = 0; let mut primesums = Vec::new(); for p in primes() { sum += p; if sum > 1_000_000 { ...
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
ValueParseErrorKind::InvalidFilter(token) => { StyleParseErrorKind::InvalidFilter(name, token) } } } _ => StyleParseErrorKind::OtherInvalidValue(name), }; cssparser::ParseError { kind: cs...
{ StyleParseErrorKind::InvalidColor(name, token) }
conditional_block
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
/// Get the pinch zoom factor as an untyped float. pub fn get(&self) -> f32 { self.0 } } /// One CSS "px" in the coordinate system of the "initial viewport": /// <http://www.w3.org/TR/css-device-adapt/#initial-viewport> /// /// `CSSPixel` is equal to `DeviceIndependentPixel` times a "page zoom" f...
{ PinchZoomFactor(scale) }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
(this: ValueParseErrorKind<'i>) -> Self { StyleParseErrorKind::ValueError(this) } } impl<'i> From<SelectorParseErrorKind<'i>> for StyleParseErrorKind<'i> { fn from(this: SelectorParseErrorKind<'i>) -> Self { StyleParseErrorKind::SelectorError(this) } } /// Specific errors that can be encou...
from
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
UnbalancedCloseCurlyBracketInDeclarationValueBlock, /// A property declaration value had input remaining after successfully parsing. PropertyDeclarationValueNotExhausted, /// An unexpected dimension token was encountered. UnexpectedDimension(CowRcStr<'i>), /// Expected identifier not found. ...
random_line_split
verify.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var fs = require('fs'); var jsdom = require('jsdom'); function cleanTag (tree) { cleanAttributes(tree); } func...
function checkTag (tree, tagName, attributes) { if (!tree || tree._nodeName !== tagName) { throw 'Invalid tag.'; } var attr; attributes = attributes || []; Object.keys(attributes).forEach(function (name) { var expectedValue = attributes[name]; var inputAttribute = tree.attributes[name]; ...
{ var output = ''; var childOutput = ''; if (tree._nodeName.indexOf('app-') === 0) { for (var i = 0, l = tree._childNodes.length; i < l; ++i) { childOutput += cleanContentSubTree(tree._childNodes[i]); } output += '<' + tree._nodeName + createAttributeString(tree) + '>' + childOutput + '</' + tre...
identifier_body