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
findBreaksVCF.py
#!/usr/bin/python import re import sys import os import getopt import vcf def main(): params = parseArgs() vfh = vcf.Reader(open(params.vcf, 'r')) #grab contig sizes contigs = dict() for c,s in vfh.contigs.items(): contigs[s.id] = s.length regions = list() this_chrom = None start = int() stop = int() ...
#Second pass to set all args. for opt, arg_raw in options: arg = arg_raw.replace(" ","") arg = arg.strip() opt = opt.replace("-","") #print(opt,arg) if opt in ('v', 'vcf'): self.vcf = arg elif opt in ('f','force'): self.force=int(arg) elif opt in ('h', 'help'): pass else: a...
self.display_help("Exiting because help menu was called.")
conditional_block
findBreaksVCF.py
#!/usr/bin/python import re import sys import os import getopt import vcf def main(): params = parseArgs() vfh = vcf.Reader(open(params.vcf, 'r')) #grab contig sizes contigs = dict() for c,s in vfh.contigs.items(): contigs[s.id] = s.length regions = list() this_chrom = None start = int() stop = int() ...
#Call main function if __name__ == '__main__': main()
if message is not None: print() print (message) print ("\nfindBreaksVCF.py\n") print ("Contact:Tyler K. Chafin, University of Arkansas,tkchafin@uark.edu") print ("\nUsage: ", sys.argv[0], "-v <input.vcf> -f <100000>\n") print ("Description: Breaks chromosomes into chunks of X parsimony-informative sites, ...
identifier_body
findBreaksVCF.py
#!/usr/bin/python import re import sys import os import getopt import vcf def main(): params = parseArgs() vfh = vcf.Reader(open(params.vcf, 'r')) #grab contig sizes contigs = dict() for c,s in vfh.contigs.items(): contigs[s.id] = s.length regions = list() this_chrom = None start = int() stop = int() ...
fh.write(ol) except IOError as e: print("Could not read file %s: %s"%(f,e)) sys.exit(1) except Exception as e: print("Unexpected error reading file %s: %s"%(f,e)) sys.exit(1) finally: fh.close() #Function to check pyVCF record for if parsimony informative or not def is_PIS(r): ref=0 alt=0 f...
try: for reg in r: ol = str(reg[0]) + ":" + str(reg[1]) + "-" + str(reg[2]) + "\n"
random_line_split
exam.ts
import { Component } from '@angular/core'; import { NavController, NavParams, ToastController } from 'ionic-angular'; import { ImagePicker } from '@ionic-native/image-picker'; import { ExamProvider } from '../../providers/exam/exam'; import { Exam } from '../../models/exam/exam'; /** * Generated class for the ExamPag...
() { this.examProvider.removeExam(this.exam.shareName).subscribe( response => { this.examProvider.toggleNewExamFlag(); this.toastCtrl.create({ message: 'El examen se ha eliminado, podrás seguir accediendo hasta que cambies de vista', duration: 3000, position: 'bo...
removeExam
identifier_name
exam.ts
import { Component } from '@angular/core'; import { NavController, NavParams, ToastController } from 'ionic-angular'; import { ImagePicker } from '@ionic-native/image-picker'; import { ExamProvider } from '../../providers/exam/exam'; import { Exam } from '../../models/exam/exam'; /** * Generated class for the ExamPag...
) } }
results => { results.forEach(image => { console.log('Image URI: ' + image) }); }
random_line_split
to-string.ts
const objectToString = Object.prototype.toString; function isNone(obj: any | null | undefined): obj is null | undefined { return obj === null || obj === undefined; } /* A `toString` util function that supports objects without a `toString` method, e.g. an object created with `Object.create(null)`. */ export defaul...
} if (typeof obj.toString === 'function') { return obj.toString(); } return objectToString.call(obj); }
} } return r;
random_line_split
to-string.ts
const objectToString = Object.prototype.toString; function isNone(obj: any | null | undefined): obj is null | undefined { return obj === null || obj === undefined; } /* A `toString` util function that supports objects without a `toString` method, e.g. an object created with `Object.create(null)`. */ export defaul...
if (!isNone(obj[k])) { r += toString(obj[k]); } } return r; } if (typeof obj.toString === 'function') { return obj.toString(); } return objectToString.call(obj); }
{ r += ','; }
conditional_block
to-string.ts
const objectToString = Object.prototype.toString; function isNone(obj: any | null | undefined): obj is null | undefined { return obj === null || obj === undefined; } /* A `toString` util function that supports objects without a `toString` method, e.g. an object created with `Object.create(null)`. */ export defaul...
} return r; } if (typeof obj.toString === 'function') { return obj.toString(); } return objectToString.call(obj); }
{ if (typeof obj === 'string') { return obj; } if (null === obj) return 'null'; if (undefined === obj) return 'undefined'; if (Array.isArray(obj)) { // Reimplement Array.prototype.join according to spec (22.1.3.13) // Changing ToString(element) with this safe version of ToString. let r = ''; ...
identifier_body
to-string.ts
const objectToString = Object.prototype.toString; function isNone(obj: any | null | undefined): obj is null | undefined { return obj === null || obj === undefined; } /* A `toString` util function that supports objects without a `toString` method, e.g. an object created with `Object.create(null)`. */ export defaul...
(obj: any | undefined | null): string { if (typeof obj === 'string') { return obj; } if (null === obj) return 'null'; if (undefined === obj) return 'undefined'; if (Array.isArray(obj)) { // Reimplement Array.prototype.join according to spec (22.1.3.13) // Changing ToString(element) with this safe...
toString
identifier_name
app.py
import os from dotenv import load_dotenv dotenv_path = os.path.join(os.path.dirname(__file__), '../.env') load_dotenv(dotenv_path) # pylama:ignore=E402 from flask import Flask from flask.ext.cors import CORS from flask.ext.session import Session from werkzeug.contrib.fixers import ProxyFix from raven.contrib.flask i...
sess.init_app(app) # Register blueprints logger.info("Creating Datastore Blueprint") app.register_blueprint(datastore.create(), url_prefix='/datastore/') logger.info("Creating Package Blueprint") app.register_blueprint(package.create(), url_prefix='/package/') logger.info("Creating Authenti...
"""Create application. """ # Create application app = Flask('service', static_folder=None) app.config['DEBUG'] = True # Respect X-Forwarding-* headers app.wsgi_app = ProxyFix(app.wsgi_app) # CORS support CORS(app, supports_credentials=True) # Exception logging Sentry(app, dsn...
identifier_body
app.py
import os from dotenv import load_dotenv dotenv_path = os.path.join(os.path.dirname(__file__), '../.env') load_dotenv(dotenv_path) # pylama:ignore=E402 from flask import Flask from flask.ext.cors import CORS from flask.ext.session import Session from werkzeug.contrib.fixers import ProxyFix from raven.contrib.flask i...
(): """Create application. """ # Create application app = Flask('service', static_folder=None) app.config['DEBUG'] = True # Respect X-Forwarding-* headers app.wsgi_app = ProxyFix(app.wsgi_app) # CORS support CORS(app, supports_credentials=True) # Exception logging Sentry(...
create
identifier_name
app.py
import os from dotenv import load_dotenv dotenv_path = os.path.join(os.path.dirname(__file__), '../.env') load_dotenv(dotenv_path) # pylama:ignore=E402 from flask import Flask from flask.ext.cors import CORS from flask.ext.session import Session from werkzeug.contrib.fixers import ProxyFix from raven.contrib.flask i...
app.register_blueprint(user.oauth_create(), url_prefix='/oauth/') logger.info("Creating Users Blueprint") app.register_blueprint(user.create(), url_prefix='/user/') logger.info("Creating Search Blueprint") app.register_blueprint(search.create(), url_prefix='/search/') # Return application r...
logger.info("Creating Datastore Blueprint") app.register_blueprint(datastore.create(), url_prefix='/datastore/') logger.info("Creating Package Blueprint") app.register_blueprint(package.create(), url_prefix='/package/') logger.info("Creating Authentication Blueprint")
random_line_split
Unwarper.py
""" Implements a task for unwarping the camera images """ import multiprocessing import cv2 from image_processing.remapping.OCameraModel import OCameraModel class Unwarper(multiprocessing.Process): """ This class implements a task for unwarping the images obtained from a camera with a fisheye lens """ ...
""" # Initialize multiprocessing.Process parent multiprocessing.Process.__init__(self) # Establish queues self._input_queue = input_queue self._output_queue = output_queue # Exit event for stopping process self._exit = multiprocessing.Event() #...
:param output_queue: multiprocessing.Queue containing output data :param width_rescaled: width of the remapped image :param height_rescaled: height of the remapped image :param flip_image: flips the image upside down if set to true :param calibration_file: calibration file (from ...
random_line_split
Unwarper.py
""" Implements a task for unwarping the camera images """ import multiprocessing import cv2 from image_processing.remapping.OCameraModel import OCameraModel class
(multiprocessing.Process): """ This class implements a task for unwarping the images obtained from a camera with a fisheye lens """ def __init__(self, input_queue, output_queue, width_rescaled, height_rescaled, scaling_factor, calibration_file, ...
Unwarper
identifier_name
Unwarper.py
""" Implements a task for unwarping the camera images """ import multiprocessing import cv2 from image_processing.remapping.OCameraModel import OCameraModel class Unwarper(multiprocessing.Process): """ This class implements a task for unwarping the images obtained from a camera with a fisheye lens """ ...
""" Parse data from input queue """ # Get data from queue data = self._input_queue.get() if data is not None: # Parse data from input queue try: self._img = data['camera_image'] except KeyError as e: raise KeyEr...
identifier_body
Unwarper.py
""" Implements a task for unwarping the camera images """ import multiprocessing import cv2 from image_processing.remapping.OCameraModel import OCameraModel class Unwarper(multiprocessing.Process): """ This class implements a task for unwarping the images obtained from a camera with a fisheye lens """ ...
try: self._img = data['camera_image'] except KeyError as e: raise KeyError('Key ' + e.args[0] + ' not found in input data!')
conditional_block
client.py
# -*- coding: utf-8 -*- # author: bambooom '''
sys.setdefaultencoding('utf-8') import requests from bs4 import BeautifulSoup import re HELP = ''' Input h/help/? for help. Input q/quit to quit the process. Input s/sync to sync the diary log. Input lt/ListTags to list all tags. Input st:TAG to set or delete tags Input FLUSH to clear all diary entries. ''' url = "ht...
My Diary Web App - CLI for client ''' import sys reload(sys)
random_line_split
client.py
# -*- coding: utf-8 -*- # author: bambooom ''' My Diary Web App - CLI for client ''' import sys reload(sys) sys.setdefaultencoding('utf-8') import requests from bs4 import BeautifulSoup import re HELP = ''' Input h/help/? for help. Input q/quit to quit the process. Input s/sync to sync the diary log. Input lt/List...
client()
conditional_block
client.py
# -*- coding: utf-8 -*- # author: bambooom ''' My Diary Web App - CLI for client ''' import sys reload(sys) sys.setdefaultencoding('utf-8') import requests from bs4 import BeautifulSoup import re HELP = ''' Input h/help/? for help. Input q/quit to quit the process. Input s/sync to sync the diary log. Input lt/List...
(): response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") log = '' for i in soup.find_all('pre'): log += i.get_text()+'\n' return log def get_log_bytag(tags): response = requests.get(url) soup = BeautifulSoup(response.text,"html.parser") ti=list(soup.find_all('i', class_='etime')) ...
get_log_all
identifier_name
client.py
# -*- coding: utf-8 -*- # author: bambooom ''' My Diary Web App - CLI for client ''' import sys reload(sys) sys.setdefaultencoding('utf-8') import requests from bs4 import BeautifulSoup import re HELP = ''' Input h/help/? for help. Input q/quit to quit the process. Input s/sync to sync the diary log. Input lt/List...
def client(): print HELP tags='' while True: print 'TAG:'+tags message = raw_input('Input>') if message in ['h','help','?']: print HELP elif message in ['s','sync']: get_log_bytag(tags) elif message in ['q','quit']: print 'Bye~' break elif message in ['lt','ListTags']: get_tags() e...
values = {'newdiary':message,'tags':tags} response = requests.post(url, data=values)
identifier_body
pncInlineNotification.js
/* * JBoss, Home of Professional Open Source. * Copyright 2014-2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 ...
(type, header, message, isPersistent) { $log.debug('Inline Notification: %O', arguments); $scope.$applyAsync(function () { $ctrl.notification.type = type; $ctrl.notification.header = header; $ctrl.notification.message = message; $ctrl.notification.persistent = isPersistent; ...
notify
identifier_name
pncInlineNotification.js
/* * JBoss, Home of Professional Open Source. * Copyright 2014-2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 ...
} }; // -------------------- $ctrl.$postLink = function () { notifyInline.registerComponent($ctrl.name, notify); }; function notify(type, header, message, isPersistent) { $log.debug('Inline Notification: %O', arguments); $scope.$applyAsync(function () { $ctrl.noti...
message: null, header: null, persistent: false, remove: function () { $ctrl.notification.visible = false;
random_line_split
pncInlineNotification.js
/* * JBoss, Home of Professional Open Source. * Copyright 2014-2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 ...
} })();
{ $log.debug('Inline Notification: %O', arguments); $scope.$applyAsync(function () { $ctrl.notification.type = type; $ctrl.notification.header = header; $ctrl.notification.message = message; $ctrl.notification.persistent = isPersistent; $ctrl.notification.visible = tr...
identifier_body
RunStatusSelect.tsx
import * as React from "react" import { isArray } from "lodash" import Select from "react-select" import { SelectOption, MultiSelectProps, RunStatus } from "../types" import * as helpers from "../helpers/selectHelpers" const RunStatusSelect: React.FunctionComponent<MultiSelectProps> = props => { let v: SelectOption[...
} export default RunStatusSelect
random_line_split
RunStatusSelect.tsx
import * as React from "react" import { isArray } from "lodash" import Select from "react-select" import { SelectOption, MultiSelectProps, RunStatus } from "../types" import * as helpers from "../helpers/selectHelpers" const RunStatusSelect: React.FunctionComponent<MultiSelectProps> = props => { let v: SelectOption[...
else { v = props.value.map(helpers.stringToSelectOpt) } return ( <Select<SelectOption> value={v} options={[ { label: RunStatus.PENDING, value: RunStatus.PENDING }, { label: RunStatus.QUEUED, value: RunStatus.QUEUED }, { label: RunStatus.RUNNING, value: RunStatus.RUNNING ...
{ v = [helpers.stringToSelectOpt(props.value)] }
conditional_block
gcp_kms_aead.rs
// 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. // //////////////////////////////////////////////////////////////////////////////// //! AEAD functionality via GCP KMS. use hyper::{body:...
fn encrypt( &self, plaintext: &[u8], additional_data: &[u8], ) -> Result<Vec<u8>, tink_core::TinkError> { let req = EncryptRequest { plaintext: Some(base64::encode_config(plaintext, base64::URL_SAFE)), additional_authenticated_data: Some(base64::encode_con...
} } } impl tink_core::Aead for GcpAead {
random_line_split
gcp_kms_aead.rs
// 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. // //////////////////////////////////////////////////////////////////////////////// //! AEAD functionality via GCP KMS. use hyper::{body:...
{ #[serde(rename = "verifiedAdditionalAuthenticatedDataCrc32c")] pub verified_additional_authenticated_data_crc32c: Option<bool>, #[serde(rename = "verifiedPlaintextCrc32c")] pub verified_plaintext_crc32c: Option<bool>, #[serde(rename = "ciphertextCrc32c")] pub ciphertext_crc32c: Option<String>...
EncryptResponse
identifier_name
gcp_kms_aead.rs
// 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. // //////////////////////////////////////////////////////////////////////////////// //! AEAD functionality via GCP KMS. use hyper::{body:...
} fn decrypt( &self, ciphertext: &[u8], additional_data: &[u8], ) -> Result<Vec<u8>, tink_core::TinkError> { let req = DecryptRequest { ciphertext: Some(base64::encode_config(ciphertext, base64::URL_SAFE)), additional_authenticated_data: Some(base64:...
{ let req = EncryptRequest { plaintext: Some(base64::encode_config(plaintext, base64::URL_SAFE)), additional_authenticated_data: Some(base64::encode_config( additional_data, base64::URL_SAFE, )), ..EncryptRequest::default() ...
identifier_body
Gruntfile.js
var pg = require("pg"); var async = require("async"); var fs = require("fs"); function getEnvironmentVariables(filepath, existingVariables)
else { console.log("ERROR", filepath, "not found"); // This should only happen on Travis CI if (process.env.DATABASE_URL) { vars.DATABASE_URL = process.env.DATABASE_URL; } } return vars; } module.exports = function (grunt) { var packageFile = grunt.file...
{ var vars = {}; // Copy over existing variables for (var key in existingVariables) { vars[key] = existingVariables[key]; } if (fs.existsSync(filepath)) { var fileOfVariables = fs.readFileSync(filepath, "utf8").split("\n"); // For every line in the .env file, parse ...
identifier_body
Gruntfile.js
var pg = require("pg"); var async = require("async"); var fs = require("fs"); function getEnvironmentVariables(filepath, existingVariables) { var vars = {}; // Copy over existing variables for (var key in existingVariables) { vars[key] = existingVariables[key]; } if (fs.existsSync(filepath...
}); } else { console.log("ERROR", filepath, "not found"); // This should only happen on Travis CI if (process.env.DATABASE_URL) { vars.DATABASE_URL = process.env.DATABASE_URL; } } return vars; } module.exports = function (grunt) { var packag...
{ vars[key.replace(" ", "")] = value; }
conditional_block
Gruntfile.js
var pg = require("pg"); var async = require("async"); var fs = require("fs"); function
(filepath, existingVariables) { var vars = {}; // Copy over existing variables for (var key in existingVariables) { vars[key] = existingVariables[key]; } if (fs.existsSync(filepath)) { var fileOfVariables = fs.readFileSync(filepath, "utf8").split("\n"); // For every...
getEnvironmentVariables
identifier_name
Gruntfile.js
var pg = require("pg"); var async = require("async"); var fs = require("fs"); function getEnvironmentVariables(filepath, existingVariables) { var vars = {}; // Copy over existing variables for (var key in existingVariables) { vars[key] = existingVariables[key]; } if (fs.existsSync(filepath...
var callback = this.async(); // TODO: check that the tables already exist before creating them... var config = require("./config"); config = getEnvironmentVariables(".env", config); var scripts = { create: fs.readFileSync("databases/create-tables.sql", "utf8"), ...
grunt.registerTask("default", ["jshint", "jade", "clean"]); grunt.registerTask("postgres:init", "Used to run any SQL scripts for a Postgres database.", function () {
random_line_split
repository.sage.ts
/// <reference path="../_references.d.ts" /> interface sage { id: number; name: string; username: string; email: string; dateOfBirth: Date; sayings?: saying[]; } interface repositorySage { getAll: () => ng.IPromise<sage[]>; getById: (id: number, forceRemote?: boolean) => ng.IPromise<sag...
() { return $http.get<sage[]>(rootUrl).then(response => { var sages = response.data; log(sages.length + " Sages loaded"); return sages; }); } function getById(id: number, forceRemote?: boolean) { var sage: sage; ...
getAll
identifier_name
repository.sage.ts
/// <reference path="../_references.d.ts" /> interface sage { id: number; name: string; username: string; email: string; dateOfBirth: Date; sayings?: saying[]; } interface repositorySage { getAll: () => ng.IPromise<sage[]>; getById: (id: number, forceRemote?: boolean) => ng.IPromise<sag...
function save(sage: sage) { return $http.post<void>(rootUrl, sage).then(response => { log("Sage " + sage.name + " [id: " + sage.id + "] saved"); return response.data; }, errorReason => $q.reject(errorReason.data)); } } })();
{ return $http.delete<void>(rootUrl + "/" + id).then(response => { log("Sage [id: " + id + "] removed"); return response.data; }, errorReason => $q.reject(errorReason.data)); }
identifier_body
repository.sage.ts
/// <reference path="../_references.d.ts" /> interface sage { id: number; name: string; username: string; email: string; dateOfBirth: Date; sayings?: saying[]; } interface repositorySage { getAll: () => ng.IPromise<sage[]>; getById: (id: number, forceRemote?: boolean) => ng.IPromise<sag...
} return $http.get<sage>(rootUrl + "/" + id).then(response => { sage = response.data; cache[sage.id] = sage; log("Sage " + sage.name + " [id: " + sage.id + "] loaded"); return sage; }); } function remo...
{ log("Sage " + sage.name + " [id: " + sage.id + "] loaded from cache"); return $q.when(sage); }
conditional_block
repository.sage.ts
/// <reference path="../_references.d.ts" /> interface sage { id: number; name: string; username: string; email: string; dateOfBirth: Date; sayings?: saying[]; } interface repositorySage { getAll: () => ng.IPromise<sage[]>; getById: (id: number, forceRemote?: boolean) => ng.IPromise<sag...
}); } function remove(id: number) { return $http.delete<void>(rootUrl + "/" + id).then(response => { log("Sage [id: " + id + "] removed"); return response.data; }, errorReason => $q.reject(errorReason.data)); } funct...
return $http.get<sage>(rootUrl + "/" + id).then(response => { sage = response.data; cache[sage.id] = sage; log("Sage " + sage.name + " [id: " + sage.id + "] loaded"); return sage;
random_line_split
auto_sync_test.ts
import { decodeBinary, routeMqttData, asTaggedResource, handleCreate, handleUpdate, handleCreateOrUpdate } from "../auto_sync"; import { SpecialStatus, TaggedSequence } from "farmbot"; import { Actions } from "../../constants"; import { fakeState } from "../../__test_support__/fake_state"; import { GetState...
expect(results.id).toEqual(1); expect(results.kind).toEqual("Sequence"); expect(results.body).toEqual(fake1.body); }); });
{ fail(); return; }
conditional_block
auto_sync_test.ts
import { decodeBinary, routeMqttData, asTaggedResource, handleCreate, handleUpdate, handleCreateOrUpdate } from "../auto_sync"; import { SpecialStatus, TaggedSequence } from "farmbot"; import { Actions } from "../../constants"; import { fakeState } from "../../__test_support__/fake_state"; import { GetState...
const fakePayload: SyncPayload = { args: { label: "label1" }, body: { foo: "bar" } }; const payload = (): UpdateMqttData<TaggedSequence> => ({ status: "UPDATE", kind: "Sequence", id: 5, body: {} as TaggedSequence["body"], sessionId: "wow" }); describe("handleCreateOrUpdate", () => { it("creates new ...
{ return Buffer.from(JSON.stringify(input), "utf8"); }
identifier_body
auto_sync_test.ts
import { decodeBinary, routeMqttData, asTaggedResource, handleCreate, handleUpdate, handleCreateOrUpdate } from "../auto_sync"; import { SpecialStatus, TaggedSequence } from "farmbot"; import { Actions } from "../../constants"; import { fakeState } from "../../__test_support__/fake_state"; import { GetState...
(input: object): Buffer { return Buffer.from(JSON.stringify(input), "utf8"); } const fakePayload: SyncPayload = { args: { label: "label1" }, body: { foo: "bar" } }; const payload = (): UpdateMqttData<TaggedSequence> => ({ status: "UPDATE", kind: "Sequence", id: 5, body: {} as TaggedSequence["body"], s...
toBinary
identifier_name
auto_sync_test.ts
import { decodeBinary, routeMqttData, asTaggedResource, handleCreate, handleUpdate, handleCreateOrUpdate } from "../auto_sync"; import { SpecialStatus, TaggedSequence } from "farmbot"; import { Actions } from "../../constants"; import { fakeState } from "../../__test_support__/fake_state"; import { GetState...
expect(results.status).toEqual("SKIP"); }); it("handles well formed deletion data", () => { const results = routeMqttData("bot/device_9/sync/Sequence/1", toBinary({})); expect(results.status).toEqual("DELETE"); if (results.status !== "DELETE") { fail(); return; } expect(results....
}); it("tosses out resources that the FE does not care about", () => { const results = routeMqttData("bot/device_9/sync/DeviceSerialNumber/1", toBinary({}));
random_line_split
AppContainer.js
/** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import StyleSheet from '../StyleSheet'; import View from '../View'; import React, { crea...
(props) { var children = props.children, WrapperComponent = props.WrapperComponent; var innerView = React.createElement(View, { children: children, key: 1, pointerEvents: "box-none", style: styles.appContainer }); if (WrapperComponent) { innerView = React.createElement(WrapperComponen...
AppContainer
identifier_name
AppContainer.js
/** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import StyleSheet from '../StyleSheet'; import View from '../View'; import React, { crea...
flex: 1 } });
appContainer: {
random_line_split
AppContainer.js
/** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import StyleSheet from '../StyleSheet'; import View from '../View'; import React, { crea...
} var styles = StyleSheet.create({ appContainer: { flex: 1 } });
{ var children = props.children, WrapperComponent = props.WrapperComponent; var innerView = React.createElement(View, { children: children, key: 1, pointerEvents: "box-none", style: styles.appContainer }); if (WrapperComponent) { innerView = React.createElement(WrapperComponent, null,...
identifier_body
AppContainer.js
/** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import StyleSheet from '../StyleSheet'; import View from '../View'; import React, { crea...
return React.createElement(RootTagContext.Provider, { value: props.rootTag }, React.createElement(View, { pointerEvents: "box-none", style: styles.appContainer }, innerView)); } var styles = StyleSheet.create({ appContainer: { flex: 1 } });
{ innerView = React.createElement(WrapperComponent, null, innerView); }
conditional_block
__init__.py
# emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: """ACE -- Automated Coordinate Extraction. """ __all__ = ["config", "database", "datatable", "exporter", "set_logging_level", "scrape", "sources", "tableparser", "tests", "__version__"] import log...
# Set up logger logger = logging.getLogger("ace") _setup_logger(logger)
console = logging.StreamHandler(sys.stdout) console.setFormatter(logging.Formatter("%(levelname)-6s %(module)-7s %(message)s")) logger.addHandler(console) set_logging_level()
identifier_body
__init__.py
# emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: """ACE -- Automated Coordinate Extraction. """ __all__ = ["config", "database", "datatable", "exporter", "set_logging_level", "scrape", "sources", "tableparser", "tests", "__version__"] import log...
logger.setLevel(getattr(logging, level.upper())) return logger.getEffectiveLevel() def _setup_logger(logger): # Basic logging setup console = logging.StreamHandler(sys.stdout) console.setFormatter(logging.Formatter("%(levelname)-6s %(module)-7s %(message)s")) logger.addHandler(console) set...
level = os.environ.get('ACE_LOGLEVEL', 'warn')
conditional_block
__init__.py
# emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: """ACE -- Automated Coordinate Extraction. """ __all__ = ["config", "database", "datatable", "exporter", "set_logging_level", "scrape", "sources", "tableparser", "tests", "__version__"] import log...
(level=None): """Set package-wide logging level Args level : Logging level constant from logging module (warning, error, info, etc.) """ if level is None: level = os.environ.get('ACE_LOGLEVEL', 'warn') logger.setLevel(getattr(logging, level.upper())) return logger.getEffectiveLe...
set_logging_level
identifier_name
__init__.py
# emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: """ACE -- Automated Coordinate Extraction. """ __all__ = ["config", "database", "datatable", "exporter", "set_logging_level", "scrape", "sources", "tableparser", "tests", "__version__"] import log...
console.setFormatter(logging.Formatter("%(levelname)-6s %(module)-7s %(message)s")) logger.addHandler(console) set_logging_level() # Set up logger logger = logging.getLogger("ace") _setup_logger(logger)
return logger.getEffectiveLevel() def _setup_logger(logger): # Basic logging setup console = logging.StreamHandler(sys.stdout)
random_line_split
class_mock.js
var class_mock = [ [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "MOCK_METHOD0", "class_mock.html#ae710f23cafb1a2f17772e8805d6312d2", null ], [ "MOCK_METHOD1", "class_mock.html#ada59eea6991953353f332e3ea1e7...
[ "MOCK_METHOD1", "class_mock.html#ae2379efbc030f1adf8b032be3bdf081d", null ], [ "MOCK_METHOD1", "class_mock.html#a3fd62026610c5d3d3aeaaf2ade3e18aa", null ], [ "MOCK_METHOD1", "class_mock.html#a890668928abcd28d4d39df164e7b6dd8", null ], [ "MOCK_METHOD1", "class_mock.html#a50e2bda4375a59bb89fd5652bd33eb0...
random_line_split
ctl_gateway.rs
//! Utilities for generating and reading the self-signed certificate for use with the control //! gateway. use crate::{crypto::keys::NamedRevision, tls::rustls_wrapper::{self, Error as RustlsReadersError}}; use rcgen::{Certificate as RcgenCertificate, Certifica...
(path: impl AsRef<Path>) -> Result<PrivateKey, Error> { let path = get_last_path(path, &format!("{}-*.{}", NAME_PREFIX, KEY_EXTENSION))?; Ok(rustls_wrapper::private_key_from_file(&path)?) } pub fn latest_root_certificate_store(path: impl AsRef<Path>) -> Result<RootCertStore, Error> { let path = get_last_pa...
latest_private_key
identifier_name
ctl_gateway.rs
//! Utilities for generating and reading the self-signed certificate for use with the control //! gateway. use crate::{crypto::keys::NamedRevision, tls::rustls_wrapper::{self, Error as RustlsReadersError}}; use rcgen::{Certificate as RcgenCertificate,
use rustls::{Certificate, PrivateKey, RootCertStore}; use std::{fs::{self, File}, io::{Error as IoError, Write}, path::{Path, PathBuf}}; use thiserror::Error; use webpki::DnsNameRef; const NAME_PREFIX: &str = "ctl-gateway"; co...
CertificateParams, DistinguishedName, DnType, RcgenError, PKCS_ECDSA_P256_SHA256};
random_line_split
ctl_gateway.rs
//! Utilities for generating and reading the self-signed certificate for use with the control //! gateway. use crate::{crypto::keys::NamedRevision, tls::rustls_wrapper::{self, Error as RustlsReadersError}}; use rcgen::{Certificate as RcgenCertificate, Certifica...
pub fn latest_certificates(path: impl AsRef<Path>) -> Result<Vec<Certificate>, Error> { let path = get_last_path(path, &format!("{}-*.{}", NAME_PREFIX, CRT_EXTENSION))?; Ok(rustls_wrapper::certificates_from_file(&path)?) } pub fn latest_private_key(path: impl AsRef<Path>) -> Result<PrivateKey, Error> { l...
{ let pattern = search_directory.as_ref().join(file_pattern); let pattern = pattern.to_string_lossy(); glob::glob(&pattern).expect("valid pattern") .filter_map(std::result::Result::ok) .filter(|p| p.metadata().map(|m| m.is_file()).unwrap_or(false)) ...
identifier_body
MainView.js
var Observable = require("FuseJS/Observable"); function Task(title){ var self = this; this.title = title; this.checked = Observable(false); this.hidden = Observable(function(){ if (currentTab.value == "all"){ return false; } else if (currentTab.value == "active"){ return self.checked.value ? true : fa...
() { currentTab.value = "completed"; } module.exports = { todoList: todoList, titleInput: titleInput, currentTab: currentTab, remainingText: remainingText, canClearCompleted: canClearCompleted, addItem: addItem, deleteItem: deleteItem, toggleAll: toggleAll, toggleItem: toggleItem, clearCompleted: clearCompl...
showCompleted
identifier_name
MainView.js
var Observable = require("FuseJS/Observable"); function Task(title){ var self = this; this.title = title; this.checked = Observable(false); this.hidden = Observable(function(){ if (currentTab.value == "all"){ return false; } else if (currentTab.value == "active"){ return self.checked.value ? true : fa...
function toggleItem(arg) { arg.data.checked.value = !arg.data.checked.value; } function clearCompleted() { todoList.removeWhere(function(x) { return x.checked.value; }); } function showAll() { currentTab.value = "all"; } function showActive() { currentTab.value = "active"; } function showCompleted() { currentT...
todoList.forEach(function(x){ x.checked.value = (remaining == 0) ? false : true; }); }
random_line_split
MainView.js
var Observable = require("FuseJS/Observable"); function Task(title){ var self = this; this.title = title; this.checked = Observable(false); this.hidden = Observable(function(){ if (currentTab.value == "all"){ return false; } else if (currentTab.value == "active")
else { return self.checked.value ? false : true; } }); } var todoList = Observable(); var titleInput = Observable(""); var currentTab = Observable("all"); var remainingCount = todoList.count(function(x){ return x.checked.not(); }); var remainingText = remainingCount.map(function(x){ return x + " " + ((x =...
{ return self.checked.value ? true : false; }
conditional_block
MainView.js
var Observable = require("FuseJS/Observable"); function Task(title){ var self = this; this.title = title; this.checked = Observable(false); this.hidden = Observable(function(){ if (currentTab.value == "all"){ return false; } else if (currentTab.value == "active"){ return self.checked.value ? true : fa...
module.exports = { todoList: todoList, titleInput: titleInput, currentTab: currentTab, remainingText: remainingText, canClearCompleted: canClearCompleted, addItem: addItem, deleteItem: deleteItem, toggleAll: toggleAll, toggleItem: toggleItem, clearCompleted: clearCompleted, showAll: showAll, showActive: s...
{ currentTab.value = "completed"; }
identifier_body
find.js
define('lodash/collection/find', ['exports', 'lodash/internal/baseEach', 'lodash/internal/createFind'], function (exports, _lodashInternalBaseEach, _lodashInternalCreateFind) { 'use strict'; /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predic...
* // => 'pebbles' * * // using the `_.matchesProperty` callback shorthand * _.result(_.find(users, 'active', false), 'user'); * // => 'fred' * * // using the `_.property` callback shorthand * _.result(_.find(users, 'active'), 'user'); * // => 'barney' */ var find = (0, _lodashInternalCre...
* _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
random_line_split
fbclient.js
, uiSideMessages: ".fb-mod_side_messages em" , uiSideNotifications: ".fb-mod_side_notifications em" , uiBodyLoader: ".fb-mod_body_loader" }; FBClient.init = function() { // DOC.body.innerHTML += '<div id="fb-root"></div>'; var that = this, $this = $(UI_CONF.uiMod); /* ui controller ...
body.currentStyle.backgroundImage == "none") { body.style.backgroundImage = (DOC.domain.indexOf("https:") == 0) ? 'url(https:///)' : 'url(about:blank)'; } } } FBClient.clickHandle = function($el, type, panel) { var that = this, fold = that.status.fo
conditional_block
fbclient.js
-mod_tip" , uiSideHome: ".fb-mod_side_home" , uiSideFriend: ".fb-mod_side_friend em" , uiSideMessages: ".fb-mod_side_messages em" , uiSideNotifications: ".fb-mod_side_notifications em" , uiBodyLoader: ".fb-mod_body_loader" }; FBClient.init = function() { // DOC.body.innerHTML += '<div id="fb-root"></div>';...
, textareaSubmit: $this.find(UI_CONF.uiTextareaSubmit) , btnSubmit: $this.find(UI_CONF.uiBtnSubmit) , body: $this.find(UI_CONF.uiBody) , tip: $this.find(UI_CONF.uiTip) , sideHome: $this.find(UI_CONF.uiSideHome) , sideFriend: $this.find(UI_CONF.uiSideFriend) , side...
, list: $this.find(UI_CONF.uiList) , usrinfo: $this.find(UI_CONF.uiUsrinfo) , avatar: $this.find(UI_CONF.uiAvatar)
random_line_split
receive-file-and-sender-disconnect-while-pending.py
import dbus from saluttest import exec_test from file_transfer_helper import ReceiveFileTest import constants as cs class ReceiveFileAndSenderDisconnectWhilePendingTest(ReceiveFileTest): def accept_file(self): # The sender of the file disconnects self.outbound.transport.loseConnection() s...
test = ReceiveFileAndSenderDisconnectWhilePendingTest() exec_test(test.test)
conditional_block
receive-file-and-sender-disconnect-while-pending.py
import dbus from saluttest import exec_test from file_transfer_helper import ReceiveFileTest import constants as cs class ReceiveFileAndSenderDisconnectWhilePendingTest(ReceiveFileTest): def
(self): # The sender of the file disconnects self.outbound.transport.loseConnection() self.contact_service.stop() self.q.expect('dbus-signal', signal='FileTransferStateChanged') # We can't accept the transfer now try: self.ft_channel.AcceptFile(cs.SOCKET_ADD...
accept_file
identifier_name
receive-file-and-sender-disconnect-while-pending.py
import dbus from saluttest import exec_test from file_transfer_helper import ReceiveFileTest import constants as cs class ReceiveFileAndSenderDisconnectWhilePendingTest(ReceiveFileTest):
if __name__ == '__main__': test = ReceiveFileAndSenderDisconnectWhilePendingTest() exec_test(test.test)
def accept_file(self): # The sender of the file disconnects self.outbound.transport.loseConnection() self.contact_service.stop() self.q.expect('dbus-signal', signal='FileTransferStateChanged') # We can't accept the transfer now try: self.ft_channel.AcceptFil...
identifier_body
receive-file-and-sender-disconnect-while-pending.py
import dbus from saluttest import exec_test from file_transfer_helper import ReceiveFileTest import constants as cs class ReceiveFileAndSenderDisconnectWhilePendingTest(ReceiveFileTest): def accept_file(self): # The sender of the file disconnects self.outbound.transport.loseConnection() s...
if __name__ == '__main__': test = ReceiveFileAndSenderDisconnectWhilePendingTest() exec_test(test.test)
# stop the test return True
random_line_split
structured_value.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
super(StructuredValue, self).__init__(**kwargs) self._type = 'StructuredValue'
identifier_body
structured_value.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
this object. :vartype url: str :ivar image: An image of the item. :vartype image: ~azure.cognitiveservices.search.visualsearch.models.ImageObject :ivar description: A short description of the item. :vartype description: str :ivar alternate_name: An alias for the item. :vartype alte...
:vartype web_search_url: str :ivar name: The name of the thing represented by this object. :vartype name: str :ivar url: The URL to get more information about the thing represented by
random_line_split
structured_value.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(self, **kwargs): super(StructuredValue, self).__init__(**kwargs) self._type = 'StructuredValue'
__init__
identifier_name
content_type.rs
use std::{ error::Error as StdError, fmt::{self, Display}, str::FromStr, }; use mime::Mime; use super::{Header, HeaderName}; use crate::BoxError; /// `Content-Type` of the body
/// /// [mime type]: https://www.iana.org/assignments/media-types/media-types.xhtml #[derive(Debug, Clone, PartialEq, Eq)] pub struct ContentType(Mime); impl ContentType { /// A `ContentType` of type `text/plain; charset=utf-8` /// /// Indicates that the body is in utf-8 encoded plain text. pub const T...
/// /// This struct can represent any valid [mime type], which can be parsed via /// [`ContentType::parse`]. Constants are provided for the most-used mime-types. /// /// Defined in [RFC2045](https://tools.ietf.org/html/rfc2045#section-5)
random_line_split
content_type.rs
use std::{ error::Error as StdError, fmt::{self, Display}, str::FromStr, }; use mime::Mime; use super::{Header, HeaderName}; use crate::BoxError; /// `Content-Type` of the body /// /// This struct can represent any valid [mime type], which can be parsed via /// [`ContentType::parse`]. Constants are provi...
<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct ContentTypeVisitor; impl<'de> Visitor<'de> for ContentTypeVisitor { type Value = ContentType; // The error message which states what the Visitor expec...
deserialize
identifier_name
decoratelayerloading.js
goog.provide('ngeo.DecorateLayerLoading'); goog.require('goog.asserts'); goog.require('ngeo'); /** * Provides a function that adds a 'loading 'property (using * `Object.defineProperty`) to an ol.layer.Group or a layer with * an ol.source.Tile or an ol.source.Image source. * This property is true when the layer i...
} /** * @function * @param {ol.layer.Base} layer Layer * @private */ function decrement_(layer) { let load_count = /** @type {number} */ (layer.get('load_count')); const parent = /** @type {ol.layer.Base} */ (layer.get('parent_group')); layer.set('load_count', --load_count, true); if...
{ increment_(parent); }
conditional_block
decoratelayerloading.js
goog.provide('ngeo.DecorateLayerLoading'); goog.require('goog.asserts'); goog.require('ngeo'); /** * Provides a function that adds a 'loading 'property (using * `Object.defineProperty`) to an ol.layer.Group or a layer with * an ol.source.Tile or an ol.source.Image source. * This property is true when the layer i...
/** * @function * @param {ol.layer.Base} layer Layer * @private */ function decrement_(layer) { let load_count = /** @type {number} */ (layer.get('load_count')); const parent = /** @type {ol.layer.Base} */ (layer.get('parent_group')); layer.set('load_count', --load_count, true); if (pa...
{ let load_count = /** @type {number} */ (layer.get('load_count')); const parent = /** @type {ol.layer.Base} */ (layer.get('parent_group')); layer.set('load_count', ++load_count, true); if (parent) { increment_(parent); } }
identifier_body
decoratelayerloading.js
goog.provide('ngeo.DecorateLayerLoading'); goog.require('goog.asserts'); goog.require('ngeo'); /** * Provides a function that adds a 'loading 'property (using * `Object.defineProperty`) to an ol.layer.Group or a layer with * an ol.source.Tile or an ol.source.Image source. * This property is true when the layer i...
(layer) { let load_count = /** @type {number} */ (layer.get('load_count')); const parent = /** @type {ol.layer.Base} */ (layer.get('parent_group')); layer.set('load_count', ++load_count, true); if (parent) { increment_(parent); } } /** * @function * @param {ol.layer.Base} layer Laye...
increment_
identifier_name
decoratelayerloading.js
goog.provide('ngeo.DecorateLayerLoading'); goog.require('goog.asserts'); goog.require('ngeo'); /** * Provides a function that adds a 'loading 'property (using * `Object.defineProperty`) to an ol.layer.Group or a layer with * an ol.source.Tile or an ol.source.Image source. * This property is true when the layer i...
/** * @function * @param {ol.layer.Base} layer Layer * @private */ function decrement_(layer) { let load_count = /** @type {number} */ (layer.get('load_count')); const parent = /** @type {ol.layer.Base} */ (layer.get('parent_group')); layer.set('load_count', --load_count, true); if (par...
if (parent) { increment_(parent); } }
random_line_split
index.d.ts
// Support for AMD require and CommonJS declare module 'angular-ui-router' { // Since angular-ui-router adds providers for a bunch of // injectable dependencies, it doesn't really return any // actual data except the plain string 'ui.router'. // // As such, I don't think anybody will ever use the ...
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/bf263437d0c2354f1599e6951d3d27c0508b0491/angular-ui-router/angular-ui-router.d.ts // Type definitions for Angular JS 1.1.5+ (ui.router module) // Project: https://github.com/angular-ui/ui-router // Definitions by: Michel Salib <https://github....
random_line_split
FancyMenuItem.ts
import { ItemTypes } from '@ephox/alloy';
import { UiFactoryBackstage } from 'tinymce/themes/silver/backstage/Backstage'; import { renderColorSwatchItem } from './ColorSwatchItem'; import { renderInsertTableMenuItem } from './InsertTableMenuItem'; const fancyMenuItems: Record<keyof Menu.FancyActionArgsMap, (mi: Menu.FancyMenuItem, bs: UiFactoryBackstage) =>...
import { Menu } from '@ephox/bridge'; import { Obj, Optional } from '@ephox/katamari';
random_line_split
journal.effects.ts
import { of } from 'rxjs'; import { catchError, map, switchMap } from 'rxjs/operators'; import { PostService } from 'src/app/services/post.service'; import { Injectable } from '@angular/core'; import { Actions, Effect, ofType } from '@ngrx/effects'; import { JournalActionsType, LoadPosts, LoadPostsFailure, LoadPo...
(private actions: Actions, private service: PostService) {} }
constructor
identifier_name
journal.effects.ts
import { of } from 'rxjs'; import { catchError, map, switchMap } from 'rxjs/operators'; import { PostService } from 'src/app/services/post.service'; import { Injectable } from '@angular/core'; import { Actions, Effect, ofType } from '@ngrx/effects'; import {
JournalActionsType, LoadPosts, LoadPostsFailure, LoadPostsSuccess, LoadSinglePost, LoadSinglePostFailure, LoadSinglePostSuccess } from './journal.actions'; @Injectable() export class JournalEffects { @Effect() public loadPosts$ = this.actions.pipe( ofType(JournalActionsType.LoadPosts), switchMap((a...
random_line_split
waybackmachine.py
"""Define related tools for web.archive.org (aka Wayback Machine).""" import logging from threading import Thread from datetime import date from urllib.parse import urlparse from regex import compile as regex_compile from requests import ConnectionError as RequestsConnectionError from lib.commons import dict_to_sfn_...
journal = find_journal(html) if journal: d['journal'] = journal d['cite_type'] = 'journal' else: d['cite_type'] = 'web' d['website'] = find_site_name( html, html_title, url, authors, hometitle_list, home_title_thread ) d['title'] = find_title( ...
d['authors'] = authors
conditional_block
waybackmachine.py
"""Define related tools for web.archive.org (aka Wayback Machine).""" import logging from threading import Thread from datetime import date from urllib.parse import urlparse from regex import compile as regex_compile from requests import ConnectionError as RequestsConnectionError from lib.commons import dict_to_sfn_...
# means that the content probably has changed and the original data # cannot be trusted. archive_dict['url-status'] = 'unfit' else: archive_dict['url-status'] = 'dead' if archive_dict['website'] == 'Wayback Machine': archive_dict['website'] = ( url...
# and original title is the same as archive title. Otherwise it
random_line_split
waybackmachine.py
"""Define related tools for web.archive.org (aka Wayback Machine).""" import logging from threading import Thread from datetime import date from urllib.parse import urlparse from regex import compile as regex_compile from requests import ConnectionError as RequestsConnectionError from lib.commons import dict_to_sfn_...
( archive_url: str, date_format: str = '%Y-%m-%d' ) -> tuple: """Create the response namedtuple.""" m = URL_FULLMATCH(archive_url) if not m: # Could not parse the archive_url. Treat as an ordinary URL. return urls_scr(archive_url, date_format) archive_year, archive_month, archive_day...
waybackmachine_scr
identifier_name
waybackmachine.py
"""Define related tools for web.archive.org (aka Wayback Machine).""" import logging from threading import Thread from datetime import date from urllib.parse import urlparse from regex import compile as regex_compile from requests import ConnectionError as RequestsConnectionError from lib.commons import dict_to_sfn_...
archive_dict['archive-url'] = archive_url archive_dict['archive-date'] = date( int(archive_year), int(archive_month), int(archive_day) ) thread.join() if original_dict: # The original_process has been successful if ( original_dict['title'] == archive_dict['title']...
"""Create the response namedtuple.""" m = URL_FULLMATCH(archive_url) if not m: # Could not parse the archive_url. Treat as an ordinary URL. return urls_scr(archive_url, date_format) archive_year, archive_month, archive_day, original_url = \ m.groups() original_dict = {} threa...
identifier_body
PRB.py
__author__ = 'shenojia' import sys sys.path.insert(0, '.') sys.path.insert(0, '..') from R12_36xxx.HighLayer import * from R12_36211.REG import REG from math import floor from matplotlib.path import Path from matplotlib.patches import PathPatch from xlsxwriter.worksheet import Worksheet class PRB: """ Resource ...
def appendReg(self, reg:REG): self.regs.append(reg) def __repr__(self): return 'prb({})'.format(self.n__PRB) def _initPatch(self, n__s:int, subFrameTypeName:str): """ generate path patch for this PRB :param n__s: :param subFrameTypeName: :return: ...
self.w = w #width in symbols self.n__s = n__s self.prbFormat = cell.add_format({"bottom":1, "top":1, "left":1, "right":1}) self.patch, self.codes, self.vertices = self._initPatch(n__s, subFrameTypeName)
random_line_split
PRB.py
__author__ = 'shenojia' import sys sys.path.insert(0, '.') sys.path.insert(0, '..') from R12_36xxx.HighLayer import * from R12_36211.REG import REG from math import floor from matplotlib.path import Path from matplotlib.patches import PathPatch from xlsxwriter.worksheet import Worksheet class PRB: """ Resource ...
def _initPatch(self, n__s:int, subFrameTypeName:str): """ generate path patch for this PRB :param n__s: :param subFrameTypeName: :return: """ vertices = [] codes = [] bottom = 0 left = 0 width = 0 height = 0 if...
return 'prb({})'.format(self.n__PRB)
identifier_body
PRB.py
__author__ = 'shenojia' import sys sys.path.insert(0, '.') sys.path.insert(0, '..') from R12_36xxx.HighLayer import * from R12_36211.REG import REG from math import floor from matplotlib.path import Path from matplotlib.patches import PathPatch from xlsxwriter.worksheet import Worksheet class PRB: """ Resource ...
if n__s %1 == 1: bottom = self.n__PRB * conf.N__sc___RB_UL left = conf.N__symb___UpPTS width = conf.N__symb___UL - conf.N__symb___DwPTS height = conf.N__sc___RB_UL codes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY] v...
bottom = self.n__PRB * conf.N__sc___RB_DL left = 0 width = conf.N__symb___DwPTS height = conf.N__sc___RB_DL
conditional_block
PRB.py
__author__ = 'shenojia' import sys sys.path.insert(0, '.') sys.path.insert(0, '..') from R12_36xxx.HighLayer import * from R12_36211.REG import REG from math import floor from matplotlib.path import Path from matplotlib.patches import PathPatch from xlsxwriter.worksheet import Worksheet class PRB: """ Resource ...
(self): return 'prb({})'.format(self.n__PRB) def _initPatch(self, n__s:int, subFrameTypeName:str): """ generate path patch for this PRB :param n__s: :param subFrameTypeName: :return: """ vertices = [] codes = [] bottom = 0 left...
__repr__
identifier_name
yield.rs
// -*- rust -*- // 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 // ...
task::yield(); error!("2"); task::yield(); error!("3"); result.unwrap().recv(); } fn child() { error!("4"); task::yield(); error!("5"); task::yield(); error!("6"); }
builder.future_result(|r| { result = Some(r); }); builder.spawn(child); error!("1");
random_line_split
yield.rs
// -*- rust -*- // 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 // ...
() { error!("4"); task::yield(); error!("5"); task::yield(); error!("6"); }
child
identifier_name
yield.rs
// -*- rust -*- // 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 // ...
fn child() { error!("4"); task::yield(); error!("5"); task::yield(); error!("6"); }
{ let mut result = None; let mut builder = task::task(); builder.future_result(|r| { result = Some(r); }); builder.spawn(child); error!("1"); task::yield(); error!("2"); task::yield(); error!("3"); result.unwrap().recv(); }
identifier_body
permission.ts
// Imports import { IPermissionRepository } from './../permission'; import { BaseRepository } from './base'; // Imports models import { Permission } from './../../entities/permission'; export class PermissionRepository extends BaseRepository implements IPermissionRepository { constructor(host: string, username: s...
public async create(permission: Permission, clientId: string): Promise<boolean> { const client: any = await BaseRepository.models.Client.find({ where: { key: clientId, }, }); await BaseRepository.models.Permission.create({ clientId: cli...
{ super(host, username, password); }
identifier_body
permission.ts
// Imports import { IPermissionRepository } from './../permission'; import { BaseRepository } from './base'; // Imports models import { Permission } from './../../entities/permission'; export class PermissionRepository extends BaseRepository implements IPermissionRepository { constructor(host: string, username: s...
return new Permission(permission.name); } public async listByClientId(clientId: string): Promise<Permission[]> { const permissions: any[] = await BaseRepository.models.Permission.findAll({ include: [ { model: BaseRepository.models.Client, required: false }, ...
{ return null; }
conditional_block
permission.ts
// Imports import { IPermissionRepository } from './../permission'; import { BaseRepository } from './base'; // Imports models import { Permission } from './../../entities/permission'; export class PermissionRepository extends BaseRepository implements IPermissionRepository { constructor(host: string, username: s...
(name: string, clientId: string): Promise<Permission> { const permission: any = await BaseRepository.models.Permission.find({ include: [ { model: BaseRepository.models.Client, required: false }, ], where: { '$client.key$': clientId, ...
find
identifier_name
permission.ts
// Imports import { IPermissionRepository } from './../permission'; import { BaseRepository } from './base'; // Imports models import { Permission } from './../../entities/permission'; export class PermissionRepository extends BaseRepository implements IPermissionRepository { constructor(host: string, username: s...
return true; } public async find(name: string, clientId: string): Promise<Permission> { const permission: any = await BaseRepository.models.Permission.find({ include: [ { model: BaseRepository.models.Client, required: false }, ], where: { ...
});
random_line_split
device.rs
use std::collections::HashMap; use std::fmt; use std::result::Result; use super::action::Action; use super::attribute::Attribute; use super::error::DeviceError; pub enum Member { Attribute(Box<dyn Attribute>), Action(Box<dyn Action>), } impl fmt::Debug for Member { fn fmt(&self, fmt: &mut fmt::Formatter)...
}
{ self.members.iter() }
identifier_body
device.rs
use std::collections::HashMap; use std::fmt; use std::result::Result; use super::action::Action; use super::attribute::Attribute; use super::error::DeviceError; pub enum Member { Attribute(Box<dyn Attribute>), Action(Box<dyn Action>), } impl fmt::Debug for Member { fn fmt(&self, fmt: &mut fmt::Formatter)...
} pub fn iter(&self) -> std::collections::hash_map::Iter<String, Member> { self.members.iter() } }
{ Err(DeviceError::PathNotFound(path)) }
conditional_block
device.rs
use std::collections::HashMap; use std::fmt; use std::result::Result; use super::action::Action; use super::attribute::Attribute; use super::error::DeviceError; pub enum Member { Attribute(Box<dyn Attribute>), Action(Box<dyn Action>), } impl fmt::Debug for Member { fn fmt(&self, fmt: &mut fmt::Formatter)...
(&self, path: &str) -> Option<&Member> { self.members.get(path) } pub fn insert(&mut self, path: &str, member: Member) -> Result<(), DeviceError> { let path = String::from(path); if self.members.contains_key(&path) { Err(DeviceError::PathExists(path)) } else { ...
get
identifier_name
device.rs
use std::collections::HashMap; use std::fmt; use std::result::Result; use super::action::Action; use super::attribute::Attribute; use super::error::DeviceError; pub enum Member { Attribute(Box<dyn Attribute>), Action(Box<dyn Action>), } impl fmt::Debug for Member { fn fmt(&self, fmt: &mut fmt::Formatter)...
Member::Action(action) => fmt.debug_tuple("Action").field(action).finish(), } } } #[derive(Debug)] pub struct Device { members: HashMap<String, Member>, } impl Device { pub fn new() -> Device { Device { members: HashMap::new(), } } pub fn get(&self,...
random_line_split
angulartics2.js
/**
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYW5ndWxhcnRpY3MyLmpzIiwic291cmNlUm9vdCI6Im5nOi8vYW5ndWxhcnRpY3MyLyIsInNvdXJjZXMiOlsiYW5ndWxhcnRpY3MyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBRUgsY0FBYyxjQUFjLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEdlbmVyYXRlZCBidW5kbGUgaW...
* Generated bundle index. Do not edit. */ export * from './public_api';
random_line_split
ControllerInjection.js
/** * Overrides the ExtJs Controller constructor and adds some functions to it * * @class Calc.library.service.ControllerInjection * @overrides Ext.app.Controller * @author Arg0n <argonthechecker@gmail.com> */ Ext.define('Calc.library.service.ControllerInjection', { override: 'Ext.app.Controller', ...
me.eventbus = Ext.app.EventBus; me.initAutoGetters(); me.initServices(); }, /** * Adds services to the collection */ initServices: function() { Calc.Service.addAll(this.services); }, /** * Returns a service fr...
{ me.ref(me.refs); }
conditional_block
ControllerInjection.js
/** * Overrides the ExtJs Controller constructor and adds some functions to it * * @class Calc.library.service.ControllerInjection * @overrides Ext.app.Controller * @author Arg0n <argonthechecker@gmail.com> */ Ext.define('Calc.library.service.ControllerInjection', { override: 'Ext.app.Controller', ...
* @param {Mixed} [scope=this] * @param {Boolean} [forceScope=false] * @return {Mixed} */ get: function(identifier, scope, forceScope) { scope = scope || this; forceScope = forceScope || false; return Calc.Service.get(identifier, scope, forceScope); } });
* @param {String} identifier
random_line_split
mkeventd.py
ats = { "ORPHANED" : _("Event deleted in counting state because rule was deleted."), "NOCOUNT" : _("Event deleted in counting state because rule does not count anymore"), "DELAYOVER" : _("Event opened because the delay time has elapsed before cancelling event arrived."), "EXPIRED" : _("Event de...
if p < prio_from or p > prio_to: return _("The syslog priority is not in the required range.")
random_line_split
mkeventd.py
_ec_directly(query): try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: timeout = config.mkeventd_connect_timeout except: timeout = 10 sock.settimeout(timeout) sock.connect(socket_path) sock.sendall(query) sock.shutdown...
if "/" not in text: return parse_ipv4_address(text), 32 network_text, bits_text = text.split("/") return parse_ipv4_address(network_text), int(bits_text)
identifier_body