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
borrowck-borrowed-uniq-rvalue-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
unsafe { error!("%?", self.x); } } } fn defer<'r>(x: &'r [&'r str]) -> defer<'r> { defer { x: x } } fn main() { let x = defer(~["Goodbye", "world!"]); //~ ERROR borrowed value does not live long enough x.x[0]; }
#[unsafe_destructor] impl<'self> Drop for defer<'self> { fn drop(&self) {
random_line_split
borrowck-borrowed-uniq-rvalue-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'r>(x: &'r [&'r str]) -> defer<'r> { defer { x: x } } fn main() { let x = defer(~["Goodbye", "world!"]); //~ ERROR borrowed value does not live long enough x.x[0]; }
defer
identifier_name
borrowck-borrowed-uniq-rvalue-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn defer<'r>(x: &'r [&'r str]) -> defer<'r> { defer { x: x } } fn main() { let x = defer(~["Goodbye", "world!"]); //~ ERROR borrowed value does not live long enough x.x[0]; }
{ unsafe { error!("%?", self.x); } }
identifier_body
irc.py
import time from typing import List, Optional from utils import tasks from zirc.event import Event from utils.database import Database
"""Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] def set_mode(irc: connection_wrapper, channel: str, users: List[str], mode: str): for block in chunks(users, 4): modes = "".join(mode[1:]) * len(block) irc.mode(channel, " ".join(block), mo...
from zirc.wrappers import connection_wrapper def chunks(l: List, n: int):
random_line_split
irc.py
import time from typing import List, Optional from utils import tasks from zirc.event import Event from utils.database import Database from zirc.wrappers import connection_wrapper def chunks(l: List, n: int): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n...
def get_users(args: str): if args.find(",") != -1: pos = args.find(",") users_str = args[pos:].strip() if args[pos + 1] != " ": users = users_str[1:].split(",") else: users = users_str[2:].split(", ") args = args[:pos].strip().split(" ") us...
for block in chunks(users, 4): modes = "".join(mode[1:]) * len(block) irc.mode(channel, " ".join(block), mode[0] + modes)
identifier_body
irc.py
import time from typing import List, Optional from utils import tasks from zirc.event import Event from utils.database import Database from zirc.wrappers import connection_wrapper def chunks(l: List, n: int): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n...
for (i, v) in enumerate(users): if not v.find("!") != -1 and userdb is not None: users[i] = get_user_host(userdb, event.target, v) return channel, users, message def unban_after_duration(irc: connection_wrapper, users: List[str], chan: str, duration: int): duration += int(time.time())...
message = f"{event.source.nick}"
conditional_block
irc.py
import time from typing import List, Optional from utils import tasks from zirc.event import Event from utils.database import Database from zirc.wrappers import connection_wrapper def chunks(l: List, n: int): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n...
(irc: connection_wrapper, users: List[str], chan: str, duration: int): duration += int(time.time()) def func(irc: connection_wrapper, users: List[str], chan: str): for i in users: irc.unban(chan, i) tasks.run_at(duration, func, (irc, users, chan)) def strip_colours(s: str): impor...
unban_after_duration
identifier_name
gzip.rs
extern crate extra; extern crate libflate; use extra::option::OptionalExt; use libflate::gzip::Encoder; use std::io::Write; use std::{env, fs, io, process}; fn
() { let mut stderr = io::stderr(); let mut keep = false; let mut files = Vec::new(); for arg in env::args().skip(1) { if arg == "-k" { keep = true; } else { files.push(arg) } } if files.is_empty() { eprintln!("gzip: no files provided"); ...
main
identifier_name
gzip.rs
extern crate extra; extern crate libflate; use extra::option::OptionalExt; use libflate::gzip::Encoder; use std::io::Write; use std::{env, fs, io, process}; fn main() { let mut stderr = io::stderr(); let mut keep = false; let mut files = Vec::new(); for arg in env::args().skip(1) { if arg == ...
} if files.is_empty() { eprintln!("gzip: no files provided"); process::exit(1); } for arg in files { { let output = fs::File::create(&format!("{}.gz", &arg)).try(&mut stderr); let mut encoder = Encoder::new(output).try(&mut stderr); let mut...
{ files.push(arg) }
conditional_block
gzip.rs
extern crate extra;
extern crate libflate; use extra::option::OptionalExt; use libflate::gzip::Encoder; use std::io::Write; use std::{env, fs, io, process}; fn main() { let mut stderr = io::stderr(); let mut keep = false; let mut files = Vec::new(); for arg in env::args().skip(1) { if arg == "-k" { k...
random_line_split
gzip.rs
extern crate extra; extern crate libflate; use extra::option::OptionalExt; use libflate::gzip::Encoder; use std::io::Write; use std::{env, fs, io, process}; fn main()
let output = fs::File::create(&format!("{}.gz", &arg)).try(&mut stderr); let mut encoder = Encoder::new(output).try(&mut stderr); let mut input = fs::File::open(&arg).try(&mut stderr); io::copy(&mut input, &mut encoder).try(&mut stderr); let mut encoded = en...
{ let mut stderr = io::stderr(); let mut keep = false; let mut files = Vec::new(); for arg in env::args().skip(1) { if arg == "-k" { keep = true; } else { files.push(arg) } } if files.is_empty() { eprintln!("gzip: no files provided"); ...
identifier_body
rotationalResistance.py
#!/usr/bin/env python # encoding: utf-8 from yade import utils, plot o = Omega() fr = 0.5;rho=2000 tc = 0.001; en = 0.7; et = 0.7; o.dt = 0.0002*tc r = 0.002 mat1 = O.materials.append(ViscElMat(frictionAngle=fr,mR = 0.05, mRtype = 1, density=rho,tc=tc,en=en,et=et)) mat2 = O.materials.append(ViscElMat(frictionAngle=fr...
plot.plots={'sc':('fc1','fc2')}; plot.plot() from yade import qt qt.View()
1 = [0,0,0] s1 = O.bodies[id1].state.pos[1] s2 = O.bodies[id3].state.pos[1] plot.addData(sc=O.time, fc1=s1, fc2=s2)
identifier_body
rotationalResistance.py
#!/usr/bin/env python
o = Omega() fr = 0.5;rho=2000 tc = 0.001; en = 0.7; et = 0.7; o.dt = 0.0002*tc r = 0.002 mat1 = O.materials.append(ViscElMat(frictionAngle=fr,mR = 0.05, mRtype = 1, density=rho,tc=tc,en=en,et=et)) mat2 = O.materials.append(ViscElMat(frictionAngle=fr,mR = 0.05, mRtype = 2, density=rho,tc=tc,en=en,et=et)) oriBody = Qu...
# encoding: utf-8 from yade import utils, plot
random_line_split
rotationalResistance.py
#!/usr/bin/env python # encoding: utf-8 from yade import utils, plot o = Omega() fr = 0.5;rho=2000 tc = 0.001; en = 0.7; et = 0.7; o.dt = 0.0002*tc r = 0.002 mat1 = O.materials.append(ViscElMat(frictionAngle=fr,mR = 0.05, mRtype = 1, density=rho,tc=tc,en=en,et=et)) mat2 = O.materials.append(ViscElMat(frictionAngle=fr...
): f1 = [0,0,0] s1 = O.bodies[id1].state.pos[1] s2 = O.bodies[id3].state.pos[1] plot.addData(sc=O.time, fc1=s1, fc2=s2) plot.plots={'sc':('fc1','fc2')}; plot.plot() from yade import qt qt.View()
ddPlotData(
identifier_name
meg.rs
PathBuf, Path}; use std::process::Command; use turbo::turbo::{execute_main_without_stdin, handle_error, shell}; use turbo::core::MultiShell; use turbo::util::{CliError, CliResult, Config}; use meg::util::{lev_distance}; use self::term_painter::Color::*; use self::term_painter::ToStyle; #[derive(RustcDecodable)] #[de...
(cmd: &str) -> Option<String> { let cmds = list_commands(); // Only consider candidates with a lev_distance of 3 or less so we don't // suggest out-of-the-blue options. let mut filtered = cmds.iter().map(|c| (lev_distance(&c, cmd), c)) .filter(|&(d, _)| d < 4) ...
find_closest
identifier_name
meg.rs
-h, --help Display this message version Print version info and exit --list List installed commands -v, --verbose Use verbose output meg commands are: ahoy Ping the status of megam. account Create an account with megam. sshkey Create SSHKey with megam. ...
if let Some(val) = env::var_os("PATH") { dirs.extend(env::split_paths(&val)); }
random_line_split
meg.rs
PathBuf, Path}; use std::process::Command; use turbo::turbo::{execute_main_without_stdin, handle_error, shell}; use turbo::core::MultiShell; use turbo::util::{CliError, CliResult, Config}; use meg::util::{lev_distance}; use self::term_painter::Color::*; use self::term_painter::ToStyle; #[derive(RustcDecodable)] #[de...
} } } Err(ref e) if e.kind() == io::ErrorKind::NotFound => { handle_error(CliError::new("No such subcommand", 127), shell) } Err(err) => { let msg = format!("Subcommand failed to run: {}", err); handle_error(CliError::new(&m...
{ let command = match find_command(cmd) { Some(command) => command, None => { let msg = match find_closest(cmd) { Some(closest) => format!("No such subcommand\n\n\t\ Did you mean `{}`?\n", closest), None => "No suc...
identifier_body
spotify-api.service.ts
import * as rp from 'request-promise-native' import { Service } from 'ts-express-decorators' import * as Express from 'express' import * as querystring from 'querystring' import { generateRandomString, getSecret } from '../utils' import { User, IUser } from '../models' import * as spotify from 'models/spotify' export...
export let redirect_uri = process.env.HOST_URL + '/callback' @Service() export class SpotifyApiService { private bearerAuthHeader(currentToken: string) { return { Authorization: `Bearer ${currentToken}` } } public getMe(token: string): Promise<spotify.IUser> { return rp(`${baseApiUrl}/me`, { headers: this....
export let client_id = getSecret('CLIENT_ID') export let client_secret = getSecret('CLIENT_SECRET') export let stateKey = 'spotify_auth_state'
random_line_split
spotify-api.service.ts
import * as rp from 'request-promise-native' import { Service } from 'ts-express-decorators' import * as Express from 'express' import * as querystring from 'querystring' import { generateRandomString, getSecret } from '../utils' import { User, IUser } from '../models' import * as spotify from 'models/spotify' export...
if (offset !== null && offset > 0) { options.qs.offset = offset } return rp(`${baseApiUrl}/users/${userId}/playlists/${playlistId}/tracks`, options).promise() } public postPlaylistTracks(token: string, userId: string, playlistId: string, trackUris: string[], position = 0) { const options = { method: 'P...
{ options.qs.limit = limit }
conditional_block
spotify-api.service.ts
import * as rp from 'request-promise-native' import { Service } from 'ts-express-decorators' import * as Express from 'express' import * as querystring from 'querystring' import { generateRandomString, getSecret } from '../utils' import { User, IUser } from '../models' import * as spotify from 'models/spotify' export...
(currentToken: string) { return { Authorization: `Bearer ${currentToken}` } } public getMe(token: string): Promise<spotify.IUser> { return rp(`${baseApiUrl}/me`, { headers: this.bearerAuthHeader(token), json: true }).promise() } public getPlaylist(token: string, userId: string, playlistId: string) { ...
bearerAuthHeader
identifier_name
cli.py
from .. import __description__ from ..defender import VkRaidDefender, data, update_data #################################################################################################### LOGO = '''\ _ _ _ _ __ _ __ _| | __ _ __ __ _(_) __| | __| | ___ / _| __...
answer == false_answer: return False else: return default def register(): use_webbrowser = ask_yes_or_no('открыть ссылку для авторизации в веб-браузере по умолчанию?') print() oauth_url = 'https://oauth.vk.com/authorize?client_id={}&display=page&redirect_uri=https://oauth.vk.com/blank...
return True elif
conditional_block
cli.py
from .. import __description__ from ..defender import VkRaidDefender, data, update_data #################################################################################################### LOGO = '''\ _ _ _ _ __ _ __ _| | __ _ __ __ _(_) __| | __| | ___ / _| __...
'n', default_answer='', default=True): true_answer = true_answer.lower() false_answer = false_answer.lower() default_answer = default_answer.lower() output = question.strip() + ' (' + (true_answer.upper() + '/' + false_answer if default else true_answer + '/' + f...
GO + '\n\n') def ask_yes_or_no(question, true_answer='y', false_answer=
identifier_body
cli.py
from .. import __description__ from ..defender import VkRaidDefender, data, update_data #################################################################################################### LOGO = '''\ _ _ _ _ __ _ __ _| | __ _ __ __ _(_) __| | __| | ___ / _| __...
if use_socks: proxies = {'http': 'socks5://' + ip, 'https': 'socks5://' + ip} else: proxies = {'http': 'http://' + ip, 'https': 'https://' + ip} if auto_login or ask_yes_or_no('сохранить введённые данные для следующих сессий?'): data['token']...
use_socks = ask_yes_or_no('использовать протокол socks5 вместо http?') if not auto_login else False
random_line_split
cli.py
from .. import __description__ from ..defender import VkRaidDefender, data, update_data #################################################################################################### LOGO = '''\ _ _ _ _ __ _ __ _| | __ _ __ __ _(_) __| | __| | ___ / _| __...
.compile(r'((socks5://)|(?:https?://))?(localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5})') if proxy: match = IP_ADDRESS.match(proxy) if not proxy or (not match and not auto_login): proxy = input('введи адрес прокси-сервера при необходимости его использования: ') ...
re
identifier_name
ml_spam.py
# ------------------- start ML blackbox ---------------------------- # the details here aren't fully important from textblob import TextBlob from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.svm import SVC from sklearn.pipeline import Pipeline from sklearn.grid_search import Gri...
if "fitted CLOB" not in params: error.write("Need a fitted CLOB object in order to perform a prediction.\n") return spam_detector = cPickle.loads(params["fitted CLOB"]) rtn = spam_detector.predict(messages.message) assert len(rtn) == len(messages.message) map(soln...
conditional_block
ml_spam.py
# ------------------- start ML blackbox ---------------------------- # the details here aren't fully important from textblob import TextBlob from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.svm import SVC from sklearn.pipeline import Pipeline from sklearn.grid_search import Gri...
# ------------------- end big ML blackbox ------------------------ from ticdat import TicDatFactory, LogFile import cPickle import time import datetime dataFactory = TicDatFactory(messages = [[],["label", "message"]], parameters = [["key"], ["value"]]) solnFactory = TicDatFactory(pred...
return GridSearchCV( pipeline_svm, # pipeline from above param_grid=param_svm, # parameters to tune via cross validation refit=True, # fit using all data, on the best detected classifier n_jobs=-1, # number of cores to use for parallelization; -1 for "all cores" scoring='accuracy', # what scor...
identifier_body
ml_spam.py
# ------------------- start ML blackbox ---------------------------- # the details here aren't fully important from textblob import TextBlob from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.svm import SVC from sklearn.pipeline import Pipeline from sklearn.grid_search import Gri...
(td, output, error): assert dataFactory.good_tic_dat_object(td) assert isinstance(output, LogFile) and isinstance(error, LogFile) output.write("Output log file for spam \n%s\n\n"%_timeStamp()) error.write("Error log file for spam \n%s\n\n"%_timeStamp()) messages = dataFactory.copy_to_pandas(td).mess...
run
identifier_name
polyfill.ts
interface String { startsWith(str: string): boolean; endsWith(str: string): boolean; compare(target: string, ignoreCase?: boolean): number; contains(str: string, ignoreCase?: boolean): boolean; } interface Array<T> { includes(obj: T): boolean; remove(from: number, to: number): Array<T>; ge...
k++; } return -1; }; if (!Array.prototype.some) { Array.prototype.some = function (fun/*, thisArg*/) { 'use strict'; if (this == null) { throw new TypeError('Array.prototype.some called on null or undefined'); } if (typeof fun !== 'function') { ...
return k; }
conditional_block
polyfill.ts
interface String { startsWith(str: string): boolean; endsWith(str: string): boolean; compare(target: string, ignoreCase?: boolean): number; contains(str: string, ignoreCase?: boolean): boolean; } interface Array<T> { includes(obj: T): boolean; remove(from: number, to: number): Array<T>; ge...
if (!String.prototype.compare) { String.prototype.compare = function (target: string, ignoreCase?: boolean) { var selfValue: string = this; var targetValue: string = target || ""; if (ignoreCase) { selfValue = selfValue.toLowerCase(); targetValue = targetValue.toLow...
random_line_split
text-editor-registry.js
to add functionality to a wider set of text editors than just // those appearing within workspace panes, use `atom.textEditors.observe` to // invoke a callback for all current and future registered text editors. // // If you want packages to be able to add functionality to your non-pane text // editors (such as a sear...
}) } selectGrammarForEditor (editor) { const grammarOverride = this.editorGrammarOverrides[editor.id] if (grammarOverride) { const grammar = this.grammarRegistry.grammarForScopeName(grammarOverride) editor.setGrammar(grammar) return } const {grammar, score} = this.grammarRe...
{ const score = this.grammarRegistry.getGrammarScore( grammar, editor.getPath(), editor.getTextInBufferRange(GRAMMAR_SELECTION_RANGE) ) let currentScore = this.editorGrammarScores.get(editor) if (currentScore == null || score > currentScore) { edi...
conditional_block
text-editor-registry.js
to add functionality to a wider set of text editors than just // those appearing within workspace panes, use `atom.textEditors.observe` to // invoke a callback for all current and future registered text editors. // // If you want packages to be able to add functionality to your non-pane text // editors (such as a sear...
{ constructor ({config, grammarRegistry, assert, packageManager}) { this.assert = assert this.config = config this.grammarRegistry = grammarRegistry this.scopedSettingsDelegate = new ScopedSettingsDelegate(config) this.grammarAddedOrUpdated = this.grammarAddedOrUpdated.bind(this) this.clear()...
TextEditorRegistry
identifier_name
text-editor-registry.js
. add (editor) { this.editors.add(editor) editor.registered = true this.emitter.emit('did-add-editor', editor) return new Disposable(() => this.remove(editor)) } build (params) { params = Object.assign({assert: this.assert}, params) let scope = null if (params.buffer) { const ...
{ return this.config.get('editor.nonWordCharacters', {scope: scope}) }
identifier_body
text-editor-registry.js
want to add functionality to a wider set of text editors than just // those appearing within workspace panes, use `atom.textEditors.observe` to // invoke a callback for all current and future registered text editors. // // If you want packages to be able to add functionality to your non-pane text // editors (such as a...
setGrammarOverride (editor, scopeName) { this.editorGrammarOverrides[editor.id] = scopeName this.editorGrammarScores.delete(editor) editor.setGrammar(this.grammarRegistry.grammarForScopeName(scopeName)) } // Retrieve the grammar scope name that has been set as a grammar override // for the given {T...
// * `editor` The editor whose gramamr will be set. // * `scopeName` The {String} root scope name for the desired {Grammar}.
random_line_split
SearchTextView.js
// -------------------------------------------------------------------------- \\ // File: SearchTextView.js \\ // Module: ControlViews \\ // Requires: TextView.js ...
draw: function (layer, Element, el) { var children = SearchTextView.parent.draw.call(this, layer, Element, el); children.push( el('i.icon.v-icon-search'), new NS.ButtonView({ type: NS.bind(this, 'value', function (val...
method: null,
random_line_split
SearchTextView.js
// -------------------------------------------------------------------------- \\ // File: SearchTextView.js \\ // Module: ControlViews \\ // Requires: TextView.js ...
else if (action = this.get('method')) { target[action](this); } this.fire('search:activate'); } }.observes('value') }); NS.SearchTextView = SearchTextView; }(O) );
target.fire(action, {originView: this}); }
conditional_block
html_builder.py
# -*- coding: utf-8 -*- """ Module for the generation of docx format documents. --- type: python_module validation_level: v00_minimum protection: k00_public copyright: "Copyright 2016 High Integrity Artificial Intelligence Systems" license: "Licensed under the Apache License, Version 2.0 (the L...
# ----------------------------------------------------------------------------- def build(_, section_list, filepath): """ Build and save the specified document. """ environment = jinja2.Environment( loader = jinja2.PackageLoader( ...
random_line_split
html_builder.py
# -*- coding: utf-8 -*- """ Module for the generation of docx format documents. --- type: python_module validation_level: v00_minimum protection: k00_public copyright: "Copyright 2016 High Integrity Artificial Intelligence Systems" license: "Licensed under the Apache License, Version 2.0 (the L...
(_, section_list, filepath): """ Build and save the specified document. """ environment = jinja2.Environment( loader = jinja2.PackageLoader( 'da.report', 'templates'), trim_blocks = True, ...
build
identifier_name
html_builder.py
# -*- coding: utf-8 -*- """ Module for the generation of docx format documents. --- type: python_module validation_level: v00_minimum protection: k00_public copyright: "Copyright 2016 High Integrity Artificial Intelligence Systems" license: "Licensed under the Apache License, Version 2.0 (the L...
section_list = filtered_list) with open(filepath, 'wt') as file: file.write(html) # _add_title_section(document, doc_data['_metadata']) # _add_toc_section(document) # for item in sorted(_generate_content_items(doc_data), # key = _doc_data_sortkey): ...
""" Build and save the specified document. """ environment = jinja2.Environment( loader = jinja2.PackageLoader( 'da.report', 'templates'), trim_blocks = True, lstrip_blocks = True) t...
identifier_body
html_builder.py
# -*- coding: utf-8 -*- """ Module for the generation of docx format documents. --- type: python_module validation_level: v00_minimum protection: k00_public copyright: "Copyright 2016 High Integrity Artificial Intelligence Systems" license: "Licensed under the Apache License, Version 2.0 (the L...
html = template.render( # pylint: disable=E1101 section_list = filtered_list) with open(filepath, 'wt') as file: file.write(html) # _add_title_section(document, doc_data['_metadata']) # _add_toc_section(document) # for item in sorted(_gener...
if section['level'] != 1 and len(section['para']) == 0: continue filtered_list.append(section)
conditional_block
dellAnalyzer.ts
import fs from 'fs'; import cheerio from 'cheerio'; import { Analyzer } from './crowller'; interface Course { title: string; count: number; } interface CourseResult { time: number; data: Course[]; } interface Content { [propName: number]: Course[]; } export default class DellAnalyzer implements Analyzer {...
{ } }
nstructor()
identifier_name
dellAnalyzer.ts
import fs from 'fs'; import cheerio from 'cheerio';
interface Course { title: string; count: number; } interface CourseResult { time: number; data: Course[]; } interface Content { [propName: number]: Course[]; } export default class DellAnalyzer implements Analyzer { private static instance: DellAnalyzer; static getInstance() { if (!DellAnalyzer.in...
import { Analyzer } from './crowller';
random_line_split
dellAnalyzer.ts
import fs from 'fs'; import cheerio from 'cheerio'; import { Analyzer } from './crowller'; interface Course { title: string; count: number; } interface CourseResult { time: number; data: Course[]; } interface Content { [propName: number]: Course[]; } export default class DellAnalyzer implements Analyzer {...
} private generateJsonContent(courseInfo: CourseResult, filePath: string) { let fileContent: Content = {}; if (fs.existsSync(filePath)) { fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8')); } fileContent[courseInfo.time] = courseInfo.data; return fileContent; } public analy...
{ const $ = cheerio.load(html); const courseItems = $('.course-item'); const courseInfos: Course[] = []; courseItems.map((index, element) => { const descs = $(element).find('.course-desc'); const title = descs.eq(0).text(); const count = parseInt( descs .eq(1) ...
identifier_body
dellAnalyzer.ts
import fs from 'fs'; import cheerio from 'cheerio'; import { Analyzer } from './crowller'; interface Course { title: string; count: number; } interface CourseResult { time: number; data: Course[]; } interface Content { [propName: number]: Course[]; } export default class DellAnalyzer implements Analyzer {...
fileContent[courseInfo.time] = courseInfo.data; return fileContent; } public analyze(html: string, filePath: string) { const courseInfo = this.getCourseInfo(html); const fileContent = this.generateJsonContent(courseInfo, filePath); return JSON.stringify(fileContent); } private constructor()...
fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8')); }
conditional_block
labels.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {GithubConfig} from '../../../utils/config'; import {GithubClient} from '../../../utils/git/github'; import {T...
return branches; } }, { pattern: 'target: rc', branches: githubTargetBranch => { // The `target: rc` label cannot be applied if there is no active feature-freeze // or release-candidate release train. if (releaseCandidateBranch === null) { throw new I...
{ branches.push(releaseCandidateBranch); }
conditional_block
labels.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {GithubConfig} from '../../../utils/config'; import {GithubClient} from '../../../utils/git/github'; import {T...
}, { pattern: 'target: minor', // Changes labeled with `target: minor` are merged most commonly into the next branch // (i.e. `master`). In rare cases of an exceptional minor version while being already // on a major release train, this would need to be overridden manually. // TODO...
{ const repo: GithubRepo = {owner: github.owner, repo: github.name, api, npmPackageName}; const nextVersion = await getVersionOfBranch(repo, nextBranchName); const hasNextMajorTrain = nextVersion.minor === 0; const {latestVersionBranch, releaseCandidateBranch} = await fetchActiveReleaseTrainBranches(repo,...
identifier_body
labels.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {GithubConfig} from '../../../utils/config'; import {GithubClient} from '../../../utils/git/github'; import {T...
( api: GithubClient, github: GithubConfig, npmPackageName: string): Promise<TargetLabel[]> { const repo: GithubRepo = {owner: github.owner, repo: github.name, api, npmPackageName}; const nextVersion = await getVersionOfBranch(repo, nextBranchName); const hasNextMajorTrain = nextVersion.minor === 0; const {l...
getDefaultTargetLabelConfiguration
identifier_name
labels.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {GithubConfig} from '../../../utils/config'; import {GithubClient} from '../../../utils/git/github'; import {T...
// Assert that the selected branch is an active LTS branch. await assertActiveLtsBranch(repo, githubTargetBranch); return [githubTargetBranch]; }, }, ]; }
`branch. Consider changing the label to "target: rc" if this is intentional.`); }
random_line_split
logs-spec.js
"use strict"; let logs = require("../logs"); let assert = require("assert"); describe("logs DB collection", function () { let userID = 1; let log = { title: "Food Journal" }; let logID = ""; it("should create a log", function () { return logs.createLog(global.db,userID,log).then(function (savedLog) { asse...
return logs.deleteLog(global.db, userID, logID).then(function () { return logs.readLogList(global.db, userID).then(function (list) { list = list.filter(function (log) { return log._id == logID; }); assert.equal(list.length, 0); }); }); }); it("should delete many logs", function () { retu...
}); it("should delete a log", function () {
random_line_split
zpm.py
('zapp.yaml')) remote_zapp_path = '%s/%s' % (target, os.path.basename(zapp_path)) swift_url = _get_swift_zapp_url(conn.url, remote_zapp_path) job = _prepare_job(tar, zapp_config, swift_url) yield (remote_zapp_path, gzip.open(zapp_path).read(), 'application/x-tar') yield ('%s/%s' % (target, SYSTEM_...
conn = _get_zerocloud_conn(args) resp = dict() if args.container:
random_line_split
zpm.py
7'}, {'name': 'stdout'}], 'name': 'hello'}] the output will look like something like this:: [{'exec': {u'args': 'hello.py', 'path': 'file://python2.7:python'}, 'devices': [ {'name': 'python2.7'}, {'name': 'stdout'}, {'name...
_generate_uploads
identifier_name
zpm.py
if path.startswith('file://'): exec_name = path.split(':')[-1] elif path.startswith('swift://'): # If obj is a pseudo path, like foo/bar/obj, we need to # handle this as well with a careful split. # If the object path is something like `swift://~/containe...
# This is here due to legacy reasons, but it's not clear to me why this is # needed. if swift_path.startswith('/v1/'): swift_path = swift_path[4:] return 'swift://%s/%s' % (swift_path, zapp_path) def _prepare_job(tar, zapp, zapp_swift_url): """ :param tar: The application .zap...
""" :param str swift_service_url: The Swift service URL returned from a Keystone service catalog. Example: http://localhost:8080/v1/AUTH_469a9cd20b5a4fc5be9438f66bb5ee04 :param str zapp_path: <container>/<zapp-file-name>. Example: test_container/myapp.zapp Here's a typ...
identifier_body
zpm.py
a `dict`. :param str zapp_swift_url: Path of the .zapp in Swift, which looks like this:: 'swift://AUTH_abcdef123/test_container/hello.zapp' See :func:`_get_swift_zapp_url`. :returns: Extracted contents of the boot/system.map with the swift path to the .zap...
if not force: raise zpmlib.ZPMException( "Target container ('%s') is not empty.\nDeploying to a " "non-empty container can cause consistency problems with " "overwritten objects.\nSpecify the flag `--force/-f` to " "overwrit...
conditional_block
spinner.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib; use glib::StaticType; use glib::Value; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::s...
fn start(&self) { unsafe { ffi::gtk_spinner_start(self.to_glib_none().0); } } fn stop(&self) { unsafe { ffi::gtk_spinner_stop(self.to_glib_none().0); } } fn get_property_active(&self) -> bool { unsafe { let mut value = Val...
} impl<O: IsA<Spinner> + IsA<glib::object::Object>> SpinnerExt for O {
random_line_split
spinner.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib; use glib::StaticType; use glib::Value; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::s...
(&self) { unsafe { ffi::gtk_spinner_start(self.to_glib_none().0); } } fn stop(&self) { unsafe { ffi::gtk_spinner_stop(self.to_glib_none().0); } } fn get_property_active(&self) -> bool { unsafe { let mut value = Value::from_typ...
start
identifier_name
spinner.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib; use glib::StaticType; use glib::Value; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::s...
} unsafe extern "C" fn notify_active_trampoline<P>(this: *mut ffi::GtkSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Spinner> { let f: &&(Fn(&P) + 'static) = transmute(f); f(&Spinner::from_glib_borrow(this).downcast_unchecked()) }
{ unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::active", transmute(notify_active_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } }
identifier_body
media_rule.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/. */ //! An [`@media`][media] urle. //! //! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media use cs...
( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard ) -> Self { let media_queries = self.media_queries.read_with(guard); let rules = self.rules.read_with(guard); MediaRule { media_queries: Arc::new(lock.wrap(media_queries.clone())), rul...
deep_clone_with_lock
identifier_name
media_rule.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/. */ //! An [`@media`][media] urle. //! //! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media use cs...
MediaRule { media_queries: Arc::new(lock.wrap(media_queries.clone())), rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))), source_location: self.source_location.clone(), } } }
lock: &SharedRwLock, guard: &SharedRwLockReadGuard ) -> Self { let media_queries = self.media_queries.read_with(guard); let rules = self.rules.read_with(guard);
random_line_split
media_rule.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/. */ //! An [`@media`][media] urle. //! //! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media use cs...
}
{ let media_queries = self.media_queries.read_with(guard); let rules = self.rules.read_with(guard); MediaRule { media_queries: Arc::new(lock.wrap(media_queries.clone())), rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))), source_location: sel...
identifier_body
CSS.js
djsex.css = { /* * http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript */ create: function(stylesheet) { var head = document.getElementsByTagName('head')[0], style = document.createElement('style'), rules = document.createTextNode(stylesh...
classes.push(classname); el.className = classes.join(" ") } else { el.className=classname; } }, deleteClass: function (el, classname) { if(el.className) { var classes = el.className.split(" "); for(i=0; i<=classes.lengt...
if(classname == thisclassname) alreadyclassed=true; }); if(!alreadyclassed)
random_line_split
color.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/. */ //! Computed color values. use cssparser::{Color as CSSParserColor, RGBA}; use std::fmt; use style_traits::{CssWr...
let a = f32::min(a, 1.); let inverse_a = 1. / a; let r = (p1 * r1 + p2 * r2) * inverse_a; let g = (p1 * g1 + p2 * g2) * inverse_a; let b = (p1 * b1 + p2 * b2) * inverse_a; return RGBA::from_floats(r, g, b, a); } } impl ToCss for Color { fn to_css<W>(&self, dest...
{ return RGBA::transparent(); }
conditional_block
color.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/. */ //! Computed color values. use cssparser::{Color as CSSParserColor, RGBA}; use std::fmt; use style_traits::{CssWr...
let p1 = ratios.bg; let a1 = color.alpha_f32(); let r1 = a1 * color.red_f32(); let g1 = a1 * color.green_f32(); let b1 = a1 * color.blue_f32(); let p2 = ratios.fg; let a2 = fg_color.alpha_f32(); let r2 = a2 * fg_color.red_f32(); let g2 = a2 * fg_...
// color = (self_color * self_alpha * bg_ratio + // fg_color * fg_alpha * fg_ratio) / alpha
random_line_split
color.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/. */ //! Computed color values. use cssparser::{Color as CSSParserColor, RGBA}; use std::fmt; use style_traits::{CssWr...
let p2 = ratios.fg; let a2 = fg_color.alpha_f32(); let r2 = a2 * fg_color.red_f32(); let g2 = a2 * fg_color.green_f32(); let b2 = a2 * fg_color.blue_f32(); let a = p1 * a1 + p2 * a2; if a <= 0. { return RGBA::transparent(); } let a = ...
{ let (color, ratios) = match *self { // Common cases that the complex color is either pure numeric // color or pure currentcolor. GenericColor::Numeric(color) => return color, GenericColor::Foreground => return fg_color, GenericColor::Complex(color, r...
identifier_body
color.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/. */ //! Computed color values. use cssparser::{Color as CSSParserColor, RGBA}; use std::fmt; use style_traits::{CssWr...
(&self, fg_color: RGBA) -> RGBA { let (color, ratios) = match *self { // Common cases that the complex color is either pure numeric // color or pure currentcolor. GenericColor::Numeric(color) => return color, GenericColor::Foreground => return fg_color, ...
to_rgba
identifier_name
main.rs
#![deny(rust_2018_idioms, deprecated)] mod commands; use std::collections::HashSet; use commands::*; use serde::Deserialize; use serenity::async_trait; use serenity::client::bridge::gateway::GatewayIntents; use serenity::framework::standard::help_commands::with_embeds; use serenity::framework::standard::macros::*; u...
; #[async_trait] impl EventHandler for Handler { async fn ready(&self, ctx: Context, _: Ready) { ctx.set_activity(Activity::playing("charades")).await; } } #[group("General")] #[commands(ping, avatar_url)] struct General; #[help] async fn my_help( ctx: &Context, msg: &Message, args: Args,...
Handler
identifier_name
main.rs
#![deny(rust_2018_idioms, deprecated)] mod commands; use std::collections::HashSet; use commands::*; use serde::Deserialize; use serenity::async_trait; use serenity::client::bridge::gateway::GatewayIntents; use serenity::framework::standard::help_commands::with_embeds; use serenity::framework::standard::macros::*; u...
} } #[derive(Deserialize)] struct Config { token: String, prefix: String, } fn read_config() -> Result<Config, Box<dyn std::error::Error>> { let path = std::env::var("KITTY_CONFIG").unwrap_or_else(|_| "config.json".to_string()); let content = std::fs::read_to_string(path)?; Ok(serde_json::fro...
{ error!("`{:?}`", err); }
conditional_block
main.rs
#![deny(rust_2018_idioms, deprecated)] mod commands; use std::collections::HashSet; use commands::*; use serde::Deserialize; use serenity::async_trait; use serenity::client::bridge::gateway::GatewayIntents; use serenity::framework::standard::help_commands::with_embeds; use serenity::framework::standard::macros::*; u...
let shard_manager = client.shard_manager.clone(); tokio::spawn(async move { tokio::signal::ctrl_c().await.unwrap(); shard_manager.lock().await.shutdown_all().await; }); client.start_autosharded().await?; Ok(()) }
random_line_split
p2p_feefilter.py
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of feefilter messages.""" from decimal import Decimal import time from test_framework...
FeeFilterTest().main()
conditional_block
p2p_feefilter.py
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of feefilter messages.""" from decimal import Decimal import time from test_framework...
# Test that invs are received by test connection for all txs at # feerate of 20 sat/byte node1.settxfee(Decimal("0.02000000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert allInvsMatch(txids, self.nodes[0].p2p) self.nodes[0].p2p.clear_i...
random_line_split
p2p_feefilter.py
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of feefilter messages.""" from decimal import Decimal import time from test_framework...
(P2PInterface): def __init__(self): super().__init__() self.txinvs = [] def on_inv(self, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [...
TestP2PConn
identifier_name
p2p_feefilter.py
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of feefilter messages.""" from decimal import Decimal import time from test_framework...
# Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True time.sleep(1) return False class TestP...
return format(hash, '064x')
identifier_body
lights.rs
extern crate nalgebra as na; use glium; use glium::uniforms::UniformValue; const MAX_SPHERICAL_LIGHTS: u32 = 32; #[derive(Copy, Clone)] pub struct SphericalLight { position: [f32; 3], color: [f32; 3], range: f32, } implement_uniform_block!(SphericalLight, position, color, range); //Testing, remove if i...
() -> LightUniform { LightUniform { sphere_light_count: 0, sphere_lights: [SphericalLight::new(); MAX_SPHERICAL_LIGHTS as usize], padding: [0.0; 3] } } pub fn add_light(&mut self, light: SphericalLight) { if self.sphere_lights.len() < ...
new
identifier_name
lights.rs
extern crate nalgebra as na; use glium; use glium::uniforms::UniformValue; const MAX_SPHERICAL_LIGHTS: u32 = 32; #[derive(Copy, Clone)] pub struct SphericalLight { position: [f32; 3], color: [f32; 3], range: f32, } implement_uniform_block!(SphericalLight, position, color, range); //Testing, remove if i...
}
{ if self.sphere_lights.len() < MAX_SPHERICAL_LIGHTS as usize { self.sphere_lights[self.sphere_light_count as usize] = light; self.sphere_light_count += 1; } else { panic!("Too many lights have been added"); } }
identifier_body
lights.rs
extern crate nalgebra as na; use glium; use glium::uniforms::UniformValue; const MAX_SPHERICAL_LIGHTS: u32 = 32; #[derive(Copy, Clone)] pub struct SphericalLight { position: [f32; 3], color: [f32; 3], range: f32, } implement_uniform_block!(SphericalLight, position, color, range); //Testing, remove if i...
} impl SphericalLight { pub fn new() -> SphericalLight { SphericalLight { position: [0.0; 3], color: [0.0; 3], range: 0.0, } } pub fn set_position(mut self, position: [f32; 3]) { self.position = position; } } #[derive(Copy, C...
fn visit_values<'a, F: FnMut(&str, UniformValue<'a>)>(&'a self, mut f: F) { f("position", UniformValue::Vec3(self.position.clone())); f("position", UniformValue::Vec3(self.color.clone())); f("color", UniformValue::Float(self.range.clone())); }
random_line_split
lights.rs
extern crate nalgebra as na; use glium; use glium::uniforms::UniformValue; const MAX_SPHERICAL_LIGHTS: u32 = 32; #[derive(Copy, Clone)] pub struct SphericalLight { position: [f32; 3], color: [f32; 3], range: f32, } implement_uniform_block!(SphericalLight, position, color, range); //Testing, remove if i...
else { panic!("Too many lights have been added"); } } }
{ self.sphere_lights[self.sphere_light_count as usize] = light; self.sphere_light_count += 1; }
conditional_block
reverse-string.rs
//! Tests for reverse-string //! //! Generated by [script][script] using [canonical data][canonical-data] //! //! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py //! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_...
#[test] /// a sentence with punctuation fn test_a_sentence_with_punctuation() { process_reverse_case("I'm hungry!", "!yrgnuh m'I"); } #[test] /// a palindrome fn test_a_palindrome() { process_reverse_case("racecar", "racecar"); }
{ process_reverse_case("Ramen", "nemaR"); }
identifier_body
reverse-string.rs
//! Tests for reverse-string //! //! Generated by [script][script] using [canonical data][canonical-data] //! //! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py //! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_...
() { process_reverse_case("", ""); } #[test] /// a word fn test_a_word() { process_reverse_case("robot", "tobor"); } #[test] /// a capitalized word fn test_a_capitalized_word() { process_reverse_case("Ramen", "nemaR"); } #[test] /// a sentence with punctuation fn test_a_sentence_with_punctuation() { ...
test_empty_string
identifier_name
reverse-string.rs
//! Tests for reverse-string //! //! Generated by [script][script] using [canonical data][canonical-data] //! //! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py //! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_...
fn test_a_word() { process_reverse_case("robot", "tobor"); } #[test] /// a capitalized word fn test_a_capitalized_word() { process_reverse_case("Ramen", "nemaR"); } #[test] /// a sentence with punctuation fn test_a_sentence_with_punctuation() { process_reverse_case("I'm hungry!", "!yrgnuh m'I"); } #[t...
#[test] /// a word
random_line_split
simple_receiver.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
match event { crust::Event::NewMessage(endpoint, bytes) => { // For this example, we only expect to receive encoded `u8`s let requested_value = match String::from_utf8(bytes) { Ok(message) => { match u8::from_str(message.as_...
println!("Run the simple_sender example in another terminal to send messages to this node."); // Receive the next event while let Ok(event) = channel_receiver.recv() { // Handle the event
random_line_split
simple_receiver.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
print!("Listening for new connections on "); for endpoint in &listening_endpoints { print!("{:?}, ", *endpoint); }; println!("Run the simple_sender example in another terminal to send messages to this node."); // Receive the next event while let Ok(event) = channel_receiver.recv() { ...
{ match env_logger::init() { Ok(()) => {}, Err(e) => debug!("Error initialising logger; continuing without: {:?}", e) } let _ = write_config_file(None, None,Some(9999)).unwrap(); // We receive events (e.g. new connection, message received) from the ConnectionManager via an // asynch...
identifier_body
simple_receiver.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
() { match env_logger::init() { Ok(()) => {}, Err(e) => debug!("Error initialising logger; continuing without: {:?}", e) } let _ = write_config_file(None, None,Some(9999)).unwrap(); // We receive events (e.g. new connection, message received) from the ConnectionManager via an // asy...
main
identifier_name
keyfsm.rs
9 A B C D E F [ 0x00, 0x43, 0x00, 0x3F, 0x3D, 0x3B, 0x3C, 0x58, 0x00, 0x44, 0x42, 0x40, 0x3E, 0x0F, 0x29, 0x00, 0x00, 0x38, 0x2A, 0x00, 0x1D, 0x10, 0x02, 0x00, 0x00, 0x00, 0x2C, 0x1F, 0x1E, 0x11, 0x03, 0x00, 0x00, 0x2E, 0x2D, 0x20, 0x12, 0x05, 0x04, 0x00...
() -> ProcReply { ProcReply::NothingToDo } } enum State { NotInKey, SimpleKey(u8), PossibleBreakCode, KnownBreakCode(u8), UnmodifiedKey(u8), ToggleLedFirst(u8), // InPause(u8), // Number of keycodes in pause left to handle- alternate impl. Inconsistent, ExpectingBufferCl...
init
identifier_name
keyfsm.rs
9 A B C D E F [ 0x00, 0x43, 0x00, 0x3F, 0x3D, 0x3B, 0x3C, 0x58, 0x00, 0x44, 0x42, 0x40, 0x3E, 0x0F, 0x29, 0x00, 0x00, 0x38, 0x2A, 0x00, 0x1D, 0x10, 0x02, 0x00, 0x00, 0x00, 0x2C, 0x1F, 0x1E, 0x11, 0x03, 0x00, 0x00, 0x2E, 0x2D, 0x20, 0x12, 0x05, 0x04, 0x00...
| (&State::SimpleKey(_), &ProcReply::SentKey(_)) | (&State::KnownBreakCode(_), &ProcReply::SentKey(_)) | (&State::UnmodifiedKey(_), &ProcReply::SentKey(_)) | (&State::ExpectingBufferClear, &ProcReply::ClearedBuffer) => State::NotInKey, (&State::NotInKey, &Proc...
fn next_state(&mut self, curr_reply: &ProcReply) -> State { match (&self.curr_state, curr_reply) { (_, &ProcReply::KeyboardReset) => State::ExpectingBufferClear, (&State::NotInKey, &ProcReply::NothingToDo)
random_line_split
test_html5lib.py
"""Tests to ensure that the html5lib tree builder generates good trees.""" import warnings try: from bs4.builder import HTML5TreeBuilder HTML5LIB_PRESENT = True except ImportError, e: HTML5LIB_PRESENT = False from bs4.element import SoupStrainer from bs4.testing import ( HTML5TreeBuilderSmokeTest, ...
(self): """ Test that extraction does not destroy the tree. https://bugs.launchpad.net/beautifulsoup/+bug/1782928 """ markup = """ <html><head></head> <style> </style><script></script><body><p>hello</p></body></html> """ soup = self.soup(markup) [s.extract() for...
test_extraction
identifier_name
test_html5lib.py
"""Tests to ensure that the html5lib tree builder generates good trees.""" import warnings try: from bs4.builder import HTML5TreeBuilder HTML5LIB_PRESENT = True except ImportError, e: HTML5LIB_PRESENT = False from bs4.element import SoupStrainer from bs4.testing import ( HTML5TreeBuilderSmokeTest, ...
def test_cloned_multivalue_node(self): markup = b"""<a class="my_class"><p></a>""" soup = self.soup(markup) a1, a2 = soup.find_all('a') self.assertEqual(a1, a2) assert a1 is not a2 def test_foster_parenting(self): markup = b"""<table><td></tbody>A""" so...
"""Processing instructions become comments.""" markup = b"""<?PITarget PIContent?>""" soup = self.soup(markup) assert str(soup).startswith("<!--?PITarget PIContent?-->")
identifier_body
test_html5lib.py
"""Tests to ensure that the html5lib tree builder generates good trees.""" import warnings try: from bs4.builder import HTML5TreeBuilder HTML5LIB_PRESENT = True except ImportError, e: HTML5LIB_PRESENT = False from bs4.element import SoupStrainer from bs4.testing import ( HTML5TreeBuilderSmokeTest, ...
self.assertEqual(len(inputs), 1) def test_tracking_line_numbers(self): # The html.parser TreeBuilder keeps track of line number and # position of each element. markup = "\n <p>\n\n<sourceline>\n<b>text</b></sourceline><sourcepos></p>" soup = self.soup(markup) self...
inputs.extend(form.find_all('input'))
conditional_block
test_html5lib.py
"""Tests to ensure that the html5lib tree builder generates good trees.""" import warnings try: from bs4.builder import HTML5TreeBuilder HTML5LIB_PRESENT = True except ImportError, e: HTML5LIB_PRESENT = False from bs4.element import SoupStrainer from bs4.testing import ( HTML5TreeBuilderSmokeTest, ...
# The <noscript> tag was moved beneath a copy of the <a> tag, # but the 'target' string within is still connected to the # (second) 'aftermath' string. self.assertEqual(final_aftermath, target.next_element) self.assertEqual(target, final_aftermath.previous_element) d...
target = soup.find(string='target') # The 'aftermath' string was duplicated; we want the second one. final_aftermath = soup.find_all(string='aftermath')[-1]
random_line_split
boxed.rs
box: //! //! ``` //! let x = Box::new(5); //! ``` //! //! Creating a recursive data structure: //! //! ``` //! #[derive(Debug)] //! enum List<T> { //! Cons(T, Box<List<T>>), //! Nil, //! } //! //! fn main() { //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); //! pri...
} #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized + PartialEq> PartialEq for Box<T> { #[inline] fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) } } #[stable(feature = "rust1", since...
{ (**self).clone_from(&(**source)); }
identifier_body
boxed.rs
Default; use core::error::{Error, FromError}; use core::fmt; use core::hash::{self, Hash}; use core::mem; use core::ops::{Deref, DerefMut}; use core::ptr::Unique; use core::raw::TraitObject; /// A value that represents the heap. This is the default place that the `box` /// keyword allocates into when no place is suppl...
} } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for Box<Any> {
random_line_split
boxed.rs
a box: //! //! ``` //! let x = Box::new(5); //! ``` //! //! Creating a recursive data structure: //! //! ``` //! #[derive(Debug)] //! enum List<T> { //! Cons(T, Box<List<T>>), //! Nil, //! } //! //! fn main() { //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); //! p...
(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) } #[inline] fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] fn gt(&self, other: &Box<T>) -> bool { Partial...
lt
identifier_name
boxed.rs
//! //! ``` //! let x = Box::new(5); //! ``` //! //! Creating a recursive data structure: //! //! ``` //! #[derive(Debug)] //! enum List<T> { //! Cons(T, Box<List<T>>), //! Nil, //! } //! //! fn main() { //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); //! println!(...
{ Err(self) }
conditional_block
ast_util.rs
a string representation of a signed int type, with its value. /// We want to avoid "45int" and "-3int" in favor of "45" and "-3" pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String { let s = match t { TyIs => "isize", TyI8 => "i8", TyI16 => "i16", TyI32 => "i32", T...
fn visit_block(&mut self, block: &Block) { self.operation.visit_id(block.id); visit::walk_block(self, block) } fn visit_stmt(&mut
{ self.operation.visit_id(local.id); visit::walk_local(self, local) }
identifier_body
ast_util.rs
Is TyI64 => 0x8000000000000000 } } /// Get a string representation of an unsigned int type, with its value. /// We want to avoid "42u" in favor of "42us". "42uint" is right out. pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String { let s = match t { TyUs => "usize", TyU8 => ...
{}
conditional_block
ast_util.rs
Get a string representation of a signed int type, with its value. /// We want to avoid "45int" and "-3int" in favor of "45" and "-3" pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String { let s = match t { TyIs => "isize", TyI8 => "i8", TyI16 => "i16", TyI32 => "i32", ...
} fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) { self.operation.visit_id(foreign_item.id); visit::walk_foreign_item(self, foreign_item) } fn visit_item(&mut self, item: &Item) { if !self.pass_through_items { if self.visited_outermost { ...
random_line_split
ast_util.rs
Get a string representation of a signed int type, with its value. /// We want to avoid "45int" and "-3int" in favor of "45" and "-3" pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String { let s = match t { TyIs => "isize", TyI8 => "i8", TyI16 => "i16", TyI32 => "i32", ...
(&mut self, id: NodeId) { self.min = cmp::min(self.min, id); self.max = cmp::max(self.max, id + 1); } } pub trait IdVisitingOperation { fn visit_id(&mut self, node_id: NodeId); } /// A visitor that applies its operation to all of the node IDs /// in a visitable thing. pub struct IdVisitor<'a,...
add
identifier_name
isari-multi-input.component.ts
import { Component, Input, EventEmitter, Output, OnInit } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; const ENTER = 13; const BACKSPACE = 8; @Component({ selector: 'isari-multi-input', templateUrl: './isari-multi-input.component.html', styleUrls: ['./isari-multi-input.componen...
} }
this.onUpdate.emit({log: true, path: this.path, type: 'push'}); }
random_line_split
isari-multi-input.component.ts
import { Component, Input, EventEmitter, Output, OnInit } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; const ENTER = 13; const BACKSPACE = 8; @Component({ selector: 'isari-multi-input', templateUrl: './isari-multi-input.component.html', styleUrls: ['./isari-multi-input.componen...
($event) { this.addValue(this.selectControl.value); this.empty = true; } onFocus($event) { this.empty = false; } onKey($event) { if ($event.keyCode === ENTER) { this.addValue(this.selectControl.value); } if ($event.keyCode === BACKSPACE && this.selectControl.value === '' && this....
onBlur
identifier_name
isari-multi-input.component.ts
import { Component, Input, EventEmitter, Output, OnInit } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; const ENTER = 13; const BACKSPACE = 8; @Component({ selector: 'isari-multi-input', templateUrl: './isari-multi-input.component.html', styleUrls: ['./isari-multi-input.componen...
if ($event.keyCode === BACKSPACE && this.selectControl.value === '' && this.values.length > 0) { this.removeValue(this.values[this.values.length - 1], {}); } } removeValue(value, $event) { const removedIndex = this.values.findIndex(v => v === value); this.values = this.values.filter(v => v !...
{ this.addValue(this.selectControl.value); }
conditional_block
isari-multi-input.component.ts
import { Component, Input, EventEmitter, Output, OnInit } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; const ENTER = 13; const BACKSPACE = 8; @Component({ selector: 'isari-multi-input', templateUrl: './isari-multi-input.component.html', styleUrls: ['./isari-multi-input.componen...
onFocus($event) { this.empty = false; } onKey($event) { if ($event.keyCode === ENTER) { this.addValue(this.selectControl.value); } if ($event.keyCode === BACKSPACE && this.selectControl.value === '' && this.values.length > 0) { this.removeValue(this.values[this.values.length - 1], {...
{ this.addValue(this.selectControl.value); this.empty = true; }
identifier_body
indexTree.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
this.model.rerender(location); } updateElementHeight(location: number[], height: number): void { this.model.updateElementHeight(location, height); } protected createModel(user: string, view: IList<ITreeNode<T, TFilterData>>, options: IIndexTreeOptions<T, TFilterData>): ITreeModel<T, TFilterData, number[]> {...
{ this.view.rerender(); return; }
conditional_block
indexTree.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(location?: number[]): void { if (location === undefined) { this.view.rerender(); return; } this.model.rerender(location); } updateElementHeight(location: number[], height: number): void { this.model.updateElementHeight(location, height); } protected createModel(user: string, view: IList<ITreeNode<...
rerender
identifier_name