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
Generate_text.py
import time import numpy as np from collections import Counter from collections import defaultdict import matplotlib.pyplot as plt def unzip(pairs): """ Splits list of pairs (tuples) into separate lists Parameter(s) -------------- pairs(list of tuples): List of pairs to be split ...
# Joins and returns the characters in text return "".join(text)
c = generate_letter(lm, history) text.append(c) history = history[1:] + c
conditional_block
Generate_text.py
import time import numpy as np from collections import Counter from collections import defaultdict import matplotlib.pyplot as plt def unzip(pairs): """ Splits list of pairs (tuples) into separate lists Parameter(s) -------------- pairs(list of tuples): List of pairs to be split ...
(lm, history): """ Generates a letter according to the probability distribution of the specified history Parameter(s) -------------- lm (Dict{str: Tuple(str, float)}): The n-gram language model relating history to letter probabilities history (str): Length n-1 context for ...
generate_letter
identifier_name
socketcluster-client-tests.ts
// Adapted from README import { create, AGClientSocket } from 'socketcluster-client'; import AuthEngine = require('socketcluster-client/lib/auth'); const socket = create({ hostname: 'localhost', port: 8000, }); socket.transmit('foo', 123); (async () => { // $ExpectType any await socket.invoke('myPro...
(_name: string): Promise<AuthEngine.AuthToken | AuthEngine.SignedAuthToken | null> { return Promise.resolve(null); } loadToken(_name: string): Promise<AuthEngine.AuthToken | AuthEngine.SignedAuthToken | null> { return Promise.resolve(null); } }
removeToken
identifier_name
socketcluster-client-tests.ts
// Adapted from README import { create, AGClientSocket } from 'socketcluster-client'; import AuthEngine = require('socketcluster-client/lib/auth'); const socket = create({ hostname: 'localhost', port: 8000, }); socket.transmit('foo', 123); (async () => { // $ExpectType any await socket.invoke('myPro...
secure: true, port: 443, rejectUnauthorized: false, // Only necessary during debug if using a self-signed certificate }; const secureSocket = create(secureOptions); const authStatus = await secureSocket.authenticate('abc'); // $ExpectType Error authStatus.authError; //...
random_line_split
socketcluster-client-tests.ts
// Adapted from README import { create, AGClientSocket } from 'socketcluster-client'; import AuthEngine = require('socketcluster-client/lib/auth'); const socket = create({ hostname: 'localhost', port: 8000, }); socket.transmit('foo', 123); (async () => { // $ExpectType any await socket.invoke('myPro...
loadToken(_name: string): Promise<AuthEngine.AuthToken | AuthEngine.SignedAuthToken | null> { return Promise.resolve(null); } }
{ return Promise.resolve(null); }
identifier_body
socketcluster-client-tests.ts
// Adapted from README import { create, AGClientSocket } from 'socketcluster-client'; import AuthEngine = require('socketcluster-client/lib/auth'); const socket = create({ hostname: 'localhost', port: 8000, }); socket.transmit('foo', 123); (async () => { // $ExpectType any await socket.invoke('myPro...
const authEngine = new AuthEngine(); const mostOptions: AGClientSocket.ClientOptions = { path: '/socketcluster/', port: 8000, hostname: '127.0.0.1', autoConnect: true, secure: false, connectTimeout: 10000, ackTimeout: 10000, channelPrefix: null, disconnectOnUnload: true, autoR...
{ // $ExpectType any authToken.iat; }
conditional_block
workspaces.service.ts
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { Logger } from 'ngx-base'; import { WIT_API_URL } from 'ngx-fabric8-wit'; import { AuthenticationService } from 'ngx-login-client'; import { Observable, throwError as observable...
* Open workspace associated with a codebase. * * @param url The open codebase URL (e.g., `${this.workspacesUrl}/${codebaseId}/open/${workspaceId}`) * @returns {Observable<WorkspaceLinks>} */ openWorkspace(url: string): Observable<WorkspaceLinks> { return this.http .post<WorkspaceLinks>(url, n...
/**
random_line_split
workspaces.service.ts
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { Logger } from 'ngx-base'; import { WIT_API_URL } from 'ngx-fabric8-wit'; import { AuthenticationService } from 'ngx-login-client'; import { Observable, throwError as observable...
this.headers = headers; this.workspacesUrl = `${apiUrl}codebases`; } /** * Create a workspace for given codebase ID * * @param codebaseId The ID associated with the given workspace * @returns {Observable<Codebase>} */ createWorkspace(codebaseId: string): Observable<WorkspaceLinks> { c...
{ headers = headers.set('Authorization', `Bearer ${this.auth.getToken()}`); }
conditional_block
workspaces.service.ts
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { Logger } from 'ngx-base'; import { WIT_API_URL } from 'ngx-fabric8-wit'; import { AuthenticationService } from 'ngx-login-client'; import { Observable, throwError as observable...
(error: HttpErrorResponse): Observable<any> { this.logger.error(error); return observableThrowError(error.message || error); } }
handleError
identifier_name
descriptor.py
# age/descriptor.py # pyAGE - A Python implementation of the Analog Genetic Encoding # Copyright (C) 2010 Janosch Gräf # # 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 ...
self): if (self.scoring==None): return True b = len(self.alphabet) if (type(self.scoring)!=tuple or len(self.scoring)!=b): return False for l in self.scoring: if (type(l)!=tuple or len(l)!=b): return False for s in l: ...
heck_scoring(
identifier_name
descriptor.py
# age/descriptor.py # pyAGE - A Python implementation of the Analog Genetic Encoding # Copyright (C) 2010 Janosch Gräf # # 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 ...
return True def check_scoring(self): if (self.scoring==None): return True b = len(self.alphabet) if (type(self.scoring)!=tuple or len(self.scoring)!=b): return False for l in self.scoring: if (type(l)!=tuple or len(l)!=b): ...
ry: self.possibilities[p] = float(self.possibilities[p]) except ValueError: return False
conditional_block
descriptor.py
# age/descriptor.py # pyAGE - A Python implementation of the Analog Genetic Encoding # Copyright (C) 2010 Janosch Gräf # # 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 ...
elif (type(self.possibilities)!=dict): return False for p in keys: if (p not in self.possibilities): self.possibilities[p] = 0.0 else: try: self.possibilities[p] = float(self.possibilities[p]) except ...
def check_possibilities(self): keys = ["char_delete", "char_insert", "char_replace", "frag_delete", "frag_move", "frag_copy", "device_insert", "chromosome_delete", "chromosome_copy", "chromosome_crossover"] if (self.possibilities==None): self.possibilities = {}
random_line_split
descriptor.py
# age/descriptor.py # pyAGE - A Python implementation of the Analog Genetic Encoding # Copyright (C) 2010 Janosch Gräf # # 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 ...
__all__ = ["Descriptor"]
eturn "Descriptor(alphabet = "+repr(self.alphabet)+",\n" \ +" devices = "+repr(self.devices)+",\n" \ +" terminal = "+repr(self.terminal)+",\n" \ +" parameter = "+repr(self.parameter)+",\n" \ +" possibilities = "+repr(self.po...
identifier_body
migrate.py
from __future__ import unicode_literals """Migrating IPython < 4.0 to Jupyter This *copies* configuration and resources to their new locations in Jupyter Migrations: - .ipython/ - nbextensions -> JUPYTER_DATA_DIR/nbextensions - kernels -> JUPYTER_DATA_DIR/kernels - .ipython/profile_default/ - static/custom -...
def migrate_static_custom(src, dst): """Migrate non-empty custom.js,css from src to dst src, dst are 'custom' directories containing custom.{js,css} """ log = get_logger() migrated = False custom_js = pjoin(src, 'custom.js') custom_css = pjoin(src, 'custom.css') # check if cust...
return False
random_line_split
migrate.py
from __future__ import unicode_literals """Migrating IPython < 4.0 to Jupyter This *copies* configuration and resources to their new locations in Jupyter Migrations: - .ipython/ - nbextensions -> JUPYTER_DATA_DIR/nbextensions - kernels -> JUPYTER_DATA_DIR/kernels - .ipython/profile_default/ - static/custom -...
(): """Migrate IPython configuration to Jupyter""" env = { 'jupyter_data': jupyter_data_dir(), 'jupyter_config': jupyter_config_dir(), 'ipython_dir': get_ipython_dir(), 'profile': os.path.join(get_ipython_dir(), 'profile_default'), } migrated = False for src_t, dst_t ...
migrate
identifier_name
migrate.py
from __future__ import unicode_literals """Migrating IPython < 4.0 to Jupyter This *copies* configuration and resources to their new locations in Jupyter Migrations: - .ipython/ - nbextensions -> JUPYTER_DATA_DIR/nbextensions - kernels -> JUPYTER_DATA_DIR/kernels - .ipython/profile_default/ - static/custom -...
break # check if custom_css is empty: custom_css_empty = True if os.path.isfile(custom_css): with open(custom_css) as f: css = f.read().strip() custom_css_empty = css.startswith('/*') and css.endswith('*/') if custom_js_empty: log.deb...
"""Migrate non-empty custom.js,css from src to dst src, dst are 'custom' directories containing custom.{js,css} """ log = get_logger() migrated = False custom_js = pjoin(src, 'custom.js') custom_css = pjoin(src, 'custom.css') # check if custom_js is empty: custom_js_empty = Tru...
identifier_body
migrate.py
from __future__ import unicode_literals """Migrating IPython < 4.0 to Jupyter This *copies* configuration and resources to their new locations in Jupyter Migrations: - .ipython/ - nbextensions -> JUPYTER_DATA_DIR/nbextensions - kernels -> JUPYTER_DATA_DIR/kernels - .ipython/profile_default/ - static/custom -...
if custom_js_empty and custom_css_empty: # nothing to migrate return False ensure_dir_exists(dst) if not custom_js_empty or not custom_css_empty: ensure_dir_exists(dst) if not custom_js_empty: if migrate_file(custom_js, pjoin(dst, 'custom.js')): ...
log.debug("Ignoring empty %s" % custom_css)
conditional_block
presupuesto_parcial.py
#------------------------------------------------------------------------------- # Name: presupuesto parcial#1 # Author: programar # # Creado: 12/11/2015 # Copyright: (c) programar 2015 # Licence: <your licence 1.1> #------------------------------------------------------------------------------- im...
(self): self.monto_iva= self.importe*self.cuota_iva/100 def monto_neto(self): self.neto= self.importe+self.monto_iva def armar_presupuesto(self): """ Esta funcion se encarga de armar todo el presupuesto """ txt = '\n'+self.div+'\n' txt += '\t'+self.i...
iva
identifier_name
presupuesto_parcial.py
#------------------------------------------------------------------------------- # Name: presupuesto parcial#1 # Author: programar # # Creado: 12/11/2015 # Copyright: (c) programar 2015 # Licence: <your licence 1.1> #------------------------------------------------------------------------------- im...
def iva(self): self.monto_iva= self.importe*self.cuota_iva/100 def monto_neto(self): self.neto= self.importe+self.monto_iva def armar_presupuesto(self): """ Esta funcion se encarga de armar todo el presupuesto """ txt = '\n'+self.div+'\n' txt +...
self.fecha= raw_input(" Fecha: ") self.servicio= raw_input("Descripcion del servicio: ") importe= raw_input("importe bruto: $") self.importe= float(importe) self.vencimiento= raw_input("fecha de expiracion: ")
identifier_body
presupuesto_parcial.py
#------------------------------------------------------------------------------- # Name: presupuesto parcial#1 # Author: programar # # Creado: 12/11/2015 # Copyright: (c) programar 2015 # Licence: <your licence 1.1> #------------------------------------------------------------------------------- im...
txt = '\n'+self.div+'\n' txt += '\t'+self.inicio_nombre+'\n' txt += '\tWeb Site: '+self.inicio_web+' | ' txt += 'E-mail: '+self.inicio_email+'\n' txt += self.div+'\n' txt += '\t'+self.titulo+'\n' txt += self.div+'\n\n' txt += '\tFecha: '+self.fecha+'\n' ...
""" Esta funcion se encarga de armar todo el presupuesto """
random_line_split
webpack.main.config.js
'use strict'; const path = require('path'); const webpack = require('webpack'); const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
bail : true, entry : path.join(__dirname, 'src/main/main.js'), target: 'electron-main', output: { path : path.join(__dirname, 'dist'), filename : 'main.js', publicPath : '/dist/', libraryTarget: 'commonjs2' }, resolve: { modules : ['node_modules'], extensions ...
module.exports = {
random_line_split
iME_Draw_colorPicker.py
#!/usr/bin/python import inkex import inkscapeMadeEasy_Base as inkBase import inkscapeMadeEasy_Draw as inkDraw class myExtension(inkBase.inkscapeMadeEasy): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option("--tab", action="store", type="string", dest="tab", default="ob...
x.affect()
random_line_split
iME_Draw_colorPicker.py
#!/usr/bin/python import inkex import inkscapeMadeEasy_Base as inkBase import inkscapeMadeEasy_Draw as inkDraw class myExtension(inkBase.inkscapeMadeEasy): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option("--tab", action="store", type="string", dest="tab", default="ob...
x = myExtension() x.affect()
conditional_block
iME_Draw_colorPicker.py
#!/usr/bin/python import inkex import inkscapeMadeEasy_Base as inkBase import inkscapeMadeEasy_Draw as inkDraw class myExtension(inkBase.inkscapeMadeEasy): def
(self): inkex.Effect.__init__(self) self.OptionParser.add_option("--tab", action="store", type="string", dest="tab", default="object") self.OptionParser.add_option("--myColorPicker", action="store", type="string", dest="myColorPickerVar", default='0') self.OptionParser.add_option("--myCo...
__init__
identifier_name
iME_Draw_colorPicker.py
#!/usr/bin/python import inkex import inkscapeMadeEasy_Base as inkBase import inkscapeMadeEasy_Draw as inkDraw class myExtension(inkBase.inkscapeMadeEasy): def __init__(self):
def effect(self): color = inkDraw.color.colorPickerToRGBalpha(self.options.myColorPickerVar) # do the same thing, but first verify whether myColorOptionVar is providing a pre defined color or asking to get it from the picker. color = inkDraw.color.parseColorPicker(self.options.myColorOpti...
inkex.Effect.__init__(self) self.OptionParser.add_option("--tab", action="store", type="string", dest="tab", default="object") self.OptionParser.add_option("--myColorPicker", action="store", type="string", dest="myColorPickerVar", default='0') self.OptionParser.add_option("--myColorOption", acti...
identifier_body
dialogflow_generated_dialogflow_v2_entity_types_batch_create_entities_async.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
(): # Create a client client = dialogflow_v2.EntityTypesAsyncClient() # Initialize request argument(s) entities = dialogflow_v2.Entity() entities.value = "value_value" entities.synonyms = ['synonyms_value_1', 'synonyms_value_2'] request = dialogflow_v2.BatchCreateEntitiesRequest( p...
sample_batch_create_entities
identifier_name
dialogflow_generated_dialogflow_v2_entity_types_batch_create_entities_async.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
print(response) # [END dialogflow_generated_dialogflow_v2_EntityTypes_BatchCreateEntities_async]
client = dialogflow_v2.EntityTypesAsyncClient() # Initialize request argument(s) entities = dialogflow_v2.Entity() entities.value = "value_value" entities.synonyms = ['synonyms_value_1', 'synonyms_value_2'] request = dialogflow_v2.BatchCreateEntitiesRequest( parent="parent_value", ...
identifier_body
dialogflow_generated_dialogflow_v2_entity_types_batch_create_entities_async.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ...
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #
random_line_split
reporter-proxy.js
module.exports = class ReporterProxy { constructor () { this.reporter = null this.timingsQueue = [] this.eventType = 'find-and-replace-v1' } setReporter (reporter) { this.reporter = reporter let timingsEvent while ((timingsEvent = this.timingsQueue.shift())) { this.reporter.add...
}
{ if (this.reporter) { this.reporter.addTiming(this.eventType, duration, metadata) } else { this.timingsQueue.push({duration, metadata}) } }
identifier_body
reporter-proxy.js
module.exports = class ReporterProxy { constructor () { this.reporter = null this.timingsQueue = [] this.eventType = 'find-and-replace-v1' } setReporter (reporter) { this.reporter = reporter let timingsEvent while ((timingsEvent = this.timingsQueue.shift()))
} unsetReporter () { delete this.reporter } sendSearchEvent (duration, numResults, crawler) { const metadata = { ec: 'time-to-search', ev: numResults, el: crawler } this._addTiming(duration, metadata) } _addTiming (duration, metadata) { if (this.reporter) { ...
{ this.reporter.addTiming(this.eventType, timingsEvent.duration, timingsEvent.metadata) }
conditional_block
reporter-proxy.js
module.exports = class ReporterProxy { constructor () { this.reporter = null this.timingsQueue = [] this.eventType = 'find-and-replace-v1' } setReporter (reporter) { this.reporter = reporter let timingsEvent while ((timingsEvent = this.timingsQueue.shift())) { this.reporter.add...
unsetReporter () { delete this.reporter } sendSearchEvent (duration, numResults, crawler) { const metadata = { ec: 'time-to-search', ev: numResults, el: crawler } this._addTiming(duration, metadata) } _addTiming (duration, metadata) { if (this.reporter) { thi...
random_line_split
reporter-proxy.js
module.exports = class ReporterProxy { constructor () { this.reporter = null this.timingsQueue = [] this.eventType = 'find-and-replace-v1' } setReporter (reporter) { this.reporter = reporter let timingsEvent while ((timingsEvent = this.timingsQueue.shift())) { this.reporter.add...
(duration, numResults, crawler) { const metadata = { ec: 'time-to-search', ev: numResults, el: crawler } this._addTiming(duration, metadata) } _addTiming (duration, metadata) { if (this.reporter) { this.reporter.addTiming(this.eventType, duration, metadata) } else { ...
sendSearchEvent
identifier_name
chat_ws.py
# -*- coding: utf-8 -*- __author__ = 'degibenz' import logging log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) import json from aiohttp import web from core.model import ObjectId from core.exceptions import * from models.chat import * from models.client import Client, Token __all__ = [ 'ChatWS'...
async def check_receiver(self, receiver: ObjectId): """ Метод проверяет, что получатель существует и находится в чате с отправителем. :param receiver: индификатор получателя """ client = Client( pk=ObjectId(receiver) ) if self.db: cl...
ws = None response = None chat = None client = None chat_pk = None client_pk = None db = None client_in_chat = None def __init__(self, request): try: self.db = request.app['db'] except(KeyError,): pass self.chat_pk = request.match_info....
identifier_body
chat_ws.py
# -*- coding: utf-8 -*- __author__ = 'degibenz' import logging log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) import json from aiohttp import web from core.model import ObjectId from core.exceptions import * from models.chat import * from models.client import Client, Token __all__ = [ 'ChatWS'...
error_info = { 'action': 'notify', 'receiver': receiver, 'sender': sender, 'error': '{}'.format(error) } log.error(error_info) if receiver: message = "@{}: {}".format(receiver, message)...
identifier_name
chat_ws.py
# -*- coding: utf-8 -*- __author__ = 'degibenz' import logging log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) import json from aiohttp import web from core.model import ObjectId from core.exceptions import * from models.chat import * from models.client import Client, Token __all__ = [ 'ChatWS'...
if receiver: await self.check_receiver(receiver) receiver = ObjectId(receiver) msg_obj = MessagesFromClientInChat( chat=self.chat_pk, client=self.client_pk, msg=content.get('msg'), receiver_message=...
random_line_split
chat_ws.py
# -*- coding: utf-8 -*- __author__ = 'degibenz' import logging log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) import json from aiohttp import web from core.model import ObjectId from core.exceptions import * from models.chat import * from models.client import Client, Token __all__ = [ 'ChatWS'...
}'.format(error) } log.error(error_info) if receiver: message = "@{}: {}".format(receiver, message) await _notify() async def mark_client_as_offline(self): q = { 'chat': self.chat_pk, 'client': self.client_pk } ...
ceiver': receiver, 'sender': sender, 'error': '{
conditional_block
attribute-function-content.component.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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 ...
() { this.form.patchValue({ js: this.attributeFunction?.js, xml: this.attributeFunction?.xml, dryRun: this.attributeFunction?.dryRun, recursive: this.attributeFunction?.recursive, }); } }
ngOnInit
identifier_name
attribute-function-content.component.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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 ...
* but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses...
* * This program is distributed in the hope that it will be useful,
random_line_split
postman-response.handler.ts
import { Project, Schema, Path, ProjectInfo, ProjectTree, ParameterPlacings } from "@maxxton/microdocs-core/domain"; import * as uuid from 'uuid'; import * as express from "express"; import { MicroDocsResponseHandler } from "./microdocs-response.handler"; import { Config } from "../../config"; import { ProjectJsonRepo...
postmans(projectTree: ProjectTree, env: string): {} { const config: { name: string, description: string, version: string, baseUrl: string } = { name: Config.get('application-name'), version: Config.get('application-version').toString(), description: Config.get('application-description'), ...
{ if (req.query['method']) { const filterMethods = (req.query['method'] as string).split(','); this.filterMethods(project, filterMethods); } this.response(req, res, 200, this.postman(project)); }
identifier_body
postman-response.handler.ts
import { Project, Schema, Path, ProjectInfo, ProjectTree, ParameterPlacings } from "@maxxton/microdocs-core/domain"; import * as uuid from 'uuid'; import * as express from "express"; import { MicroDocsResponseHandler } from "./microdocs-response.handler"; import { Config } from "../../config"; import { ProjectJsonRepo...
} handleProject(req: express.Request, res: express.Response, project: Project, env: string) { if (req.query['method']) { const filterMethods = (req.query['method'] as string).split(','); this.filterMethods(project, filterMethods); } this.response(req, res, 200, this.postman(project)); } ...
{ this.response(req, res, 200, this.postmans(projectTree, env)); }
conditional_block
postman-response.handler.ts
import { Project, Schema, Path, ProjectInfo, ProjectTree, ParameterPlacings } from "@maxxton/microdocs-core/domain"; import * as uuid from 'uuid'; import * as express from "express"; import { MicroDocsResponseHandler } from "./microdocs-response.handler"; import { Config } from "../../config"; import { ProjectJsonRepos...
handleProjects(req: express.Request, res: express.Response, projectTree: ProjectTree, env: string) { if (projectTree.projects.length == 1) { const projectNode = projectTree.projects[0]; const project = this.injection.ProjectRepository().getAggregatedProject(env, projectNode.title, projectNode.version...
import { mergeProjects } from "@maxxton/microdocs-core/helpers"; export class PostmanResponseHandler extends MicroDocsResponseHandler {
random_line_split
postman-response.handler.ts
import { Project, Schema, Path, ProjectInfo, ProjectTree, ParameterPlacings } from "@maxxton/microdocs-core/domain"; import * as uuid from 'uuid'; import * as express from "express"; import { MicroDocsResponseHandler } from "./microdocs-response.handler"; import { Config } from "../../config"; import { ProjectJsonRepo...
extends MicroDocsResponseHandler { handleProjects(req: express.Request, res: express.Response, projectTree: ProjectTree, env: string) { if (projectTree.projects.length == 1) { const projectNode = projectTree.projects[0]; const project = this.injection.ProjectRepository().getAggregatedProject(env, pr...
PostmanResponseHandler
identifier_name
Psiquica_vw.js
function dialogoCV() { var dialogo = getDiv(); var actualizarDialogoPsiquica = function() { var titulo; var contenido; var cvLibres = personaje_actual.getHabilidadDePersonaje(HB_CV).valorFinalActual() - personaje_actual.getCVGastados(); dialogo.empty(); /** *...
ent) { var disciplina = event.data.disciplina; var arrayOpciones = []; var poderesPsiquicos = disciplina.getPoderesPsiquicos(); for (var j = 0; j < poderesPsiquicos.length; j++) { var poder = poderesPsiquicos[j]; arrayOpciones.push(new OpcionMostrable(_l(poder.getNombre()),poder.getNomb...
girPoderADominar(ev
identifier_name
Psiquica_vw.js
function dialogoCV() { var dialogo = getDiv(); var actualizarDialogoPsiquica = function() { var titulo; var contenido; var cvLibres = personaje_actual.getHabilidadDePersonaje(HB_CV).valorFinalActual() - personaje_actual.getCVGastados(); dialogo.empty(); /** *...
var disciplina = event.data.disciplina; var arrayOpciones = []; var poderesPsiquicos = disciplina.getPoderesPsiquicos(); for (var j = 0; j < poderesPsiquicos.length; j++) { var poder = poderesPsiquicos[j]; arrayOpciones.push(new OpcionMostrable(_l(poder.getNombre()),poder.getNombre(),"",...
identifier_body
Psiquica_vw.js
function dialogoCV() { var dialogo = getDiv(); var actualizarDialogoPsiquica = function() { var titulo; var contenido; var cvLibres = personaje_actual.getHabilidadDePersonaje(HB_CV).valorFinalActual() - personaje_actual.getCVGastados(); dialogo.empty(); /** * ...
var divPoder = getDiv(); var botonMas = boton("small primary pretty btn",_l("+"),((poder.getFortalecimiento() == 10) || noQuedanCV)); var botonMenos = boton("small primary pretty btn",_l("-"),(poder.getFortalecimiento() == 0)); var divBotones = getDiv().append(botonMas).append(botonMeno...
var poder = poderesDominados[i];
random_line_split
Psiquica_vw.js
function dialogoCV() { var dialogo = getDiv(); var actualizarDialogoPsiquica = function() { var titulo; var contenido; var cvLibres = personaje_actual.getHabilidadDePersonaje(HB_CV).valorFinalActual() - personaje_actual.getCVGastados(); dialogo.empty(); /** *...
function elegirPoderADominar(event) { var disciplina = event.data.disciplina; var arrayOpciones = []; var poderesPsiquicos = disciplina.getPoderesPsiquicos(); for (var j = 0; j < poderesPsiquicos.length; j++) { var poder = poderesPsiquicos[j]; arrayOpciones.push(new OpcionMostrable(_l...
var poder = poderesDominados[i]; var divPoder = getDiv(); var botonMas = boton("small primary pretty btn",_l("+"),((poder.getFortalecimiento() == 10) || noQuedanCV)); var botonMenos = boton("small primary pretty btn",_l("-"),(poder.getFortalecimiento() == 0)); var divBotones = ge...
conditional_block
fold.rs
use std::mem; use {Task, Future, Poll, IntoFuture}; use stream::Stream; /// A future used to collect all the results of a stream into one generic type. /// /// This future is returned by the `Stream::fold` method. pub struct
<S, F, Fut, T> where Fut: IntoFuture { stream: S, f: F, state: State<T, Fut::Future>, } enum State<T, Fut> { /// Placeholder state when doing work Empty, /// Ready to process the next stream item; current accumulator is the `T` Ready(T), /// Working on a future the process the previou...
Fold
identifier_name
fold.rs
use std::mem; use {Task, Future, Poll, IntoFuture}; use stream::Stream; /// A future used to collect all the results of a stream into one generic type. /// /// This future is returned by the `Stream::fold` method. pub struct Fold<S, F, Fut, T> where Fut: IntoFuture { stream: S, f: F, state: State<T, Fut::...
T: Send + 'static { type Item = T; type Error = S::Error; fn poll(&mut self, task: &mut Task) -> Poll<T, S::Error> { loop { match mem::replace(&mut self.state, State::Empty) { State::Empty => panic!("cannot poll Fold twice"), State::Ready(state)...
Fut::Error: Into<S::Error>,
random_line_split
statsd.js
"use strict"; var dgram = require("dgram"); var mersenne = require("./mersenne"); var mt = new mersenne.MersenneTwister19937(); var EPHEMERAL_LIFETIME_MS = 1000; var Client = function(host, port, socket, options) { this.host = host || "localhost"; this.port = port || 8125; // optional shared socket ...
for (var stat in sampled_data) { var send_data = stat + ":" + sampled_data[stat]; this.send_data(new Buffer(send_data)); } }; Client.prototype.close = function() { if (this.socket) this.socket.close(); if (this.ephemeral_socket) this.ephemeral_socket.close(); if (t...
{ var merged_tags = []; if (Array.isArray(this.global_tags)) merged_tags = merged_tags.concat(this.global_tags); if (Array.isArray(tags)) merged_tags = merged_tags.concat(tags); if (merged_tags.length > 0) { var merged_tags_str = merged_tags.join(','); ...
conditional_block
statsd.js
"use strict"; var dgram = require("dgram"); var mersenne = require("./mersenne"); var mt = new mersenne.MersenneTwister19937(); var EPHEMERAL_LIFETIME_MS = 1000; var Client = function(host, port, socket, options) { this.host = host || "localhost"; this.port = port || 8125; // optional shared socket ...
} for (var stat in sampled_data) { var send_data = stat + ":" + sampled_data[stat]; this.send_data(new Buffer(send_data)); } }; Client.prototype.close = function() { if (this.socket) this.socket.close(); if (this.ephemeral_socket) this.ephemeral_socket.close(); ...
random_line_split
articles.client.controller.js
'use strict'; angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles', function($scope, $stateParams, $location, Authentication, Articles) { $scope.authentication = Authentication; $scope.create = function() { var article = new Articles(...
} } else { $scope.article.$remove(function() { $location.path('articles'); }); } }; $scope.update = function() { var article = $scope.article; article.$update(function() { $location.path('articles/' + article._id); }, function(errorResponse) { $scope.error = errorResponse.d...
}
random_line_split
articles.client.controller.js
'use strict'; angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles', function($scope, $stateParams, $location, Authentication, Articles) { $scope.authentication = Authentication; $scope.create = function() { var article = new Articles(...
}; $scope.update = function() { var article = $scope.article; article.$update(function() { $location.path('articles/' + article._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.find = function() { $scope.articles = Articles.query(); }; $...
{ $scope.article.$remove(function() { $location.path('articles'); }); }
conditional_block
extern-pass-TwoU32s.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test a foreig...
random_line_split
extern-pass-TwoU32s.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 ...
() { unsafe { let x = TwoU32s {one: 22, two: 23}; let y = rust_dbg_extern_identity_TwoU32s(x); assert_eq!(x, y); } }
main
identifier_name
test_sockopt.rs
::socket::{socket, sockopt, getsockopt, setsockopt, AddressFamily, SockType, SockFlag, SockProtocol}; #[cfg(any(target_os = "android", target_os = "linux"))] use crate::*; // NB: FreeBSD supports LOCAL_PEERCRED for SOCK_SEQPACKET, but OSX does not. #[cfg(any( target_os = "dragonfly", target_os = "freeb...
#[test] fn test_so_tcp_keepalive() { let fd = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp).unwrap(); setsockopt(fd, sockopt::KeepAlive, &true).unwrap(); assert!(getsockopt(fd, sockopt::KeepAlive).unwrap()); #[cfg(any(target_os = "android", target_o...
{ skip_if_not_root!("test_bindtodevice"); let fd = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap(); let val = getsockopt(fd, sockopt::BindToDevice).unwrap(); setsockopt(fd, sockopt::BindToDevice, &val).unwrap(); assert_eq!( getsockopt(fd, sockopt::BindToDev...
identifier_body
test_sockopt.rs
sys::socket::{socket, sockopt, getsockopt, setsockopt, AddressFamily, SockType, SockFlag, SockProtocol}; #[cfg(any(target_os = "android", target_os = "linux"))] use crate::*; // NB: FreeBSD supports LOCAL_PEERCRED for SOCK_SEQPACKET, but OSX does not. #[cfg(any( target_os = "dragonfly", target_os = "fr...
} } #[test] #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] fn test_ttl_opts() { let fd4 = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None).unwrap(); setsockopt(fd4, sockopt::Ipv4Ttl, &1) .expect("setting ipv4ttl on an inet socket should succee...
let x = getsockopt(fd, sockopt::TcpKeepInterval).unwrap(); setsockopt(fd, sockopt::TcpKeepInterval, &(x + 1)).unwrap(); assert_eq!(getsockopt(fd, sockopt::TcpKeepInterval).unwrap(), x + 1);
random_line_split
test_sockopt.rs
::socket::{socket, sockopt, getsockopt, setsockopt, AddressFamily, SockType, SockFlag, SockProtocol}; #[cfg(any(target_os = "android", target_os = "linux"))] use crate::*; // NB: FreeBSD supports LOCAL_PEERCRED for SOCK_SEQPACKET, but OSX does not. #[cfg(any( target_os = "dragonfly", target_os = "freeb...
() { use nix::{ unistd::{Gid, Uid}, sys::socket::socketpair }; let (fd1, _fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()).unwrap(); let xucred = getsockopt(fd1, sockopt::LocalPeerCred).unwrap(); assert_eq!(xucred.vers...
test_local_peercred_stream
identifier_name
constants.ts
/** * @license * Copyright Google LLC 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://angular.io/license */ export const $COMPILE = '$compile'; export const $CONTROLLER = '$controller'; export const $DELEGATE = '$delegate'; e...
export const LAZY_MODULE_REF = '$$angularLazyModuleRef'; export const NG_ZONE_KEY = '$$angularNgZone'; export const UPGRADE_APP_TYPE_KEY = '$$angularUpgradeAppType'; export const REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY; export const REQUIRE_NG_MODEL = '?ngModel'; export const UPGRADE_MODULE_NAME = '$$UpgradeModule';
export const COMPILER_KEY = '$$angularCompiler'; export const DOWNGRADED_MODULE_COUNT_KEY = '$$angularDowngradedModuleCount'; export const GROUP_PROJECTABLE_NODES_KEY = '$$angularGroupProjectableNodes'; export const INJECTOR_KEY = '$$angularInjector';
random_line_split
mappingMaker.js
'use strict'; const inflect = require('i')(); const _ = require('lodash'); const Promise = require('bluebird'); const fs = Promise.promisifyAll(require('fs')); const options = { adapter: 'mongodb', connectionString: 'mongodb://127.0.0.1:27017/testDB', db: 'testDB', inflect: true }; console.log(JSON.stringify(o...
(propertyName, propertyValue, cursor, depth) { let nextCursor; if (depth === 1) { cursor.links = cursor.links || { type: 'nested' }; cursor.links.properties = cursor.links.properties || {}; cursor.links.properties[propertyName] = { type: 'nested', properties: {} }; ...
getNextLevelSchema
identifier_name
mappingMaker.js
'use strict'; const inflect = require('i')(); const _ = require('lodash'); const Promise = require('bluebird'); const fs = Promise.promisifyAll(require('fs')); const options = { adapter: 'mongodb', connectionString: 'mongodb://127.0.0.1:27017/testDB', db: 'testDB', inflect: true }; console.log(JSON.stringify(o...
function MappingMaker() { } MappingMaker.prototype.generateMapping = function generateMapping(harvestApp, pov, outputFile) { let harvesterApp; if (_.isString(harvestApp)) { harvesterApp = require(harvestApp)(options); } else { harvesterApp = Promise.resolve(harvestApp); } return harvesterApp ...
{ return functionTypeLookup[fn.toString().substr(0, 13)]; }
identifier_body
mappingMaker.js
'use strict'; const inflect = require('i')(); const _ = require('lodash'); const Promise = require('bluebird'); const fs = Promise.promisifyAll(require('fs')); const options = { adapter: 'mongodb', connectionString: 'mongodb://127.0.0.1:27017/testDB', db: 'testDB', inflect: true }; console.log(JSON.stringify(o...
} if (runningAsScript) { const mappingMaker = new MappingMaker(); mappingMaker.generateMapping(process.argv[2], process.argv[3], process.argv[4]); } else { module.exports = MappingMaker; }
return cursor; } getLinkedSchemas(startingSchema, _cursor, _depth); return retVal;
random_line_split
mappingMaker.js
'use strict'; const inflect = require('i')(); const _ = require('lodash'); const Promise = require('bluebird'); const fs = Promise.promisifyAll(require('fs')); const options = { adapter: 'mongodb', connectionString: 'mongodb://127.0.0.1:27017/testDB', db: 'testDB', inflect: true }; console.log(JSON.stringify(o...
{ module.exports = MappingMaker; }
conditional_block
fractions.js
const multiples = '(hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion)' const here = 'fraction-tagger' // plural-ordinals like 'hundredths' are already tagged as Fraction by compromise const tagFractions = function (doc) { // hundred doc.match(multiples).tag('#Multiple', her...
// fraction - 'a third of a slice' // TODO:fixme // m = doc.match(`[(#Cardinal|a) ${ordinals}] of (a|an|the)`, 0).tag('Fraction', 'ord-of') // tag 'thirds' as a ordinal // m.match('.$').tag('Ordinal', 'plural-ordinal') return doc } module.exports = tagFractions
// // '3 out of 5' doc.match('#Cardinal+ out? of every? #Cardinal').tag('Fraction', here) // // one and a half // doc.match('#Cardinal and a (#Fraction && #Value)').tag('Fraction', here)
random_line_split
gui.rs
use edit::Editor; use std::fmt::Write; use gtk::{self, Widget, Window, Frame, EventBox, DrawingArea, WindowPosition}; use gtk::signal::Inhibit; use gtk::traits::*; use gdk::EventType; use cairo::{Context, Antialias}; use cairo::enums::{FontSlant, FontWeight}; pub struct Gui { #[allow(dead_code)] win: &'static mut ...
c.fill(); } c.translate(-undo_x, SCALE + 10.0); } } }
let trans_x = SCALE * 8.0; undo_x += trans_x; c.translate(trans_x, 0.0); c.text_path(&s);
random_line_split
gui.rs
use edit::Editor; use std::fmt::Write; use gtk::{self, Widget, Window, Frame, EventBox, DrawingArea, WindowPosition}; use gtk::signal::Inhibit; use gtk::traits::*; use gdk::EventType; use cairo::{Context, Antialias}; use cairo::enums::{FontSlant, FontWeight}; pub struct Gui { #[allow(dead_code)] win: &'static mut...
(&self) { self.win.queue_draw(); } pub fn render(&self, w: Widget, c: Context) { let (_alloc_w, _alloc_h) = (w.get_allocated_width(), w.get_allocated_height()); const FONT_SIZE: f64 = 17.0; const SCALE: f64 = FONT_SIZE * 1.0; // 1.0 for Helvetica, c.select_font_face("Times New Roman", FontSlant::Norma...
dirty
identifier_name
gui.rs
use edit::Editor; use std::fmt::Write; use gtk::{self, Widget, Window, Frame, EventBox, DrawingArea, WindowPosition}; use gtk::signal::Inhibit; use gtk::traits::*; use gdk::EventType; use cairo::{Context, Antialias}; use cairo::enums::{FontSlant, FontWeight}; pub struct Gui { #[allow(dead_code)] win: &'static mut...
} s.push('}'); let trans_x = SCALE * 8.0; undo_x += trans_x; c.translate(trans_x, 0.0); c.text_path(&s); c.fill(); } c.translate(-undo_x, SCALE + 10.0); } } }
{ s.push(','); s.push(' '); }
conditional_block
instances.py
#!python import re import sys import logging import boto.ec2 from texttable import Texttable from pprint import PrettyPrinter from optparse import OptionParser PP = PrettyPrinter( indent=2 ) ################### ### Arg parsing ################### parser = OptionParser("usage: %prog [options]" ) parser.add_...
### XXX EVERY column in this output had better have a non-zero length ### or texttable blows up with 'width must be greater than 0' error table.add_row( [ i.id, i.tags.get( 'Name', ' ' ), i.instance_type, i._placement , i.groups[0].name, i.state, ...
### you can use i.region instead of i._placement, but it pretty ### prints to RegionInfo:us-east-1. For now, use the private version
random_line_split
instances.py
#!python import re import sys import logging import boto.ec2 from texttable import Texttable from pprint import PrettyPrinter from optparse import OptionParser PP = PrettyPrinter( indent=2 ) ################### ### Arg parsing ################### parser = OptionParser("usage: %prog [options]" ) parser.add_...
logging.basicConfig(stream=sys.stdout, level=log_level) logging.basicConfig(stream=sys.stderr, level=(logging.ERROR,logging.CRITICAL)) ################### ### Connection ################### conn = boto.ec2.connect_to_region( options.region ) ################### ### Regexes ################### regexes = {} for op...
log_level = logging.INFO
conditional_block
instances.py
#!python import re import sys import logging import boto.ec2 from texttable import Texttable from pprint import PrettyPrinter from optparse import OptionParser PP = PrettyPrinter( indent=2 ) ################### ### Arg parsing ################### parser = OptionParser("usage: %prog [options]" ) parser.add_...
(): instances = [ i for r in conn.get_all_instances() for i in r.instances ] rv = []; for i in instances: ### we will assume this node is one of the nodes we want ### to operate on, and we will unset this flag if any of ### the criteria fail ...
get_instances
identifier_name
instances.py
#!python import re import sys import logging import boto.ec2 from texttable import Texttable from pprint import PrettyPrinter from optparse import OptionParser PP = PrettyPrinter( indent=2 ) ################### ### Arg parsing ################### parser = OptionParser("usage: %prog [options]" ) parser.add_...
### prints to RegionInfo:us-east-1. For now, use the private version ### XXX EVERY column in this output had better have a non-zero length ### or texttable blows up with 'width must be greater than 0' error table.add_row( [ i.id, i.tags.get( 'Name', ' ' ), i.instance_type, ...
table = Texttable( max_width=0 ) table.set_deco( Texttable.HEADER ) table.set_cols_dtype( [ 't', 't', 't', 't', 't', 't', 't', 't' ] ) table.set_cols_align( [ 'l', 'l', 'l', 'l', 'l', 'l', 'l', 't' ] ) if not options.no_header: ### using add_row, so the headers aren't being centered, for...
identifier_body
uploader.py
#! /usr/bin/python # -*- coding: utf-8 -*- """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Title: uploader Author: David Leclerc Version: 0.1 Date: 01.07.2017 License: GNU General Public License, Version 3 (http://www.gnu.org/licens...
# CLASSES class Uploader(object): def __init__(self): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INIT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Define report self.report = reporter...
# Define instances Logger = logger.Logger("uploader")
random_line_split
uploader.py
#! /usr/bin/python # -*- coding: utf-8 -*- """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Title: uploader Author: David Leclerc Version: 0.1 Date: 01.07.2017 License: GNU General Public License, Version 3 (http://www.gnu.org/licens...
def upload(self, sftp, path, ext = None): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UPLOAD ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Get all files from path files = os.listdir(pa...
""" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INIT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Define report self.report = reporter.getSFTPReport()
identifier_body
uploader.py
#! /usr/bin/python # -*- coding: utf-8 -*- """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Title: uploader Author: David Leclerc Version: 0.1 Date: 01.07.2017 License: GNU General Public License, Version 3 (http://www.gnu.org/licens...
main()
conditional_block
uploader.py
#! /usr/bin/python # -*- coding: utf-8 -*- """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Title: uploader Author: David Leclerc Version: 0.1 Date: 01.07.2017 License: GNU General Public License, Version 3 (http://www.gnu.org/licens...
(self): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RUN ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Test if report is empty before proceding if not self.report.isValid(): raise e...
run
identifier_name
__init__.py
cmp,ververify', 'portage.xpak', 'subprocess', 'time', ) try: from collections import OrderedDict except ImportError: proxy.lazyimport.lazyimport(globals(), 'portage.cache.mappings:OrderedDict') import portage.const from portage.const import VDB_PATH, PRIVATE_PATH, CACHE_PATH, DEPCACHE_PATH, \ USER...
""" Quote a string in double-quotes and use backslashes to escape any backslashes, double-quotes, dollar signs, or backquotes in the string. """ for letter in "\\\"$`": if letter in s: s = s.replace(letter, "\\" + letter) return "\"%s\"" % s
identifier_body
__init__.py
\ 'suffix_value@endversion,pkgcmp,pkgsplit,vercmp,ververify', 'portage.xpak', 'subprocess', 'time', ) try: from collections import OrderedDict except ImportError: proxy.lazyimport.lazyimport(globals(), 'portage.cache.mappings:OrderedDict') import portage.const from portage.const import VDB_PATH,...
(s, encoding=_encodings['content'], errors='backslashreplace'): if isinstance(s, str): s = s.encode(encoding, errors) return s def _unicode_decode(s, encoding=_encodings['content'], errors='replace'): if isinstance(s, bytes): s = str(s, encoding=encoding, errors=errors) return s else: def _unicode_enco...
_unicode_encode
identifier_name
__init__.py
\ 'suffix_value@endversion,pkgcmp,pkgsplit,vercmp,ververify', 'portage.xpak', 'subprocess', 'time', ) try: from collections import OrderedDict except ImportError: proxy.lazyimport.lazyimport(globals(), 'portage.cache.mappings:OrderedDict') import portage.const from portage.const import VDB_PATH,...
return s def _unicode_decode(s, encoding=_encodings['content'], errors='replace'): if isinstance(s, bytes): s = str(s, encoding=encoding, errors=errors) return s else: def _unicode_encode(s, encoding=_encodings['content'], errors='backslashreplace'): if isinstance(s, unicode): s = s.encode(encoding, e...
s = s.encode(encoding, errors)
conditional_block
__init__.py
and failure here indicates that you have a problem with your\n") sys.stderr.write("!!! installation of portage. Please try a rescue portage located in the\n") sys.stderr.write("!!! portage tree under '/usr/portage/sys-apps/portage/files/' (default).\n") sys.stderr.write("!!! There is a README.RESCUE file that detai...
random_line_split
Device.js
var net = require('net'); var util = require('util'); var events = require('events'); var proto = require('./protocol'); module.exports = Device; function Device(conf) { events.EventEmitter.call(this, conf); var self = this; this.backlog = []; this.device_id = conf.device_id; this.device_ip = conf.device_ip; ...
Device.prototype._request = function (msg, cb) { var self = this; var to = setTimeout(function () { var unanswered = self.backlog.shift(); var cb = unanswered.callback; var err = new Error('request timeout'); cb(err); if (self.backlog.length > 0) self.emit('CTS'); }, 2500); this.backlog.push({reques...
{ var which = 'set'; if ((arguments.length == 2) && (typeof (value) == 'function')) { cb = value; value = null; which = 'get'; } var msg = { type: proto.types.getset_req, getset_name: name }; if (which == 'set') msg.getset_value = value; this._request(msg, cb); }
identifier_body
Device.js
var net = require('net'); var util = require('util'); var events = require('events'); var proto = require('./protocol'); module.exports = Device; function Device(conf) { events.EventEmitter.call(this, conf); var self = this; this.backlog = []; this.device_id = conf.device_id; this.device_ip = conf.device_ip; ...
this.backlog.push({request: msg, callback: cb, timeout: to}); if (this.backlog.length === 1) this.emit('CTS'); }
if (self.backlog.length > 0) self.emit('CTS'); }, 2500);
random_line_split
Device.js
var net = require('net'); var util = require('util'); var events = require('events'); var proto = require('./protocol'); module.exports = Device; function
(conf) { events.EventEmitter.call(this, conf); var self = this; this.backlog = []; this.device_id = conf.device_id; this.device_ip = conf.device_ip; this.control_sock = net.createConnection(65001, this.device_ip, function () { self.emit('connected'); }); this.request_encoder = new proto.RequestEncode...
Device
identifier_name
test_check_coverage.py
#!/usr/bin/env python3 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
for src_file in check_coverage.WHITELISTED_FILES: yield os.path.join('qutebrowser', src_file) for test_file, src_file in check_coverage.PERFECT_FILES: if test_file is not None: yield test_file yield os.path.join('qutebrowser', src_file) @pytest.mark.parametrize('filename', ...
def _generate_files(): """Get filenames from WHITELISTED_/PERFECT_FILES."""
random_line_split
test_check_coverage.py
#!/usr/bin/env python3 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
def run(self): """Run pytest with coverage for the given module.py.""" coveragerc = str(self._testdir.tmpdir / 'coveragerc') self._monkeypatch.delenv('PYTEST_ADDOPTS', raising=False) return self._testdir.runpytest('--cov=module', '--cov-config...
"""Generate a module.py for the given code.""" self._testdir.makepyfile(module=code)
identifier_body
test_check_coverage.py
#!/usr/bin/env python3 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
(self, perfect_files=None): """Run check_coverage.py and run its return value.""" coverage_file = self._testdir.tmpdir / 'coverage.xml' if perfect_files is None: perfect_files = [(None, 'module.py')] argv = [sys.argv[0]] self._monkeypatch.setattr(check_coverage.sys,...
check
identifier_name
test_check_coverage.py
#!/usr/bin/env python3 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
yield os.path.join('qutebrowser', src_file) @pytest.mark.parametrize('filename', list(_generate_files())) def test_files_exist(filename): basedir = os.path.join(os.path.dirname(check_coverage.__file__), os.pardir, os.pardir) assert os.path.exists(os.path.join(basedir, filen...
yield test_file
conditional_block
TrailerWindow.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2014 Philipp Temminghoff (philipptemminghoff@gmail.com) # # 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 version ...
CONTROL_SLIDER = 101 ACTION_CONTEXT_MENU = [117] ACTION_OSD = [122] ACTION_PREVIOUS_MENU = [9, 92, 10] ACTION_SHOW_INFO = [11] ACTION_EXIT_SCRIPT = [13] ACTION_DOWN = [4] ACTION_UP = [3] ACTION_LEFT = [1] ACTION_RIGHT = [2] ACTION_0 = [58, 18] ACTION_PLAY = [79] ACTION_SELECT_ITEM = [7] LISTS = [8001, 8002, 8003, 8004,...
__addonpath__ = __addon__.getAddonInfo('path')
random_line_split
TrailerWindow.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2014 Philipp Temminghoff (philipptemminghoff@gmail.com) # # 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 version ...
pass
identifier_body
TrailerWindow.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2014 Philipp Temminghoff (philipptemminghoff@gmail.com) # # 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 version ...
(xbmcgui.WindowXML): def __init__(self, skin_file, addon_path): log('__init__') def onInit(self, startGUI=True): pass def onAction(self, action): action_id = action.getId() if action_id in ACTION_PREVIOUS_MENU: self.close() elif action_id in ACTION_SHOW...
TrailerWindow
identifier_name
TrailerWindow.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2014 Philipp Temminghoff (philipptemminghoff@gmail.com) # # 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 version ...
# elif action_id in ACTION_LEFT: # for controlnumber in LISTS: # if controlnumber != focusedcontrol: # xbmc.executebuiltin("Control.Move(%i,-1)" % (controlnumber)) # elif action_id in ACTION_RIGHT: # for controlnumber in LISTS: # ...
focusedcontrol = self.getFocusId() MoveProperties(focusedcontrol, focusedcontrol) movieid = xbmc.getInfoLabel("Container(%i).ListItem.Property(ID)" % focusedcontrol) builtin = "RunScript(script.extendedinfo,info=extendedinfo,id=%s,imdbid=%s)" % (movieid, xbmc.getInfoLabel("Window(hom...
conditional_block
cancel.py
# Copyright (c) 2015 Uber Technologies, 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, modify, merge, publ...
cancel_rw = rw.instance( CancelMessage, ('ttl', rw.number(4)), # ttl:4 ('tracing', common.tracing_rw), # tracing:24 ('why', rw.len_prefixed_string(rw.number(2))), # why:2 )
__slots__ = BaseMessage.__slots__ + ( 'ttl', 'tracing', 'why', ) def __init__(self, ttl=DEFAULT_TIMEOUT, tracing=None, why=None, id=0): super(CancelMessage, self).__init__(id) self.ttl = ttl self.tracing = tracing or common.Tracing(0, 0, 0, 0) self.why = ...
identifier_body
cancel.py
# Copyright (c) 2015 Uber Technologies, 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, modify, merge, publ...
(BaseMessage): __slots__ = BaseMessage.__slots__ + ( 'ttl', 'tracing', 'why', ) def __init__(self, ttl=DEFAULT_TIMEOUT, tracing=None, why=None, id=0): super(CancelMessage, self).__init__(id) self.ttl = ttl self.tracing = tracing or common.Tracing(0, 0, 0, 0) ...
CancelMessage
identifier_name
cancel.py
# Copyright (c) 2015 Uber Technologies, 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, modify, merge, publ...
('why', rw.len_prefixed_string(rw.number(2))), # why:2 )
random_line_split
project.py
c c++', 'ClCompile'), ('h h++', 'ClInclude'), ('rc', 'ResourceCompile'), ('vcxproj', 'ProjectReference'), ]) for kk in k.split()} def proj_import(root, path): SubElement(root, 'Import', {'Project': path}) def emit_properties(*, element, props, var=None): for k, v in sorted(props.items()): ...
create_user
identifier_name
project.py
(variant) SOURCE_TYPES = {kk: (n, v) for n, (k, v) in enumerate([ ('c c++', 'ClCompile'), ('h h++', 'ClInclude'), ('rc', 'ResourceCompile'), ('vcxproj', 'ProjectReference'), ]) for kk in k.split()} def proj_import(root, path): SubElement(root, 'Import', {'Project': path}) def emit_properties(*, e...
def create_project(*, name, sources, uuid, variants, props, arguments): """Create a Visual Studio project. name: the project name. sources: list of source files in the project. uuid: the project UUID. variants: list of "config|arch" variants. props: map from "config|arch" to map from group to...
indent_xml(root) return etree.tostring(root, encoding='UTF-8')
identifier_body
project.py
(variant) SOURCE_TYPES = {kk: (n, v) for n, (k, v) in enumerate([ ('c c++', 'ClCompile'), ('h h++', 'ClInclude'), ('rc', 'ResourceCompile'), ('vcxproj', 'ProjectReference'), ]) for kk in k.split()} def proj_import(root, path): SubElement(root, 'Import', {'Project': path}) def emit_properties(*, e...
ig = SubElement(root, 'ImportGroup', { 'Label': 'PropertySheets', 'Condition': condition(variant), }) path = '$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props' i = SubElement(ig, 'Import', { 'Project': path, ...
SubElement(root, 'ImportGroup', {'Label': 'ExtensionSettings'}) for variant in variants:
random_line_split
project.py
(variant) SOURCE_TYPES = {kk: (n, v) for n, (k, v) in enumerate([ ('c c++', 'ClCompile'), ('h h++', 'ClInclude'), ('rc', 'ResourceCompile'), ('vcxproj', 'ProjectReference'), ]) for kk in k.split()} def proj_import(root, path): SubElement(root, 'Import', {'Project': path}) def emit_properties(*, e...
del n, elt proj_import(root, '$(VCTargetsPath)\\Microsoft.Cpp.targets') SubElement(root, 'ImportGroup', {'Label': 'ExtensionTargets'}) return root def create_filter(): filters = set() root = Element('Project', { 'xmlns': XMLNS, 'ToolsVersi...
root.append(elt)
conditional_block
module.js
angular .module('eventApp', [ 'ngResource', 'ui.bootstrap', 'ui.select', 'ui.bootstrap.datetimepicker', 'global', 'messagingApp', 'datasetApp' ]) .constant('HEK_URL', 'http://www.lmsal.com/hek/her') .constant('HEK_QUERY_PARAMS', { 'cosec': 2, // ask for json 'cmd': 'search', // search command 'type': 'column'...
TO : 'Topological Object' });
CR : 'Coronal Rain', CC : 'Coronal Cavity', ER : 'Eruption',
random_line_split
i18n.ts
export const enum I18nMutateOpCode { /** * Stores shift amount for bits 17-3 that contain reference index. */ SHIFT_REF = 3, /** * Stores shift amount for bits 31-17 that contain parent index. */ SHIFT_PARENT = 17, /** * Mask for OpCode */ MASK_OPCODE = 0b111, /** * OpCode to select ...
* * See: `I18nCreateOpCodes` for example of usage. */ import {SanitizerFn} from './sanitization';
random_line_split
index.js
/** * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applic...
() { return Promise.resolve(true); } }; return Driver.loadPage(driver, {}, { flags: { loadPage: true } }).then(res => { assert.equal(res, true); }); }); it('reloads a page via about:blank', () => { const expected = [ 'https://example.com', 'a...
gotoURL
identifier_name
index.js
/** * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applic...
}] }; return Driver.setup({driver, config}).then(_ => { assert.equal(calledTrace, true); }); }); it('tells the driver to end tracing', () => { let calledTrace = false; const driver = { endTrace() { calledTrace = true; return Promise.resolve({x: 1}); } ...
{}
identifier_body