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
routes.js
/** * Created by andyf on 4/14/2017. */ //------------------------------------------// //------------------ROUTES------------------// //------------------------------------------// var multer = require("multer"); var express = require("express"); var app = express(); var multer = require("multer"); var m...
var upload = multer({ storage : storage}).single('userPhoto'); var User = require('./models/user'); module.exports = function(app, passport){ app.get('/authenticate', function(req, res){ res.render('authenticate.ejs'); }); app.post('/api/photo',function(req,res) { console.log("g...
create(file); callback(null, file.originalname); } });
random_line_split
action_support.js
/** @module ember @submodule ember-views */ import { inspect } from 'ember-utils'; import { Mixin, get, isNone, assert } from 'ember-metal'; import { MUTABLE_CELL } from '../compat/attrs'; function
(component, actionName) { if (actionName && actionName[MUTABLE_CELL]) { actionName = actionName.value; } assert( 'The default action was triggered on the component ' + component.toString() + ', but the action name (' + actionName + ') was not a string.', isNone(actionName) || typeof actionName ==...
validateAction
identifier_name
action_support.js
/** @module ember @submodule ember-views */ import { inspect } from 'ember-utils'; import { Mixin, get, isNone, assert } from 'ember-metal'; import { MUTABLE_CELL } from '../compat/attrs'; function validateAction(component, actionName) { if (actionName && actionName[MUTABLE_CELL]) { actionName = actionName.val...
else { assert(`${inspect(this)} had no action handler for: ${actionName}`, action); } } });
{ assert( 'The `target` for ' + this + ' (' + target + ') does not have a `send` method', typeof target.send === 'function' ); target.send(...arguments); }
conditional_block
action_support.js
/** @module ember @submodule ember-views */ import { inspect } from 'ember-utils'; import { Mixin, get, isNone, assert } from 'ember-metal'; import { MUTABLE_CELL } from '../compat/attrs'; function validateAction(component, actionName) { if (actionName && actionName[MUTABLE_CELL]) { actionName = actionName.val...
playNextSongInAlbum() { ... } } }); ``` @method sendAction @param [action] {String} the action to call @param [params] {*} arguments for the action @public */ sendAction(action, ...contexts) { let actionName; // Send the default action if (action...
```javascript // app/controllers/application.js App.ApplicationController = Ember.Controller.extend({ actions: {
random_line_split
action_support.js
/** @module ember @submodule ember-views */ import { inspect } from 'ember-utils'; import { Mixin, get, isNone, assert } from 'ember-metal'; import { MUTABLE_CELL } from '../compat/attrs'; function validateAction(component, actionName)
/** @class ActionSupport @namespace Ember @private */ export default Mixin.create({ /** Calls an action passed to a component. For example a component for playing or pausing music may translate click events into action notifications of "play" or "stop" depending on some internal state of the com...
{ if (actionName && actionName[MUTABLE_CELL]) { actionName = actionName.value; } assert( 'The default action was triggered on the component ' + component.toString() + ', but the action name (' + actionName + ') was not a string.', isNone(actionName) || typeof actionName === 'string' || typeof act...
identifier_body
app.js
//Express, Mongo & Environment specific imports var express = require('express'); var morgan = require('morgan'); var serveStatic = require('serve-static'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var compression = require('compression'); var errorHandler = require('errorha...
// Route definitions app.get('/api/books', BookController.list); app.get('/api/books/:id', BookController.show); app.post('api/books', BookController.create); app.put('/api/books/:id', BookController.update); app.delete('/api/books/:id', BookController.remove); var server = app.listen(3000, function () { var ho...
{ app.use(errorHandler({ dumpExceptions: true, showStack: true })); var ImportController = require('./api/controller/ImportController'); app.get('/import', ImportController.import); app.get('/import/reset', ImportController.reset); }
conditional_block
app.js
//Express, Mongo & Environment specific imports var express = require('express'); var morgan = require('morgan'); var serveStatic = require('serve-static'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var compression = require('compression'); var errorHandler = require('errorha...
app.get('/api/books', BookController.list); app.get('/api/books/:id', BookController.show); app.post('api/books', BookController.create); app.put('/api/books/:id', BookController.update); app.delete('/api/books/:id', BookController.remove); var server = app.listen(3000, function () { var host = server.address().add...
// Route definitions
random_line_split
cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // macro_rules! ord_impl { // ($($t:ty)*) => ($( // #[stable(feature = "rust1", since = "1.0.0")] // impl Ord for $t { // #[i...
// } // ord_impl! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 } macro_rules! cmp_test { ($($t:ty)*) => ($({ let v1: $t = 68 as $t; { let result: Ordering = v1.cmp(&v1); assert_eq!(result, Equal); } let v2: $t = 100 as $t; { let result: Ordering = v1.cmp(&v2); ...
// )*)
random_line_split
cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // macro_rules! ord_impl { // ($($t:ty)*) => ($( // #[stable(feature = "rust1", since = "1.0.0")] // impl Ord for $t { // #[i...
}
{ cmp_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }; }
identifier_body
cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // macro_rules! ord_impl { // ($($t:ty)*) => ($( // #[stable(feature = "rust1", since = "1.0.0")] // impl Ord for $t { // #[i...
() { cmp_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 }; } }
cmp_test1
identifier_name
fertility_rate_preprocess_gen_tmcf.py
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
(df, cleaned_csv): with open(cleaned_csv, 'w', newline='') as f_out: writer = csv.DictWriter(f_out, fieldnames=_OUTPUT_COLUMNS, lineterminator='\n') writer.writeheader() for _, row in df.iterrows(): writer.writerow({...
preprocess
identifier_name
fertility_rate_preprocess_gen_tmcf.py
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
df['value'] = pd.to_numeric(df['value']) df = df.pivot_table(values='value', index=['geo', 'time'], columns=['indicator_unit'], aggfunc='first').reset_index().rename_axis(None, axis=1) return df def preprocess(df, cleaned_csv): ...
df['value'] = df['value'].str.replace(flag, '')
conditional_block
fertility_rate_preprocess_gen_tmcf.py
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def get_template_mcf(): # Automate Template MCF generation since there are many Statistical Variables. TEMPLATE_MCF_TEMPLATE = """ Node: E:Eurostats_NUTS3_FRate_Age->E{index} typeOf: dcs:StatVarObservation variableMeasured: dcs:{stat_var} observationAbout: C:Eurostats_NUTS3_FRate_Age->GeoId observa...
with open(cleaned_csv, 'w', newline='') as f_out: writer = csv.DictWriter(f_out, fieldnames=_OUTPUT_COLUMNS, lineterminator='\n') writer.writeheader() for _, row in df.iterrows(): writer.writerow({ 'Date'...
identifier_body
fertility_rate_preprocess_gen_tmcf.py
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
df = df.pivot_table(values='value', index=['geo', 'time'], columns=['indicator_unit'], aggfunc='first').reset_index().rename_axis(None, axis=1) return df def preprocess(df, cleaned_csv): with open(cleaned_csv, 'w', newline='') as f_ou...
possible_flags = [' ', ':'] for flag in possible_flags: df['value'] = df['value'].str.replace(flag, '') df['value'] = pd.to_numeric(df['value'])
random_line_split
MyProfileSettings.tsx
import { MenuItem } from "app/Components/MenuItem" import { presentEmailComposer } from "app/NativeModules/presentEmailComposer" import { navigate } from "app/navigation/navigate" import { GlobalStore, useFeatureFlag } from "app/store/GlobalStore" import { Button, Flex, Sans, Separator, Spacer, useColor } from "palette...
<Spacer my={1} /> <MenuItem title="Account" onPress={() => navigate("my-account")} /> <Separator my={1} borderColor={separatorColor} /> {!!showOrderHistory && ( <> <MenuItem title="Order History" onPress={() => navigate("/orders")} /> <Separator my={1} borderColor={se...
random_line_split
api.js
(function (root, factory) { if (typeof module === 'object' && module.exports) { module.exports = factory(require('jquery'), require('../common/utility')); } else { root.api = factory(root.jQuery, root.utility); } }(this, function ($, util) { // API var self = {}; // Object -> Promise[[Entity]] s...
(){ return { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Littlesis-Request-Type': 'API', // TODO: retrieve this w/o JQuery 'X-CSRF-Token': $("meta[name='csrf-token']").attr("content") || "" }; } function qs(queryParams){ retur...
headers
identifier_name
api.js
(function (root, factory) { if (typeof module === 'object' && module.exports)
else { root.api = factory(root.jQuery, root.utility); } }(this, function ($, util) { // API var self = {}; // Object -> Promise[[Entity]] self.searchEntity = function(query){ return get('/search/entity', { num: 10, q: query }) .then(format) .catch(handleError); // [Entity] -> [Enti...
{ module.exports = factory(require('jquery'), require('../common/utility')); }
conditional_block
api.js
(function (root, factory) { if (typeof module === 'object' && module.exports) { module.exports = factory(require('jquery'), require('../common/utility')); } else { root.api = factory(root.jQuery, root.utility); } }(this, function ($, util) { // API var self = {}; // Object -> Promise[[Entity]] s...
return fetch(url + qs(queryParams), { headers: headers(), method: 'get', credentials: 'include' // use auth tokens stored in session cookies }).then(jsonify); } function post(url, payload){ return fetch(url, { headers: headers(), method: 'post', cr...
random_line_split
api.js
(function (root, factory) { if (typeof module === 'object' && module.exports) { module.exports = factory(require('jquery'), require('../common/utility')); } else { root.api = factory(root.jQuery, root.utility); } }(this, function ($, util) { // API var self = {}; // Object -> Promise[[Entity]] s...
}; // [EntityWithoutId] -> Promise[[Entity]] self.createEntities = function(entities){ return post('/entities/bulk', formatReq(entities)) .then(formatResp); // [Entity] -> [Entity] function formatReq(entities){ return { data: entities.map(function(entity){ return { ...
{ console.error('API request error: ', err); return []; }
identifier_body
mod.rs
extern crate chrono; extern crate chrono_tz; extern crate clap; extern crate ical; use std::fs::File; use std::io::BufReader; use self::chrono::{DateTime, TimeZone}; use self::chrono_tz::{Tz, UTC}; use self::clap::SubCommand; use self::ical::IcalParser; #[derive(Debug)] enum LineInfo { TextInfo { name: String, v...
let input = IcalParser::new(BufReader::new(file)); for line in input { let line = line.unwrap(); for evt in line.events { println!("EVENT"); for prop in evt.properties { let parsedval: LineInfo = match prop.value { Some(mut v) => { let tz = if (&v).ends_with("Z") { v.pop(); ...
random_line_split
mod.rs
extern crate chrono; extern crate chrono_tz; extern crate clap; extern crate ical; use std::fs::File; use std::io::BufReader; use self::chrono::{DateTime, TimeZone}; use self::chrono_tz::{Tz, UTC}; use self::clap::SubCommand; use self::ical::IcalParser; #[derive(Debug)] enum
{ TextInfo { name: String, value: Option<String>, }, DateTimeInfo { name: String, value: DateTime<UTC>, } } pub fn entry(m: &SubCommand) -> i32 { let fname = m.matches.value_of("filename").unwrap(); let file = match File::open(fname) { Ok(f) => f, Err(f) => { println!("{}", f); return 1; } ...
LineInfo
identifier_name
security-check.py
) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Perform basic ELF security checks on a series of executables. Exit status will be 0 if successful, and the program will be silent. Otherwis...
return (arch,bits) IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA = 0x0020 IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040 IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100 def check_PE_DYNAMIC_BASE(executable): '''PIE: DllCharacteristics bit 0x40 signifies dynamicbase (ASLR)''' (arch,bits) = get_PE_dll_c...
tokens = line.split() if len(tokens)>=2 and tokens[0] == 'architecture:': arch = tokens[1].rstrip(',') if len(tokens)>=2 and tokens[0] == 'DllCharacteristics': bits = int(tokens[1],16)
conditional_block
security-check.py
c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Perform basic ELF security checks on a series of executables. Exit status will be 0 if successful, and the program will be silent. Otherwi...
for line in stdout.splitlines(): tokens = line.split() if len(tokens)>1 and tokens[1] == '(BIND_NOW)' or (len(tokens)>2 and tokens[1] == '(FLAGS)' and 'BIND_NOW' in tokens[2:]): have_bindnow = True return have_gnu_relro and have_bindnow def check_ELF_Canary(executable): ''' ...
''' Check for read-only relocations. GNU_RELRO program header must exist Dynamic section must have BIND_NOW flag ''' have_gnu_relro = False for (typ, flags) in get_ELF_program_headers(executable): # Note: not checking flags == 'R': here as linkers set the permission differently #...
identifier_body
security-check.py
) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Perform basic ELF security checks on a series of executables. Exit status will be 0 if successful, and the program will be silent. Otherwis...
(executable): '''Return type and flags for ELF program headers''' p = subprocess.Popen([READELF_CMD, '-l', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error o...
get_ELF_program_headers
identifier_name
security-check.py
c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Perform basic ELF security checks on a series of executables. Exit status will be 0 if successful, and the program will be silent. Otherwi...
('NX', check_PE_NX) ] } def identify_executable(executable): with open(filename, 'rb') as f: magic = f.read(4) if magic.startswith(b'MZ'): return 'PE' elif magic.startswith(b'\x7fELF'): return 'ELF' return None if __name__ == '__main__': retval = 0 for filename in s...
random_line_split
voir.py
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
msg = "Détail sur le chemin {} :".format(chemin.cle) msg += "\n Flags :" for nom_flag in FLAGS.keys(): msg += "\n {}".format(nom_flag.capitalize()) msg += " : " + oui_ou_non(chemin.a_flag(nom_flag)) msg += "\n Salles du chemin :" if len(chemin.salles)...
personnage << "|err|Ce chemin n'existe pas.|ff|" return chemin = importeur.pnj.chemins[cle]
random_line_split
voir.py
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
personnage << msg
retour " + chemin.salles_retour[salle] + ")"
conditional_block
voir.py
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
ef interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" cle = dic_masques["cle"].cle if cle not in importeur.pnj.chemins: personnage << "|err|Ce chemin n'existe pas.|ff|" return chemin = importeur.pnj.chemins[cle] msg = "Détail su...
Méthode appelée lors de l'ajout de la commande à l'interpréteur""" cle = self.noeud.get_masque("cle") cle.proprietes["regex"] = r"'[a-z0-9_:]{3,}'" d
identifier_body
voir.py
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
lf): """Méthode appelée lors de l'ajout de la commande à l'interpréteur""" cle = self.noeud.get_masque("cle") cle.proprietes["regex"] = r"'[a-z0-9_:]{3,}'" def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" cle = dic_masques["cle"].cle ...
uter(se
identifier_name
rack-add-modal.js
import Ember from "ember"; import ModalBaseView from "./modal-base"; import Form from "./mixins/form-modal-mixin"; import Full from "./mixins/full-modal-mixin"; import Save from "./mixins/object-action-mixin"; import Row from "mb-test-1/models/row"; import Rack from "mb-test-1/models/rack"; var RackAddModal = ModalBas...
export default RackAddModal;
random_line_split
http-request.service.ts
import { Http, Headers, Response, RequestOptions } from '@angular/http'; import { Injectable, Inject } from '@angular/core'; import { DefaultRequest } from '../models/default-request.model' import { Observable } from 'rxjs'; import 'rxjs/add/operator/map' import 'rxjs/add/operator/catch'; import { CookieService } fr...
private getOptions(): RequestOptions { let headers; if (this.config.MOCK) { headers = new Headers({ 'Content-Type': 'application/json'}); }else{ headers = new Headers({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': "*" }); } let options = new RequestOptions({ heade...
{ let fullURL = this.config.API_URL if (this.config.MOCK) { fullURL = fullURL + data.sei; } console.info("Post: " + fullURL); let dataString = JSON.stringify(data); // Stringify console.info("Data:", dataString); console.info("Options", this.getOptions...
identifier_body
http-request.service.ts
import { Http, Headers, Response, RequestOptions } from '@angular/http'; import { Injectable, Inject } from '@angular/core'; import { DefaultRequest } from '../models/default-request.model' import { Observable } from 'rxjs'; import 'rxjs/add/operator/map' import 'rxjs/add/operator/catch'; import { CookieService } fr...
"string", "string", moduleName, endpoint, data ); } }
let cookie = this.cookieService.getObject(this.cookieName); console.log(cookie); return new DefaultRequest(
random_line_split
http-request.service.ts
import { Http, Headers, Response, RequestOptions } from '@angular/http'; import { Injectable, Inject } from '@angular/core'; import { DefaultRequest } from '../models/default-request.model' import { Observable } from 'rxjs'; import 'rxjs/add/operator/map' import 'rxjs/add/operator/catch'; import { CookieService } fr...
{ private cookieName: string = "test"; constructor(private http: Http, @Inject("Config") private config: any, private cookieService: CookieService) { } post(data: DefaultRequest): Observable<any> { let fullURL = this.config.API_URL if (this.config.MOCK) { full...
HttpRequest
identifier_name
http-request.service.ts
import { Http, Headers, Response, RequestOptions } from '@angular/http'; import { Injectable, Inject } from '@angular/core'; import { DefaultRequest } from '../models/default-request.model' import { Observable } from 'rxjs'; import 'rxjs/add/operator/map' import 'rxjs/add/operator/catch'; import { CookieService } fr...
console.info("Post: " + fullURL); let dataString = JSON.stringify(data); // Stringify console.info("Data:", dataString); console.info("Options", this.getOptions()); return this.http.post(fullURL, dataString, this.getOptions()) .map(this.extractData) .catc...
{ fullURL = fullURL + data.sei; }
conditional_block
tester.rs
iter::range(0, self.max_tests) { if ntests >= self.tests { break } let r = f.result(&mut self.gen); match r.status { Pass => ntests += 1, Discard => continue, Fail => return Err(r), } } ...
{ Pass, Fail, Discard } impl TestResult { /// Produces a test result that indicates the current test has passed. pub fn passed() -> TestResult { TestResult::from_bool(true) } /// Produces a test result that indicates the current test has failed. pub fn failed() -> TestResult { TestResult::from_bool(f...
Status
identifier_name
tester.rs
log messages for the `quickcheck` crate, then this will /// include output on how many QuickCheck tests were passed. /// /// # Example /// /// ```rust /// use quickcheck::QuickCheck; /// /// fn prop_reverse_reverse() { /// fn revrev(xs: Vec<uint>) -> bool { /// let r...
{ let f = *self; safe(proc() { f() }).result(g) }
identifier_body
tester.rs
iter::range(0, self.max_tests) { if ntests >= self.tests { break } let r = f.result(&mut self.gen); match r.status { Pass => ntests += 1, Discard => continue, Fail => return Err(r), } } ...
/// /// For functions, an implementation must generate random arguments /// and potentially shrink those arguments if they produce a failure. /// /// It's unlikely that you'll have to implement this trait yourself. /// This comes with a caveat: currently, only functions with 4 parameters /// or fewer (both `fn` and `|...
/// Anything that can be tested must be capable of producing a `TestResult` /// given a random number generator. This is trivial for types like `bool`, /// which are just converted to either a passing or failing test result.
random_line_split
CtrlDialogView.js
define(['backbone', 'marionette', 'mustache', 'jquery', 'text!templates/ctrldialog.html'], function(Backbone, Marionette, Mustache, $, template) { return Marionette.ItemView.extend({ initialize: function(options) { if (!options.icon_name) { options.icon_name ...
'tap @ui.close': 'onCancel' }, onOk: function(ev) { this.trigger('ok'); this.destroy(); }, onCancel: function(ev) { this.trigger('cancel'); this.destroy(); }, onRender:...
'tap @ui.cancel': 'onCancel',
random_line_split
CtrlDialogView.js
define(['backbone', 'marionette', 'mustache', 'jquery', 'text!templates/ctrldialog.html'], function(Backbone, Marionette, Mustache, $, template) { return Marionette.ItemView.extend({ initialize: function(options) { if (!options.icon_name) {
this.model = new Backbone.Model( options ); this.render(); }, template: function(serialized_model) { return Mustache.render(template, serialized_model); }, ui: { 'ok': '.btn-ok', 'cancel': '.b...
options.icon_name = 'bird'; }
conditional_block
sociallogin_interface.js
var options={}; options.login=true; LoginRadius_SocialLogin.util.ready(function () { $ui = LoginRadius_SocialLogin.lr_login_settings; $ui.interfacesize = Drupal.settings.lrsociallogin.interfacesize; $ui.lrinterfacebackground=Drupal.settings.lrsociallogin.lrinterfacebackground; $ui.noofcolumns= Drupal.settin...
var hiddenToken = document.createElement('input'); hiddenToken.type = 'hidden'; hiddenToken.value = token; hiddenToken.name = 'token'; form.appendChild(hiddenToken); document.body.appendChild(form); form.submit(); });
form.method = 'POST';
random_line_split
abiquo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' External inventory script for Abiquo ==================================== Shamelessly copied from an existing inventory script. This script generates an inventory that Ansible can understand by making API requests to Abiquo API Requires some python libraries, ensure ...
def get_cache(cache_item, config): ''' returns cached item ''' dpath = config.get('cache','cache_dir') inv = {} try: cache = open('/'.join([dpath,'inventory']), 'r') inv = cache.read() cache.close() except IOError as e: pass # not really sure what to do here ...
''' saves item to cache ''' dpath = config.get('cache','cache_dir') try: cache = open('/'.join([dpath,'inventory']), 'w') cache.write(json.dumps(data)) cache.close() except IOError as e: pass # not really sure what to do here
identifier_body
abiquo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' External inventory script for Abiquo ==================================== Shamelessly copied from an existing inventory script. This script generates an inventory that Ansible can understand by making API requests to Abiquo API Requires some python libraries, ensure ...
(enterprise_entity,config): try: inventory['all'] = {} inventory['all']['children'] = [] inventory['all']['hosts'] = [] inventory['_meta'] = {} inventory['_meta']['hostvars'] = {} enterprise = api_get(enterprise_entity,config) vms_entity = next(link for link ...
generate_inv_from_api
identifier_name
abiquo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' External inventory script for Abiquo ==================================== Shamelessly copied from an existing inventory script. This script generates an inventory that Ansible can understand by making API requests to Abiquo API Requires some python libraries, ensure ...
maxage = config.get('cache', 'cache_max_age') if ((int(time.time()) - int(existing.st_mtime)) <= int(maxage)): return True return False def generate_inv_from_api(enterprise_entity,config): try: inventory['all'] = {} inventory['all']['children'] = [] ...
random_line_split
abiquo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' External inventory script for Abiquo ==================================== Shamelessly copied from an existing inventory script. This script generates an inventory that Ansible can understand by making API requests to Abiquo API Requires some python libraries, ensure ...
if vm_template not in inventory: inventory[vm_template] = {} inventory[vm_template]['children'] = [] inventory[vm_template]['hosts'] = [] if config.getboolean('defaults', 'get_metadata') == True: meta_entity...
inventory[vm_vdc] = {} inventory[vm_vdc]['hosts'] = [] inventory[vm_vdc]['children'] = []
conditional_block
map.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
pub fn get(&self, key: &K) -> Result<V> where V: TryFrom<RetValue, Error = Error>, { let key = key.clone(); let oref: ObjectRef = map_get_item(self.object.clone(), key.upcast())?; oref.downcast() } } pub struct IntoIter<K, V> { // NB: due to FFI this isn't as lazy ...
{ let func = Function::get("node.Map").expect( "node.Map function is not registered, this is most likely a build or linking error", ); let map_data: ObjectPtr<Object> = func.invoke(data)?.try_into()?; debug_assert!( map_data.count() >= 1, "map_data c...
identifier_body
map.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
V: IsObjectRef, { type Error = Error; fn try_from(array: RetValue) -> Result<Map<K, V>> { let object_ref = array.try_into()?; // TODO: type check Ok(Map { object: object_ref, _data: PhantomData, }) } } #[cfg(test)] mod test { use std::collect...
K: IsObjectRef,
random_line_split
map.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
else { None } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { ((self.key_and_values.len() / 2) as usize, None) } } impl<K, V> IntoIterator for Map<K, V> where K: IsObjectRef, V: IsObjectRef, { type Item = (K, V); type IntoIter = IntoIter<K, V>; ...
{ let key = self .key_and_values .get(self.next_key as isize) .expect("this should always succeed"); let value = self .key_and_values .get((self.next_key as isize) + 1) .expect("this should always suc...
conditional_block
map.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
(&self, key: &K) -> Result<V> where V: TryFrom<RetValue, Error = Error>, { let key = key.clone(); let oref: ObjectRef = map_get_item(self.object.clone(), key.upcast())?; oref.downcast() } } pub struct IntoIter<K, V> { // NB: due to FFI this isn't as lazy as one might lik...
get
identifier_name
duration.pipe.ts
import * as moment from 'moment'; import { Inject, Optional, Pipe, PipeTransform } from '@angular/core'; import { NGX_MOMENT_OPTIONS, NgxMomentOptions } from './moment-options'; @Pipe({ name: 'amDuration' }) export class DurationPipe implements PipeTransform { allowedUnits: Array<string> = ['ss', 's', 'm', 'h', 'd'...
(value: moment.DurationInputArg1, ...args: string[]): string { if (typeof args === 'undefined' || args.length !== 1) { throw new Error('DurationPipe: missing required time unit argument'); } return moment.duration(value, args[0] as moment.unitOfTime.DurationConstructor).humanize(); } private _app...
transform
identifier_name
duration.pipe.ts
import * as moment from 'moment'; import { Inject, Optional, Pipe, PipeTransform } from '@angular/core'; import { NGX_MOMENT_OPTIONS, NgxMomentOptions } from './moment-options'; @Pipe({ name: 'amDuration' }) export class DurationPipe implements PipeTransform { allowedUnits: Array<string> = ['ss', 's', 'm', 'h', 'd'...
}
{ if (!momentOptions) { return; } if (!!momentOptions.relativeTimeThresholdOptions) { const units: Array<string> = Object.keys(momentOptions.relativeTimeThresholdOptions); const filteredUnits: Array<string> = units.filter( (unit) => this.allowedUnits.indexOf(unit) !== -1, );...
identifier_body
duration.pipe.ts
import * as moment from 'moment'; import { Inject, Optional, Pipe, PipeTransform } from '@angular/core'; import { NGX_MOMENT_OPTIONS, NgxMomentOptions } from './moment-options'; @Pipe({ name: 'amDuration' }) export class DurationPipe implements PipeTransform { allowedUnits: Array<string> = ['ss', 's', 'm', 'h', 'd'...
if (!momentOptions) { return; } if (!!momentOptions.relativeTimeThresholdOptions) { const units: Array<string> = Object.keys(momentOptions.relativeTimeThresholdOptions); const filteredUnits: Array<string> = units.filter( (unit) => this.allowedUnits.indexOf(unit) !== -1, ); ...
private _applyOptions(momentOptions: NgxMomentOptions): void {
random_line_split
duration.pipe.ts
import * as moment from 'moment'; import { Inject, Optional, Pipe, PipeTransform } from '@angular/core'; import { NGX_MOMENT_OPTIONS, NgxMomentOptions } from './moment-options'; @Pipe({ name: 'amDuration' }) export class DurationPipe implements PipeTransform { allowedUnits: Array<string> = ['ss', 's', 'm', 'h', 'd'...
return moment.duration(value, args[0] as moment.unitOfTime.DurationConstructor).humanize(); } private _applyOptions(momentOptions: NgxMomentOptions): void { if (!momentOptions) { return; } if (!!momentOptions.relativeTimeThresholdOptions) { const units: Array<string> = Object.keys(mom...
{ throw new Error('DurationPipe: missing required time unit argument'); }
conditional_block
settings.py
""" Django settings for librarymanagementsystem project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(B...
LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_DIRS = ( os.path.join(BASE_DIR, 'static')...
} # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/
random_line_split
test_cmdline.py
# pyOCD debugger # Copyright (c) 2015,2018-2019 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
def test_noncasesense(self): # Test separate paths for with and without a value. assert convert_session_options(['AUTO_Unlock']) == {'auto_unlock': True} assert convert_session_options(['AUTO_Unlock=0']) == {'auto_unlock': False} def test_int(self): # Non-bool with no v...
random_line_split
test_cmdline.py
# pyOCD debugger # Copyright (c) 2015,2018-2019 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
def test_all_b(self): assert convert_vector_catch(b'all') == Target.VectorCatch.ALL @pytest.mark.parametrize(("vc", "msk"), list(VECTOR_CATCH_CHAR_MAP.items())) def test_vc_str(self, vc, msk): assert convert_vector_catch(vc) == msk @pytest.mark.parametrize(("vc", "msk"), ...
assert convert_vector_catch(b'none') == 0
identifier_body
test_cmdline.py
# pyOCD debugger # Copyright (c) 2015,2018-2019 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
(self): # Non-bool with no value is ignored (and logged). assert convert_session_options(['frequency']) == {} # Invalid int value is ignored and logged assert convert_session_options(['frequency=abc']) == {} # Ignore with no- prefix assert convert_session_options(['no-fre...
test_int
identifier_name
network-task.js
'use strict'; /** * Expose 'NetworkTask' */ module.exports = NetworkTask; /** * Module dependencies */ var networkObject = require('./network-object'); var readLine = require('readline'); var childProcess = require('child_process'); /** * Constants */ var NETWORK_TOPIC = 'monitor/network'; /** * Constructo...
(){ var result={}; var availableInterfaces=[]; var returnObject = childProcess.spawnSync('ifconfig', ['-a']); if(returnObject.stdout){ var displayStr = returnObject.stdout.toString().trim().toLowerCase(); if(displayStr){ var ifSplit = displayStr.split('\n'); if(ifSplit){ //declare a point ar...
getNetworkInterfacesLinux
identifier_name
network-task.js
'use strict'; /** * Expose 'NetworkTask' */ module.exports = NetworkTask; /** * Module dependencies */ var networkObject = require('./network-object'); var readLine = require('readline'); var childProcess = require('child_process'); /** * Constants */ var NETWORK_TOPIC = 'monitor/network'; /** * Constructo...
} } //lets save the last interface if(currInterface.iname){ availableInterfaces.push(currInterface); } } } } //currently only returns the first active link - if there are multiple //interfaces active, we will probably need to handle multiple if(availableInterfaces.length > 0)...
{ var ipBlockSplit = temp.split(' '); if(ipBlockSplit.length >= 2){ //take the second entry var ipSplit=ipBlockSplit[1].split(':'); if(ipSplit.length >= 2){ currInterface.ip=ipSplit[1].trim(); //if both ip and mac exist if(currInterface....
conditional_block
network-task.js
'use strict'; /** * Expose 'NetworkTask' */ module.exports = NetworkTask; /** * Module dependencies */ var networkObject = require('./network-object'); var readLine = require('readline'); var childProcess = require('child_process'); /** * Constants */ var NETWORK_TOPIC = 'monitor/network'; /** * Constructo...
/** * Class Methods */ NetworkTask.prototype.runAndParse = function(callback){ if(this.generalInfo){ //run the command, parse the command, return a result console.log('running network command'); //make sure this is a new instance everytime this.noInstance = new networkObject(this.generalInfo.thingId); ...
{ this.noInstance = null; this.generalInfo = info; }
identifier_body
network-task.js
'use strict'; /** * Expose 'NetworkTask' */ module.exports = NetworkTask; /** * Module dependencies */ var networkObject = require('./network-object'); var readLine = require('readline'); var childProcess = require('child_process'); /** * Constants */ var NETWORK_TOPIC = 'monitor/network'; /** * Constructo...
if(macSplit.length==3){ macAddr = macSplit[2]; } //create a new interface and point current to this one var tempInterface = {}; tempInterface.iname=iName; if(macAddr){ tempInterface.mac=macAddr; } currInterface = tempInterface; ...
var macAddr=''; //lets get the macaddr var macSplit = interfaceSplit[1].trim().split(' ');
random_line_split
base.py
from couchpotato.core.event import addEvent from couchpotato.core.helpers.variable import tryFloat from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env from urlparse import urlparse import re import time log = CPLog(__name__) class Provid...
def parseSize(self, size): sizeRaw = size.lower() size = tryFloat(re.sub(r'[^0-9.]', '', size).strip()) for s in self.sizeGb: if s in sizeRaw: return size * 1024 for s in self.sizeMb: if s in sizeRaw: return size f...
try: if provider and provider == self.getName(): return self hostname = urlparse(url).hostname if host and hostname in host: return self else: for url_type in self.urls: download_url = self.urls[url_type...
identifier_body
base.py
from couchpotato.core.event import addEvent from couchpotato.core.helpers.variable import tryFloat from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env from urlparse import urlparse import re import time log = CPLog(__name__) class Provid...
(self, url, provider = None, host = None): try: if provider and provider == self.getName(): return self hostname = urlparse(url).hostname if host and hostname in host: return self else: for url_type in self.urls: ...
belongsTo
identifier_name
base.py
from couchpotato.core.event import addEvent from couchpotato.core.helpers.variable import tryFloat from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env from urlparse import urlparse import re import time log = CPLog(__name__) class Provid...
if provider and provider == self.getName(): return self hostname = urlparse(url).hostname if host and hostname in host: return self else: for url_type in self.urls: download_url = self.urls[url_type] ...
def search(self, movie, quality): return [] def belongsTo(self, url, provider = None, host = None): try:
random_line_split
base.py
from couchpotato.core.event import addEvent from couchpotato.core.helpers.variable import tryFloat from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env from urlparse import urlparse import re import time log = CPLog(__name__) class Provid...
hostname = urlparse(url).hostname if host and hostname in host: return self else: for url_type in self.urls: download_url = self.urls[url_type] if hostname in download_url: return self ...
return self
conditional_block
dialog_presenter.py
from __future__ import absolute_import, print_function from .presenter_base import AlgorithmProgressPresenterBase class AlgorithmProgressDialogPresenter(AlgorithmProgressPresenterBase): """ Presents progress reports on algorithms. """ def __init__(self, view, model): super(AlgorithmProgressDi...
def update(self): """ Update the gui asynchronously. """ self.need_update_gui.emit() def close(self): """ Close the dialog. """ self.model.remove_presenter(self) self.progress_bars.clear() self.view.close() def cancel_algori...
self.need_update_progress_bar.emit(progress_bar, progress, message)
conditional_block
dialog_presenter.py
from __future__ import absolute_import, print_function from .presenter_base import AlgorithmProgressPresenterBase class
(AlgorithmProgressPresenterBase): """ Presents progress reports on algorithms. """ def __init__(self, view, model): super(AlgorithmProgressDialogPresenter, self).__init__() view.close_button.clicked.connect(self.close) self.view = view self.model = model self.mode...
AlgorithmProgressDialogPresenter
identifier_name
dialog_presenter.py
from __future__ import absolute_import, print_function from .presenter_base import AlgorithmProgressPresenterBase class AlgorithmProgressDialogPresenter(AlgorithmProgressPresenterBase): """ Presents progress reports on algorithms. """
super(AlgorithmProgressDialogPresenter, self).__init__() view.close_button.clicked.connect(self.close) self.view = view self.model = model self.model.add_presenter(self) self.progress_bars = {} def update_gui(self): """ Update the gui elements. ...
def __init__(self, view, model):
random_line_split
dialog_presenter.py
from __future__ import absolute_import, print_function from .presenter_base import AlgorithmProgressPresenterBase class AlgorithmProgressDialogPresenter(AlgorithmProgressPresenterBase): """ Presents progress reports on algorithms. """ def __init__(self, view, model): super(AlgorithmProgressDi...
def add_progress_bar(self, algorithm_id, progress_bar): """ Store the mapping between the algorithm and its progress bar. :param algorithm_id: An id of an algorithm. :param progress_bar: QProgressBar widget. """ self.progress_bars[algorithm_id] = progress_bar d...
""" Update the gui elements. """ self.progress_bars.clear() algorithm_data = self.model.get_running_algorithm_data() self.view.update(algorithm_data)
identifier_body
testes_notificacao.py
# coding=utf-8 # --------------------------------------------------------------- # Desenvolvedor: Arannã Sousa Santos # Mês: 12 # Ano: 2015 # Projeto: pagseguro_xml # e-mail: asousas@live.com # --------------------------------------------------------------- import loggin...
if ok: print u'-' * 50 print retorno.xml print u'-' * 50 for a in retorno.alertas: print a else: print u'Motivo do erro:', retorno
ok, retorno = api.consulta_notificacao_transacao_v3(PAGSEGURO_API_EMAIL, PAGSEGURO_API_TOKEN, CHAVE_NOTIFICACAO)
random_line_split
testes_notificacao.py
# coding=utf-8 # --------------------------------------------------------------- # Desenvolvedor: Arannã Sousa Santos # Mês: 12 # Ano: 2015 # Projeto: pagseguro_xml # e-mail: asousas@live.com # --------------------------------------------------------------- import loggin...
nt u'Motivo do erro:', retorno
conditional_block
mid-path-type-params.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 ...
<U>(x: isize, _: U) -> S2 { S2 { contents: x, } } } pub fn main() { let _ = S::<isize>::new::<f64>(1, 1.0); let _: S2 = Trait::<isize>::new::<f64>(1, 1.0); }
new
identifier_name
mid-path-type-params.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 ...
impl<T> S<T> { fn new<U>(x: T, _: U) -> S<T> { S { contents: x, } } } trait Trait<T> { fn new<U>(x: T, y: U) -> Self; } struct S2 { contents: isize, } impl Trait<isize> for S2 { fn new<U>(x: isize, _: U) -> S2 { S2 { contents: x, } } } ...
}
random_line_split
spawn.ts
import { addProcess, getProcessById } from "../../kernel/kernel/kernel"; import Process = require("../../kernel/kernel/process"); import { ProcessPriority } from "../constants"; interface CreepRequest { pid: number; creepID: string; bodyParts: bodyMap; priority: number; } class SpawnProcess extends Proc...
const creepName = spawn.createCreep(body); process.receiveCreep(request.creepID, Game.creeps[creepName]); } } } return 0; } private findFreeSpawn(roomName: string) { const spawns = _.filter(Game.spawns, fun...
if (spawn) { const body = makeBody(request.bodyParts); const canSpawn = spawn.canCreateCreep(body); if (canSpawn === OK) { const process: any = getProcessById(request.pid);
random_line_split
spawn.ts
import { addProcess, getProcessById } from "../../kernel/kernel/kernel"; import Process = require("../../kernel/kernel/process"); import { ProcessPriority } from "../constants"; interface CreepRequest { pid: number; creepID: string; bodyParts: bodyMap; priority: number; } class SpawnProcess extends Proc...
; } export = SpawnProcess;
{ const spawns = _.filter(Game.spawns, function(spawn) { return spawn.room.name === roomName && spawn.spawning == null && spawn.canCreateCreep([MOVE]) === OK && spawn.isActive(); }); if (spawns.length > 0...
identifier_body
spawn.ts
import { addProcess, getProcessById } from "../../kernel/kernel/kernel"; import Process = require("../../kernel/kernel/process"); import { ProcessPriority } from "../constants"; interface CreepRequest { pid: number; creepID: string; bodyParts: bodyMap; priority: number; } class SpawnProcess extends Proc...
(roomName: string, parentPID: number) { let p = new SpawnProcess(0, parentPID); p = addProcess(p, ProcessPriority.TiclyLast); p.memory.roomName = roomName; return p; } public classPath() { return "components.processes.room.spawn"; } public getRoomName() { ...
start
identifier_name
c-stack-returning-int64.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 ...
s.with_c_str(|x| unsafe { libc::atoll(x) as i64 }) } pub fn main() { assert_eq!(atol(~"1024") * 10, atol(~"10240")); assert!((atoll(~"11111111111111111") * 10) == atoll(~"111111111111111110")); }
} #[fixed_stack_segment] fn atoll(s: ~str) -> i64 {
random_line_split
c-stack-returning-int64.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 ...
(s: ~str) -> i64 { s.with_c_str(|x| unsafe { libc::atoll(x) as i64 }) } pub fn main() { assert_eq!(atol(~"1024") * 10, atol(~"10240")); assert!((atoll(~"11111111111111111") * 10) == atoll(~"111111111111111110")); }
atoll
identifier_name
c-stack-returning-int64.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 ...
#[fixed_stack_segment] fn atoll(s: ~str) -> i64 { s.with_c_str(|x| unsafe { libc::atoll(x) as i64 }) } pub fn main() { assert_eq!(atol(~"1024") * 10, atol(~"10240")); assert!((atoll(~"11111111111111111") * 10) == atoll(~"111111111111111110")); }
{ s.with_c_str(|x| unsafe { libc::atol(x) as int }) }
identifier_body
core.js
"use strict"; (function (socket_path, thread_id) { var socket = io(socket_path) , thread_id = 6 , commentLists = [] , commentBox; socket.emit('comment/list', {thread_id: thread_id}); socket.on('user', function (user) { var comments = []; var submitCallback = function (replyTo, body) { ...
}; var renderList = function (list) { commentBox = React.renderComponent( CommentBox({ key: 'CommentBox', user: user, getRepliesCallback: getRepliesCallback, likeCallback: likeCallback, submitCallback: submitCallback, initialCommentLists...
}
random_line_split
core.js
"use strict"; (function (socket_path, thread_id) { var socket = io(socket_path) , thread_id = 6 , commentLists = [] , commentBox; socket.emit('comment/list', {thread_id: thread_id}); socket.on('user', function (user) { var comments = []; var submitCallback = function (replyTo, body) { ...
// Delete all list after the list matching commentReplyId for (var id in commentLists) { // If the id matches the commentReplyId then all loops going // forward will delete the lists if (id === commentReplyId) { commentLists.length = parseInt(id) + 1; break; ...
{ reset = true; }
conditional_block
htmldataelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLDataElementBinding; use crate::dom::bindings::codegen::Bindings:...
pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLDataElement> { Node::reflect_node( Box::new(HTMLDataElement::new_inherited(local_name, prefix, document)), document, HTMLDataElementBinding::Wrap, ...
} #[allow(unrooted_must_root)]
random_line_split
htmldataelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLDataElementBinding; use crate::dom::bindings::codegen::Bindings:...
{ htmlelement: HTMLElement, } impl HTMLDataElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLDataElement { HTMLDataElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } ...
HTMLDataElement
identifier_name
mainThreadService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return winners[Math.floor(Math.random() * winners.length)]; } let scramble = 0; if (this._affinityScrambler.hasOwnProperty(obj.getId())) { scramble = this._affinityScrambler[obj.getId()]; } else { scramble = Math.floor(Math.random() * this._workerPool.length); this._affinityScrambler[obj.getId()] =...
random_line_split
mainThreadService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return winners[Math.floor(Math.random() * winners.length)]; } let scramble = 0; if (this._affinityScrambler.hasOwnProperty(obj.getId())) { scramble = this._affinityScrambler[obj.getId()]; } else { scramble = Math.floor(Math.random() * this._workerPool.length); this._affinityScrambler[obj.getId()]...
{ let queueSize = this._workerPool[i].getQueueSize(); if (queueSize < winnersQueueSize) { winnersQueueSize = queueSize; winners = [i]; } else if (queueSize === winnersQueueSize) { winners.push(i); } }
conditional_block
mainThreadService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
scramble = this._affinityScrambler[obj.getId()]; } else { scramble = Math.floor(Math.random() * this._workerPool.length); this._affinityScrambler[obj.getId()] = scramble; } return (scramble + affinity) % this._workerPool.length; } OneWorker(obj: IThreadSynchronizableObject, methodName: string, targe...
{ if (affinity === ThreadAffinity.None) { let winners: number[] = [0], winnersQueueSize = this._workerPool[0].getQueueSize(); for (let i = 1; i < this._workerPool.length; i++) { let queueSize = this._workerPool[i].getQueueSize(); if (queueSize < winnersQueueSize) { winnersQueueSize = queueSize...
identifier_body
mainThreadService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(whichWorker: ThreadAffinity): remote.IProxyHelper { return { callOnRemote: (proxyId: string, path: string, args: any[]): TPromise<any> => { return this._callOnWorker(whichWorker, proxyId, path, args); } }; } private _callOnWorker(whichWorker: ThreadAffinity, proxyId: string, path: string, args: any[])...
_createWorkerProxyHelper
identifier_name
my.js
/* this is all example code which should be changed; see query.js for how it works */ authUrl = "http://importio-signedserver.herokuapp.com/"; reEx.push(/\/_source$/); /* //change doReady() to auto-query on document ready var doReadyOrg = doReady; doReady = function() { doReadyOrg(); doQuery();//query on ready } ...
var dataCompleteCallback = function(data, term) { console.log("Data received", data); for (var i = 0; i < data.length; i++) { var d = data[i]; var c = d.data[acField]; if (typeof filterComplete === 'function') { c = filterComplete(c); } c = c.trim(); if (!c) { continue; } ...
{ doQueryMy(); var qObjComplete = jQuery.extend({}, qObj);//copy to new obj qObjComplete.maxPages = 1; importio.query(qObjComplete, { "data": function(data) { dataCompleteCallback(data, term); }, "done": function(data) { doneCompleteCallback(data, term); } } ); }
identifier_body
my.js
/* this is all example code which should be changed; see query.js for how it works */ authUrl = "http://importio-signedserver.herokuapp.com/"; reEx.push(/\/_source$/); /* //change doReady() to auto-query on document ready var doReadyOrg = doReady; doReady = function() { doReadyOrg(); doQuery();//query on ready } ...
]; var doQueryMy = function() { qObj.input = { "search": $("#title").val() }; } */ /* Here's some other example code for a completely different API colNames = ["ranking", "title", "artist", "album", "peak_pos", "last_pos", "weeks", "image", "spotify", "rdio", "video"]; filters["title"] = function(val, row) { ...
return '<a href="' + val + '" target="_blank">' + val + '</a>'; } qObj.connectorGuids = [ "ABC"
random_line_split
my.js
/* this is all example code which should be changed; see query.js for how it works */ authUrl = "http://importio-signedserver.herokuapp.com/"; reEx.push(/\/_source$/); /* //change doReady() to auto-query on document ready var doReadyOrg = doReady; doReady = function() { doReadyOrg(); doQuery();//query on ready } ...
(term) { doQueryMy(); var qObjComplete = jQuery.extend({}, qObj);//copy to new obj qObjComplete.maxPages = 1; importio.query(qObjComplete, { "data": function(data) { dataCompleteCallback(data, term); }, "done": function(data) { doneCompleteCallback(data, term); } } ...
doComplete
identifier_name
workfile.rs
use std; use std::io; use std::io::prelude::*; use std::fs::File; use std::io::{Error, ErrorKind}; // Helps creating a working file and move the working file // to the final file when done, or automatically delete the // working file in case of error. pub struct
{ file_path: String, work_file_path: String, file: Option<File> } impl WorkFile { pub fn create(file_path: &str) -> io::Result<WorkFile> { let work_file_path: String = format!("{}.work", file_path); let file = match File::create(&work_file_path) { Ok(file) => file, Err(err) => { return Err(err); } }; ...
WorkFile
identifier_name
workfile.rs
use std; use std::io; use std::io::prelude::*; use std::fs::File; use std::io::{Error, ErrorKind}; // Helps creating a working file and move the working file // to the final file when done, or automatically delete the // working file in case of error. pub struct WorkFile { file_path: String, work_file_path: String, ...
}
{ if self.file.is_some() { drop(self.file.take()); match std::fs::remove_file(&self.work_file_path) { Ok(_) => (), Err(err) => panic!("rollback failed: {}", err) } } }
identifier_body
workfile.rs
use std; use std::io; use std::io::prelude::*; use std::fs::File;
// Helps creating a working file and move the working file // to the final file when done, or automatically delete the // working file in case of error. pub struct WorkFile { file_path: String, work_file_path: String, file: Option<File> } impl WorkFile { pub fn create(file_path: &str) -> io::Result<WorkFile> { l...
use std::io::{Error, ErrorKind};
random_line_split
PatternResolver.ts
import template = require("es6-template-string"); import { dirname, parse, relative } from "upath"; import { Progress, TextDocument } from "vscode"; import { ConversionType } from "../../Conversion/ConversionType"; import { Resources } from "../../Properties/Resources"; import { IProgressState } from "../Tasks/IProgres...
{ template(pattern, context); } catch { variables.push(key); } context[key as keyof IPatternContext] = ""; } this.variables = variables; } /** * Gets the pattern to resolve. */ ...
{ let variables: Array<string | number | symbol> = []; this.pattern = pattern; this.reporter = reporter; let context: IPatternContext = { basename: "", extension: "", filename: "", dirname: "", workspaceFolder: "" }; ...
identifier_body
PatternResolver.ts
import template = require("es6-template-string"); import { dirname, parse, relative } from "upath"; import { Progress, TextDocument } from "vscode"; import { ConversionType } from "../../Conversion/ConversionType"; import { Resources } from "../../Properties/Resources"; import { IProgressState } from "../Tasks/IProgres...
(pattern: string, reporter?: Progress<IProgressState>) { let variables: Array<string | number | symbol> = []; this.pattern = pattern; this.reporter = reporter; let context: IPatternContext = { basename: "", extension: "", filename: "", ...
constructor
identifier_name
PatternResolver.ts
import template = require("es6-template-string"); import { dirname, parse, relative } from "upath"; import { Progress, TextDocument } from "vscode"; import { ConversionType } from "../../Conversion/ConversionType"; import { Resources } from "../../Properties/Resources"; import { IProgressState } from "../Tasks/IProgres...
/** * Initializes a new instance of the {@link PatternResolver `PatternResolver`} class. * * @param pattern * The pattern to resolve. * * @param reporter * A component for reporting progress. */ public constructor(pattern: string, reporter?: Progress<IProgressState>) ...
* The variables inside the pattern. */ private variables: Array<string | number | symbol>;
random_line_split
createContext.js
/*global define*/ define([ 'Core/clone', 'Core/defaultValue', 'Core/defined', 'Core/queryToObject', 'Renderer/Context', 'Specs/createCanvas', 'Specs/createFrameState' ], function( clone, defaultValue, defined, queryToObject, ...
(options, canvasWidth, canvasHeight) { // clone options so we can change properties options = clone(defaultValue(options, {})); options.webgl = clone(defaultValue(options.webgl, {})); options.webgl.alpha = defaultValue(options.webgl.alpha, true); options.webgl.antialias = default...
createContext
identifier_name
createContext.js
/*global define*/ define([ 'Core/clone', 'Core/defaultValue', 'Core/defined', 'Core/queryToObject', 'Renderer/Context', 'Specs/createCanvas', 'Specs/createFrameState' ], function( clone, defaultValue, defined, queryToObject, ...
return context; } return createContext; });
{ // clone options so we can change properties options = clone(defaultValue(options, {})); options.webgl = clone(defaultValue(options.webgl, {})); options.webgl.alpha = defaultValue(options.webgl.alpha, true); options.webgl.antialias = defaultValue(options.webgl.antialias, false)...
identifier_body
createContext.js
/*global define*/ define([ 'Core/clone', 'Core/defaultValue', 'Core/defined', 'Core/queryToObject', 'Renderer/Context', 'Specs/createCanvas', 'Specs/createFrameState' ], function( clone, defaultValue, defined, queryToObject, ...
options = clone(defaultValue(options, {})); options.webgl = clone(defaultValue(options.webgl, {})); options.webgl.alpha = defaultValue(options.webgl.alpha, true); options.webgl.antialias = defaultValue(options.webgl.antialias, false); var canvas = createCanvas(canvasWidth, canva...
function createContext(options, canvasWidth, canvasHeight) { // clone options so we can change properties
random_line_split
createContext.js
/*global define*/ define([ 'Core/clone', 'Core/defaultValue', 'Core/defined', 'Core/queryToObject', 'Renderer/Context', 'Specs/createCanvas', 'Specs/createFrameState' ], function( clone, defaultValue, defined, queryToObject, ...
var us = context.uniformState; us.update(context, createFrameState()); return context; } return createContext; });
{ context.validateShaderProgram = true; context.validateFramebuffer = true; context.logShaderCompilation = true; context.throwOnWebGLError = true; }
conditional_block
main.controller.js
import {Task} from '../components/tasks/tasks.service.js'; export class MainController { constructor ($interval, $log, tasksService, speechService) { 'ngInject'; const vm = this, currentTime = getPomodoroTime(); Object.assign(vm, { // timer timeLeft: formatTime(currentTime), ...
completePomodoro(){ this.activeTask.workedPomodoros++; this.stopPomodoro(); this.startRest(); } startRest(){ this.resting = true; this.setupRestTime(); this.setTimerInterval(getRestTime(this.activeTask)); } setTimerInterval(seconds){ //console.log('create interval...
{ this.performingTask = false; this.cleanInterval(); this.speechService.say('Stop! Time to rest and reflect!'); }
identifier_body