file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
test_user.py
from shuttl.tests import testbase from shuttl.Models.User import User, UserDataTakenException, NoOrganizationException, ToManyOrganizations from shuttl.Models.organization import Organization from shuttl.Models.Reseller import Reseller class
(testbase.BaseTest): def _setUp(self): self.reseller = Reseller(name ="test4", url="test2.com") self.reseller.save() pass def test_create(self): organization = Organization(name="Test", reseller=self.reseller) organization.save() organization = Organization.Get(...
UserTestCase
identifier_name
push.js
/* * Copyright (c) 2016, Two Sigma Open Source * 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 list of...
* - closed submodules with commits that need to be pushed * - submodules that do not exist in the `source` commit, but did previously * and need synthetic-meta-refs * - submodules with divergent histories, i.e., the commit we create the * synthetic-meta-ref for doesn't contain one or more commits that need to ...
* situations: *
random_line_split
push.js
/* * Copyright (c) 2016, Two Sigma Open Source * 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 list of...
else { baseTree = EMPTY_TREE; } const tree = yield commit.getTree(); const diff = yield NodeGit.Diff.treeToTree(repo, baseTree, tree, null); const changes = SubmoduleUtil.getSubmoduleChangesFromDiff(diff, true); const pushMap = {}; for (const path of Object.keys(changes)) { co...
{ baseTree = yield baseCommit.getTree(); }
conditional_block
server.js
var express = require('express'), app = express(), router = express.Router(), mongoose = require('mongoose'), bodyParser = require('body-parser'), morest = require('../src/morest').Morest; //Connect to your mongoDB database mongoose.connect('mongodb://127.0.0.1:27017/bears'); //Use bodyparser app....
BearController, HoneypotController, CaveController ] })); //Remove all old data mongoose.model('Bear').remove() .then(function () { return mongoose.model('Honeypot').remove(); }) .then(function () { return mongoose.model('Cave').remove(); }) //Prepare som...
random_line_split
next_v2.x.x.js
// flow-typed signature: f037cda650f1487eb396cefd7e64a025 // flow-typed version: 5bd730d605/next_v2.x.x/flow_>=v0.37.x declare module "next" { declare export type RequestHandler = ( req: http$IncomingMessage, res: http$ServerResponse, parsedUrl: any ) => Promise<void>; declare export type NextApp = {...
declare export var Head: Class<Component<void, *, *>>; declare export var Main: Class<Component<void, *, *>>; declare export var NextScript: Class<Component<void, *, *>>; declare export default Class<Component<void, *, *>> & { getInitialProps: (ctx: Context) => Promise<*>, renderPage(cb: Function): void...
err?: any };
random_line_split
train_left.py
#!/usr/bin/python ## Author: akshat ## Date: Dec, 3,2016 # trains the model from keras.models import model_from_json import load_data import numpy import matplotlib.pyplot as plt import time # load json model json_file = open('model.json', 'r') loaded_model = json_file.read() json_file.close() model = model_from_json...
trainPredict = numpy.expand_dims(trainPredict, axis = 1) # estimate model performance trainScore = model.evaluate(x_train, y_train, verbose=2) print 'Train Score: ', trainScore # shift train predictions for plotting trainPredictPlot = numpy.empty_like(y_train_data) trainPredictPlot[:, :] = numpy.nan trainPredictPlo...
trainPredict = numpy.empty([0]) for j in range(load_data.len_train_samples/batch_size): x_train, y_train = load_data.loadTrainData(batch_size, 'left') history = model.fit(x_train, y_train, nb_epoch = 1, verbose = 2) trainPredict = numpy.append(trainPredict, model.predict(x_train)) pr...
conditional_block
train_left.py
#!/usr/bin/python ## Author: akshat ## Date: Dec, 3,2016 # trains the model from keras.models import model_from_json import load_data import numpy import matplotlib.pyplot as plt import time # load json model json_file = open('model.json', 'r') loaded_model = json_file.read() json_file.close() model = model_from_json...
print("Saved weights to disk")
# get time stamp timestr = time.strftime("%Y%m%d-%H%M%S") # serialize weights to HDF5 model.save_weights("weights-left-" + timestr + ".h5")
random_line_split
compare_shuffled.py
import sys q_to_time = {} i = 0 for line in open(sys.argv[1]): try: line = line.strip() cols = line.split('\t') q_to_time[cols[0]] = [(int(cols[2].split(' ')[0]), i)] i += 1 except ValueError: continue i = 0 for line in open(sys.argv[2]): try: line = line.s...
except: print('problem with : ' + k + ' ' + str(larger) + ' ' + str(smaller))
random_line_split
compare_shuffled.py
import sys q_to_time = {} i = 0 for line in open(sys.argv[1]):
i = 0 for line in open(sys.argv[2]): try: line = line.strip() cols = line.split('\t') q_to_time[cols[0]].append((int(cols[2].split(' ')[0]), i)) i += 1 except KeyError: continue except ValueError: continue for k,v in q_to_time.items(): if v[0][0] < ...
try: line = line.strip() cols = line.split('\t') q_to_time[cols[0]] = [(int(cols[2].split(' ')[0]), i)] i += 1 except ValueError: continue
conditional_block
rec-align-u64.rs
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
#[cfg(target_os = "android")] mod m { #[cfg(target_arch = "arm")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } pub fn main() { unsafe { let x = Outer {c8: 22u8, t: Inner {c64: 44u64}}; let y = format!("{:?}", x); println!("align i...
pub fn size() -> uint { 16u } } }
random_line_split
rec-align-u64.rs
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() -> uint { 16u } } #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } #[cfg(target_os = "android")] mod m { #[cfg(target_arch = "arm")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16...
size
identifier_name
decorators.py
""" Decorators """ from __future__ import unicode_literals from functools import wraps from django.http import HttpResponseBadRequest from django.utils.decorators import available_attrs from django_ajax.shortcuts import render_to_json def ajax(function=None, mandatory=True, **ajax_kwargs): """ Decorator wh...
@ajax def my_view(request): return redirect('home') # will send {'status': 302, 'statusText': 'FOUND', 'content': '/'} # combination with others decorators: @ajax @login_required @require_POST def my_view(request): pass ...
def my_view(request): return HttpResponse('<h1>Hi!</h1>') # will send {'status': 200, 'statusText': 'OK', 'content': '<h1>Hi!</h1>'}
random_line_split
decorators.py
""" Decorators """ from __future__ import unicode_literals from functools import wraps from django.http import HttpResponseBadRequest from django.utils.decorators import available_attrs from django_ajax.shortcuts import render_to_json def ajax(function=None, mandatory=True, **ajax_kwargs): """ Decorator wh...
return inner if function: return decorator(function) return decorator
return func(request, *args, **kwargs)
conditional_block
decorators.py
""" Decorators """ from __future__ import unicode_literals from functools import wraps from django.http import HttpResponseBadRequest from django.utils.decorators import available_attrs from django_ajax.shortcuts import render_to_json def
(function=None, mandatory=True, **ajax_kwargs): """ Decorator who guesses the user response type and translates to a serialized JSON response. Usage:: @ajax def my_view(request): do_something() # will send {'status': 200, 'statusText': 'OK', 'content': null} ...
ajax
identifier_name
decorators.py
""" Decorators """ from __future__ import unicode_literals from functools import wraps from django.http import HttpResponseBadRequest from django.utils.decorators import available_attrs from django_ajax.shortcuts import render_to_json def ajax(function=None, mandatory=True, **ajax_kwargs): """ Decorator wh...
return inner if function: return decorator(function) return decorator
if mandatory and not request.is_ajax(): return HttpResponseBadRequest() if request.is_ajax(): # return json response try: return render_to_json(func(request, *args, **kwargs), **ajax_kwargs) except Exception as exception: ...
identifier_body
push.py
#!/usr/bin/env python """ $push is similar to $addToSet. The difference is that rather than accumulating only unique values it aggregates all values into an array. Using an aggregation query, count the number of tweets for each user. In the same $group stage, use $push to accumulate all the tweet texts for each user...
Please note that the dataset you are using here is a smaller version of the twitter dataset used in examples in this lesson. If you attempt some of the same queries that we looked at in the lesson examples, your results will be different. """ def get_db(db_name): from pymongo import MongoClient client = Mon...
random_line_split
push.py
#!/usr/bin/env python """ $push is similar to $addToSet. The difference is that rather than accumulating only unique values it aggregates all values into an array. Using an aggregation query, count the number of tweets for each user. In the same $group stage, use $push to accumulate all the tweet texts for each user...
def make_pipeline(): # complete the aggregation pipeline ''' pipeline = [ {"$unwind" : "$entities.hashtags"}, {"$group" : {"_id" : "$user.screen_name", "unique_hashtags" : { "$addToSet" : "$entities.hashtags.text" }}}, ...
from pymongo import MongoClient client = MongoClient('localhost:27017') db = client[db_name] return db
identifier_body
push.py
#!/usr/bin/env python """ $push is similar to $addToSet. The difference is that rather than accumulating only unique values it aggregates all values into an array. Using an aggregation query, count the number of tweets for each user. In the same $group stage, use $push to accumulate all the tweet texts for each user...
db = get_db('twitter') pipeline = make_pipeline() result = aggregate(db, pipeline) assert len(result["result"]) == 5 assert result["result"][0]["count"] > result["result"][4]["count"] import pprint pprint.pprint(result)
conditional_block
push.py
#!/usr/bin/env python """ $push is similar to $addToSet. The difference is that rather than accumulating only unique values it aggregates all values into an array. Using an aggregation query, count the number of tweets for each user. In the same $group stage, use $push to accumulate all the tweet texts for each user...
(db_name): from pymongo import MongoClient client = MongoClient('localhost:27017') db = client[db_name] return db def make_pipeline(): # complete the aggregation pipeline ''' pipeline = [ {"$unwind" : "$entities.hashtags"}, {"$group" : {"_id" : "$user.screen_name", ...
get_db
identifier_name
app.js
var express = require('express');//加载express var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan');//加载morgan,主要功能是在控制台中,显示req请求的信息 var cookieParser = require('cookie-parser');//支持cookie var bodyParser = require('body-parser'); var ejs = require('ejs'); var util = require('...
var restResult = new RestResult(); restResult.errorCode = errorCode; restResult.errorReason = errorReason; res.send(restResult); }; res.success = function (returnValue) { var restResult = new RestResult(); restResult.errorCode = RestResult.NO_ERROR; restR...
//app访问预处理中间件 app.use(function (req, res, next) { res.error = function (errorCode, errorReason) {
random_line_split
app.js
var express = require('express');//加载express var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan');//加载morgan,主要功能是在控制台中,显示req请求的信息 var cookieParser = require('cookie-parser');//支持cookie var bodyParser = require('body-parser'); var ejs = require('ejs'); var util = require('...
ken))) { var timestamp = result.timestamp; //todo 如果对token的时间有限制,可以在这里做处理 var userId = result.userId; UserEntity.findById(userId, '_id', function (err, user) { if (!user) { res.error(RestResult.AUTH_ERROR_CODE, "用户不存在"); ...
ar result; if (myUtils.StringUtils.isNotEmpty(token) && (result = tokenUtils.parseLoginAutoToken(to
conditional_block
grouped.ts
import { Chart } from '@antv/g2'; const data = [ { name: 'London', 月份: 'Jan.', 月均降雨量: 18.9 }, { name: 'London', 月份: 'Feb.', 月均降雨量: 28.8 }, { name: 'London', 月份: 'Mar.', 月均降雨量: 39.3 }, { name: 'London', 月份: 'Apr.', 月均降雨量: 81.4 }, { name: 'London', 月份: 'May', 月均降雨量: 47 }, { name: 'London', 月份: 'Jun.', 月均降雨量:...
const chart = new Chart({ container: 'container', autoFit: true, height: 500, }); chart.data(data); chart.scale('月均降雨量', { nice: true, }); chart.tooltip({ showMarkers: false, shared: true, }); chart .interval() .position('月份*月均降雨量') .color('name') .adjust([ { type: 'dodge', marginR...
];
random_line_split
FileAppender.js
define([ "../declare", "./_MixinFileAppender", "../fs/dfs", "../promise/sync", "dojo/Deferred", "../node!path" ], function (declare, _MixinFileAppender, dfs, sync, Deferred, path) { /** * This module is the class for elenajs logger. * Constructor accepts 'category' as parameter (de...
return { valid: validLogs, invalid: invalidLogs }; } }, { maxFileSize: { get: function () { return this._maxFileSize; }, set: function (va...
{ validLogs = logs; }
conditional_block
FileAppender.js
define([ "../declare", "./_MixinFileAppender", "../fs/dfs", "../promise/sync", "dojo/Deferred", "../node!path" ], function (declare, _MixinFileAppender, dfs, sync, Deferred, path) { /** * This module is the class for elenajs logger. * Constructor accepts 'category' as parameter (de...
break; case 'm': case 'M': this.maxFileSizeBytes = sz[1] * 1048576; break; case 'g': case 'G': ...
} else { switch (sz[2]) { case 'k': case 'K': this.maxFileSizeBytes = sz[1] * 1024;
random_line_split
create.component.ts
import { Component, ViewEncapsulation, ViewChild, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormBuilder, Validator, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { ManajementPemerintahService } from './../../../_serviceAdmin/manajemenPemerintah.service'; imp...
}) } back() { this.clearForm(); this.router.navigate(['admin/pemerintah']); } clearForm() { this.form.value.username = ''; this.form.value.email = ''; this.form.value.nama = ''; this.form.value.kode_pemerintahan = ''; this.form.value...
{ this.dataservice.showMessageSuccess(data.message); this.clearForm(); this.router.navigate(['admin/pemerintah']); }
conditional_block
create.component.ts
import { Component, ViewEncapsulation, ViewChild, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormBuilder, Validator, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { ManajementPemerintahService } from './../../../_serviceAdmin/manajemenPemerintah.service'; imp...
() { if(this.form.value.kode_pemerintahan != 0) { this.dataservice.getDataProvinsi() .subscribe(data => { this.provinsion = true; this.provinsis = data.data; }); } else { this.selected = { id: 0, ...
getprovinsi
identifier_name
create.component.ts
import { Component, ViewEncapsulation, ViewChild, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormBuilder, Validator, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { ManajementPemerintahService } from './../../../_serviceAdmin/manajemenPemerintah.service'; imp...
back() { this.clearForm(); this.router.navigate(['admin/pemerintah']); } clearForm() { this.form.value.username = ''; this.form.value.email = ''; this.form.value.nama = ''; this.form.value.kode_pemerintahan = ''; this.form.value.provinsi = ''; ...
{ this.data = { username: this.form.value.username, email: this.form.value.email, name: this.form.value.name, kode_pemerintahan: this.form.value.kode_pemerintahan, role: 2, fk_lokasiid: this.selected.id, nama_lokasi: this.select...
identifier_body
create.component.ts
import { Component, ViewEncapsulation, ViewChild, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormBuilder, Validator, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { ManajementPemerintahService } from './../../../_serviceAdmin/manajemenPemerintah.service'; imp...
email: ['', Validators.required], name: ['', Validators.required], kode_pemerintahan: ['', Validators.required], role: '', provinsi: '', kabupaten: '', status: '' }); } getprovinsi() { if(this.form.value.kode_pe...
ngOnInit() { this.form = this._fb.group({ username: ['', Validators.required],
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
#[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod hash; pub mod invalidation; #[allow(missing_docs)] // TODO. pub mod logical_geometry; pub mod matching; pub mod media_queries; pub mod parallel; pub mod parser; pub mod rule_cac...
pub mod font_face; pub mod font_metrics;
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
}
{ match self { selectors::attr::CaseSensitivity::CaseSensitive => a == b, selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
(self, a: &WeakAtom, b: &WeakAtom) -> bool { match self { selectors::attr::CaseSensitivity::CaseSensitive => a == b, selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } } }
eq_atom
identifier_name
level-one.js
/****************************************/ /* Level One - Concatenation Exercises */ /****************************************/ /* Return a string that will add a "Hello" string in front of the name ie: sayHello("Jesse") => Hello Jesse sayHello("Mat") => Hello Mat */ function sayHello(name) { ...
{ }
identifier_body
level-one.js
/****************************************/ /* Level One - Concatenation Exercises */ /****************************************/ /* Return a string that will add a "Hello" string in front of the name ie: sayHello("Jesse") => Hello Jesse sayHello("Mat") => Hello Mat */ function sayHello(name) { ...
} /* Return a string that will display how many points a player made ie: playerStats("Steph Curry", 32") => Steph Curry made 32 points playerStats("Meghan", 12) => Meghan made 12 points */ function playerStats(player, points) { } /* Return a number that will be the total score in points ...
random_line_split
level-one.js
/****************************************/ /* Level One - Concatenation Exercises */ /****************************************/ /* Return a string that will add a "Hello" string in front of the name ie: sayHello("Jesse") => Hello Jesse sayHello("Mat") => Hello Mat */ function sayHello(name) { ...
(twoPointersMade, threePointersMade) { } /* Calculates the totalScore a player has made Then return a string that will display the total score a player made ie: playerStatsAdv("Steph Curry", 6, 7) => "Steph Curry made 33 points" playerStatsAdv("Meghan", 4, 2) => "Meghan made 14 points" */ fun...
calculateScore
identifier_name
task.ts
import { task as gulpTask, TaskFunction } from "gulp"; import { Options as ConfigOptions } from "../libs/config"; interface TaskErrorDefinition { taskName: string; error: unknown; done?: TaskCallback; } export interface Options { name?: string; settings: ConfigOptions; } export type TaskCallback = (error?...
}
} return `${base}:${step}`; }
random_line_split
task.ts
import { task as gulpTask, TaskFunction } from "gulp"; import { Options as ConfigOptions } from "../libs/config"; interface TaskErrorDefinition { taskName: string; error: unknown; done?: TaskCallback; } export interface Options { name?: string; settings: ConfigOptions; } export type TaskCallback = (error?...
return `${base}:${step}`; } }
{ return base; }
conditional_block
task.ts
import { task as gulpTask, TaskFunction } from "gulp"; import { Options as ConfigOptions } from "../libs/config"; interface TaskErrorDefinition { taskName: string; error: unknown; done?: TaskCallback; } export interface Options { name?: string; settings: ConfigOptions; } export type TaskCallback = (error?...
}
{ // eslint-disable-next-line @typescript-eslint/no-explicit-any const base: string = (this.constructor as any).taskName + (this._name ? `:${this._name}` : ""); if (!step) { return base; } return `${base}:${step}`; }
identifier_body
task.ts
import { task as gulpTask, TaskFunction } from "gulp"; import { Options as ConfigOptions } from "../libs/config"; interface TaskErrorDefinition { taskName: string; error: unknown; done?: TaskCallback; } export interface Options { name?: string; settings: ConfigOptions; } export type TaskCallback = (error?...
(options: Options) { this._name = options.name || ""; this._settings = options.settings || {}; } /** * Register task in Gulp. * * @param {string} step * @param {TaskFunction} task * @returns {string} * @protected */ protected _defineTask(step: string, task: TaskFunction): string { ...
constructor
identifier_name
calc.py
""" To start UNO for both Calc and Writer: (Note that if you use the current_document command, it will open the Calc's current document since it's the first switch passed) libreoffice "--accept=socket,host=localhost,port=18100;urp;StarOffice.ServiceManager" --norestore --nofirststartwizard --nologo --calc --writer To ...
(document): """[document].current_sheet()""" return document.getCurrentController().getActiveSheet() @staticmethod def save_as(document, path): """[document].save_as(['path'])""" url = systemPathToFileUrl(path) # Set file to overwrite property_value = Proper...
current_sheet
identifier_name
calc.py
""" To start UNO for both Calc and Writer: (Note that if you use the current_document command, it will open the Calc's current document since it's the first switch passed) libreoffice "--accept=socket,host=localhost,port=18100;urp;StarOffice.ServiceManager" --norestore --nofirststartwizard --nologo --calc --writer To ...
else: return False
cell.CharWeight = BOLD return True
conditional_block
calc.py
""" To start UNO for both Calc and Writer: (Note that if you use the current_document command, it will open the Calc's current document since it's the first switch passed) libreoffice "--accept=socket,host=localhost,port=18100;urp;StarOffice.ServiceManager" --norestore --nofirststartwizard --nologo --calc --writer To ...
"""current_document()""" return desktop.getCurrentComponent() @staticmethod def load_document(path): """load_document(['path'])""" url = systemPathToFileUrl(path) return desktop.loadComponentFromURL(url ,"_blank", 0, ()) @staticmethod def new_document(): ...
random_line_split
calc.py
""" To start UNO for both Calc and Writer: (Note that if you use the current_document command, it will open the Calc's current document since it's the first switch passed) libreoffice "--accept=socket,host=localhost,port=18100;urp;StarOffice.ServiceManager" --norestore --nofirststartwizard --nologo --calc --writer To ...
@staticmethod def new_document(): """new_document()""" return desktop.loadComponentFromURL("private:factory/scalc","_blank", 0, ()) @staticmethod def current_sheet(document): """[document].current_sheet()""" return document.getCurrentController().getActiveSheet() ...
"""load_document(['path'])""" url = systemPathToFileUrl(path) return desktop.loadComponentFromURL(url ,"_blank", 0, ())
identifier_body
vgng.py
#!/usr/bin/env python # # Translation of videogamena.me javascript to python # # http://videogamena.me/vgng.js # http://videogamena.me/video_game_names.txt # # (C) 2014 Dustin Knie <dustin@nulldomain.com> import argparse import os import random from math import floor, trunc _word_list_file = 'video_game_names.txt' _...
def generate_game_name(allow_similar_matches=False): words = [] bad_match_list = [] for word_list in _word_list: (words, bad_match_list) = _get_word(word_list, words=words, bad_match_list=bad_match_list, allow_similar_matches=allow_similar_matches) return ...
bad_word = True while bad_word: word = word_list[trunc(floor(random.random() * len(word_list)))] if '^' in word: if not allow_similar_matches: bad_match_list += word.split('^')[1].split('|') word = word.split('^')[0] if word in words or word in bad_ma...
identifier_body
vgng.py
#!/usr/bin/env python # # Translation of videogamena.me javascript to python # # http://videogamena.me/vgng.js # http://videogamena.me/video_game_names.txt # # (C) 2014 Dustin Knie <dustin@nulldomain.com> import argparse import os import random from math import floor, trunc _word_list_file = 'video_game_names.txt' _...
(allow_similar_matches=False): words = [] bad_match_list = [] for word_list in _word_list: (words, bad_match_list) = _get_word(word_list, words=words, bad_match_list=bad_match_list, allow_similar_matches=allow_similar_matches) return ' '.join(words) if __na...
generate_game_name
identifier_name
vgng.py
#!/usr/bin/env python # # Translation of videogamena.me javascript to python # # http://videogamena.me/vgng.js # http://videogamena.me/video_game_names.txt # # (C) 2014 Dustin Knie <dustin@nulldomain.com> import argparse import os import random from math import floor, trunc _word_list_file = 'video_game_names.txt' _...
_word_list.append(words) except IOError as e: print("Error opening {}: {}".format(word_list, e)) exit(1) def _get_word(word_list, words=[], bad_match_list=[], allow_similar_matches=False): bad_word = True while bad_word: word = word_list[trunc(floor(random.random() * len(w...
words.append(line)
random_line_split
vgng.py
#!/usr/bin/env python # # Translation of videogamena.me javascript to python # # http://videogamena.me/vgng.js # http://videogamena.me/video_game_names.txt # # (C) 2014 Dustin Knie <dustin@nulldomain.com> import argparse import os import random from math import floor, trunc _word_list_file = 'video_game_names.txt' _...
if word in words or word in bad_match_list: continue bad_word = False words.append(word) return (words, bad_match_list) def generate_game_name(allow_similar_matches=False): words = [] bad_match_list = [] for word_list in _word_list: (words, bad_match_list) =...
if not allow_similar_matches: bad_match_list += word.split('^')[1].split('|') word = word.split('^')[0]
conditional_block
api.ts
import { PassThrough } from 'stream'; import { S3 } from 'aws-sdk'; import * as bodyParser from 'body-parser'; import { MD5 } from 'crypto-js'; import { NextFunction, Request, Response, Router } from 'express'; import * as sendRequest from 'request-promise-native'; import { UserClient as UserClientType } from 'common/u...
(): Router { const router = PromiseRouter(); router.use(bodyParser.json()); router.use((request: Request, response: Response, next: NextFunction) => { this.metrics.countRequest(request); next(); }, authMiddleware); router.get('/metrics', (request: Request, response: Response) => { ...
getRouter
identifier_name
api.ts
import { PassThrough } from 'stream'; import { S3 } from 'aws-sdk'; import * as bodyParser from 'body-parser'; import { MD5 } from 'crypto-js'; import { NextFunction, Request, Response, Router } from 'express'; import * as sendRequest from 'request-promise-native'; import { UserClient as UserClientType } from 'common/u...
} break; case 'file': avatarURL = 'data:' + headers['content-type'] + ';base64,' + body.toString('base64'); console.log(avatarURL.length); if (avatarURL.length > 8000) { error = 'too_large'; } break; ...
} catch (e) { if (e.name != 'StatusCodeError') { throw e; } error = 'not_found';
random_line_split
api.ts
import { PassThrough } from 'stream'; import { S3 } from 'aws-sdk'; import * as bodyParser from 'body-parser'; import { MD5 } from 'crypto-js'; import { NextFunction, Request, Response, Router } from 'express'; import * as sendRequest from 'request-promise-native'; import { UserClient as UserClientType } from 'common/u...
response.json({}); }; insertDownloader = async ( { client_id, params }: Request, response: Response ) => { await this.model.db.insertDownloader(params.locale, params.email); response.json({}); }; seenAwards = async ({ client_id, query }: Request, response: Response) => { await Award...
{ await UserClient.claimContributions(client_id, [params.client_id]); }
conditional_block
api.ts
import { PassThrough } from 'stream'; import { S3 } from 'aws-sdk'; import * as bodyParser from 'body-parser'; import { MD5 } from 'crypto-js'; import { NextFunction, Request, Response, Router } from 'express'; import * as sendRequest from 'request-promise-native'; import { UserClient as UserClientType } from 'common/u...
getRandomSentences = async (request: Request, response: Response) => { const { client_id, params } = request; const sentences = await this.model.findEligibleSentences( client_id, params.locale, parseInt(request.query.count, 10) || 1 ); response.json(sentences); }; getRequeste...
{ const router = PromiseRouter(); router.use(bodyParser.json()); router.use((request: Request, response: Response, next: NextFunction) => { this.metrics.countRequest(request); next(); }, authMiddleware); router.get('/metrics', (request: Request, response: Response) => { this.met...
identifier_body
day_14.rs
use tdd_kata::string_calc_kata::iter_1::day_14::evaluate; #[cfg(test)] mod tests { use super::*; #[test] fn test_eval_simple_num() { assert_eq!(evaluate("1"), Ok(1.0)); } #[test] fn test_eval_three_digit_num() { assert_eq!(evaluate("256"), Ok(256.0)); } #[test] f...
() { assert_eq!(evaluate("125.256"), Ok(125.256)); } #[test] fn test_eval_add() { assert_eq!(evaluate("1+2"), Ok(3.0)); } #[test] fn test_eval_sub() { assert_eq!(evaluate("3-1"), Ok(2.0)); } #[test] fn test_eval_few_operations() { assert_eq!(evaluat...
test_eval_real_num
identifier_name
day_14.rs
use tdd_kata::string_calc_kata::iter_1::day_14::evaluate; #[cfg(test)] mod tests { use super::*; #[test] fn test_eval_simple_num() { assert_eq!(evaluate("1"), Ok(1.0)); } #[test] fn test_eval_three_digit_num() { assert_eq!(evaluate("256"), Ok(256.0)); } #[test] f...
#[test] fn test_eval_div() { assert_eq!(evaluate("10÷2"), Ok(5.0)); } #[test] fn test_eval_operations_with_diff_priority() { assert_eq!(evaluate("20+2×5-100÷4"), Ok(5.0)); } #[test] fn test_eval_operations_with_parentheses() { assert_eq!(evaluate("2+(2-3+5×2)-8...
{ assert_eq!(evaluate("2×5"), Ok(10.0)); }
identifier_body
day_14.rs
use tdd_kata::string_calc_kata::iter_1::day_14::evaluate; #[cfg(test)] mod tests { use super::*; #[test] fn test_eval_simple_num() { assert_eq!(evaluate("1"), Ok(1.0)); } #[test] fn test_eval_three_digit_num() { assert_eq!(evaluate("256"), Ok(256.0)); } #[test] f...
#[test] fn test_eval_operations_with_parentheses() { assert_eq!(evaluate("2+(2-3+5×2)-8"), Ok(3.0)); } #[test] fn test_eval_operations_with_two_levels_of_parentheses() { assert_eq!(evaluate("2+(2-3+5×2)-((1+1)×4)"), Ok(3.0)); } }
random_line_split
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule, Routes } from '@angular/router'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { AppComponent } from './a...
AddClientComponent, EditClientComponent, GroupListComponent, AddGroupComponent, EditGroupComponent, FilterArrayPipe ], bootstrap: [ AppComponent ] }) export class AppModule { }
random_line_split
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule, Routes } from '@angular/router'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { AppComponent } from './a...
{ }
AppModule
identifier_name
clock.ts
import { injectable } from 'tsyringe' import { monotonicNow } from './monotonic-now' export type TimeoutId = ReturnType<typeof setTimeout> /** An injected utility class for retrieving the current time. */ @injectable() export class
{ /** * Retrieves the current time as a number of milliseconds since the epoch. * * @see Date.now */ now(): number { return Date.now() } /** * Retrieves the current monotonic clock offset in milliseconds. This value will always tick * upwards regardless of any system clock changes (or of...
Clock
identifier_name
clock.ts
import { injectable } from 'tsyringe' import { monotonicNow } from './monotonic-now' export type TimeoutId = ReturnType<typeof setTimeout> /** An injected utility class for retrieving the current time. */ @injectable() export class Clock {
/** * Retrieves the current time as a number of milliseconds since the epoch. * * @see Date.now */ now(): number { return Date.now() } /** * Retrieves the current monotonic clock offset in milliseconds. This value will always tick * upwards regardless of any system clock changes (or offse...
random_line_split
extern-crate-only-used-in-link.rs
// This test is just a little cursed.
// aux-crate:priv:empty=empty.rs // aux-build:empty2.rs // aux-crate:priv:empty2=empty2.rs // build-aux-docs // compile-flags:-Z unstable-options --edition 2018 // @has extern_crate_only_used_in_link/index.html // @has - '//a[@href="../issue_66159_1/struct.Something.html"]' 'issue_66159_1::Something' //! [issue_66159_...
// aux-build:issue-66159-1.rs // aux-crate:priv:issue_66159_1=issue-66159-1.rs // aux-build:empty.rs
random_line_split
shocker.py
import src import random class Shocker(src.items.Item): """ ingame item used as ressource to build bombs and stuff should have the habit to explode at inconvienent times """ type = "Shocker" def __init__(self): """ set up internal state """ super().__init__(di...
else: character.addMessage("this room can't be charged") else: character.addMessage("no room found") else: character.addMessage("no crystal compressor found in inventory") src.items.addType(Shocker)
character.addMessage("this room is fully charged")
random_line_split
shocker.py
import src import random class Shocker(src.items.Item):
src.items.addType(Shocker)
""" ingame item used as ressource to build bombs and stuff should have the habit to explode at inconvienent times """ type = "Shocker" def __init__(self): """ set up internal state """ super().__init__(display="/\\") def apply(self, character): """ ...
identifier_body
shocker.py
import src import random class Shocker(src.items.Item): """ ingame item used as ressource to build bombs and stuff should have the habit to explode at inconvienent times """ type = "Shocker" def __init__(self): """ set up internal state """ super().__init__(di...
(self, character): """ Parameters: character: the character trying to use the item """ compressorFound = None for item in character.inventory: if isinstance(item,src.items.itemMap["CrystalCompressor"]): compressorFound = item ...
apply
identifier_name
shocker.py
import src import random class Shocker(src.items.Item): """ ingame item used as ressource to build bombs and stuff should have the habit to explode at inconvienent times """ type = "Shocker" def __init__(self): """ set up internal state """ super().__init__(di...
else: character.addMessage("no room found") else: character.addMessage("no crystal compressor found in inventory") src.items.addType(Shocker)
character.addMessage("this room can't be charged")
conditional_block
15.2.3.13-2-13.js
/// Copyright (c) 2009 Microsoft Corporation /// /// 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 list of conditions and /// ...
}, precondition: function prereq() { return fnExists(Object.isExtensible); } });
{ return true; }
conditional_block
15.2.3.13-2-13.js
/// Copyright (c) 2009 Microsoft Corporation /// /// 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 list of conditions and /// ...
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and /// the following disclaimer in the documentation and/or other materials provided with the distribution. /// * Neither the name of Microsoft nor the names of its contributors may be used to /// ...
random_line_split
E-value-distribution.py
#!/usr/bin/env python2 import sys, getopt import re import time def get_option(): opts, args = getopt.getopt(sys.argv[1:], "hi:o:") input_file = "" output_file = "" h = "" for op, value in opts: if op == "-i": input_file = value elif op == "-o": output_file = value elif op == "-h": h = "E-value di...
(input_file, output_file): o = a = b = c = d = e = g = 0 fout = open(output_file, 'w') with open (input_file) as f: for i in f: i = float(i[:-1]) if i == 0: o +=1 elif i < float(1e-150): a +=1 elif i < float(1e-100): b +=1 elif i < float(1e-50): c +=1 elif i < 1e-10: d +=1 ...
main
identifier_name
E-value-distribution.py
#!/usr/bin/env python2 import sys, getopt import re import time def get_option(): opts, args = getopt.getopt(sys.argv[1:], "hi:o:") input_file = "" output_file = "" h = "" for op, value in opts: if op == "-i": input_file = value elif op == "-o": output_file = value elif op == "-h":
def main(input_file, output_file): o = a = b = c = d = e = g = 0 fout = open(output_file, 'w') with open (input_file) as f: for i in f: i = float(i[:-1]) if i == 0: o +=1 elif i < float(1e-150): a +=1 elif i < float(1e-100): b +=1 elif i < float(1e-50): c +=1 elif i < 1e-10: ...
h = "E-value distribution.\n-i : inputfile\n-o : outputfile\n" return input_file,output_file,h
random_line_split
E-value-distribution.py
#!/usr/bin/env python2 import sys, getopt import re import time def get_option(): opts, args = getopt.getopt(sys.argv[1:], "hi:o:") input_file = "" output_file = "" h = "" for op, value in opts: if op == "-i": input_file = value elif op == "-o": output_file = value elif op == "-h":
return input_file,output_file,h def main(input_file, output_file): o = a = b = c = d = e = g = 0 fout = open(output_file, 'w') with open (input_file) as f: for i in f: i = float(i[:-1]) if i == 0: o +=1 elif i < float(1e-150): a +=1 elif i < float(1e-100): b +=1 elif i < float(1e-50):...
h = "E-value distribution.\n-i : inputfile\n-o : outputfile\n"
conditional_block
E-value-distribution.py
#!/usr/bin/env python2 import sys, getopt import re import time def get_option(): opts, args = getopt.getopt(sys.argv[1:], "hi:o:") input_file = "" output_file = "" h = "" for op, value in opts: if op == "-i": input_file = value elif op == "-o": output_file = value elif op == "-h": h = "E-value di...
if __name__ == "__main__": time_start = time.time() input_file,output_file,h = get_option() if str(h) == "": main(input_file, output_file) print ("time: " + str (time.time()-time_start)) else: print (h)
o = a = b = c = d = e = g = 0 fout = open(output_file, 'w') with open (input_file) as f: for i in f: i = float(i[:-1]) if i == 0: o +=1 elif i < float(1e-150): a +=1 elif i < float(1e-100): b +=1 elif i < float(1e-50): c +=1 elif i < 1e-10: d +=1 else : g +=1 out = str(...
identifier_body
ml.js
// moment.js locale configuration // locale : malayalam (ml) // author : Floyd Pink : https://github.com/floydpink (function( factory ) { if (typeof define === 'function' && define.amd) { define( ['moment'], factory ); // AMD } else { if (typeof exports === 'object') { module.export...
if (hour < 20) { return 'വൈകുന്നേരം'; } else { return 'രാത്രി'; } } } } } } ); } ));
return 'രാവിലെ'; } else { if (hour < 17) { return 'ഉച്ച കഴിഞ്ഞ്'; } else {
random_line_split
ml.js
// moment.js locale configuration // locale : malayalam (ml) // author : Floyd Pink : https://github.com/floydpink (function( factory ) { if (typeof define === 'function' && define.amd) { define( ['moment'], factory ); // AMD } else { if (typeof exports === 'object')
else { factory( (typeof global !== 'undefined' ? global : this).moment ); // node or other global } } }( function( moment ) { return moment.defineLocale( 'ml', { months: 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split( '_' ), mo...
{ module.exports = factory( require( '../moment' ) ); // Node }
conditional_block
export.js
// This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle is dis...
boxquantity++; }); $(t.CSS.SELECTALLPOST).prop('disabled', uncheckBoxes == 0); $(t.CSS.SELECTNONE).prop('disabled', uncheckBoxes == boxquantity); $(t.CSS.EXPORTSELECTED).prop('disabled', t.contentIds.length == 0); }, /** * Update...
{ uncheckBoxes++; }
conditional_block
export.js
// This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle is dis...
t.removePost(event.target.value); } t.initButtonState(); }, /** * Set checkbox state to checked if user already selected it. * @method selectNone */ initSelectedPost: function() { $(t.CSS.CHECKBOXS).each(function() {...
*/ selectPost: function(event) { if (event.target.checked == true) { t.addPost(event.target.value); } else {
random_line_split
ecdsa_common.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
EllipticCurveType::NistP521 => { if hash_alg != HashType::Sha512 { return Err("invalid hash type, expect SHA-512".into()); } } _ => return Err(format!("unsupported curve: {:?}", curve).into()), } Ok(encoding) }
{ if hash_alg != HashType::Sha384 && hash_alg != HashType::Sha512 { return Err("invalid hash type, expect SHA-384 or SHA-512".into()); } }
conditional_block
ecdsa_common.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
{ Der, IeeeP1363, } /// Validate ECDSA parameters. /// The hash's strength must not be weaker than the curve's strength. /// DER and IEEE_P1363 encodings are supported. pub fn validate_ecdsa_params( hash_alg: tink_proto::HashType, curve: tink_proto::EllipticCurveType, encoding: tink_proto::EcdsaSi...
SignatureEncoding
identifier_name
ecdsa_common.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
{ let encoding = match encoding { EcdsaSignatureEncoding::IeeeP1363 => SignatureEncoding::IeeeP1363, EcdsaSignatureEncoding::Der => SignatureEncoding::Der, _ => return Err("ecdsa: unsupported encoding".into()), }; match curve { EllipticCurveType::NistP256 => { if ...
identifier_body
ecdsa_common.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
use tink_core::TinkError; use tink_proto::{EcdsaSignatureEncoding, EllipticCurveType, HashType}; /// Supported signature encodings. This is a precise subset of the protobuf enum, /// allowing exact `match`es. #[derive(Clone, Debug)] pub enum SignatureEncoding { Der, IeeeP1363, } /// Validate ECDSA parameter...
random_line_split
common.rs
// Copyright 2012-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-MI...
} #[derive(Clone)] pub struct Config { // The library paths required for running the compiler pub compile_lib_path: String, // The library paths required for running compiled programs pub run_lib_path: String, // The rustc executable pub rustc_path: PathBuf, // The rustdoc executable ...
{ fmt::Display::fmt(match *self { CompileFail => "compile-fail", ParseFail => "parse-fail", RunFail => "run-fail", RunPass => "run-pass", RunPassValgrind => "run-pass-valgrind", Pretty => "pretty", DebugInfoGdb => "debuginfo-gdb...
identifier_body
common.rs
// Copyright 2012-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-MI...
pub python: String, // The llvm binaries path pub llvm_bin_path: Option<PathBuf>, // The valgrind path pub valgrind_path: Option<String>, // Whether to fail if we can't run run-pass-valgrind tests under valgrind // (or, alternatively, to silently run them like regular run-pass tests). ...
// The python executable
random_line_split
common.rs
// Copyright 2012-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-MI...
{ // The library paths required for running the compiler pub compile_lib_path: String, // The library paths required for running compiled programs pub run_lib_path: String, // The rustc executable pub rustc_path: PathBuf, // The rustdoc executable pub rustdoc_path: PathBuf, // T...
Config
identifier_name
main.rs
// // main.rs // // Copyright 2015-2019 Laurent Wandrebeck <l.wandrebeck@quelquesmots.fr> // // This program 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 op...
2 => rush.prompt = Prompt::get(&mut rush, "PS2"), 3 => rush.prompt = Prompt::get(&mut rush, "PS3"), 4 => rush.prompt = Prompt::get(&mut rush, "PS4"), _ => panic!("wrong line_case value."), } } }
match rush.line_case { 1 => rush.prompt = Prompt::get(&mut rush, "PS1"),
random_line_split
main.rs
// // main.rs // // Copyright 2015-2019 Laurent Wandrebeck <l.wandrebeck@quelquesmots.fr> // // This program 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 op...
{ let mut rush = RuSh::default(); //rush.prompt = Prompt::get(&mut rush.shell_vars, "PS1"); rush.prompt = Prompt::get(&mut rush, "PS1"); //let mut stdin = io::stdin(); let mut rl = rustyline::Editor::<()>::new(); // take care of SECOND env var //~ let child = thread::spawn(move || { //~...
identifier_body
main.rs
// // main.rs // // Copyright 2015-2019 Laurent Wandrebeck <l.wandrebeck@quelquesmots.fr> // // This program 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 op...
() { let mut rush = RuSh::default(); //rush.prompt = Prompt::get(&mut rush.shell_vars, "PS1"); rush.prompt = Prompt::get(&mut rush, "PS1"); //let mut stdin = io::stdin(); let mut rl = rustyline::Editor::<()>::new(); // take care of SECOND env var //~ let child = thread::spawn(move || { ...
main
identifier_name
GraphRenderer.js
define(['rickshaw'], function(Rickshaw) { /* A dot is rendered for a point whose neighboring points are both null values. Also handles rendering the vertical 'time line' when the graph is clicked. */ Rickshaw.namespace('Rickshaw.Graph.Renderer.LineDot'); Rickshaw.Graph.Renderer.LineDot = Rickshaw.Class.create( ...
series.forEach(function(series) { if (series.disabled) return; var nodes = vis.selectAll("x") .data(series.stack.filter( function(d, i, data) { // filter points whose neighbors are undefined return (d.y !== null && (data[i-1] && data[i-1].y === null) && (data[i+1] && data[i+1].y ===...
}, this);
random_line_split
outputPanel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(action: Action): IActionItem { if (action.id === SwitchOutputAction.ID) { return this.instantiationService.createInstance(SwitchOutputActionItem, action); } return super.getActionItem(action); } protected getConfigurationOverrides(): IEditorOptions { const options = super.getConfigurationOverrides(); ...
getActionItem
identifier_name
outputPanel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} public getId(): string { return OUTPUT_PANEL_ID; } public getTitle(): string { return nls.localize('output', "Output"); } public getActions(): IAction[] { if (!this.actions) { this.actions = [ this.instantiationService.createInstance(SwitchOutputAction), this.instantiationService.createInsta...
random_line_split
outputPanel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return this.actions; } public getActionItem(action: Action): IActionItem { if (action.id === SwitchOutputAction.ID) { return this.instantiationService.createInstance(SwitchOutputActionItem, action); } return super.getActionItem(action); } protected getConfigurationOverrides(): IEditorOptions { con...
{ this.actions = [ this.instantiationService.createInstance(SwitchOutputAction), this.instantiationService.createInstance(ClearOutputAction, ClearOutputAction.ID, ClearOutputAction.LABEL), this.instantiationService.createInstance(ToggleOutputScrollLockAction, ToggleOutputScrollLockAction.ID, ToggleOutput...
conditional_block
outputPanel.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public getActionItem(action: Action): IActionItem { if (action.id === SwitchOutputAction.ID) { return this.instantiationService.createInstance(SwitchOutputActionItem, action); } return super.getActionItem(action); } protected getConfigurationOverrides(): IEditorOptions { const options = super.getConfi...
{ if (!this.actions) { this.actions = [ this.instantiationService.createInstance(SwitchOutputAction), this.instantiationService.createInstance(ClearOutputAction, ClearOutputAction.ID, ClearOutputAction.LABEL), this.instantiationService.createInstance(ToggleOutputScrollLockAction, ToggleOutputScrollLock...
identifier_body
fulfill.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 ...
typer: &Typer<'tcx>) -> Result<(),Vec<FulfillmentError<'tcx>>> { try!(self.select_where_possible(infcx, param_env, typer)); // Anything left is ambiguous. let errors: Vec<FulfillmentError> = self.trait_obligat...
infcx: &InferCtxt<'a,'tcx>, param_env: &ty::ParameterEnvironment<'tcx>,
random_line_split
fulfill.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 ...
pub fn register_obligation(&mut self, tcx: &ty::ctxt<'tcx>, obligation: Obligation<'tcx>) { debug!("register_obligation({})", obligation.repr(tcx)); assert!(!obligation.trait_ref.has_escaping_regions()); self.trait_obligatio...
{ FulfillmentContext { trait_obligations: Vec::new(), attempted_mark: 0, } }
identifier_body
fulfill.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 ...
<'a>(&mut self, infcx: &InferCtxt<'a,'tcx>, param_env: &ty::ParameterEnvironment<'tcx>, typer: &Typer<'tcx>) -> Result<(),Vec<FulfillmentError<'tcx>>> { let mut...
select_where_possible
identifier_name
callback.rs
// Copyright (c) 2016 Yusuke Sasaki // // This software is released under the MIT License. // See http://opensource.org/licenses/mit-license.php or <LICENSE>. extern crate gurobi; use gurobi::*; use std::io::{BufWriter, Write}; use std::fs::OpenOptions; fn main()
{ let mut env = Env::new("callback.log").unwrap(); env.set(param::OutputFlag, 0).unwrap(); env.set(param::Heuristics, 0.0).unwrap(); let mut model = Model::read_from(&std::env::args().nth(1).unwrap(), &env).unwrap(); let callback = { let mut lastiter = -INFINITY; let mut lastnode = -INFINITY; le...
identifier_body
callback.rs
// Copyright (c) 2016 Yusuke Sasaki // // This software is released under the MIT License. // See http://opensource.org/licenses/mit-license.php or <LICENSE>. extern crate gurobi; use gurobi::*; use std::io::{BufWriter, Write}; use std::fs::OpenOptions; fn main() { let mut env = Env::new("callback.log").unwrap(); ...
// Found a new MIP incumbent MIPSol { solcnt, obj, nodcnt, .. } => { println!("@MIPSol: "); let x = try!(ctx.get_solution(vars.as_slice())); println!("**** New solution at node {}, obj {}, sol {}, x[0] = {} ****", nodcnt, obj, ...
{ if nodcnt - lastnode >= 100.0 { lastnode = nodcnt; println!("@MIP: nodcnt={}, actnodes={}, itrcnt={}, objbst={}, objbnd={}, solcnt={}, cutcnt={}.", nodcnt, actnodes, itrcnt, objbst, ...
conditional_block
callback.rs
// Copyright (c) 2016 Yusuke Sasaki // // This software is released under the MIT License. // See http://opensource.org/licenses/mit-license.php or <LICENSE>. extern crate gurobi; use gurobi::*; use std::io::{BufWriter, Write}; use std::fs::OpenOptions; fn main() { let mut env = Env::new("callback.log").unwrap(); ...
writer.write_all(message.as_bytes()).unwrap(); writer.write_all(&[b'\n']).unwrap(); } } Ok(()) } }; model.optimize_with_callback(callback).unwrap(); println!("\nOptimization complete"); if model.get(attr::SolCount).unwrap() == 0 { println!("No solution found. op...
} // Printing a log message Message(message) => {
random_line_split
callback.rs
// Copyright (c) 2016 Yusuke Sasaki // // This software is released under the MIT License. // See http://opensource.org/licenses/mit-license.php or <LICENSE>. extern crate gurobi; use gurobi::*; use std::io::{BufWriter, Write}; use std::fs::OpenOptions; fn
() { let mut env = Env::new("callback.log").unwrap(); env.set(param::OutputFlag, 0).unwrap(); env.set(param::Heuristics, 0.0).unwrap(); let mut model = Model::read_from(&std::env::args().nth(1).unwrap(), &env).unwrap(); let callback = { let mut lastiter = -INFINITY; let mut lastnode = -INFINITY; ...
main
identifier_name
performanceentry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::PerformanceEntryBinding; use dom::bindings::codegen::Bindings::PerformanceEn...
// https://w3c.github.io/performance-timeline/#dom-performanceentry-duration fn Duration(&self) -> Finite<f64> { Finite::wrap(self.duration) } }
random_line_split
performanceentry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::PerformanceEntryBinding; use dom::bindings::codegen::Bindings::PerformanceEn...
(&self) -> Finite<f64> { Finite::wrap(self.duration) } }
Duration
identifier_name
performanceentry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::PerformanceEntryBinding; use dom::bindings::codegen::Bindings::PerformanceEn...
pub fn entry_type(&self) -> &DOMString { &self.entry_type } pub fn name(&self) -> &DOMString { &self.name } pub fn start_time(&self) -> f64 { self.start_time } } impl PerformanceEntryMethods for PerformanceEntry { // https://w3c.github.io/performance-timeline/#do...
{ let entry = PerformanceEntry::new_inherited(name, entry_type, start_time, duration); reflect_dom_object(Box::new(entry), global, PerformanceEntryBinding::Wrap) }
identifier_body
models.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from datetime import datetime from django.conf import settings from django.db import models from django_extensions.db.f...
def equivalent_desktop_release(self): if self.product == 'Firefox for Android': return self.equivalent_release_for_product('Firefox') def notes(self, public_only=False): """ Retrieve a list of Note instances that should be shown for this release, grouped as either ...
if self.product == 'Firefox': return self.equivalent_release_for_product('Firefox for Android')
identifier_body
models.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from datetime import datetime from django.conf import settings from django.db import models from django_extensions.db.f...
def equivalent_android_release(self): if self.product == 'Firefox': return self.equivalent_release_for_product('Firefox for Android') def equivalent_desktop_release(self): if self.product == 'Firefox for Android': return self.equivalent_release_for_product('Firefox') ...
return sorted( sorted(releases, reverse=True, key=lambda r: len(r.version.split('.'))), reverse=True, key=lambda r: r.version.split('.')[1])[0]
conditional_block
models.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from datetime import datetime from django.conf import settings from django.db import models from django_extensions.db.f...
""" created = CreationDateTimeField() modified = models.DateTimeField(editable=False, blank=True, db_index=True) class Meta: abstract = True def save(self, *args, **kwargs): if kwargs.pop('modified', True): self.modified = datetime.now() super(TimeStampedModel, ...
parameter to the save method
random_line_split