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
ModuleLoader.ts
import {Observer} from '@enbock/state-value-observer/ValueObserver'; import React from 'react'; interface LoadedModuleDictionary {
[name: string]: typeof React.Component, } export default class ModuleLoader { moduleState: Observer<typeof React.Component | null>; dictionary: LoadedModuleDictionary; pathToRoot: string; constructor(pathToRoot: string, moduleState: Observer<typeof React.Component | null>) { this.moduleState = moduleSta...
random_line_split
ModuleLoader.ts
import {Observer} from '@enbock/state-value-observer/ValueObserver'; import React from 'react'; interface LoadedModuleDictionary { [name: string]: typeof React.Component, } export default class ModuleLoader { moduleState: Observer<typeof React.Component | null>; dictionary: LoadedModuleDictionary; pathToRoot:...
(pathToRoot: string, moduleState: Observer<typeof React.Component | null>) { this.moduleState = moduleState; this.dictionary = {}; this.pathToRoot = pathToRoot; } async loadModule(modulePath: string) { let module: typeof React.Component; if (!this.dictionary.hasOwnProperty(modulePath)) { ...
constructor
identifier_name
todo.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; @Injectable() export class TodoService { co
private http: Http ) { } private requestOptions = new RequestOptions({ headers: new Headers({ 'Content-Type': 'application/json' }) }); create(todo: src.Models.Todo) { return this.http.post('/api/Todoes', todo, this.requestOptions) .map((response: Response) => response.json()); } readAll() { re...
nstructor(
identifier_name
todo.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; @Injectable() export class TodoService { constructor( private http: Http ) {
private requestOptions = new RequestOptions({ headers: new Headers({ 'Content-Type': 'application/json' }) }); create(todo: src.Models.Todo) { return this.http.post('/api/Todoes', todo, this.requestOptions) .map((response: Response) => response.json()); } readAll() { return this.http.get('/api/Todo...
}
identifier_body
todo.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; @Injectable() export class TodoService { constructor( private http: Http ) { } private requestOptions = new RequestOptions({ headers: new Headers({
}); create(todo: src.Models.Todo) { return this.http.post('/api/Todoes', todo, this.requestOptions) .map((response: Response) => response.json()); } readAll() { return this.http.get('/api/Todoes', this.requestOptions) .map((response: Response) => response.json()); } update(todo: src.Models.Todo) { ...
'Content-Type': 'application/json' })
random_line_split
notify.py
# coding: utf-8 import requests _IFTTT_URL = 'https://maker.ifttt.com/trigger/{event}/with/key/{key}' class IFTTTNotifier: def __init__(self, key, event_name): self._key = key self._timeout = 5 self._event = event_name def trigger(self, **kwargs): return self._trigger(self....
query_data[key] = kwargs[key] if query_data: r = requests.post(url, json=query_data, timeout=self._timeout) else: r = requests.post(url, timeout=self._timeout) if r.status_code == 200: print(r.text) elif r.status_code == 401: ...
query_data = {} for key in valid_params: if key in kwargs:
random_line_split
notify.py
# coding: utf-8 import requests _IFTTT_URL = 'https://maker.ifttt.com/trigger/{event}/with/key/{key}' class IFTTTNotifier: def
(self, key, event_name): self._key = key self._timeout = 5 self._event = event_name def trigger(self, **kwargs): return self._trigger(self._event, **kwargs) def _trigger(self, event, **kwargs): url = _IFTTT_URL.format(key=self._key, event=event) valid_params = (...
__init__
identifier_name
notify.py
# coding: utf-8 import requests _IFTTT_URL = 'https://maker.ifttt.com/trigger/{event}/with/key/{key}' class IFTTTNotifier: def __init__(self, key, event_name): self._key = key self._timeout = 5 self._event = event_name def trigger(self, **kwargs):
def _trigger(self, event, **kwargs): url = _IFTTT_URL.format(key=self._key, event=event) valid_params = ('value1', 'value2', 'value3') query_data = {} for key in valid_params: if key in kwargs: query_data[key] = kwargs[key] if query_data: ...
return self._trigger(self._event, **kwargs)
identifier_body
notify.py
# coding: utf-8 import requests _IFTTT_URL = 'https://maker.ifttt.com/trigger/{event}/with/key/{key}' class IFTTTNotifier: def __init__(self, key, event_name): self._key = key self._timeout = 5 self._event = event_name def trigger(self, **kwargs): return self._trigger(self....
raise RuntimeError('IFTTT trigger failed! unknow error')
conditional_block
io.rs
use alloc::boxed::Box; use core::result; use std::error; /// A specialized [`Result`](../result/enum.Result.html) type for I/O /// operations. /// /// This type is broadly used across `std::io` for any operation which may /// produce an error. /// /// This typedef is generally used to avoid writing out `io::Error` dir...
(&mut self) -> Result<()> { Ok(()) } } pub trait Read { fn read(&mut self, buf: &mut [u8]) -> Result<usize>; }
flush
identifier_name
io.rs
use alloc::boxed::Box; use core::result; use std::error; /// A specialized [`Result`](../result/enum.Result.html) type for I/O /// operations. /// /// This type is broadly used across `std::io` for any operation which may /// produce an error. /// /// This typedef is generally used to avoid writing out `io::Error` dir...
/// ``` //#[stable(feature = "rust1", since = "1.0.0")] pub type Result<T> = result::Result<T, Error>; /// The error type for I/O operations of the `Read`, `Write`, `Seek`, and /// associated traits. /// /// Errors mostly originate from the underlying OS, but custom instances of /// `Error` can be created with crafted...
/// Ok(buffer) /// }
random_line_split
ivy-codemirror-test.js
import CodeMirror from 'codemirror'; import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('ivy-codemirror', { unit: true }); test('should update value property when CodeMirror changes', function(assert) { var component = this.subject(); this.render(); var code...
var context = Ember.Object.extend({ computedValue: Ember.computed.readOnly('actualValue') }).create({ actualValue: beforeValue }); var componentOptions = { foo: context }; componentOptions[key + 'Binding'] = 'foo.computedValue'; var component = this.subject(componentOptions); th...
{ test('should update CodeMirror ' + key + ' option when ' + key + ' property changes', function(assert) { var component = this.subject(); this.render(); var codeMirror = component.get('codeMirror'); assert.equal( codeMirror.getOption(key), beforeValue, 'precond - initial value of ' + key...
identifier_body
ivy-codemirror-test.js
import CodeMirror from 'codemirror'; import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('ivy-codemirror', { unit: true }); test('should update value property when CodeMirror changes', function(assert) { var component = this.subject(); this.render(); var code...
(key, beforeValue, afterValue) { test('should update CodeMirror ' + key + ' option when ' + key + ' property changes', function(assert) { var component = this.subject(); this.render(); var codeMirror = component.get('codeMirror'); assert.equal( codeMirror.getOption(key), beforeValue, 'pre...
optionTest
identifier_name
ivy-codemirror-test.js
import CodeMirror from 'codemirror'; import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('ivy-codemirror', { unit: true }); test('should update value property when CodeMirror changes', function(assert) { var component = this.subject(); this.render(); var code...
var codeMirror = component.get('codeMirror'); assert.equal( codeMirror.getOption(key), beforeValue, 'precond - initial value of ' + key + ' option is correct'); Ember.run(function() { context.set('actualValue', afterValue); }); assert.equal( codeMirror.getOption(key), after...
var component = this.subject(componentOptions); this.render();
random_line_split
ast-to-selector-map.ts
import { EastStore } from '../../reducers/reducers'; import * as ESTree from 'estree'; import { Program } from 'estree'; import { selectAllFilesList, selectASTNodeByTypeAndId, selectAvailableImportsFromFile, selectNextParentByType } from '../../selectors/select-ast-node'; import { TextualViewProps } from '...
{ const filePathOfCurrentProgram = selectNextParentByType(state, astNode, "Program").__east_uid; const absolutePath: string = path.join(path.dirname(filePathOfCurrentProgram), ownProps.sourceFile as string) + '.js'; return selectAvailableImportsFromFile( state, selectASTNodeByTypeAndId(state, 'Program', a...
identifier_body
ast-to-selector-map.ts
import { EastStore } from '../../reducers/reducers'; import * as ESTree from 'estree'; import { Program } from 'estree'; import { selectAllFilesList, selectASTNodeByTypeAndId, selectAvailableImportsFromFile, selectNextParentByType } from '../../selectors/select-ast-node'; import { TextualViewProps } from '...
const availableImports = getPotentialImportsOfFile(state, ownProps, astNode); const selectedImportSpecifierName = selectASTNodeByTypeAndId(state, "Identifier", (astNode.imported as any).uid) as ESTree.Identifier; const selectedImportSpecifierIndex = availableImports.findIndex( importElement => i...
random_line_split
ast-to-selector-map.ts
import { EastStore } from '../../reducers/reducers'; import * as ESTree from 'estree'; import { Program } from 'estree'; import { selectAllFilesList, selectASTNodeByTypeAndId, selectAvailableImportsFromFile, selectNextParentByType } from '../../selectors/select-ast-node'; import { TextualViewProps } from '...
(state: EastStore, ownProps: TextualViewProps, astNode: ESTree.Node): { label: string, value: ESTree.ImportSpecifier | ESTree.ImportNamespaceSpecifier }[] { const filePathOfCurrentProgram = selectNextParentByType(state, astNode, "Program").__east_uid; const absolutePath: string = path.join(path.dirname(filePath...
getPotentialImportsOfFile
identifier_name
docs.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const chalk_1 = require("chalk"); const command_1 = require("@ionic/cli-utils/lib/command"); const serve_1 = require("@ionic/cli-utils/lib/serve"); let DocsCommand = class DocsCommand extends command_1.Command...
} catch (e) { if (isSuperAgentError(e)) { if (e.response.status === 404) { this.env.log.warn(`Docs not found for your specific version of Ionic. Directing you to latest docs.`); opn(`${docsHomepage}/api`, { wait:...
{ return tslib_1.__awaiter(this, void 0, void 0, function* () { const { isSuperAgentError } = yield Promise.resolve().then(() => require('@ionic/cli-utils/guards')); const { createRequest } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/http')); const brow...
identifier_body
docs.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const chalk_1 = require("chalk"); const command_1 = require("@ionic/cli-utils/lib/command"); const serve_1 = require("@ionic/cli-utils/lib/serve"); let DocsCommand = class DocsCommand extends command_1.Command...
(inputs, options) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const { isSuperAgentError } = yield Promise.resolve().then(() => require('@ionic/cli-utils/guards')); const { createRequest } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/http')); ...
run
identifier_name
docs.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const chalk_1 = require("chalk"); const command_1 = require("@ionic/cli-utils/lib/command"); const serve_1 = require("@ionic/cli-utils/lib/serve"); let DocsCommand = class DocsCommand extends command_1.Command...
const browser = options['browser'] ? String(options['browser']) : undefined; const opn = yield Promise.resolve().then(() => require('opn')); const docsHomepage = 'https://ionicframework.com/docs'; let url = docsHomepage; const project = this.env.project.direct...
const { createRequest } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/http'));
random_line_split
docs.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const chalk_1 = require("chalk"); const command_1 = require("@ionic/cli-utils/lib/command"); const serve_1 = require("@ionic/cli-utils/lib/serve"); let DocsCommand = class DocsCommand extends command_1.Command...
else if (project.type === 'ionic-angular') { url = 'https://ionicframework.com/docs/api'; // TODO: can know framework version, HEAD request, etc } } try { const { req } = yield createRequest(this.env.config, 'head', url); ...
{ url = 'https://ionicframework.com/docs/v1/'; }
conditional_block
deslizador.py
import pilasengine # Permite que este ejemplo funcion incluso si no has instalado pilas. import sys sys.path.insert(0, "..") pilas = pilasengine.iniciar() mono = pilas.actores.Mono(y=-100) def cuando_cambia_escala(valor):
deslizador_escala = pilas.interfaz.Deslizador(y=50) deslizador_escala.conectar(cuando_cambia_escala) def cuando_cambia_rotacion(valor): mono.rotacion = valor * 360 deslizador_rotacion = pilas.interfaz.Deslizador(y=100) deslizador_rotacion.conectar(cuando_cambia_rotacion) def cuando_cambia_posicion(valor): ...
mono.escala = valor * 2
identifier_body
deslizador.py
import pilasengine # Permite que este ejemplo funcion incluso si no has instalado pilas. import sys sys.path.insert(0, "..") pilas = pilasengine.iniciar() mono = pilas.actores.Mono(y=-100) def cuando_cambia_escala(valor): mono.escala = valor * 2 deslizador_escala = pilas.interfaz.Deslizador(y=50) deslizador_esca...
print valor deslizador_posicion = pilas.interfaz.Deslizador(y=150) deslizador_posicion.conectar(cuando_cambia_posicion) pilas.avisar("Usa el deslizador para modificar al mono.") pilas.ejecutar()
mono.x = -200 + 400 * valor
random_line_split
deslizador.py
import pilasengine # Permite que este ejemplo funcion incluso si no has instalado pilas. import sys sys.path.insert(0, "..") pilas = pilasengine.iniciar() mono = pilas.actores.Mono(y=-100) def
(valor): mono.escala = valor * 2 deslizador_escala = pilas.interfaz.Deslizador(y=50) deslizador_escala.conectar(cuando_cambia_escala) def cuando_cambia_rotacion(valor): mono.rotacion = valor * 360 deslizador_rotacion = pilas.interfaz.Deslizador(y=100) deslizador_rotacion.conectar(cuando_cambia_rotacion) d...
cuando_cambia_escala
identifier_name
testExtractACM.py
# Copyright (C) 2013-2015 MetaMorph Software, Inc # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specifications, and documentation # (collectively "the Data"), to deal in the Data ...
(mypath): print "Starting test script for ExtractACM-XMLfromCASModules.exe" from os import listdir from os.path import isfile, join, getsize matches = [] for root, dirs, files in os.walk(mypath): for filename in fnmatch.filter(files, '*.prt*') + fnmatch.filter(files, '*.asm...
scan_for_CAD_files
identifier_name
testExtractACM.py
# Copyright (C) 2013-2015 MetaMorph Software, Inc # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specifications, and documentation # (collectively "the Data"), to deal in the Data ...
def run_the_extractor(filename): print "converting " + filename outfilename = filename + '.xml' exe_path = os.getenv("PROE_ISIS_EXTENSIONS") + 'bin\ExtractACM-XMLfromCreoModels.exe' arguments = ' -c "'+filename+'" -x "' + outfilename + '"' command = exe_path + arguments return_code = s...
count = 0 for t in thread_array: if t.isAlive(): count += 1 return count
identifier_body
testExtractACM.py
# Copyright (C) 2013-2015 MetaMorph Software, Inc # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specifications, and documentation # (collectively "the Data"), to deal in the Data ...
max_threads = 1 threads = [] for fn in matches: while count_alive_threads(threads) >= max_threads: time.sleep(1) newThread = threading.Thread(target=run_the_extractor, kwargs={"filename": fn}) newThread.start() threads.append(newThread) def count_ali...
for filename in fnmatch.filter(files, '*.prt*') + fnmatch.filter(files, '*.asm*'): if not filename.endswith('.xml'): matches.append(os.path.join(root, filename))
conditional_block
testExtractACM.py
# Copyright (C) 2013-2015 MetaMorph Software, Inc # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specifications, and documentation # (collectively "the Data"), to deal in the Data ...
from os.path import isfile, join, getsize matches = [] for root, dirs, files in os.walk(mypath): for filename in fnmatch.filter(files, '*.prt*') + fnmatch.filter(files, '*.asm*'): if not filename.endswith('.xml'): matches.append(os.path.join(root, filename)) ...
from os import listdir
random_line_split
challenge13.rs
use aes::Aes128; use aes::{chunks_count, BLOCK_SIZE}; use crate::errors::*; use crate::prefix_suffix_oracles::Oracle; use crate::prefix_suffix_oracles::Oracle13; use super::challenge12::prefix_plus_suffix_length; use super::prefix_length; // The following function works under the single assumption that the target v...
() -> Result<()> { let oracle = Oracle13::new()?; let prefix_len = prefix_length(&oracle)?; let (prefix_chunks_count, prefix_fill_len) = chunks_count(prefix_len); let target_cleartext = b"admin".pad(); let mut input = vec![0; prefix_fill_len]; input.extend_from_slice(&target_cleartext); //...
run
identifier_name
challenge13.rs
use aes::Aes128; use aes::{chunks_count, BLOCK_SIZE}; use crate::errors::*; use crate::prefix_suffix_oracles::Oracle; use crate::prefix_suffix_oracles::Oracle13; use super::challenge12::prefix_plus_suffix_length; use super::prefix_length; // The following function works under the single assumption that the target v...
compare_eq((chunks_count + 1) * BLOCK_SIZE, ciphertext.len())?; // Replace last block with target_last_block ciphertext[chunks_count * BLOCK_SIZE..].copy_from_slice(target_last_block); oracle.verify_solution(&ciphertext) }
{ let oracle = Oracle13::new()?; let prefix_len = prefix_length(&oracle)?; let (prefix_chunks_count, prefix_fill_len) = chunks_count(prefix_len); let target_cleartext = b"admin".pad(); let mut input = vec![0; prefix_fill_len]; input.extend_from_slice(&target_cleartext); // Determine the ci...
identifier_body
challenge13.rs
use aes::Aes128; use aes::{chunks_count, BLOCK_SIZE}; use crate::errors::*; use crate::prefix_suffix_oracles::Oracle; use crate::prefix_suffix_oracles::Oracle13; use super::challenge12::prefix_plus_suffix_length; use super::prefix_length; // The following function works under the single assumption that the target v...
// The following input is chosen in such a way that the cleartext in oracle looks as follows: // email=\0 ... \0 || \0 ...\0&uid=10&role= || user <- padding -> let (chunks_count, fill_len) = chunks_count(prefix_plus_suffix_length(&oracle)?); let mut ciphertext = oracle.encrypt(&vec![0; fill_len + "user...
.encrypt(&input)? .split_off(prefix_chunks_count * BLOCK_SIZE)[0..BLOCK_SIZE];
random_line_split
EventTrigger.ts
namespace AjaxFileJQuery.JQueryEventTrigger { 'use strict'; declare var $: any; export function send(option: IJQueryOption, xmlHttpRequest: IJQueryXHR): void { if ($.active++ === 0) { sendGlobalEvent(option, 'ajaxStart'); } sendGlobalEvent(option, 'ajaxSend', [xmlHttp...
$.event.trigger(eventName, parameters); }; };
return; }
conditional_block
EventTrigger.ts
namespace AjaxFileJQuery.JQueryEventTrigger { 'use strict'; declare var $: any; export function send(option: IJQueryOption, xmlHttpRequest: IJQueryXHR): void { if ($.active++ === 0) { sendGlobalEvent(option, 'ajaxStart'); } sendGlobalEvent(option, 'ajaxSend', [xmlHttp...
export function success(option: IJQueryOption, xmlHttpRequest: IJQueryXHR): void { sendGlobalEvent(option, 'ajaxSuccess', [xmlHttpRequest, option]); completed(option, xmlHttpRequest); }; function completed(option: IJQueryOption, xmlHttpRequest: IJQueryXHR): void { sendGlobalEvent(o...
sendGlobalEvent(option, 'ajaxError', [xmlHttpRequest, option, errorThrown]); completed(option, xmlHttpRequest); };
identifier_body
EventTrigger.ts
namespace AjaxFileJQuery.JQueryEventTrigger { 'use strict';
export function send(option: IJQueryOption, xmlHttpRequest: IJQueryXHR): void { if ($.active++ === 0) { sendGlobalEvent(option, 'ajaxStart'); } sendGlobalEvent(option, 'ajaxSend', [xmlHttpRequest, option]); }; export function error(option: IJQueryOption, xmlHttpRequest:...
declare var $: any;
random_line_split
EventTrigger.ts
namespace AjaxFileJQuery.JQueryEventTrigger { 'use strict'; declare var $: any; export function se
ption: IJQueryOption, xmlHttpRequest: IJQueryXHR): void { if ($.active++ === 0) { sendGlobalEvent(option, 'ajaxStart'); } sendGlobalEvent(option, 'ajaxSend', [xmlHttpRequest, option]); }; export function error(option: IJQueryOption, xmlHttpRequest: IJQueryXHR, errorThrown?:...
nd(o
identifier_name
svg.rs
use gio::MemoryInputStream; use glib::Bytes; use predicates::prelude::*; use predicates::reflection::{Case, Child, PredicateReflection, Product}; use std::cmp; use std::fmt; use librsvg::{CairoRenderer, Length, Loader, LoadingError, SvgHandle}; /// Checks that the variable of type [u8] can be parsed as a SVG file. #[...
(self: Self, width: Length, height: Length) -> DetailPredicate<Self> { DetailPredicate::<Self> { p: self, d: Detail::Size(Dimensions { w: width, h: height, }), } } } fn svg_from_bytes(data: &[u8]) -> Result<SvgHandle, LoadingError>...
with_size
identifier_name
svg.rs
use gio::MemoryInputStream; use glib::Bytes; use predicates::prelude::*; use predicates::reflection::{Case, Child, PredicateReflection, Product}; use std::cmp; use std::fmt; use librsvg::{CairoRenderer, Length, Loader, LoadingError, SvgHandle}; /// Checks that the variable of type [u8] can be parsed as a SVG file. #[...
fn find_case<'a>(&'a self, _expected: bool, data: &[u8]) -> Option<Case<'a>> { match svg_from_bytes(data) { Ok(_) => None, Err(e) => Some(Case::new(Some(self), false).add_product(Product::new("Error", e))), } } } impl PredicateReflection for SvgPredicate {} impl fmt::...
{ svg_from_bytes(data).is_ok() }
identifier_body
svg.rs
use gio::MemoryInputStream; use glib::Bytes; use predicates::prelude::*; use predicates::reflection::{Case, Child, PredicateReflection, Product}; use std::cmp; use std::fmt; use librsvg::{CairoRenderer, Length, Loader, LoadingError, SvgHandle}; /// Checks that the variable of type [u8] can be parsed as a SVG file. #[...
impl PredicateReflection for SvgPredicate {} impl fmt::Display for SvgPredicate { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "is an SVG") } } /// Extends a SVG Predicate by a check for its size #[derive(Debug)] pub struct DetailPredicate<SvgPredicate> { p: SvgPredicate, d...
random_line_split
places.js
'use strict'; var accessToken; const checkin = require('../functions/checkin'); const comment = require('../functions/comment'); module.exports = (router, foursquare, config) => { router.get('/api', function(req, res) { res.writeHead(303, { 'location': foursquare.getAuthClientRedirectUrl() }); res.end(); ...
}); }); router.get('/hello', function (req, res) { res.send('Hello World!') console.log('I received') }) router.get('/places', function (req, res) { var accessToken = accessToken; var lat = req.query.lat; var lng = req.query.lng; var near = null var cb = function(error, json) { var re...
{ accessToken = accessToken; res.redirect('/places?token='+accessToken); }
conditional_block
places.js
module.exports = (router, foursquare, config) => { router.get('/api', function(req, res) { res.writeHead(303, { 'location': foursquare.getAuthClientRedirectUrl() }); res.end(); }); router.get('/callback', function (req, res) { foursquare.getAccessToken({ code: req.query.code }, function (err...
'use strict'; var accessToken; const checkin = require('../functions/checkin'); const comment = require('../functions/comment');
random_line_split
edit.js
'use strict'; var async = require('async'); var validator = require('validator'); var _ = require('underscore'); var db = require('../database'); var topics = require('../topics'); var user = require('../user'); var privileges = require('../privileges'); var plugins = require('../plugins'); var cache = require('./cac...
var topicData = { tid: tid, cid: results.topic.cid, uid: postData.uid, mainPid: data.pid }; if (title) { topicData.title = title; topicData.slug = tid + '/' + (utils.slugify(title) || 'topic'); } topicData.thumb = data.thumb || ''; data.tags = data.tags || []; async.wa...
{ return callback(null, { tid: tid, cid: results.topic.cid, isMainPost: false, renamed: false }); }
conditional_block
edit.js
'use strict'; var async = require('async'); var validator = require('validator'); var _ = require('underscore'); var db = require('../database'); var topics = require('../topics'); var user = require('../user'); var privileges = require('../privileges'); var plugins = require('../plugins'); var cache = require('./cac...
(data, postData, callback) { var tid = postData.tid; var title = data.title ? data.title.trim() : ''; async.parallel({ topic: function (next) { topics.getTopicFields(tid, ['cid', 'title'], next); }, isMain: function (next) { Posts.isMain(data.pid, next); } }, function (err, results) { if...
editMainPost
identifier_name
edit.js
'use strict'; var async = require('async'); var validator = require('validator'); var _ = require('underscore'); var db = require('../database'); var topics = require('../topics'); var user = require('../user'); var privileges = require('../privileges'); var plugins = require('../plugins'); var cache = require('./cac...
function (_postData, next) { if (!_postData) { return next(new Error('[[error:no-post]]')); } postData = _postData; postData.content = data.content; postData.edited = Date.now(); postData.editor = data.uid; if (data.handle) { postData.handle = data.handle; } plugins.fir...
},
random_line_split
edit.js
'use strict'; var async = require('async'); var validator = require('validator'); var _ = require('underscore'); var db = require('../database'); var topics = require('../topics'); var user = require('../user'); var privileges = require('../privileges'); var plugins = require('../plugins'); var cache = require('./cac...
isMainPost: false, renamed: false }); } var topicData = { tid: tid, cid: results.topic.cid, uid: postData.uid, mainPid: data.pid }; if (title) { topicData.title = title; topicData.slug = tid + '/' + (utils.slugify(title) || 'topic'); } topicData.thumb = data.th...
{ var tid = postData.tid; var title = data.title ? data.title.trim() : ''; async.parallel({ topic: function (next) { topics.getTopicFields(tid, ['cid', 'title'], next); }, isMain: function (next) { Posts.isMain(data.pid, next); } }, function (err, results) { if (err) { return callbac...
identifier_body
widgets.py
""" Form widget classes """ from __future__ import absolute_import from django.conf import settings from django.forms.utils import flatatt from django.forms.widgets import CheckboxInput from django.urls import reverse from django.utils.encoding import force_text from django.utils.html import format_html from django.u...
if not (value is True or value is False or value is None or value == ''): # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_text(value) # Translators: link_start and link_end are HTML tags for a link to the terms of service. # platfo...
final_attrs['checked'] = 'checked'
conditional_block
widgets.py
""" Form widget classes """ from __future__ import absolute_import from django.conf import settings from django.forms.utils import flatatt from django.forms.widgets import CheckboxInput from django.urls import reverse
from django.utils.html import format_html from django.utils.translation import ugettext as _ from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.djangolib.markup import HTML, Text class TermsOfServiceCheckboxInput(CheckboxInput): """ Renders a checkbox with a...
from django.utils.encoding import force_text
random_line_split
widgets.py
""" Form widget classes """ from __future__ import absolute_import from django.conf import settings from django.forms.utils import flatatt from django.forms.widgets import CheckboxInput from django.urls import reverse from django.utils.encoding import force_text from django.utils.html import format_html from django.u...
(CheckboxInput): """ Renders a checkbox with a label linking to the terms of service. """ def render(self, name, value, attrs=None): extra_attrs = attrs.copy() extra_attrs.update({'type': 'checkbox', 'name': name}) final_attrs = self.build_attrs(self.attrs, extra_attrs=extra_attrs) ...
TermsOfServiceCheckboxInput
identifier_name
widgets.py
""" Form widget classes """ from __future__ import absolute_import from django.conf import settings from django.forms.utils import flatatt from django.forms.widgets import CheckboxInput from django.urls import reverse from django.utils.encoding import force_text from django.utils.html import format_html from django.u...
url=reverse('api_admin:api-tos') ), link_end=HTML('</a>'), ) html = HTML(u'<input{{}} /> <label class="tos-checkbox-label" for="{id}">{label}</label>').format( id=final_attrs['id'], label=label ) return format_html(html, fl...
""" Renders a checkbox with a label linking to the terms of service. """ def render(self, name, value, attrs=None): extra_attrs = attrs.copy() extra_attrs.update({'type': 'checkbox', 'name': name}) final_attrs = self.build_attrs(self.attrs, extra_attrs=extra_attrs) if self.check_te...
identifier_body
bfe_comments.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN. ## ## Invenio 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 ve...
user_info=bfo.user_info) return comments + reviews def escape_values(bfo): """ Called by BibFormat in order to check if output of this element should be escaped. """ return 0
""" Prints comments posted for the record. @param nbReviews: The max number of reviews to print @param nbComments: The max number of comments to print """ nb_reviews = nbReviews if nb_reviews.isdigit(): nb_reviews = int(nb_reviews) nb_comments = nbComments if nb_comments.isdigi...
identifier_body
bfe_comments.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN. ## ## Invenio 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 ve...
(comments, reviews) = get_first_comments_or_remarks(recID=bfo.recID, ln=bfo.lang, nb_comments=nb_comments, nb_reviews=nb_reviews, ...
nb_comments = int(nb_comments)
conditional_block
bfe_comments.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN. ##
## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU...
## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as
random_line_split
bfe_comments.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN. ## ## Invenio 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 ve...
(bfo, nbReviews='all', nbComments='all'): """ Prints comments posted for the record. @param nbReviews: The max number of reviews to print @param nbComments: The max number of comments to print """ nb_reviews = nbReviews if nb_reviews.isdigit(): nb_reviews = int(nb_reviews) nb_c...
format_element
identifier_name
roxor.rs
use std::env; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::process; const PREVIEW_LEN: usize = 50; #[derive(Debug, PartialEq)] struct Match { offset: usize, key: u8, preview: String, } fn main() { let args: Vec<String> = env::args().skip(1).collect(); if args.len() < ...
(ciphertext: &[u8], crib: &[u8]) -> Vec<Match> { let mut matches: Vec<Match> = Vec::new(); for (i, x) in ciphertext.iter().enumerate() { let mut old_key = x ^ crib[0]; let mut j = 1; while j < crib.len() && (i + j) < ciphertext.len() { let key = ciphertext[i + j] ^ crib[j]; ...
attack_cipher
identifier_name
roxor.rs
use std::env; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::process; const PREVIEW_LEN: usize = 50; #[derive(Debug, PartialEq)] struct Match { offset: usize, key: u8, preview: String, } fn main() { let args: Vec<String> = env::args().skip(1).collect(); if args.len() < ...
offset: i, key, preview, }); } } } matches } #[cfg(test)] mod tests { use super::{attack_cipher, Match}; struct Test { ciphertext: &'static [u8], crib: &'static [u8], matches: Vec<M...
{ let mut matches: Vec<Match> = Vec::new(); for (i, x) in ciphertext.iter().enumerate() { let mut old_key = x ^ crib[0]; let mut j = 1; while j < crib.len() && (i + j) < ciphertext.len() { let key = ciphertext[i + j] ^ crib[j]; if key != old_key { ...
identifier_body
roxor.rs
use std::env; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::process; const PREVIEW_LEN: usize = 50; #[derive(Debug, PartialEq)] struct Match { offset: usize, key: u8, preview: String, } fn main() { let args: Vec<String> = env::args().skip(1).collect(); if args.len() < ...
else { '.' }) .collect(); matches.push(Match { offset: i, key, preview, }); } } } matches } #[cfg(test)] mod tests { use super::{attack_cipher, Match}; struct Test { ...
{ x as char }
conditional_block
roxor.rs
use std::env; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::process; const PREVIEW_LEN: usize = 50; #[derive(Debug, PartialEq)] struct Match { offset: usize, key: u8, preview: String, } fn main() { let args: Vec<String> = env::args().skip(1).collect(); if args.len() < ...
ciphertext: b"needle in haystack", crib: b"needle", matches: vec![ Match { offset: 0, key: 0, preview: "needle in haystack".to_string() }, ], }, Test { ciphertext: b"a needle, another needle", ...
}, Test {
random_line_split
deep_pytorch.py
_handle = input_handle def add_handles(self, model, forward_handle, backward_handle): """ Add handles to all non-container layers in the model. Recursively for non-container layers """ handles_list = [] model_children = list(model.children()) if model_childre...
else: for idx, x in enumerate(X): grad = torch.autograd.grad(selected, x, retain_graph=True if idx + 1 < len(X) else None, allow_unused=True)[0] if grad is not None: ...
interim_inputs = self.layer.target_input for idx, input in enumerate(interim_inputs): grad = torch.autograd.grad(selected, input, retain_graph=True if idx + 1 < len(interim_inputs) else None, allow_unused=T...
conditional_block
deep_pytorch.py
X = [X] else: assert type(X) == list, "Expected a list of model inputs!" X = [x.detach().to(self.device) for x in X] if ranked_outputs is not None and self.multi_output: with torch.no_grad(): model_output_values = self.model(*X) # rank and d...
"""No change made to gradients.""" return None
identifier_body
deep_pytorch.py
_handle = input_handle def add_handles(self, model, forward_handle, backward_handle): """ Add handles to all non-container layers in the model. Recursively for non-container layers """ handles_list = [] model_children = list(model.children()) if model_childre...
(self, idx, inputs): self.model.zero_grad() X = [x.requires_grad_() for x in inputs] outputs = self.model(*X) selected = [val for val in outputs[:, idx]] grads = [] if self.interim: interim_inputs = self.layer.target_input for idx, input in enumera...
gradient
identifier_name
deep_pytorch.py
_handle, backward_handle)) else: # leaves handles_list.append(model.register_forward_hook(forward_handle)) handles_list.append(model.register_backward_hook(backward_handle)) return handles_list def remove_attributes(self, model): """ Removes the x and y attr...
'MaxPool1d': torch.nn.functional.max_unpool1d, 'MaxPool2d': torch.nn.functional.max_unpool2d,
random_line_split
timescales-plot.py
"""Plot implied timescales vs lagtime {{header}} """ # ? include "plot_header.template" # ? from "plot_macros.template" import xdg_open with context import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt sns.set_style('ticks') colors = sns.color_palette() ## Load timescal...
xmin, xmax = ax.get_xlim() xx = np.linspace(xmin, xmax) ax.plot(xx, xx, color=colors[2], label='$y=x$') ax.legend(loc='best', fontsize=14) ax.set_xlabel('Lag Time / todo:units', fontsize=18) ax.set_ylabel('Implied Timescales / todo:units', fontsize=18) ax.set_xscale('log') ax.set_yscal...
ax.scatter(timescales['lag_time'], timescales['timescale_{}'.format(i)], s=50, c=colors[0], label=None, # pandas be interfering )
conditional_block
timescales-plot.py
"""Plot implied timescales vs lagtime {{header}} """ # ? include "plot_header.template" # ? from "plot_macros.template" import xdg_open with context import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt sns.set_style('ticks') colors = sns.color_palette() ## Load timescal...
# {{xdg_open('percent-trimmed.pdf')}}
fig.savefig('percent-trimmed.pdf')
random_line_split
timescales-plot.py
"""Plot implied timescales vs lagtime {{header}} """ # ? include "plot_header.template" # ? from "plot_macros.template" import xdg_open with context import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt sns.set_style('ticks') colors = sns.color_palette() ## Load timescal...
(ax): ax.plot(timescales['lag_time'], timescales['percent_retained'], 'o-', label=None, # pandas be interfering ) ax.axhline(100, color='k', ls='--', label='100%') ax.legend(loc='best', fontsize=14) ax.set_xlabel('Lag Time / todo:units', fontsize=18) ...
plot_trimmed
identifier_name
timescales-plot.py
"""Plot implied timescales vs lagtime {{header}} """ # ? include "plot_header.template" # ? from "plot_macros.template" import xdg_open with context import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt sns.set_style('ticks') colors = sns.color_palette() ## Load timescal...
## Percent trimmed vs lagtime def plot_trimmed(ax): ax.plot(timescales['lag_time'], timescales['percent_retained'], 'o-', label=None, # pandas be interfering ) ax.axhline(100, color='k', ls='--', label='100%') ax.legend(loc='best', fontsize=14) ax.set_x...
for i in range(n_timescales): ax.scatter(timescales['lag_time'], timescales['timescale_{}'.format(i)], s=50, c=colors[0], label=None, # pandas be interfering ) xmin, xmax = ax.get_xlim() xx = np.linspace(xmin, xmax) ax.plo...
identifier_body
hw5_1.py
from numpy import any, array, array_str, concatenate, dot, intersect1d from numpy import nonzero, ravel, setdiff1d, zeros from numpy.linalg import lstsq, norm def active_constraints(A, b, x): """Return a set of active constraints """ dx = b - dot(A, x) if any(dx > 0): raise ValueError('x is inf...
(G, f, A, b, x_0=None, max_iter=1e6, tol=1e-4, verbose=True): """Solve convex QP via active set method min 0.5 * x^T * G * x + f^T * x s.t. A * x >= b """ # Compute a feasible starting point if x_0 is None: x = get_starting_point(A, b) else: x = x_0.copy() m, n, k = x.s...
quadprog
identifier_name
hw5_1.py
from numpy import any, array, array_str, concatenate, dot, intersect1d from numpy import nonzero, ravel, setdiff1d, zeros from numpy.linalg import lstsq, norm def active_constraints(A, b, x): """Return a set of active constraints """ dx = b - dot(A, x) if any(dx > 0): raise ValueError('x is inf...
p = solve_qp_eq(G, f, A[W, :], b[W], x) if norm(p) <= tol * m**2: lmbda = get_dual_vars(G, f, A, x, W) if all(lmbda >= 0): # Global minimizer was found if verbose: print 'Optimization finished\n' break else: ...
print 'Iter: {0}\tObj: {1}\tW: {2:5}\tx: {3}'.format(k, array_str(ravel(f_obj), precision=3), array_str(W), array_str(ravel(x), precision=3))
conditional_block
hw5_1.py
from numpy import any, array, array_str, concatenate, dot, intersect1d from numpy import nonzero, ravel, setdiff1d, zeros from numpy.linalg import lstsq, norm def active_constraints(A, b, x): """Return a set of active constraints """ dx = b - dot(A, x) if any(dx > 0): raise ValueError('x is inf...
mu, res, rank, s = lstsq(A[W, :].T, dot(G, x) + f) return mu def quadprog(G, f, A, b, x_0=None, max_iter=1e6, tol=1e-4, verbose=True): """Solve convex QP via active set method min 0.5 * x^T * G * x + f^T * x s.t. A * x >= b """ # Compute a feasible starting point if x_0 is None: ...
raise NotImplementedError('You need to provide x_0') def get_dual_vars(G, f, A, x, W): """Compute lagrange multiplies for W"""
random_line_split
hw5_1.py
from numpy import any, array, array_str, concatenate, dot, intersect1d from numpy import nonzero, ravel, setdiff1d, zeros from numpy.linalg import lstsq, norm def active_constraints(A, b, x): """Return a set of active constraints """ dx = b - dot(A, x) if any(dx > 0): raise ValueError('x is inf...
def step_size(A, b, x, p, W): """Compute minimum step size such that x + p is still in the polyhedron""" num, den, alpha_min, block = b - dot(A, x), dot(A, p), 1, None alpha = num / den J = intersect1d(setdiff1d(range(A.shape[0]), W, assume_unique=True), nonzero(den < 0)[0]) if...
"""Solve QP with equality constraint""" m, n = x.size, C.shape[0] A = concatenate((concatenate((G, C.T), axis=1), concatenate((C, zeros((n, n))), axis=1)), axis=0) b = concatenate((f + dot(G, x), dot(C, x) - d), axis=0) lmbda, res, rank, s = lstsq(A, b) return -lmbda[:m, :]
identifier_body
wizard.py
", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, T...
If xpub_hot is None, request N cosigning master xpub keys, xprv keys, or seeds in order to perform wallet restore.""" raise NotImplementedError def choose_server(self, network): """Choose a server if one is not set in the config anyway.""" raise NotImplementedError def ...
random_line_split
wizard.py
", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, T...
(self, device_text, restore=True): """Request a passphrase for a wallet from the given device and confirm it. restore is True if restoring a wallet. Should return a unicode string.""" raise NotImplementedError def request_password(self, msg=None): """Request the user enter...
request_passphrase
identifier_name
wizard.py
", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, T...
def request_seed(self, msg, is_valid=None): """Request the user enter a seed. Returns the seed the user entered. is_valid is a function that returns True if a seed is valid, for dynamic feedback. If not provided, Wallet.is_any is used.""" raise NotImplementedError def reques...
"""Request the user enter a new password and confirm it. Return the password or None for no password.""" raise NotImplementedError
identifier_body
wizard.py
", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, T...
# Plugin (two-factor or hardware) wallet = self.construct_wallet(storage, wallet_type) return wallet.plugin.on_restore_wallet(wallet, self) def restore_standard_wallet(self, storage): text = self.request_seed(MSG_ENTER_ANYTHING) need_password = Wallet.should_encrypt(text) ...
return self.restore_multisig_wallet(storage, wallet_type)
conditional_block
160 Intersection of Two Linked Lists.py
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ p1 = headA...
return p1 """ If there is an intersection A1 -> A2 -> C1 B1 -> C1 THEN: A1 -> A2 -> C1 -> None -> B1 ->C1 B1 -> C1 -> None-> A1 -> A2 ->C1 if thre is no intersection A1 -> A2 -> C1 B1 THEN: A1 -> A2 -> C1 -> B1 -> None B1 -> A1 -> A2 -> C1 -> None Here, p1 == p2 == None, break. then return None. """
p1 = p1.next p2 = p2.next if p1 is p2: return p1 if not p1: p1 = headB if not p2: p2 = headA
conditional_block
160 Intersection of Two Linked Lists.py
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def
(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ p1 = headA p2 = headB if not p1 or not p2: return None while p1 and p2 and (p1 is not p2): p1 = p1.next p2 = p2.next if...
getIntersectionNode
identifier_name
160 Intersection of Two Linked Lists.py
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ p1 = headA...
THEN: A1 -> A2 -> C1 -> None -> B1 ->C1 B1 -> C1 -> None-> A1 -> A2 ->C1 if thre is no intersection A1 -> A2 -> C1 B1 THEN: A1 -> A2 -> C1 -> B1 -> None B1 -> A1 -> A2 -> C1 -> None Here, p1 == p2 == None, break. then return None. """
random_line_split
160 Intersection of Two Linked Lists.py
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object):
return p1 """ If there is an intersection A1 -> A2 -> C1 B1 -> C1 THEN: A1 -> A2 -> C1 -> None -> B1 ->C1 B1 -> C1 -> None-> A1 -> A2 ->C1 if thre is no intersection A1 -> A2 -> C1 B1 THEN: A1 -> A2 -> C1 -> B1 -> None B1 -> A1 -> A2 -> C1 -> None Here, p1 == p2 == None, break. then return None. """
def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ p1 = headA p2 = headB if not p1 or not p2: return None while p1 and p2 and (p1 is not p2): p1 = p1.next p2 = p2.next ...
identifier_body
index.js
var assign = require('object-assign'); module.exports = { name: 'ember-cli-cloudinary-images', config: function(environment, appConfig) { var CLOUDINARY = appConfig.CLOUDINARY || {}; return { CLOUDINARY: assign({ /** For future support */ API_KEY: '', /** The user in Cloudi...
/* jshint node: true */ 'use strict';
random_line_split
parser_any_macro.rs
// from src/libsyntax/ext/tt/macro_rules.rs use std::cell::RefCell; use syntax::parse::parser::Parser; use syntax::parse::token; use syntax::ast; use syntax::ptr::P; use syntax::ext::base::MacResult; use syntax::util::small_vector::SmallVector; pub struct ParserAnyMacro<'a> { parser: RefCell<Parser<'a>>, } impl<...
/// Make sure we don't have any tokens left to parse, so we don't /// silently drop anything. `allow_semi` is so that "optional" /// semicolons at the end of normal expressions aren't complained /// about e.g. the semicolon in `macro_rules! kapow { () => { /// panic!(); } }` doesn't get picked up b...
{ ParserAnyMacro { parser: RefCell::new(p) } }
identifier_body
parser_any_macro.rs
// from src/libsyntax/ext/tt/macro_rules.rs use std::cell::RefCell;
use syntax::parse::token; use syntax::ast; use syntax::ptr::P; use syntax::ext::base::MacResult; use syntax::util::small_vector::SmallVector; pub struct ParserAnyMacro<'a> { parser: RefCell<Parser<'a>>, } impl<'a> ParserAnyMacro<'a> { pub fn new(p: Parser<'a>) -> ParserAnyMacro<'a> { ParserAnyMacro { ...
use syntax::parse::parser::Parser;
random_line_split
parser_any_macro.rs
// from src/libsyntax/ext/tt/macro_rules.rs use std::cell::RefCell; use syntax::parse::parser::Parser; use syntax::parse::token; use syntax::ast; use syntax::ptr::P; use syntax::ext::base::MacResult; use syntax::util::small_vector::SmallVector; pub struct ParserAnyMacro<'a> { parser: RefCell<Parser<'a>>, } impl<...
(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Item>>> { let mut ret = SmallVector::zero(); while let Some(item) = self.parser.borrow_mut().parse_item() { ret.push(item); } self.ensure_complete_parse(false); Some(ret) } fn make_impl_items(self: ...
make_items
identifier_name
loop_def.rs
// loop operation // store temp values for loop name and refill addresses use super::ItemID; use super::vm_code::CodeCollection; pub struct Loop { pub name: Option<String>, pub continue_addr: usize, pub break_addrs: Vec<usize>, } pub struct LoopCollection { loops: Vec<Loop>, pub r...
} _ => (), } } return None; } }
{ lp.break_addrs.push(break_addr); return Some(()); }
conditional_block
loop_def.rs
// loop operation // store temp values for loop name and refill addresses use super::ItemID; use super::vm_code::CodeCollection; pub struct Loop { pub name: Option<String>, pub continue_addr: usize, pub break_addrs: Vec<usize>, } pub struct LoopCollection { loops: Vec<Loop>,
pub ret_type: ItemID, // so it is not only loop collection but a jump statement context storage } impl LoopCollection { pub fn new() -> LoopCollection { LoopCollection{ loops: Vec::new(), ret_type: ItemID::new_invalid(), } } pub fn push_loop(&mut...
random_line_split
loop_def.rs
// loop operation // store temp values for loop name and refill addresses use super::ItemID; use super::vm_code::CodeCollection; pub struct Loop { pub name: Option<String>, pub continue_addr: usize, pub break_addrs: Vec<usize>, } pub struct LoopCollection { loops: Vec<Loop>, pub r...
() -> LoopCollection { LoopCollection{ loops: Vec::new(), ret_type: ItemID::new_invalid(), } } pub fn push_loop(&mut self, name: Option<String>, continue_addr: usize) { self.loops.push(Loop{ name: name, continue_addr: continue_addr, break_addrs: Vec:...
new
identifier_name
loop_def.rs
// loop operation // store temp values for loop name and refill addresses use super::ItemID; use super::vm_code::CodeCollection; pub struct Loop { pub name: Option<String>, pub continue_addr: usize, pub break_addrs: Vec<usize>, } pub struct LoopCollection { loops: Vec<Loop>, pub r...
// Panic on empty contents pub fn pop_and_refill(&mut self, refill_adder: usize, codes: &mut CodeCollection) { let last = self.loops.pop().unwrap(); for break_addr in last.break_addrs { codes.refill_addr(break_addr, refill_adder); } } pub fn get_last_loop_c...
{ self.loops.push(Loop{ name: name, continue_addr: continue_addr, break_addrs: Vec::new() }) }
identifier_body
cache.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/. */ use std::collections::HashMap; use std::collections::hash_map::{Occupied, Vacant}; use rand::Rng; use std::hash::{...
cache.insert(1, Cell::new("one")); assert!(cache.find(&1).is_some()); assert!(cache.find(&2).is_none()); cache.find_or_create(&2, |_v| { Cell::new("two") }); assert!(cache.find(&1).is_some()); assert!(cache.find(&2).is_some()); } pub struct LRUCache<K, V> { entries: Vec<(K, V)>, cache...
random_line_split
cache.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/. */ use std::collections::HashMap; use std::collections::hash_map::{Occupied, Vacant}; use rand::Rng; use std::hash::{...
} impl<K: Clone + PartialEq, V: Clone> Cache<K,V> for LRUCache<K,V> { fn insert(&mut self, key: K, val: V) { if self.entries.len() == self.cache_size { self.entries.remove(0); } self.entries.push((key, val)); } fn find(&mut self, key: &K) -> Option<V> { match s...
{ self.entries.iter() }
identifier_body
cache.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/. */ use std::collections::HashMap; use std::collections::hash_map::{Occupied, Vacant}; use rand::Rng; use std::hash::{...
(&mut self) { self.entries.clear(); } } impl<K,V> HashCache<K,V> where K: Clone + PartialEq + Eq + Hash, V: Clone { pub fn find_equiv<'a,Sized? Q>(&'a self, key: &Q) -> Option<&'a V> where Q: Hash + Equiv<K> { self.entries.find_equiv(key) } } #[test] fn test_hashcache() { let mut cach...
evict_all
identifier_name
redis.py
from stream_framework.tests.feeds.base import TestBaseFeed, implementation from stream_framework.feeds.redis import RedisFeed from stream_framework.activity import Activity from stream_framework.utils import datetime_to_epoch class CustomActivity(Activity): @property def serialization_id(self): ''' ...
milliseconds = str(int(datetime_to_epoch(self.time) * 1000)) # shorter than the default version serialization_id_str = '%s%0.2d%0.2d' % ( milliseconds, self.object_id % 100, self.verb.id) serialization_id = int(serialization_id_str) return serialization_id class ...
raise TypeError('Cant serialize activities without a time')
conditional_block
redis.py
from stream_framework.tests.feeds.base import TestBaseFeed, implementation from stream_framework.feeds.redis import RedisFeed from stream_framework.activity import Activity from stream_framework.utils import datetime_to_epoch class CustomActivity(Activity): @property def serialization_id(self): ''' ...
class TestRedisFeed(TestBaseFeed): feed_cls = RedisFeed class TestCustomRedisFeed(TestBaseFeed): ''' Test if the option to customize the activity class works without troubles ''' feed_cls = RedisCustom activity_class = CustomActivity @implementation def test_custom_activity(self):...
activity_class = CustomActivity
identifier_body
redis.py
from stream_framework.tests.feeds.base import TestBaseFeed, implementation from stream_framework.feeds.redis import RedisFeed from stream_framework.activity import Activity from stream_framework.utils import datetime_to_epoch class CustomActivity(Activity): @property def serialization_id(self): ''' ...
assert type(self.activity) == type(self.test_feed[0][0]) # make sure nothing is wrong with the activity storage
random_line_split
redis.py
from stream_framework.tests.feeds.base import TestBaseFeed, implementation from stream_framework.feeds.redis import RedisFeed from stream_framework.activity import Activity from stream_framework.utils import datetime_to_epoch class CustomActivity(Activity): @property def serialization_id(self): ''' ...
(self): assert self.test_feed.count() == 0 self.feed_cls.insert_activity( self.activity ) self.test_feed.add(self.activity) assert self.test_feed.count() == 1 assert self.activity == self.test_feed[:10][0] assert type(self.activity) == type(self.test_f...
test_custom_activity
identifier_name
connection.py
from stormed.util import add_method, AmqpError, logger from stormed.serialization import table2str from stormed.heartbeat import HeartbeatMonitor from stormed.frame import status from stormed.method.codegen import id2class from stormed.method.constant import id2constant from stormed.method.codegen.connection import * ...
response = table2str(dict(LOGIN = conn.username, PASSWORD = conn.password)) client_properties = {'client': 'stormed-amqp'} start_ok = StartOk(client_properties=client_properties, mechanism='AMQPLAIN', response=response, locale=...
raise AmqpError("'en_US' not in locales")
conditional_block
connection.py
from stormed.util import add_method, AmqpError, logger from stormed.serialization import table2str from stormed.heartbeat import HeartbeatMonitor from stormed.frame import status from stormed.method.codegen import id2class from stormed.method.constant import id2constant from stormed.method.codegen.connection import * ...
(self, reply_code, reply_text, method): self.reply_code = reply_code self.reply_text = reply_text self.method = method @add_method(Close) def handle(self, conn): try: mod = id2class[self.class_id] method = getattr(mod, 'id2method')[self.method_id] except: method ...
__init__
identifier_name
connection.py
from stormed.util import add_method, AmqpError, logger from stormed.serialization import table2str from stormed.heartbeat import HeartbeatMonitor from stormed.frame import status from stormed.method.codegen import id2class from stormed.method.constant import id2constant from stormed.method.codegen.connection import * ...
conn.write_method(_open) @add_method(OpenOk) def handle(self, conn): conn.status = status.OPENED if conn.heartbeat: HeartbeatMonitor(conn).start() try: conn.on_connect() except Exception: logger.error('ERROR in on_connect() callback', exc_info=True) @add_method(CloseOk) def...
random_line_split
connection.py
from stormed.util import add_method, AmqpError, logger from stormed.serialization import table2str from stormed.heartbeat import HeartbeatMonitor from stormed.frame import status from stormed.method.codegen import id2class from stormed.method.constant import id2constant from stormed.method.codegen.connection import * ...
try: mod = id2class[self.class_id] method = getattr(mod, 'id2method')[self.method_id] except: method = None conn.reset() error_code = id2constant.get(self.reply_code, '') logger.warn('Connection Hard Error. code=%r. %s', error_code, ...
identifier_body
ai_to_pajek.py
#!/usr/bin/env python from util.misc import open_file, Benchmark from util.PajekFactory import PajekFactory import ujson if __name__ == "__main__":
pjk.write(f)
import argparse parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from JSON") parser.add_argument('outfile') parser.add_argument('--temp-dir', help="Directory to store temporary files in", default=None) parser.add_argument('infile', nargs='+') arguments = parser.parse_args() ...
conditional_block
ai_to_pajek.py
#!/usr/bin/env python from util.misc import open_file, Benchmark
from util.PajekFactory import PajekFactory import ujson if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from JSON") parser.add_argument('outfile') parser.add_argument('--temp-dir', help="Directory to store temporary files in", default...
random_line_split
init-res-into-things.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ x: r } #[unsafe_destructor] impl Drop for r { fn drop(&mut self) { self.i.set(self.i.get() + 1) } } fn r(i: Gc<Cell<int>>) -> r { r { i: i } } fn test_box() { let i = box(GC) Cell::new(0i); { let _a = box(GC) r(i); } assert_eq!(i.get(), 1); } fn test_rec() ...
Box
identifier_name
init-res-into-things.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 test_tag() { enum t { t0(r), } let i = box(GC) Cell::new(0i); { let _a = t0(r(i)); } assert_eq!(i.get(), 1); } fn test_tup() { let i = box(GC) Cell::new(0i); { let _a = (r(i), 0i); } assert_eq!(i.get(), 1); } fn test_unique() { let i = box(GC) C...
} assert_eq!(i.get(), 1); }
random_line_split
nibbleslice.rs
2,3,4,5 /// let n2 = NibbleSlice::new(d2); // 3,4,5,0,1,2 /// let n3 = NibbleSlice::new_offset(d3, 1); // 0,1,2 /// assert!(n1 > n3); // 0,1,2,... > 0,1,2 /// assert!(n1 < n2); // 0,... < 3,... /// assert!(n2.mid(3) == n3); // 0,1,2 == 0,1,2 /// assert!(n1.starts_with(&n3)); /// assert_e...
+ if is_leaf { 0x20 } else { 0 }); while i < l { r.push(self.at(i) * 16 + self.at(i + 1)); i += 2; } r } } impl<'a> PartialEq for NibbleSlice<'a> { fn eq(&self, them: &Self) -> bool { self.len() == them.len() && self.starts_with(them) } } impl<'a> PartialOrd for NibbleSlice<'a> { fn partial_cmp(&se...
{ 0 }
conditional_block