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
win32spawn.py
import os import threading import Queue # Windows import import win32file import win32pipe import win32api import win32con import win32security import win32process import win32event class Win32Spawn(object): def __init__(self, cmd, shell=False): self.queue = Queue.Queue() self.is_terminated = Fal...
def get(self, block=True, timeout=None): return self.queue.get(block=block, timeout=timeout) def qsize(self): return self.queue.qsize() def __wait_for_child(self): # kick off threads to read from stdout and stderr of the child process threading.Thread(target=self.__do_...
# The wake_up_event must have been signalled return False
random_line_split
qsr_qtc_bc_simplified.py
# -*- coding: utf-8 -*- from __future__ import division from qsrlib_qsrs.qsr_qtc_simplified_abstractclass import QSR_QTC_Simplified_Abstractclass import numpy as np from qsrlib_io.world_qsr_trace import * class QSR_QTC_BC_Simplified(QSR_QTC_Simplified_Abstractclass): """QTCBC simplified relations. Values of ...
def qtc_to_output_format(self, qtc): """Overwrite this for the different QTC variants to select only the parts from the QTCCS tuple that you would like to return. Example for QTCBS: return `qtc[0:2]`. :param qtc: Full QTCC tuple [q1,q2,q4,q5]. :type qtc: list or tuple :ret...
""" :param qtc: :type qtc: :param distances: :type distances: :param distance_threshold: :type distance_threshold: :return: :rtype: """ ret = np.array([]) if len(qtc.shape) == 1: qtc = [qtc] for dist, state in z...
identifier_body
qsr_qtc_bc_simplified.py
# -*- coding: utf-8 -*- from __future__ import division from qsrlib_qsrs.qsr_qtc_simplified_abstractclass import QSR_QTC_Simplified_Abstractclass import numpy as np from qsrlib_io.world_qsr_trace import * class QSR_QTC_BC_Simplified(QSR_QTC_Simplified_Abstractclass): """QTCBC simplified relations. Values of ...
(self, p, q): """Calculate the Euclidean distance between points `p` and `q`. :param p: x,y coordinates. :type p: tuple :param q: x,y coordinates. :type q: tuple :return: Euclidean distance between `p` and `q`. :rtype: float """ return np.sqrt(np....
_get_euclidean_distance
identifier_name
qsr_qtc_bc_simplified.py
# -*- coding: utf-8 -*- from __future__ import division from qsrlib_qsrs.qsr_qtc_simplified_abstractclass import QSR_QTC_Simplified_Abstractclass import numpy as np from qsrlib_io.world_qsr_trace import * class QSR_QTC_BC_Simplified(QSR_QTC_Simplified_Abstractclass): """QTCBC simplified relations. Values of ...
world_state_previous.objects[o1_name].y, world_state_now.objects[o1_name].x, world_state_now.objects[o1_name].y] l = [world_state_previous.objects[o2_name].x, world_state_previous.objects[o2_name].y, ...
random_line_split
qsr_qtc_bc_simplified.py
# -*- coding: utf-8 -*- from __future__ import division from qsrlib_qsrs.qsr_qtc_simplified_abstractclass import QSR_QTC_Simplified_Abstractclass import numpy as np from qsrlib_io.world_qsr_trace import * class QSR_QTC_BC_Simplified(QSR_QTC_Simplified_Abstractclass): """QTCBC simplified relations. Values of ...
return ret.reshape(-1,4) def qtc_to_output_format(self, qtc): """Overwrite this for the different QTC variants to select only the parts from the QTCCS tuple that you would like to return. Example for QTCBS: return `qtc[0:2]`. :param qtc: Full QTCC tuple [q1,q2,q4,q5]. :typ...
ret = np.append(ret, state, axis=0)
conditional_block
content.js
(function (w) { var MIN_LENGTH = 4; if (w.self != w.top) { return; } function
(config) { if ((config.enabled && config.disallowed && config.disallowed.indexOf(w.location.hostname)!== -1) || (!config.enabled && (!config.allowed || config.allowed.indexOf(w.location.hostname)=== -1))) return; var freqRus = {}, freqEng = {}; var rus = config.charsets.indexOf("rus")!==-1; var eng = co...
colorize
identifier_name
content.js
(function (w) { var MIN_LENGTH = 4; if (w.self != w.top) { return; } function colorize(config) { if ((config.enabled && config.disallowed && config.disallowed.indexOf(w.location.hostname)!== -1) || (!config.enabled && (!config.allowed || config.allowed.indexOf(w.location.hostname)=== -1))) ret...
return initial; } stat(w.document.getElementsByTagName('html')[0]); removeUseless(); markup(w.document.getElementsByTagName('html')[0], {}, patternCurrent); } function clean() { var affected = w.document.querySelectorAll(".nlc47"); if (!affected.length) return; for (var i=0;i<affected.length;i++) { ...
return collect(element.nodeValue, initial, pattern); }
conditional_block
content.js
(function (w) { var MIN_LENGTH = 4; if (w.self != w.top) { return; } function colorize(config) { if ((config.enabled && config.disallowed && config.disallowed.indexOf(w.location.hostname)!== -1) || (!config.enabled && (!config.allowed || config.allowed.indexOf(w.location.hostname)=== -1))) ret...
} } } } } if (element.nodeType === Node.TEXT_NODE && (/\S/.test(element.nodeValue))) { return collect(element.nodeValue, initial, pattern); } return initial; } stat(w.document.getElementsByTagName('html')[0]); removeUseless(); markup(w.document.getElementsByTagName('...
var middlebit = element.childNodes[i].splitText(minPos); var endbit = middlebit.splitText(key.length); var middleclone = middlebit.cloneNode(true); spannode.appendChild(middleclone); element.replaceChild(spannode, middlebit);
random_line_split
content.js
(function (w) { var MIN_LENGTH = 4; if (w.self != w.top) { return; } function colorize(config) { if ((config.enabled && config.disallowed && config.disallowed.indexOf(w.location.hostname)!== -1) || (!config.enabled && (!config.allowed || config.allowed.indexOf(w.location.hostname)=== -1))) ret...
for (var j in efreq) { key = efreq[j][0]; var pos = element.childNodes[i].nodeValue.toLowerCase().indexOf(key); if (pos >= 0 && (minJ === -1 || minPos>pos)) { minPos = pos; minJ = j; } } if (minPos !== -1) { key = efreq[minJ][0]; val = efreq[minJ][1]; var spa...
f (/(script|style)/i.test(element.tagName)) return; if (element.nodeType === Node.ELEMENT_NODE && element.childNodes.length > 0) { var freq = {}; for (var i = 0; i < element.childNodes.length; i++) { freq = markup(element.childNodes[i], freq, pattern); } if (freq && freq.length !== 0) { var...
identifier_body
CardsService.ts
import _ from 'lodash'; import {setFilters, IQueryParams} from 'apps/search/services/SearchService'; import {PUBLISHED_STATES} from 'apps/archive/constants'; import {ITEM_STATE} from 'apps/archive/constants'; import { DESK_OUTPUT, SENT_OUTPUT, SCHEDULED_OUTPUT, } from 'apps/desks/constants'; import {appConf...
(card: ICard): IQueryParams { let params: IQueryParams = {}; if (card.type === 'search' && card.search && card.search.filter.query) { angular.copy(card.search.filter.query, params); if (card.query) { if (card.search.filter.query.q) { params.q ...
getCriteriaParams
identifier_name
CardsService.ts
import _ from 'lodash'; import {setFilters, IQueryParams} from 'apps/search/services/SearchService'; import {PUBLISHED_STATES} from 'apps/archive/constants'; import {ITEM_STATE} from 'apps/archive/constants'; import { DESK_OUTPUT, SENT_OUTPUT, SCHEDULED_OUTPUT, } from 'apps/desks/constants'; import {appConf...
case SENT_OUTPUT: deskId = card._id.substring(0, card._id.indexOf(':')); query.filter({bool: { filter: {term: {'task.desk_history': deskId}}, must_not: {term: {'task.desk': deskId}}, }}); break; case SCHEDULED_OUTPUT: ...
filterQueryByDeskType(query, card); break;
random_line_split
CardsService.ts
import _ from 'lodash'; import {setFilters, IQueryParams} from 'apps/search/services/SearchService'; import {PUBLISHED_STATES} from 'apps/archive/constants'; import {ITEM_STATE} from 'apps/archive/constants'; import { DESK_OUTPUT, SENT_OUTPUT, SCHEDULED_OUTPUT, } from 'apps/desks/constants'; import {appConf...
termsFileType, ]}); } else { query.filter(termsFileType); } } } function filterQueryByContentProfile(query, card: ICard) { if (card.contentProfile) { query.filter({terms: {profile: JSON.parse(card.contentPr...
{ if (card.fileType) { var termsHighlightsPackage = {and: [ {bool: {must: {exists: {field: 'highlight'}}}}, {term: {type: 'composite'}}, ]}; var termsFileType: any = {terms: {type: JSON.parse(card.fileType)}}; // Normal package ...
identifier_body
CardsService.ts
import _ from 'lodash'; import {setFilters, IQueryParams} from 'apps/search/services/SearchService'; import {PUBLISHED_STATES} from 'apps/archive/constants'; import {ITEM_STATE} from 'apps/archive/constants'; import { DESK_OUTPUT, SENT_OUTPUT, SCHEDULED_OUTPUT, } from 'apps/desks/constants'; import {appConf...
break; case 'spike': query.filter({term: {'task.desk': card._id}}); break; case 'highlights': query.filter({and: [ {term: {highlights: queryParam.highlight}}, ]}); break; case DESK_OUTPUT: fil...
{ query.filter({bool: { must: {term: {original_creator: session.identity._id}}, must_not: {exists: {field: 'task.desk'}}, }}); }
conditional_block
UrlscanGetHttpTransactions.js
var url = args.url; var limit = args.limitl; var defaultWaitTime = Number(args.wait_time_for_polling) uuid = executeCommand('urlscan-submit-url-command', {'url': url})[0].Contents; uri = executeCommand('urlscan-get-result-page', {'uuid': uuid})[0].Contents; var resStatusCode = 404 var waitedTime = 0 while(resStatusCo...
return 'Could not get result from UrlScan, possible rate-limit issues.' } }
return 'Could not get result from UrlScan, please try to increase the timeout.' } else {
random_line_split
UrlscanGetHttpTransactions.js
var url = args.url; var limit = args.limitl; var defaultWaitTime = Number(args.wait_time_for_polling) uuid = executeCommand('urlscan-submit-url-command', {'url': url})[0].Contents; uri = executeCommand('urlscan-get-result-page', {'uuid': uuid})[0].Contents; var resStatusCode = 404 var waitedTime = 0 while(resStatusCo...
}
{ return 'Could not get result from UrlScan, possible rate-limit issues.' }
conditional_block
fixtureSelectWithState.tsx
import retry from '@skidding/async-retry'; import React from 'react'; import { createFixtureStateProps, createValues } from '../../fixtureState'; import { uuid } from '../../util'; import { testFixtureLoader } from '../testHelpers'; import { HelloMessage } from '../testHelpers/components'; import { wrapFixtures } from ...
const fixtures = wrapFixtures({ first: <HelloMessage name="Bianca" />, }); const fixtureId = { path: 'first' }; testFixtureLoader( 'renders selected fixture with fixture state', { rendererId, fixtures }, async ({ renderer, selectFixture }) => { await selectFixture({ rendererId, fixtureId, ...
const rendererId = uuid();
random_line_split
TextArea.stories.tsx
/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. 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...
defaultValue: 'A value', } export const Disabled = Template.bind({}) Disabled.args = { ...Value.args, disabled: true, } export const Resize = Template.bind({}) Resize.args = { resize: true, } export const Error = Template.bind({}) Error.args = { validationType: 'error', }
export const Value = Template.bind({}) Value.args = {
random_line_split
PaginationDropdown.test.tsx
import { shallow, ShallowWrapper } from 'enzyme'; import { DropdownItem } from 'reactstrap'; import PaginationDropdown from '../../src/utils/PaginationDropdown'; describe('<PaginationDropdown />', () => { const setValue = jest.fn(); let wrapper: ShallowWrapper; beforeEach(() => { wrapper = shallow(<Paginati...
])('sets expected value when an item is clicked', (index, expectedValue) => { const item = wrapper.find(DropdownItem).at(index); expect(setValue).not.toHaveBeenCalled(); item.simulate('click'); expect(setValue).toHaveBeenCalledWith(expectedValue); }); });
[ 0, 10 ], [ 1, 50 ], [ 2, 100 ], [ 3, 200 ], [ 5, Infinity ],
random_line_split
setup.py
from setuptools import setup, find_packages import os version = '0.5' setup(name='uwosh.emergency.master', version=version, description="", long_description=open("README.txt").read() + "\n" + open(os.path.join("docs", "HISTORY.txt")).read(), # Get more strings from http:...
)
random_line_split
localStorageKeys.js
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2013 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, eith...
ALERT_SMS_NOTIFICATION_OVERDUE_REQUISITION: "ALERT_SMS_NOTIFICATION_OVERDUE_REQUISITION", ALERT_EMAIL_OVER_DUE_REQUISITION: "ALERT_EMAIL_OVER_DUE_REQUISITION" }, DASHBOARD_FILTERS: { "SUMMARY": "DASHBOARD_SUMMARY_PAGE", "STOCK": "DASHBOARD_STOCK_EFFICIENCY_PAGE", "STOCK-OUT": "DASHBOARD_STOCKED_...
DEFAULT_GEOGRAPHIC_ZONE: "DEFAULT_GEOGRAPHIC_ZONE", DEFAULT_PRODUCT: "DEFAULT_PRODUCT", DEFAULT_PRODUCTS: "DEFAULT_PRODUCTS", DEFAULT_FACILITY: "DEFAULT_FACILITY",
random_line_split
compute-graph.service.ts
// Copyright 2014 The Oppia Authors. 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 required by ap...
import { Injectable } from '@angular/core'; import { States } from 'domain/exploration/StatesObjectFactory'; export interface GraphLink { source: string; target: string; } export interface GraphNodes { [stateName: string]: string; } export interface GraphData { finalStateIds: string[]; initStateId: string...
import { downgradeInjectable } from '@angular/upgrade/static';
random_line_split
compute-graph.service.ts
// Copyright 2014 The Oppia Authors. 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 required by ap...
( initStateId: string, states: States, sourceStateName: string): string[] { let stateGraph = this._computeGraphData(initStateId, states); let stateNamesInBfsOrder: string[] = []; let queue: string[] = []; let seen: Record<string, boolean> = {}; seen[sourceStateName] = true; queue.push(sour...
_computeBfsTraversalOfStates
identifier_name
compute-graph.service.ts
// Copyright 2014 The Oppia Authors. 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 required by ap...
} } return stateNamesInBfsOrder; } compute(initStateId: string, states: States): GraphData { return this._computeGraphData(initStateId, states); } computeBfsTraversalOfStates( initStateId: string, states: States, sourceStateName: string): string[] { return this._computeBfsTraversa...
{ seen[dest] = true; queue.push(dest); }
conditional_block
compute-graph.service.ts
// Copyright 2014 The Oppia Authors. 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 required by ap...
} } return stateNamesInBfsOrder; } compute(initStateId: string, states: States): GraphData { return this._computeGraphData(initStateId, states); } computeBfsTraversalOfStates( initStateId: string, states: States, sourceStateName: string): string[] { return this._computeBfsTraversa...
{ let stateGraph = this._computeGraphData(initStateId, states); let stateNamesInBfsOrder: string[] = []; let queue: string[] = []; let seen: Record<string, boolean> = {}; seen[sourceStateName] = true; queue.push(sourceStateName); while (queue.length > 0) { // '.shift()' here can return...
identifier_body
styles.py
""" InaSAFE Disaster risk assessment tool developed by AusAid **Messaging styles.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 ...
'style_class': 'info'} INFO_STYLE = { 'level': 5, 'icon': 'icon-info-sign icon-white', 'style_class': 'info'} WARNING_STYLE = { 'level': 5, 'icon': 'icon-warning-sign icon-white', 'style_class': 'warning'} SUGGESTION_STYLE = { 'level': 5, 'icon': 'icon-comment icon-white', 'st...
'level': 5, 'icon': 'icon-cog icon-white',
random_line_split
gray.rs
/// Reads in a list of values and returns the gray codes of the length of each value /// Does so only up to the length of 64 bits (unsigned values) // io functions use std::io::prelude::*; use std::error::Error; use std::fs::File; use std::path::Path; use std::env; /// Decimal to Gray Code fn gray(num: u64) -> u64 {...
for val in vals { for gray in gray_length(val) { out(gray, 3); } } }
Ok(n) => parse(n), Err(why) => panic!("File could not be accessed {}", why), };
random_line_split
gray.rs
/// Reads in a list of values and returns the gray codes of the length of each value /// Does so only up to the length of 64 bits (unsigned values) // io functions use std::io::prelude::*; use std::error::Error; use std::fs::File; use std::path::Path; use std::env; /// Decimal to Gray Code fn gray(num: u64) -> u64 {...
fn main() { let args: Vec<String> = env::args().collect(); let path = Path::new(&args[1]); let vals = match get_input(path) { Ok(n) => parse(n), Err(why) => panic!("File could not be accessed {}", why), }; for val in vals { for gray in gray_length(val) { out(g...
{ let vals: Vec<u8> = contents.split("\n").map(|x| s_parser(x)).collect(); vals }
identifier_body
gray.rs
/// Reads in a list of values and returns the gray codes of the length of each value /// Does so only up to the length of 64 bits (unsigned values) // io functions use std::io::prelude::*; use std::error::Error; use std::fs::File; use std::path::Path; use std::env; /// Decimal to Gray Code fn gray(num: u64) -> u64 {...
() { let args: Vec<String> = env::args().collect(); let path = Path::new(&args[1]); let vals = match get_input(path) { Ok(n) => parse(n), Err(why) => panic!("File could not be accessed {}", why), }; for val in vals { for gray in gray_length(val) { out(gray, 3); ...
main
identifier_name
future.rs
// Copyright 2012-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-MI...
pub fn from_value(val: A) -> Future<A> { /*! * Create a future from a value. * * The value is immediately available and calling `get` later will * not block. */ Future {state: Forced(val)} } pub fn from_fn(f: ~fn() -> A) -> Future<A> { ...
{ /*! * Executes the future's closure and then returns a borrowed * pointer to the result. The borrowed pointer lasts as long as * the future. */ match self.state { Forced(ref v) => return v, Evaluating => fail2!("Recursive forcing of future!"), ...
identifier_body
future.rs
// Copyright 2012-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-MI...
do task::spawn_with((v, chan)) |(v, chan)| { chan.send(blk(v)); } Future::from_port(port) } } #[cfg(test)] mod test { use future::Future; use std::cell::Cell; use std::comm::oneshot; use std::task; #[test] fn test_from_value() { let mut f =...
* The closure and its argument will be moved into a new task. The * closure will be run and its result used as the value of the future. */ let (port, chan) = oneshot();
random_line_split
future.rs
// Copyright 2012-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-MI...
() { let mut f = Future::spawn_with(~"gale", |s| { s }); assert_eq!(f.get(), ~"gale"); } #[test] #[should_fail] fn test_futurefail() { let mut f = Future::spawn(|| fail2!()); let _x: ~str = f.get(); } #[test] fn test_sendable_future() { let expected ...
test_spawn_with
identifier_name
index.test-d.ts
import {expectType} from 'tsd'; import stripCssComments from './index.js'; expectType<string>( stripCssComments('/*! <copyright> */ body { /* unicorns */color: hotpink; }'), ); expectType<string>( stripCssComments( '/*! <copyright> */ body { /* unicorns */color: hotpink; }', { preserve: false, }), ); expectTy...
}), ); expectType<string>( stripCssComments('/*# preserved */ body { /* unicorns */color: hotpink; }', { whitespace: false, }), );
); expectType<string>( stripCssComments('/*# preserved */ body { /* unicorns */color: hotpink; }', { preserve: comment => comment.startsWith('#'),
random_line_split
mongoose.ts
import chalk = require('chalk'); import path = require('path'); import mongoose = require('mongoose'); import { FrameworkConfiguration } from '../config'; const fc: FrameworkConfiguration = FrameworkConfiguration.get(); export interface ConnectCallbackFunction { (db: mongoose.Mongoose): any; } expor...
(): boolean { return this.db !== null; } loadModels(callbackFn?: LoadModuleCallbackFunction): void { for (let modelPath of fc.assets.server.models) require(path.resolve(modelPath)); } }
isConnected
identifier_name
mongoose.ts
import chalk = require('chalk'); import path = require('path'); import mongoose = require('mongoose'); import { FrameworkConfiguration } from '../config'; const fc: FrameworkConfiguration = FrameworkConfiguration.get(); export interface ConnectCallbackFunction { (db: mongoose.Mongoose): any; } expor...
constructor() { this.db = null; } connect(callbackFn?: ConnectCallbackFunction): void { this.db = mongoose.connect(fc.config.db.uri, fc.config.db.options, (err: any): void => { if (err) { console.error(chalk.red('Could not connect to...
random_line_split
mongoose.ts
import chalk = require('chalk'); import path = require('path'); import mongoose = require('mongoose'); import { FrameworkConfiguration } from '../config'; const fc: FrameworkConfiguration = FrameworkConfiguration.get(); export interface ConnectCallbackFunction { (db: mongoose.Mongoose): any; } expor...
else { mongoose.set('debug', fc.config.db.debug); if (callbackFn) callbackFn(this.db); } }); } disconnect(callbackFn?: DisconnectCallbackFunction): void { mongoose.disconnect((err: any): void => { console.info(cha...
{ console.error(chalk.red('Could not connect to MongoDB!')); console.log(err.toString()); }
conditional_block
mongoose.ts
import chalk = require('chalk'); import path = require('path'); import mongoose = require('mongoose'); import { FrameworkConfiguration } from '../config'; const fc: FrameworkConfiguration = FrameworkConfiguration.get(); export interface ConnectCallbackFunction { (db: mongoose.Mongoose): any; } expor...
}
{ for (let modelPath of fc.assets.server.models) require(path.resolve(modelPath)); }
identifier_body
redact.test.js
/** * Copyright 2017, Google, 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 agreed to i...
const output = await runAsync(`${cmd} string "My name is Gary and my phone number is (123) 456-7890." REDACTED -t PHONE_NUMBER -a foo`); t.regex(output, /Error in redactString/); t.regex(output, /invalid authentication/); });
random_line_split
graphs.py
are created in list order. Args: so_path: list of SegmentationObject dest_path: str scaling: np.ndarray or tuple comment: str Returns: """ if scaling is None: scaling = np.array(global_params.config['scaling']) skel = Skeleton() anno = SkeletonAnnotati...
""" Stitch connected components within a graph by recursively adding edges between the closest components. Args: skel_nx: Networkx graph. Nodes require 'position' attribute. n_jobs: Number of jobs used for query of cKDTree. Returns: Single connected component graph. """ if ...
identifier_body
graphs.py
g_neuron.remove_node(n) neuron2ccsize_dict = create_ccsize_dict(g_neuron, size_dict) if np.all(np.array(list(neuron2ccsize_dict.values())) <= global_params.config['min_cc_size_ssv']): # no significant neuron SV if return_removed_nodes: return [], [list(g.nod...
vert = so.mesh[1].reshape((-1, 3)) com = np.mean(vert, axis=0) kd_tree = spatial.cKDTree(vert) dist, nn_ix = kd_tree.query([com]) nn = vert[nn_ix[0]] / scaling n = SkeletonNode().from_scratch(anno, nn[0], nn[1], nn[2]) anno.addNode(n) rep_nodes.append(n)
conditional_block
graphs.py
""" Split graph into glia and non-glua CC's. Args: nx_g: nx.Graph thresh: float clahe: bool nb_cpus: int pred_key_appendix: str verbose: bool Returns: list, list Neuron, glia connected components. """ glia_key = "glia_probas" if clahe: ...
(glia_path, glia_dict, write_paths=None): """ Get the path length of glia SV within glia_path. Assumes single connected glia component within this path. Uses the mesh property of each SegmentationObject to build a graph from all vertices to find shortest path through (or more precise: along the surf...
glia_path_length
identifier_name
graphs.py
)[0]] + weights[list(e)[1]] # nx.set_node_attributes(g, weights, 'weight') # nx.set_edge_attributes(g, e_weights, 'weights') # get neuron type connected component sizes g_neuron = g.copy() for n in g.nodes(): if glia_dict[n] != 0: g_neuron.remove_node(n) neuron2ccsize_dict =...
rep_nodes = [] for so in so_path: vert = so.mesh[1].reshape((-1, 3)) com = np.mean(vert, axis=0)
random_line_split
create.component.ts
import { Component } from '@angular/core'; import { ROUTER_DIRECTIVES, Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { HTTP_PROVIDERS } from '@angular/http'; import 'rxjs/Rx'; import { RewardType, RewardTypeService } from './RewardType.service'; @Component({ moduleId:module....
// In a real world app, we might use a remote logging infrastructure let errMsg = error.message || 'Server error'; console.error(errMsg); // log to console instead return Observable.throw(errMsg); } goBack() { window.history.back(); } }
ata.type); } }); } private handleError(error: any) { this.loading = 0;
identifier_body
create.component.ts
import { Component } from '@angular/core'; import { ROUTER_DIRECTIVES, Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { HTTP_PROVIDERS } from '@angular/http'; import 'rxjs/Rx'; import { RewardType, RewardTypeService } from './RewardType.service'; @Component({ moduleId:module....
case 1: router = '/show/add'; break; case 2: router = '/pin/add'; break; case 3: router = '/baccarat/add'; break; case 4: router = '/'; break; case 5: router = '/'; break; case 6:...
identifier_name
create.component.ts
import { Component } from '@angular/core'; import { ROUTER_DIRECTIVES, Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { HTTP_PROVIDERS } from '@angular/http'; import 'rxjs/Rx'; import { RewardType, RewardTypeService } from './RewardType.service'; @Component({ moduleId:module....
break; default: router = '/create'; } this.router.navigate([router]); } redirectTo() { this.list.map(data => { if (data.isChecked) { this.routerUrl(data.type); } }); } private handleError(error: any) { this.loading = 0; ...
break; case 8: router = '/';
random_line_split
object_safety.rs
`trait Foo : Bar<Self>`) SupertraitSelf, /// Method has something illegal Method(Rc<ty::Method<'tcx>>, MethodViolationCode), } /// Reasons a method might not be object-safe. #[derive(Copy,Clone,Debug)] pub enum
{ /// e.g., `fn foo()` StaticMethod, /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self` ReferencesSelf, /// e.g., `fn foo<A>()` Generic, } pub fn is_object_safe<'tcx>(tcx: &ty::ctxt<'tcx>, trait_def_id: ast::DefId) -> bool { ...
MethodViolationCode
identifier_name
object_safety.rs
Self)` or `fn foo(&self) -> Self` ReferencesSelf, /// e.g., `fn foo<A>()` Generic, } pub fn is_object_safe<'tcx>(tcx: &ty::ctxt<'tcx>, trait_def_id: ast::DefId) -> bool { // Because we query yes/no results frequently, we keep a cache: let de...
// fn foo(&self) -> Option<Self> // bad
random_line_split
fuzzyset.js
SizeLower || 2; fuzzyset.gramSizeUpper = gramSizeUpper || 3; fuzzyset.useLevenshtein = (typeof useLevenshtein !== 'boolean') ? true : useLevenshtein; // define all the object functions and attributes fuzzyset.exactSet = {}; fuzzyset.matchDict = {}; fuzzyset.items = {}; // helper functions ...
for (var i = 0; i < simplified.length - gramSize + 1; ++i) { results.push(simplified.slice(i, i + gramSize)); } return results; }; var _gramCounter = function(value, gramSize) { // return an object where key=gram, value=number of occurrences gramSize = gramS...
{ for (var i = 0; i < lenDiff; ++i) { value += '-'; } }
conditional_block
fuzzyset.js
gramSizeLower || 2; fuzzyset.gramSizeUpper = gramSizeUpper || 3; fuzzyset.useLevenshtein = (typeof useLevenshtein !== 'boolean') ? true : useLevenshtein; // define all the object functions and attributes fuzzyset.exactSet = {}; fuzzyset.matchDict = {}; fuzzyset.items = {}; // helper funct...
}; // return length of items in set fuzzyset.length = function() { var count = 0, prop; for (prop in this.exactSet) { if (this.exactSet.hasOwnProperty(prop)) { count += 1; } } return count; }; // return is set is e...
if (Object.prototype.toString.call(str) !== '[object String]') throw 'Must use a string as argument to FuzzySet functions'; return str.toLowerCase();
random_line_split
fuzzyset.js
gramSizeLower || 2; fuzzyset.gramSizeUpper = gramSizeUpper || 3; fuzzyset.useLevenshtein = (typeof useLevenshtein !== 'boolean') ? true : useLevenshtein; // define all the object functions and attributes fuzzyset.exactSet = {}; fuzzyset.matchDict = {}; fuzzyset.items = {}; // helper funct...
(obj) { for(var prop in obj) { if(obj.hasOwnProperty(prop)) return false; } return true; } if (isEmptyObject(matches)) { return null; } var vectorNormal = Math.sqrt(sumOfSquareGramCounts), r...
isEmptyObject
identifier_name
fuzzyset.js
SizeLower || 2; fuzzyset.gramSizeUpper = gramSizeUpper || 3; fuzzyset.useLevenshtein = (typeof useLevenshtein !== 'boolean') ? true : useLevenshtein; // define all the object functions and attributes fuzzyset.exactSet = {}; fuzzyset.matchDict = {}; fuzzyset.items = {}; // helper functions ...
if (isEmptyObject(matches)) { return null; } var vectorNormal = Math.sqrt(sumOfSquareGramCounts), results = [], matchScore; // build a results list of [score, str] for (var matchIndex in matches) { matchScore = matches[matchIndex...
{ for(var prop in obj) { if(obj.hasOwnProperty(prop)) return false; } return true; }
identifier_body
tableViewConflicts.js
// 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 // distributed un...
} };
.end();
random_line_split
label_break_value_illegal_uses.rs
// Copyright 2018 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 ...
//~ ERROR expected `{`, found `'b` } fn labeled_else() { if true {} else 'b: {} //~ ERROR expected `{`, found `'b` } fn labeled_match() { match false 'b: {} //~ ERROR expected one of `.`, `?`, `{`, or an operator } pub fn main() {}
'b: {}
conditional_block
label_break_value_illegal_uses.rs
// Copyright 2018 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 ...
pub fn main() {}
random_line_split
label_break_value_illegal_uses.rs
// Copyright 2018 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 ...
{}
identifier_body
label_break_value_illegal_uses.rs
// Copyright 2018 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 ...
() { match false 'b: {} //~ ERROR expected one of `.`, `?`, `{`, or an operator } pub fn main() {}
labeled_match
identifier_name
defaults.py
from draftjs_exporter.constants import BLOCK_TYPES, INLINE_STYLES from draftjs_exporter.dom import DOM from draftjs_exporter.types import Element, Props def
(props: Props) -> Element: """ Renders the children of a component without any specific markup for the component itself. """ return props["children"] def code_block(props: Props) -> Element: return DOM.create_element( "pre", {}, DOM.create_element("code", {}, props["children"]) ) ...
render_children
identifier_name
defaults.py
from draftjs_exporter.constants import BLOCK_TYPES, INLINE_STYLES from draftjs_exporter.dom import DOM from draftjs_exporter.types import Element, Props
""" Renders the children of a component without any specific markup for the component itself. """ return props["children"] def code_block(props: Props) -> Element: return DOM.create_element( "pre", {}, DOM.create_element("code", {}, props["children"]) ) # Default block map to ext...
def render_children(props: Props) -> Element:
random_line_split
defaults.py
from draftjs_exporter.constants import BLOCK_TYPES, INLINE_STYLES from draftjs_exporter.dom import DOM from draftjs_exporter.types import Element, Props def render_children(props: Props) -> Element: """ Renders the children of a component without any specific markup for the component itself. """ r...
# Default block map to extend. BLOCK_MAP = { BLOCK_TYPES.UNSTYLED: "p", BLOCK_TYPES.HEADER_ONE: "h1", BLOCK_TYPES.HEADER_TWO: "h2", BLOCK_TYPES.HEADER_THREE: "h3", BLOCK_TYPES.HEADER_FOUR: "h4", BLOCK_TYPES.HEADER_FIVE: "h5", BLOCK_TYPES.HEADER_SIX: "h6", BLOCK_TYPES.UNORDERED_LIST_IT...
return DOM.create_element( "pre", {}, DOM.create_element("code", {}, props["children"]) )
identifier_body
TwitchSource.py
"""News source to send a notification whenever a twitch streamer goes live.""" import datetime import logging import discord from dateutil import parser from .AbstractSources import DataBasedSource DOZER_LOGGER = logging.getLogger('dozer') class TwitchSource(DataBasedSource): """News source to send a notificat...
# streams endpoint only returns game ID, do a second request to get game names game_ids = [] for stream in json['data']: game_ids.append(stream['game_id']) params = [] for game in game_ids: params.append(('id', game)) games_json = await self.req...
return {}
conditional_block
TwitchSource.py
"""News source to send a notification whenever a twitch streamer goes live.""" import datetime import logging import discord from dateutil import parser from .AbstractSources import DataBasedSource DOZER_LOGGER = logging.getLogger('dozer') class TwitchSource(DataBasedSource): """News source to send a notificat...
client_id = self.bot.config['news']['twitch']['client_id'] self.client_id = client_id client_secret = self.bot.config['news']['twitch']['client_secret'] params = { 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'client_credential...
async def get_token(self): """Use OAuth2 to request a new token. If token fails, disable the source."""
random_line_split
TwitchSource.py
"""News source to send a notification whenever a twitch streamer goes live.""" import datetime import logging import discord from dateutil import parser from .AbstractSources import DataBasedSource DOZER_LOGGER = logging.getLogger('dozer') class TwitchSource(DataBasedSource): """News source to send a notificat...
(self): """Assemble all the current user IDs, get any game names and return the embeds and strings""" if datetime.datetime.now() > self.expiry_time: DOZER_LOGGER.info("Refreshing Twitch token due to expiry time") await self.get_token() params = [] for user in sel...
get_new_posts
identifier_name
TwitchSource.py
"""News source to send a notification whenever a twitch streamer goes live.""" import datetime import logging import discord from dateutil import parser from .AbstractSources import DataBasedSource DOZER_LOGGER = logging.getLogger('dozer') class TwitchSource(DataBasedSource): """News source to send a notificat...
async def clean_data(self, text): """Request user data from Twitch to verify the username exists and clean the data""" try: user_obj = self.users[text] except KeyError: json = await self.request('users', params={'login': text}) if len(json['data']) == 0:...
"""Make sure we have a token, then verify and add all the current users in the DB""" await self.get_token() if not data: return params = [] for login in data: params.append(('login', login)) json = await self.request("users", params=params) for u...
identifier_body
server.js
// EXPRESS SERVER HERE // // BASE SETUP var express = require('express'), app = express(), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), session = require('express-session'), methodOverride = require('method-override'), // routes = require('./routes/routes'), ...
exports = module.exports = app; // This is needed otherwise the index.js for routes will not work
console.log('Serving on port ' + app.get('port') + '. Serving more Nodes than Big Macs!'); app.listen(app.get('port')); // Not used if Gulp is activated - it is bypassed
random_line_split
server.js
// EXPRESS SERVER HERE // // BASE SETUP var express = require('express'), app = express(), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), session = require('express-session'), methodOverride = require('method-override'), // routes = require('./routes/routes'), ...
// ==========================ROUTER=================================// // =================================================================// // ROUTES FOR THE API - RUN IN THE ORDER LISTED var router = express.Router(); // ------------- ROUTES ---------------- // // REGISTERING THE ROUTES app.use('/', router); ...
{ app.use(errorHandler()); }
conditional_block
CalcView.js
foam.apps.calc.NumberFormatter', 'foam.apps.calc.SecondaryButtonsView', 'foam.apps.calc.TertiaryButtonsView', 'foam.ui.SlidePanel', 'foam.ui.animated.Label' // 'foam.chromeapp.ui.ZoomView' ], imports: [ 'document' ], exports: [ 'data' ], properties: [ { model_: 'StringProperty', ...
padding: 0; width: 100%; } .CalcView ::-webkit-scrollbar { display: none; } .CalcView ::-webkit-scrollbar-thumb { display: none; } .calc { background-color: #eee; border: 0; display: flex; flex-direction: column; height: 100%; margin...
position: fixed; margin: 0;
random_line_split
app.js
(function(){ var app = angular.module('gnsApp', ['firebase', 'gns.controllers', 'ui.router']) app.controller('loadController', function($scope, $firebaseObject){ var storage = firebase.storage(); $scope.storageRef = storage.ref() $scope.one = [] $scope.empty_alert = false/* $scope.alert_empty_field = ...
} var j = 0 for(var genero in $scope.metadatos.genero){ for(var i = 0; i<unordered_list.length; i++){ if(unordered_list[i].genero == genero){ ordered_list[j] = unordered_list[i] j++ } } } $scope.lista_especies = ordered_list } var fulfill = function(){ var result =...
{ unordered_list[k]= $scope.database.Basic[e] k++ }
conditional_block
app.js
(function(){ var app = angular.module('gnsApp', ['firebase', 'gns.controllers', 'ui.router']) app.controller('loadController', function($scope, $firebaseObject){ var storage = firebase.storage(); $scope.storageRef = storage.ref() $scope.one = [] $scope.empty_alert = false/* $scope.alert_empty_field = ...
url: '/configuracion_perfil', templateUrl: "components/configuracion_perfil/view.html" }) .state('calendar', { name: 'calendar', controller: 'calendarController', url: '/calendar', templateUrl: "components/calendar/view.html" }) .state('tourist', { name: 'tourist', controller...
random_line_split
setup.py
"""Device tracker helpers.""" import asyncio from typing import Dict, Any, Callable, Optional from types import ModuleType import attr from homeassistant.core import callback from homeassistant.setup import async_prepare_setup_platform from homeassistant.helpers import config_per_platform from homeassistant.exception...
return legacy async def async_create_platform_type( hass, config, p_type, p_config ) -> Optional[DeviceTrackerPlatform]: """Determine type of platform.""" platform = await async_prepare_setup_platform(hass, config, DOMAIN, p_type) if platform is None: return None return DeviceTrack...
"""Extract device tracker config and split between legacy and modern.""" legacy = [] for platform in await asyncio.gather( *( async_create_platform_type(hass, config, p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN) ) ): if platfo...
identifier_body
setup.py
"""Device tracker helpers.""" import asyncio from typing import Dict, Any, Callable, Optional from types import ModuleType import attr from homeassistant.core import callback from homeassistant.setup import async_prepare_setup_platform from homeassistant.helpers import config_per_platform from homeassistant.exception...
: """Class to hold platform information.""" LEGACY_SETUP = ( "async_get_scanner", "get_scanner", "async_setup_scanner", "setup_scanner", ) name = attr.ib(type=str) platform = attr.ib(type=ModuleType) config = attr.ib(type=Dict) @property def type(self):...
DeviceTrackerPlatform
identifier_name
setup.py
"""Device tracker helpers.""" import asyncio from typing import Dict, Any, Callable, Optional from types import ModuleType import attr from homeassistant.core import callback from homeassistant.setup import async_prepare_setup_platform from homeassistant.helpers import config_per_platform from homeassistant.exception...
return None async def async_setup_legacy(self, hass, tracker, discovery_info=None): """Set up a legacy platform.""" LOGGER.info("Setting up %s.%s", DOMAIN, self.type) try: scanner = None setup = None if hasattr(self.platform, "async_get_scanner"...
if hasattr(self.platform, meth): return platform_type
conditional_block
setup.py
"""Device tracker helpers.""" import asyncio from typing import Dict, Any, Callable, Optional from types import ModuleType import attr from homeassistant.core import callback from homeassistant.setup import async_prepare_setup_platform from homeassistant.helpers import config_per_platform from homeassistant.exception...
hass.async_create_task(async_device_tracker_scan(None))
async_track_time_interval(hass, async_device_tracker_scan, interval)
random_line_split
initial.rs
use git::Config; use helpers; use author::Author; use author_selection::AuthorSelection; use xdg::BaseDirectories; use Result; use CannotProcede; pub fn initial() -> Result<Config> { let xdg_dirs = BaseDirectories::with_prefix("partners")?; let config_path = xdg_dirs.place_config_file("partners.cfg")?; i...
Ok(partners_config) }
{ partners_config.add_author(&author)?; }
conditional_block
initial.rs
use git::Config; use helpers; use author::Author; use author_selection::AuthorSelection; use xdg::BaseDirectories; use Result; use CannotProcede; pub fn initial() -> Result<Config> { let xdg_dirs = BaseDirectories::with_prefix("partners")?; let config_path = xdg_dirs.place_config_file("partners.cfg")?;
if helpers::confirm("do you want to create it?")? { helpers::create_config_file(&config_path)?; } else { Err(CannotProcede)?; } } let partners_config = Config::File(config_path); let author = match Config::Local.current_author() { Ok(author) => autho...
if !config_path.exists() { println!("config file not found at {:?}", config_path);
random_line_split
initial.rs
use git::Config; use helpers; use author::Author; use author_selection::AuthorSelection; use xdg::BaseDirectories; use Result; use CannotProcede; pub fn initial() -> Result<Config>
println!("It seems like the current git author is not known to partners"); let nick = Config::Local.nick().or_else(|_| { println!("Please enter a nickname you would like to use"); helpers::query_required("Nick") })?; let name = Config::Lo...
{ let xdg_dirs = BaseDirectories::with_prefix("partners")?; let config_path = xdg_dirs.place_config_file("partners.cfg")?; if !config_path.exists() { println!("config file not found at {:?}", config_path); if helpers::confirm("do you want to create it?")? { helpers::create_con...
identifier_body
initial.rs
use git::Config; use helpers; use author::Author; use author_selection::AuthorSelection; use xdg::BaseDirectories; use Result; use CannotProcede; pub fn
() -> Result<Config> { let xdg_dirs = BaseDirectories::with_prefix("partners")?; let config_path = xdg_dirs.place_config_file("partners.cfg")?; if !config_path.exists() { println!("config file not found at {:?}", config_path); if helpers::confirm("do you want to create it?")? { ...
initial
identifier_name
express.js
'use strict'; var env = require('./env.js'), express = require('express'), morgan = require('morgan'), compression = require('compression'), bodyParser = require('body-parser'), methodOverride = require('method-override'), session = require('express-session'), passport = require('passport')...
app.use(express.static('./public')); return app; };
require('../app/route/post.server.route.js')(app); require('../app/route/tag.server.route.js')(app); require('../app/route/comment.server.route.js')(app);
random_line_split
mod.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/. */ #[cfg(any(target_os = "linux", target_os = "android"))] pub use crate::platform::freetype::{font, font_context}; ...
#[cfg(target_os = "macos")] pub use crate::platform::macos::{font, font_context, font_list, font_template}; #[cfg(any(target_os = "linux", target_os = "android"))] mod freetype { use libc::c_char; use std::ffi::CStr; use std::str; /// Creates a String from the given null-terminated buffer. /// Pa...
#[cfg(target_os = "windows")] pub use crate::platform::windows::{font, font_context, font_list, font_template};
random_line_split
mod.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/. */ #[cfg(any(target_os = "linux", target_os = "android"))] pub use crate::platform::freetype::{font, font_context}; ...
pub mod font; pub mod font_context; #[cfg(target_os = "linux")] pub mod font_list; #[cfg(target_os = "android")] mod android { pub mod font_list; } #[cfg(target_os = "android")] pub use self::android::font_list; #[cfg(any(target_os = "linux", target_os = "android"))] ...
{ str::from_utf8(CStr::from_ptr(s).to_bytes()) .unwrap() .to_owned() }
identifier_body
mod.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/. */ #[cfg(any(target_os = "linux", target_os = "android"))] pub use crate::platform::freetype::{font, font_context}; ...
(s: *const c_char) -> String { str::from_utf8(CStr::from_ptr(s).to_bytes()) .unwrap() .to_owned() } pub mod font; pub mod font_context; #[cfg(target_os = "linux")] pub mod font_list; #[cfg(target_os = "android")] mod android { pub mod font_list; ...
c_str_to_string
identifier_name
base.rs
][5], [lists][6] and [non-null wrappers][7] only require `resolve`. /// - [Interfaces][1] and [objects][3] require `resolve_field` _or_ `resolve` if you want to /// implement a custom resolution logic (probably not). /// - [Interfaces][1] and [unions][2] require `resolve_into_type` and `concrete_type_name`. /// - [In...
/// # Example /// /// This trait is intended to be used in a conjunction with a [`GraphQLType`] trait. See the example /// in the documentation of a [`GraphQLType`] trait. /// /// [1]: https://spec.graphql.org/June2018/#sec-Interfaces /// [2]: https://spec.graphql.org/June2018/#sec-Unions /// [3]: https://spec.graphql....
/// resolving GraphQL values even when a concrete Rust type is erased. ///
random_line_split
base.rs
_set` is [`None`]. /// /// [0]: https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability /// [3]: https://spec.graphql.org/June2018/#sec-Objects fn resolve( &self, info: &Self::TypeInfo, selection_set: Option<&[Selection<S>]>, executor: &Executor<Self::Context, S...
{ if is_excluded(&spread.directives, executor.variables()) { continue; } let fragment = &executor .fragment_by_name(spread.name.item) .expect("Fragment could not be found"); let sub_exec = execu...
conditional_block
base.rs
5], [lists][6] and [non-null wrappers][7] only require `resolve`. /// - [Interfaces][1] and [objects][3] require `resolve_field` _or_ `resolve` if you want to /// implement a custom resolution logic (probably not). /// - [Interfaces][1] and [unions][2] require `resolve_into_type` and `concrete_type_name`. /// - [Inpu...
/// Returns the concrete [`GraphQLType`] name for this [`GraphQLValue`] being an [interface][1], /// an [union][2] or an [object][3]. /// /// # Panics /// /// The default implementation panics. /// /// [1]: https://spec.graphql.org/June2018/#sec-Interfaces /// [2]: https://spec.gra...
{ if self.type_name(info).unwrap() == type_name { self.resolve(info, selection_set, executor) } else { panic!( "GraphQLValue::resolve_into_type() must be implemented by unions and interfaces" ); } }
identifier_body
base.rs
{ /// ## Scalar types /// /// Scalar types appear as the leaf nodes of GraphQL queries. Strings,\ /// numbers, and booleans are the built in types, and while it's possible\ /// to define your own, it's relatively uncommon. Scalar, /// ## Object types /// /// The most common type to...
TypeKind
identifier_name
master.py
import argparse import time import subprocess import logging from deep_architect import search_logging as sl from deep_architect import utils as ut from deep_architect.contrib.communicators.mongo_communicator import MongoCommunicator from search_space_factory import name_to_search_space_factory_fn from searcher impor...
(): comm, search_logger, searcher, state, config = process_config_and_args() logger.info('Using config %s', str(config)) logger.info('Current state %s', str(state)) state['search_finished'] = False comm.subscribe(get_topic_name(RESULTS_TOPIC, config), callback=lambda message: upda...
main
identifier_name
master.py
import argparse import time import subprocess import logging from deep_architect import search_logging as sl from deep_architect import utils as ut from deep_architect.contrib.communicators.mongo_communicator import MongoCommunicator from search_space_factory import name_to_search_space_factory_fn from searcher impor...
searcher.save_state(search_logger.get_search_data_folderpath()) state = { 'finished': state['finished'], 'models_sampled': state['models_sampled'], 'epochs': state['epochs'], 'best_accuracy': state['best_accuracy'] } ut.write_jsonfile(state, config['save_filepath']) u...
def save_searcher_state(searcher, state, config, search_logger): logger.info('Models finished: %d Best Accuracy: %f', state['finished'], state['best_accuracy'])
random_line_split
master.py
import argparse import time import subprocess import logging from deep_architect import search_logging as sl from deep_architect import utils as ut from deep_architect.contrib.communicators.mongo_communicator import MongoCommunicator from search_space_factory import name_to_search_space_factory_fn from searcher impor...
def should_continue(state, config): cont = config[ 'num_samples'] == -1 or state['models_sampled'] < config['num_samples'] cont = cont and (config['num_epochs'] == -1 or state['epochs'] < config['num_epochs']) return cont def should_end_searcher(state, config): kill = c...
logger.info('Publishing architecture number %d', state['models_sampled']) _, _, vs, searcher_eval_token = searcher.sample() arch = { 'vs': vs, 'evaluation_id': state['models_sampled'], 'searcher_eval_token': searcher_eval_token, 'eval_h...
conditional_block
master.py
import argparse import time import subprocess import logging from deep_architect import search_logging as sl from deep_architect import utils as ut from deep_architect.contrib.communicators.mongo_communicator import MongoCommunicator from search_space_factory import name_to_search_space_factory_fn from searcher impor...
def update_searcher_state(state, config, results): state['best_accuracy'] = max(state['best_accuracy'], results['validation_accuracy']) state['finished'] += 1 state['epochs'] += config['eval_epochs'] def log_results(results, vs, evaluation_id, searcher_eval_token, searc...
logger.info('Models finished: %d Best Accuracy: %f', state['finished'], state['best_accuracy']) searcher.save_state(search_logger.get_search_data_folderpath()) state = { 'finished': state['finished'], 'models_sampled': state['models_sampled'], 'epochs': state['epochs'], ...
identifier_body
platform.test.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
test('registry - knows, as', function() { let ext = {}; Platform.Registry.add('knows,as', ext); assert.ok(Platform.Registry.knows('knows,as')); assert.ok(!Platform.Registry.knows('knows,as1234')); assert.ok(Platform.Registry.as('knows,as') === ext); assert.ok(Platform.Registry.as('knows,as1234') === n...
assert.ok(Platform.Registry.as('foo').bar); assert.equal(Platform.Registry.as('foo').bar, true); });
random_line_split
TextureDummy.js
/** * Copyright (c) 2015, Alexander Orzechowski. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, ...
; }; Tessellator.extend(Tessellator.TextureDummy, Tessellator.Texture); Tessellator.TextureDummy.prototype.configure = Tessellator.EMPTY_FUNC; Tessellator.TextureDummy.prototype.bind = Tessellator.EMPTY_FUNC;
{ this.setReady(); }
conditional_block
TextureDummy.js
/** * Copyright (c) 2015, Alexander Orzechowski. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, ...
/** * Currently in beta stage. Changes can and will be made to the core mechanic * making this not backwards compatible. * * Github: https://github.com/Need4Speed402/tessellator */ Tessellator.TextureDummy = function (ready){ this.super(null); if (ready){ this.setReady(); }; }; Tessell...
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */
random_line_split
S15.3.2.1_A3_T14.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * When the Function constructor is called with arguments p, body the following steps are taken: * i) Let Result(i) be the first argument * ii) Let P be ToString(Result(i)) * iii) ...
//CHECK#3 if (f()!==undefined) { $ERROR('#3: When the Function constructor is called with arguments p, body the following steps are taken...'); } var body;
{ $ERROR('#2: When the Function constructor is called with arguments p, body creates a new Function object as specified in 13.2'); }
conditional_block
S15.3.2.1_A3_T14.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * When the Function constructor is called with arguments p, body the following steps are taken: * i) Let Result(i) be the first argument * ii) Let P be ToString(Result(i)) * iii) ...
* @description Values of the function constructor arguments are "a,b,c" and an undefined variable */ var p = "a,b,c"; //CHECK#1 try { var f = new Function(p, body); } catch (e) { $FAIL('#1: test failed with error '+e); } //CHECK#2 if (f.constructor !== Function) { $ERROR('#2: When the Function constructor is...
* vii) Return Result(vi) * * @path ch15/15.3/15.3.2/S15.3.2.1_A3_T14.js
random_line_split
error.rs
// Copyright 2016 evic Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to th...
(error: io::Error) -> Error { Error::Io(error) } }
from
identifier_name
error.rs
// Copyright 2016 evic Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to th...
} impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Io(..) => "eVic IO error", Error::Firmware(..) => "eVic firmware error", Error::CliError(..) => "eVic CLI error", } } fn cause(&self) -> Option<&error::Error> { ...
{ match *self { Error::Io(ref err) => write!(f, "IO error: {}", err), Error::Firmware(ref err) => write!(f, "Firmware error: {}", err), Error::CliError(ref err) => write!(f, "CLI error: {}", err), } }
identifier_body
error.rs
// Copyright 2016 evic Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to th...
}
}
random_line_split
morphology.py
import numpy as np import scipy.interpolate as interp import warnings from astropy.io import fits def concentration(radii, phot, eta_radius=0.2, eta_radius_factor=1.5, interp_kind='linear', add_zero=False): """ Calculates the concentration parameter C = 5 * log10(r_80 / r2_0) Inputs: radii -- 1d a...
norm_phot = phot / maxphot radius_interp = interp.interp1d(norm_phot, radii, kind=interp_kind) r20 = radius_interp(0.2) r80 = radius_interp(0.8) assert r20 < r80 < np.max(radii) c = 5 * np.log10(r80 / r20) return c def eta(radii, phot): """ eta = I(r) / \bar{I}(<r) rad...
maxphot = np.max(phot)
conditional_block
morphology.py
import numpy as np import scipy.interpolate as interp import warnings from astropy.io import fits def concentration(radii, phot, eta_radius=0.2, eta_radius_factor=1.5, interp_kind='linear', add_zero=False): """ Calculates the concentration parameter C = 5 * log10(r_80 / r2_0) Inputs: radii -- 1d a...
def snr(name): """ name before fits and apphot files """ #first calculate the image uncertainty using the MAD hdulist = fits.open(name + '_bs.fits') im_med = np.median(hdulist[0].data) im_err = np.median(np.abs(hdulist[0].data - im_med)) #now get the total flux apphot = np...
eta_interp = interp.interp1d(eta(radii, phot), radii) return eta_interp(eta_val)
identifier_body
morphology.py
import numpy as np import scipy.interpolate as interp import warnings from astropy.io import fits def concentration(radii, phot, eta_radius=0.2, eta_radius_factor=1.5, interp_kind='linear', add_zero=False): """ Calculates the concentration parameter C = 5 * log10(r_80 / r2_0) Inputs: radii -- 1d a...
(radii, phot): """ eta = I(r) / \bar{I}(<r) radii -- 1d array of aperture photometry radii phot -- 1d array of aperture photometry fluxes this is currently calculated quite naively, and probably could be done better """ phot_area = np.pi * radii**2 phot_area_diff = np.ediff1d(p...
eta
identifier_name
morphology.py
import numpy as np import scipy.interpolate as interp import warnings from astropy.io import fits def concentration(radii, phot, eta_radius=0.2, eta_radius_factor=1.5, interp_kind='linear', add_zero=False): """ Calculates the concentration parameter C = 5 * log10(r_80 / r2_0) Inputs: radii -- 1d a...
def snr(name): """ name before fits and apphot files """ #first calculate the image uncertainty using the MAD hdulist = fits.open(name + '_bs.fits') im_med = np.median(hdulist[0].data) im_err = np.median(np.abs(hdulist[0].data - im_med)) #now get the total flux apphot = np....
def find_eta(eta_val, radii, phot): eta_interp = interp.interp1d(eta(radii, phot), radii) return eta_interp(eta_val)
random_line_split
base.py
# Copyright 2014 Cisco Systems, 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 o...
class BaseOVSLinuxTestCase(BaseLinuxTestCase): def setUp(self, root_helper='sudo'): super(BaseOVSLinuxTestCase, self).setUp(root_helper) self.ovs = ovs_lib.BaseOVS(self.root_helper) def create_ovs_bridge(self, br_prefix=BR_PREFIX): br = self.create_resource(br_prefix, self.ovs.add_brid...
random_line_split