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
option_unwrap.rs
// The commoner has seen it all, and can handle any gift well. // All gifts are handled explicitly using `match`. fn give_commoner(gift: Option<&str>) { // Specify a course of action for each case. match gift { Some("snake") => println!("Yuck! I'm throwing that snake in a fire."), Some(inner) ...
give_princess(nothing); }
let bird = Some("robin"); let nothing = None; give_princess(bird);
random_line_split
exclusive_conditions.py
# Copyright 2013-present Barefoot Networks, Inc. # # 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 ...
return extracted_headers = _get_extracted_headers(state) for hdr1, hdr2 in itertools.product(path_hdrs, extracted_headers): compatibles.add( (hdr1, hdr2) ) compatibles.add( (hdr2, hdr1) ) for next_state in next_states: _find_rec(next_state, curren...
if state in current_path: return try: next_states = set(state.branch_to.values()) except:
random_line_split
exclusive_conditions.py
# Copyright 2013-present Barefoot Networks, Inc. # # 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 ...
(hlir): def _find_paths(state, paths, current_path, path_hdrs, tag_stacks_index): try: next_states = set(state.branch_to.values()) except: paths.append(path_hdrs) return extracted_headers = set() for call in state.call_sequence: if call...
_find_parser_paths
identifier_name
exclusive_conditions.py
# Copyright 2013-present Barefoot Networks, Inc. # # 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 ...
def _check_condition(self, c, hdrs_valid): if not c: return Solver.TRUE if c.op == "valid": if hdrs_valid[c.right]: return Solver.TRUE else: return Solver.FALSE elif c.op == "and": left = self._check_condition(c.left, hdrs...
for hdr1, hdr2 in itertools.product(hdrs_valid, repeat = 2): if hdr2 not in self.compatible_headers[hdr1] and\ hdrs_valid[hdr1] and hdrs_valid[hdr2]: return False if hdr1 in self.implied_headers[hdr2] and\ hdrs_valid[hdr2] and not hdrs_v...
identifier_body
exclusive_conditions.py
# Copyright 2013-present Barefoot Networks, Inc. # # 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 ...
self.compatible_headers[hdr] = set() self.implied_headers[hdr] = all_headers.copy() for path in self.paths: for hdr in path: self.compatible_headers[hdr] |= path self.implied_headers[hdr] &= path # print "COMPATIBLE_HEADERS" #...
continue
conditional_block
request.js
/* jshint sub: true */ /* global exports: true */ 'use strict'; // ////////////////////////////////////////////////////////////////////////////// // / @brief node-request-style HTTP requests // / // / @file // / // / DISCLAIMER // / // / Copyright 2015 triAGENS GmbH, Cologne, Germany // / // / Licensed under the Apach...
else if (typeof url === 'string') { options = extend({}, options, {url: url}); } return request(extend({method: method.toUpperCase()}, options)); }; }); module.exports = exports;
{ options = url; url = undefined; }
conditional_block
request.js
/* jshint sub: true */ /* global exports: true */ 'use strict'; // ////////////////////////////////////////////////////////////////////////////// // / @brief node-request-style HTTP requests // / // / @file // / // / DISCLAIMER // / // / Copyright 2015 triAGENS GmbH, Cologne, Germany // / // / Licensed under the Apach...
let path = req.url || req.uri; if (!path) { throw new Error('Request URL must not be empty.'); } let pathObj = typeof path === 'string' ? url.parse(path) : path; if (pathObj.auth) { let auth = pathObj.auth.split(':'); req = extend({ auth: { username: decodeURIComponent(auth[0]), ...
function request (req) { if (typeof req === 'string') { req = {url: req, method: 'GET'}; }
random_line_split
request.js
/* jshint sub: true */ /* global exports: true */ 'use strict'; // ////////////////////////////////////////////////////////////////////////////// // / @brief node-request-style HTTP requests // / // / @file // / // / DISCLAIMER // / // / Copyright 2015 triAGENS GmbH, Cologne, Germany // / // / Licensed under the Apach...
{ throw (msg) { if (this.status >= 400) { throw Object.assign( httperr(this.status, msg || this.message), {details: this} ); } } constructor (res, encoding, json) { this.status = this.statusCode = res.code; this.message = res.message; this.headers = res.headers ? r...
Response
identifier_name
test_flavor_rxtx.py
# Copyright 2012 Nebula, Inc. # # 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 agree...
(self): return fakes.wsgi_app_v21(init_only=('servers', 'flavors', 'os-flavor-rxtx')) def _get_flavor(self, body): return jsonutils.loads(body).get('flavor') def _get_flavors(self, body): return jsonutils.loads(body).get('flavors') def assertFlavorRxtx(self, flavor, rx...
_get_app
identifier_name
test_flavor_rxtx.py
# Copyright 2012 Nebula, Inc. # # 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 agree...
class FlavorRxtxTestV21(test.NoDBTestCase): content_type = 'application/json' _prefix = "/v2/fake" def setUp(self): super(FlavorRxtxTestV21, self).setUp() ext = ('nova.api.openstack.compute.contrib' '.flavor_rxtx.Flavor_rxtx') self.flags(osapi_compute_extension=[ext...
return [ fake_flavor_get_by_flavor_id(1), fake_flavor_get_by_flavor_id(2) ]
identifier_body
test_flavor_rxtx.py
# Copyright 2012 Nebula, Inc. # # 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 agree...
def assertFlavorRxtx(self, flavor, rxtx): self.assertEqual(str(flavor.get('rxtx_factor')), rxtx) def test_show(self): url = self._prefix + '/flavors/1' res = self._make_request(url) self.assertEqual(res.status_int, 200) self.assertFlavorRxtx(self._get_flavor(res.body), ...
random_line_split
dht_log.py
#!/usr/bin/python # Internet de las Cosas - http://internetdelascosas.cl # # Descripcion : Programa que permite obtener la lectura de un sensor DHT11 # Lenguaje : Python # Autor : Jose Zorrilla <jzorrilla@iot.cl> # Dependencias : Libreria de Adafruit https://github.com/adafruit/Adafruit_Python_DHT # Web ...
# Se ejecuta en caso de que falle alguna instruccion dentro del try except Exception,e: # Registra el error en el archivo log y termina la ejecucion write_log(str(e))
humedad, temperatura = Adafruit_DHT.read_retry(sensor, pin) # Si obtiene una lectura del sensor la registra en el archivo log if humedad is not None and temperatura is not None: write_log("DHT Sensor - Temperatura: %s" % str(temperatura)) write_log("DHT Sensor - Humedad: %s" % str(humedad)) else: write...
conditional_block
dht_log.py
#!/usr/bin/python # Internet de las Cosas - http://internetdelascosas.cl # # Descripcion : Programa que permite obtener la lectura de un sensor DHT11 # Lenguaje : Python # Autor : Jose Zorrilla <jzorrilla@iot.cl> # Dependencias : Libreria de Adafruit https://github.com/adafruit/Adafruit_Python_DHT # Web ...
# Escribe un archivo log en log_path con el nombre en el formato yyyy-mm-dd_dht.log def write_log(text): log = open(log_path + datetime.datetime.now().strftime("%Y-%m-%d") + "_dht.log","a") line = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " " + text + "\n" log.write(line) log.close() # Intenta ejecut...
pin = 23
random_line_split
dht_log.py
#!/usr/bin/python # Internet de las Cosas - http://internetdelascosas.cl # # Descripcion : Programa que permite obtener la lectura de un sensor DHT11 # Lenguaje : Python # Autor : Jose Zorrilla <jzorrilla@iot.cl> # Dependencias : Libreria de Adafruit https://github.com/adafruit/Adafruit_Python_DHT # Web ...
# Intenta ejecutar las siguientes instrucciones, si falla va a la instruccion except try: # Ciclo principal infinito while True: # Obtiene la humedad y la temperatura desde el sensor humedad, temperatura = Adafruit_DHT.read_retry(sensor, pin) # Si obtiene una lectura del sensor la registra en el archivo log...
log = open(log_path + datetime.datetime.now().strftime("%Y-%m-%d") + "_dht.log","a") line = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " " + text + "\n" log.write(line) log.close()
identifier_body
dht_log.py
#!/usr/bin/python # Internet de las Cosas - http://internetdelascosas.cl # # Descripcion : Programa que permite obtener la lectura de un sensor DHT11 # Lenguaje : Python # Autor : Jose Zorrilla <jzorrilla@iot.cl> # Dependencias : Libreria de Adafruit https://github.com/adafruit/Adafruit_Python_DHT # Web ...
(text): log = open(log_path + datetime.datetime.now().strftime("%Y-%m-%d") + "_dht.log","a") line = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " " + text + "\n" log.write(line) log.close() # Intenta ejecutar las siguientes instrucciones, si falla va a la instruccion except try: # Ciclo principal infi...
write_log
identifier_name
FileMetricManagerReporter.test.ts
import { expect } from 'chai'; import { BaseCounter, BaseFastCompass, BaseGauge, BaseHistogram, BaseMeter, BaseTimer, MetricName } from '../../../src/common'; import { FileMetricsManagerReporter, MetricsServerManager } from '../../../src'; import { join } from 'path'; const fs = require('fs'); const os =...
}); it('register a metric and report to file reporter invoke test', (done) => { expect(fs.existsSync(metricsPath)).to.false; const manager = new MetricsServerManager(); manager.register('test', MetricName.build('reporter.register.pv'), new BaseCounter()); manager.register('test', MetricName.build...
{ fs.unlinkSync(metricsPath); }
conditional_block
FileMetricManagerReporter.test.ts
import { expect } from 'chai'; import { BaseCounter, BaseFastCompass, BaseGauge, BaseHistogram, BaseMeter, BaseTimer, MetricName } from '../../../src/common'; import { FileMetricsManagerReporter, MetricsServerManager } from '../../../src'; import { join } from 'path'; const fs = require('fs'); const os =...
}); manager.register('test', MetricName.build('reporter.register.histogram'), new BaseHistogram()); manager.register('test', MetricName.build('reporter.register.timer'), new BaseTimer()); manager.register('test', MetricName.build('reporter.register.meter'), new BaseMeter()); manager.register('test'...
{ return 0; }
identifier_body
FileMetricManagerReporter.test.ts
import { expect } from 'chai'; import { BaseCounter,
MetricName } from '../../../src/common'; import { FileMetricsManagerReporter, MetricsServerManager } from '../../../src'; import { join } from 'path'; const fs = require('fs'); const os = require('os'); describe('/test/unit/reporter/FileMetricManagerReporter.test.ts', () => { const metricsPath = join(os.tmpdir()...
BaseFastCompass, BaseGauge, BaseHistogram, BaseMeter, BaseTimer,
random_line_split
FileMetricManagerReporter.test.ts
import { expect } from 'chai'; import { BaseCounter, BaseFastCompass, BaseGauge, BaseHistogram, BaseMeter, BaseTimer, MetricName } from '../../../src/common'; import { FileMetricsManagerReporter, MetricsServerManager } from '../../../src'; import { join } from 'path'; const fs = require('fs'); const os =...
() { return 0; } }); manager.register('test', MetricName.build('reporter.register.histogram'), new BaseHistogram()); manager.register('test', MetricName.build('reporter.register.timer'), new BaseTimer()); manager.register('test', MetricName.build('reporter.register.meter'), new BaseMeter()...
getValue
identifier_name
button-noscript.test.ts
import * as path from 'path' import { ComponentDoc } from '../../../src/Documentation' import { parse } from '../../../src/main'
describe('tests button with no script block', () => { beforeEach(async () => { docButton = await parse(button) }) it('should have a slot.', () => { expect(docButton.slots && docButton.slots.length).toEqual(1) }) it('the default slot should have "Use this slot default" as description', () => { expect(getTe...
import getTestDescriptor from '../../utils/getTestDescriptor' const button = path.join(__dirname, './MyButton.vue') let docButton: ComponentDoc
random_line_split
mavproxy_calibration.py
#!/usr/bin/env python '''calibration command handling''' import time, os from pymavlink import mavutil from MAVProxy.modules.lib import mp_module class CalibrationModule(mp_module.MPModule): def __init__(self, mpstate): super(CalibrationModule, self).__init__(mpstate, "calibration") self.add_comm...
'''run a accel level''' self.master.calibrate_level() def cmd_accelcal(self, args): '''do a full 3D accel calibration''' mav = self.master # ack the APM to begin 3D calibration of accelerometers mav.mav.command_long_send(mav.target_system, mav.target_component, ...
'''do a ground start mode''' self.master.calibrate_imu() def cmd_level(self, args):
random_line_split
mavproxy_calibration.py
#!/usr/bin/env python '''calibration command handling''' import time, os from pymavlink import mavutil from MAVProxy.modules.lib import mp_module class
(mp_module.MPModule): def __init__(self, mpstate): super(CalibrationModule, self).__init__(mpstate, "calibration") self.add_command('ground', self.cmd_ground, 'do a ground start') self.add_command('level', self.cmd_level, 'set level on a multicopter') self.add_command('compassmo...
CalibrationModule
identifier_name
mavproxy_calibration.py
#!/usr/bin/env python '''calibration command handling''' import time, os from pymavlink import mavutil from MAVProxy.modules.lib import mp_module class CalibrationModule(mp_module.MPModule): def __init__(self, mpstate): super(CalibrationModule, self).__init__(mpstate, "calibration") self.add_comm...
def cmd_compassmot(self, args): '''do a compass/motor interference calibration''' mav = self.master print("compassmot starting") mav.mav.command_long_send(mav.target_system, mav.target_component, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, ...
'''handle mavlink packets''' if self.accelcal_count != -1: if self.accelcal_wait_enter and self.empty_input_count != self.mpstate.empty_input_count: self.accelcal_wait_enter = False self.accelcal_count += 1 # tell the APM that user has done as requeste...
identifier_body
mavproxy_calibration.py
#!/usr/bin/env python '''calibration command handling''' import time, os from pymavlink import mavutil from MAVProxy.modules.lib import mp_module class CalibrationModule(mp_module.MPModule): def __init__(self, mpstate): super(CalibrationModule, self).__init__(mpstate, "calibration") self.add_comm...
def cmd_compassmot(self, args): '''do a compass/motor interference calibration''' mav = self.master print("compassmot starting") mav.mav.command_long_send(mav.target_system, mav.target_component, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, ...
if self.mpstate.empty_input_count != self.empty_input_count: # user has hit enter, stop the process self.compassmot_running = False print("sending stop") self.master.mav.command_ack_send(0, 1)
conditional_block
Confirmation.js
import Timeouts from 'platform/testing/e2e/timeouts'; class
{ validatePageLoaded = () => { cy.get('h1', { timeout: Timeouts.slow }) .should('be.visible') .and('have.text', 'You’ve completed pre-check-in'); }; validatePageContent = () => { cy.get('h1', { timeout: Timeouts.slow }) .should('be.visible') .and('have.text', 'You’ve completed pr...
Confirmation
identifier_name
Confirmation.js
import Timeouts from 'platform/testing/e2e/timeouts'; class Confirmation { validatePageLoaded = () => { cy.get('h1', { timeout: Timeouts.slow }) .should('be.visible') .and('have.text', 'You’ve completed pre-check-in'); }; validatePageContent = () => { cy.get('h1', { timeout: Timeouts.slow })...
validateConfirmNoUpdates = () => { cy.get("[data-testid='confirmation-update-alert']").should('not.exist'); }; } export default new Confirmation();
); };
random_line_split
where_op_test.py
required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ==========...
(self, dtype, expected_err_re=None): shape = [127, 33, 53] x = np.random.randn(*shape) + 1j * np.random.randn(*shape) x = (np.random.randn(*shape) > 0).astype(dtype) truth = np.where(np.abs(x) > 0) # Tuples of indices by axis. truth = np.vstack(truth).T # Convert to [num_true, indices]. self._...
_testRandom
identifier_name
where_op_test.py
tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.platform import benchmark from tensorflow.python.platform import test class WhereOpTest(test.TestCase): ...
name = "m_%d_n_%d_use_gpu_%s" % (m, n, use_gpu) device = "/%s:0" % ("gpu" if use_gpu else "cpu") with ops.Graph().as_default(): with ops.device(device): x_gen = random_ops.random_uniform([m, n], dtype=dtypes.float32) y_gen = random_ops.random_uniform([m, n], dtype=dtypes.float32)...
conditional_block
where_op_test.py
required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ==========...
@test_util.run_deprecated_v1 def testRandomInt64(self): self._testRandom(np.int64) @test_util.run_deprecated_v1 def testRandomFloat(self): self._testRandom(np.float32) @test_util.run_deprecated_v1 def testRandomDouble(self): self._testRandom(np.float64) @test_util.run_deprecated_v1 def ...
self._testRandom(np.int32)
identifier_body
where_op_test.py
required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ==========...
def testRandomBool(self): self._testRandom(np.bool) @test_util.run_deprecated_v1 def testRandomInt32(self): self._testRandom(np.int32) @test_util.run_deprecated_v1 def testRandomInt64(self): self._testRandom(np.int64) @test_util.run_deprecated_v1 def testRandomFloat(self): self._testRan...
@test_util.run_deprecated_v1
random_line_split
array.rs
use array_ext; use arrayvec; use smallvec; pub trait Array: arrayvec::Array + smallvec::Array<Item = <Self as arrayvec::Array>::Item> + array_ext::Array<<Self as arrayvec::Array>::Item> { } pub trait ReplaceItemType<U>: Array { type Type: Array + arrayvec::Array<Item = U> + array_ext::Array<U>; } pub trait Sm...
array_impls!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,); smaller_array_impls!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,);
random_line_split
attr.rs
; use codemap::respan; use parse::common::SeqSep; use parse::PResult; use parse::token::{self, Nonterminal}; use parse::parser::{Parser, TokenType, PathStyle}; use tokenstream::TokenStream; #[derive(PartialEq, Eq, Debug)] enum InnerAttributeParsePolicy<'a> { Permitted, NotPermitted { reason: &'a str }, } cons...
(&mut self) -> PResult<'a, ast::MetaItemKind> { Ok(if self.eat(&token::Eq) { ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?) } else if self.token == token::OpenDelim(token::Paren) { ast::MetaItemKind::List(self.parse_meta_seq()?) } else { self.eat(&...
parse_meta_item_kind
identifier_name
attr.rs
; use codemap::respan; use parse::common::SeqSep; use parse::PResult; use parse::token::{self, Nonterminal}; use parse::parser::{Parser, TokenType, PathStyle}; use tokenstream::TokenStream; #[derive(PartialEq, Eq, Debug)] enum InnerAttributeParsePolicy<'a> { Permitted, NotPermitted { reason: &'a str }, } cons...
/// matches inner_attrs* pub fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> { let mut attrs: Vec<ast::Attribute> = vec![]; loop { match self.token { token::Pound => { // Don't even try to parse if it's not an inner attrib...
/// Parse attributes that appear after the opening of an item. These should /// be preceded by an exclamation mark, but we accept and warn about one /// terminated by a semicolon.
random_line_split
attr.rs
; use codemap::respan; use parse::common::SeqSep; use parse::PResult; use parse::token::{self, Nonterminal}; use parse::parser::{Parser, TokenType, PathStyle}; use tokenstream::TokenStream; #[derive(PartialEq, Eq, Debug)] enum InnerAttributeParsePolicy<'a> { Permitted, NotPermitted { reason: &'a str }, } cons...
`//! My crate`, annotate the item enclosing them, and are \ usually found at the beginning of source files. Outer \ attributes and doc comments, like `#[test]` and `/// My function...
{ debug!("parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}", inner_parse_policy, self.token); let (span, path, tokens, mut style) = match self.token { token::Pound => { let lo = self.span; self.bump...
identifier_body
merge-with-customize.test.ts
import assert from "assert"; import webpack from "webpack"; import { mergeWithCustomize } from "../resolve"; describe("Merge", function () { customizeMergeTests(mergeWithCustomize); }); function customizeMergeTests(merge) { it("should allow overriding array behavior", function () { const first = { entry...
(a) { return a; }, })(first, second), first ); }); it("should pass key to array customizer", function () { let receivedKey; const first = { entry: ["a"], }; const second = { entry: ["b"], }; const result = merge({ customizeArray(a, _, key)...
customizeArray
identifier_name
merge-with-customize.test.ts
import assert from "assert"; import webpack from "webpack"; import { mergeWithCustomize } from "../resolve"; describe("Merge", function () { customizeMergeTests(mergeWithCustomize); }); function customizeMergeTests(merge) { it("should allow overriding array behavior", function () { const first = { entry...
assert.deepStrictEqual( merge({ customizeObject(a) { return a; }, })(first, second), first ); }); it("should pass key to object customizer", function () { let receivedKey; const first = { entry: { a: "foo", }, }; const second ...
random_line_split
merge-with-customize.test.ts
import assert from "assert"; import webpack from "webpack"; import { mergeWithCustomize } from "../resolve"; describe("Merge", function () { customizeMergeTests(mergeWithCustomize); }); function customizeMergeTests(merge) { it("should allow overriding array behavior", function () { const first = { entry...
, })(first, second); assert.strictEqual(receivedKey, "entry"); assert.deepStrictEqual(result, first); }); it("should allow overriding object behavior", function () { const first = { entry: { a: "foo", }, }; const second = { entry: { a: "bar", }, ...
{ receivedKey = key; return a; }
identifier_body
gulp-sort.d.ts
// Type definitions for gulp-sort // Project: https://github.com/pgilad/gulp-sort // Definitions by: Joe Skeen <http://github.com/joeskeen>
/// <reference path="../node/node.d.ts" /> /// <reference path="../gulp-util/gulp-util.d.ts" /> /** Sort files in stream by path or any custom sort comparator */ declare module 'gulp-sort' { import gulpUtil = require('gulp-util'); interface IOptions { /** * A function to compare two files. * Returns: * ...
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
random_line_split
test_etl_helper.py
# -*- coding: utf-8 -*- import pytest from tests.models.test_etl_record import etl_records # noqa from tests.models.test_abstract_records import dynamodb_connection # noqa from mycroft.backend.worker.etl_status_helper import ETLStatusHelper import mock RECORDS = [ {'status': 'error', 'date': '2014-09-01', 'star...
(self, get_etl_helper): etl = get_etl_helper for r in RECORDS: date = r['date'] step = 'et' # test case: no previous record etl.etl_step_complete(MSG, date, step, r) # test case: existing record etl.etl_step_started(MSG, date, ste...
test_etl_step_complete
identifier_name
test_etl_helper.py
# -*- coding: utf-8 -*- import pytest from tests.models.test_etl_record import etl_records # noqa from tests.models.test_abstract_records import dynamodb_connection # noqa from mycroft.backend.worker.etl_status_helper import ETLStatusHelper import mock RECORDS = [ {'status': 'error', 'date': '2014-09-01', 'star...
with pytest.raises(ValueError): etl.etl_step_complete(MSG, None, 'et', RECORDS[0])
assert entry_dict['etl_error'] == str(r['error_info'])
conditional_block
test_etl_helper.py
# -*- coding: utf-8 -*- import pytest from tests.models.test_etl_record import etl_records # noqa from tests.models.test_abstract_records import dynamodb_connection # noqa from mycroft.backend.worker.etl_status_helper import ETLStatusHelper import mock RECORDS = [ {'status': 'error', 'date': '2014-09-01', 'star...
with pytest.raises(ValueError): etl.etl_step_started(MSG, None, 'et') def test_etl_step_complete(self, get_etl_helper): etl = get_etl_helper for r in RECORDS: date = r['date'] step = 'et' # test case: no previous record etl.etl_s...
assert entry_dict['data_date'] == date
random_line_split
test_etl_helper.py
# -*- coding: utf-8 -*- import pytest from tests.models.test_etl_record import etl_records # noqa from tests.models.test_abstract_records import dynamodb_connection # noqa from mycroft.backend.worker.etl_status_helper import ETLStatusHelper import mock RECORDS = [ {'status': 'error', 'date': '2014-09-01', 'star...
assert entry_dict['etl_error'] == str(r['error_info']) with pytest.raises(ValueError): etl.etl_step_complete(MSG, None, 'et', RECORDS[0])
etl = get_etl_helper for r in RECORDS: date = r['date'] step = 'et' # test case: no previous record etl.etl_step_complete(MSG, date, step, r) # test case: existing record etl.etl_step_started(MSG, date, step) etl.etl_step_comp...
identifier_body
__init__.py
"""Support Google Home units.""" import logging import asyncio import voluptuous as vol from homeassistant.const import CONF_DEVICES, CONF_HOST from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession _LOG...
: """Handle all communication with the Google Home unit.""" def __init__(self, hass): """Initialize the Google Home Client.""" self.hass = hass self._connected = None async def update_info(self, host): """Update data from Google Home.""" from googledevices.api.conne...
GoogleHomeClient
identifier_name
__init__.py
"""Support Google Home units.""" import logging import asyncio import voluptuous as vol from homeassistant.const import CONF_DEVICES, CONF_HOST from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession _LOG...
hass.data[CLIENT] = GoogleHomeClient(hass) for device in config[DOMAIN][CONF_DEVICES]: hass.data[DOMAIN][device['host']] = {} if device[CONF_TRACK_DEVICES]: hass.async_create_task( discovery.async_load_platform( hass, 'device_tracker', DOMAIN, dev...
"""Set up the Google Home component.""" hass.data[DOMAIN] = {}
random_line_split
__init__.py
"""Support Google Home units.""" import logging import asyncio import voluptuous as vol from homeassistant.const import CONF_DEVICES, CONF_HOST from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession _LOG...
if device[CONF_TRACK_ALARMS]: hass.async_create_task( discovery.async_load_platform( hass, 'sensor', DOMAIN, device, config)) return True class GoogleHomeClient: """Handle all communication with the Google Home unit.""" def __init__(self, hass): ...
hass.async_create_task( discovery.async_load_platform( hass, 'device_tracker', DOMAIN, device, config))
conditional_block
__init__.py
"""Support Google Home units.""" import logging import asyncio import voluptuous as vol from homeassistant.const import CONF_DEVICES, CONF_HOST from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession _LOG...
async def update_info(self, host): """Update data from Google Home.""" from googledevices.api.connect import Cast _LOGGER.debug("Updating Google Home info for %s", host) session = async_get_clientsession(self.hass) device_info = await Cast(host, self.hass.loop, session).in...
"""Initialize the Google Home Client.""" self.hass = hass self._connected = None
identifier_body
mention-container.tsx
import * as ProfileGen from '../actions/profile-gen' import * as Tracker2Gen from '../actions/tracker2-gen' import Mention, {OwnProps} from './mention' import {isSpecialMention} from '../constants/chat2' import * as Container from '../util/container' export default Container.connect( (state, {username}: OwnProps) =>...
}), (s, d, o: OwnProps) => ({...o, ...s, ...d}) )(Mention)
} },
random_line_split
mention-container.tsx
import * as ProfileGen from '../actions/profile-gen' import * as Tracker2Gen from '../actions/tracker2-gen' import Mention, {OwnProps} from './mention' import {isSpecialMention} from '../constants/chat2' import * as Container from '../util/container' export default Container.connect( (state, {username}: OwnProps) =>...
if (state.config.following.has(username)) { return {theme: 'follow' as const} } return {theme: 'nonFollow' as const} }, (dispatch, {username}: OwnProps) => ({ onClick: isSpecialMention(username) ? undefined : () => { if (Container.isMobile) { dispatch(Profi...
{ return {theme: 'highlight' as const} }
conditional_block
balls2.rs
extern crate nalgebra as na; use na::{Point2, RealField, Vector2}; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::object::{ BodyPartHandle, ColliderDesc, DefaultBodySet, DefaultCollider...
{ let testbed = Testbed::<f32>::from_builders(0, vec![("Balls", init_world)]); testbed.run() }
identifier_body
balls2.rs
extern crate nalgebra as na; use na::{Point2, RealField, Vector2}; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::object::{ BodyPartHandle, ColliderDesc, DefaultBodySet, DefaultCollider...
<N: RealField>(testbed: &mut Testbed<N>) { /* * World */ let mechanical_world = DefaultMechanicalWorld::new(Vector2::new(r!(0.0), r!(-9.81))); let geometrical_world = DefaultGeometricalWorld::new(); let mut bodies = DefaultBodySet::new(); let mut colliders = DefaultColliderSet::new(); ...
init_world
identifier_name
balls2.rs
extern crate nalgebra as na; use na::{Point2, RealField, Vector2}; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::object::{ BodyPartHandle, ColliderDesc, DefaultBodySet, DefaultCollider...
for i in 0usize..num { for j in 0..num { let x = r!(i as f64) * shift - centerx; let y = r!(j as f64) * shift + centery; // Build the rigid body. let rb = RigidBodyDesc::new().translation(Vector2::new(x, y)).build(); let rb_handle = bodies.insert...
let centerx = shift * r!(num as f64) / r!(2.0); let centery = shift / r!(2.0);
random_line_split
main.rs
extern crate tar; extern crate flate2; use std::io::{self, Read}; use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::env; use std::process; fn decompress(tarpath: PathBuf, extract_path: PathBuf) -> io::Result<()> { use flate2::read::GzDecoder; use tar::Archive; let tarball = fs::File::op...
fn verify(res: io::Result<()>) { let _ = res.map_err(|e| { println!("error: {}", e); process::exit(1); }); } fn main() { let pwd = env::current_dir().unwrap(); let data = "./data.txt"; let tarpath = Path::new(&pwd).join("data.tar.gz"); let extractpath = Path::new(&pwd).join("o...
{ use flate2::write::GzEncoder; use flate2::Compression; use tar::Builder; let file = File::create(&output_file)?; let mut encoder = GzEncoder::new(file, Compression::default()); let mut builder = Builder::new(&mut encoder); builder.append_path(input_file)?; // scope Drop's builder, t...
identifier_body
main.rs
extern crate tar; extern crate flate2; use std::io::{self, Read}; use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::env; use std::process; fn decompress(tarpath: PathBuf, extract_path: PathBuf) -> io::Result<()> { use flate2::read::GzDecoder; use tar::Archive; let tarball = fs::File::op...
verify(decompress(tarpath, extractpath)); println!("Decompressed data"); let mut f = File::open(Path::new(&pwd).join("output").join("data.txt")).unwrap(); let mut text = String::new(); f.read_to_string(&mut text).unwrap(); assert_eq!(&text, "hi\n"); println!("Verified data"); }
verify(compress(data, tarpath.clone())); println!("Compressed data");
random_line_split
main.rs
extern crate tar; extern crate flate2; use std::io::{self, Read}; use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::env; use std::process; fn
(tarpath: PathBuf, extract_path: PathBuf) -> io::Result<()> { use flate2::read::GzDecoder; use tar::Archive; let tarball = fs::File::open(tarpath)?; let decompressed = GzDecoder::new(tarball); let mut archive = Archive::new(decompressed); fs::create_dir_all(&extract_path)?; archive.unpack(...
decompress
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
{ if list.is_empty() { return Ok(()); } try!(list[0].to_css(dest)); for item in list.iter().skip(1) { try!(write!(dest, ", ")); try!(item.to_css(dest)); } Ok(()) }
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
try!(list[0].to_css(dest)); for item in list.iter().skip(1) { try!(write!(dest, ", ")); try!(item.to_css(dest)); } Ok(()) }
{ return Ok(()); }
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
<T: ?Sized>(a: *const T, b: *const T) -> bool { a == b } /// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn serialize_comma_separated_list<W, T>(dest: &mut W, list: &[T]) -...
ptr_eq
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
#[cfg(feature = "servo")] extern crate servo_config; #[cfg(feature = "servo")] extern crate servo_url; extern crate smallvec; #[macro_use] extern crate style_derive; #[macro_use] extern crate style_traits; extern crate time; extern crate unicode_bidi; #[allow(unused_extern_crates)] extern crate unicode_segmentation; #...
#[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms;
random_line_split
test_configs.py
_dir = str(tmpdir.mkdir('cache')) temp_astropy_cache = os.path.join(temp_cache_dir, 'astropy') # Test decorator mode @paths.set_temp_cache(temp_cache_dir) def test_func(): assert paths.get_cache_dir() == temp_astropy_cache # Test temporary restoration of original default with p...
ecutable, '-
conditional_block
test_configs.py
() def test_set_temp_config(tmpdir, monkeypatch): monkeypatch.setattr(paths.set_temp_config, '_temp_path', None) orig_config_dir = paths.get_config_dir() temp_config_dir = str(tmpdir.mkdir('config')) temp_astropy_config = os.path.join(temp_config_dir, 'astropy') # Test decorator mode @paths....
(): assert paths.get_cache_dir() == temp_astropy_cache # Test temporary restoration of original default with paths.set_temp_cache() as d: assert d == orig_cache_dir == paths.get_cache_dir() test_func() # Test context manager mode (with cleanup) with paths.set_temp_cach...
test_func
identifier_name
test_configs.py
_dir() def test_set_temp_config(tmpdir, monkeypatch): monkeypatch.setattr(paths.set_temp_config, '_temp_path', None) orig_config_dir = paths.get_config_dir() temp_config_dir = str(tmpdir.mkdir('config')) temp_astropy_config = os.path.join(temp_config_dir, 'astropy') # Test decorator mode @pa...
except Exception: pass assert conf.tstnm12 == 43 def test_empty_config_file(): from ..configuration import is_unedited_config_file def get_content(fn): with io.open(get_pkg_data_filename(fn), 'rt', encoding='latin-1') as fd: return fd.read() content = get_content('da...
random_line_split
test_configs.py
@paths.set_temp_config(temp_config_dir) def test_func(): assert paths.get_config_dir() == temp_astropy_config # Test temporary restoration of original default with paths.set_temp_config() as d: assert d == orig_config_dir == paths.get_config_dir() test_func() # Te...
t_pkg_data_filename('data/deprecated.cfg') try: with catch_warnings(AstropyDeprecationWarning) as w: conf.reload() conf.max_lines assert len(w) == 1 finally: configuration._override_config_file = None conf.reload() def test_no_home(): # "import astr...
identifier_body
stateful.py
""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be ...
def shutdown(): """ Called when the module is reloaded. In ``shutdown()`` you must * Stop all created threads * Unregister all event handlers ..note :: We do *not* guaranteed to be call when Sevabot process shutdowns as the process may termina...
"""Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """
identifier_body
stateful.py
""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be ...
(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this method to have a ...
init
identifier_name
stateful.py
""" Stateful module base class and interface description. All stateful Python modules - Get Skype4Py Skype instance on init - have full control over Skype and thus are not limited to !command handlers - Reside in the some modules/ folder as UNIX script modules - Have .py extension and be ...
def init(self, sevabot): """ Set-up our state. This is called every time module is (re)loaded. You can get Skype4Py instance via ``sevabot.getSkype()``. :param sevabot: Handle to Sevabot instance """ def handle_message(self, msg, status): """Override this meth...
All exceptions slip through are caught and logged. """
random_line_split
loaders.py
# -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2019 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # ...
(fileExtension, loaderClass): """Add a new loader for fileextension @type fileExtension: string @param fileExtension: The file extension the loader is registered for @type loaderClass: object @param loaderClass: A fife.ResourceLoader implementation that loads maps from files with ...
addMapLoader
identifier_name
loaders.py
# -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2019 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # ...
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions) map = map_loader.loadResource(path) if debug: print("--- Loading map took: ", map_loader.time_to_load, " seconds.") return map def addMapLoader(fileExtension, loaderClass): """Add a new loader for fileextension @type fileExtension...
""" load map file and get (an optional) callback if major stuff is done: - map creation - parsed imports - parsed layers - parsed cameras the callback will send both a string and a float (which shows the overall process), callback(string, float) @type engine: object @param engine: FIFE engine instanc...
identifier_body
loaders.py
# -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2019 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # ...
return map def addMapLoader(fileExtension, loaderClass): """Add a new loader for fileextension @type fileExtension: string @param fileExtension: The file extension the loader is registered for @type loaderClass: object @param loaderClass: A fife.ResourceLoader implementation that loads maps ...
print("--- Loading map took: ", map_loader.time_to_load, " seconds.")
conditional_block
loaders.py
# -*- coding: utf-8 -*- # ####################################################################
# FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful...
# Copyright (C) 2005-2019 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. #
random_line_split
extra.rs
// Some helper functions pub fn range(lo: uint, hi: uint, it: |uint| -> ()) { let mut iter = lo; while iter < hi { it(iter); iter += 1; } } // Convert an integer to a string #[no_mangle] pub fn to_str_bytes(num : int, base : int) -> ~[u8] { let neg = num < 0; let digits = "0123456789ABCD...
let mut ret : ~[u8] = ~[0, ..65]; if neg { ret[place] = '-' as u8; place += 1; m_num = -num; } whole = m_num as int; if whole == 0 { ret[place] = '0' as u8; place += 1; ret[place] = '.' as u8; place += 1; } else { stored = whole; while stored != 0 { place += 1; stored /= 10; } stor...
let mut m_num = num; let mut whole : int; let mut stored : int; let mut stored_place : int; let mut rem : f32;
random_line_split
extra.rs
// Some helper functions pub fn range(lo: uint, hi: uint, it: |uint| -> ()) { let mut iter = lo; while iter < hi { it(iter); iter += 1; } } // Convert an integer to a string #[no_mangle] pub fn
(num : int, base : int) -> ~[u8] { let neg = num < 0; let digits = "0123456789ABCDEF"; let mut place = 0; let mut stored = num; let mut stor2 = num; let mut ret : ~[u8] = ~[0, ..65]; if neg { ret[place] = '-' as u8; place += 1; stored = -stored; stor2 = -stor2; } if num == 0 { ret[place] = '0' as u8...
to_str_bytes
identifier_name
extra.rs
// Some helper functions pub fn range(lo: uint, hi: uint, it: |uint| -> ()) { let mut iter = lo; while iter < hi { it(iter); iter += 1; } } // Convert an integer to a string #[no_mangle] pub fn to_str_bytes(num : int, base : int) -> ~[u8] { let neg = num < 0; let digits = "0123456789ABCD...
if num == 0 { ret[place] = '0' as u8; return ret; } while stored != 0 { place += 1; stored /= base as int; } stored = stor2; while stored != 0 { place -= 1; ret[place] = digits[stored % base as int]; stored /= base as int; } return ret; } // Dumb and simple way to convert float to string // Is n...
{ ret[place] = '-' as u8; place += 1; stored = -stored; stor2 = -stor2; }
conditional_block
extra.rs
// Some helper functions pub fn range(lo: uint, hi: uint, it: |uint| -> ())
// Convert an integer to a string #[no_mangle] pub fn to_str_bytes(num : int, base : int) -> ~[u8] { let neg = num < 0; let digits = "0123456789ABCDEF"; let mut place = 0; let mut stored = num; let mut stor2 = num; let mut ret : ~[u8] = ~[0, ..65]; if neg { ret[place] = '-' as u8; place += 1; stored = -...
{ let mut iter = lo; while iter < hi { it(iter); iter += 1; } }
identifier_body
mysql.py
#!/usr/bin/python import os from autotest.client import utils version = 3 def setup(tarball, topdir): srcdir = os.path.join(topdir, 'src') if not os.path.exists(tarball): utils.get_file('http://downloads.mysql.com/archives/mysql-5.0/mysql-5.0.45.tar.gz', tarball)
% topdir) utils.make('-j %d' % utils.count_cpus()) utils.make('install') # # MySQL doesn't create this directory on it's own. # This is where database logs and files are created. # try: os.mkdir(topdir + '/mysql/var') except Exception: pass # ...
utils.extract_tarball_to_dir(tarball, 'src') os.chdir(srcdir) utils.configure('--prefix=%s/mysql --enable-thread-safe-client' \
random_line_split
mysql.py
#!/usr/bin/python import os from autotest.client import utils version = 3 def setup(tarball, topdir):
# utils.system('%s/mysql/bin/mysql_install_db' % topdir) os.chdir(topdir) pwd = os.getcwd() tarball = os.path.join(pwd, 'mysql-5.0.45.tar.gz') utils.update_version(pwd+'/src', False, version, setup, tarball, pwd)
srcdir = os.path.join(topdir, 'src') if not os.path.exists(tarball): utils.get_file('http://downloads.mysql.com/archives/mysql-5.0/mysql-5.0.45.tar.gz', tarball) utils.extract_tarball_to_dir(tarball, 'src') os.chdir(srcdir) utils.configure('--prefix=%s/mysql --enable-thread-safe-client' \ ...
identifier_body
mysql.py
#!/usr/bin/python import os from autotest.client import utils version = 3 def
(tarball, topdir): srcdir = os.path.join(topdir, 'src') if not os.path.exists(tarball): utils.get_file('http://downloads.mysql.com/archives/mysql-5.0/mysql-5.0.45.tar.gz', tarball) utils.extract_tarball_to_dir(tarball, 'src') os.chdir(srcdir) utils.configure('--prefix=%s/mysql --enable-threa...
setup
identifier_name
mysql.py
#!/usr/bin/python import os from autotest.client import utils version = 3 def setup(tarball, topdir): srcdir = os.path.join(topdir, 'src') if not os.path.exists(tarball):
utils.extract_tarball_to_dir(tarball, 'src') os.chdir(srcdir) utils.configure('--prefix=%s/mysql --enable-thread-safe-client' \ % topdir) utils.make('-j %d' % utils.count_cpus()) utils.make('install') # # MySQL doesn't create this directory on it's own. # This is wh...
utils.get_file('http://downloads.mysql.com/archives/mysql-5.0/mysql-5.0.45.tar.gz', tarball)
conditional_block
lib.rs
v1_management* API can be found at the //! [official documentation site](https://developers.google.com/games/services). //! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/gamesmanagement1_management). //! # Features //! //! Handle the following *Resources* with ease fro...
//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. //! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making //! this call: `.param("alt", "media")`. //! //! Methods supporting uploads...
//! makes the system potentially resilient to all kinds of errors. //! //! ## Uploads and Downloads //! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be //! read by you to obtain the media.
random_line_split
subs.tsx
import { Dequeue, MarkTrackSkipped, Pause, Play, SeekBackwards, SeekForwards, Stop, UpdateQueue, } from "./actions"; import { ApiRequest, SendCommand } from "./effects"; import { Keyboard, Interval } from "hyperapp-fx"; import { MQTTSubscribe } from "@shish2k/hyperapp-mqtt"; import { htt...
}, 0); } return function () { // no unsubscribe }; } export function FetchRandomImages(room_name: string): Subscription { return [_friSubscriber, { room: room_name }]; }
{ setTimeout(function () { dispatch((state) => [ state, ApiRequest({ function: "random_images", state: state, action(state: State, response): State { let images = response.data.images....
conditional_block
subs.tsx
import { Dequeue, MarkTrackSkipped, Pause, Play, SeekBackwards, SeekForwards, Stop, UpdateQueue, } from "./actions"; import { ApiRequest, SendCommand } from "./effects"; import { Keyboard, Interval } from "hyperapp-fx"; import { MQTTSubscribe } from "@shish2k/hyperapp-mqtt"; import { htt...
(dispatch, props) { // subscription is restarted whenever props changes, // and props is just {room: state.room_name} if (props.room) { setTimeout(function () { dispatch((state) => [ state, ApiRequest({ function: "random_images", ...
_friSubscriber
identifier_name
subs.tsx
import { Dequeue, MarkTrackSkipped, Pause, Play, SeekBackwards, SeekForwards, Stop, UpdateQueue, } from "./actions"; import { ApiRequest, SendCommand } from "./effects"; import { Keyboard, Interval } from "hyperapp-fx"; import { MQTTSubscribe } from "@shish2k/hyperapp-mqtt"; import { htt...
, }), ]); }, 0); } return function () { // no unsubscribe }; } export function FetchRandomImages(room_name: string): Subscription { return [_friSubscriber, { room: room_name }]; }
{ let images = response.data.images.slice(0, 25); return { ...state, images: images.map((fn, n) => ({ filename: fn, x: n / images.length, ...
identifier_body
subs.tsx
import { Dequeue, MarkTrackSkipped, Pause, Play, SeekBackwards, SeekForwards, Stop, UpdateQueue, } from "./actions"; import { ApiRequest, SendCommand } from "./effects"; import { Keyboard, Interval } from "hyperapp-fx"; import { MQTTSubscribe } from "@shish2k/hyperapp-mqtt"; import { htt...
...state.settings, ...JSON.parse(data), }, }; case "queue": return UpdateQueue(state, JSON.parse(data)); default: return state; } ...
...state, settings: {
random_line_split
middleware.ts
import * as cuid from 'cuid'; import { applyMiddleware, compose, createStore, Middleware as ReduxMiddleware, Store } from 'redux'; import { batchActions, batchMiddleware, batchStoreEnhancer, POP, PUSH } from 'redux-batch-enhancer'; import { ActionCreators as ReduxActionCreators } from 'redux-undo'; import * as validato...
return next(action); }; } export function thunkEvaluator({ getState }: Store<any>) { return (next) => (thunkAction) => { if (typeof thunkAction === 'function') { return next(thunkAction(getState())); } else { return next(thunkAction); } }; } export functio...
{ hasDispatched = false; }
conditional_block
middleware.ts
import * as cuid from 'cuid'; import { applyMiddleware, compose, createStore, Middleware as ReduxMiddleware, Store } from 'redux'; import { batchActions, batchMiddleware, batchStoreEnhancer, POP, PUSH } from 'redux-batch-enhancer'; import { ActionCreators as ReduxActionCreators } from 'redux-undo'; import * as validato...
() { let hasDispatched = false; let batchLevel = 0; return ({ dispatch }: Store<any>) => (next) => (action) => { if (action.type === PUSH) { batchLevel++; } else if (action.type === POP) { batchLevel--; } else if (SAVE_STATE_ACTIONS.includes(action.type) && !hasDispatched) ...
saveStateAnalyzer
identifier_name
middleware.ts
import * as cuid from 'cuid'; import { applyMiddleware, compose, createStore, Middleware as ReduxMiddleware, Store } from 'redux'; import { batchActions, batchMiddleware, batchStoreEnhancer, POP, PUSH } from 'redux-batch-enhancer'; import { ActionCreators as ReduxActionCreators } from 'redux-undo'; import * as validato...
} export function arrayMiddleware() { return (next) => (action) => { return next(Array.isArray(action) ? batchActions(action) : action); }; } export function create(sagaMiddleware: any, flux: FluxCapacitor): any { const normalizingMiddleware = [ thunkEvaluator, arrayMiddleware, ...
} };
random_line_split
middleware.ts
import * as cuid from 'cuid'; import { applyMiddleware, compose, createStore, Middleware as ReduxMiddleware, Store } from 'redux'; import { batchActions, batchMiddleware, batchStoreEnhancer, POP, PUSH } from 'redux-batch-enhancer'; import { ActionCreators as ReduxActionCreators } from 'redux-undo'; import * as validato...
export function personalizationAnalyzer({ getState, dispatch }: Store<any>) { return (next) => (action) => { if (ConfigurationAdapter.isRealTimeBiasEnabled(Selectors.config(getState())) && PERSONALIZATION_CHANGE_ACTIONS.includes(action.type)) { const biasing = PersonalizationAdapter.extr...
{ return (store) => (next) => (action) => { if (!PAST_PURCHASE_SKU_ACTIONS.includes(action.type) || Selectors.pastPurchases(flux.store.getState()).length > 0) { return next(action); } if (ConfigurationAdapter.extractSecuredPayload(Selectors.config(flux.store.getState()))) { ...
identifier_body
swfScriptType.ts
/* * WHEEL (Workflow in Hierarchical distributEd parallEL) * * Copyright (c) 2016-2017 Research Institute for Information Technology(RIIT), Kyushu University. All rights reserved. * Copyright (c) 2016-2017 Advanced Institute for Computational Science, RIKEN. All rights reserved. */ import path = require('path'); ...
} export = SwfScriptType;
{ return (task.script.type === this.LUA || path.extname(task.script.path) === '.lua'); }
identifier_body
swfScriptType.ts
/* * WHEEL (Workflow in Hierarchical distributEd parallEL) * * Copyright (c) 2016-2017 Research Institute for Information Technology(RIIT), Kyushu University. All rights reserved. * Copyright (c) 2016-2017 Advanced Institute for Computational Science, RIKEN. All rights reserved. */ import path = require('path'); ...
*/ export const BASH: SwfScriptType = 'Bash'; /** * state running */ export const LUA: SwfScriptType = 'Lua'; /** * state rerunning */ export const BATCH: SwfScriptType = 'Batch'; /** * whether specified task script is bash or not * @param task task json ...
* state planning
random_line_split
swfScriptType.ts
/* * WHEEL (Workflow in Hierarchical distributEd parallEL) * * Copyright (c) 2016-2017 Research Institute for Information Technology(RIIT), Kyushu University. All rights reserved. * Copyright (c) 2016-2017 Advanced Institute for Computational Science, RIKEN. All rights reserved. */ import path = require('path'); ...
(task: SwfTaskJson): boolean { return (task.script.type === this.BASH || path.extname(task.script.path) === '.sh'); } /** * whether specified task script is batch or not * @param task task json * @return whether specified task script is batch or not */ export function isBatch(ta...
isBash
identifier_name
float.rs
#[macro_use] extern crate nom; use nom::character::streaming::digit1 as digit; use std::str; use std::str::FromStr; named!( unsigned_float<f32>, map_res!( map_res!( recognize!(alt!( delimited!(digit, tag!("."), opt!(digit)) | delimited!(opt!(digit), tag!("."), digit) )), str::from_u...
{ assert_eq!(float(&b"123.456;"[..]), Ok((&b";"[..], 123.456))); assert_eq!(float(&b"+123.456;"[..]), Ok((&b";"[..], 123.456))); assert_eq!(float(&b"-123.456;"[..]), Ok((&b";"[..], -123.456))); }
identifier_body
float.rs
#[macro_use] extern crate nom; use nom::character::streaming::digit1 as digit; use std::str; use std::str::FromStr; named!( unsigned_float<f32>, map_res!( map_res!( recognize!(alt!( delimited!(digit, tag!("."), opt!(digit)) | delimited!(opt!(digit), tag!("."), digit) )), str::from_u...
() { assert_eq!(unsigned_float(&b"123.456;"[..]), Ok((&b";"[..], 123.456))); assert_eq!(unsigned_float(&b"0.123;"[..]), Ok((&b";"[..], 0.123))); assert_eq!(unsigned_float(&b"123.0;"[..]), Ok((&b";"[..], 123.0))); assert_eq!(unsigned_float(&b"123.;"[..]), Ok((&b";"[..], 123.0))); assert_eq!(unsigned_float(&b"....
unsigned_float_test
identifier_name
float.rs
#[macro_use] extern crate nom; use nom::character::streaming::digit1 as digit; use std::str; use std::str::FromStr; named!( unsigned_float<f32>, map_res!( map_res!( recognize!(alt!( delimited!(digit, tag!("."), opt!(digit)) | delimited!(opt!(digit), tag!("."), digit) )), str::from_u...
pair!(opt!(alt!(tag!("+") | tag!("-"))), unsigned_float), |(sign, value): (Option<&[u8]>, f32)| sign .and_then(|s| if s[0] == b'-' { Some(-1f32) } else { None }) .unwrap_or(1f32) * value ) ); #[test] fn unsigned_float_test() { assert_eq!(unsigned_float(&b"123.456;"[..]), Ok((&b";"[..], 123.456)...
map!(
random_line_split
button_touch_test.rs
extern crate piston; extern crate opengl_graphics; extern crate graphics; extern crate sdl2_window; extern crate button_controller; use piston::*; use graphics::*; use opengl_graphics::*; use sdl2_window::Sdl2Window; use button_controller::{ButtonController, ButtonEvent, ButtonState}; fn main() { let opengl = Ope...
if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, g| { clear([1.0; 4], g); let color = match click_me.state(0.2) { ButtonState::Inactive => [0.6, 0.6, 0.6, 1.0], ButtonState::Hover => [0.4, 0.4, 0.4, 1.0], ...
ButtonEvent::Cancel => "Cancel", }) }
random_line_split
button_touch_test.rs
extern crate piston; extern crate opengl_graphics; extern crate graphics; extern crate sdl2_window; extern crate button_controller; use piston::*; use graphics::*; use opengl_graphics::*; use sdl2_window::Sdl2Window; use button_controller::{ButtonController, ButtonEvent, ButtonState}; fn main()
ButtonEvent::Cancel => "Cancel", }) } if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, g| { clear([1.0; 4], g); let color = match click_me.state(0.2) { ButtonState::Inactive => [0.6, 0.6, 0.6, ...
{ let opengl = OpenGL::V3_2; let mut window: Sdl2Window = WindowSettings::new("touch button", [300; 2]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let mut events = Events::new(EventSettings::new()); let mut gl = GlGraphics::new(opengl); let mut clic...
identifier_body
button_touch_test.rs
extern crate piston; extern crate opengl_graphics; extern crate graphics; extern crate sdl2_window; extern crate button_controller; use piston::*; use graphics::*; use opengl_graphics::*; use sdl2_window::Sdl2Window; use button_controller::{ButtonController, ButtonEvent, ButtonState}; fn
() { let opengl = OpenGL::V3_2; let mut window: Sdl2Window = WindowSettings::new("touch button", [300; 2]) .exit_on_esc(true) .graphics_api(opengl) .build() .unwrap(); let mut events = Events::new(EventSettings::new()); let mut gl = GlGraphics::new(opengl); let mut c...
main
identifier_name
window_helper.rs
RUSH as _); let col = brush_data.lbColor; Ok([GetRValue(col), GetGValue(col), GetBValue(col)]) }, Err(_) => Err(()) } } /// Haha you maybe though that destroying windows would be easy right? WRONG. /// The window children must first be destroyed otherwise `DestroyWindow` w...
b unsafe fn get_window_position(handle: HWND) -> (i32, i32) { use winapi::um::winuser::{GetWindowRect, ScreenToClient, GetParent}; use winapi::shared::windef::{RECT, POINT}; let mut r: RECT = mem::zeroed(); GetWindowRect(handle, &mut r); let parent = GetParent(handle); let (x, y) = if !par...
use winapi::um::winuser::SetWindowPos; use winapi::um::winuser::{HWND_TOP, SWP_NOSIZE, SWP_NOMOVE, SWP_NOACTIVATE, SWP_NOOWNERZORDER}; let after_handle = match after { None => HWND_TOP, Some(w) => w }; SetWindowPos(handle, after_handle, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVAT...
identifier_body
window_helper.rs
} }; let mut brush_data: LOGBRUSH = mem::zeroed(); GetObjectW(brush as _, mem::size_of::<LOGBRUSH>() as _, &mut brush_data as *mut LOGBRUSH as _); let col = brush_data.lbColor; Ok([GetRValue(col), GetGValue(col), GetBValue(col)]) }, ...
GetSysColorBrush(0) }
conditional_block
window_helper.rs
SW_MAXIMIZE}; unsafe { ShowWindow(handle, SW_MAXIMIZE); } } pub fn minimize_window(handle: HWND) { use winapi::um::winuser::{ShowWindow, SW_MINIMIZE}; unsafe { ShowWindow(handle, SW_MINIMIZE); } } pub fn restore_window(handle: HWND) { use winapi::um::winuser::{ShowWindow, SW_R...
window_class_name(han
identifier_name
window_helper.rs
pub const NWG_TIMER_TICK: UINT = WM_USER + 103; pub const NWG_TIMER_STOP: UINT = WM_USER + 104; /// Returns the class info of a hwnd handle #[cfg(feature = "rich-textbox")] pub fn get_class_info(hwnd: HWND) -> Result<WNDCLASSEXW, ()> { use winapi::um::winuser::{GetClassInfoExW, GetClassNameW}; use winapi::um:...
pub const NOTICE_MESSAGE: UINT = WM_USER+100; pub const NWG_INIT: UINT = WM_USER + 101; pub const NWG_TRAY: UINT = WM_USER + 102;
random_line_split
PaiCard.tsx
import { useBackend, useLocalState } from '../backend'; import { Box, Button, LabeledList, NoticeBox, Section, Stack, Tabs } from '../components'; import { Window } from '../layouts'; type PaiCardData = { candidates: Candidate[]; pai: Pai; }; type Candidate = { comments: string; description: string; key: st...
/** Once a pAI has been loaded, you can alter its settings here */ const PaiOptions = (_, context) => { const { act, data } = useBackend<PaiCardData>(context); const { pai } = data; const { can_holo, dna, emagged, laws, master, name, transmit, receive } = pai; return ( <Section fill scrollable title={name}...
random_line_split