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
db.rs
_entry(&mut conn, &request.qid, &f_name, &f_r_name).unwrap(); let (fid, ref retr_name, ref retr_r_name) = get_files(&mut conn, &request.qid)[0]; assert_eq!(retr_name, f_name); assert_eq!(retr_r_name, f_r_name); assert_eq!(n_fid, fid); assert!(set_file_valid_flag(&mut conn, &fid, ...
{ let (conf, pool) = connect(); let mut conn = pool.get_conn().unwrap(); let request = create_request(false, &conf); setup(&mut conn); let id = insert_query_core(&request, &mut conn).unwrap(); let new_error = String::from("asd"); super::add_query_error(&mut conn...
identifier_body
db.rs
mut row: Row; { row = match db_conn.query_first( "SELECT queries.qid,url,quality,`split`,`from`,`to`,uid,`type` FROM queries \ JOIN querydetails ON queries.qid = querydetails.qid \ LEFT JOIN playlists ON queries.qid = playlists.qid \ WHERE querydetails.cod...
get_error
identifier_name
LinkDialog.js.uncompressed.js
}</a>", // tag: [protected] String // Tag used for the link type. tag: "a", // _hostRxp [private] RegExp // Regular expression used to validate url fragments (ip address, hostname, etc) _hostRxp: new RegExp("^((([^\\[:]+):)?([^@]+)@)?(\\[([^\\]]+)\\]|([^\\[:]*))(:([0-9]+))?$"), // _userAtRxp [private] RegE...
this._delayedCheck = setTimeout(function(){ fixupUrl(url); }, 250); }, _connectTagEvents: function(){ // summary: // Over-ridable function that connects tag specific events. this.editor.onLoadDeferred.addCallback(lang.hitch(this, function(){ this.connect(this.editor.editNode, "ondblclick", this._on...
{ clearTimeout(this._delayedCheck); this._delayedCheck = null; }
conditional_block
LinkDialog.js.uncompressed.js
textInput}</a>", // tag: [protected] String // Tag used for the link type. tag: "a", // _hostRxp [private] RegExp // Regular expression used to validate url fragments (ip address, hostname, etc) _hostRxp: new RegExp("^((([^\\[:]+):)?([^@]+)@)?(\\[([^\\]]+)\\]|([^\\[:]*))(:([0-9]+))?$"), // _userAtRxp [priv...
// not present, try and guess if the input url is relative or not, and if // not, append http:// to it. Also validates other fields as determined by // the internal _isValid function. var self = this; var url = this._urlInput.get("value"); var fixupUrl = function(url){ var appendHttp = false; var ...
random_line_split
index.ts
/* * The MIT License (MIT) * * Copyright (c) 2019 Looker Data Sciences, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rig...
* 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, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SO...
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
random_line_split
context.js
function timeline(fps, state){ timeline.base.call(this, state); this._listeners = $.observer(); this._ticks = 0; this.fps(fps || 30); } timeline.prototype = { fps: function(fps){ this._interval = 1000/fps; return this.property("fps", fps); }, interval: function(){ ...
this._listeners.add(f, scope, _id); return this; }, remove: function(id){ this._listeners.remove(id); return this; }, clear: function(){ this._listeners.clear(); return this; }, tick: function(){ this._ticks++; return this; } } $.Class.extend(timeline, $.abs...
stall = function() { if(!me._ticks % w == 0) return; func(); f = func; }, f = (!wait) ? func : stall;
random_line_split
context.js
function timeline(fps, state)
timeline.prototype = { fps: function(fps){ this._interval = 1000/fps; return this.property("fps", fps); }, interval: function(){ return this.get("interval"); }, listeners: function(){ return this.get("listeners"); }, ticks: function(){ return this.get("ticks"); }, start...
{ timeline.base.call(this, state); this._listeners = $.observer(); this._ticks = 0; this.fps(fps || 30); }
identifier_body
context.js
function
(fps, state){ timeline.base.call(this, state); this._listeners = $.observer(); this._ticks = 0; this.fps(fps || 30); } timeline.prototype = { fps: function(fps){ this._interval = 1000/fps; return this.property("fps", fps); }, interval: function(){ return this.get("...
timeline
identifier_name
cached_crop.ts
import axios, { AxiosResponse } from "axios"; import { Dictionary } from "farmbot"; import { isObject, isUndefined } from "lodash"; import { OFCropAttrs, OFCropResponse, svgToUrl } from "./icons"; import { ExternalUrl } from "../external_urls"; export type OFIcon = Readonly<OFCropAttrs>; type IconDictionary = Dictiona...
/** PROBLEM: HTTP requests get fired too fast. If you have 10 garlic plants, * and the garlic icon is not cached locally, and you try to render 10 garlic * icons in the first 100ms, and HTTP requests take more than 100ms, you will * end up performing 10 HTTP requests at application start time. Not very * efficien...
{ const dictionary = getAllIconsFromCache(); dictionary[icon.slug] = icon; localStorage.setItem(STORAGE_KEY, JSON.stringify(dictionary)); }
identifier_body
cached_crop.ts
import axios, { AxiosResponse } from "axios"; import { Dictionary } from "farmbot"; import { isObject, isUndefined } from "lodash"; import { OFCropAttrs, OFCropResponse, svgToUrl } from "./icons"; import { ExternalUrl } from "../external_urls"; export type OFIcon = Readonly<OFCropAttrs>; type IconDictionary = Dictiona...
(slug: string): Promise<OFIcon> { return localStorageIconFetch(slug) || HTTPIconFetch(slug); } export const maybeGetCachedPlantIcon = ( slug: string | undefined, target: React.SyntheticEvent<HTMLImageElement>["currentTarget"], cb: (icon: string) => void) => { slug && cachedCrop(slug) .then(crop => { ...
cachedCrop
identifier_name
cached_crop.ts
import axios, { AxiosResponse } from "axios"; import { Dictionary } from "farmbot"; import { isObject, isUndefined } from "lodash"; import { OFCropAttrs, OFCropResponse, svgToUrl } from "./icons"; import { ExternalUrl } from "../external_urls"; export type OFIcon = Readonly<OFCropAttrs>; type IconDictionary = Dictiona...
}; export const setImgSrc = ( target: React.SyntheticEvent<HTMLImageElement>["currentTarget"], icon: string) => { if (icon !== target.getAttribute("src")) { target.setAttribute("src", icon); } };
random_line_split
cached_crop.ts
import axios, { AxiosResponse } from "axios"; import { Dictionary } from "farmbot"; import { isObject, isUndefined } from "lodash"; import { OFCropAttrs, OFCropResponse, svgToUrl } from "./icons"; import { ExternalUrl } from "../external_urls"; export type OFIcon = Readonly<OFCropAttrs>; type IconDictionary = Dictiona...
};
{ target.setAttribute("src", icon); }
conditional_block
DataStoreInit.py
#!/usr/bin/env python from pymongo import MongoClient import pymongo HOST = "wfSciwoncWiki:enw1989@172.31.2.76:27001/?authSource=admin" c = MongoClient('mongodb://'+HOST) dbname = "wiki" sessions = "sessions" contributors = "contributors" user_sessions = "user_sessions" top_sessions = "top_sessions" c[dbname]....
user_sessions_col.create_index([("_id.filepath", pymongo.ASCENDING),("_id.numline", pymongo.ASCENDING)]) top_sessions_col.create_index([("_id.filepath", pymongo.ASCENDING),("_id.numline", pymongo.ASCENDING)])
#sessions_col.create_index([("_id.filepath", pymongo.ASCENDING),("_id.numline", pymongo.ASCENDING)]) contributors_col.create_index([("_id.filepath", pymongo.ASCENDING),("_id.numline", pymongo.ASCENDING)])
random_line_split
js-signals.d.ts
// Type definitions for JS-Signals // Project: http://millermedeiros.github.io/js-signals/ // Definitions by: Diullei Gomes <https://github.com/diullei> // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module "signals" { var signals: SignalWrapper; export = signals; } interface Signa...
/** * Signals Version Number */ VERSION: string; /** * Add a listener to the signal. * * @param listener Signal handler function. * @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function). ...
* execute listener during add()/addOnce() if Signal was already dispatched before. */ memorize: boolean;
random_line_split
tests.rs
extern crate arrayvec; use arrayvec::ArrayVec; use std::mem; #[test] fn test_simple() { use std::ops::Add; let mut vec: ArrayVec<[Vec<i32>; 3]> = ArrayVec::new(); vec.push(vec![1, 2, 3, 4]); vec.push(vec![10]); vec.push(vec![-1, 13, -2]); for elt in &vec { assert_eq!(elt.iter().fol...
() { const N: usize = 4096; let mut vec: ArrayVec<[_; N]> = ArrayVec::new(); for _ in 0..N { assert!(vec.push(1u8).is_none()); } assert!(vec.push(0).is_some()); assert_eq!(vec.len(), N); } #[test] fn test_iter() { let mut iter = ArrayVec::from([1, 2, 3]).into_iter(); assert_eq!(...
test_u16_index
identifier_name
tests.rs
extern crate arrayvec; use arrayvec::ArrayVec; use std::mem; #[test] fn test_simple() { use std::ops::Add; let mut vec: ArrayVec<[Vec<i32>; 3]> = ArrayVec::new(); vec.push(vec![1, 2, 3, 4]); vec.push(vec![10]); vec.push(vec![-1, 13, -2]); for elt in &vec { assert_eq!(elt.iter().fol...
fn test_is_send_sync() { let data = ArrayVec::<[Vec<i32>; 5]>::new(); &data as &Send; &data as &Sync; } #[test] fn test_compact_size() { // Future rust will kill these drop flags! // 4 elements size + 1 len + 1 enum tag + [1 drop flag] type ByteArray = ArrayVec<[u8; 4]>; println!("{}", mem:...
assert_eq!(&array[..], &[0, 1, 2, 3, 4]); } #[test]
random_line_split
tests.rs
extern crate arrayvec; use arrayvec::ArrayVec; use std::mem; #[test] fn test_simple() { use std::ops::Add; let mut vec: ArrayVec<[Vec<i32>; 3]> = ArrayVec::new(); vec.push(vec![1, 2, 3, 4]); vec.push(vec![10]); vec.push(vec![-1, 13, -2]); for elt in &vec { assert_eq!(elt.iter().fol...
#[test] fn test_insert() { let mut v = ArrayVec::from([]); assert_eq!(v.push(1), Some(1)); assert_eq!(v.insert(0, 1), Some(1)); let mut v = ArrayVec::<[_; 3]>::new(); v.insert(0, 0); v.insert(1, 1); v.insert(2, 2); v.insert(3, 3); assert_eq!(&v[..], &[0, 1, 2]); v.insert(1, 9)...
{ let mut v = ArrayVec::from([0; 8]); v.pop(); v.drain(0..8); }
identifier_body
exposure.rs
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by app...
out.rgb = convert_uchar3(clamp(convert_int3(t * bright), 0, 255)); return out; }
uchar4 RS_KERNEL exposure(uchar4 in) { uchar4 out = {0, 0, 0, 255}; float3 t = convert_float3(in.rgb);
random_line_split
playlist-metadata-widget.service.ts
import { Injectable, OnDestroy } from '@angular/core'; import { KalturaMultiRequest } from 'kaltura-ngx-client'; import { PlaylistWidget } from '../playlist-widget'; import { KalturaPlaylist } from 'kaltura-ngx-client'; import { Observable } from 'rxjs'; import { FormBuilder, FormGroup, Validators } from '@angular/form...
}, err => { observer.error(err); } ); return () => { console.log('entryMetadataHandler.searchTags(): cancelled'); requestSubscription.unsubscribe(); } }); } }
random_line_split
playlist-metadata-widget.service.ts
import { Injectable, OnDestroy } from '@angular/core'; import { KalturaMultiRequest } from 'kaltura-ngx-client'; import { PlaylistWidget } from '../playlist-widget'; import { KalturaPlaylist } from 'kaltura-ngx-client'; import { Observable } from 'rxjs'; import { FormBuilder, FormGroup, Validators } from '@angular/form...
(private _formBuilder: FormBuilder, private _permissionsService: KMCPermissionsService, private _kalturaServerClient: KalturaClient, logger: KalturaLogger) { super(ContentPlaylistViewSections.Metadata, logger); this._buildForm(); } ngOnDestroy() { } private _...
constructor
identifier_name
playlist-metadata-widget.service.ts
import { Injectable, OnDestroy } from '@angular/core'; import { KalturaMultiRequest } from 'kaltura-ngx-client'; import { PlaylistWidget } from '../playlist-widget'; import { KalturaPlaylist } from 'kaltura-ngx-client'; import { Observable } from 'rxjs'; import { FormBuilder, FormGroup, Validators } from '@angular/form...
private _buildForm(): void { this.metadataForm = this._formBuilder.group({ name: ['', Validators.required], description: '', tags: null }); } private _monitorFormChanges(): void { merge(this.metadataForm.valueChanges, this.metadataForm.statusChanges) .pipe(cancelOnDestroy(th...
{ }
identifier_body
playlist-metadata-widget.service.ts
import { Injectable, OnDestroy } from '@angular/core'; import { KalturaMultiRequest } from 'kaltura-ngx-client'; import { PlaylistWidget } from '../playlist-widget'; import { KalturaPlaylist } from 'kaltura-ngx-client'; import { Observable } from 'rxjs'; import { FormBuilder, FormGroup, Validators } from '@angular/form...
if (!this.isNewData && !this._permissionsService.hasPermission(KMCPermissions.PLAYLIST_UPDATE)) { this.metadataForm.disable({ emitEvent: false, onlySelf: true }); } } public searchTags(text: string): Observable<string[]> { return Observable.create( observer => { const requestSubsc...
{ this._monitorFormChanges(); }
conditional_block
kivyapp.py
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' kivyapp.py Este arquivo descreve a classe KivyApp que é a classe derivada de kivy.app.App do kivy. Esta classe é necessaria para inicializar um aplicativo com o kivy. Após inicializar a classe, voce deve setar uma classe parent (atraves de KivyApp.par...
def __str__(self): return repr(self.value)
.value = value
identifier_body
kivyapp.py
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' kivyapp.py Este arquivo descreve a classe KivyApp que é a classe derivada de kivy.app.App do kivy. Esta classe é necessaria para inicializar um aplicativo com o kivy. Após inicializar a classe, voce deve setar uma classe parent (atraves de KivyApp.par...
from kivy.app import App from kivy.clock import Clock class KivyApp(App): parent = None def build(self): if self.parent == None: raise KivyAppException("Variable parent not defined in KivyApp") Config.set('kivy', 'exit_on_escape', 0) Config.set('kivy', 'log_enable', 0) Cloc...
Dependencias (dentro do projeto) ''' from kivy import Config
random_line_split
kivyapp.py
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' kivyapp.py Este arquivo descreve a classe KivyApp que é a classe derivada de kivy.app.App do kivy. Esta classe é necessaria para inicializar um aplicativo com o kivy. Após inicializar a classe, voce deve setar uma classe parent (atraves de KivyApp.par...
): parent = None def build(self): if self.parent == None: raise KivyAppException("Variable parent not defined in KivyApp") Config.set('kivy', 'exit_on_escape', 0) Config.set('kivy', 'log_enable', 0) Clock.schedule_interval(self.on_update, 0) #Schedule main update de...
App(App
identifier_name
kivyapp.py
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' kivyapp.py Este arquivo descreve a classe KivyApp que é a classe derivada de kivy.app.App do kivy. Esta classe é necessaria para inicializar um aplicativo com o kivy. Após inicializar a classe, voce deve setar uma classe parent (atraves de KivyApp.par...
Config.set('kivy', 'exit_on_escape', 0) Config.set('kivy', 'log_enable', 0) Clock.schedule_interval(self.on_update, 0) #Schedule main update def on_start(self): return self.parent.on_start() def on_stop(self): return self.parent.on_stop() def on_pause(self...
e KivyAppException("Variable parent not defined in KivyApp")
conditional_block
stream.rs
haydn.developer@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublic...
rx } /// Will merge multiple streams into a single stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let a = Stream::range(0, 4); /// let b = Stream::range(4, 8); /// let c = Stream::merge(vec![a, b]); /// for n in c.read() { /// // 0, 1, 2, 3, 4, 5, 6, 7 //...
let (tx, rx) = sync_channel(bound); let _ = thread::spawn(move || self.func.call(tx));
random_line_split
stream.rs
dn.developer@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicens...
(self) -> StreamReceiver<T> { let (tx, rx) = sync_channel(1); let _ = thread::spawn(move || self.func.call(tx)); rx } /// Reads elements from the stream with a bound. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// for n in Stream::range(0, 4).read() { /// // 0...
read
identifier_name
stream.rs
dn.developer@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicens...
/// Will merge multiple streams into a single stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let a = Stream::range(0, 4); /// let b = Stream::range(4, 8); /// let c = Stream::merge(vec![a, b]); /// for n in c.read() { /// // 0, 1, 2, 3, 4, 5, 6, 7 /// } /// ``...
{ let (tx, rx) = sync_channel(bound); let _ = thread::spawn(move || self.func.call(tx)); rx }
identifier_body
social.js
var is_connected=false; var user_email_name=[]; var user_data={}; var user_fiends_data={}; var user_picture={}; public_profile='id ,name ,first_name ,last_name ,age_range ,link ,gender ,locale ,picture, timezone ,updated_time ,verified,email'; function fb_signin(){ FB.login(function(response){ if (response.statu...
(url){ window.location.replace(url); }; $(document).ready( function() { window.fbAsyncInit = function() { //SDK loaded, initialize it FB.init({ appId : '685715351578146', xfbml : true, cookie : true, version : 'v2.8'}); //check user session and refresh i...
redirect_me
identifier_name
social.js
var is_connected=false; var user_email_name=[]; var user_data={}; var user_fiends_data={}; var user_picture={}; public_profile='id ,name ,first_name ,last_name ,age_range ,link ,gender ,locale ,picture, timezone ,updated_time ,verified,email'; function fb_signin(){ FB.login(function(response){ if (response.statu...
FB.api('/me', 'get', {fields: public_profile }, function(response) { user_data=response; }); }; function get_user_freinds(){ FB.api('/me/friends', 'get', function(response) { user_fiends_data=response; }); }; function get_user_picture(){ FB.api('/me/picture?height=600', 'get', function(...
} }); }; function get_user_info(){
random_line_split
social.js
var is_connected=false; var user_email_name=[]; var user_data={}; var user_fiends_data={}; var user_picture={}; public_profile='id ,name ,first_name ,last_name ,age_range ,link ,gender ,locale ,picture, timezone ,updated_time ,verified,email'; function fb_signin(){ FB.login(function(response){ if (response.statu...
; function get_user_info(){ FB.api('/me', 'get', {fields: public_profile }, function(response) { user_data=response; }); }; function get_user_freinds(){ FB.api('/me/friends', 'get', function(response) { user_fiends_data=response; }); }; function get_user_picture(){ FB.api('/me/picture?h...
{ FB.api('/me','get' ,{fields:'email,first_name,last_name'}, function(response) { if (response['email']==undefined){ user_email_name={type:'name',first_name:response['first_name'] ,last_name:response['last_name']}; } else{ user_email_name={type:'email',email:response['email']}; ...
identifier_body
net_base.py
# (c) 2015, Ansible Inc, # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is di...
connection = self._shared_loader_obj.connection_loader.get('persistent', play_context, sys.stdin) socket_path = connection.run() display.vvvv('socket_path: %s' % socket_path, play_context.remote_addr) if not socket_path:...
def _start_connection(self, play_context): display.vvv('using connection plugin %s' % play_context.connection, play_context.remote_addr)
random_line_split
net_base.py
# (c) 2015, Ansible Inc, # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is di...
(self, task_vars): if ('network_os' in self._task.args and self._task.args['network_os']): display.vvvv('Getting network OS from task argument') network_os = self._task.args['network_os'] elif (self._play_context.network_os): display.vvvv('Getting network OS from inve...
_get_network_os
identifier_name
net_base.py
# (c) 2015, Ansible Inc, # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is di...
return result def _start_connection(self, play_context): display.vvv('using connection plugin %s' % play_context.connection, play_context.remote_addr) connection = self._shared_loader_obj.connection_loader.get('persistent', ...
new_module_args = self._task.args.copy() # perhaps delete the provider argument here as well since the # module code doesn't need the information, the connection is # already started if 'network_os' in new_module_args: del new_module_args['network_os'] ...
conditional_block
net_base.py
# (c) 2015, Ansible Inc, # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is di...
if play_context.network_os == 'junos': play_context.connection = 'netconf' play_context.port = int(self.provider['port'] or self._play_context.port or 830) else: play_context.connection = 'network_cli' play_context.port = int(self.provider['port'] or self...
if self._play_context.connection != 'local': return dict( failed=True, msg='invalid connection specified, expected connection=local, ' 'got %s' % self._play_context.connection ) play_context = copy.deepcopy(self._play_context) ...
identifier_body
index.js
/* * Off-the-Record Messaging bindings for nodejs * Copyright (C) 2012 Mokhtar Naamani, * <mokhtar.naamani@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free ...
case "display_otr_message": emit(o.EVENT,o.message);break; case "notify": emit(o.EVENT,o.title,o.primary,o.secondary);break; case "log_message": emit(o.EVENT,o.message);break; case "new_fingerprint": emit(o.EVENT,o.fingerprint);break; case "write_fingerpr...
{ function emit(){ otrChannel.emit.apply(otrChannel,arguments); } return (function(o){ debug(o.EVENT); switch(o.EVENT){ //custom events - raised by ops.messageReceiving() case "smp_request": emit(o.EVENT,o.question);break; case "smp_complete": emit(o.EVENT);break; ...
identifier_body
index.js
/* * Off-the-Record Messaging bindings for nodejs * Copyright (C) 2012 Mokhtar Naamani, * <mokhtar.naamani@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free ...
if(!sec) throw( new Error("No Secret Provided")); this.ops.respondSMP(this.user.state, this.context, sec); }; OTRChannel.prototype.isEncrypted = function(){ return (this.context.msgstate===1); }; OTRChannel.prototype.isAuthenticated = function(){ return (this.context.trust==="smp"); }; function Ot...
{ sec = this.parameters ? this.parameters.secret : undefined; }
conditional_block
index.js
/* * Off-the-Record Messaging bindings for nodejs * Copyright (C) 2012 Mokhtar Naamani, * <mokhtar.naamani@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free ...
if(!sec) throw(new Error("No Secrets Provided")); sec = sec[question]; } if(!sec) throw(new Error("No Secret Matched for Question")); this.ops.initSMP(this.user.state, this.context, sec,question); }; OTRChannel.prototype.respond_smp = function(secret){ var sec = sec...
} var sec = secret; if(!sec){ sec = this.parameters ? this.parameters.secrets : undefined;
random_line_split
index.js
/* * Off-the-Record Messaging bindings for nodejs * Copyright (C) 2012 Mokhtar Naamani, * <mokhtar.naamani@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free ...
( otrChannel ){ function emit(){ otrChannel.emit.apply(otrChannel,arguments); } return (function(o){ debug(o.EVENT); switch(o.EVENT){ //custom events - raised by ops.messageReceiving() case "smp_request": emit(o.EVENT,o.question);break; case "smp_complete": emit(o....
OtrEventHandler
identifier_name
register.js
var Q = require('q'); var chalk = require('chalk'); var PackageRepository = require('../core/PackageRepository'); var createError = require('../util/createError'); var defaultConfig = require('../config'); var open = require('opn'); function
(logger, name, url, config) { var repository; var registryClient; var force; config = defaultConfig(config); force = config.force; name = (name || '').trim(); url = (url || '').trim(); // Bypass any cache config.offline = false; config.force = true; var sUrl = config.regi...
register
identifier_name
register.js
var Q = require('q'); var chalk = require('chalk'); var PackageRepository = require('../core/PackageRepository'); var createError = require('../util/createError'); var defaultConfig = require('../config'); var open = require('opn'); function register(logger, name, url, config) { var repository; var registryCli...
}; module.exports = register;
return [name, url];
random_line_split
register.js
var Q = require('q'); var chalk = require('chalk'); var PackageRepository = require('../core/PackageRepository'); var createError = require('../util/createError'); var defaultConfig = require('../config'); var open = require('opn'); function register(logger, name, url, config) { var repository; var registryCli...
// If non interactive or user forced, bypass confirmation if (!config.interactive || force) { return true; } // Confirm if the user really wants to register return Q.nfcall(logger.prompt.bind(logger), { type: 'confirm', message: 'Registering...
{ throw createError('The package you are trying to register is marked as private', 'EPRIV'); }
conditional_block
register.js
var Q = require('q'); var chalk = require('chalk'); var PackageRepository = require('../core/PackageRepository'); var createError = require('../util/createError'); var defaultConfig = require('../config'); var open = require('opn'); function register(logger, name, url, config)
return; return Q.try(function () { // Verify name and url if (!name || !url) { throw createError('Usage: bower register <name> <url>', 'EINVFORMAT'); } // Attempt to resolve the package referenced by the URL to ensure // everything is ok before registering ...
{ var repository; var registryClient; var force; config = defaultConfig(config); force = config.force; name = (name || '').trim(); url = (url || '').trim(); // Bypass any cache config.offline = false; config.force = true; var sUrl = config.registryUrl + '/#register'; ...
identifier_body
utils.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @date: 2014-07-02 @author: shell.xu ''' import os, sys, json, logging import bottle from bottle import request, template, redirect from db import * logger = logging.getLogger('utils') app = bottle.default_app() sess = app.config.get('db.session') LOGFMT = '%(asctime)s.%(m...
def log(logger, log): session = request.environ.get('beaker.session') logger.info(log) sess.add(AuditLogs(username=session['username'], log=log)) def paged_template(tmpl, **kw): for k, v in kw.items(): if k.startswith('_'): name, objs = k[1:], v break del kw['_' + ...
def _inner(*p, **kw): try: r = func(*p, **kw) except Exception, err: r = {'errmsg': str(err)} r = json.dumps(r) logger.debug(r) return r return _inner
identifier_body
utils.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @date: 2014-07-02 @author: shell.xu ''' import os, sys, json, logging import bottle from bottle import request, template, redirect from db import * logger = logging.getLogger('utils') app = bottle.default_app() sess = app.config.get('db.session') LOGFMT = '%(asctime)s.%(m...
(func): def _inner(*p, **kw): session = request.environ.get('beaker.session') if 'username' not in session or 'perms' not in session: return redirect('/usr/login?next=%s' % (next or request.path)) if perm: if hasattr(perm, '__iter__'): ...
receiver
identifier_name
utils.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @date: 2014-07-02 @author: shell.xu ''' import os, sys, json, logging import bottle from bottle import request, template, redirect from db import * logger = logging.getLogger('utils') app = bottle.default_app() sess = app.config.get('db.session') LOGFMT = '%(asctime)s.%(m...
logger.info(log) sess.add(AuditLogs(username=session['username'], log=log)) def paged_template(tmpl, **kw): for k, v in kw.items(): if k.startswith('_'): name, objs = k[1:], v break del kw['_' + name] page = int(request.query.page or 1) cnt = objs.count() pa...
return r return _inner def log(logger, log): session = request.environ.get('beaker.session')
random_line_split
utils.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @date: 2014-07-02 @author: shell.xu ''' import os, sys, json, logging import bottle from bottle import request, template, redirect from db import * logger = logging.getLogger('utils') app = bottle.default_app() sess = app.config.get('db.session') LOGFMT = '%(asctime)s.%(m...
elif perm not in session['perms']: return "you don't have %s permissions" % perm return func(session, *p, **kw) return _inner return receiver def jsonenc(func): def _inner(*p, **kw): try: r = func(*p, **kw) except Exception, err: ...
if not all([p in session['perms'] for p in perm]): return "you don't have %s permissions" % perm
conditional_block
index.js
const ButtonBackToTop = FocusComponents.common.button.backToTop.component; const ButtonBTSample = React.createClass({ /** * Render the component. * @return {object} React node */ render()
}); return <ButtonBTSample/>;
{ return ( <div className='button-bt-example'> <img src="http://lorempixel.com/800/600/sports/"/> <img src="http://lorempixel.com/800/600/abstract/"/> <img src="http://lorempixel.com/800/600/city/"/> <img src="http://lorempixel.com/800/...
identifier_body
index.js
const ButtonBackToTop = FocusComponents.common.button.backToTop.component; const ButtonBTSample = React.createClass({ /** * Render the component. * @return {object} React node */ render() { return ( <div className='button-bt-example'> <img src="http://lorempixel....
return <ButtonBTSample/>;
});
random_line_split
index.js
const ButtonBackToTop = FocusComponents.common.button.backToTop.component; const ButtonBTSample = React.createClass({ /** * Render the component. * @return {object} React node */
() { return ( <div className='button-bt-example'> <img src="http://lorempixel.com/800/600/sports/"/> <img src="http://lorempixel.com/800/600/abstract/"/> <img src="http://lorempixel.com/800/600/city/"/> <img src="http://lorempixel.com/8...
render
identifier_name
associated-types-ref-in-struct-literal.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// except according to those terms. // run-pass // Test associated type references in a struct literal. Issue #20535. pub trait Foo { type Bar; fn dummy(&self) { } } impl Foo for isize { type Bar = isize; } struct Thing<F: Foo> { a: F, b: F::Bar, } fn main() { let thing = Thing{a: 1, b: 2...
// 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
associated-types-ref-in-struct-literal.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let thing = Thing{a: 1, b: 2}; assert_eq!(thing.a + 1, thing.b); }
identifier_body
associated-types-ref-in-struct-literal.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<F: Foo> { a: F, b: F::Bar, } fn main() { let thing = Thing{a: 1, b: 2}; assert_eq!(thing.a + 1, thing.b); }
Thing
identifier_name
groups_to_user.py
from collections import namedtuple from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed from corehq.apps.change_feed.document_types import GROUP from corehq.apps.groups.models import Group from corehq.elastic import stream_es_query, get_es_new, ES_META from corehq.pillows.mappings.user_mapping import USER_...
def update_es_user_with_groups(group_doc, es_client=None): if not es_client: es_client = get_es_new() for user_source in stream_user_sources(group_doc.get("users", [])): if group_doc["name"] not in user_source.group_names or group_doc["_id"] not in user_source.group_ids: user_sou...
doc = {"__group_ids": list(user_source.group_ids), "__group_names": list(user_source.group_names)} es_client.update(USER_INDEX, ES_META['users'].type, user_source.user_id, body={"doc": doc})
conditional_block
groups_to_user.py
from collections import namedtuple from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed from corehq.apps.change_feed.document_types import GROUP from corehq.apps.groups.models import Group from corehq.elastic import stream_es_query, get_es_new, ES_META from corehq.pillows.mappings.user_mapping import USER_...
def get_group_to_user_pillow(pillow_id='GroupToUserPillow'): assert pillow_id == 'GroupToUserPillow', 'Pillow ID is not allowed to change' checkpoint = get_checkpoint_for_elasticsearch_pillow(pillow_id, USER_INDEX_INFO) processor = GroupsToUsersProcessor() return ConstructedPillow( name=pillo...
if change.deleted: remove_group_from_users(change.get_document(), self._es) else: update_es_user_with_groups(change.get_document(), self._es)
identifier_body
groups_to_user.py
from collections import namedtuple from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed from corehq.apps.change_feed.document_types import GROUP from corehq.apps.groups.models import Group from corehq.elastic import stream_es_query, get_es_new, ES_META from corehq.pillows.mappings.user_mapping import USER_...
(pillow_id='GroupToUserPillow'): assert pillow_id == 'GroupToUserPillow', 'Pillow ID is not allowed to change' checkpoint = get_checkpoint_for_elasticsearch_pillow(pillow_id, USER_INDEX_INFO) processor = GroupsToUsersProcessor() return ConstructedPillow( name=pillow_id, checkpoint=checkp...
get_group_to_user_pillow
identifier_name
groups_to_user.py
from collections import namedtuple from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed from corehq.apps.change_feed.document_types import GROUP from corehq.apps.groups.models import Group from corehq.elastic import stream_es_query, get_es_new, ES_META from corehq.pillows.mappings.user_mapping import USER_...
for result in stream_es_query(es_index='users', q=q, fields=["__group_ids", "__group_names"]): group_ids = result.get('fields', {}).get("__group_ids", []) group_ids = set(group_ids) if isinstance(group_ids, list) else {group_ids} group_names = result.get('fields', {}).get("__group_names", []...
q = {"filter": {"and": [{"terms": {"_id": user_ids}}]}}
random_line_split
server-time.service.spec.ts
import { async, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; import { BaseRequestOptions, Http, HttpModule, Response, ResponseOptions } from '@angular/http'; import { MockBackend, MockConnection } from '@angular/http/testing'; import {} from 'jasmine'; import { ServerTimeService } from './server-tim...
++currentTime; }); const times = []; const subscription = serverTimeService.getUnixTimeMs().subscribe((t) => times.push(t)); tick(serverTimeService.getFetchInterval() * 4); expect(times).toEqual([0, 2, 4]); subscription.unsubscribe(); })(); })); });
{ connection.mockError(); }
conditional_block
server-time.service.spec.ts
import { async, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; import { BaseRequestOptions, Http, HttpModule, Response, ResponseOptions } from '@angular/http'; import { MockBackend, MockConnection } from '@angular/http/testing'; import {} from 'jasmine'; import { ServerTimeService } from './server-tim...
if (currentTime % 2 == 0) { connection.mockRespond(new Response(new ResponseOptions({ body: { serverTime: currentTime }, }))); } else { connection.mockError(); } ++currentTime; }); const times = []; const ...
mockBackend.connections.subscribe((connection: MockConnection) => {
random_line_split
sco_bulletins_json.py
('not mx: %s' % type(o)) return json.JSONEncoder.default(self, o) def make_json_formsemestre_bulletinetud( context, formsemestre_id, etudid, REQUEST=None, xml_with_decisions=False, version='long', force_publishing=False # force publication meme si semestre non publie sur "portail" ...
# (fonction séparée: n'utilise pas formsemestre_bulletinetud_dict() # pour simplifier le code, mais attention a la maintenance !) # def formsemestre_bulletinetud_published_dict( context, formsemestre_id, etudid, force_publishing=False, xml_nodate=False, REQUEST=None, xml_with_d...
Renvoie bulletin en chaine JSON""" d = formsemestre_bulletinetud_published_dict( context, formsemestre_id, etudid, force_publishing=force_publishing, REQUEST=REQUEST, xml_with_decisions=xml_with_decisions, version=version) if REQUEST: REQUEST.RESPONSE.setHeader...
identifier_body
sco_bulletins_json.py
log('not mx: %s' % type(o)) return json.JSONEncoder.default(self, o) def make_json_formsemestre_bulletinetud( context, formsemestre_id, etudid, REQUEST=None, xml_with_decisions=False, version='long', force_publishing=False # force publication meme si semestre non publie sur "porta...
continue mod = modimpl['module'] #if mod['ects'] is None: # ects = '' #else: # ects = str(mod['ects']) modstat = nt.get_mod_stats(modimpl['moduleimpl_id']) m = dict( id=modimpl['moduleimpl_id'], co...
random_line_split
sco_bulletins_json.py
ud_groups_in_partition(context, pid) nt = context._getNotesCache().get_NotesTable(context, formsemestre_id) #> toutes notes ues = nt.get_ues() modimpls = nt.get_modimpls() nbetuds = len(nt.rangs) mg = fmt_note(nt.get_etud_moy_gen(etudid)) if nt.get_moduleimpls_attente() or context.get_prefe...
'] = dict( code='', etat='DEM' ) #
conditional_block
sco_bulletins_json.py
not mx: %s' % type(o)) return json.JSONEncoder.default(self, o) def mak
context, formsemestre_id, etudid, REQUEST=None, xml_with_decisions=False, version='long', force_publishing=False # force publication meme si semestre non publie sur "portail" ): """Renvoie bulletin en chaine JSON""" d = formsemestre_bulletinetud_published_dict( conte...
e_json_formsemestre_bulletinetud(
identifier_name
test.js
var GlobalSystem = window.System; require("./utils_test"); require("./crawl_test"); require("./normalize_test"); require("./import_test"); require("./load_test"); require("./locate_test"); var makeIframe = function(src){ var iframe = document.createElement('iframe'); window.removeMyself = function(){ delete windo...
}).then(function(env){ equal(env, "development", "loaded the env"); }).then(start); }); asyncTest("Reuse existing npmContext.pkgInfo", function(){ GlobalSystem.npmContext.pkgInfo = [{ name: "reuse-test", version: "1.0.0", fileUrl: GlobalSystem.baseURL }]; GlobalSystem["delete"]("package.json!npm"); GlobalS...
GlobalSystem["delete"]("package.json!npm"); delete window.process; GlobalSystem["import"]("package.json!npm").then(function() { return GlobalSystem["import"]("test/env");
random_line_split
horn_sequence.py
LONG_HORN = 750 LONG_HORN_SPACE = LONG_HORN/2 SHORT_HORN = 400 SHORT_HORN_SPACE = SHORT_HORN/2
0: 'LLL', # Two long horns a minute later (two minutes to start) 60000: 'LL', # One short, three long horns 30s later (one minute 30s to start) 90000: 'LSSS', # One long horn 30s later (one minute to start) 120000: 'L', # Three short horns 30s later...
sequences = { 'CreekFleet': { # Three long horns immediately (three minutes to start)
random_line_split
horn_sequence.py
LONG_HORN = 750 LONG_HORN_SPACE = LONG_HORN/2 SHORT_HORN = 400 SHORT_HORN_SPACE = SHORT_HORN/2 sequences = { 'CreekFleet': { # Three long horns immediately (three minutes to start) 0: 'LLL', # Two long horns a minute later (two minutes to start) 60000: 'LL', # One...
if blast == 'S': stepTime += SHORT_HORN HORN_TIMES.append(stepTime) HORN_COMMANDS.append(False) stepTime += SHORT_HORN_SPACE f.write( f'uint8_t {option.upper()}_NUM_HORNS = {len(HORN_TIMES)};\n') ...
stepTime += LONG_HORN HORN_TIMES.append(stepTime) HORN_COMMANDS.append(False) stepTime += LONG_HORN_SPACE
conditional_block
node.ts
import * as babylon from 'babylon'; export abstract class Node<T extends babylon.Node> { private _instrumented: boolean; private _raw: T; private _parent: Node<any>; private _start: number; private _end: number; constructor(raw: T, parent?: Node<any>, instrumented = false) { this._raw = raw; ...
get loc() { return this.raw.loc; } get start() { if (typeof this._start == 'undefined') { this._start = this.raw.start; } return this._start; } get end() { if (typeof this._end == 'undefined') { this._end = this.raw.end; } return this._end; } get instrumented()...
{ this._parent = parent; }
identifier_body
node.ts
import * as babylon from 'babylon'; export abstract class Node<T extends babylon.Node> { private _instrumented: boolean; private _raw: T; private _parent: Node<any>; private _start: number; private _end: number; constructor(raw: T, parent?: Node<any>, instrumented = false) { this._raw = raw; ...
this.parent.replaceChild(this, children); } insertAfter(nodes: Node<any>|Node<any>[]) { let children; if (Array.isArray(nodes)) { children = [].concat(this, nodes); } else { children = [this, nodes]; } this.parent.replaceChild(this, children); } public visit(fn: (node: Nod...
{ children = [nodes, this]; }
conditional_block
node.ts
import * as babylon from 'babylon'; export abstract class Node<T extends babylon.Node> { private _instrumented: boolean; private _raw: T; private _parent: Node<any>; private _start: number; private _end: number; constructor(raw: T, parent?: Node<any>, instrumented = false) { this._raw = raw; ...
public visit(fn: (node: Node<any>) => void): void { throw new Error('Unsupported'); } public toJavaScript(): string { throw new Error('Unsupported'); } }
random_line_split
node.ts
import * as babylon from 'babylon'; export abstract class Node<T extends babylon.Node> { private _instrumented: boolean; private _raw: T; private _parent: Node<any>; private _start: number; private _end: number; constructor(raw: T, parent?: Node<any>, instrumented = false) { this._raw = raw; ...
(path: string): void { throw new Error('Unsupported'); } replaceWith(nodes: Node<any>|Node<any>[]) { this.parent.replaceChild(this, nodes); } protected replaceChild(source: Node<any>, dest: Node<any>|Node<any>[]) { throw new Error('Unsupported'); } insertBefore(nodes: Node<any>|Node<any>[]) {...
instrument
identifier_name
add_fort_modifier_response_pb2.py
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/networking/responses/add_fort_modifier_response.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _messa...
package='pogoprotos.networking.responses', syntax='proto3', serialized_pb=_b('\n@pogoprotos/networking/responses/add_fort_modifier_response.proto\x12\x1fpogoprotos.networking.responses\x1a;pogoprotos/networking/responses/fort_details_response.proto\"\xc2\x02\n\x17\x41\x64\x64\x46ortModifierResponse\x12O\n\x06resu...
DESCRIPTOR = _descriptor.FileDescriptor( name='pogoprotos/networking/responses/add_fort_modifier_response.proto',
random_line_split
index.js
'use strict'; // Load modules const Code = require('code'); const Hapi = require('hapi'); const Lab = require('lab'); const Info = require('../lib/modules/hello-world'); // Declare internals const internals = {}; // Test shortcuts const lab = exports.lab = Lab.script(); const it = lab.it; const describe = lab.de...
server.inject(request, (response) => { expect(response.statusCode).to.equal(200); expect(response.result).to.equal({ msg: 'hello world!' }); done(); }); }); }); });
const request = { method: 'GET', url: '/' };
random_line_split
TestUtil.js
Elm.Native.TestUtil = {}; Elm.Native.TestUtil.make = function (localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.TestUtil = localRuntime.Native.TestUtil || {}; if (!localRuntime.Native.TestUtil.values) {
var sample = function (signal) { // Use closure to track value var val = signal.value; var handler = function (value) { val = value; }; // We construct a new "output" node, because otherwise the incoming // signal may be p...
var Task = Elm.Native.Task.make(localRuntime); var Signal = Elm.Native.Signal.make(localRuntime);
random_line_split
TestUtil.js
Elm.Native.TestUtil = {}; Elm.Native.TestUtil.make = function (localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.TestUtil = localRuntime.Native.TestUtil || {}; if (!localRuntime.Native.TestUtil.values)
// previous `Task.andThen` which updated a Signal may not have // actually completed yet unless we do this inside a timeout. localRuntime.setTimeout(function () { callback(Task.succeed(val)); }, 0); }); }; l...
{ var Task = Elm.Native.Task.make(localRuntime); var Signal = Elm.Native.Signal.make(localRuntime); var sample = function (signal) { // Use closure to track value var val = signal.value; var handler = function (value) { val = value; ...
conditional_block
vu.rs
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applic...
#pragma rs java_package_name(com.android.musicvis.vis4) #include "rs_graphics.rsh" // State float gAngle; int gPeak; rs_program_vertex gPVBackground; rs_program_fragment gPFBackground; rs_allocation gTvumeter_background; rs_allocation gTvumeter_peak_on; rs_allocation gTvumeter_peak_off; rs_allocation gTvumeter_n...
#pragma version(1)
random_line_split
vu.rs
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applic...
else { rsgBindTexture(gPFBackground, 0, gTvumeter_peak_off); } rsgDrawQuadTexCoords( 140.0f, 70.0f, -1.0f, // space 0.0, 1.0f, // texture 196, 70.0f, -1.0f, // space 1.0f, 1.0f, // texture ...
{ rsgBindTexture(gPFBackground, 0, gTvumeter_peak_on); }
conditional_block
practice.js
Engine wants to be notified, gets placed. -When stack is empty, JS engine looks at Event Queue periodically and then creates Execution Context -Browser is putting things asynchronously -Asynchronous is possible in JS but it's about events happening outside JS Engine. */ function waitThreeSeconds() { var ms = 3000...
// Function Statement function greet(name) { console.log('Hello' + name); } greet(); // Function Expression (sort of Object Literal, not in memoryspace) var greetFunc = function(name) { console.log('Hello' + name); }; greetFunc(); // IIFE var greetFunc = function(name) { return 'Hello' + name; }(); // Lecture...
*/
random_line_split
practice.js
var myVar = 2; b(); } var myVar = 1; a(); b(); // a() is 2, b() is undefined // b()'s Outer Reference is a() now // Lexical refers to when it is created // Lecture 17: Scope, ES6, and let /* -Scope: Where a variable is available in your code -ECMAScript 6 -let can be used instead of var -Allows JS engine t...
{ console.log(myVar); }
identifier_body
practice.js
3 // Lecture 19: Conceptual Aside: Types and JS /* -Dynamic Typing: You don't tell the engine what type of data a variable holds, it figures it out while your code is running. -C# using Static Typing hence you have to tell. */ // Lecture 20: Primitive Types /* -Primitive or Simple Type: A type of data that repre...
makeGreeting
identifier_name
practice.js
wants to be notified, gets placed. -When stack is empty, JS engine looks at Event Queue periodically and then creates Execution Context -Browser is putting things asynchronously -Asynchronous is possible in JS but it's about events happening outside JS Engine. */ function waitThreeSeconds() { var ms = 3000 + new ...
; // returns true and console logs it... // Lecture 28: Default Values /* -Operators are functions that return values */ function greet(name) { console.console.log(name); console.log('Hello' + name); } greet(); // Lecture 29: Framework Aside // Lecture 30: Objects and Functions /* -Objects: Collections of N...
{ console.log('Something is there.'); }
conditional_block
rust_base58.rs
extern crate rust_base58; use errors::prelude::*; use self::rust_base58::{FromBase58, ToBase58}; pub fn
(doc: &[u8]) -> String { doc.to_base58() } pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> { doc.from_base58() .map_err(|err| err_msg(IndyErrorKind::InvalidStructure, format!("Invalid base58 sequence: {:}", err))) } #[cfg(test)] mod tests { use super::*; #[test] fn encode_works() {...
encode
identifier_name
rust_base58.rs
extern crate rust_base58; use errors::prelude::*; use self::rust_base58::{FromBase58, ToBase58}; pub fn encode(doc: &[u8]) -> String { doc.to_base58() } pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> { doc.from_base58() .map_err(|err| err_msg(IndyErrorKind::InvalidStructure, format!("Invalid ...
#[test] fn decode_works() { let result = decode("Ldp"); assert!(result.is_ok(), "Got error"); assert_eq!(&[1, 2, 3], &result.unwrap()[..], "Get unexpected data"); } }
{ let result = encode(&[1, 2, 3]); assert_eq!("Ldp", &result, "Got unexpected data"); }
identifier_body
rust_base58.rs
extern crate rust_base58;
pub fn encode(doc: &[u8]) -> String { doc.to_base58() } pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> { doc.from_base58() .map_err(|err| err_msg(IndyErrorKind::InvalidStructure, format!("Invalid base58 sequence: {:}", err))) } #[cfg(test)] mod tests { use super::*; #[test] fn enc...
use errors::prelude::*; use self::rust_base58::{FromBase58, ToBase58};
random_line_split
qbittorrent_client.py
# Author: Mr_Orange <mr_orange@hotmail.it> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
(GenericClient): def __init__(self, host=None, username=None, password=None): super(qbittorrentAPI, self).__init__('qbittorrent', host, username, password) self.url = self.host self.session.auth = HTTPDigestAuth(self.username, self.password); def _get_auth(self): try: ...
qbittorrentAPI
identifier_name
qbittorrent_client.py
# Author: Mr_Orange <mr_orange@hotmail.it> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
data = {'hash': result.hash} return self._request(method='post', data=data) api = qbittorrentAPI()
self.url = self.host+'command/pause'
conditional_block
qbittorrent_client.py
# Author: Mr_Orange <mr_orange@hotmail.it> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
def _add_torrent_uri(self, result): self.url = self.host+'command/download' data = {'urls': result.url} return self._request(method='post', data=data) def _add_torrent_file(self, result): self.url = self.host+'command/upload' files = {'torrents': (result.name + '.tor...
try: self.response = self.session.get(self.host, verify=False) self.auth = self.response.content except: return None return self.auth if not self.response.status_code == 404 else None
identifier_body
qbittorrent_client.py
# Author: Mr_Orange <mr_orange@hotmail.it> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
api = qbittorrentAPI()
random_line_split
app.py
import logging import sys from mutant.parsers.python_parser import PythonParser logger = logging.getLogger(__name__)
class MutantApp(object): """ App stores all readers, parser middlewares generators. All plugins can register themselves on this instance. And finally it has `parse` and `mutate` methods, that executes mutation. """ def __init__(self): self.readers = {} self.parser_middlewares =...
random_line_split
app.py
import logging import sys from mutant.parsers.python_parser import PythonParser logger = logging.getLogger(__name__) class MutantApp(object):
self.generators[generator_name] = generator_class def extend_generator(self, generator_name, extension): self.generator_extensions.setdefault(generator_name, []).append(extension) def parse(self, reader_name, file_or_name): """ Parsing contains 3 steps: 1) Read input fi...
""" App stores all readers, parser middlewares generators. All plugins can register themselves on this instance. And finally it has `parse` and `mutate` methods, that executes mutation. """ def __init__(self): self.readers = {} self.parser_middlewares = [] self.generators = ...
identifier_body
app.py
import logging import sys from mutant.parsers.python_parser import PythonParser logger = logging.getLogger(__name__) class MutantApp(object): """ App stores all readers, parser middlewares generators. All plugins can register themselves on this instance. And finally it has `parse` and `mutate` meth...
(self, generator_name): gen = self.generators[generator_name](self.schema) for ext in self.generator_extensions.get(generator_name, []): gen.register_extension(ext) return gen.render() def _read(self, reader_name, file_or_name): reader = self.readers[reader_name] ...
mutate
identifier_name
app.py
import logging import sys from mutant.parsers.python_parser import PythonParser logger = logging.getLogger(__name__) class MutantApp(object): """ App stores all readers, parser middlewares generators. All plugins can register themselves on this instance. And finally it has `parse` and `mutate` meth...
schema = self.parser.parse(data) for middleware in reversed(self.parser_middlewares): if hasattr(middleware, 'after_parse'): schema = middleware.after_parse(schema) self.schema = schema return self.schema def mutate(self, generator_name): gen = s...
data = middleware.before_parse(data)
conditional_block
frano_filters.py
from django import template from django.template.defaultfilters import stringfilter import locale register = template.Library() #-----------\ # FILTERS | #-----------/ @register.filter @stringfilter def num_format(value, places = 2, min_places = 2): return format(value, '.', int(places), 3, ',', int(min_places))...
#if decimal_pos: # dec_part = dec_part + ('0' * (decimal_pos - len(dec_part))) # zero pad to minimum decimal positions if min_decimal_pos: dec_part = dec_part + ('0' * (min_decimal_pos - len(dec_part))) if dec_part: dec_part = decimal_sep + dec_part # grouping if thousan...
# do not zero pad when its not needed
random_line_split
frano_filters.py
from django import template from django.template.defaultfilters import stringfilter import locale register = template.Library() #-----------\ # FILTERS | #-----------/ @register.filter @stringfilter def num_format(value, places = 2, min_places = 2): return format(value, '.', int(places), 3, ',', int(min_places))...
#-------------\ # UTILITIES | #-------------/ def format(number, decimal_sep, decimal_pos, grouping=0, thousand_sep='', min_decimal_pos = None): """ NOTE: taken from django 1.2.3 source Gets a number (as a number or string), and returns it as a string, using formats definied as arguments: ...
return sorted(value)
identifier_body
frano_filters.py
from django import template from django.template.defaultfilters import stringfilter import locale register = template.Library() #-----------\ # FILTERS | #-----------/ @register.filter @stringfilter def num_format(value, places = 2, min_places = 2): return format(value, '.', int(places), 3, ',', int(min_places))...
# do not zero pad when its not needed #if decimal_pos: # dec_part = dec_part + ('0' * (decimal_pos - len(dec_part))) # zero pad to minimum decimal positions if min_decimal_pos: dec_part = dec_part + ('0' * (min_decimal_pos - len(dec_part))) if dec_part: dec_part = ...
int_part, dec_part = str_number, ''
conditional_block
frano_filters.py
from django import template from django.template.defaultfilters import stringfilter import locale register = template.Library() #-----------\ # FILTERS | #-----------/ @register.filter @stringfilter def num_format(value, places = 2, min_places = 2): return format(value, '.', int(places), 3, ',', int(min_places))...
(number, decimal_sep, decimal_pos, grouping=0, thousand_sep='', min_decimal_pos = None): """ NOTE: taken from django 1.2.3 source Gets a number (as a number or string), and returns it as a string, using formats definied as arguments: * decimal_sep: Decimal separator symbol (for example ".") ...
format
identifier_name
filter.py
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
from buildbot.changes.filter import ChangeFilter _hush_pyflakes = ChangeFilter # keep pyflakes happy
random_line_split
backend.memory.js
this.recline = this.recline || {}; this.recline.Backend = this.recline.Backend || {}; this.recline.Backend.Memory = this.recline.Backend.Memory || {}; (function(my, recline) { "use strict"; my.__type__ = 'memory'; // private data - use either jQuery or Underscore Deferred depending on what is available var De...
else { // value can be null (apparently in some cases) value = ''; } // TODO regexes? foundmatch = foundmatch || (pattern.test(value.toLowerCase())); // TODO: early out (once we are true should break to spare unnecessary testing) ...
{ value = value.toString(); }
conditional_block
backend.memory.js
this.recline = this.recline || {}; this.recline.Backend = this.recline.Backend || {}; this.recline.Backend.Memory = this.recline.Backend.Memory || {}; (function(my, recline) { "use strict"; my.__type__ = 'memory'; // private data - use either jQuery or Underscore Deferred depending on what is available var De...
(record, filter) { var parse = getDataParser(filter); var value = parse(record[filter.field]); var terms = parse(filter.terms).split(","); return (_.indexOf(terms, value) >= 0); } function range(record, filter) { var fromnull = (_.isUndefined(filter.from) || filter...
terms
identifier_name
backend.memory.js
this.recline = this.recline || {}; this.recline.Backend = this.recline.Backend || {}; this.recline.Backend.Memory = this.recline.Backend.Memory || {}; (function(my, recline) { "use strict"; my.__type__ = 'memory'; // private data - use either jQuery or Underscore Deferred depending on what is available var De...
}; // we OR across fields but AND across terms in query string this._applyFreeTextQuery = function(results, queryObj) { if (queryObj.q) { var terms = queryObj.q.split(' '); var patterns=_.map(terms, function(term) { return new RegExp(term.toLowerCase()); }); ...
{ // TODO code here }
identifier_body