file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
xsp-info.ts
/* Copyright(c) 2015 - 2021 3NSoft Inc. 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 3 of the License, or (at your option) any later version. This program is distributed in...
yield segmentInfo(chain, seg, l, segSize, infoExtender); } fstSegInd = 0; if (l.chain.isEndless) { throw new Error( `Generator in endless chain is not supposed to be run till its done, and it has already run all allowed segment index values.`); } } } Object.freeze(exports);
{ throw exception( 'concurrentIteration', `Can't iterate cause underlying index has changed.`); }
conditional_block
xsp-info.ts
/* Copyright(c) 2015 - 2021 3NSoft Inc. 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 3 of the License, or (at your option) any later version. This program is distributed in...
get totalSegsLen(): number|undefined { if (this.locations.length === 0) { return 0; } const lastChain = this.locations[this.locations.length-1]; return lastChain.packed.end; } get finitePartSegsLen(): number { const totalLen = this.totalSegsLen; if (typeof totalLen === 'number') { return totalLen; } i...
{ return this.segs.segSize; }
identifier_body
xsp-info.ts
/* Copyright(c) 2015 - 2021 3NSoft Inc. 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 3 of the License, or (at your option) any later version. This program is distributed in...
(x: Uint8Array, i: number): number { // Note that (x << 24) may produce negative number, probably due to // treating intermediate integer as signed, and pulling sign to resulting // float number. Hence, we need a bit different operation here. return x[i]*0x1000000 + ((x[i+1] << 16) | (x[i+2] << 8) | x[i+3]); } /**...
loadUintFrom4Bytes
identifier_name
xsp-info.ts
/* Copyright(c) 2015 - 2021 3NSoft Inc. 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 3 of the License, or (at your option) any later version. This program is distributed in...
indOrChain: number|SegsChainInfo ): ChainLocations|undefined { if (typeof indOrChain === 'number') { return this.locations[indOrChain]; } else { return this.locations.find(l => (l.chain === indOrChain)); } } segmentInfo<T extends SegmentInfo>( segId: SegId, infoExtender?: InfoExtender<T> ): T { c...
} getChainLocations(
random_line_split
Observable.test.ts
import {TeardownLogic, Subscription, SubscriptionHandler, Observable, PartialObserver, Subscriber} from 'tabris'; let observable: Observable<string>; let observer: Subscriber<string>; let partialObserver: PartialObserver<string> = {}; let subHandler: SubscriptionHandler<string>; let subscription: Subscription; let tea...
teardownObject = {unsubscribe: () => undefined} observable = new Observable(() => {}); observable = new Observable<string>(() => {}); observable = new Observable(observerArg => { observer = observerArg; bool = observer.closed; }); observable = new Observable(observerArg => { observerArg.next('foo'); observerAr...
let err: Error;
random_line_split
__init__.py
#!/usr/bin/python # -*- coding: utf-8 -*- """Layman is a complete library for the operation and maintainance on all gentoo repositories and overlays """ import sys try: from layman.api import LaymanAPI from layman.config import BareConfig from layman.output import Message except ImportError: sys.stde...
(LaymanAPI): """A complete high level interface capable of performing all overlay repository actions.""" def __init__(self, stdout=sys.stdout, stdin=sys.stdin, stderr=sys.stderr, config=None, read_configfile=True, quiet=False, quietness=4, verbose=False, nocolor=False, width=0, root=None ...
Layman
identifier_name
__init__.py
#!/usr/bin/python # -*- coding: utf-8 -*- """Layman is a complete library for the operation and maintainance on all gentoo repositories and overlays """ import sys try: from layman.api import LaymanAPI from layman.config import BareConfig from layman.output import Message except ImportError: sys.stde...
nocolor=nocolor, width=width, root=root ) LaymanAPI.__init__(self, self.config, report_errors=True, output=self.config['output'] ) return
quietness=quietness, verbose=verbose,
random_line_split
__init__.py
#!/usr/bin/python # -*- coding: utf-8 -*- """Layman is a complete library for the operation and maintainance on all gentoo repositories and overlays """ import sys try: from layman.api import LaymanAPI from layman.config import BareConfig from layman.output import Message except ImportError: sys.stde...
"""A complete high level interface capable of performing all overlay repository actions.""" def __init__(self, stdout=sys.stdout, stdin=sys.stdin, stderr=sys.stderr, config=None, read_configfile=True, quiet=False, quietness=4, verbose=False, nocolor=False, width=0, root=None ): ...
identifier_body
settings.ts
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. "use strict"; import vscode = require("vscode"); import utils = require("./utils"); enum CodeFormattingPreset { Custom, Allman, OTBS, Stroustrup, } enum PipelineIndentationStyle { IncreaseIndentationForFirstPipeline, ...
(): ISettings { const configuration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration( utils.PowerShellLanguageId); const defaultBugReportingSettings: IBugReportingSettings = { project: "https://github.com/PowerShell/vscode-powershell", }; const defaultScri...
load
identifier_name
settings.ts
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. "use strict"; import vscode = require("vscode"); import utils = require("./utils"); enum CodeFormattingPreset { Custom, Allman, OTBS, Stroustrup, } enum PipelineIndentationStyle { IncreaseIndentationForFirstPipeline, ...
else if (typeof detail.workspaceValue !== "undefined") { configurationTarget = vscode.ConfigurationTarget.Workspace; } else if (typeof detail.globalValue !== "undefined") { configurationTarget = vscode.ConfigurationTarget.Global; } return configurationTarget; } export async functio...
{ configurationTarget = vscode.ConfigurationTarget.WorkspaceFolder; }
conditional_block
settings.ts
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. "use strict"; import vscode = require("vscode"); import utils = require("./utils"); enum CodeFormattingPreset { Custom, Allman, OTBS, Stroustrup, } enum PipelineIndentationStyle { IncreaseIndentationForFirstPipeline, ...
export async function change( settingName: string, newValue: any, configurationTarget?: vscode.ConfigurationTarget | boolean): Promise<void> { const configuration = vscode.workspace.getConfiguration(utils.PowerShellLanguageId); await configuration.update(settingName, newValue, configurationTarge...
{ const configuration = vscode.workspace.getConfiguration(utils.PowerShellLanguageId); const detail = configuration.inspect(settingName); let configurationTarget = null; if (typeof detail.workspaceFolderValue !== "undefined") { configurationTarget = vscode.ConfigurationTarget.WorkspaceFolder; ...
identifier_body
settings.ts
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. "use strict"; import vscode = require("vscode"); import utils = require("./utils"); enum CodeFormattingPreset { Custom, Allman, OTBS, Stroustrup, } enum PipelineIndentationStyle { IncreaseIndentationForFirstPipeline, ...
developer: getWorkspaceSettingsWithDefaults<IDeveloperSettings>(configuration, "developer", defaultDeveloperSettings), codeFolding: configuration.get<ICodeFoldingSettings>("codeFolding", defaultCodeFoldingSettings), codeFormatting: configuration.get<ICodeForma...
scriptAnalysis: configuration.get<IScriptAnalysisSettings>("scriptAnalysis", defaultScriptAnalysisSettings), debugging: configuration.get<IDebuggingSettings>("debugging", defaultDebuggingSettings),
random_line_split
Calculator.ts
/** * A class that implements a simple Calculator */ export class Calculator { /** * Adds the provided numbers and returns the result * @param a First number * @param b Second number */ public add(a: number, b: number): number { return a + b; } /** * Subtracts second ...
(a: number, b: number): number { return a - b; } /** * Multiplies the provided numbers and returns the result * @param a First number * @param b Second number */ public multiply(a: number, b: number): number { return a * b; } /** * Divides the first number ...
subtract
identifier_name
Calculator.ts
/** * A class that implements a simple Calculator */ export class Calculator { /** * Adds the provided numbers and returns the result * @param a First number * @param b Second number */ public add(a: number, b: number): number {
* @param a First number * @param b Second number */ public subtract(a: number, b: number): number { return a - b; } /** * Multiplies the provided numbers and returns the result * @param a First number * @param b Second number */ public multiply(a: number, b: n...
return a + b; } /** * Subtracts second number from first number and returns the result
random_line_split
Calculator.ts
/** * A class that implements a simple Calculator */ export class Calculator { /** * Adds the provided numbers and returns the result * @param a First number * @param b Second number */ public add(a: number, b: number): number { return a + b; } /** * Subtracts second ...
/** * Multiplies the provided numbers and returns the result * @param a First number * @param b Second number */ public multiply(a: number, b: number): number { return a * b; } /** * Divides the first number by the second number and returns the result * @param a ...
{ return a - b; }
identifier_body
webpack.local.config.js
var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') var config = require('./webpack.base.config.js') // Use webpack dev server config.entry = [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './assets/js/index' ] /...
]) // Add a loader for JSX files with react-hot enabled config.module.loaders.push( { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] } ) module.exports = config
// Add HotModuleReplacementPlugin and BundleTracker plugins config.plugins = config.plugins.concat([ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new BundleTracker({filename: './webpack-stats.json'}),
random_line_split
product_spec.js
(function() { "use strict"; var image, master, product, store, variants; module('App.Product', { setup: function() { Ember.run(function() { store = dataStore(); product = store.find('product', 'some-shirt'); }); }, teardown: function() { store = undefined; p...
equal(product.get('permalink'), 'some-shirt'); }); test('#price', function() { equal(product.get('price'), 24.99); }); // --------------------------------------------------------- // Computed Properties // --------------------------------------------------------- test('#masterImage', function(...
random_line_split
Changelog.tsx
import CORE_CHANGELOG from 'CHANGELOG'; import { ChangelogEntry } from 'common/changelog'; import Contributor from 'interface/ContributorButton'; import ReadableListing from 'interface/ReadableListing'; interface Props { changelog: ChangelogEntry[]; limit?: number; includeCore?: boolean;
const mergedChangelog: ChangelogEntry[] = includeCore ? [...CORE_CHANGELOG, ...changelog].sort( (a: ChangelogEntry, b: ChangelogEntry) => b.date.getTime() - a.date.getTime(), ) : changelog; return ( <ul className="list text"> {mergedChangelog .filter((_, i) => !limit || i < ...
} const Changelog = ({ changelog, limit, includeCore = true }: Props) => {
random_line_split
diffie_hellman.rs
use num_bigint::{BigUint, RandBigInt}; use num_integer::Integer; use num_traits::{One, Zero}; use once_cell::sync::Lazy; use rand::{CryptoRng, Rng}; static DH_GENERATOR: Lazy<BigUint> = Lazy::new(|| BigUint::from_bytes_be(&[0x02])); static DH_PRIME: Lazy<BigUint> = Lazy::new(|| { BigUint::from_bytes_be(&[ ...
exp >>= 1; base = (&base * &base) % modulus; } result } pub struct DhLocalKeys { private_key: BigUint, public_key: BigUint, } impl DhLocalKeys { pub fn random<R: Rng + CryptoRng>(rng: &mut R) -> DhLocalKeys { let private_key = rng.gen_biguint(95 * 8); let public_k...
{ result = (result * &base) % modulus; }
conditional_block
diffie_hellman.rs
use num_bigint::{BigUint, RandBigInt}; use num_integer::Integer; use num_traits::{One, Zero}; use once_cell::sync::Lazy; use rand::{CryptoRng, Rng}; static DH_GENERATOR: Lazy<BigUint> = Lazy::new(|| BigUint::from_bytes_be(&[0x02])); static DH_PRIME: Lazy<BigUint> = Lazy::new(|| { BigUint::from_bytes_be(&[ ...
}); fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint { let mut base = base.clone(); let mut exp = exp.clone(); let mut result: BigUint = One::one(); while !exp.is_zero() { if exp.is_odd() { result = (result * &base) % modulus; } exp >>= 1; ...
])
random_line_split
diffie_hellman.rs
use num_bigint::{BigUint, RandBigInt}; use num_integer::Integer; use num_traits::{One, Zero}; use once_cell::sync::Lazy; use rand::{CryptoRng, Rng}; static DH_GENERATOR: Lazy<BigUint> = Lazy::new(|| BigUint::from_bytes_be(&[0x02])); static DH_PRIME: Lazy<BigUint> = Lazy::new(|| { BigUint::from_bytes_be(&[ ...
(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint { let mut base = base.clone(); let mut exp = exp.clone(); let mut result: BigUint = One::one(); while !exp.is_zero() { if exp.is_odd() { result = (result * &base) % modulus; } exp >>= 1; base = (&b...
powm
identifier_name
diffie_hellman.rs
use num_bigint::{BigUint, RandBigInt}; use num_integer::Integer; use num_traits::{One, Zero}; use once_cell::sync::Lazy; use rand::{CryptoRng, Rng}; static DH_GENERATOR: Lazy<BigUint> = Lazy::new(|| BigUint::from_bytes_be(&[0x02])); static DH_PRIME: Lazy<BigUint> = Lazy::new(|| { BigUint::from_bytes_be(&[ ...
}
{ let shared_key = powm( &BigUint::from_bytes_be(remote_key), &self.private_key, &DH_PRIME, ); shared_key.to_bytes_be() }
identifier_body
dnc.py
#! /usr/bin/env python # Copyright (C) 2009 Sebastian Garcia # # 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 2 of the License, or # (at your option) any later version. # #...
nmap_process = Popen(nmap_command, stdout=PIPE) raw_nmap_output = nmap_process.communicate()[0] nmap_returncode = nmap_process.returncode except OSError: print 'You don\'t have nmap installed. You can install it with apt-get install nmap' exit(-1) except ValueError: raw_nmap_out...
nmap_command_string = nmap_command_string + i + ' ' print "\tCommand Executed: {0}".format(nmap_command_string) # For some reason this executable thing does not work! seems to change nmap sP for sS # nmap_process = Popen(nmap_command,executable='nmap',stdout=PIPE)
random_line_split
dnc.py
#! /usr/bin/env python # Copyright (C) 2009 Sebastian Garcia # # 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 2 of the License, or # (at your option) any later version. # #...
try: if server_ip and server_port: version() # Start connecting process_commands() else: usage() except KeyboardInterrupt: # CTRL-C pretty handling. print "Keyboard Interruption!. Exiting." sys.exit(1) if __name__ == '__main__': main()
if opt in ("-s", "--server-ip"): server_ip=str(arg) if opt in ("-p", "--server-port"): server_port=arg if opt in ("-a", "--alias"): alias=str(arg).strip('\n').strip('\r').strip(' ') if opt in ("-d", "--debug"): debug=True if opt in ("-m", "--max-rate"): maxrate=str(arg)
conditional_block
dnc.py
#! /usr/bin/env python # Copyright (C) 2009 Sebastian Garcia # # 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 2 of the License, or # (at your option) any later version. # #...
# Print help information and exit: def usage(): print "+----------------------------------------------------------------------+" print "| dnmap Client Version "+ vernum +" |" print "| This program is free software; you can redistribute it and/or modify |" print "| ...
print "+----------------------------------------------------------------------+" print "| dnmap Client Version "+ vernum +" |" print "| This program is free software; you can redistribute it and/or modify |" print "| it under the terms of the GNU General Public License ...
identifier_body
dnc.py
#! /usr/bin/env python # Copyright (C) 2009 Sebastian Garcia # # 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 2 of the License, or # (at your option) any later version. # #...
(): print "+----------------------------------------------------------------------+" print "| dnmap Client Version "+ vernum +" |" print "| This program is free software; you can redistribute it and/or modify |" print "| it under the terms of the GNU General Public Li...
usage
identifier_name
policytree.py
#!/usr/bin/python from pyparsing import * from charm.toolbox.node import * import string objStack = [] def createAttribute(s, loc, toks): if toks[0] == '!': newtoks = "" for i in toks: newtoks += i return BinNode(newtoks) return BinNode(toks[0]) # create # convert 'attr <...
def labelDuplicates(self, tree, _dictLabel): if tree.left: self.labelDuplicates(tree.left, _dictLabel) if tree.right: self.labelDuplicates(tree.right, _dictLabel) if tree.getNodeType() == OpType.ATTR: key = tree.getAttribute() if _dictLabel.get(key) != None: ...
if tree.left: self.findDuplicates(tree.left, _dict) if tree.right: self.findDuplicates(tree.right, _dict) if tree.getNodeType() == OpType.ATTR: key = tree.getAttribute() if _dict.get(key) == None: _dict[ key ] = 1 else: _dict[ key ] += 1
identifier_body
policytree.py
#!/usr/bin/python from pyparsing import * from charm.toolbox.node import * import string objStack = [] def createAttribute(s, loc, toks): if toks[0] == '!': newtoks = "" for i in toks: newtoks += i return BinNode(newtoks) return BinNode(toks[0]) # create # convert 'attr <...
return if __name__ == "__main__": # policy parser test cases parser = PolicyParser() attrs = ['1', '3'] print("Attrs in user set: ", attrs) tree1 = parser.parse("(1 or 2) and (2 and 3))") print("case 1: ", tree1, ", pruned: ", parser.prune(tree1, attrs)) ...
return (False, None)
conditional_block
policytree.py
#!/usr/bin/python from pyparsing import * from charm.toolbox.node import * import string objStack = [] def createAttribute(s, loc, toks): if toks[0] == '!': newtoks = "" for i in toks: newtoks += i return BinNode(newtoks) return BinNode(toks[0]) # create # convert 'attr <...
(self, tree, _dictLabel): if tree.left: self.labelDuplicates(tree.left, _dictLabel) if tree.right: self.labelDuplicates(tree.right, _dictLabel) if tree.getNodeType() == OpType.ATTR: key = tree.getAttribute() if _dictLabel.get(key) != None: tree.index = _d...
labelDuplicates
identifier_name
policytree.py
#!/usr/bin/python from pyparsing import * from charm.toolbox.node import * import string objStack = [] def createAttribute(s, loc, toks): if toks[0] == '!': newtoks = "" for i in toks: newtoks += i return BinNode(newtoks) return BinNode(toks[0]) # create # convert 'attr <...
# policy parser test cases parser = PolicyParser() attrs = ['1', '3'] print("Attrs in user set: ", attrs) tree1 = parser.parse("(1 or 2) and (2 and 3))") print("case 1: ", tree1, ", pruned: ", parser.prune(tree1, attrs)) tree2 = parser.parse("1 or (2 and 3)") print("cas...
if __name__ == "__main__":
random_line_split
merge.js
import React from 'react' import Icon from 'react-icon-base' const IoMerge = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m30 17.5c2.7 0 5 2.3 5 5s-2.3 5-5 5c-1.9 0-3.4-1-4.3-2.5h-0.8c-4.7 0-9-2-12.4-5.8v9c1.5 0.9 2.5 2.4 2.5 4.3 0 2.7-2.3 5-5 5s-5-2.3-5-5c0-1.9 1-3.4 2.5-4.3v-16.4c-1.5-0.9...
export default IoMerge
</Icon> )
random_line_split
RHPF.js
import assert from "assert"; import RHPF from "../../../src/scapi/units/RHPF"; import createNode from "../../../src/scapi/utils/createNode"; describe("scapi/units/RHPF", () => { it(".ar should create audio rate node", () => { const a = createNode("SinOsc", "audio", [ 440, 0 ]); const node = RHPF.ar(a, 1000, ...
it("default rate is the same as the first input", () => { const a = createNode("SinOsc", "audio", [ 440, 0 ]); const node = RHPF(a); assert.deepEqual(node, { type: "RHPF", rate: "audio", props: [ a, 440, 1 ] }); }); });
assert.deepEqual(node, { type: "RHPF", rate: "control", props: [ a, 1000, 2 ] }); });
random_line_split
chromosome_simulator.py
import argparse import sys from Bio import SeqIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq import random import sys import re import os.path import markov_gen def parse_params(args): parser = argparse.ArgumentParser(description = "Generate simulated chromosome") # parser.add_argument('-c', ...
(seq_file, k, suppress_save = False, mc_file = None, retain_n = False): """Load the sequence and the Markov Chain List. Load the MC list from a file if it exists. If not, create the chain and save it to the file for the next use (skip the save if suppressed). Parameters: * seq_file: The sequence fi...
loadSeqAndChain
identifier_name
chromosome_simulator.py
import argparse import sys from Bio import SeqIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq import random import sys import re import os.path import markov_gen def parse_params(args): parser = argparse.ArgumentParser(description = "Generate simulated chromosome") # parser.add_argument('-c', ...
# fa_out_header: The fixed header lines for the .fa.out file fa_out_header = "\tSW\tperc\tperc\tperc\tquery\tposition in query\tmatching\trepeat\tposition in repeat\n\tscore\tdiv.\tdel.\tins.\tsequence\tbegin\tend\t(left)\trepeat\tclass/family\tbegin\tend (left)\tID\n" # fa_out_template: A template for creating line...
"""Generator: each invokation returns the chromosome, start, finish, starand, and family for the next repeat of the repeatmasker .fa.out files. S, if not empty, is a filter for which repeats to use.""" fp = open(rpt_file) fp.readline() fp.readline() for line in fp: if line.rstrip(): ...
identifier_body
chromosome_simulator.py
import argparse import sys from Bio import SeqIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq import random import sys import re import os.path import markov_gen def parse_params(args): parser = argparse.ArgumentParser(description = "Generate simulated chromosome") # parser.add_argument('-c', ...
sim_seq = "" # Simulated sequence fa_out = [] # Hold the new .fa.out file contents (by line) rpt_count = 0 # Count of repeats (so we can quit when we reach num_repeats, if applicable) for chr, start, finish, strand, family, rpt_class, rpt_id in rpt_gen: if limiting...
max_interval = len(seq)
conditional_block
chromosome_simulator.py
import argparse import sys from Bio import SeqIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq import random import sys import re import os.path import markov_gen def parse_params(args): parser = argparse.ArgumentParser(description = "Generate simulated chromosome") # parser.add_argument('-c', ...
random.seed(args.seed) # First: load in the template sequence, markov chain, and the start/end coords of what we are using. template_seq, markov_list, chr_start, chr_finish = loadSeqAndChain(args.seq_file, args.k, suppress, args.mc_file, args.retain_n) # Read in the set of families to be ignored ...
* seed: RNG seed """ if not output_file.endswith(".fa"): output_file += ".fa"
random_line_split
Alternative.ts
/* * @Author: aaronpmishkin * @Date: 2016-05-25 16:41:41 * @Last Modified by: aaronpmishkin * @Last Modified time: 2016-09-22 20:35:14 */ // Import Utility Classes: import * as Formatter from '../modules/utilities/classes/Formatter'; /* This class is the data representation of a decision option ...
getDescription(): string { return this.description; } setDescription(description: string): void { this.description = description; } getObjectiveValue(objectiveName: string): string | number { return this.objectiveValues.get(objectiveName); } /* @returns {{ objectiveName: string, value: string | numb...
{ this.name = name; this.id = Formatter.nameToID(this.name); }
identifier_body
Alternative.ts
/* * @Author: aaronpmishkin * @Date: 2016-05-25 16:41:41 * @Last Modified by: aaronpmishkin * @Last Modified time: 2016-09-22 20:35:14 */ // Import Utility Classes: import * as Formatter from '../modules/utilities/classes/Formatter'; /* This class is the data representation of a decision option ...
(): string { return this.name; } setName(name: string): void { this.name = name; this.id = Formatter.nameToID(this.name); } getDescription(): string { return this.description; } setDescription(description: string): void { this.description = description; } getObjectiveValue(objectiveName: string): ...
getName
identifier_name
Alternative.ts
/* * @Author: aaronpmishkin * @Date: 2016-05-25 16:41:41 * @Last Modified by: aaronpmishkin * @Last Modified time: 2016-09-22 20:35:14 */ // Import Utility Classes: import * as Formatter from '../modules/utilities/classes/Formatter'; /* This class is the data representation of a decision option ...
setObjectiveValue(objectiveName: string, value: string | number): void { this.objectiveValues.set(objectiveName, value); } removeObjective(objectiveName: string): void { this.objectiveValues.delete(objectiveName); } }
random_line_split
Alternative.ts
/* * @Author: aaronpmishkin * @Date: 2016-05-25 16:41:41 * @Last Modified by: aaronpmishkin * @Last Modified time: 2016-09-22 20:35:14 */ // Import Utility Classes: import * as Formatter from '../modules/utilities/classes/Formatter'; /* This class is the data representation of a decision option ...
return objectiveValuePairs; } setObjectiveValue(objectiveName: string, value: string | number): void { this.objectiveValues.set(objectiveName, value); } removeObjective(objectiveName: string): void { this.objectiveValues.delete(objectiveName); } }
{ objectiveValuePairs.push({ objectiveName: iteratorElement.value, value: this.objectiveValues.get(iteratorElement.value) }); iteratorElement = mapIterator.next(); }
conditional_block
schedule.service.ts
import { Injectable, OnDestroy, Injector, } from '@angular/core'; import { Store } from '@ngrx/store'; import { Observable, Subject, Subscription } from 'rxjs'; import { v1 as uuidV1 } from 'uuid'; import * as schedule from 'node-schedule'; import { UtilService, WebNotificationService, MailNotificationSe...
this.store.dispatch({ type: 'SET_TASK_SCHEDULE_EXECUTED_AT', payload: { id: taskSchedule.id, executedAt, } as TaskScheduleExecutedAt, }) } catch (error) { if (error === false) return; console.error('Error happened executing taskSchedule: ', taskSch...
random_line_split
schedule.service.ts
import { Injectable, OnDestroy, Injector, } from '@angular/core'; import { Store } from '@ngrx/store'; import { Observable, Subject, Subscription } from 'rxjs'; import { v1 as uuidV1 } from 'uuid'; import * as schedule from 'node-schedule'; import { UtilService, WebNotificationService, MailNotificationS...
}
{ console.log('Executing TaskSchedule: ', taskSchedule.name); const tasks = await this.tasks$ .map((tasksArr) => tasksArr.filter(task => task.taskScheduleId === taskSchedule.id )) .take(1) .toPromise() try { const taskData = []; for (const [taskIndex, ...
identifier_body
schedule.service.ts
import { Injectable, OnDestroy, Injector, } from '@angular/core'; import { Store } from '@ngrx/store'; import { Observable, Subject, Subscription } from 'rxjs'; import { v1 as uuidV1 } from 'uuid'; import * as schedule from 'node-schedule'; import { UtilService, WebNotificationService, MailNotificationS...
implements OnDestroy { public tasks$: Observable<Task[]>; public scheduleEmitter = new Subject<TaskSchedule>(); public jobs: schedule.Job[] = []; private scheduleServiceSub: Subscription; constructor( public store: Store<RXState>, public injector: Injector, public notificationService: WebNotifi...
ScheduleService
identifier_name
count.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let ...
() { let mut a: A<T> = A { begin: 0, end: 10 }; assert_eq!(a.next(), Some::<T>(0)); let count: usize = a.count(); assert_eq!(count, 9); } }
count_test2
identifier_name
count.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end {
None::<Self::Item> } } // fn count(self) -> usize where Self: Sized { // // Might overflow. // self.fold(0, |cnt, _| cnt + 1) // } } } } type T = i32; Iterator_impl!(T); #[test] fn count_test1() { let a: A<T> = A { begin: 0, end: 10 }; let count: usize = a.count...
let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else {
random_line_split
global.js
/** * Created by LPAC006013 on 23/11/14. */ /* * wiring Super fish to menu */ var sfvar = jQuery('div.menu'); var phoneSize = 600; jQuery(document).ready(function($) { //if screen size is bigger than phone's screen (Tablet,Desktop) if($(document).width() >= phoneSize) { // enable superfish ...
});
random_line_split
global.js
/** * Created by LPAC006013 on 23/11/14. */ /* * wiring Super fish to menu */ var sfvar = jQuery('div.menu'); var phoneSize = 600; jQuery(document).ready(function($) { //if screen size is bigger than phone's screen (Tablet,Desktop) if($(document).width() >= phoneSize)
$(window).resize(function() { if($(document).width() >= phoneSize && !sfvar.hasClass('sf-js-enabled')) { sfvar.superfish({ delay: 500, speed: 'slow' }); } // phoneSize, disable superfish else if($(document).width() < phoneSize)...
{ // enable superfish sfvar.superfish({ delay: 500, speed: 'slow' }); jQuery("#menu-main-menu").addClass('clear'); var containerheight = jQuery("#menu-main-menu").height(); jQuery("#menu-main-menu").children().css("height",containerheight); }
conditional_block
main.rs
// 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 agreed to in ...
states: u32, width: u32, } const fn num_bits<T>() -> usize { std::mem::size_of::<T>() * 8 } fn log_2(x: u32) -> u32 { num_bits::<u32>() as u32 - x.leading_zeros() } impl Generator { fn generate<'a>(&'a self, c: &'a mut Context<'a>) -> &'a Module { let mut rng = rand::thread_rng(); //...
} struct Generator {
random_line_split
main.rs
// 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 agreed to in ...
<'a>(&'a self, c: &'a mut Context<'a>) -> &'a Module { let mut rng = rand::thread_rng(); // compute width of state register let state_reg_width = log_2(self.states - 1u32); // create lock module with a single state register and trigger input let lock = c.module("lock"); ...
generate
identifier_name
main.rs
// 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 agreed to in ...
fn log_2(x: u32) -> u32 { num_bits::<u32>() as u32 - x.leading_zeros() } impl Generator { fn generate<'a>(&'a self, c: &'a mut Context<'a>) -> &'a Module { let mut rng = rand::thread_rng(); // compute width of state register let state_reg_width = log_2(self.states - 1u32); /...
{ std::mem::size_of::<T>() * 8 }
identifier_body
settings.py
# coding:utf-8 """ Django settings for turbo project. Generated by 'django-admin startproject' using Django 1.11.1. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ "...
MEDIA_URL = '/' MEDIA_ROOT = BASE_DIR + '/media/' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } JWT_AUTH = { 'JWT_SECRET_KE...
random_line_split
slab.rs
use alloc::heap::{Alloc, AllocErr, Layout}; use spin::Mutex; use slab_allocator::Heap; static HEAP: Mutex<Option<Heap>> = Mutex::new(None); pub struct Allocator; impl Allocator { pub unsafe fn init(offset: usize, size: usize) { *HEAP.lock() = Some(Heap::new(offset, size)); } } unsafe impl<'a> Alloc ...
if let Some(ref mut heap) = *HEAP.lock() { heap.allocate(layout) } else { panic!("__rust_allocate: heap not initialized"); } } unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout) { if let Some(ref mut heap) = *HEAP.lock() { heap.dealloc...
unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
random_line_split
slab.rs
use alloc::heap::{Alloc, AllocErr, Layout}; use spin::Mutex; use slab_allocator::Heap; static HEAP: Mutex<Option<Heap>> = Mutex::new(None); pub struct Allocator; impl Allocator { pub unsafe fn init(offset: usize, size: usize) { *HEAP.lock() = Some(Heap::new(offset, size)); } } unsafe impl<'a> Alloc ...
(&mut self, error: AllocErr) -> ! { panic!("Out of memory: {:?}", error); } fn usable_size(&self, layout: &Layout) -> (usize, usize) { if let Some(ref mut heap) = *HEAP.lock() { heap.usable_size(layout) } else { panic!("__rust_usable_size: heap not initialized");...
oom
identifier_name
slab.rs
use alloc::heap::{Alloc, AllocErr, Layout}; use spin::Mutex; use slab_allocator::Heap; static HEAP: Mutex<Option<Heap>> = Mutex::new(None); pub struct Allocator; impl Allocator { pub unsafe fn init(offset: usize, size: usize) { *HEAP.lock() = Some(Heap::new(offset, size)); } } unsafe impl<'a> Alloc ...
fn usable_size(&self, layout: &Layout) -> (usize, usize) { if let Some(ref mut heap) = *HEAP.lock() { heap.usable_size(layout) } else { panic!("__rust_usable_size: heap not initialized"); } } }
{ panic!("Out of memory: {:?}", error); }
identifier_body
slab.rs
use alloc::heap::{Alloc, AllocErr, Layout}; use spin::Mutex; use slab_allocator::Heap; static HEAP: Mutex<Option<Heap>> = Mutex::new(None); pub struct Allocator; impl Allocator { pub unsafe fn init(offset: usize, size: usize) { *HEAP.lock() = Some(Heap::new(offset, size)); } } unsafe impl<'a> Alloc ...
} unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout) { if let Some(ref mut heap) = *HEAP.lock() { heap.deallocate(ptr, layout) } else { panic!("__rust_deallocate: heap not initialized"); } } fn oom(&mut self, error: AllocErr) -> ! { pani...
{ panic!("__rust_allocate: heap not initialized"); }
conditional_block
ui_highlowDialog.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\JohnnyG\Documents\XRDproject_Python_11June2010Release backup\highlowDialog.ui' # # Created: Mon Jun 14 16:20:37 2010 # by: PyQt4 UI code generator 4.5.4 # # WARNING! All changes made in this file will be lost! from PyQt4 impor...
highlowDialog.setWindowTitle(QtGui.QApplication.translate("highlowDialog", "Enter range for colorbar", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("highlowDialog", "low value", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.trans...
identifier_body
ui_highlowDialog.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\JohnnyG\Documents\XRDproject_Python_11June2010Release backup\highlowDialog.ui' # # Created: Mon Jun 14 16:20:37 2010 # by: PyQt4 UI code generator 4.5.4 # # WARNING! All changes made in this file will be lost! from PyQt4 impor...
(self, highlowDialog): highlowDialog.setWindowTitle(QtGui.QApplication.translate("highlowDialog", "Enter range for colorbar", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("highlowDialog", "low value", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.s...
retranslateUi
identifier_name
ui_highlowDialog.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\JohnnyG\Documents\XRDproject_Python_11June2010Release backup\highlowDialog.ui' # # Created: Mon Jun 14 16:20:37 2010 # by: PyQt4 UI code generator 4.5.4 # # WARNING! All changes made in this file will be lost! from PyQt4 impor...
self.label_2.setText(QtGui.QApplication.translate("highlowDialog", "high value", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("highlowDialog", "low value", None, QtGui.QApplication.UnicodeUTF8))
random_line_split
SetPhotoLocation.py
# -*- coding: utf-8 -*- ############################################################################### # # SetPhotoLocation # Sets the geo data (including latitude and longitude) for a specified photo. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0...
(self, value): """ Set the value of the AccessTokenSecret input for this Choreo. ((required, string) The Access Token Secret retrieved during the OAuth process.) """ super(SetPhotoLocationInputSet, self)._set_input('AccessTokenSecret', value) def set_AccessToken(self, value): ...
set_AccessTokenSecret
identifier_name
SetPhotoLocation.py
# -*- coding: utf-8 -*- ############################################################################### # # SetPhotoLocation # Sets the geo data (including latitude and longitude) for a specified photo. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0...
def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from Flickr.) """ return self._output.get('Response', None) class SetPhotoLocationChoreographyExecution(ChoreographyExecution): def _make_result_set(self, respon...
return json.loads(str)
identifier_body
SetPhotoLocation.py
# -*- coding: utf-8 -*- ############################################################################### # # SetPhotoLocation # Sets the geo data (including latitude and longitude) for a specified photo. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0...
def __init__(self, temboo_session): """ Create a new instance of the SetPhotoLocation Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(SetPhotoLocation, self).__init__(temboo_session, '/Library/Flickr/Geo/SetPhotoLocati...
random_line_split
util.js
// @flow import Decimal from "decimal.js-light" import * as R from "ramda" import _ from "lodash" import moment from "moment" import { CS_DEFAULT, CS_ERROR_MESSAGES, ORDER_FULFILLED } from "../constants" import type { BootcampRun } from "../flow/bootcampTypes" import type { HttpResponse } from "../flow/httpTypes" /*...
(Array.isArray(response.body.errors)) { return response.body.errors.length === 0 ? null : response.body.errors } return response.body.errors === "" ? null : response.body.errors } export const getFirstResponseBodyError = ( response: HttpResponse<*> ): ?string => { const errors = getResponseBodyErrors(resp...
if
identifier_name
util.js
// @flow import Decimal from "decimal.js-light" import * as R from "ramda" import _ from "lodash" import moment from "moment" import { CS_DEFAULT, CS_ERROR_MESSAGES, ORDER_FULFILLED } from "../constants" import type { BootcampRun } from "../flow/bootcampTypes" import type { HttpResponse } from "../flow/httpTypes" /*...
export const isNilOrBlank = R.either(R.isNil, R.isEmpty) export const formatDollarAmount = (amount: ?number): string => { amount = amount || 0 const formattedAmount = amount.toLocaleString("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2, maximu...
{ const form = document.createElement("form") form.setAttribute("action", url) form.setAttribute("method", "post") form.setAttribute("class", "cybersource-payload") for (const key: string of Object.keys(payload)) { const value = payload[key] const input = document.createElement("input") input.set...
identifier_body
util.js
// @flow import Decimal from "decimal.js-light" import * as R from "ramda" import _ from "lodash" import moment from "moment" import { CS_DEFAULT, CS_ERROR_MESSAGES, ORDER_FULFILLED } from "../constants" import type { BootcampRun } from "../flow/bootcampTypes" import type { HttpResponse } from "../flow/httpTypes" /*...
* Our uploaded filenames begin with a media path. Until we start saving the * raw file names for uploaded files, this utility function can be used to * extract the file name. * Ex: "media/1/abcde-12345_some_resume.pdf" -> "some_resume.pdf" */ export const getFilenameFromMediaPath = R.compose( R.join("_"), R.ta...
/*
random_line_split
util.js
// @flow import Decimal from "decimal.js-light" import * as R from "ramda" import _ from "lodash" import moment from "moment" import { CS_DEFAULT, CS_ERROR_MESSAGES, ORDER_FULFILLED } from "../constants" import type { BootcampRun } from "../flow/bootcampTypes" import type { HttpResponse } from "../flow/httpTypes" /*...
if (_.isArray(response) && response.length > 0) { return response[0] } if (response.errors && response.errors.length > 0) { return response.errors[0] } if (response.error && response.error !== "") { return response.error } return null } export const parsePrice = (priceStr: string | number): ...
{ return null }
conditional_block
index.js
'use strict'; require('nightingale-app-console'); var _pool = require('koack/pool'); var _pool2 = _interopRequireDefault(_pool); var _server = require('koack/server'); var _server2 = _interopRequireDefault(_server); var _memory = require('koack/storages/memory'); var _memory2 = _interopRequireDefault(_memory); ...
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const pool = new _pool2.default({ size: 100, path: require.resolve('./bot') }); const server = new _server2.default({ pool, scopes: ['bot'], slackClient: _config2.default.slackClient, storage: (0, _memory2.default)() }); server.proxy = true...
_interopRequireDefault
identifier_name
index.js
'use strict'; require('nightingale-app-console'); var _pool = require('koack/pool'); var _pool2 = _interopRequireDefault(_pool); var _server = require('koack/server'); var _server2 = _interopRequireDefault(_server); var _memory = require('koack/storages/memory'); var _memory2 = _interopRequireDefault(_memory); ...
server.listen({ port: process.env.PORT || 3000 }); //# sourceMappingURL=index.js.map
random_line_split
index.js
'use strict'; require('nightingale-app-console'); var _pool = require('koack/pool'); var _pool2 = _interopRequireDefault(_pool); var _server = require('koack/server'); var _server2 = _interopRequireDefault(_server); var _memory = require('koack/storages/memory'); var _memory2 = _interopRequireDefault(_memory); ...
const pool = new _pool2.default({ size: 100, path: require.resolve('./bot') }); const server = new _server2.default({ pool, scopes: ['bot'], slackClient: _config2.default.slackClient, storage: (0, _memory2.default)() }); server.proxy = true; server.use((0, _interactiveMessages2.default)({ pool, tok...
{ return obj && obj.__esModule ? obj : { default: obj }; }
identifier_body
memory.ts
import { union } from 'lodash'; import matchesClientOption from '../utils/memoryModels/matchesClientOption'; import FacadeConfig from '../utils/memoryModels/FacadeConfig'; import Signature, { Opts } from './Signature'; export default (config: FacadeConfig): Signature => { return async ({ id, client, agen...
activities: union(activities, model.activities), relatedActivities: union(relatedActivities, model.relatedActivities), registrations: union(registrations, model.registrations), }; } return model; }); }; };
agents: union(agents, model.agents), relatedAgents: union(relatedAgents, model.relatedAgents), verbs: union(verbs, model.verbs),
random_line_split
memory.ts
import { union } from 'lodash'; import matchesClientOption from '../utils/memoryModels/matchesClientOption'; import FacadeConfig from '../utils/memoryModels/FacadeConfig'; import Signature, { Opts } from './Signature'; export default (config: FacadeConfig): Signature => { return async ({ id, client, agen...
return model; }); }; };
{ return { ...model, agents: union(agents, model.agents), relatedAgents: union(relatedAgents, model.relatedAgents), verbs: union(verbs, model.verbs), activities: union(activities, model.activities), relatedActivities: union(relatedActivities, model.rel...
conditional_block
Featured.js
var // get util library util = require("core/Util"); function Featured(options){ var self = Ti.UI.createTableView({ width : Ti.UI.FILL, backgroundColor : Theme.Home.Featured.HeaderBackgroundColor, height : options.height || null }); return { get : function(){ return self; }, /* * Featured...
body = Ti.UI.createLabel({ text : desc, height : Ti.UI.SIZE, left : 2, top : 2, color : Theme.Home.Featured.DescriptionColor, font : { fontSize : Theme.Home.Featured.DescriptionFontSize, fontWeight : Theme.Home.Featured.DescriptionFontWeight } ...
fontSize : Theme.Home.Featured.TitleFontSize, fontWeight : Theme.Home.Featured.TitleFontWeight } }),
random_line_split
Featured.js
var // get util library util = require("core/Util"); function Featured(options){ var self = Ti.UI.createTableView({ width : Ti.UI.FILL, backgroundColor : Theme.Home.Featured.HeaderBackgroundColor, height : options.height || null }); return { get : function(){ return self; }, /* * Feature...
row.add(bodyView); // handle featured item click event row.addEventListener( "click", function(e){ Ti.App.fireEvent( "APP:SHOW_PRODUCT", { "itemId" : itemId, "tab" : "Home" } ); } ); return row; } } } exports.create = function(options){ return Featured(option...
{ img.width = Theme.Home.Featured.ImageWidth; bodyView.left = Theme.Home.Featured.ImageWidth + 1; bodyView.height = Ti.UI.SIZE; }
conditional_block
Featured.js
var // get util library util = require("core/Util"); function Featured(options)
exports.create = function(options){ return Featured(options); };
{ var self = Ti.UI.createTableView({ width : Ti.UI.FILL, backgroundColor : Theme.Home.Featured.HeaderBackgroundColor, height : options.height || null }); return { get : function(){ return self; }, /* * Featured row factory method * * @param {String} name: the product name to display ...
identifier_body
Featured.js
var // get util library util = require("core/Util"); function
(options){ var self = Ti.UI.createTableView({ width : Ti.UI.FILL, backgroundColor : Theme.Home.Featured.HeaderBackgroundColor, height : options.height || null }); return { get : function(){ return self; }, /* * Featured row factory method * * @param {String} name: the product name to di...
Featured
identifier_name
module.js
define(['angular','search/module-name','kylo-utils/LazyLoadUtil','constants/AccessConstants', 'kylo-services','kylo-feedmgr'], function (angular,moduleName,lazyLoadUtil,AccessConstants) { var module = angular.module(moduleName, []); module.config(['$stateProvider',function ($stateProvider) { $statePro...
}]); return module; });
{ return lazyLoadUtil.lazyLoadController(path,'search/module-require'); }
identifier_body
module.js
define(['angular','search/module-name','kylo-utils/LazyLoadUtil','constants/AccessConstants', 'kylo-services','kylo-feedmgr'], function (angular,moduleName,lazyLoadUtil,AccessConstants) { var module = angular.module(moduleName, []); module.config(['$stateProvider',function ($stateProvider) { $statePro...
(path){ return lazyLoadUtil.lazyLoadController(path,'search/module-require'); } }]); return module; });
lazyLoadController
identifier_name
module.js
define(['angular','search/module-name','kylo-utils/LazyLoadUtil','constants/AccessConstants', 'kylo-services','kylo-feedmgr'], function (angular,moduleName,lazyLoadUtil,AccessConstants) { var module = angular.module(moduleName, []); module.config(['$stateProvider',function ($stateProvider) { $statePro...
breadcrumbRoot:false, displayName:'Search', module:moduleName, permissions:AccessConstants.UI_STATES.SEARCH.permissions } }) function lazyLoadController(path){ return lazyLoadUtil.lazyLoadController(path,'search/mo...
}, data:{
random_line_split
mod.rs
//! Module containing various utility functions. mod os; mod webdav; mod content_encoding; use base64; use std::path::Path; use percent_encoding; use walkdir::WalkDir; use std::borrow::Cow; use rfsapi::RawFileData; use std::{cmp, f64, str}; use std::time::SystemTime; use std::collections::HashMap; use time::{self, D...
} /// Get the metadata of the specified file. /// /// The specified path must point to a file. pub fn get_raw_fs_metadata<P: AsRef<Path>>(f: P) -> RawFileData { get_raw_fs_metadata_impl(f.as_ref()) } fn get_raw_fs_metadata_impl(f: &Path) -> RawFileData { let meta = f.metadata().expect("Failed to get requested...
"" }
random_line_split
mod.rs
//! Module containing various utility functions. mod os; mod webdav; mod content_encoding; use base64; use std::path::Path; use percent_encoding; use walkdir::WalkDir; use std::borrow::Cow; use rfsapi::RawFileData; use std::{cmp, f64, str}; use std::time::SystemTime; use std::collections::HashMap; use time::{self, D...
} impl<'n> BorrowXmlName<'n> for OwnedXmlName { #[inline(always)] fn borrow_xml_name(&'n self) -> XmlName<'n> { self.borrow() } } #[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct Spaces(pub usize); impl fmt::Display for Spaces { fn fmt(&self, f: &mut fmt::Format...
{ *self }
identifier_body
mod.rs
//! Module containing various utility functions. mod os; mod webdav; mod content_encoding; use base64; use std::path::Path; use percent_encoding; use walkdir::WalkDir; use std::borrow::Cow; use rfsapi::RawFileData; use std::{cmp, f64, str}; use std::time::SystemTime; use std::collections::HashMap; use time::{self, D...
f_whom { return true; } while let Some(who_p) = who.parent().map(|p| p.to_path_buf()) { who = who_p; if who == of_whom { return true; } } false } /// Check if the specified path is a direct descendant (or an equal) of the specified path, without without re...
alse; }; if who == o
conditional_block
mod.rs
//! Module containing various utility functions. mod os; mod webdav; mod content_encoding; use base64; use std::path::Path; use percent_encoding; use walkdir::WalkDir; use std::borrow::Cow; use rfsapi::RawFileData; use std::{cmp, f64, str}; use std::time::SystemTime; use std::collections::HashMap; use time::{self, D...
-> Tm { match time.elapsed() { Ok(dur) => time::now_utc() - Duration::from_std(dur).unwrap(), Err(ste) => time::now_utc() + Duration::from_std(ste.duration()).unwrap(), } } /// Check, whether, in any place of the path, a file is treated like a directory. /// /// A file is treated like a direct...
e: SystemTime)
identifier_name
categoriesFormView.js
define([ 'jquery', 'underscore', 'backbone', 'mustache', 'initView', 'text!templates/categories/categoriesItem.mustache', 'text!templates/categories/categoriesForm.mustache', 'categoryModel', 'categoryCollection', 'storage' ], function( $, _, Backbone, Mustache, InitView, CategoriesIte...
}); } }); return CategoryFormView; });
{ view.displayForm(); }
conditional_block
categoriesFormView.js
define([ 'jquery', 'underscore', 'backbone', 'mustache', 'initView', 'text!templates/categories/categoriesItem.mustache', 'text!templates/categories/categoriesForm.mustache', 'categoryModel', 'categoryCollection', 'storage' ], function( $, _, Backbone, Mustache,
InitView, CategoriesItemTemplate, CategoriesFormTemplate, Category, CategoryCollection, storage) { var CategoryFormView = Backbone.View.extend({ el: $("#content"), displayForm: function(categorie){ var categories_actives = storage.categories.enable(); var template = Mustache.render(Categ...
random_line_split
record-pat.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 ...
{x: t1, y: int} enum t3 { c(T2, uint), } fn m(in: t3) -> int { match in { c(T2 {x: a(m), _}, _) => { return m; } c(T2 {x: b(m), y: y}, z) => { return ((m + z) as int) + y; } } } pub fn main() { assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10); assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u)), 19); ...
T2
identifier_name
record-pat.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 ...
c(T2 {x: b(m), y: y}, z) => { return ((m + z) as int) + y; } } } pub fn main() { assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10); assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u)), 19); }
{ return m; }
conditional_block
record-pat.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 ...
assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10); assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u)), 19); }
c(T2 {x: b(m), y: y}, z) => { return ((m + z) as int) + y; } } } pub fn main() {
random_line_split
length_limit.rs
//! See [`HtmlWithLimit`]. use std::fmt::Write; use std::ops::ControlFlow; use crate::html::escape::Escape; /// A buffer that allows generating HTML with a length limit. /// /// This buffer ensures that: /// /// * all tags are closed, /// * tags are closed in the reverse order of when they were opened (i.e., the cor...
/// Open an HTML tag. /// /// **Note:** HTML attributes have not yet been implemented. /// This function will panic if called with a non-alphabetic `tag_name`. pub(super) fn open_tag(&mut self, tag_name: &'static str) { assert!( tag_name.chars().all(|c| ('a'..='z').contains(&c)...
{ if self.len + text.len() > self.limit { return ControlFlow::BREAK; } self.flush_queue(); write!(self.buf, "{}", Escape(text)).unwrap(); self.len += text.len(); ControlFlow::CONTINUE }
identifier_body
length_limit.rs
//! See [`HtmlWithLimit`]. use std::fmt::Write; use std::ops::ControlFlow; use crate::html::escape::Escape; /// A buffer that allows generating HTML with a length limit. /// /// This buffer ensures that: /// /// * all tags are closed, /// * tags are closed in the reverse order of when they were opened (i.e., the cor...
// a tag is opened after the length limit is exceeded; // `flush_queue()` will never be called, and thus, the tag will // not end up being added to `unclosed_tags`. None => {} } } /// Write all queued tags and add them to the `unclosed_tags` list. fn ...
random_line_split
length_limit.rs
//! See [`HtmlWithLimit`]. use std::fmt::Write; use std::ops::ControlFlow; use crate::html::escape::Escape; /// A buffer that allows generating HTML with a length limit. /// /// This buffer ensures that: /// /// * all tags are closed, /// * tags are closed in the reverse order of when they were opened (i.e., the cor...
(&mut self) { while !self.unclosed_tags.is_empty() { self.close_tag(); } } } #[cfg(test)] mod tests;
close_all_tags
identifier_name
constraints.py
import datetime import logging from django.conf import settings from django.core.exceptions import NON_FIELD_ERRORS from google.appengine.api.datastore import Key, Delete, MAX_ALLOWABLE_QUERIES from google.appengine.datastore.datastore_rpc import TransactionOptions from google.appengine.ext import db from .unique_uti...
(marker, instance): marker = UniqueMarker.get(marker.key()) if not marker: return marker.instance = instance marker.put() @db.transactional(propagation=TransactionOptions.INDEPENDENT, xg=True) def update_all(): instance = entity.key() for marker in m...
update
identifier_name
constraints.py
import datetime import logging from django.conf import settings from django.core.exceptions import NON_FIELD_ERRORS from google.appengine.api.datastore import Key, Delete, MAX_ALLOWABLE_QUERIES from google.appengine.datastore.datastore_rpc import TransactionOptions from google.appengine.ext import db from .unique_uti...
def release_identifiers(identifiers, namespace): @db.transactional(propagation=TransactionOptions.INDEPENDENT, xg=len(identifiers) > 1) def txn(): _release_identifiers(identifiers, namespace) txn() def _release_identifiers(identifiers, namespace): keys = [Key.from_path(UniqueMarker.kind(),...
""" Delete the given UniqueMarker objects. """ # Note that these should all be from the same Django model instance, and therefore there should # be a maximum of 25 of them (because everything blows up if you have more than that - limitation) @db.transactional(propagation=TransactionOptions.INDEPENDENT, xg=...
identifier_body
constraints.py
import datetime import logging from django.conf import settings from django.core.exceptions import NON_FIELD_ERRORS from google.appengine.api.datastore import Key, Delete, MAX_ALLOWABLE_QUERIES from google.appengine.datastore.datastore_rpc import TransactionOptions from google.appengine.ext import db from .unique_uti...
####################################################### # Deal with long __in lookups by doing multiple queries in that case # This is a bit hacky, but we really have no choice due to App Engine's # 30 multi-query limit. This also means we can't support multiple list fi...
continue
conditional_block
constraints.py
import datetime import logging from django.conf import settings from django.core.exceptions import NON_FIELD_ERRORS from google.appengine.api.datastore import Key, Delete, MAX_ALLOWABLE_QUERIES from google.appengine.datastore.datastore_rpc import TransactionOptions from google.appengine.ext import db from .unique_uti...
def validate(self, value): if value is None or isinstance(value, Key): return value raise ValueError("KeyProperty only accepts datastore.Key or None") class UniqueMarker(db.Model): instance = KeyProperty() created = db.DateTimeProperty(required=True, auto_now_add=True) @s...
object, or a db.ReferenceProperty which can point to any model kind, and only returns the Key. """
random_line_split
tuple_impl.rs
//! Some iterator that produces tuples use std::iter::Fuse; // `HomogeneousTuple` is a public facade for `TupleCollect`, allowing // tuple-related methods to be used by clients in generic contexts, while // hiding the implementation details of `TupleCollect`. // See https://github.com/rust-itertools/itertools/issues/...
where T: HomogeneousTuple { type Item = T::Item; fn next(&mut self) -> Option<Self::Item> { let s = self.buf.as_mut(); if let Some(ref mut item) = s.get_mut(self.cur) { self.cur += 1; item.take() } else { None } } fn size_hint(&se...
impl<T> Iterator for TupleBuffer<T>
random_line_split
tuple_impl.rs
//! Some iterator that produces tuples use std::iter::Fuse; // `HomogeneousTuple` is a public facade for `TupleCollect`, allowing // tuple-related methods to be used by clients in generic contexts, while // hiding the implementation details of `TupleCollect`. // See https://github.com/rust-itertools/itertools/issues/...
} pub trait TupleCollect: Sized { type Item; type Buffer: Default + AsRef<[Option<Self::Item>]> + AsMut<[Option<Self::Item>]>; fn collect_from_iter<I>(iter: I, buf: &mut Self::Buffer) -> Option<Self> where I: IntoIterator<Item = Self::Item>; fn collect_from_iter_no_buf<I>(iter: I) -> Option<...
{ if T::num_items() == 1 { return T::collect_from_iter_no_buf(&mut self.iter) } if let Some(ref mut last) = self.last { if let Some(new) = self.iter.next() { last.left_shift_push(new); return Some(last.clone()); } } ...
identifier_body
tuple_impl.rs
//! Some iterator that produces tuples use std::iter::Fuse; // `HomogeneousTuple` is a public facade for `TupleCollect`, allowing // tuple-related methods to be used by clients in generic contexts, while // hiding the implementation details of `TupleCollect`. // See https://github.com/rust-itertools/itertools/issues/...
; (len, Some(len)) } } impl<T> ExactSizeIterator for TupleBuffer<T> where T: HomogeneousTuple { } /// An iterator that groups the items in tuples of a specific size. /// /// See [`.tuples()`](../trait.Itertools.html#method.tuples) for more information. #[derive(Clone)] #[must_use = "iterator adaptors ...
{ buffer.iter() .position(|x| x.is_none()) .unwrap_or(buffer.len()) }
conditional_block
tuple_impl.rs
//! Some iterator that produces tuples use std::iter::Fuse; // `HomogeneousTuple` is a public facade for `TupleCollect`, allowing // tuple-related methods to be used by clients in generic contexts, while // hiding the implementation details of `TupleCollect`. // See https://github.com/rust-itertools/itertools/issues/...
(&mut self) -> Option<T> { if T::num_items() == 1 { return T::collect_from_iter_no_buf(&mut self.iter) } if let Some(ref mut last) = self.last { if let Some(new) = self.iter.next() { last.left_shift_push(new); return Some(last.clone()); ...
next
identifier_name
draft.py
from datetime import datetime from xmodule.modulestore import Location, namedtuple_to_son from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.inheritance import own_metadata from xmodule.exceptions import InvalidVersionError from xmodule.modulestore.mongo.base import MongoModuleStore ...
super(DraftModuleStore, self).clone_item(location, as_draft(location)) super(DraftModuleStore, self).delete_item(location) def _query_children_for_cache_children(self, items): # first get non-draft in a round-trip queried_children = [] to_process_non_drafts = super(DraftMod...
raise InvalidVersionError(location)
conditional_block
draft.py
from datetime import datetime from xmodule.modulestore import Location, namedtuple_to_son from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.inheritance import own_metadata from xmodule.exceptions import InvalidVersionError from xmodule.modulestore.mongo.base import MongoModuleStore ...
(self, location, course_id=None, depth=0): """ Returns a list of XModuleDescriptor instances for the items that match location. Any element of location that is None is treated as a wildcard that matches any value location: Something that can be passed to Location depth:...
get_items
identifier_name
draft.py
from datetime import datetime from xmodule.modulestore import Location, namedtuple_to_son from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.inheritance import own_metadata from xmodule.exceptions import InvalidVersionError from xmodule.modulestore.mongo.base import MongoModuleStore ...
def clone_item(self, source, location): """ Clone a new item that is a copy of the item at the location `source` and writes it to `location` """ if Location(location).category in DIRECT_ONLY_CATEGORIES: raise InvalidVersionError(location) return wrap_dra...
""" Returns a list of XModuleDescriptor instances for the items that match location. Any element of location that is None is treated as a wildcard that matches any value location: Something that can be passed to Location depth: An argument that some module stores may use to pre...
identifier_body