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
check_const.rs
// Copyright 2012-2013 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-MI...
fn visit_expr(&mut self, e: &Expr, _: ()) { match e.node { ExprPath(..) => { match self.def_map.borrow().find(&e.id) { Some(&DefStatic(def_id, _)) if ast_util::is_local(def_id) => { self.visit_item(&*self.a...
{ if self.idstack.iter().any(|x| x == &(it.id)) { self.sess.span_fatal(self.root_it.span, "recursive constant"); } self.idstack.push(it.id); visit::walk_item(self, it, ()); self.idstack.pop(); }
identifier_body
ExtendedInformationType.py
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP is ...
(Model): MODEL_MAP = { 'tag_name': 'extended-information', 'elements': [ {'tag_name': '*'}, ], }
ExtendedInformationType
identifier_name
ExtendedInformationType.py
# Copyright 2016 Casey Jaymes
# PySCAP 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. # # PySCAP is distributed in the hope that it will be useful, # but WITHOUT AN...
# This file is part of PySCAP. #
random_line_split
ExtendedInformationType.py
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP is ...
MODEL_MAP = { 'tag_name': 'extended-information', 'elements': [ {'tag_name': '*'}, ], }
identifier_body
test_tokenization_rag.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
(self): save_dir = os.path.join(self.tmpdirname, "rag_tokenizer") rag_config = RagConfig(question_encoder=DPRConfig().to_dict(), generator=BartConfig().to_dict()) rag_tokenizer = RagTokenizer(question_encoder=self.get_dpr_tokenizer(), generator=self.get_bart_tokenizer()) rag_config.save...
test_save_load_pretrained_with_saved_config
identifier_name
test_tokenization_rag.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
vocab_tokens = dict(zip(vocab, range(len(vocab)))) merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] self.special_tokens_map = {"unk_token": "<unk>"} bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer") os.makedirs(bart_tokenizer_path,...
"<unk>", ]
random_line_split
test_tokenization_rag.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq") input_strings = [ "who got the first nobel prize in physics", "when is the next deadpool movie being released", "which mode is used for short wave broadcast service", "who is the owner of reading...
identifier_body
test_tokenization_rag.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
@require_faiss @require_torch class RagTokenizerTest(TestCase): def setUp(self): self.tmpdirname = tempfile.mkdtemp() self.retrieval_vector_size = 8 # DPR tok vocab_tokens = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"...
from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer
conditional_block
eslint.js
import glob from 'glob'; import { CLIEngine } from 'eslint'; import { assert } from 'chai'; const paths = glob.sync('./src/**/!(*.spec).js'); const engine = new CLIEngine({ envs: ['node', 'mocha'], useEslintrc: true }); const results = engine.executeOnFiles(paths).results; describe('ESLint', function() { ...
}); } function formatMessages(messages) { const errors = messages.map((message) => { return `${message.line}:${message.column} ${message.message.slice(0, -1)} - ${message.ruleId}\n`; }); return `\n${errors.join('')}`; }
{ assert.fail(false, true, formatMessages(messages)); }
conditional_block
eslint.js
import glob from 'glob'; import { CLIEngine } from 'eslint'; import { assert } from 'chai'; const paths = glob.sync('./src/**/!(*.spec).js'); const engine = new CLIEngine({ envs: ['node', 'mocha'], useEslintrc: true }); const results = engine.executeOnFiles(paths).results; describe('ESLint', function() { ...
function formatMessages(messages) { const errors = messages.map((message) => { return `${message.line}:${message.column} ${message.message.slice(0, -1)} - ${message.ruleId}\n`; }); return `\n${errors.join('')}`; }
{ const { filePath, messages, errorCount } = result; it(`validates ${filePath}`, function() { if (messages.length > 0 && errorCount > 0) { assert.fail(false, true, formatMessages(messages)); } }); }
identifier_body
eslint.js
import glob from 'glob'; import { CLIEngine } from 'eslint'; import { assert } from 'chai'; const paths = glob.sync('./src/**/!(*.spec).js'); const engine = new CLIEngine({ envs: ['node', 'mocha'], useEslintrc: true }); const results = engine.executeOnFiles(paths).results; describe('ESLint', function() { ...
function formatMessages(messages) { const errors = messages.map((message) => { return `${message.line}:${message.column} ${message.message.slice(0, -1)} - ${message.ruleId}\n`; }); return `\n${errors.join('')}`; }
}); }
random_line_split
eslint.js
import glob from 'glob'; import { CLIEngine } from 'eslint'; import { assert } from 'chai'; const paths = glob.sync('./src/**/!(*.spec).js'); const engine = new CLIEngine({ envs: ['node', 'mocha'], useEslintrc: true }); const results = engine.executeOnFiles(paths).results; describe('ESLint', function() { ...
(result) { const { filePath, messages, errorCount } = result; it(`validates ${filePath}`, function() { if (messages.length > 0 && errorCount > 0) { assert.fail(false, true, formatMessages(messages)); } }); } function formatMessages(messages) { const errors = messages.map((m...
generateTest
identifier_name
rake.py
# Implementation of RAKE - Rapid Automtic Keyword Exraction algorithm # as described in: # Rose, S., D. Engel, N. Cramer, and W. Cowley (2010). # Automatic keyword extraction from indi-vidual documents. # In M. W. Berry and J. Kogan (Eds.), Text Mining: Applications and Theory.unknown: John Wiley and Sons, Ltd. impo...
# Calculate Word scores = deg(w)/frew(w) word_score = {} for item in word_frequency: word_score.setdefault(item, 0) word_score[item] = word_degree[item]/(word_frequency[item]*1.0) # orig. # word_score[item] = word_frequency[item]/(word_degree[item] * 1.0) #exp. return word_score ...
word_degree[item] = word_degree[item]+word_frequency[item]
conditional_block
rake.py
# Implementation of RAKE - Rapid Automtic Keyword Exraction algorithm # as described in: # Rose, S., D. Engel, N. Cramer, and W. Cowley (2010). # Automatic keyword extraction from indi-vidual documents. # In M. W. Berry and J. Kogan (Eds.), Text Mining: Applications and Theory.unknown: John Wiley and Sons, Ltd. impo...
def run(self, text): sentence_list = split_sentences(text) phrase_list = generate_candidate_keywords(sentence_list, self.__stop_words_pattern) word_scores = calculate_word_scores(phrase_list) keyword_candidates = generate_candidate_keyword_scores(phrase_list, word_scores) ...
self.stop_words_path = stop_words_path self.__stop_words_pattern = build_stop_word_regex(stop_words_path)
identifier_body
rake.py
# Implementation of RAKE - Rapid Automtic Keyword Exraction algorithm # as described in: # Rose, S., D. Engel, N. Cramer, and W. Cowley (2010). # Automatic keyword extraction from indi-vidual documents. # In M. W. Berry and J. Kogan (Eds.), Text Mining: Applications and Theory.unknown: John Wiley and Sons, Ltd. impo...
word_score.setdefault(item, 0) word_score[item] = word_degree[item]/(word_frequency[item]*1.0) # orig. # word_score[item] = word_frequency[item]/(word_degree[item] * 1.0) #exp. return word_score def generate_candidate_keyword_scores(phrase_list, word_score): keyword_candidates = {} fo...
for item in word_frequency:
random_line_split
rake.py
# Implementation of RAKE - Rapid Automtic Keyword Exraction algorithm # as described in: # Rose, S., D. Engel, N. Cramer, and W. Cowley (2010). # Automatic keyword extraction from indi-vidual documents. # In M. W. Berry and J. Kogan (Eds.), Text Mining: Applications and Theory.unknown: John Wiley and Sons, Ltd. impo...
(stop_word_file): """ Utility function to load stop words from a file and return as a list of words @param stop_word_file Path and file name of a file containing stop words. @return list A list of stop words. """ stop_words = [] for line in open(stop_word_file): if line.strip()[0:1] ...
load_stop_words
identifier_name
extrainfo.py
#!/usr/bin/python #-*-coding:utf8-*- from bs4 import BeautifulSoup as Soup #import pandas as pd import glob import sys import re """ Version xml de cfdi 3.3 """ class CFDI(object): def __init__(self, f): """ Constructor que requiere en el parámetro una cadena con el nombre del cfdi. ...
elif(impuesto=='001'): retisr += importe return retiva, retisr @property def lista_valores(self): v = [self.__emisornombre,self.__fechatimbrado, self.__tipo, self.__emisorrfc ] v += [self.__uuid, self.__folio, self.__receptornombre, self.__r...
tiva += importe
conditional_block
extrainfo.py
#!/usr/bin/python #-*-coding:utf8-*- from bs4 import BeautifulSoup as Soup #import pandas as pd import glob import sys import re """ Version xml de cfdi 3.3 """ class CFDI(object): def __init__(self, f): """ Constructor que requiere en el parámetro una cadena con el nombre del cfdi. ...
@property def tipodecambio(self): return self.__tcambio @property def lugar(self): return self.__lugar @property def moneda(self): return self.__moneda @property def traslado_iva(self): return self.__triva @property def traslado_isr(self): ...
turn self.__fechatimbrado
identifier_body
extrainfo.py
#!/usr/bin/python #-*-coding:utf8-*- from bs4 import BeautifulSoup as Soup #import pandas as pd import glob import sys import re """ Version xml de cfdi 3.3 """ class CFDI(object): def __init__(self, f): """ Constructor que requiere en el parámetro una cadena con el nombre del cfdi. ...
retiva += importe elif(self.__version=='3.3'): if(impuesto=='002'): retiva += importe elif(impuesto=='001'): retisr += importe return retiva, retisr @property def lista_valores(self): ...
elif(impuesto=='IVA'):
random_line_split
extrainfo.py
#!/usr/bin/python #-*-coding:utf8-*- from bs4 import BeautifulSoup as Soup #import pandas as pd import glob import sys import re """ Version xml de cfdi 3.3 """ class CFDI(object): def __init__(self, f): """ Constructor que requiere en el parámetro una cadena con el nombre del cfdi. ...
elf): return self.__lugar @property def moneda(self): return self.__moneda @property def traslado_iva(self): return self.__triva @property def traslado_isr(self): return self.__trisr @property def traslado_ieps(self): return self.__trieps ...
gar(s
identifier_name
test_bubble_chart.py
from __future__ import absolute_import # Copyright (c) 2010-2015 openpyxl import pytest from openpyxl.xml.functions import fromstring, tostring from openpyxl.tests.helper import compare_xml @pytest.fixture def BubbleChart(): from ..bubble_chart import BubbleChart return BubbleChart class
: def test_ctor(self, BubbleChart): bubble_chart = BubbleChart() xml = tostring(bubble_chart.to_tree()) expected = """ <bubbleChart> <axId val="10" /> <axId val="20" /> </bubbleChart> """ diff = compare_xml(xml, expected) assert di...
TestBubbleChart
identifier_name
test_bubble_chart.py
from __future__ import absolute_import # Copyright (c) 2010-2015 openpyxl import pytest from openpyxl.xml.functions import fromstring, tostring from openpyxl.tests.helper import compare_xml @pytest.fixture def BubbleChart(): from ..bubble_chart import BubbleChart return BubbleChart class TestBubbleChart: ...
def test_from_xml(self, BubbleChart): src = """ <bubbleChart> <axId val="10" /> <axId val="20" /> </bubbleChart> """ node = fromstring(src) bubble_chart = BubbleChart.from_tree(node) assert dict(bubble_chart) == {}
bubble_chart = BubbleChart() xml = tostring(bubble_chart.to_tree()) expected = """ <bubbleChart> <axId val="10" /> <axId val="20" /> </bubbleChart> """ diff = compare_xml(xml, expected) assert diff is None, diff
identifier_body
test_bubble_chart.py
from __future__ import absolute_import # Copyright (c) 2010-2015 openpyxl import pytest from openpyxl.xml.functions import fromstring, tostring from openpyxl.tests.helper import compare_xml @pytest.fixture def BubbleChart(): from ..bubble_chart import BubbleChart return BubbleChart class TestBubbleChart: ...
""" node = fromstring(src) bubble_chart = BubbleChart.from_tree(node) assert dict(bubble_chart) == {}
<axId val="20" /> </bubbleChart>
random_line_split
10_users.js
exports.seed = function(knex, Promise) { return knex('users') .del() .then(function() { // Inserts seed entries return knex('users').insert([ { id: 1, first_name: 'Steve', last_name: 'Morse', email: 'steve@gmail.com', hashed_password:
id: 2, first_name: 'Steve', last_name: 'Vaughan', email: 'steve2@gmail.com', hashed_password: '$2a$10$ha5HzJWYkRcwQLhT9kHb.eZJ0sT26edJnHAcbpPrF5tMqo3w26Ux2' } ]); }) .then(() => knex.raw("SELECT setval('users_id_seq', (SELECT MAX(...
'$2a$10$Sc1JH2uOZ1Cv0t3hoWoc1OyWCdy6Q6BP07b8zWqjT2A2bBbZr6Ab6' }, {
random_line_split
cell_manhattan_inv.rs
// Copyright 2015 The Noise-rs Developers. // // 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 ...
{ cell4_manhattan_inv(seed, &[point[0] / 16.0, point[1] / 16.0, point[0] / 16.0, point[1] / 16.0]) * 2.0 - 1.0 }
identifier_body
cell_manhattan_inv.rs
// Copyright 2015 The Noise-rs Developers. // // 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 ...
// See the License for the specific language governing permissions and // limitations under the License. //! An example of using cell range noise extern crate noise; use noise::{cell2_manhattan_inv, cell3_manhattan_inv, cell4_manhattan_inv, Seed, Point2}; mod debug; fn main() { debug::render_png("cell2_manhatt...
random_line_split
cell_manhattan_inv.rs
// Copyright 2015 The Noise-rs Developers. // // 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 ...
() { debug::render_png("cell2_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell2_manhattan_inv); debug::render_png("cell3_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell3_manhattan_inv); debug::render_png("cell4_manhattan_inv.png", &Seed::new(0), 1024, 1024, scaled_cell4_manhattan_inv); ...
main
identifier_name
conf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # au...
# The master toctree document. master_doc = 'index' # General information about the project. project = u'{{ cookiecutter.project_name }}' #copyright = u'{{ cookiecutter.year }}, {{ cookiecutter.full_name }}' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, als...
# The encoding of source files. #source_encoding = 'utf-8-sig'
random_line_split
net.py
#!/usr/bin/env python3 # Copyright (c) 2017 The Sarielsaz Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPC calls related to net. Tests correspond to code in rpc/net.cpp. """ import time from test_frame...
(self): self._test_connection_count() self._test_getnettotals() self._test_getnetworkinginfo() self._test_getaddednodeinfo() self._test_getpeerinfo() def _test_connection_count(self): # connect_nodes_bi connects each node to the other assert_equal(self.nodes[...
run_test
identifier_name
net.py
#!/usr/bin/env python3 # Copyright (c) 2017 The Sarielsaz Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPC calls related to net. Tests correspond to code in rpc/net.cpp. """ import time from test_frame...
NetTest().main()
conditional_block
net.py
#!/usr/bin/env python3 # Copyright (c) 2017 The Sarielsaz Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPC calls related to net. Tests correspond to code in rpc/net.cpp. """ import time from test_frame...
def _test_getaddednodeinfo(self): assert_equal(self.nodes[0].getaddednodeinfo(), []) # add a node (node2) to node0 ip_port = "127.0.0.1:{}".format(p2p_port(2)) self.nodes[0].addnode(ip_port, 'add') # check that the node has indeed been added added_nodes = self.nodes...
assert_equal(self.nodes[0].getnetworkinfo()['networkactive'], True) assert_equal(self.nodes[0].getnetworkinfo()['connections'], 2) self.nodes[0].setnetworkactive(False) assert_equal(self.nodes[0].getnetworkinfo()['networkactive'], False) timeout = 3 while self.nodes[0].getnetwor...
identifier_body
net.py
# file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPC calls related to net. Tests correspond to code in rpc/net.cpp. """ import time from test_framework.test_framework import SarielsazTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, connec...
#!/usr/bin/env python3 # Copyright (c) 2017 The Sarielsaz Core developers # Distributed under the MIT software license, see the accompanying
random_line_split
training-repo.ts
import * as sdk from 'botpress/sdk' import { Transaction } from 'knex' import ms from 'ms' import { TrainingId, TrainingState, TrainingSession, I } from './typings' const TABLE_NAME = 'nlu_training_queue' const TRANSACTION_TIMEOUT_MS = ms('5s') const debug = DEBUG('nlu').sub('database') const timeout = (ms: number) =...
() { if (this.transaction) { return this._database.table(TABLE_NAME).transacting(this.transaction) } return this._database.table(TABLE_NAME) } public set = async (trainId: TrainingId, trainState: TrainingState): Promise<void> => { const { botId, language } = trainId const { progress, stat...
table
identifier_name
training-repo.ts
import * as sdk from 'botpress/sdk' import { Transaction } from 'knex' import ms from 'ms' import { TrainingId, TrainingState, TrainingSession, I } from './typings' const TABLE_NAME = 'nlu_training_queue' const TRANSACTION_TIMEOUT_MS = ms('5s') const debug = DEBUG('nlu').sub('database') const timeout = (ms: number) =...
return this.table.insert({ botId, language, progress, status, modifiedOn, owner }) } public has = async (trainId: TrainingId): Promise<boolean> => { const { botId, language } = trainId const result = !!(await this.get({ botId, language })) return result } public get = async (trainId: Training...
{ return this.table.where({ botId, language }).update({ progress, status, modifiedOn, owner }) }
conditional_block
training-repo.ts
import * as sdk from 'botpress/sdk' import { Transaction } from 'knex' import ms from 'ms' import { TrainingId, TrainingState, TrainingSession, I } from './typings' const TABLE_NAME = 'nlu_training_queue' const TRANSACTION_TIMEOUT_MS = ms('5s') const debug = DEBUG('nlu').sub('database') const timeout = (ms: number) =...
public set = async (trainId: TrainingId, trainState: TrainingState): Promise<void> => { const { botId, language } = trainId const { progress, status, owner } = trainState const modifiedOn = this._database.date.now() if (await this.has({ botId, language })) { return this.table.where({ botId, l...
{ if (this.transaction) { return this._database.table(TABLE_NAME).transacting(this.transaction) } return this._database.table(TABLE_NAME) }
identifier_body
training-repo.ts
import * as sdk from 'botpress/sdk' import { Transaction } from 'knex' import ms from 'ms' import { TrainingId, TrainingState, TrainingSession, I } from './typings' const TABLE_NAME = 'nlu_training_queue' const TRANSACTION_TIMEOUT_MS = ms('5s') const debug = DEBUG('nlu').sub('database') const timeout = (ms: number) =...
return this.table.where({ botId, language }).delete() } public clear = async (): Promise<void[]> => { return this.table.delete('*') } } export type ITrainingRepository = I<TrainingRepository> export class TrainingRepository implements TrainingRepository { private _context: TrainingTransactionContext ...
const { botId, language } = trainId
random_line_split
editor.js
import cloneDeep from 'lodash/cloneDeep' import merge from 'lodash/merge' import zipObject from 'lodash/zipObject' import set from 'lodash/set' import {ITEM_CREATE} from './../../quiz/editor/actions' import {SCORE_FIXED} from './../../quiz/enums' import {makeActionCreator, makeId} from './../../utils/utils' import {tex...
feedback: '', score: 0 }) const deletable = newItem.choices.length > 2 newItem.choices.forEach(choice => choice._deletable = deletable) return newItem } case REMOVE_CHOICE: { const newItem = cloneDeep(item) const choiceIndex = newItem.choices.findIndex(choice ...
random_line_split
editor.js
import cloneDeep from 'lodash/cloneDeep' import merge from 'lodash/merge' import zipObject from 'lodash/zipObject' import set from 'lodash/set' import {ITEM_CREATE} from './../../quiz/editor/actions' import {SCORE_FIXED} from './../../quiz/enums' import {makeActionCreator, makeId} from './../../utils/utils' import {tex...
function validate(item) { const errors = {} if (item.choices.find(choice => notBlank(choice.data, true))) { errors.choices = tex('choice_empty_data_error') } if (item.score.type === SCORE_FIXED) { if (item.score.failure >= item.score.success) { set(errors, 'score.failure', tex('fixed_failure_a...
{ switch (action.type) { case ITEM_CREATE: { const firstChoiceId = makeId() const secondChoiceId = makeId() return decorate(Object.assign({}, item, { multiple: false, random: false, choices: [ { id: firstChoiceId, type: 'text/html', ...
identifier_body
editor.js
import cloneDeep from 'lodash/cloneDeep' import merge from 'lodash/merge' import zipObject from 'lodash/zipObject' import set from 'lodash/set' import {ITEM_CREATE} from './../../quiz/editor/actions' import {SCORE_FIXED} from './../../quiz/enums' import {makeActionCreator, makeId} from './../../utils/utils' import {tex...
else { if (!item.choices.find(choice => choice._score > 0)) { errors.choices = tex( item.multiple ? 'sum_score_choice_at_least_one_correct_answer_error' : 'sum_score_choice_no_correct_answer_error' ) } } return errors } function setScores(item, setter) { const sc...
{ if (item.score.failure >= item.score.success) { set(errors, 'score.failure', tex('fixed_failure_above_success_error')) set(errors, 'score.success', tex('fixed_success_under_failure_error')) } if (!item.choices.find(choice => choice._score > 0)) { errors.choices = tex( item.multi...
conditional_block
editor.js
import cloneDeep from 'lodash/cloneDeep' import merge from 'lodash/merge' import zipObject from 'lodash/zipObject' import set from 'lodash/set' import {ITEM_CREATE} from './../../quiz/editor/actions' import {SCORE_FIXED} from './../../quiz/enums' import {makeActionCreator, makeId} from './../../utils/utils' import {tex...
(item) { const errors = {} if (item.choices.find(choice => notBlank(choice.data, true))) { errors.choices = tex('choice_empty_data_error') } if (item.score.type === SCORE_FIXED) { if (item.score.failure >= item.score.success) { set(errors, 'score.failure', tex('fixed_failure_above_success_error'...
validate
identifier_name
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser');
var routes = require('./routes/index'); var admin = require('./routes/admin'); var public = require('./routes/public'); var login = require('./routes/login'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your fav...
random_line_split
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var admin = require('./routes/admin'); var public = require...
// production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); var mongoose = require("mongoose"); if(app.get('env') === 'development') { mongoose.set('debug', true); } ...
{ app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); }
conditional_block
index.js
import browserColor from 'tap-browser-color'; browserColor(); import test from 'tape'; import React from 'react'; import universal from '../../client'; import routes from '../fixtures/routes'; import reducers from '../fixtures/reducers'; const app = universal({ React, routes, reducers }); const store = app();
const msg = 'should not return an Express instance'; const actual = typeof app.use; const expected = 'undefined'; assert.equal(actual, expected, msg); assert.end(); }); nest.test('...initalState', assert => { const msg = 'should render initialState'; const text = 'Untitled'; cons...
test('Client app', nest => { nest.test('...without Express instance', assert => {
random_line_split
packetParser.py
#!/usr/bin/env python # Welcome to Gobbler, the Scapy pcap parser and dump scripts # Part of the sniffMyPackets suite http://www.sniffmypackets.net # Written by @catalyst256 / catalyst256@gmail.com import datetime from layers.http import * from layers.BadLayers import * from auxtools import error_logging import loggi...
def find_layers(pkts, pcap, pcap_id, streamid): packet = OrderedDict() count = 1 pcap_id = pcap_id.encode('utf-8') streamid = streamid.encode('utf-8') try: for p in pkts: header = {"Buffer": {"timestamp": datetime.datetime.fromtimestamp(p.time).strftime('%Y-%m-%d %H:%M:%S.%f')...
n = n.lower().replace(' ', '_').replace('-', '_').replace('.', '_') + '_' return dict((n+k.lower(), f(v) if hasattr(v, 'keys') else v) for k, v in x.items())
identifier_body
packetParser.py
#!/usr/bin/env python # Welcome to Gobbler, the Scapy pcap parser and dump scripts # Part of the sniffMyPackets suite http://www.sniffmypackets.net # Written by @catalyst256 / catalyst256@gmail.com
from layers.BadLayers import * from auxtools import error_logging import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import * from collections import OrderedDict bind_layers(TCP, HTTP) def rename_layer(x, n): n = n.lower().replace(' ', '_').replace('-', '_').replace('.', '_'...
import datetime from layers.http import *
random_line_split
packetParser.py
#!/usr/bin/env python # Welcome to Gobbler, the Scapy pcap parser and dump scripts # Part of the sniffMyPackets suite http://www.sniffmypackets.net # Written by @catalyst256 / catalyst256@gmail.com import datetime from layers.http import * from layers.BadLayers import * from auxtools import error_logging import loggi...
(pkts, pcap, pcap_id, streamid): packet = OrderedDict() count = 1 pcap_id = pcap_id.encode('utf-8') streamid = streamid.encode('utf-8') try: for p in pkts: header = {"Buffer": {"timestamp": datetime.datetime.fromtimestamp(p.time).strftime('%Y-%m-%d %H:%M:%S.%f'), ...
find_layers
identifier_name
packetParser.py
#!/usr/bin/env python # Welcome to Gobbler, the Scapy pcap parser and dump scripts # Part of the sniffMyPackets suite http://www.sniffmypackets.net # Written by @catalyst256 / catalyst256@gmail.com import datetime from layers.http import * from layers.BadLayers import * from auxtools import error_logging import loggi...
counter += 1 count += 1 yield packet packet.clear() except Exception as e: error_logging(str(e), 'PacketParser') pass
break
conditional_block
virtualdisk.py
# # Copyright (c) 2007, 2008 Agostino Russo # Python port of wubi/disckimage/main.c by Hampus Wessman # # Written by Agostino Russo <agostino.russo@gmail.com> # # win32.ui 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 So...
def call_SetFileValidData(file_handle, size_bytes): # No need, Windows 95/98/ME do this automatically anyway. full_version = sys.getwindowsversion() major, minor, build, platform, txt = full_version if platform < 2: log.debug("Skipping SetFileValidData, because Windows 95/98/ME was dete...
log.debug("grant_privileges: OpenProcessToken() failed.")
conditional_block
virtualdisk.py
# # Copyright (c) 2007, 2008 Agostino Russo # Python port of wubi/disckimage/main.c by Hampus Wessman # # Written by Agostino Russo <agostino.russo@gmail.com> # # win32.ui 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 So...
(file_handle, size_bytes): # No need, Windows 95/98/ME do this automatically anyway. full_version = sys.getwindowsversion() major, minor, build, platform, txt = full_version if platform < 2: log.debug("Skipping SetFileValidData, because Windows 95/98/ME was detected") return t...
call_SetFileValidData
identifier_name
virtualdisk.py
# # Copyright (c) 2007, 2008 Agostino Russo # Python port of wubi/disckimage/main.c by Hampus Wessman # # Written by Agostino Russo <agostino.russo@gmail.com> # # win32.ui 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 So...
def zero_file(file_handle, clear_bytes): bytes_cleared = 0 buf_size = 1000 n_bytes_written = c_long(0) write_buf = "0"*buf_size while bytes_cleared < clear_bytes: bytes_to_write = buf_size if (bytes_to_write > clear_bytes - bytes_cleared): bytes_to_write = clear_byt...
full_version = sys.getwindowsversion() major, minor, build, platform, txt = full_version if platform < 2: log.debug("Skipping SetFileValidData, because Windows 95/98/ME was detected") return try: SetFileValidData = ctypes.windll.kernel32.SetFileValidData except: l...
identifier_body
virtualdisk.py
# # Copyright (c) 2007, 2008 Agostino Russo # Python port of wubi/disckimage/main.c by Hampus Wessman # # Written by Agostino Russo <agostino.russo@gmail.com> # # win32.ui 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 So...
log.exception("WriteFile() failed!") bytes_cleared += n_bytes_written.value
defs.NULL) if not result or not n_bytes_written.value:
random_line_split
cmsis_pack.py
# pyOCD debugger # Copyright (c) 2019 Arm Limited # Copyright (c) 2020 Men Shiyun # SPDX-License-Identifier: Apache-2.0 # # 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.apac...
the PDSC. """ def __init__(self, pack, device_info): """! @brief Constructor. @param self @param pack The CmsisPack object that contains this device. @param device_info A _DeviceInfo object with the XML elements that describe this device. """ self._pack = pac...
Responsible for converting the XML elements that describe the device into objects usable by pyOCD. This includes the memory map and flash algorithms. An instance of this class can represent either a `<device>` or `<variant>` XML element from
random_line_split
cmsis_pack.py
# pyOCD debugger # Copyright (c) 2019 Arm Limited # Copyright (c) 2020 Men Shiyun # SPDX-License-Identifier: Apache-2.0 # # 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.apac...
def _extract_debugs(self): def filter(map, elem): if 'Pname' in elem.attrib: name = elem.attrib['Pname'] unit = elem.attrib.get('Punit', 0) name += str(unit) if '*' in map: map.clear() ...
def filter(map, elem): # We only support Keil FLM style flash algorithms (for now). if ('style' in elem.attrib) and (elem.attrib['style'] != 'Keil'): LOG.debug("skipping non-Keil flash algorithm") return None, None # Both start and size are requir...
identifier_body
cmsis_pack.py
# pyOCD debugger # Copyright (c) 2019 Arm Limited # Copyright (c) 2020 Men Shiyun # SPDX-License-Identifier: Apache-2.0 # # 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.apac...
# Both start and size are required attributes. start = int(elem.attrib['start'], base=0) size = int(elem.attrib['size'], base=0) isDefault = _get_bool_attribute(elem, 'default') isStartup = _get_bool_attri...
continue
conditional_block
cmsis_pack.py
# pyOCD debugger # Copyright (c) 2019 Arm Limited # Copyright (c) 2020 Men Shiyun # SPDX-License-Identifier: Apache-2.0 # # 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.apac...
(map, elem): if 'Pname' in elem.attrib: name = elem.attrib['Pname'] unit = elem.attrib.get('Punit', 0) name += str(unit) if '*' in map: map.clear() map[name] = elem else: ...
filter
identifier_name
query.py
import itertools from django.conf import settings from django.db import models from django.utils import translation as translation_utils from olympia.addons.query import IndexCompiler, IndexQuery def order_by_translation(qs, fieldname): """ Order the QuerySet by the translated field, honoring the current a...
class SQLCompiler(IndexCompiler): """Overrides get_from_clause to LEFT JOIN translations with a locale.""" def get_from_clause(self): # Temporarily remove translation tables from query.tables so Django # doesn't create joins against them. old_tables = list(self.query.tables) ...
""" Overrides sql.Query to hit our special compiler that knows how to JOIN translations. """ def clone(self, klass=None, **kwargs): # Maintain translation_aliases across clones. c = super(TranslationQuery, self).clone(klass, **kwargs) c.translation_aliases = self.translation_ali...
identifier_body
query.py
import itertools from django.conf import settings from django.db import models from django.utils import translation as translation_utils from olympia.addons.query import IndexCompiler, IndexQuery def order_by_translation(qs, fieldname): """ Order the QuerySet by the translated field, honoring the current a...
qs = qs.all() model = qs.model field = model._meta.get_field(fieldname) # connection is a tuple (lhs, table, join_cols) connection = (model._meta.db_table, field.rel.to._meta.db_table, field.rel.field_name) # Doing the manual joins is flying under Django's radar, so we need...
desc = False
conditional_block
query.py
import itertools from django.conf import settings from django.db import models from django.utils import translation as translation_utils from olympia.addons.query import IndexCompiler, IndexQuery def order_by_translation(qs, fieldname): """ Order the QuerySet by the translated field, honoring the current a...
(IndexQuery): """ Overrides sql.Query to hit our special compiler that knows how to JOIN translations. """ def clone(self, klass=None, **kwargs): # Maintain translation_aliases across clones. c = super(TranslationQuery, self).clone(klass, **kwargs) c.translation_aliases = se...
TranslationQuery
identifier_name
query.py
import itertools from django.conf import settings from django.db import models from django.utils import translation as translation_utils from olympia.addons.query import IndexCompiler, IndexQuery def order_by_translation(qs, fieldname): """ Order the QuerySet by the translated field, honoring the current a...
translations. """ def clone(self, klass=None, **kwargs): # Maintain translation_aliases across clones. c = super(TranslationQuery, self).clone(klass, **kwargs) c.translation_aliases = self.translation_aliases return c def get_compiler(self, using=None, connection=None):...
random_line_split
parse_spec.py
#!/usr/bin/env python # Copyright (c) 2015 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Parse specification extracted from NEXRAD ICD PDFs and generate Python code.""" from __future__ import print_function import warnings def register_proces...
(fname): """Handle information for message type 18.""" with open(fname, 'r') as infile: info = [] for lineno, line in enumerate(infile): parts = line.split(' ') try: if len(parts) == 8: parts = parts[:6] + [parts[6] + parts[7]] ...
process_msg18
identifier_name
parse_spec.py
#!/usr/bin/env python # Copyright (c) 2015 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Parse specification extracted from NEXRAD ICD PDFs and generate Python code.""" from __future__ import print_function import warnings def register_proces...
types = [('Real*4', ('f', 4)), ('Integer*4', ('L', 4)), ('SInteger*4', ('l', 4)), ('Integer*2', ('H', 2)), ('', lambda s: ('{size}x', s)), ('N/A', lambda s: ('{size}x', s)), (lambda t: t.startswith('String'), lambda s: ('{size}s', s))] def fix_type(typ, size, additional=None): """Fix...
"""Handle information for message type 18.""" with open(fname, 'r') as infile: info = [] for lineno, line in enumerate(infile): parts = line.split(' ') try: if len(parts) == 8: parts = parts[:6] + [parts[6] + parts[7]] var...
identifier_body
parse_spec.py
#!/usr/bin/env python # Copyright (c) 2015 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Parse specification extracted from NEXRAD ICD PDFs and generate Python code.""" from __future__ import print_function import warnings
def register_processor(num): """Register functions to handle particular message numbers.""" def inner(func): """Perform actual function registration.""" processors[num] = func return func return inner processors = {} @register_processor(3) def process_msg3(fname): """Handle ...
random_line_split
parse_spec.py
#!/usr/bin/env python # Copyright (c) 2015 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Parse specification extracted from NEXRAD ICD PDFs and generate Python code.""" from __future__ import print_function import warnings def register_proces...
raise ValueError('No type match! ({})'.format(typ)) def fix_var_name(var_name): """Clean up and apply standard formatting to variable names.""" name = var_name.strip() for char in '(). /#,': name = name.replace(char, '_') name = name.replace('+', 'pos_') name = name.replace('-', 'neg...
if callable(info): fmt_str, true_size = info(size) else: fmt_str, true_size = info assert size == true_size, ('{}: Got size {} instead of {}'.format(typ, size, true_size)) re...
conditional_block
holiday.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { IconModule } from './../shared/icon/icon.module'; import { ListModule } from './../shared/list/list.module'; import { FormdefModule, FormdefRegistry } from './../sh...
( private _slotRegistry: FormdefRegistry ) { this._slotRegistry.register(new ApplyHolidayDetailSlot()); this._slotRegistry.register(new ApproveHolidayDetailSlot()); } }
constructor
identifier_name
holiday.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { IconModule } from './../shared/icon/icon.module'; import { ListModule } from './../shared/list/list.module'; import { FormdefModule, FormdefRegistry } from './../sh...
{ path: '', component: HolidayDashboardComponent, children: [ { path: 'detail/:id', component: HolidayComponent }, { path: 'detail/new', component: HolidayComponent } ] } ]; @NgModule({ imports: [ CommonModule, RouterModule.forChild(ROUTES), FormdefModule, WorkflowModule, ...
random_line_split
site.py
# -*- coding: utf-8 -*- # This file is part of Dyko # Copyright © 2008-2010 Kozea # # This library 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 lat...
if select_range is not None: if hasattr(select_range, "__iter__"): select_range = slice(*select_range) else: select_range = slice(select_range) chain.append(QueryRange(select_range)) query = QueryChain(chain)...
hain.append(QueryAggregate(aggregate))
conditional_block
site.py
# -*- coding: utf-8 -*- # This file is part of Dyko # Copyright © 2008-2010 Kozea # # This library 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 lat...
QueryDistinct, QueryAggregate from .access_point import DEFAULT_PARAMETER def _translate_request(request, aliases): """Translate high-level ``request`` to low-level using ``aliases``.""" if isinstance(request, And): return And(*(_translate_request(req, aliases) for req in requ...
from .query import QueryFilter, QuerySelect, QueryChain, QueryOrder, QueryRange,\
random_line_split
site.py
# -*- coding: utf-8 -*- # This file is part of Dyko # Copyright © 2008-2010 Kozea # # This library 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 lat...
def from_repr(self, access_point_name, repr, default=DEFAULT_PARAMETER): """ Return an item of ``access_point_name`` from the ``repr`` string. ``repr`` should have been generated with item.__repr__() """ access_point = self.access_points[access_point_name] return acc...
""Call :meth:`kalamar.access_point.AccessPoint.view`. If ``alias`` and ``request`` are given, a query is created from them. The query is then validated and then passed to the ``view`` method of the acess point called ``access_point_name``. """ access_point = self.access_points...
identifier_body
site.py
# -*- coding: utf-8 -*- # This file is part of Dyko # Copyright © 2008-2010 Kozea # # This library 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 lat...
self, access_point_name, request=None, *args, **kwargs): """Call ``access_point.method_name(request, *args, **kwargs)``.""" access_point = self.access_points[access_point_name] request = normalize(access_point.properties, request) return getattr(access_point, method_name)...
rapper(
identifier_name
enum.rs
// Copyright 2015, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. extern crate winreg; use std::io; use winreg::enums::*; use winreg::RegKey; fn main() -> io::Result<()> { ...
Ok(()) }
println!("{} = {:?}", name, value); }
random_line_split
enum.rs
// Copyright 2015, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. extern crate winreg; use std::io; use winreg::enums::*; use winreg::RegKey; fn main() -> io::Result<()>
{ println!("File extensions, registered in system:"); for i in RegKey::predef(HKEY_CLASSES_ROOT) .enum_keys() .map(|x| x.unwrap()) .filter(|x| x.starts_with('.')) { println!("{}", i); } let system = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey("HARDWARE\\DESCRIPTIO...
identifier_body
enum.rs
// Copyright 2015, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. extern crate winreg; use std::io; use winreg::enums::*; use winreg::RegKey; fn
() -> io::Result<()> { println!("File extensions, registered in system:"); for i in RegKey::predef(HKEY_CLASSES_ROOT) .enum_keys() .map(|x| x.unwrap()) .filter(|x| x.starts_with('.')) { println!("{}", i); } let system = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(...
main
identifier_name
article.rs
use chrono::naive::NaiveDateTime; use serde::{Deserialize, Serialize}; use validator::Validate; use crate::schema::articles; #[derive(Debug, Clone, Queryable, Insertable, Serialize, Deserialize)] pub struct Article { pub id: i32, pub author_id: i32, pub in_reply_to: Option<String>,
pub article_format: String, pub excerpt: Option<String>, pub body: String, pub published: bool, pub inserted_at: NaiveDateTime, pub updated_at: NaiveDateTime, pub posse: bool, pub lang: String, } #[derive(Deserialize, Serialize, Debug, Insertable, Clone, Validate, Default)] #[table_...
pub title: String, pub slug: String, pub guid: String,
random_line_split
article.rs
use chrono::naive::NaiveDateTime; use serde::{Deserialize, Serialize}; use validator::Validate; use crate::schema::articles; #[derive(Debug, Clone, Queryable, Insertable, Serialize, Deserialize)] pub struct Article { pub id: i32, pub author_id: i32, pub in_reply_to: Option<String>, pub title: String,...
{ pub author_id: Option<i32>, pub in_reply_to: Option<String>, #[validate(length(min = 3, max = 255))] pub title: String, #[validate(length(min = 3, max = 255))] pub slug: String, pub guid: Option<String>, pub article_format: Option<String>, pub excerpt: Option<String>, #[val...
NewArticle
identifier_name
jinja_helper.py
# Copyright (c) 2016 Dustin Doloff # Licensed under Apache License v2.0 import jinja2 import os MESSAGE_FILL = '`' AUTO_GEN_MESSAGE = """ `````````````````````````````````````````````````````` `````````````````````````````````````````````````````` ````````______________________________________ `````` ```````/ ...
def generate(template, config, out_file, pretty=False): path, ext = os.path.splitext(out_file.name) ext = ext[1:] if pretty: if ext == 'py': out_file.write(auto_gen_message('#', '#', '')) elif ext == 'html': out_file.write(auto_gen_message('<!--', '-', '-->')) ...
""" Produces the auto-generated warning header with language-spcific syntax open - str - The language-specific opening of the comment fill - str - The values to fill the background with close - str - The language-specific closing of the comment """ assert open or fill or close ...
identifier_body
jinja_helper.py
# Copyright (c) 2016 Dustin Doloff # Licensed under Apache License v2.0 import jinja2 import os MESSAGE_FILL = '`' AUTO_GEN_MESSAGE = """ `````````````````````````````````````````````````````` `````````````````````````````````````````````````````` ````````______________________________________ `````` ```````/ ...
(template, config, out_file, pretty=False): path, ext = os.path.splitext(out_file.name) ext = ext[1:] if pretty: if ext == 'py': out_file.write(auto_gen_message('#', '#', '')) elif ext == 'html': out_file.write(auto_gen_message('<!--', '-', '-->')) template_path...
generate
identifier_name
jinja_helper.py
# Copyright (c) 2016 Dustin Doloff # Licensed under Apache License v2.0 import jinja2 import os MESSAGE_FILL = '`'
`````````````````````````````````````````````````````` `````````````````````````````````````````````````````` ````````______________________________________ `````` ```````/ /\ ````` ``````/ /..\ ```` `````/ AUTO-GENERATED FILE. DO NOT EDIT /....
AUTO_GEN_MESSAGE = """
random_line_split
jinja_helper.py
# Copyright (c) 2016 Dustin Doloff # Licensed under Apache License v2.0 import jinja2 import os MESSAGE_FILL = '`' AUTO_GEN_MESSAGE = """ `````````````````````````````````````````````````````` `````````````````````````````````````````````````````` ````````______________________________________ `````` ```````/ ...
return message def generate(template, config, out_file, pretty=False): path, ext = os.path.splitext(out_file.name) ext = ext[1:] if pretty: if ext == 'py': out_file.write(auto_gen_message('#', '#', '')) elif ext == 'html': out_file.write(auto_gen_message('<!--'...
message = message.replace(MESSAGE_FILL * len(fill), fill)
conditional_block
chrono.rs
//! This module makes it possible to map `chrono::DateTime` values to postgres `Date` //! and `Timestamp` fields. It is enabled with the `chrono` feature. extern crate chrono; use std::error::Error; use std::io::Write; use self::chrono::{Duration, NaiveDateTime, NaiveDate, NaiveTime}; use expression::AsExpression; us...
}
{ let connection = connection(); let midnight = NaiveTime::from_hms(0, 0, 0); let query = select(sql::<Time>("'00:00:00'::time")); assert_eq!(Ok(midnight), query.get_result::<NaiveTime>(&connection)); let noon = NaiveTime::from_hms(12, 0, 0); let query = select(sql::<Tim...
identifier_body
chrono.rs
//! This module makes it possible to map `chrono::DateTime` values to postgres `Date` //! and `Timestamp` fields. It is enabled with the `chrono` feature. extern crate chrono; use std::error::Error;
use query_source::Queryable; use super::{PgTime, PgTimestamp}; use types::{self, FromSql, IsNull, Time, Timestamp, ToSql}; expression_impls! { Time -> NaiveTime, Timestamp -> NaiveDateTime, } queryable_impls! { Time -> NaiveTime, Timestamp -> NaiveDateTime, } // Postgres timestamps start from January...
use std::io::Write; use self::chrono::{Duration, NaiveDateTime, NaiveDate, NaiveTime}; use expression::AsExpression; use expression::bound::Bound;
random_line_split
chrono.rs
//! This module makes it possible to map `chrono::DateTime` values to postgres `Date` //! and `Timestamp` fields. It is enabled with the `chrono` feature. extern crate chrono; use std::error::Error; use std::io::Write; use self::chrono::{Duration, NaiveDateTime, NaiveDate, NaiveTime}; use expression::AsExpression; us...
() -> Connection { dotenv().ok(); let connection_url = ::std::env::var("DATABASE_URL").ok() .expect("DATABASE_URL must be set in order to run tests"); Connection::establish(&connection_url).unwrap() } #[test] fn unix_epoch_encodes_correctly() { let connection = ...
connection
identifier_name
AbstractNode.ts
import { Maybe } from '../../maybe'; import InternalNode from './InternalNode'; import { IIdentifiableObject } from './types'; // An AbstractNode has a required id and optional additional props abstract class AbstractNode { protected words: string[] = []; protected letter: Maybe<string>; private id: string; pr...
(level: number = Infinity): IIdentifiableObject { return this.getStructure(); } public findEntity(id: string): Maybe<AbstractNode> { if (id === this.getId()) { return this; } return undefined; } } export default AbstractNode;
getTree
identifier_name
AbstractNode.ts
import { Maybe } from '../../maybe'; import InternalNode from './InternalNode'; import { IIdentifiableObject } from './types'; // An AbstractNode has a required id and optional additional props abstract class AbstractNode { protected words: string[] = []; protected letter: Maybe<string>; private id: string; pr...
}; } public getTree(level: number = Infinity): IIdentifiableObject { return this.getStructure(); } public findEntity(id: string): Maybe<AbstractNode> { if (id === this.getId()) { return this; } return undefined; } } export default AbstractNode;
props: this.props
random_line_split
AbstractNode.ts
import { Maybe } from '../../maybe'; import InternalNode from './InternalNode'; import { IIdentifiableObject } from './types'; // An AbstractNode has a required id and optional additional props abstract class AbstractNode { protected words: string[] = []; protected letter: Maybe<string>; private id: string; pr...
return undefined; } } export default AbstractNode;
{ return this; }
conditional_block
AbstractNode.ts
import { Maybe } from '../../maybe'; import InternalNode from './InternalNode'; import { IIdentifiableObject } from './types'; // An AbstractNode has a required id and optional additional props abstract class AbstractNode { protected words: string[] = []; protected letter: Maybe<string>; private id: string; pr...
public setParent(parent: InternalNode) { this.parent = parent; } public getId() { return this.id; } public getProps() { return this.props; } public getParent() { return this.parent; } /** * @returns New vocabulary */ public abstract getNewVocabulary(): string[]; /** ...
{ this.id = id; this.words = words || []; this.letter = letter; this.props = props; }
identifier_body
main.rs
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_xml_rs; extern crate quick_xml; //extern crate serde_derive; use std::env; use std::fs::File; use std::io::prelude::*; use std::str; use serde_xml_rs::deserialize; mod server; mod iso8583_parser; struct Configuration { address: String...
{ let config :Configuration; config = read_configuration(); let listening_address = format!("{}:{}", config.address, config.port); server::start_listening(listening_address); }
identifier_body
main.rs
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_xml_rs; extern crate quick_xml; //extern crate serde_derive; use std::env; use std::fs::File; use std::io::prelude::*; use std::str; use serde_xml_rs::deserialize; mod server; mod iso8583_parser; struct Configuration { address: String...
() { let config :Configuration; config = read_configuration(); let listening_address = format!("{}:{}", config.address, config.port); server::start_listening(listening_address); }
main
identifier_name
main.rs
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_xml_rs; extern crate quick_xml; //extern crate serde_derive; use std::env; use std::fs::File; use std::io::prelude::*;
mod server; mod iso8583_parser; struct Configuration { address: String, port: String, } //read connection configuration from config.xml and set it in 'Configuration' struct fn read_configuration() -> Configuration { use quick_xml::reader::Reader; use quick_xml::events::Event; let mut cfg: Config...
use std::str; use serde_xml_rs::deserialize;
random_line_split
deserialize.ts
/* Copyright 2019 New Vector Ltd Copyright 2019, 2020 The Matrix.org Foundation C.I.C. 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 require...
(event: MatrixEvent, pc: PartCreator, { isQuotedMessage = false } = {}) { const content = event.getContent(); let parts: Part[]; const isEmote = content.msgtype === "m.emote"; let isRainbow = false; if (content.format === "org.matrix.custom.html") { parts = parseHtmlMessage(content.formatte...
parseEvent
identifier_name
deserialize.ts
/* Copyright 2019 New Vector Ltd Copyright 2019, 2020 The Matrix.org Foundation C.I.C. 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 require...
else { return [pc.plain("["), ...parseChildren(n, pc), pc.plain(`](${href})`)]; } } function parseImage(n: Node, pc: PartCreator): Part[] { const { alt, src } = n as HTMLImageElement; return pc.plainWithEmoji(`![${escape(alt)}](${src})`); } function parseCodeBlock(n: Node, pc: PartCreator): Part[...
{ return parseAtRoomMentions(n.textContent, pc); }
conditional_block
deserialize.ts
/* Copyright 2019 New Vector Ltd Copyright 2019, 2020 The Matrix.org Foundation C.I.C. 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 require...
export function parsePlainTextMessage(body: string, pc: PartCreator, isQuotedMessage?: boolean): Part[] { const lines = body.split(/\r\n|\r|\n/g); // split on any new-line combination not just \n, collapses \r\n return lines.reduce((parts, line, i) => { if (isQuotedMessage) { parts.push(pc....
prefixLines(parts, "> ", pc); } return parts; }
random_line_split
deserialize.ts
/* Copyright 2019 New Vector Ltd Copyright 2019, 2020 The Matrix.org Foundation C.I.C. 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 require...
// Finds the length of the longest backtick sequence in the given text, used for // escaping backticks in code blocks function longestBacktickSequence(text: string): number { let length = 0; let currentLength = 0; for (const c of text) { if (c === "`") { currentLength++; } els...
{ return text.replace(/[\\*_[\]`<]|^>/g, match => `\\${match}`); }
identifier_body
issue-13560.rs
// Copyright 2014 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 ...
fn main() {}
random_line_split
issue-13560.rs
// Copyright 2014 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 ...
() {}
main
identifier_name
issue-13560.rs
// Copyright 2014 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 ...
{}
identifier_body
list_container.js
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert, assertInstanceof, assertNotReached} from 'chrome://resources/js/assert.m.js'; import {dispatchSimpleEvent} from 'chrome://resources/js/cr....
* @type {ListThumbnailLoader} */ this.listThumbnailLoader = null; /** * @type {ListSelectionModel|ListSingleSelectionModel} */ this.selectionModel = null; /** * Data model which is used as a placefolder in inactive file list. * @type {FileListModel} */ this.empty...
/**
random_line_split
list_container.js
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert, assertInstanceof, assertNotReached} from 'chrome://resources/js/assert.m.js'; import {dispatchSimpleEvent} from 'chrome://resources/js/cr....
/** * Focuses the active file list in the list container. */ focus() { switch (this.currentListType) { case ListContainer.ListType.DETAIL: this.table.list.focus(); break; case ListContainer.ListType.THUMBNAIL: this.grid.focus(); break; default: a...
{ const item = this.currentList.getListItemAncestor(node); // TODO(serya): list should check that. return item && this.currentList.isItem(item) ? assertInstanceof(item, ListItem) : null; }
identifier_body
list_container.js
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert, assertInstanceof, assertNotReached} from 'chrome://resources/js/assert.m.js'; import {dispatchSimpleEvent} from 'chrome://resources/js/cr....
(event) { // The user grabbed the mouse, restore the hover highlighting. this.element.classList.remove('nohover'); } } /** * @enum {string} * @const */ ListContainer.EventType = { TEXT_SEARCH: 'textsearch' }; /** * @enum {string} * @const */ ListContainer.ListType = { UNINITIALIZED: 'uninitialized...
onMouseMove_
identifier_name
list_container.js
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert, assertInstanceof, assertNotReached} from 'chrome://resources/js/assert.m.js'; import {dispatchSimpleEvent} from 'chrome://resources/js/cr....
}.bind(this)); this.element.addEventListener('contextmenu', function(e) { // Block context menu triggered by touch event unless it is right after // multi-touch, or we are currently selecting a file. if (this.currentList.selectedItem && !this.allowContextMenuByTouch_ && e.sourceCapa...
{ // contextmenu event will be sent right after touchend. setTimeout(function() { this.allowContextMenuByTouch_ = false; }.bind(this)); }
conditional_block
keyboardjs.d.ts
// Type definitions for KeyboardJS v2.2.0 // Project: https://github.com/RobertWHurst/KeyboardJS // Definitions by: Vincent Bortone <https://github.com/vbortone/>, // David Asmuth <https://github.com/piranha771> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // KeyboardJS is a libra...
/** * Triggers a key press. Stays in pressed state until released. * @param keyCombo String of keys to be pressed to execute 'pressed' callbacks. */ export function pressKey(keyCombo: string): void /** * Triggers a key release. * @param keyCombo String of keys to be released to exec...
*/ export function reset(): void; // ---------- Virtual Key Press ---------- //
random_line_split