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 |
|---|---|---|---|---|
ogone.py | AAVZIP',
'ACCEPTANCE',
'ALIAS',
'AMOUNT',
'BIC',
'BIN',
'BRAND',
'CARDNO',
'CCCTY',
'CN',
'COMPLUS',
... | (self, cr, uid, tx, data, context=None):
invalid_parameters = []
# TODO: txn_id: should be false at draft, set afterwards, and verified with txn details
if tx.acquirer_reference and data.get('PAYID') != tx.acquirer_reference:
invalid_parameters.append(('PAYID', data.get('PAYID'), tx... | _ogone_form_get_invalid_parameters | identifier_name |
ogone.py | AAVZIP',
'ACCEPTANCE',
'ALIAS',
'AMOUNT',
'BIC',
'BIN',
'BRAND',
'CARDNO',
'CCCTY',
'CN',
'COMPLUS',
... |
else:
error_msg += '; multiple order found'
_logger.error(error_msg)
raise ValidationError(error_msg)
tx = self.pool['payment.transaction'].browse(cr, uid, tx_ids[0], context=context)
# verify shasign
shasign_check = self.pool['payment.acquir... | error_msg += '; no order found' | conditional_block |
ogone.py | ign
ogone_tx_values.update(temp_ogone_tx_values)
return partner_values, ogone_tx_values
def ogone_get_form_action_url(self, cr, uid, id, context=None):
acquirer = self.browse(cr, uid, id, context=context)
return self._get_ogone_urls(cr, uid, acquirer.environment, context=context)['o... | """ Generate valid Ogone values for a s2s tx.
.. versionadded:: pre-v8 saas-3
.. warning::
Experimental code. You should not use it before OpenERP v8 official
release.
"""
tx = self.browse(cr, uid, id, context=context)
tx_data = {
'PSPID': ... | identifier_body | |
generateTemplate.py |
def generateTemplate(source, filename, sumname, dataname=None):
"""
Generate a model summary file (model_summary.txt) and a template file (filename) from one or more SBML source files.
***** args *****
source: a list of strings.
Each entry describes a SBML file.
... | """
Return the initial amount of a species.
If species.isSetInitialAmount() == True, return the initial amount.
Otherwise, return the initial concentration.
***** args *****
species: a libsbml.Species object
"""
if species.isSetInitialAmount():
return species.getInitia... | identifier_body | |
generateTemplate.py | data\n\n")
out_file.write("<data>\n")
out_file.write("# times: For ABC SMC, times must be a whitespace delimited list\n")
out_file.write("# In simulation mode these are the timepoints for which the simulations will be output\n")
if have_data == False:
out_file.write("<times> 0 1 2 3 4 5 6 7 8 9... | if parameterId[k]==listOfRules[j].getVariable(): Print = False | conditional_block | |
generateTemplate.py | (species):
"""
Return the initial amount of a species.
If species.isSetInitialAmount() == True, return the initial amount.
Otherwise, return the initial concentration.
***** args *****
species: a libsbml.Species object
"""
if species.isSetInitialAmount():
return sp... | getSpeciesValue | identifier_name | |
generateTemplate.py | (defaults to 0.9)\n")
out_file.write("<autoepsilon>\n")
out_file.write("<finalepsilon> 1.0 </finalepsilon>\n")
out_file.write("<alpha> 0.9 </alpha>\n")
out_file.write("</autoepsilon>\n\n")
out_file.write("# OR\n")
out_file.write("# Series of epsilons. (Whitespace delimited list)\n")
out_f... | out_file.write("# one of \n")
out_file.write("# constant, value \n")
out_file.write("# normal, mean, variance \n") | random_line_split | |
toggle_button.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
fn set_inconsistent(&mut self, setting: bool) {
unsafe { ffi::gtk_toggle_button_set_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(setting)); }
}
fn get_inconsistent(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_wi... | {
unsafe { to_bool(ffi::gtk_toggle_button_get_active(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
} | identifier_body |
toggle_button.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | fn set_inconsistent(&mut self, setting: bool) {
unsafe { ffi::gtk_toggle_button_set_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(setting)); }
}
fn get_inconsistent(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widg... | fn get_active(&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_active(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
| random_line_split |
toggle_button.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | (&self) -> bool {
unsafe { to_bool(ffi::gtk_toggle_button_get_active(GTK_TOGGLEBUTTON(self.unwrap_widget()))) }
}
fn set_inconsistent(&mut self, setting: bool) {
unsafe { ffi::gtk_toggle_button_set_inconsistent(GTK_TOGGLEBUTTON(self.unwrap_widget()), to_gboolean(setting)); }
}
fn get_i... | get_active | identifier_name |
atr.py | from __future__ import print_function
import numpy as np
h, l, c = np.loadtxt('data.csv', delimiter=',', usecols=(4, 5, 6), unpack=True)
N = 5
h = h[-N:]
l = l[-N:]
print("len(h)", len(h), "len(l)", len(l))
print("Close", c)
previousclose = c[-N -1: -1]
print("len(previousclose)", len(previousclose))
print("Previou... |
print("ATR", atr)
| atr[i] = (N - 1) * atr[i - 1] + truerange[i]
atr[i] /= N | conditional_block |
atr.py | from __future__ import print_function
import numpy as np
h, l, c = np.loadtxt('data.csv', delimiter=',', usecols=(4, 5, 6), unpack=True)
N = 5
h = h[-N:]
l = l[-N:]
print("len(h)", len(h), "len(l)", len(l))
print("Close", c)
previousclose = c[-N -1: -1]
print("len(previousclose)", len(previousclose))
print("Previou... | atr[i] /= N
print("ATR", atr) | random_line_split | |
getting_started.py | #!/usr/bin/env python
# Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | for row in query_response['rows']:
print('\t'.join(field['v'] for field in row['f']))
# [END print_results]
except HttpError as err:
print('Error: {}'.format(err.content))
raise err
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=_... | bigquery_service = googleapiclient.discovery.build('bigquery', 'v2')
# [END build_service]
try:
# [START run_query]
query_request = bigquery_service.jobs()
query_data = {
'query': (
'SELECT TOP(corpus, 10) as title, '
'COUNT(*) as unique_words... | identifier_body |
getting_started.py | #!/usr/bin/env python
# Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | (project_id):
# [START build_service]
# Construct the service object for interacting with the BigQuery API.
bigquery_service = googleapiclient.discovery.build('bigquery', 'v2')
# [END build_service]
try:
# [START run_query]
query_request = bigquery_service.jobs()
query_data ... | main | identifier_name |
getting_started.py | #!/usr/bin/env python
# Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
def main(project_id):
# [START build_service]
# Construct the service object for interacting with the BigQuery API.
bigquery_service = googleapiclient.discovery.build('bigquery', 'v2')
# [END build_service]
try:
# [START run_query]
query_request = bigquery_service.jobs()
q... | from googleapiclient.errors import HttpError | random_line_split |
getting_started.py | #!/usr/bin/env python
# Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
# [END all]
| parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('project_id', help='Your Google Cloud Project ID.')
args = parser.parse_args()
main(args.project_id) | conditional_block |
merkleTree.js | import {keccak256, bufferToHex} from "ethereumjs-util"
export default class MerkleTree {
constructor(elements) {
// Filter empty strings and hash elements
this.elements = elements.filter(el => el).map(el => keccak256(el))
// Deduplicate elements
this.elements = this.bufDedup(this.eleme... |
idx = Math.floor(idx / 2)
return proof
}, [])
}
getHexProof(el) {
const proof = this.getProof(el)
return this.bufArrToHexArr(proof)
}
getPairElement(idx, layer) {
const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1
if (pairIdx < layer.... | {
proof.push(pairElement)
} | conditional_block |
merkleTree.js | import {keccak256, bufferToHex} from "ethereumjs-util"
export default class MerkleTree {
constructor(elements) {
// Filter empty strings and hash elements
this.elements = elements.filter(el => el).map(el => keccak256(el))
// Deduplicate elements
this.elements = this.bufDedup(this.eleme... | (idx, layer) {
const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1
if (pairIdx < layer.length) {
return layer[pairIdx]
} else {
return null
}
}
bufIndexOf(el, arr) {
let hash
// Convert element to 32 byte hash if it is not one already
... | getPairElement | identifier_name |
merkleTree.js | import {keccak256, bufferToHex} from "ethereumjs-util"
export default class MerkleTree {
constructor(elements) {
// Filter empty strings and hash elements
this.elements = elements.filter(el => el).map(el => keccak256(el))
// Deduplicate elements
this.elements = this.bufDedup(this.eleme... | combinedHash(first, second) {
if (!first) {
return second
}
if (!second) {
return first
}
return keccak256(this.sortAndConcat(first, second))
}
getRoot() {
return this.layers[this.layers.length - 1][0]
}
getHexRoot() {
... | }, [])
}
| random_line_split |
merkleTree.js | import {keccak256, bufferToHex} from "ethereumjs-util"
export default class MerkleTree {
constructor(elements) |
getLayers(elements) {
if (elements.length === 0) {
return [[""]]
}
const layers = []
layers.push(elements)
// Get next layer until we reach the root
while (layers[layers.length - 1].length > 1) {
layers.push(this.getNextLayer(layers[layers.... | {
// Filter empty strings and hash elements
this.elements = elements.filter(el => el).map(el => keccak256(el))
// Deduplicate elements
this.elements = this.bufDedup(this.elements)
// Sort elements
this.elements.sort(Buffer.compare)
// Create layers
this.laye... | identifier_body |
server.tsx | import 'reflect-metadata';
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { ServerStyleSheets } from '@material-ui/styles';
import { Bootstrapper } from 'shared/helpers/bootstrap';
import { IAssets, IAppData } from 'shared/types/app';
import { Html }... |
async function handleAppRequest(req: express.Request, res: express.Response, assets: IAssets) {
const appData = configureApp();
if (__DISABLE_SSR__) {
res.status(200).send(renderWithoutSSR(appData, assets));
}
/* used to handle redirect inside rendered app */
const context: { url?: string } = {};
t... | {
try {
await handleAppRequest(req, res, assets);
} catch (e) {
res.status(500).send(JSON.stringify(e));
}
} | identifier_body |
server.tsx | import 'reflect-metadata';
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { ServerStyleSheets } from '@material-ui/styles';
import { Bootstrapper } from 'shared/helpers/bootstrap';
import { IAssets, IAppData } from 'shared/types/app';
import { Html }... |
/* used to handle redirect inside rendered app */
const context: { url?: string } = {};
try {
const document = await renderWithSSR(appData, assets, req.originalUrl, context);
context.url
? res.redirect(context.url)
: res.status(200).send(document);
} catch (error) {
res.status(500).se... | {
res.status(200).send(renderWithoutSSR(appData, assets));
} | conditional_block |
server.tsx | import 'reflect-metadata';
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { ServerStyleSheets } from '@material-ui/styles';
import { Bootstrapper } from 'shared/helpers/bootstrap';
import { IAssets, IAppData } from 'shared/types/app';
import { Html }... |
// server export used in server/starters.tsx
export { render }; | } | random_line_split |
server.tsx | import 'reflect-metadata';
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { ServerStyleSheets } from '@material-ui/styles';
import { Bootstrapper } from 'shared/helpers/bootstrap';
import { IAssets, IAppData } from 'shared/types/app';
import { Html }... | (
{ req, res, assets }: { req: express.Request; res: express.Response; assets: IAssets },
) {
try {
await handleAppRequest(req, res, assets);
} catch (e) {
res.status(500).send(JSON.stringify(e));
}
}
async function handleAppRequest(req: express.Request, res: express.Response, assets: IAssets) {
cons... | render | identifier_name |
05_table_maker.py | #!/usr/bin/env python
# encoding: utf-8
"""
Creates a new sound table from random chunks of a soundfile.
"""
from pyo import *
import random, os
s = Server(sr=44100, nchnls=2, buffersize=512, duplex=0).boot()
path = "../snds/baseballmajeur_m.aif"
dur = sndinfo(path)[1]
t = SndTable(path, start=0, stop=1)
amp = Fade... |
caller = CallAfter(function=delayed_generation, time=0.005).stop()
def gen():
amp.stop()
caller.play()
gen()
s.gui(locals()) | start = random.uniform(0, dur*0.7)
duration = random.uniform(.1, .3)
t.setSound(path, start=start, stop=start+duration)
for i in range(10):
addsnd()
a.dur = t.getDur()
a.reset()
amp.play() | identifier_body |
05_table_maker.py | #!/usr/bin/env python
# encoding: utf-8
"""
Creates a new sound table from random chunks of a soundfile.
"""
from pyo import *
import random, os
s = Server(sr=44100, nchnls=2, buffersize=512, duplex=0).boot()
path = "../snds/baseballmajeur_m.aif"
dur = sndinfo(path)[1]
t = SndTable(path, start=0, stop=1)
amp = Fade... |
a.dur = t.getDur()
a.reset()
amp.play()
caller = CallAfter(function=delayed_generation, time=0.005).stop()
def gen():
amp.stop()
caller.play()
gen()
s.gui(locals()) | addsnd() | conditional_block |
05_table_maker.py | #!/usr/bin/env python
# encoding: utf-8
"""
Creates a new sound table from random chunks of a soundfile.
"""
from pyo import *
import random, os
s = Server(sr=44100, nchnls=2, buffersize=512, duplex=0).boot()
path = "../snds/baseballmajeur_m.aif"
dur = sndinfo(path)[1]
t = SndTable(path, start=0, stop=1)
amp = Fade... |
def delayed_generation():
start = random.uniform(0, dur*0.7)
duration = random.uniform(.1, .3)
t.setSound(path, start=start, stop=start+duration)
for i in range(10):
addsnd()
a.dur = t.getDur()
a.reset()
amp.play()
caller = CallAfter(function=delayed_generation, time=0.005).stop()
... | t.insert(path, pos=pos, crossfade=cross, start=start, stop=start+duration) | random_line_split |
05_table_maker.py | #!/usr/bin/env python
# encoding: utf-8
"""
Creates a new sound table from random chunks of a soundfile.
"""
from pyo import *
import random, os
s = Server(sr=44100, nchnls=2, buffersize=512, duplex=0).boot()
path = "../snds/baseballmajeur_m.aif"
dur = sndinfo(path)[1]
t = SndTable(path, start=0, stop=1)
amp = Fade... | ():
start = random.uniform(0, dur*0.7)
duration = random.uniform(.1, .3)
t.setSound(path, start=start, stop=start+duration)
for i in range(10):
addsnd()
a.dur = t.getDur()
a.reset()
amp.play()
caller = CallAfter(function=delayed_generation, time=0.005).stop()
def gen():
amp.stop... | delayed_generation | identifier_name |
formService.js |
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apac... | templateRequest = emptyTemplate.promise;
}
// Defer compilation of template pending successful retrieval
var compiledTemplate = $q.defer();
// Resolve with compiled HTML upon success
templateRequest.then(function templateRetrieved(html) {
... | emptyTemplate.resolve(''); | random_line_split |
train_test.py | # coding=utf-8
# Copyright 2022 The Trax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | (tf.test.TestCase):
def testRuns(self):
with mock.patch.object(dataset, 'load', new=fake_mnist_data):
train.train(
batch_size=1,
learning_rate=0.1,
num_training_iters=10,
validation_steps=5)
train.train(
batch_size=2,
learning_rate=0.1,
... | TFNumpyMnistExampleTest | identifier_name |
train_test.py | # coding=utf-8
# Copyright 2022 The Trax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
if __name__ == '__main__':
tf.compat.v1.enable_eager_execution()
tf.test.main()
| def gen_examples(num_examples):
x = np.array(
np.random.randn(num_examples, 784), copy=False, dtype=np.float32)
y = np.zeros((num_examples, 10), dtype=np.float32)
y[:][0] = 1.
return (x, y)
return (gen_examples(100), gen_examples(10), gen_examples(10)) | identifier_body |
train_test.py | # coding=utf-8
# Copyright 2022 The Trax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
return (gen_examples(100), gen_examples(10), gen_examples(10))
if __name__ == '__main__':
tf.compat.v1.enable_eager_execution()
tf.test.main() | return (x, y) | random_line_split |
train_test.py | # coding=utf-8
# Copyright 2022 The Trax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | tf.compat.v1.enable_eager_execution()
tf.test.main() | conditional_block | |
lhpFunctions.py | "e", "f", "g", "h", "i", "s", ",", "'", "1", "2", "4", "8", "6", "3", ".", "5", "7", "9", "0", "M", "B", "I", "N", "S", "E", "R", "T", " ", "-", "V","U" ,"A", "L", "O", "D", ":", "m", "j", "n", "u", "C", "H", "k", "l", "o", "p", "r", "t", "v", "z", "K", "P", "%", "/"]
def pixel2Ton(pixel):
rezolucija = 90
indent ... |
def checkXColision(nota, cursorLeft, trajanje):
if ( nota.pozicija == cursorLeft):
print("kolizija na pocetku note s CL")
return(True)
elif ( cursorLeft > nota.pozicija ) & ( cursorLeft < ( nota.pozicija + nota.trajanje )):
print("kolizija na sredini note s CL")
return(True)
elif ( cursorLeft ==... | def __init__(self, pozicija, ton, trajanje):
self.pozicija = pozicija
self.ton = ton
self.trajanje = trajanje
self.sprite = 0
self.bg_scroll_x = 0
self.bg_scroll_y = 0
self.bg_scroll_x_offset = 0 #used for cursor follow efect
self.bg_scroll_y_offset = 0 #used for cursor follow efect
... | identifier_body |
lhpFunctions.py | "e", "f", "g", "h", "i", "s", ",", "'", "1", "2", "4", "8", "6", "3", ".", "5", "7", "9", "0", "M", "B", "I", "N", "S", "E", "R", "T", " ", "-", "V","U" ,"A", "L", "O", "D", ":", "m", "j", "n", "u", "C", "H", "k", "l", "o", "p", "r", "t", "v", "z", "K", "P", "%", "/"]
def pixel2Ton(pixel):
rezolucija = 90
indent ... | 1 : ("e", ",,"),
2 : ("f", ",,"),
3 : ("g", ",,"),
4 : ("a", ",,"),
5 : ("h", ",,"),
6 : ("c", ","),
7 : ("d", ","),
8 : ("e", ","),
9 : ("f", ","),
10 : ("g", ","),
11 : ("a", ","),
12 : ("h", ","),
13 : ("c", ""),
... | }
kljucevi = {
0 : ("d", ",,"), | random_line_split |
lhpFunctions.py | e", "f", "g", "h", "i", "s", ",", "'", "1", "2", "4", "8", "6", "3", ".", "5", "7", "9", "0", "M", "B", "I", "N", "S", "E", "R", "T", " ", "-", "V","U" ,"A", "L", "O", "D", ":", "m", "j", "n", "u", "C", "H", "k", "l", "o", "p", "r", "t", "v", "z", "K", "P", "%", "/"]
def pixel2Ton(pixel):
rezolucija = 90
indent = ... |
elif ( ( cursorLeft + trajanje ) == ( nota.pozicija + nota.trajanje )):
print("na kraju note s CR")
return(6)
elif ( ( cursorLeft < nota | print("na sredini note sa CR")
return(5) | conditional_block |
lhpFunctions.py | e", "f", "g", "h", "i", "s", ",", "'", "1", "2", "4", "8", "6", "3", ".", "5", "7", "9", "0", "M", "B", "I", "N", "S", "E", "R", "T", " ", "-", "V","U" ,"A", "L", "O", "D", ":", "m", "j", "n", "u", "C", "H", "k", "l", "o", "p", "r", "t", "v", "z", "K", "P", "%", "/"]
def pixel2Ton(pixel):
rezolucija = 90
indent = ... | (slovo):
return(slovo.replace(',', '').replace('\'', '').upper())
def slovoPozicija(slovo):
for i in [i for i,x in enumerate(spriteSlova) if x == slovo]:
return(i)
rijecnikNotnihVrijednosti = {
0 : "16",
1 : "8",
2 : "8.",
3 : "4",
4 : "416",
5 : "4.",
6 : "4.16",
7 : "2",
8 : "216",
9 : "... | removeLily | identifier_name |
parsed.rs | This is what the `ParsedDName` type does: It takes a reference to a
/// message and an indicator where inside the message the name starts and
/// then walks over the message as necessity dictates. When created while
/// parsing a message, the parser quickly walks over the labels to make sure
/// that the name indeed i... | other: &N) -> bool {
let self_iter = self.labelettes();
let other_iter = other.labelettes();
self_iter.eq(other_iter)
}
}
impl<'a> PartialEq<str> for ParsedDName<'a> {
fn eq(&self, other: &str) -> bool {
use std::str::FromStr;
let other = match DNameBuf::from_str(other)... | , | identifier_name |
parsed.rs | This is what the `ParsedDName` type does: It takes a reference to a
/// message and an indicator where inside the message the name starts and
/// then walks over the message as necessity dictates. When created while
/// parsing a message, the parser quickly walks over the labels to make sure
/// that the name indeed i... | }
}
/// Splits off the part that is uncompressed.
fn split_uncompressed(&self) -> (Option<&'a DNameSlice>, Option<Self>) {
let mut name = self.clone();
loop {
name = match name.split_label() {
Ok((_, Some(new_name))) => new_name,
Ok((label, None)... | Ok((label, Some(ParsedDName{message: self.message,
start: start})))
}
| conditional_block |
parsed.rs | (res),
Ok(false) => { }
Err(x) => {
pos = x;
break
}
}
}
// Step 2: Walk over the rest to see if the name is valid.
let mut parser = parser.clone();
parser.remove_limit();
try!(pa... | }
Ok(())
}
} | random_line_split | |
parsed.rs | This is what the `ParsedDName` type does: It takes a reference to a
/// message and an indicator where inside the message the name starts and
/// then walks over the message as necessity dictates. When created while
/// parsing a message, the parser quickly walks over the labels to make sure
/// that the name indeed i... | -- PartialEq and Eq
impl<'a, N: DName> PartialEq<N> for ParsedDName<'a> {
fn eq(&self, other: &N) -> bool {
let self_iter = self.labelettes();
let other_iter = other.labelettes();
self_iter.eq(other_iter)
}
}
impl<'a> PartialEq<str> for ParsedDName<'a> {
fn eq(&self, other: &str) -... | NameLabels::from_parsed(self.clone())
}
}
//- | identifier_body |
reproducibility.py | import json, logging, os, re, subprocess, shlex
from tools import get_category_by_status
log = logging.getLogger()
meta_files = ['Disassembly', 'Stacktrace', 'Registers',
'SegvAnalysis', 'ProcMaps', "BootLog" , "CoreDump",
"BootDmesg", "syslog", "UbiquityDebug.gz", "Casper.gz",
"UbiquityPar... | (metadata, bugdir):
indicators = {}
# look for file arg; this needs work TODO
cmdline = None
uri = None
for line in metadata['description'].splitlines():
if "proccmdline" in line.lower():
cmdline = ":".join(line.split(":")[1:]).strip()
try:
toks = shl... | get | identifier_name |
reproducibility.py | import json, logging, os, re, subprocess, shlex
from tools import get_category_by_status | meta_files = ['Disassembly', 'Stacktrace', 'Registers',
'SegvAnalysis', 'ProcMaps', "BootLog" , "CoreDump",
"BootDmesg", "syslog", "UbiquityDebug.gz", "Casper.gz",
"UbiquityPartman.gz", "UbiquityDm.gz", "GdmLog", "XorgLog"
"log", "Log"]
def get(metadata, bugdir):
indicators = {}
... |
log = logging.getLogger()
| random_line_split |
reproducibility.py | import json, logging, os, re, subprocess, shlex
from tools import get_category_by_status
log = logging.getLogger()
meta_files = ['Disassembly', 'Stacktrace', 'Registers',
'SegvAnalysis', 'ProcMaps', "BootLog" , "CoreDump",
"BootDmesg", "syslog", "UbiquityDebug.gz", "Casper.gz",
"UbiquityPar... | # look for interesting attachments; ugly
interesting_files = []
for f in os.listdir(bugdir):
fpath = os.path.join(bugdir, f)
if not os.path.isfile(fpath):
continue
for fn in meta_files:
if fn.lower() in f.lower():
break
else:
... | indicators = {}
# look for file arg; this needs work TODO
cmdline = None
uri = None
for line in metadata['description'].splitlines():
if "proccmdline" in line.lower():
cmdline = ":".join(line.split(":")[1:]).strip()
try:
toks = shlex.split(cmdline)
... | identifier_body |
reproducibility.py | import json, logging, os, re, subprocess, shlex
from tools import get_category_by_status
log = logging.getLogger()
meta_files = ['Disassembly', 'Stacktrace', 'Registers',
'SegvAnalysis', 'ProcMaps', "BootLog" , "CoreDump",
"BootDmesg", "syslog", "UbiquityDebug.gz", "Casper.gz",
"UbiquityPar... |
else:
# no break in loop above, i.e. still interested
out = subprocess.check_output(["file", fpath])
ftype = out.split(":")[-1]
if ftype.strip() == "empty":
continue
for tstr in ["ASCII", "text", "core file"]:
... | if fn.lower() in f.lower():
break | conditional_block |
test_log_depot_operation.py | self.machine_ip = None
@property
def ftp(self):
if self.protocol == "anon_ftp":
ftp_user_name = "anonymous"
ftp_password = ""
# case anonymous connection cfme works only with hardcoded "incoming" directory
# incoming folder used for https://bugzilla.redh... | data = conf.cfme_data.get("log_db_operations", {})
depot_provider_key = data["log_db_depot_template"]["provider"]
depot_template_name = data["log_db_depot_template"]["template_name"]
prov = get_mgmt(depot_provider_key)
deploy_template(depot_provider_key,
depot_machine_name,
... | depot_machine_name = "test_long_log_depot_{}".format(fauxfactory.gen_alphanumeric()) | random_line_split |
test_log_depot_operation.py | _ip = None
@property
def ftp(self):
if self.protocol == "anon_ftp":
ftp_user_name = "anonymous"
ftp_password = ""
# case anonymous connection cfme works only with hardcoded "incoming" directory
# incoming folder used for https://bugzilla.redhat.com/show_b... | emp_appliance_preconfig, app_creds_modscope,
temp_appliance_unconfig):
hostname = temp_appliance_preconfig.address
temp_appliance_unconfig.appliance_console_cli.configure_appliance_external_join(hostname,
app_creds_modscope['username'], app_creds_modscope['password'], '... | nfigured_external_appliance(t | identifier_name |
test_log_depot_operation.py | .machine_ip = None
@property
def ftp(self):
if self.protocol == "anon_ftp":
ftp_user_name = "anonymous"
ftp_password = ""
# case anonymous connection cfme works only with hardcoded "incoming" directory
# incoming folder used for https://bugzilla.redhat.co... | fixtures = ['log_depot']
data = conf.cfme_data.get("log_db_operations", {})
depots = []
ids = []
creds = conf.credentials[data['credentials']]
for protocol, proto_data in data['protocols'].iteritems():
if proto_data['use_for_log_collection']:
depots.append([LogDepotType(
... | turn
| conditional_block |
test_log_depot_operation.py | .machine_ip = None
@property
def ftp(self):
if self.protocol == "anon_ftp":
ftp_user_name = "anonymous"
ftp_password = ""
# case anonymous connection cfme works only with hardcoded "incoming" directory
# incoming folder used for https://bugzilla.redhat.co... | # Prepare empty workspace
with log_depot.ftp as ftp:
# move to upload folder
ftp.cwd(ftp.upload_dir)
# delete all files
ftp.recursively_delete()
# Start the collection
configured_depot.collect_all()
# Check it on FTP
check_ftp(log_depot.ftp, appliance.server_name... | th log_depot.ftp as ftp:
ftp.cwd(ftp.upload_dir)
ftp.recursively_delete()
| identifier_body |
misc.rs | //! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty}; | use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Adds a new temporary value of type `ty` storing the result of
/// evaluating `expr`.
///
/// N.B., **No cleanup is scheduled for this temporary.** You should
/// call `schedule_d... | random_line_split | |
misc.rs | //! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Ad... |
}
| {
let tcx = self.tcx;
let ty = place.ty(&self.local_decls, tcx).ty;
if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, DUMMY_SP) {
Operand::Move(place)
} else {
Operand::Copy(place)
}
} | identifier_body |
misc.rs | //! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Ad... |
}
}
| {
Operand::Copy(place)
} | conditional_block |
misc.rs | //! Miscellaneous builder routines that are not specific to building any particular
//! kind of thing.
use crate::build::Builder;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Ad... | (
&mut self,
block: BasicBlock,
source_info: SourceInfo,
value: u64,
) -> Place<'tcx> {
let usize_ty = self.tcx.types.usize;
let temp = self.temp(usize_ty, source_info.span);
self.cfg.push_assign_constant(
block,
source_info,
... | push_usize | identifier_name |
sky-scroll.ssr.js | (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var _throttle = _interopDefault(require('lodash.throttle'));
var SkyScrollPlugin = {
install: function install(Vue, options) {
var _defaults = {
throttle: 0,
};
var config = Object.assign({}, _defaults, options);
v... | _interopDefault | identifier_name | |
sky-scroll.ssr.js |
var _throttle = _interopDefault(require('lodash.throttle'));
var SkyScrollPlugin = {
install: function install(Vue, options) {
var _defaults = {
throttle: 0,
};
var config = Object.assign({}, _defaults, options);
var _vm = new Vue({
data: function data() {
return {
scroll: {
x: 0,
... | { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | identifier_body | |
sky-scroll.ssr.js | (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var _throttle = _interopDefault(require('lodash.throttle'));
var SkyScrollPlugin = {
install: function install(Vue, options) {
var _defaults = {
throttle: 0,
};
var config = Object.assign({}, _defaults, options);
var _vm = new Vue({
... |
// Setup reactive $SkyScroll, $scroll and $window variables on instance
Vue.util.defineReactive(this, '$SkyScroll', $SkyScroll);
Vue.util.defineReactive(this, '$scroll', $SkyScroll.scroll);
Vue.util.defineReactive(this, '$window', $SkyScroll.window);
// Prepare _skyScroll - it will be used as a co... | $SkyScroll: {
onMounted: true, // Run scroll and resize functions on mounted by default
},
beforeCreate: function beforeCreate() {
var this$1 = this; | random_line_split |
sky-scroll.ssr.js | (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var _throttle = _interopDefault(require('lodash.throttle'));
var SkyScrollPlugin = {
install: function install(Vue, options) {
var _defaults = {
throttle: 0,
};
var config = Object.assign({}, _defaults, options);
var _vm = new Vue({
... | width: bounds.width,
height: bounds.height,
};
this$1.$set(this$1, '$dimensions', dim);
return dim;
};
this.$SkyScroll.on('resize', this._skyScroll.recalculateDimensions);
}
// If $SkyScroll.scroll function on instance:
if (typeof scrollFn === 'function') {
/... | {
// Setup $dimensions object on instance + make reactive
this.$dimensions = {
top: 0,
bottom: 0,
left: 0,
right: 0,
width: 0,
height: 0,
};
Vue.util.defineReactive(this, '$dimensions', this.$dimensions);
// Setup recalculate method on resize
this._skyS... | conditional_block |
build.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | fn main() {
pyo3_build_config::add_extension_module_link_args();
// NB: The native extension only works with the Python interpreter version it was built with
// (e.g. Python 3.7 vs 3.8).
println!("cargo:rerun-if-env-changed=PY");
} | // Arc<Mutex> can be more clear than needing to grok Orderings:
#![allow(clippy::mutex_atomic)]
| random_line_split |
build.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | () {
pyo3_build_config::add_extension_module_link_args();
// NB: The native extension only works with the Python interpreter version it was built with
// (e.g. Python 3.7 vs 3.8).
println!("cargo:rerun-if-env-changed=PY");
}
| main | identifier_name |
build.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | {
pyo3_build_config::add_extension_module_link_args();
// NB: The native extension only works with the Python interpreter version it was built with
// (e.g. Python 3.7 vs 3.8).
println!("cargo:rerun-if-env-changed=PY");
} | identifier_body | |
db.rs | use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use rocket::http::Status;
use rocket::request::{self, FromRequest};
use rocket::{Outcome, Request, State};
use std::ops::Deref;
type PgPool = Pool<ConnectionManager<PgConnection>>;
pub struct DbConn(pub PooledConnection<Conne... |
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
let pool = request.guard::<State<PgPool>>()?;
match pool.get() {
Ok(conn) => Outcome::Success(DbConn(conn)),
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
}
}
}
im... | impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
type Error = (); | random_line_split |
db.rs | use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use rocket::http::Status;
use rocket::request::{self, FromRequest};
use rocket::{Outcome, Request, State};
use std::ops::Deref;
type PgPool = Pool<ConnectionManager<PgConnection>>;
pub struct DbConn(pub PooledConnection<Conne... | () -> PgPool {
let manager = ConnectionManager::<PgConnection>::new(env!("DATABASE_URL"));
Pool::new(manager).expect("db pool")
}
| init_pool | identifier_name |
queues.py | #!/usr/bin/env python
"""Queue definitions.
This module defines the queues where a worker may look for work.
"""
from grr_response_core.lib import rdfvalue
| WORKER_LIST = list(map(rdfvalue.RDFURN, ["CA", "W", "E", "F", "H", "S"]))
# The normal queue for enrollment messages.
ENROLLMENT = rdfvalue.RDFURN("E")
# The normal queue for flows. Must be kept synchronized with the default value
# of FlowRunnerArgs.queue.
FLOWS = rdfvalue.RDFURN("F")
# The normal queue for hunts. ... | # Queues that a standard worker should work from, highest priority first.
#
# "W" and "CA" are deprecated, but included until we are sure that they are
# empty. | random_line_split |
manage_team.js | angular.module('teamform-manage_team-app', ['firebase'])
.controller('ManageTeamCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {
initalizeFirebase();
var teamleader;
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var userPath ... | $scope.teamtaginfo.Give_and_go = 0;
$scope.teamtaginfo.The_long_through_ball = 0;
$scope.teamtaginfo.Triangular_movement = 0;
$scope.teamtaginfo.Swapping_of_the_wing_man = 0;
$scope.teamtaginfo.Strong_side_overloads = 0;
$scope.teamtaginfo.The_zone_defence = 0;
$scope.teamtaginfo.Depth_consideratio... | $scope.teamtaginfo.The_zone_defence = $scope.teamtaginput.the_zone_defence;
$scope.teamtaginfo.Depth_considerations = $scope.teamtaginput.depth_considerations;
$scope.teamtaginfo.The_man_to_man_defence = $scope.teamtaginput.the_man_to_man_defence;
*/
$scope.teamtaginfo.Pass_and_move = 0; | random_line_split |
manage_team.js | angular.module('teamform-manage_team-app', ['firebase'])
.controller('ManageTeamCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {
initalizeFirebase();
var teamleader;
firebase.auth().onAuthStateChanged(function(user) {
if (user) |
else {}
});
$scope.teaminfo = {TeamLeader:"", Description:"", Forward:"", Midfield:"", LeftBack:"", RightBack:"", Goalkeeper:""};
$scope.input = {teamLeader: teamleader, forward:"", midfield:"", leftBack:"", rightBack:"", goalkeeper:""};
$scope.teamtaginfo = {Pass_and_move:"", Give_and_go:"", The_long_... | {
var userPath = "/user/" + user.uid;
var userref = firebase.database().ref(userPath);
userref.on("value", function(snapshot) {
console.log(snapshot.val());
teamleader = snapshot.val().name;
console.log(teamleader);
}, function (errorObject) {
console.log("The read fai... | conditional_block |
events.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
let tx = &mut self.transactions[len - 1];
tx.set_event(event);
//sc_app_layer_decoder_events_set_event_raw(&mut tx.events, event as u8);
}
}
| {
return;
} | conditional_block |
events.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | * You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use crate::core::*;
use crate::smb::smb::*;
#[derive(AppLayerEvent)]
pub enum SMBEvent ... | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* | random_line_split |
events.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
/// Set events from vector of events.
pub fn set_events(&mut self, events: Vec<SMBEvent>) {
for e in events {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
}
}
impl SMBState {
/// Set an event. The event is set on the most recent transaction.
... | {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
} | identifier_body |
events.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | (&mut self, event: SMBEvent) {
let len = self.transactions.len();
if len == 0 {
return;
}
let tx = &mut self.transactions[len - 1];
tx.set_event(event);
//sc_app_layer_decoder_events_set_event_raw(&mut tx.events, event as u8);
}
}
| set_event | identifier_name |
console.ts | import chalk = require("chalk");
import { take, select } from "redux-saga/effects";
import path = require("path");
import moment = require("moment");
import { titleize } from "inflection";
import { parallel } from "mesh";
import { weakMemo } from "../memo";
import AnsiUp from "ansi_up";
import { reader } from "../mona... | // duration
createLogColorizer(/\s\d+(\.\d+)?(s|ms|m|h|d)(\s|$)/g, (match) => chalk.bold.cyan(match)),
// numbers
createLogColorizer(/\b\d+(\.\d+)?\b/g, (match, inner) => `${chalk.cyan(match)}`),
// strings
createLogColorizer(/"(.*?)"/g, (match, inner) => `"${chalk.blue(inner)}"`),
// tokens
createLo... | // URL
createLogColorizer(/((\w{3,}\:\/\/)|([^\/\s\("':]+)?\/)([^\/\)\s"':]+\/?)+/g, (match) => {
return chalk.yellow(/\w+:\/\//.test(match) ? match : match.replace(cwd + "/", ""))
}),
| random_line_split |
console.ts | import chalk = require("chalk");
import { take, select } from "redux-saga/effects";
import path = require("path");
import moment = require("moment");
import { titleize } from "inflection";
import { parallel } from "mesh";
import { weakMemo } from "../memo";
import AnsiUp from "ansi_up";
import { reader } from "../mona... | export type ConsoleLogState = {
argv?: {
color?: boolean,
hlog?: boolean
},
log?: {
level: LogLevel,
prefix?: string
}
}
const cwd = process.cwd();
const highlighters = [
createLogColorizer(/^INF/, (match) => chalk.bgCyan(match)),
createLogColorizer(/^ERR/, (match) => chalk.bgRed(match)),... | return function(input: string) {
if (!tester.test(input)) return input;
return input.replace(tester, replaceValue);
}
}
| identifier_body |
console.ts | import chalk = require("chalk");
import { take, select } from "redux-saga/effects";
import path = require("path");
import moment = require("moment");
import { titleize } from "inflection";
import { parallel } from "mesh";
import { weakMemo } from "../memo";
import AnsiUp from "ansi_up";
import { reader } from "../mona... | }
}
| const { log: { level: acceptedLevel, prefix }}: ConsoleLogState = (yield select()) || defaultState;
let { text, level }: LogAction = (yield take(LogActionTypes.LOG));
if (!(acceptedLevel & level)) continue;
const log = {
[LogLevel.DEBUG]: console.log.bind(console),
[LogLevel.LOG]: console.lo... | conditional_block |
console.ts | import chalk = require("chalk");
import { take, select } from "redux-saga/effects";
import path = require("path");
import moment = require("moment");
import { titleize } from "inflection";
import { parallel } from "mesh";
import { weakMemo } from "../memo";
import AnsiUp from "ansi_up";
import { reader } from "../mona... | ..args: any[]) {
var argArray = [];
if (args.length) {
var startTagRe = /<span\s+style=(['"])([^'"]*)\1\s*>/gi;
var endTagRe = /<\/span>/gi;
var reResultArray;
argArray.push(arguments[0].replace(startTagRe, '%c').replace(endTagRe, '%c'));
while (reResultArray = startTag... | yledConsoleLog(. | identifier_name |
simple-table-export.spec.ts | import { TestBed } from '@angular/core/testing';
import { Injector } from '@angular/core';
import { XlsxService } from '../xlsx/xlsx.service';
import { XlsxExportOptions } from '../xlsx/interface';
import { SimpleTableExport } from './simple-table-export';
import { STExportOptions, SimpleTableColumn } from './interface... | { title: 'img', index: ['img'], type: 'img', exported: false },
{ title: 'currency', index: ['currency'], type: 'currency' },
{ title: 'date', index: ['date'], type: 'date' },
{ title: 'status', index: ['status'], type: 'yn' }
];
const data: any[] = [
{ id: 1, name: 'n1', img: '1.jpg', currency: 100... | random_line_split | |
simple-table-export.spec.ts | import { TestBed } from '@angular/core/testing';
import { Injector } from '@angular/core';
import { XlsxService } from '../xlsx/xlsx.service';
import { XlsxExportOptions } from '../xlsx/interface';
import { SimpleTableExport } from './simple-table-export';
import { STExportOptions, SimpleTableColumn } from './interface... | (options: XlsxExportOptions) {
return options;
}
}
const columns: SimpleTableColumn[] = [
{ title: 'id', index: ['id'], type: 'checkbox' },
{ title: 'name', index: ['name'] },
{ title: 'img', index: ['img'], type: 'img', exported: false },
{ title: 'currency', index: ['currency'], type: 'cur... | export | identifier_name |
param_route_path.ts | `PathSegment`s, each of which can
* match a segment of a URL. Different kind of `PathSegment`s match
* URL segments in different ways...
*/
interface PathSegment {
name: string;
generate(params: TouchMap): string;
match(path: string): boolean;
specificity: string;
hash: string;
}
/**
* Identified by a `... | constructor(public name: string) {}
match(path: string): boolean { return path.length > 0; }
generate(params: TouchMap): string {
if (!StringMapWrapper.contains(params.map, this.name)) {
throw new BaseException(
`Route generator for '${this.name}' was not included in parameters passed.`);
... | static paramMatcher = /^:([^\/]+)$/g;
specificity = '1';
hash = ':'; | random_line_split |
param_route_path.ts | `PathSegment`s, each of which can
* match a segment of a URL. Different kind of `PathSegment`s match
* URL segments in different ways...
*/
interface PathSegment {
name: string;
generate(params: TouchMap): string;
match(path: string): boolean;
specificity: string;
hash: string;
}
/**
* Identified by a `... | (public name: string) {}
match(path: string): boolean { return path.length > 0; }
generate(params: TouchMap): string {
if (!StringMapWrapper.contains(params.map, this.name)) {
throw new BaseException(
`Route generator for '${this.name}' was not included in parameters passed.`);
}
return ... | constructor | identifier_name |
param_route_path.ts | `PathSegment`s, each of which can
* match a segment of a URL. Different kind of `PathSegment`s match
* URL segments in different ways...
*/
interface PathSegment {
name: string;
generate(params: TouchMap): string;
match(path: string): boolean;
specificity: string;
hash: string;
}
/**
* Identified by a `... |
match(path: string): boolean { return path.length > 0; }
generate(params: TouchMap): string {
if (!StringMapWrapper.contains(params.map, this.name)) {
throw new BaseException(
`Route generator for '${this.name}' was not included in parameters passed.`);
}
return encodeDynamicSegment(nor... | {} | identifier_body |
param_route_path.ts | `PathSegment`s, each of which can
* match a segment of a URL. Different kind of `PathSegment`s match
* URL segments in different ways...
*/
interface PathSegment {
name: string;
generate(params: TouchMap): string;
match(path: string): boolean;
specificity: string;
hash: string;
}
/**
* Identified by a `... |
auxiliary = currentUrlSegment.auxiliary;
}
return new MatchedUrl(urlPath, urlParams, allParams, auxiliary, nextUrlSegment);
}
generateUrl(params: {[key: string]: any}): GeneratedUrl {
var paramTokens = new TouchMap(params);
var path = [];
for (var i = 0; i < this._segments.length; i+... | {
allParams = positionalParams;
} | conditional_block |
App.tsx | import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import { ThemeProvider } from "@material-ui/styles";
import { CssBaseline } from "@material-ui/core";
import { createMuiTheme } from "@material-ui/core/styles";
import View from "./components/View";
import Home from "./views/Hom... | },
body2: {
...LibreBaskerville,
},
subtitle1: {
...Monsterrat,
},
},
});
const App: React.FC<Props> = ({}) => {
return (
<BrowserRouter>
<ThemeProvider theme={theme}>
<>
<CssBaseline />
<View>
<Switch>
<Route path="/ou... | h6: {
...Monsterrat,
},
body1: {
...LibreBaskerville, | random_line_split |
urls.py | from django.conf.urls import url
from .views import (homepage, aboutpage, newspage, gallerypage, hellopage,
embedpage, widgetpage, newsdetailpage, apps_landing_page, |
urlpatterns = [
# url(r'^apps/$', apps_landing_page, name='apps'),
url(r'^$', homepage, name='home'),
url(r'^about/$', aboutpage, name='about'),
url(r'^getting-started/$', gettingstartedpage, name='gettingstartedpage'),
url(r'^hello/$', hellopage, name='hello'),
url(r'^gallery/$', gallerypage, ... | border_adjustment_plot, docspage, gettingstartedpage) | random_line_split |
ExtensionSemantic.py | #!/usr/bin/env python
#
# Beautiful Capi generates beautiful C API wrappers for your C++ classes
# Copyright (C) 2015 Petr Petrovich Petrov
#
# This file is part of Beautiful Capi.
#
# Beautiful Capi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis... |
self.class_stack.pop()
def process_namespace(self, namespace: TNamespace):
self.class_stack.append(namespace.name)
for nested_namespace in namespace.namespaces:
self.process_namespace(nested_namespace)
for cur_class in namespace.classes:
self.process_class(c... | new_extension_class = deepcopy(cur_class)
new_extension_class.name = lifecycle_extension.name
new_extension_class.lifecycle = lifecycle_extension.lifecycle
new_extension_class.lifecycle_filled = True
new_extension_class.wrap_name = lifecycle_extension.wrap_name
... | conditional_block |
ExtensionSemantic.py | #!/usr/bin/env python
#
# Beautiful Capi generates beautiful C API wrappers for your C++ classes
# Copyright (C) 2015 Petr Petrovich Petrov
#
# This file is part of Beautiful Capi.
#
# Beautiful Capi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis... | new_extension_class.down_cast_filled = True
cur_namespace.classes.append(new_extension_class)
self.class_stack.pop()
def process_namespace(self, namespace: TNamespace):
self.class_stack.append(namespace.name)
for nested_namespace in namespace.namespaces:
... | random_line_split | |
ExtensionSemantic.py | #!/usr/bin/env python
#
# Beautiful Capi generates beautiful C API wrappers for your C++ classes
# Copyright (C) 2015 Petr Petrovich Petrov
#
# This file is part of Beautiful Capi.
#
# Beautiful Capi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis... | (self, namespace: TNamespace):
self.class_stack.append(namespace.name)
for nested_namespace in namespace.namespaces:
self.process_namespace(nested_namespace)
for cur_class in namespace.classes:
self.process_class(cur_class, namespace)
self.class_stack.pop()
d... | process_namespace | identifier_name |
ExtensionSemantic.py | #!/usr/bin/env python
#
# Beautiful Capi generates beautiful C API wrappers for your C++ classes
# Copyright (C) 2015 Petr Petrovich Petrov
#
# This file is part of Beautiful Capi.
#
# Beautiful Capi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis... |
def process(self):
for cur_namespace in self.root_node.namespaces:
self.process_namespace(cur_namespace)
def process(root_node: TBeautifulCapiRoot):
semantic_processor = ExtensionSemanticProcessor(root_node)
semantic_processor.process()
| self.class_stack.append(namespace.name)
for nested_namespace in namespace.namespaces:
self.process_namespace(nested_namespace)
for cur_class in namespace.classes:
self.process_class(cur_class, namespace)
self.class_stack.pop() | identifier_body |
schema.py | # Copyright (c) 2017 pandas-gbq Authors All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Helper methods for BigQuery schemas"""
import copy
# API may return data types as legacy SQL, so maintain a mapping of aliases
# from standard SQL to ... | (schema_old, schema_new):
"""
Given an old BigQuery schema, update it with a new one.
Where a field name is the same, the new will replace the old. Any
new fields not present in the old schema will be added.
Arguments:
schema_old: the old schema to update
schema_new: the new schema... | update_schema | identifier_name |
schema.py | # Copyright (c) 2017 pandas-gbq Authors All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Helper methods for BigQuery schemas"""
import copy
# API may return data types as legacy SQL, so maintain a mapping of aliases
# from standard SQL to ... |
def remove_policy_tags(schema):
"""Manually create the schema objects, removing policyTags.
Workaround for 403 error with policy tags, which are not required in a load
job: https://github.com/googleapis/python-bigquery/pull/557
"""
# Returns a copy rather than modifying the mutable arg,
# pe... | """Manually create the schema objects, adding NULLABLE mode.
Workaround for error in SchemaField.from_api_repr, which required
"mode" to be set:
https://github.com/GoogleCloudPlatform/google-cloud-python/issues/4456
"""
# Returns a copy rather than modifying the mutable arg,
# per Issue #277
... | identifier_body |
schema.py | # Copyright (c) 2017 pandas-gbq Authors All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Helper methods for BigQuery schemas"""
import copy
# API may return data types as legacy SQL, so maintain a mapping of aliases
# from standard SQL to ... |
return {"fields": output_fields}
def add_default_nullable_mode(schema):
"""Manually create the schema objects, adding NULLABLE mode.
Workaround for error in SchemaField.from_api_repr, which required
"mode" to be set:
https://github.com/GoogleCloudPlatform/google-cloud-python/issues/4456
"""... | name = field["name"]
if name in field_indices:
# replace old field with new field of same name
output_fields[field_indices[name]] = field | conditional_block |
schema.py | # Copyright (c) 2017 pandas-gbq Authors All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Helper methods for BigQuery schemas"""
import copy
# API may return data types as legacy SQL, so maintain a mapping of aliases
# from standard SQL to ... |
def update_schema(schema_old, schema_new):
"""
Given an old BigQuery schema, update it with a new one.
Where a field name is the same, the new will replace the old. Any
new fields not present in the old schema will be added.
Arguments:
schema_old: the old schema to update
schema_n... | }
)
return {"fields": fields}
| random_line_split |
model_describe.py | # -*- coding: utf-8 -*-
"""
Provides textual descriptions for :mod:`behave.model` elements.
"""
from behave.textutil import indent
# -----------------------------------------------------------------------------
# FUNCTIONS:
# -----------------------------------------------------------------------------
def escape_ce... | (object):
@staticmethod
def describe_table(table, indentation=None):
"""
Provide a textual description of the table (as used w/ Gherkin).
:param table: Table to use (as :class:`behave.model.Table`)
:param indentation: Line prefix to use (as string, if any).
:return: T... | ModelDescriptor | identifier_name |
model_describe.py | # -*- coding: utf-8 -*-
"""
Provides textual descriptions for :mod:`behave.model` elements.
"""
from behave.textutil import indent
# -----------------------------------------------------------------------------
# FUNCTIONS:
# -----------------------------------------------------------------------------
def escape_ce... |
# -- STEP: Determine max. output size for each column.
max_lengths = []
for col in range(0, len(cell_lengths[0])):
max_lengths.append(max([c[col] for c in cell_lengths]))
# -- STEP: Build textual table description.
lines = []
for r, row in enumerate(all_row... | lengths = [len(escape_cell(c)) for c in row]
cell_lengths.append(lengths) | conditional_block |
model_describe.py | # -*- coding: utf-8 -*-
"""
Provides textual descriptions for :mod:`behave.model` elements.
"""
from behave.textutil import indent
# -----------------------------------------------------------------------------
# FUNCTIONS:
# -----------------------------------------------------------------------------
def escape_ce... | for r, row in enumerate(all_rows):
line = u"|"
for c, (cell, max_length) in enumerate(zip(row, max_lengths)):
pad_size = max_length - cell_lengths[r][c]
line += u" %s%s |" % (escape_cell(cell), " " * pad_size)
line += u"\n"
lines.ap... |
# -- STEP: Build textual table description.
lines = [] | random_line_split |
model_describe.py | # -*- coding: utf-8 -*-
"""
Provides textual descriptions for :mod:`behave.model` elements.
"""
from behave.textutil import indent
# -----------------------------------------------------------------------------
# FUNCTIONS:
# -----------------------------------------------------------------------------
def escape_ce... |
class ModelPrinter(ModelDescriptor):
def __init__(self, stream):
super(ModelPrinter, self).__init__()
self.stream = stream
def print_table(self, table, indentation=None):
self.stream.write(self.describe_table(table, indentation))
self.stream.flush()
def print_docstring(... | """
Provide a textual description of the multi-line text/triple-quoted
doc-string (as used w/ Gherkin).
:param doc_string: Multi-line text to use.
:param indentation: Line prefix to use (as string, if any).
:return: Textual table description (as unicode string).
"""
... | identifier_body |
counters.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Counters", inherited=False, gecko... |
${helpers.predefined_type(
"counter-reset",
"CounterReset",
initial_value="Default::default()",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-lists-3/#propdef-counter-reset",
servo_restyle_damage="rebuild_and_reflow",
)} | servo_restyle_damage="rebuild_and_reflow",
)} | random_line_split |
serialwin32.py | ) #numbers are transformed to a string
else:
return r'\\.\COM%d' % (portnum+1)
class Serial(SerialBase):
"""Serial port implemenation for Win32. This implemenatation requires a
win32all installation."""
BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
1... |
else:
raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
if self._parity == PARITY_NONE:
comDCB.Parity = win32file.NOPARITY
comDCB.fParity = 0 # Dis/Enable Parity Check
elif self._parity == PARITY_EVEN:
comDCB.Par... | comDCB.ByteSize = 8 | conditional_block |
serialwin32.py | ) #numbers are transformed to a string
else:
return r'\\.\COM%d' % (portnum+1)
class Serial(SerialBase):
"""Serial port implemenation for Win32. This implemenatation requires a
win32all installation."""
BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
1... | self._orgTimeouts = win32file.GetCommTimeouts(self.hComPort)
self._reconfigurePort()
# Clear buffers:
# Remove anything that was there
win32file.PurgeComm(self.hComPort,
win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT |
... | """Open port with current settings. This may throw a SerialException
if the port cannot be opened."""
if self._port is None:
raise SerialException("Port must be configured before it can be used.")
self.hComPort = None
try:
self.hComPort = win32file.CreateFile(s... | identifier_body |
serialwin32.py | 0, None)
self._overlappedWrite = win32file.OVERLAPPED()
self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None)
self._isOpen = True
def _reconfigurePort(self):
"""Set commuication parameters on opened port."""
if not self.hComPort:
raise SerialExc... | return MS_DSR_ON & win32file.GetCommModemStatus(self.hComPort) != 0
def getRI(self):
"""Read terminal status line: Ring Indicator"""
if not self.hComPort: raise portNotOpenError | random_line_split | |
serialwin32.py | ) #numbers are transformed to a string
else:
return r'\\.\COM%d' % (portnum+1)
class Serial(SerialBase):
"""Serial port implemenation for Win32. This implemenatation requires a
win32all installation."""
BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
1... | (self, port):
return device(port)
# - - - - - - - - - - - - - - - - - - - - - - - -
def inWaiting(self):
"""Return the number of characters currently in the input buffer."""
flags, comstat = win32file.ClearCommError(self.hComPort)
return comstat.cbIn... | makeDeviceName | identifier_name |
hdtorrents.py | # Author: Idan Gutman
# Modified by jkaberg, https://github.com/jkaberg for SceneAccess
# URL: https://sickrage.ca
#
# This file is part of SickRage.
#
# SickRage 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... | (self):
super(HDTorrentsProvider, self).__init__("HDTorrents", 'https://hd-torrents.org', True)
self.urls.update({
'login': '{base_url}/login.php'.format(**self.urls),
'search': '{base_url}/torrents.php'.format(**self.urls)
})
self.username = None
self.p... | __init__ | identifier_name |
hdtorrents.py | # Author: Idan Gutman
# Modified by jkaberg, https://github.com/jkaberg for SceneAccess
# URL: https://sickrage.ca
#
# This file is part of SickRage.
#
# SickRage 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... |
def _check_auth(self):
if not self.username or not self.password:
sickrage.app.log.warning(
"Invalid username or password. Check your settings")
return True
def login(self):
if any(dict_from_cookiejar(self.session.cookies).values()):
return Tru... | super(HDTorrentsProvider, self).__init__("HDTorrents", 'https://hd-torrents.org', True)
self.urls.update({
'login': '{base_url}/login.php'.format(**self.urls),
'search': '{base_url}/torrents.php'.format(**self.urls)
})
self.username = None
self.password = None
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.