file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
utils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
(timestamp): """Normalize time in arbitrary timezone to UTC""" offset = timestamp.utcoffset() return timestamp.replace(tzinfo=None) - offset if offset else timestamp def safe_mkdirs(path): try: os.makedirs(path) except OSError, e: if e.errno != errno.EEXIST: raise def...
normalize_time
identifier_name
utils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
if chunk: yield chunk else: break def image_meta_to_http_headers(image_meta): """ Returns a set of image metadata into a dict of HTTP headers that can be fed to either a Webob Request object or an httplib.HTTP(S)Connection object :param image_meta: Mapping ...
random_line_split
utils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
def safe_remove(path): try: os.remove(path) except OSError, e: if e.errno != errno.ENOENT: raise class PrettyTable(object): """Creates an ASCII art table for use in bin/heat Example: ID Name Size Hits --- ----------------- --------...
raise
conditional_block
utils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
def import_class(import_str): """Returns a class from a string including module and class""" mod_str, _sep, class_str = import_str.rpartition('.') try: __import__(mod_str) return getattr(sys.modules[mod_str], class_str) except (ImportError, ValueError, AttributeError), e: rais...
""" Interpret a string as a boolean. Any string value in: ('True', 'true', 'On', 'on', '1') is interpreted as a boolean True. Useful for JSON-decoded stuff and config file parsing """ if isinstance(subject, bool): return subject elif isinstance(subject, int): return...
identifier_body
web.py
""" Nodes that use web services to do something. """ import json import httplib2 import urllib from BeautifulSoup import BeautifulSoup from nodetree import node, exceptions from . import base from .. import stages class WebServiceNodeError(exceptions.NodeError): pass class BaseWebService(node.Node, base.TextW...
(BaseWebService): """OpenCalias sematic markup.""" stage = stages.POST baseurl = "http://api.opencalais.com/tag/rs/enrich" parameters = [ ] def process(self, input): http = httplib2.Http() headers = { "x-calais-licenseID": "dsza6q6zwa9nzvz9wbz7f6y5", ...
OpenCalais
identifier_name
web.py
""" Nodes that use web services to do something. """ import json import httplib2 import urllib from BeautifulSoup import BeautifulSoup from nodetree import node, exceptions from . import base from .. import stages class WebServiceNodeError(exceptions.NodeError): pass class BaseWebService(node.Node, base.TextW...
class OpenCalais(BaseWebService): """OpenCalias sematic markup.""" stage = stages.POST baseurl = "http://api.opencalais.com/tag/rs/enrich" parameters = [ ] def process(self, input): http = httplib2.Http() headers = { "x-calais-licenseID": "dsza6q6zwa9nzvz9wbz7f...
random_line_split
web.py
""" Nodes that use web services to do something. """ import json import httplib2 import urllib from BeautifulSoup import BeautifulSoup from nodetree import node, exceptions from . import base from .. import stages class WebServiceNodeError(exceptions.NodeError): pass class BaseWebService(node.Node, base.TextW...
elif request["status"] == "400": raise WebServiceNodeError("No text, limit exceeded, or incorrect language", self) out = u"" try: data = json.loads(content) except ValueError: return content for key in ["GPE", "VP", "LOCATION", "NP", "DATE"]: ...
raise WebServiceNodeError("Daily limit exceeded", self)
conditional_block
web.py
""" Nodes that use web services to do something. """ import json import httplib2 import urllib from BeautifulSoup import BeautifulSoup from nodetree import node, exceptions from . import base from .. import stages class WebServiceNodeError(exceptions.NodeError): pass class BaseWebService(node.Node, base.TextW...
class OpenCalais(BaseWebService): """OpenCalias sematic markup.""" stage = stages.POST baseurl = "http://api.opencalais.com/tag/rs/enrich" parameters = [ ] def process(self, input): http = httplib2.Http() headers = { "x-calais-licenseID": "dsza6q6zwa9nzvz9wbz...
http = httplib2.Http() headers = {} body = dict( text=input.encode("utf8", "replace"), confidence=self._params.get("confident"), support=self._params.get("support"), ) url = "%s?%s" % (self.baseurl, urllib.urlencode(body)) request, ...
identifier_body
syslog.py
import SocketServer from abc import ABCMeta, abstractmethod import json import requests import six from .. import LOG as _LOG from ..signal.signal import DEFAULT_ORCHESTRATOR_URL from ..signal.event import LogEvent LOG = _LOG.getChild(__name__) @six.add_metaclass(ABCMeta) class SyslogInspectorBase(object): de...
insp = BasicSyslogInspector() insp.start()
conditional_block
syslog.py
import SocketServer from abc import ABCMeta, abstractmethod import json import requests import six from .. import LOG as _LOG from ..signal.signal import DEFAULT_ORCHESTRATOR_URL from ..signal.event import LogEvent LOG = _LOG.getChild(__name__) @six.add_metaclass(ABCMeta) class SyslogInspectorBase(object): de...
def send_event_to_orchestrator(self, event): event_jsdict = event.to_jsondict() headers = {'content-type': 'application/json'} post_url = self.orchestrator_rest_url + \ '/events/' + self.entity_id + '/' + event.uuid # LOG.debug('POST %s', post_url) r = requests.po...
except Exception as e: LOG.error('cannot send event: %s', event, exc_info=True)
random_line_split
syslog.py
import SocketServer from abc import ABCMeta, abstractmethod import json import requests import six from .. import LOG as _LOG from ..signal.signal import DEFAULT_ORCHESTRATOR_URL from ..signal.event import LogEvent LOG = _LOG.getChild(__name__) @six.add_metaclass(ABCMeta) class SyslogInspectorBase(object): de...
( self, udp_port=10514, orchestrator_rest_url=DEFAULT_ORCHESTRATOR_URL, entity_id='_earthquake_syslog_inspector'): LOG.info('Syslog UDP port: %d', udp_port) LOG.info('Orchestrator REST URL: %s', orchestrator_rest_url) self.orchestrator_rest_url = orchestrator_rest_url ...
__init__
identifier_name
syslog.py
import SocketServer from abc import ABCMeta, abstractmethod import json import requests import six from .. import LOG as _LOG from ..signal.signal import DEFAULT_ORCHESTRATOR_URL from ..signal.event import LogEvent LOG = _LOG.getChild(__name__) @six.add_metaclass(ABCMeta) class SyslogInspectorBase(object):
class BasicSyslogInspector(SyslogInspectorBase): # @Override def map_syslog_to_event(self, ip, port, data): entity = 'entity-%s:%d' % (ip, port) event = LogEvent.from_message(entity, data) return event if __name__ == "__main__": insp = BasicSyslogInspector() insp.start()
def __init__( self, udp_port=10514, orchestrator_rest_url=DEFAULT_ORCHESTRATOR_URL, entity_id='_earthquake_syslog_inspector'): LOG.info('Syslog UDP port: %d', udp_port) LOG.info('Orchestrator REST URL: %s', orchestrator_rest_url) self.orchestrator_rest_url = orchestrator...
identifier_body
Read.js
//Capturar possibles errors process.on('uncaughtException', function(err) { console.log(err); }); //Importar mòdul net var net = require('net') //Port d'escolta del servidor var port = 8002; //Crear servidor TCP net.createServer(function(socket){ socket.on('data', function(data){ //Parse dades JSON var jso...
}); //Configuració del port en el servidor TCP }).listen(port);
client.thingRead(json.key, {limit: 100,endDate: endDate, startDate: json.startDate}, function (error, data) { if (typeof data!=='undefined' && data!==null){ if (data.length > 0) { var dataSend="" var coma="," for (var i=0;i<=(data.length - 1);i++){ dataSend=dataSend+data[i].value+coma...
identifier_body
Read.js
//Capturar possibles errors process.on('uncaughtException', function(err) { console.log(err); }); //Importar mòdul net var net = require('net') //Port d'escolta del servidor var port = 8002; //Crear servidor TCP net.createServer(function(socket){ socket.on('data', function(data){ //Parse dades JSON var jso...
}else{ socket.write("</FINAL>"); } } }) } }); //Configuració del port en el servidor TCP }).listen(port);
} socket.write(dataSend); read(data[data.length - 1].datetime.split('.')[0].replace(/-/g, '').replace(/:/g, '').replace('T', ''))
random_line_split
Read.js
//Capturar possibles errors process.on('uncaughtException', function(err) { console.log(err); }); //Importar mòdul net var net = require('net') //Port d'escolta del servidor var port = 8002; //Crear servidor TCP net.createServer(function(socket){ socket.on('data', function(data){ //Parse dades JSON var jso...
}) } }); //Configuració del port en el servidor TCP }).listen(port);
if (data.length > 0) { var dataSend="" var coma="," for (var i=0;i<=(data.length - 1);i++){ dataSend=dataSend+data[i].value+coma+data[i].datetime.split('T')[1]+coma } socket.write(dataSend); read(data[data.length - 1].datetime.split('.')[0].replace(/-/g, '').replac...
conditional_block
Read.js
//Capturar possibles errors process.on('uncaughtException', function(err) { console.log(err); }); //Importar mòdul net var net = require('net') //Port d'escolta del servidor var port = 8002; //Crear servidor TCP net.createServer(function(socket){ socket.on('data', function(data){ //Parse dades JSON var jso...
dDate){ client.thingRead(json.key, {limit: 100,endDate: endDate, startDate: json.startDate}, function (error, data) { if (typeof data!=='undefined' && data!==null){ if (data.length > 0) { var dataSend="" var coma="," for (var i=0;i<=(data.length - 1);i++){ dataSend=dataSend+data[i].v...
d(en
identifier_name
tab-group-harness-example.spec.ts
import {TestBed, ComponentFixture} from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting, } from '@angular/platform-browser-dynamic/testing'; import {MatTabsModule} from '@angular/material/tabs'; import {TabGroupHarnessExample} from './tab-group-harness-example'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'...
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {MatTabGroupHarness} from '@angular/material/tabs/testing'; import {HarnessLoader} from '@angular/cdk/testing';
random_line_split
flow_management.py
# -*- coding: utf-8 -*- from flask import render_template, redirect, url_for, flash, abort from purchasing.decorators import requires_roles from purchasing.data.stages import Stage from purchasing.data.flows import Flow from purchasing.conductor.forms import FlowForm, NewFlowForm from purchasing.conductor.manager im...
return render_template('conductor/flows/browse.html', active=active, archived=archived) @blueprint.route('/flow/<int:flow_id>', methods=['GET', 'POST']) @requires_roles('conductor', 'admin', 'superadmin') def flow_detail(flow_id): '''View/edit a flow's details :status 200: Render the flow edit template ...
active.append(flow)
conditional_block
flow_management.py
# -*- coding: utf-8 -*- from flask import render_template, redirect, url_for, flash, abort from purchasing.decorators import requires_roles from purchasing.data.stages import Stage from purchasing.data.flows import Flow from purchasing.conductor.forms import FlowForm, NewFlowForm from purchasing.conductor.manager im...
(): '''Create a new flow :status 200: Render the new flow template :status 302: Try to create a new flow using the :py:class:`~purchasing.conductor.forms.NewFlowForm`, redirect to the flows list view if successful ''' stages = Stage.choices_factory() form = NewFlowForm(stages=st...
new_flow
identifier_name
flow_management.py
# -*- coding: utf-8 -*- from flask import render_template, redirect, url_for, flash, abort from purchasing.decorators import requires_roles from purchasing.data.stages import Stage from purchasing.data.flows import Flow from purchasing.conductor.forms import FlowForm, NewFlowForm from purchasing.conductor.manager im...
abort(404)
random_line_split
flow_management.py
# -*- coding: utf-8 -*- from flask import render_template, redirect, url_for, flash, abort from purchasing.decorators import requires_roles from purchasing.data.stages import Stage from purchasing.data.flows import Flow from purchasing.conductor.forms import FlowForm, NewFlowForm from purchasing.conductor.manager im...
@blueprint.route('/flow/<int:flow_id>', methods=['GET', 'POST']) @requires_roles('conductor', 'admin', 'superadmin') def flow_detail(flow_id): '''View/edit a flow's details :status 200: Render the flow edit template :status 302: Post changes to the a flow using the submitted :py:class:`~purchasi...
'''List all flows :status 200: Render the all flows list template ''' flows = Flow.query.order_by(Flow.flow_name).all() active, archived = [], [] for flow in flows: if flow.is_archived: archived.append(flow) else: active.append(flow) return render_templat...
identifier_body
IosCrop.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("val...
var IosCrop = function (_React$Component) { _inherits(IosCrop, _React$Component); function IosCrop() { _classCallCheck(this, IosCrop); return _possibleConstructorReturn(this, Object.getPrototypeOf(IosCrop).apply(this, arguments)); } _createClass(IosCrop, [{ key: 'render', value: function render() { ...
{ if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable...
identifier_body
IosCrop.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("val...
_createClass(IosCrop, [{ key: 'render', value: function render() { if (this.props.bare) { return _react2.default.createElement( 'g', null, _react2.default.createElement( 'g', null, _react2.default.createElement('rect', { x: '128', y: '64', width: '16', height: '48' }), ...
function IosCrop() { _classCallCheck(this, IosCrop); return _possibleConstructorReturn(this, Object.getPrototypeOf(IosCrop).apply(this, arguments)); }
random_line_split
IosCrop.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("val...
(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw n...
_possibleConstructorReturn
identifier_name
IosCrop.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("val...
return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype =...
{ throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); }
conditional_block
rust-indexer.rs
#[macro_use] extern crate clap; extern crate env_logger; #[macro_use] extern crate log; extern crate rls_analysis; extern crate rls_data as data; extern crate tools; use crate::data::GlobalCrateId; use crate::data::{DefKind, ImplKind}; use rls_analysis::{AnalysisHost, AnalysisLoader, SearchDirectory}; use std::collect...
fn pretty_for_def(def: &data::Def, qualname: &str) -> String { let mut pretty = def_kind_to_human(def.kind).to_owned(); pretty.push_str(" "); // We use the unsanitized qualname here because it's more human-readable // and the source-analysis pretty name is allowed to have commas and such pretty.pu...
{ let mut pretty = impl_kind_to_human(&imp.kind).to_owned(); pretty.push_str(" "); pretty.push_str(qualname); pretty }
identifier_body
rust-indexer.rs
#[macro_use] extern crate clap; extern crate env_logger; #[macro_use] extern crate log; extern crate rls_analysis; extern crate rls_data as data; extern crate tools; use crate::data::GlobalCrateId; use crate::data::{DefKind, ImplKind}; use rls_analysis::{AnalysisHost, AnalysisLoader, SearchDirectory}; use std::collect...
(&self) -> Vec<SearchDirectory> { self.deps_dirs .iter() .map(|pb| SearchDirectory { path: pb.clone(), prefix_rewrite: None, }) .collect() } } fn def_kind_to_human(kind: DefKind) -> &'static str { match kind { DefKi...
search_directories
identifier_name
rust-indexer.rs
#[macro_use] extern crate clap; extern crate env_logger; #[macro_use] extern crate log; extern crate rls_analysis; extern crate rls_data as data; extern crate tools; use crate::data::GlobalCrateId; use crate::data::{DefKind, ImplKind}; use rls_analysis::{AnalysisHost, AnalysisLoader, SearchDirectory}; use std::collect...
if !local_source_path.exists() { warn!( "Skipping nonexistent source file with searchfox path '{}' which mapped to local path '{}'", searchfox_path.display(), local_source_path.display() ); return; }; // Attempt to open the source file to extract...
random_line_split
question-player-state.service.spec.ts
// Copyright 2021 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...
it('should access on question session completed', () => { expect(qpss.onQuestionSessionCompleted).toBeDefined(); }); });
it('should get question player state data', () => { expect(qpss.getQuestionPlayerStateData()).toBeDefined(); });
random_line_split
puertas.py
#!/bin/python3.5 # Programa obtenido de hacker run, se le pasa lista con 0 y 1, que simbolizan puertas, 0 la puerta abierta 1 la puerta cerrada. # Nuestro objetivo es abrir todas las puertas # si se abre y las subyacentes se abrirán si no están abiertas # el programa devuelve para una lista de 0 y 1 le mínimo de puert...
eturn [ min , max] def prueba ( ): for i in range (10): print (i ) i += i if __name__ == "__main__": doors = list ( map( int, input().strip().split(' '))) print ("La puerta creada: " , doors) result = puertas (doors) print( " ".join( map(str , result ))) prueba();
rs[ i-1 : i+2] == [1,1,1]: min += 1 max += 2 i += 2 elif doors[ i] == 1: min += 1 max += 1 i += 1 else: min += 1 max += 1 i += 1 r
conditional_block
puertas.py
#!/bin/python3.5 # Programa obtenido de hacker run, se le pasa lista con 0 y 1, que simbolizan puertas, 0 la puerta abierta 1 la puerta cerrada. # Nuestro objetivo es abrir todas las puertas # si se abre y las subyacentes se abrirán si no están abiertas # el programa devuelve para una lista de 0 y 1 le mínimo de puert...
if __name__ == "__main__": doors = list ( map( int, input().strip().split(' '))) print ("La puerta creada: " , doors) result = puertas (doors) print( " ".join( map(str , result ))) prueba();
in range (10): print (i ) i += i
identifier_body
puertas.py
#!/bin/python3.5 # Programa obtenido de hacker run, se le pasa lista con 0 y 1, que simbolizan puertas, 0 la puerta abierta 1 la puerta cerrada. # Nuestro objetivo es abrir todas las puertas # si se abre y las subyacentes se abrirán si no están abiertas
import sys def puertas( doors ): min = 0 max = 0 i = 1 while i < len( doors) -2 : # Casos en los que hay reducción if(doors[i]) == 1: if doors[ i-1 : i+2] == [1,1,1]: min += 1 max += 2 i += 2 elif do...
# el programa devuelve para una lista de 0 y 1 le mínimo de puertas a abrir y el máximo siguiendo este patrón
random_line_split
puertas.py
#!/bin/python3.5 # Programa obtenido de hacker run, se le pasa lista con 0 y 1, que simbolizan puertas, 0 la puerta abierta 1 la puerta cerrada. # Nuestro objetivo es abrir todas las puertas # si se abre y las subyacentes se abrirán si no están abiertas # el programa devuelve para una lista de 0 y 1 le mínimo de puert...
for i in range (10): print (i ) i += i if __name__ == "__main__": doors = list ( map( int, input().strip().split(' '))) print ("La puerta creada: " , doors) result = puertas (doors) print( " ".join( map(str , result ))) prueba();
( ):
identifier_name
traits.rs
use approx::AbsDiffEq; use num::{Bounded, FromPrimitive, Signed}; use na::allocator::Allocator; use na::{DimMin, DimName, Scalar, U1}; use simba::scalar::{ClosedAdd, ClosedMul, ClosedSub}; use std::cmp::PartialOrd; /// A type-level number representing a vector, matrix row, or matrix column, dimension. pub trait Dimen...
+ AbsDiffEq<Epsilon = Self> + Signed + FromPrimitive + Bounded, > Number for T { } #[doc(hidden)] pub trait Alloc<N: Scalar, R: Dimension, C: Dimension = U1>: Allocator<N, R> + Allocator<N, C> + Allocator<N, U1, R> + Allocator<N, U1, C> + Allocato...
+ ClosedSub + ClosedMul
random_line_split
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn build (matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need passw...
} } if matches.opt_present("b") { let conn = Connection::connect("postgres://stratis:stratis@localhost", TlsMode::None).expect("cannot connect to sql"); let build = vec![&include_bytes!("../../sql/create_players.sql")[..], ...
{ println!("build:{:?}\nfor:{:?}\n\n",e,s); }
conditional_block
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn
(matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localho...
build
identifier_name
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn build (matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need passw...
{ let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localhost")); let conn = Connection::connect(s, ...
identifier_body
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn build (matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need passw...
let conn = Connection::connect("postgres://stratis:stratis@localhost", TlsMode::None).expect("cannot connect to sql"); let build = vec![&include_bytes!("../../sql/create_players.sql")[..], &include_bytes!("../../sql/create_msg.sql")[..], ...
} } if matches.opt_present("b") {
random_line_split
strategy_utils.py
# coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
(tpu, use_gpu): """Utility to create a `tf.DistributionStrategy` for TPU or GPU. If neither is being used a DefaultStrategy is returned which allows executing on CPU only. Args: tpu: BNS address of TPU to use. Note the flag and param are called TPU as that is what the xmanager utilities call. us...
get_strategy
identifier_name
strategy_utils.py
# coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
logging.info('Devices after getting strategy:\n%s', tf.config.list_logical_devices()) else: strategy = tf.distribute.get_strategy() return strategy
strategy = tf.distribute.MirroredStrategy()
conditional_block
strategy_utils.py
# coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
"""Utility to create a `tf.DistributionStrategy` for TPU or GPU. If neither is being used a DefaultStrategy is returned which allows executing on CPU only. Args: tpu: BNS address of TPU to use. Note the flag and param are called TPU as that is what the xmanager utilities call. use_gpu: Whether a G...
identifier_body
strategy_utils.py
# coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
strategy = tf.distribute.get_strategy() return strategy
random_line_split
ef2.py
#!/usr/bin/env python import itertools from operator import attrgetter, itemgetter class ClusterRecommendation(object): __slots__ = ("cluster_id", "papers") def __init__(self, cluster_id, papers): self.cluster_id = cluster_id self.papers = [(p.pid, p.score) for p in papers] def __str__(s...
(self): return "<ClusterRecommendation %s>" % self.cluster_id def get_papers(self): """Only return a tuple of papers""" return tuple(zip(*self.papers))[0] def get_parent(cluster_id): parent = ":".join(cluster_id.split(":")[:-1]) if parent == "": return None return paren...
__repr__
identifier_name
ef2.py
#!/usr/bin/env python import itertools from operator import attrgetter, itemgetter class ClusterRecommendation(object): __slots__ = ("cluster_id", "papers") def __init__(self, cluster_id, papers): self.cluster_id = cluster_id self.papers = [(p.pid, p.score) for p in papers] def __str__(s...
papers = sorted(papers, key=attrgetter('score'), reverse=True) yield ClusterRecommendation(cluster_id, papers[:rec_limit]) def parse_tree(stream, rec_limit=10): mstream = make_leaf_rec(stream, rec_limit) child_stream = itertools.groupby(mstream, lambda e: get_parent(e.cluster_id)) for (pare...
def make_leaf_rec(stream, rec_limit=10): leaf_stream = itertools.groupby(stream, lambda e: e.local) for (cluster_id, stream) in leaf_stream: papers = [e for e in stream]
random_line_split
ef2.py
#!/usr/bin/env python import itertools from operator import attrgetter, itemgetter class ClusterRecommendation(object): __slots__ = ("cluster_id", "papers") def __init__(self, cluster_id, papers): self.cluster_id = cluster_id self.papers = [(p.pid, p.score) for p in papers] def __str__(s...
def parse_tree(stream, rec_limit=10): mstream = make_leaf_rec(stream, rec_limit) child_stream = itertools.groupby(mstream, lambda e: get_parent(e.cluster_id)) for (parent_cluster_id, recs) in child_stream: child_recs = [r for r in recs] papers = itertools.chain.from_iterable(map(attrgetter...
papers = [e for e in stream] papers = sorted(papers, key=attrgetter('score'), reverse=True) yield ClusterRecommendation(cluster_id, papers[:rec_limit])
conditional_block
ef2.py
#!/usr/bin/env python import itertools from operator import attrgetter, itemgetter class ClusterRecommendation(object): __slots__ = ("cluster_id", "papers") def __init__(self, cluster_id, papers):
def __str__(self): return "%s %s" % (self.cluster_id, len(self.papers)) def __repr__(self): return "<ClusterRecommendation %s>" % self.cluster_id def get_papers(self): """Only return a tuple of papers""" return tuple(zip(*self.papers))[0] def get_parent(cluster_id): ...
self.cluster_id = cluster_id self.papers = [(p.pid, p.score) for p in papers]
identifier_body
git.py
from .utils import do, do_ex, trace from .version import meta from os.path import abspath, realpath FILES_COMMAND = 'git ls-files' DEFAULT_DESCRIBE = 'git describe --dirty --tags --long --match *.*' def
(root, describe_command=DEFAULT_DESCRIBE): real_root, _, ret = do_ex('git rev-parse --show-toplevel', root) if ret: return trace('real root', real_root) if abspath(realpath(real_root)) != abspath(realpath(root)): return rev_node, _, ret = do_ex('git rev-parse --verify --quiet HEAD', ...
parse
identifier_name
git.py
from .utils import do, do_ex, trace from .version import meta from os.path import abspath, realpath
FILES_COMMAND = 'git ls-files' DEFAULT_DESCRIBE = 'git describe --dirty --tags --long --match *.*' def parse(root, describe_command=DEFAULT_DESCRIBE): real_root, _, ret = do_ex('git rev-parse --show-toplevel', root) if ret: return trace('real root', real_root) if abspath(realpath(real_root)) !...
random_line_split
git.py
from .utils import do, do_ex, trace from .version import meta from os.path import abspath, realpath FILES_COMMAND = 'git ls-files' DEFAULT_DESCRIBE = 'git describe --dirty --tags --long --match *.*' def parse(root, describe_command=DEFAULT_DESCRIBE): real_root, _, ret = do_ex('git rev-parse --show-toplevel', ro...
rev_node, _, ret = do_ex('git rev-parse --verify --quiet HEAD', root) if ret: return meta('0.0') rev_node = rev_node[:7] out, err, ret = do_ex(describe_command, root) if '-' not in out and '.' not in out: revs = do('git rev-list HEAD', root) count = revs.count('\n') ...
return
conditional_block
git.py
from .utils import do, do_ex, trace from .version import meta from os.path import abspath, realpath FILES_COMMAND = 'git ls-files' DEFAULT_DESCRIBE = 'git describe --dirty --tags --long --match *.*' def parse(root, describe_command=DEFAULT_DESCRIBE):
real_root, _, ret = do_ex('git rev-parse --show-toplevel', root) if ret: return trace('real root', real_root) if abspath(realpath(real_root)) != abspath(realpath(root)): return rev_node, _, ret = do_ex('git rev-parse --verify --quiet HEAD', root) if ret: return meta('0.0') ...
identifier_body
class.spec.ts
/** * @license * Copyright Renobi. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://opensource.org/licenses/MIT */ import { expect } from 'chai'; import { Any, MockType1 } from '../test/any'; import { getClass, getClassOrSymbo...
describe('Get Constructor', () => { it('should return constructor if type', () => { expect(getContructor(MockType1)).to.equal(MockType1); }); it('should return self if function', () => { expect(getContructor(new MockType1())).to.equal(MockType1); }); }); ...
expect(getClassName(Symbol('test:MockType1'))).to.equal('Symbol(test:MockType1)'); }); });
random_line_split
confirmationController.js
'use strict'; /* main App */ var app = angular.module('submitConformationcontroller', []); app.controller('confirmationCtrl', ['$scope', function($scope){ $scope.volunteerList = ["Joop Bakker", "Dirk Dijkstra", "Sterre Hendriks", "Hendrik Jacobs", "Hans Heuvel", "Jaap Beek", "Jan-Jaap Dijk", "Marleen Jansen", "...
(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } $scope.jobTitle = getParameterByName('jobTitle')...
getParameterByName
identifier_name
confirmationController.js
'use strict'; /* main App */ var app = angular.module('submitConformationcontroller', []); app.controller('confirmationCtrl', ['$scope', function($scope){ $scope.volunteerList = ["Joop Bakker", "Dirk Dijkstra", "Sterre Hendriks", "Hendrik Jacobs", "Hans Heuvel", "Jaap Beek", "Jan-Jaap Dijk", "Marleen Jansen", "...
$scope.jobTitle = getParameterByName('jobTitle'); $scope.jobType = getParameterByName('jobType'); $scope.describeWork = getParameterByName('describeWork'); }]);
{ name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); }
identifier_body
confirmationController.js
'use strict'; /* main App */ var app = angular.module('submitConformationcontroller', []); app.controller('confirmationCtrl', ['$scope', function($scope){ $scope.volunteerList = ["Joop Bakker", "Dirk Dijkstra", "Sterre Hendriks", "Hendrik Jacobs", "Hans Heuvel", "Jaap Beek", "Jan-Jaap Dijk", "Marleen Jansen", "...
$scope.jobTitle = ''; $scope.jobType = ''; $scope.describeWork = ''; function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : dec...
random_line_split
cstore.rs
// Copyright 2012 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 ...
cstore.used_libraries.push(lib); true } pub fn get_used_libraries<'a>(cstore: &'a CStore) -> &'a [@str] { let slice: &'a [@str] = cstore.used_libraries; slice } pub fn add_used_link_args(cstore: &mut CStore, args: &str) { for args.split_iter(' ').advance |s| { cstore.used_link_args.push(s...
{ return false; }
conditional_block
cstore.rs
// Copyright 2012 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 ...
// returns hashes of crates directly used by this crate. Hashes are sorted by // (crate name, crate version, crate hash) in lexicographic order (not semver) pub fn get_dep_hashes(cstore: &CStore) -> ~[@str] { struct crate_hash { name: @str, vers: @str, hash: @str } let mut result = ~[]; for cstore.extern...
{ cstore.extern_mod_crate_map.find(&emod_id).map_consume(|x| *x) }
identifier_body
cstore.rs
// Copyright 2012 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 ...
// The crate store - a central repo for information collected about external // crates and libraries use metadata::cstore; use metadata::decoder; use std::hashmap::HashMap; use extra; use syntax::ast; use syntax::parse::token::ident_interner; // A map from external crate numbers (as decoded from some crate file) to...
// except according to those terms.
random_line_split
cstore.rs
// Copyright 2012 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 ...
(cstore: &CStore, cnum: ast::crate_num) -> @str { let cdata = get_crate_data(cstore, cnum); decoder::get_crate_vers(cdata.data) } pub fn set_crate_data(cstore: &mut CStore, cnum: ast::crate_num, data: @crate_metadata) { cstore.metas.insert(cnum, data); } pub fn ...
get_crate_vers
identifier_name
test_program_code.py
# Copyright (c) 2018 PaddlePaddle 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 app...
if __name__ == "__main__": unittest.main()
def test_print(self): place = fluid.CPUPlace() self.init_serv(place) self.init_client(place, 9123) def init_serv(self, place): main = fluid.Program() with fluid.program_guard(main): serv = ListenAndServ("127.0.0.1:0", ["X"], optimizer_mode=False) wit...
identifier_body
test_program_code.py
# Copyright (c) 2018 PaddlePaddle 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 app...
(self, place): main = fluid.Program() with fluid.program_guard(main): serv = ListenAndServ("127.0.0.1:0", ["X"], optimizer_mode=False) with serv.do(): out_var = main.global_block().create_var( name="scale_0.tmp_0", psersist...
init_serv
identifier_name
test_program_code.py
# Copyright (c) 2018 PaddlePaddle 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 app...
with fluid.program_guard(main): serv = ListenAndServ("127.0.0.1:0", ["X"], optimizer_mode=False) with serv.do(): out_var = main.global_block().create_var( name="scale_0.tmp_0", psersistable=True, dtype="float32",...
random_line_split
test_program_code.py
# Copyright (c) 2018 PaddlePaddle 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 app...
unittest.main()
conditional_block
ShouldDecorateChildren.js
import React from 'react'; import ReactTouchPosition from '../../../dist/ReactTouchPosition'; import TouchPositionLabel from './TouchPositionLabel'; import OnPositionChangedLabel from './OnPositionChangedLabel'; import InstructionsLabel from './InstructionsLabel'; export default class extends React.Component { c...
}
random_line_split
ShouldDecorateChildren.js
import React from 'react'; import ReactTouchPosition from '../../../dist/ReactTouchPosition'; import TouchPositionLabel from './TouchPositionLabel'; import OnPositionChangedLabel from './OnPositionChangedLabel'; import InstructionsLabel from './InstructionsLabel'; export default class extends React.Component { c...
}
{ return ( <div className="example-container"> <ReactTouchPosition {...{ className: 'example', onPositionChanged: ({ isPositionOutside, touchPosition }) => { this.setState({ isPositionOutside...
identifier_body
ShouldDecorateChildren.js
import React from 'react'; import ReactTouchPosition from '../../../dist/ReactTouchPosition'; import TouchPositionLabel from './TouchPositionLabel'; import OnPositionChangedLabel from './OnPositionChangedLabel'; import InstructionsLabel from './InstructionsLabel'; export default class extends React.Component {
(props) { super(props); this.state = { isPositionOutside: true, touchPosition: { x: 0, y: 0, } } } render() { return ( <div className="example-container"> <ReactTouchPosition {...{ ...
constructor
identifier_name
connect-vue.ts
import { join, relative } from 'path'; import { red } from 'colors/safe'; import { FileSystem } from '../../file-system'; export function connectVue(path: string) { const fs = new FileSystem(); if (!fs.exists(path)) { if (process.env.P1Z7kEbSUUPMxF8GqPwD8Gx_FOAL_CLI_TEST !== 'true') { console.log(red(`...
}); }
pkg.vue.outputDir = outputPath; return JSON.stringify(pkg, null, 2);
random_line_split
connect-vue.ts
import { join, relative } from 'path'; import { red } from 'colors/safe'; import { FileSystem } from '../../file-system'; export function connectVue(path: string) { const fs = new FileSystem(); if (!fs.exists(path)) { if (process.env.P1Z7kEbSUUPMxF8GqPwD8Gx_FOAL_CLI_TEST !== 'true')
return; } if (!fs.exists(join(path, 'package.json'))) { if (process.env.P1Z7kEbSUUPMxF8GqPwD8Gx_FOAL_CLI_TEST !== 'true') { console.log(red(` The directory ${path} is not a Vue project (missing package.json).`)); } return; } fs .cd(path) .modify('package.json', content => { ...
{ console.log(red(` The directory ${path} does not exist.`)); }
conditional_block
connect-vue.ts
import { join, relative } from 'path'; import { red } from 'colors/safe'; import { FileSystem } from '../../file-system'; export function connectVue(path: string)
{ const fs = new FileSystem(); if (!fs.exists(path)) { if (process.env.P1Z7kEbSUUPMxF8GqPwD8Gx_FOAL_CLI_TEST !== 'true') { console.log(red(` The directory ${path} does not exist.`)); } return; } if (!fs.exists(join(path, 'package.json'))) { if (process.env.P1Z7kEbSUUPMxF8GqPwD8Gx_FOAL_C...
identifier_body
connect-vue.ts
import { join, relative } from 'path'; import { red } from 'colors/safe'; import { FileSystem } from '../../file-system'; export function
(path: string) { const fs = new FileSystem(); if (!fs.exists(path)) { if (process.env.P1Z7kEbSUUPMxF8GqPwD8Gx_FOAL_CLI_TEST !== 'true') { console.log(red(` The directory ${path} does not exist.`)); } return; } if (!fs.exists(join(path, 'package.json'))) { if (process.env.P1Z7kEbSUUPMxF8...
connectVue
identifier_name
stats_bootstrap.py
import random from math import sqrt import numpy def validate_cost(result, boot_size, delta=500): budget = result["budget"] for metric_name, _, data_process in result['analysis']: if metric_name == "cost": cost_data = list(x() for x in data_process) data_analysis = yield_analys...
return sum(xs) * 1.0 / len(xs) def sample_wr(population, k): """Chooses k random elements (with replacement) from a population""" n = len(population) - 1 return [population[int(random.randint(0, n))] for i in range(k)] def bootstrap(population, f, n, k, alpha): btstrp = sorted(f(sample_wr(popula...
return -float("inf")
conditional_block
stats_bootstrap.py
import random from math import sqrt import numpy def validate_cost(result, boot_size, delta=500): budget = result["budget"] for metric_name, _, data_process in result['analysis']: if metric_name == "cost": cost_data = list(x() for x in data_process) data_analysis = yield_analys...
def bootstrap(population, f, n, k, alpha): btstrp = sorted(f(sample_wr(population, k)) for i in range(n)) return { "confidence": 100.0 * (1 - 2 * alpha), "from": btstrp[int(1.0 * n * alpha)], "to": btstrp[int(1.0 * n * (1 - alpha))], "metrics": f(population) } def yield_a...
"""Chooses k random elements (with replacement) from a population""" n = len(population) - 1 return [population[int(random.randint(0, n))] for i in range(k)]
identifier_body
stats_bootstrap.py
import random from math import sqrt import numpy def validate_cost(result, boot_size, delta=500): budget = result["budget"] for metric_name, _, data_process in result['analysis']: if metric_name == "cost": cost_data = list(x() for x in data_process) data_analysis = yield_analys...
if len(xs) == 0: return -float("inf") return sum(xs) * 1.0 / len(xs) def sample_wr(population, k): """Chooses k random elements (with replacement) from a population""" n = len(population) - 1 return [population[int(random.randint(0, n))] for i in range(k)] def bootstrap(population, f, n, ...
return result prev_budget = budget return None def average(xs):
random_line_split
stats_bootstrap.py
import random from math import sqrt import numpy def
(result, boot_size, delta=500): budget = result["budget"] for metric_name, _, data_process in result['analysis']: if metric_name == "cost": cost_data = list(x() for x in data_process) data_analysis = yield_analysis(cost_data, boot_size) cost_val = data_analysis["btstr...
validate_cost
identifier_name
util.py
# # GdbLib - A Gdb python library. # Copyright (C) 2012 Fernando Castillo # # This program 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 3 of the License, or # (at your option) any la...
index = path.rfind(os.sep) return path[:index]
identifier_body
util.py
# # GdbLib - A Gdb python library. # Copyright (C) 2012 Fernando Castillo # # This program 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 3 of the License, or # (at your option) any la...
def removeFile(path): index = path.rfind(os.sep) return path[:index]
random_line_split
util.py
# # GdbLib - A Gdb python library. # Copyright (C) 2012 Fernando Castillo # # This program 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 3 of the License, or # (at your option) any la...
(values): pass def removeFile(path): index = path.rfind(os.sep) return path[:index]
change
identifier_name
utils.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt, cstr, cint from frappe import _ import json from erpnext.stock.doctype.item.item import get_last_purchase_d...
(doc): items = [] for d in doc.get("items"): if not d.qty: if doc.doctype == "Purchase Receipt" and d.rejected_qty: continue frappe.throw(_("Please enter quantity for Item {0}").format(d.item_code)) # update with latest quantities bin = frappe.db.sql("""select projected_qty from `tabBin` where ite...
validate_for_items
identifier_name
utils.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt, cstr, cint from frappe import _ import json from erpnext.stock.doctype.item.item import get_last_purchase_d...
(flt(last_purchase_rate), d.item_code)) def validate_for_items(doc): items = [] for d in doc.get("items"): if not d.qty: if doc.doctype == "Purchase Receipt" and d.rejected_qty: continue frappe.throw(_("Please enter quantity for Item {0}").format(d.item_code)) # update with latest quantities bin...
# update last purchsae rate if last_purchase_rate: frappe.db.sql("""update `tabItem` set last_purchase_rate = %s where name = %s""",
random_line_split
utils.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt, cstr, cint from frappe import _ import json from erpnext.stock.doctype.item.item import get_last_purchase_d...
# update with latest quantities bin = frappe.db.sql("""select projected_qty from `tabBin` where item_code = %s and warehouse = %s""", (d.item_code, d.warehouse), as_dict=1) f_lst ={'projected_qty': bin and flt(bin[0]['projected_qty']) or 0, 'ordered_qty': 0, 'received_qty' : 0} if d.doctype in ('Purchase ...
if doc.doctype == "Purchase Receipt" and d.rejected_qty: continue frappe.throw(_("Please enter quantity for Item {0}").format(d.item_code))
conditional_block
utils.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt, cstr, cint from frappe import _ import json from erpnext.stock.doctype.item.item import get_last_purchase_d...
def validate_for_items(doc): items = [] for d in doc.get("items"): if not d.qty: if doc.doctype == "Purchase Receipt" and d.rejected_qty: continue frappe.throw(_("Please enter quantity for Item {0}").format(d.item_code)) # update with latest quantities bin = frappe.db.sql("""select projected_qty fr...
"""updates last_purchase_rate in item table for each item""" import frappe.utils this_purchase_date = frappe.utils.getdate(doc.get('posting_date') or doc.get('transaction_date')) for d in doc.get("items"): # get last purchase details last_purchase_details = get_last_purchase_details(d.item_code, doc.name) #...
identifier_body
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn...
use crate::test::*; #[test] fn retrieve_limits() { wrapper(|env| { let db = env.db(); let krate = "hexponent"; // limits work if no crate has limits set let hexponent = Limits::for_crate(&db.conn(), krate)?; assert_eq!(hexponent, Limits::...
mod test { use super::*;
random_line_split
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn...
pub(crate) fn max_log_size(&self) -> usize { self.max_log_size } pub(crate) fn targets(&self) -> usize { self.targets } pub(crate) fn for_website(&self) -> BTreeMap<String, String> { let mut res = BTreeMap::new(); res.insert("Available RAM".into(), SIZE_SCALE(self...
{ self.networking }
identifier_body
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn...
res.insert( "Maximum number of build targets".into(), self.targets.to_string(), ); res } } const TIME_SCALE: fn(usize) -> String = |v| scale(v, 60, &["seconds", "minutes", "hours"]); const SIZE_SCALE: fn(usize) -> String = |v| scale(v, 1024, &["bytes", "KB", "MB", "...
{ res.insert("Network access".into(), "blocked".into()); }
conditional_block
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn...
(conn: &Connection, name: &str) -> Result<Self> { let mut limits = Self::default(); let res = conn.query( "SELECT * FROM sandbox_overrides WHERE crate_name = $1;", &[&name], )?; if !res.is_empty() { let row = res.get(0); if let Some(memory...
for_crate
identifier_name
sqlite_utilities.py
#!/usr/bin/env python3 # This script connects to and performs queries on an SQLite database using Python. # Jen Thomas, Oct 2016. ######################################################### import sqlite3 import shutil def connect_to_sqlite_db(sqlite_file): """ Connect to an SQLite database. Return a connection...
if __name__ == '__main__': main()
sqlite_file = '/home/jen/projects/smelly_london/git/smelly_london/database' column_names = ['category', 'location', 'number_of_smells', 'centroid_lat', 'centroid_lon', 'id', 'year', 'sentence'] sql = 'select {column_names} from (select Category category, Borough location, Id id, Year year, Sentence sentence, co...
identifier_body
sqlite_utilities.py
#!/usr/bin/env python3 # This script connects to and performs queries on an SQLite database using Python. # Jen Thomas, Oct 2016. ######################################################### import sqlite3 import shutil
conn = sqlite3.connect(sqlite_file) cur = conn.cursor() return conn, cur except: print() return None def close_sqlite_connection(conn): """ Close the connection to an SQLite database.""" conn.close() def sql_get_data_colnames(cur, sql, column_names): """Perform an...
def connect_to_sqlite_db(sqlite_file): """ Connect to an SQLite database. Return a connection.""" try:
random_line_split
sqlite_utilities.py
#!/usr/bin/env python3 # This script connects to and performs queries on an SQLite database using Python. # Jen Thomas, Oct 2016. ######################################################### import sqlite3 import shutil def connect_to_sqlite_db(sqlite_file): """ Connect to an SQLite database. Return a connection...
(): sqlite_file = '/home/jen/projects/smelly_london/git/smelly_london/database' column_names = ['category', 'location', 'number_of_smells', 'centroid_lat', 'centroid_lon', 'id', 'year', 'sentence'] sql = 'select {column_names} from (select Category category, Borough location, Id id, Year year, Sentence sen...
main
identifier_name
sqlite_utilities.py
#!/usr/bin/env python3 # This script connects to and performs queries on an SQLite database using Python. # Jen Thomas, Oct 2016. ######################################################### import sqlite3 import shutil def connect_to_sqlite_db(sqlite_file): """ Connect to an SQLite database. Return a connection...
main()
conditional_block
BorjesProtoLattice.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("...
(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw n...
_possibleConstructorReturn
identifier_name
BorjesProtoLattice.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("...
delete x[el]; this.props.update(x); } }, { key: 'cpEl', value: function cpEl(el) { this.props.opts.cpbuffer.v = { borjes: 'latticeel', l: this.props.name || this.props.opts.name, e: el }; ...
random_line_split
BorjesProtoLattice.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props)
return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _borjes = require('b...
{ for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
identifier_body
costMemory.py
# -*- coding: utf-8 -*- """ @file costMemory.py @author Jakob Erdmann @author Michael Behrisch @date 2012-03-14 @version $Id: costMemory.py 22608 2017-01-17 06:28:54Z behrisch $ Perform smoothing of edge costs across successive iterations of duaIterate SUMO, Simulation of Urban MObility; see http://sumo.dlr.d...
(handler.ContentHandler): # memorize the weighted average of edge costs def __init__(self, cost_attribute, pessimism=0, network_file=None): # the cost attribute to parse (i.e. 'traveltime') self.cost_attribute = cost_attribute.encode('utf8') # the duaIterate iteration index self...
CostMemory
identifier_name
costMemory.py
# -*- coding: utf-8 -*- """ @file costMemory.py @author Jakob Erdmann @author Michael Behrisch @date 2012-03-14 @version $Id: costMemory.py 22608 2017-01-17 06:28:54Z behrisch $ Perform smoothing of edge costs across successive iterations of duaIterate SUMO, Simulation of Urban MObility; see http://sumo.dlr.d...
self.pessimism = pessimism def startElement(self, name, attrs): if name == 'interval': self.current_interval = self.intervals[float(attrs['begin'])] if name == 'edge': id = attrs['id'] # may be missing for some if self.cost_attribute.decode('...
self.traveltime_free = dict([(e.getID(), e.getLength() / e.getSpeed()) for e in readNet(network_file).getEdges()])
conditional_block
costMemory.py
# -*- coding: utf-8 -*- """ @file costMemory.py @author Jakob Erdmann @author Michael Behrisch @date 2012-03-14 @version $Id: costMemory.py 22608 2017-01-17 06:28:54Z behrisch $ Perform smoothing of edge costs across successive iterations of duaIterate SUMO, Simulation of Urban MObility; see http://sumo.dlr.d...
def update(self, cost, memory_weight, new_weight, pessimism): p = (cost / self.cost) ** pessimism if self.cost > 0 else 1 memory_factor = memory_weight / (memory_weight + new_weight * p) self.cost = self.cost * memory_factor + cost * (1 - memory_factor) self.seen = True class Cos...
self.cost = cost self.seen = True
identifier_body
costMemory.py
# -*- coding: utf-8 -*- """ @file costMemory.py @author Jakob Erdmann @author Michael Behrisch @date 2012-03-14 @version $Id: costMemory.py 22608 2017-01-17 06:28:54Z behrisch $ Perform smoothing of edge costs across successive iterations of duaIterate SUMO, Simulation of Urban MObility; see http://sumo.dlr.d...
sorted_begin_times = sorted(self.intervals.keys()) self.interval_length = sorted_begin_times[ 1] - sorted_begin_times[0] self.memory_weight += self.new_weight def write_costs(self, weight_file): with open(weight_file, 'w') as f: f.write('<netstats...
if len(self.intervals.keys()) > 1:
random_line_split
modal_button.js
/** * @fileOverview This file initializes the modal button (browser action). * This file initializing the button's state on browser start and * change button's state (badage color and text) when user toggles * injection in popup.html. * * The text message on the button determines the operating mode. * "off" ind...
// Subscribe to option changed events chrome.runtime.onMessage.addListener(function (request) { if (request.ask === 'options/changed') { if (request.option === 'options/isInjectionEnabled') { updateBrowserAction(request.newValue); } } }); // Retrive the initial option value updateBrowserAction(Priv...
{ if (enableInjection) { chrome.browserAction.setBadgeBackgroundColor({color: "#004F00"}); chrome.browserAction.setBadgeText({text: "on"}); } else { chrome.browserAction.setBadgeBackgroundColor({color: "#FF0000"}); chrome.browserAction.setBadgeText({text: "off"}); } }
identifier_body
modal_button.js
/** * @fileOverview This file initializes the modal button (browser action). * This file initializing the button's state on browser start and * change button's state (badage color and text) when user toggles * injection in popup.html. * * The text message on the button determines the operating mode. * "off" ind...
(enableInjection) { if (enableInjection) { chrome.browserAction.setBadgeBackgroundColor({color: "#004F00"}); chrome.browserAction.setBadgeText({text: "on"}); } else { chrome.browserAction.setBadgeBackgroundColor({color: "#FF0000"}); chrome.browserAction.setBadgeText({text: "off"}); } } // Subscri...
updateBrowserAction
identifier_name
modal_button.js
* This file initializing the button's state on browser start and * change button's state (badage color and text) when user toggles * injection in popup.html. * * The text message on the button determines the operating mode. * "off" indicates that the content script can be injected, but it * doesn't execute any ...
/** * @fileOverview This file initializes the modal button (browser action).
random_line_split
modal_button.js
/** * @fileOverview This file initializes the modal button (browser action). * This file initializing the button's state on browser start and * change button's state (badage color and text) when user toggles * injection in popup.html. * * The text message on the button determines the operating mode. * "off" ind...
}); // Retrive the initial option value updateBrowserAction(Privly.options.isInjectionEnabled());
{ if (request.option === 'options/isInjectionEnabled') { updateBrowserAction(request.newValue); } }
conditional_block
Color.ts
const allColors = ["0072C6", "4617B4", "8C0095", "008A17", "D24726", "008299", "AC193D", "DC4FAD", "FF8F32", "82BA00", "03B3B2", "5DB2FF"]; const currentIterationColor = "#C1E6FF"; /*Pattens Blue*/ const otherIterationColors = ["#FFDAC1", "#E6FFC1", "#FFC1E6"]; /*Negroni, Chiffon, Cotton Candy*/ var interationCou...
ame: string): string { if (name === "currentIteration") { return currentIterationColor; } if (name === "otherIteration") { return otherIterationColors[interationCount++ % otherIterationColors.length]; } const id = name.slice().toLowerCase(); let value = 0; for (l...
nerateColor(n
identifier_name