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 |
|---|---|---|---|---|
request-methods.spec.ts |
import {assert} from 'chai';
import { Observable } from "rxjs";
import { HttpClient } from "../../http/http-client";
import { Response } from '../../http/response';
import { Request } from '../../http/request';
import { RequestMethod } from '../../http/request-method';
import { RestClient } from "../rest-client";
impo... | implements HttpClient{
constructor(private requestFunction:(req:Request) =>Observable<Response>){}
public callCount:number = 0;
public lastRequest:Request;
public request(req:Request):Observable<Response> {
this.callCount++;
this.lastRequest = req;
return this.requestFunction(req);
}
}
class ... | RequestMock | identifier_name |
request-methods.spec.ts | import {assert} from 'chai';
import { Observable } from "rxjs";
import { HttpClient } from "../../http/http-client";
import { Response } from '../../http/response';
import { Request } from '../../http/request';
import { RequestMethod } from '../../http/request-method';
import { RestClient } from "../rest-client";
impor... |
class TestClient extends RestClient {
constructor(httpClient:HttpClient){
super(httpClient );
}
@Get('/test')
public getItems():Observable<Response>{
return null;
}
@Post('/test')
public createItems():Observable<Response>{
return null;
}
} | random_line_split | |
request-methods.spec.ts |
import {assert} from 'chai';
import { Observable } from "rxjs";
import { HttpClient } from "../../http/http-client";
import { Response } from '../../http/response';
import { Request } from '../../http/request';
import { RequestMethod } from '../../http/request-method';
import { RestClient } from "../rest-client";
impo... |
}
class TestClient extends RestClient {
constructor(httpClient:HttpClient){
super(httpClient );
}
@Get('/test')
public getItems():Observable<Response>{
return null;
}
@Post('/test')
public createItems():Observable<Response>{
return null;
}
}
| {
this.callCount++;
this.lastRequest = req;
return this.requestFunction(req);
} | identifier_body |
AlwaysBeCasting.tsx | import { t } from '@lingui/macro';
import { formatPercentage } from 'common/format';
import { Options } from 'parser/core/Analyzer';
import { When } from 'parser/core/ParseResults';
import CoreAlwaysBeCastingHealing from 'parser/shared/modules/AlwaysBeCastingHealing';
import lowRankSpells, { LowRankSpells } from '../.... | (when: When) {
const deadTimePercentage = this.totalTimeWasted / this.owner.fightDuration;
when(deadTimePercentage)
.isGreaterThan(0.15)
.addSuggestion((suggest, actual, recommended) =>
suggest('Your downtime can be improved. Try to Always Be Casting (ABC).')
.icon('spell_mage_alt... | suggestions | identifier_name |
AlwaysBeCasting.tsx | import { t } from '@lingui/macro';
import { formatPercentage } from 'common/format';
import { Options } from 'parser/core/Analyzer';
import { When } from 'parser/core/ParseResults';
import CoreAlwaysBeCastingHealing from 'parser/shared/modules/AlwaysBeCastingHealing';
import lowRankSpells, { LowRankSpells } from '../.... | static HEALING_ABILITIES_ON_GCD: number[] = [
SPELLS.TRANQUILITY,
SPELLS.REMOVE_CURSE,
SPELLS.REJUVENATION,
SPELLS.REGROWTH,
SPELLS.REBIRTH,
SPELLS.MARK_OF_THE_WILD,
SPELLS.LIFEBLOOM,
SPELLS.INNERVATE,
SPELLS.HEALING_TOUCH,
SPELLS.CURE_POISON,
SPELLS.ABOLISH_POISON,
];
... | random_line_split | |
Viewport.tsx | width: number;
height: number;
};
// This awkward declaration is required because of the cosmosCapture static
// property, which makes TS generate a declaration for Viewport that doesn't
// conform to React's component interface. Without this explicit type TS would
// allow clients to pass any props to Viewport.
e... | import React from 'react';
import { FixtureContext } from './FixtureContext';
type Props = {
children: React.ReactNode; | random_line_split | |
pick.js | Model} from 'pods-dfv/_src/core/pods-field-model';
import {PodsDFVFieldLayout} from 'pods-dfv/_src/core/pods-field-views';
import {IframeFrame} from 'pods-dfv/_src/core/iframe-frame';
import {RelationshipCollection} from 'pods-dfv/_src/pick/relationship-model';
import {PickFieldModel} from 'pods-dfv/_src/pick/pick-fi... |
},
setModalListeners: function() {
jQuery( window ).on( 'dfv:modal:update', this.modalSuccess.bind( this ) );
jQuery( window ).on( 'dfv:modal:cancel', this.modalCancel.bind( this ) );
},
clearModalListeners: function() {
jQuery( window ).off( 'dfv:modal:update' );
jQuery( window ).off( 'dfv:modal:cancel'... | {
this.buildAutocomplete();
this.getChildView( 'list' ).render();
} | conditional_block |
pick.js | Model} from 'pods-dfv/_src/core/pods-field-model';
import {PodsDFVFieldLayout} from 'pods-dfv/_src/core/pods-field-views';
import {IframeFrame} from 'pods-dfv/_src/core/iframe-frame';
import {RelationshipCollection} from 'pods-dfv/_src/pick/relationship-model';
import {PickFieldModel} from 'pods-dfv/_src/pick/pick-fi... | viewName = this.fieldConfig.get( 'view_name' );
if ( views[ viewName ] === undefined ) {
throw new Error( `Invalid view name "${viewName}"` );
}
View = views[ viewName ];
list = new View( { collection: this.collection, fieldModel: this.model } );
this.showChildView( 'list', list );
},
/**
*
*/
s... | random_line_split | |
eventsocket.py | self._parent_close_cb = close_cb
self._parent_output_empty_cb = output_empty_cb
# This is the pending global error message. It's sort of a hack, but it's
# used for __protected_cb in much the same way as errno. This prevents
# having to pass an error message around, when the best way to do that is
... | (self, cb):
"""
Set the read callback. If there's data in the output buffer, immediately
setup a call.
"""
self._parent_read_cb = cb
#if self._read_buf.tell()>0 and self._parent_read_cb!=None and self._pending_read_cb_event==None:
if len(self._read_buf)>0 and self._parent_read_cb!=None and ... | _set_read_cb | identifier_name |
eventsocket.py | _at. Otherwise, the socket will forever try to connect.
Passes *args on to socket.connect_ex, and **kwargs are used for local
control of `timeout` and `timeout_at`.
'''
timeout_at = kwargs.get('timeout_at')
timeout = kwargs.get('timeout')
if not isinstance(timeout_at, float):
if not isin... | cur = self._write_buf.popleft()
# Catch all env errors since that should catch OSError, IOError and
# socket.error. | random_line_split | |
eventsocket.py | self._logger = logger
if self._debug and not self._logger:
print 'WARNING: to debug EventSocket, must provide a logger'
self._debug = False
# There various events we may or may not schedule
self._read_event = None
self._write_event = None
self._accept_event = None
self._conn... | """
A socket wrapper which uses libevent.
"""
def __init__( self, family=socket.AF_INET, type=socket.SOCK_STREAM, \
protocol=socket.IPPROTO_IP, read_cb=None, accept_cb=None, \
close_cb=None, error_cb=None, output_empty_cb=None, sock=None, \
debug=False, logger=None... | identifier_body | |
eventsocket.py | self._parent_close_cb = close_cb
self._parent_output_empty_cb = output_empty_cb
# This is the pending global error message. It's sort of a hack, but it's
# used for __protected_cb in much the same way as errno. This prevents
# having to pass an error message around, when the best way to do that is
... |
if self._connect_event:
self._connect_event.delete()
self._connect_event = None
if self._sock:
self._sock.close()
self._sock = None
# Flush any pending data to the read callbacks as appropriate. Do this
# manually as there is a chance for the following race condition to o... | self._write_event.delete()
self._write_event = None | conditional_block |
rnn_text.py | , 'r') as f:
line = f.readline()
[length, dim] = line.split(' ')
vec = np.zeros((int(length)+1, int(dim)), dtype = np.float64) # {index: [vector], ...}
line = f.readline()
i = 1
while line != '':
index = line.find(' ')
word = line[:index... |
# make every input have same length
if weights is None:
data = padding(data, False)
else:
data = padding(data, True)
return np.array(data, dtype=np.float64), np.array(result, dtype=np.float64)
# compute results based on the attributes
def compute_result(attrs):
# attrs: is... | try:
if weights is None:
data.append(model[word]) # convert word to index
else:
data.append(weights[model[word]]) # convert to vector
except:
pass
#data.append(model['unk'])
| conditional_block |
rnn_text.py | , 'r') as f:
line = f.readline()
[length, dim] = line.split(' ')
vec = np.zeros((int(length)+1, int(dim)), dtype = np.float64) # {index: [vector], ...}
line = f.readline()
i = 1
while line != '':
index = line.find(' ')
word = line[:index... |
def train_data_generator2(dataPath, weights):
total = 2528
index = 0
while True:
inputs = np.load('%s%d%s'%(dataPath, index, '_x.npy'))
result = np.load('%s%d%s'%(dataPath, index, '_y.npy'))
data = np.zeros([BATCH,LEN,DIM],dtype=np.float64)
for i in range(len(inputs)... | total = 2528
index = 0
while True:
inputs, targets = build_dataset('%s%d'%(dataPath, index), vocab)
for i in range(1, limit):
index += 1
if index == total:
index = 0
newInputs, newTargets = build_dataset('%s%d'%(dataPath, index), vocab)... | identifier_body |
rnn_text.py | , 'r') as f:
line = f.readline()
[length, dim] = line.split(' ')
vec = np.zeros((int(length)+1, int(dim)), dtype = np.float64) # {index: [vector], ...}
line = f.readline()
i = 1
while line != '':
index = line.find(' ')
word = line[:index... | (dataPath, weights):
total = 2528
index = 0
while True:
inputs = np.load('%s%d%s'%(dataPath, index, '_x.npy'))
result = np.load('%s%d%s'%(dataPath, index, '_y.npy'))
data = np.zeros([BATCH,LEN,DIM],dtype=np.float64)
for i in range(len(inputs)):
for j in ra... | train_data_generator2 | identifier_name |
rnn_text.py | , 'r') as f:
line = f.readline()
[length, dim] = line.split(' ')
vec = np.zeros((int(length)+1, int(dim)), dtype = np.float64) # {index: [vector], ...}
line = f.readline()
i = 1
while line != '':
index = line.find(' ')
word = line[:index... | # extract data and result from each line
data, result = extract_data(line.strip(' '), vocab, weights=weights)
trainData.append(data)
trainResult.append(result)
line = src.readline().strip('\n')
return trainData, trainResult
# a generator used to fi... | trainData, trainResult = [], []
with open(fileName, 'r') as src:
line = src.readline().strip('\n')
while line != '':
| random_line_split |
main.ts | ///<reference path="engine/dimension.ts"/>
///<reference path="engine/position.ts"/>
///<reference path="engine/engine.ts"/>
///<reference path="engine/bounds.ts"/>
///<reference path="timeManager.ts"/>
///<reference path="input/eventSet.ts"/>
///<reference path="input/keyboardKeys.ts"/>
///<reference path="input/xbo... | ///<reference path="world/worldLayer.ts"/>
///<reference path="world/worldManager.ts"/>
"use strict";
/**
* The Last Pastry
* @author TheMuffinCoder (a.k.a Sebastian)
*/
module PastryCore {
/*
export class CharacterAnimation {
constructor(public idleLeft: SpriteIndexs, public idleRight: SpriteIndexs, public i... | ///<reference path="world/world.ts"/> | random_line_split |
EmailHandlerV1.py | #!/usr/bin/env python
import webapp2
import logging
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext import ndb
from MailMessage import MailMessage
# the email domain of this app is @pomis-newsletterman.appspotmail.com | logging.info(mail_message.to_mime_message())
# store message
service_id = mail_message.to.split('@')[0]
if '<' in service_id:
service_id = service_id.split('<')[1]
mime_message = str(mail_message.to_mime_message())
service_key = ndb.Key(MailMessage, ... |
class EmailHandlerV1(InboundMailHandler):
def receive(self, mail_message): | random_line_split |
EmailHandlerV1.py | #!/usr/bin/env python
import webapp2
import logging
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext import ndb
from MailMessage import MailMessage
# the email domain of this app is @pomis-newsletterman.appspotmail.com
class EmailHandlerV1(InboundMailHandler):
... | (self, mail_message):
logging.info(mail_message.to_mime_message())
# store message
service_id = mail_message.to.split('@')[0]
if '<' in service_id:
service_id = service_id.split('<')[1]
mime_message = str(mail_message.to_mime_message())
service_key =... | receive | identifier_name |
EmailHandlerV1.py | #!/usr/bin/env python
import webapp2
import logging
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext import ndb
from MailMessage import MailMessage
# the email domain of this app is @pomis-newsletterman.appspotmail.com
class EmailHandlerV1(InboundMailHandler):
... |
mime_message = str(mail_message.to_mime_message())
service_key = ndb.Key(MailMessage, service_id)
new_id = ndb.Model.allocate_ids(size = 1, parent = service_key)[0]
mail_message_key = ndb.Key(MailMessage, new_id, parent = service_key)
persistent_mail_message = MailMessa... | service_id = service_id.split('<')[1] | conditional_block |
EmailHandlerV1.py | #!/usr/bin/env python
import webapp2
import logging
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext import ndb
from MailMessage import MailMessage
# the email domain of this app is @pomis-newsletterman.appspotmail.com
class EmailHandlerV1(InboundMailHandler):
... |
app = webapp2.WSGIApplication([EmailHandlerV1.mapping()], debug=True)
| def receive(self, mail_message):
logging.info(mail_message.to_mime_message())
# store message
service_id = mail_message.to.split('@')[0]
if '<' in service_id:
service_id = service_id.split('<')[1]
mime_message = str(mail_message.to_mime_message())
se... | identifier_body |
Utility.ts |
* @para value Количество.
* @param word1 Одна штука.
* @param word234 Деве штуки.
* @param wordmore Десять штук.
*/
public static GetCountAsString(value: number, word1: string, word234: string, wordmore: string) {
var decintpart = value;
var intpart = decintpart;
var e | t % 100);
if (endpart > 19) endpart = endpart % 10;
switch (endpart) {
case 1:
return word1;
case 2:
case 3:
case 4:
return word234;
default:
return wordmore;
}
}
/** Сравнивает две даты.*/
public static CompareDates(... | ndpart = (intpar | identifier_name |
Utility.ts |
* @para value Количество.
* @param word1 Одна штука.
* @param word234 Деве штуки.
* @param wordmore Десять штук.
*/
public static GetCountAsString(value: number, word1: string, word234: string, wordmore: string) {
var decintpart = value;
var intpart = decintpart;
var end... | }
/** Преобразует строку, содержащую дату в формате ДД.ММ.ГГГГ, в дату. */
public static GetDateFromString(dateString: string): Date {
var dpg = $.fn.datepicker.DPGlobal;
return dpg.parseDate(dateString, dpg.parseFormat('dd.mm.yyyy'));
}
/*
* Возвращает строку представляющую дату ... | return new Date((<Date>datetime).getFullYear(),(<Date>datetime).getMonth(),(<Date>datetime).getDate()); | random_line_split |
Utility.ts | (d: any): Date {
return <any>(
d.constructor === Date ? new Date(d.getFullYear(), d.getMonth(), d.getDate()) :
d.constructor === Array ? new Date(d[0], d[1], d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? (/[0-9]{2}.[0-9]{2}.[0-9]{4}/.test(d... | ing-right")) | conditional_block | |
jquery.colorbox-1.5.10.js | (settings, url) {
return settings.get('retinaUrl') && window.devicePixelRatio > 1 ? url.replace(settings.get('photoRegex'), settings.get('retinaSuffix')) : url;
}
function trapFocus(e) {
if ('contains' in $box[0] && !$box[0].contains(e.target) && e.target !== $overlay[0]) {
e.stopPropagation();
$box.focus(... | retinaUrl | identifier_name | |
jquery.colorbox-1.5.10.js | } else if (options[key] !== undefined) {
this.cache[key] = options[key];
} else if (defaults[key] !== undefined) {
this.cache[key] = defaults[key];
}
}
return this.cache[key];
};
this.get = function(key) {
var value = this.value(key);
return $.isFunction(value) ? value.call(this.... | if (dataAttr !== undefined) {
this.cache[key] = dataAttr; | random_line_split | |
jquery.colorbox-1.5.10.js | style.width = (settings.w + loadedWidth + interfaceWidth) + "px";
$wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px";
if (settings.get('reposition')) {
setTimeout(function () { // small delay before binding onresize due to an IE8 bug.
$window.bind('resize.' + prefix, p... | {
return;
} | conditional_block | |
jquery.colorbox-1.5.10.js | click." + prefix,
timeOut;
function clear () {
clearTimeout(timeOut);
}
function set() {
if (settings.get('loop') || $related[index + 1]) {
clear();
timeOut = setTimeout(publicMethod.next, settings.get('slideshowSpeed'));
}
}
function start() |
function stop() {
clear();
$events
.unbind(event_complete, set)
.unbind(event_load, clear);
$slideshow
.html(settings.get('slideshowStart'))
.unbind(click)
.one(click, function () {
publicMethod.next();
start();
});
$box.removeClass(className + "on").addClass(clas... | {
$slideshow
.html(settings.get('slideshowStop'))
.unbind(click)
.one(click, stop);
$events
.bind(event_complete, set)
.bind(event_load, clear);
$box.removeClass(className + "off").addClass(className + "on");
} | identifier_body |
load.js | var mongoose = require('mongoose'),
Schema = mongoose.Schema,
async = require('async'),
jf = require('jsonfile'),
executing = false;
var config = require('../config.json');
var configM = require('./config.json');
jf.spaces = 2;
mongoose.connect(config.db.url ||
('mongodb://' + config.db.host + '/'+ config... | if (err) { return done(err); }
User.count(hasCreated, function(err, count){
done(err, {
total: count,
data: users
});
});
});
},
projects: function(done){
var Project = mongoose.model('Project');
Project.aggregate(aggregation, function(err, projec... |
users: function(done){
var User = mongoose.model('User');
User.aggregate(aggregation, function(err, users){ | random_line_split |
load.js |
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
async = require('async'),
jf = require('jsonfile'),
executing = false;
var config = require('../config.json');
var configM = require('./config.json');
jf.spaces = 2;
mongoose.connect(config.db.url ||
('mongodb://' + config.db.host + '/'+ confi... |
Dashboard.count(hasCreated, function(err, count){
done(err, {
total: count,
data: dashboards
});
});
});
},
collections: function(done){
var Collection = mongoose.model('Collection');
Collection.aggregate(aggregation, function(err, collections){
... | { return done(err); } | conditional_block |
string.ts | import { locale } from "./time/format/defaultLocale";
const interpolatePattern = /(#\{(.*?)\})/g;
type NumberFormat = {
locales?: string | string[];
options?: any;
};
type DateFormat = string;
type ValueFormat = NumberFormat | DateFormat;
export function | (input: string, values: { [key in string]: any },
formats?: { [key in string]: ValueFormat }): string {
return input.replace(interpolatePattern, function () {
const name = arguments[2];
const [valueName, formatName] = name.split(':');
const value = values[valueNam... | interpolate | identifier_name |
string.ts | import { locale } from "./time/format/defaultLocale";
const interpolatePattern = /(#\{(.*?)\})/g;
type NumberFormat = {
locales?: string | string[];
options?: any;
};
type DateFormat = string;
type ValueFormat = NumberFormat | DateFormat;
export function interpolate(input: string, values: { [key in string]... |
return value.toDateString();
}
if (typeof value === 'string' || (value && value.toString)) {
return String(value);
}
return '';
});
} | {
const formatter = locale.format(format);
return formatter(value);
} | conditional_block |
string.ts | import { locale } from "./time/format/defaultLocale";
const interpolatePattern = /(#\{(.*?)\})/g;
type NumberFormat = {
locales?: string | string[];
options?: any;
};
type DateFormat = string;
type ValueFormat = NumberFormat | DateFormat;
export function interpolate(input: string, values: { [key in string]... | const formatter = locale.format(format);
return formatter(value);
}
return value.toDateString();
}
if (typeof value === 'string' || (value && value.toString)) {
return String(value);
}
return '';
});
} | {
return input.replace(interpolatePattern, function () {
const name = arguments[2];
const [valueName, formatName] = name.split(':');
const value = values[valueName];
if (typeof value === 'number') {
const format = formatName && formats && formats[formatName];
... | identifier_body |
string.ts | import { locale } from "./time/format/defaultLocale";
const interpolatePattern = /(#\{(.*?)\})/g;
type NumberFormat = {
locales?: string | string[];
options?: any;
};
type DateFormat = string;
type ValueFormat = NumberFormat | DateFormat;
export function interpolate(input: string, values: { [key in string]... | return value.toLocaleString(locales, options);
}
return String(value);
}
if (value instanceof Date) {
const format = formatName && formats && formats[formatName];
if (typeof format === 'string') {
const formatter = locale.... | const { locales, options } = format as NumberFormat; | random_line_split |
move-1.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. | // except according to those terms.
struct Triple { x: int, y: int, z: int }
fn test(x: bool, foo: @Triple) -> int {
let bar = foo;
let mut y: @Triple;
if x { y = bar; } else { y = @Triple{x: 4, y: 5, z: 6}; }
return y.y;
}
pub fn main() {
let x = @Triple {x: 1, y: 2, z: 3};
assert!((test(tru... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
move-1.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 ... |
pub fn main() {
let x = @Triple {x: 1, y: 2, z: 3};
assert!((test(true, x) == 2));
assert!((test(true, x) == 2));
assert!((test(true, x) == 2));
assert!((test(false, x) == 5));
}
| {
let bar = foo;
let mut y: @Triple;
if x { y = bar; } else { y = @Triple{x: 4, y: 5, z: 6}; }
return y.y;
} | identifier_body |
move-1.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 ... | () {
let x = @Triple {x: 1, y: 2, z: 3};
assert!((test(true, x) == 2));
assert!((test(true, x) == 2));
assert!((test(true, x) == 2));
assert!((test(false, x) == 5));
}
| main | identifier_name |
move-1.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 ... | else { y = @Triple{x: 4, y: 5, z: 6}; }
return y.y;
}
pub fn main() {
let x = @Triple {x: 1, y: 2, z: 3};
assert!((test(true, x) == 2));
assert!((test(true, x) == 2));
assert!((test(true, x) == 2));
assert!((test(false, x) == 5));
}
| { y = bar; } | conditional_block |
utils.py | from fabric.api import *
from fabric.contrib.files import exists
import fabric
counter = 0
@roles('master')
def start_spark():
run('/home/mdindex/scripts/startSystems.sh')
@roles('master')
def stop_spark():
run('/home/mdindex/scripts/stopSystems.sh')
@roles('master')
def start_zookeeper():
run('/home/md... |
@roles('master')
def update_master_jar():
if not exists('/data/mdindex/jars'):
run('mkdir -p /data/mdindex/jars')
put('../build/libs/amoeba-all.jar', '/data/mdindex/jars/')
@serial
def update_config():
global counter
put('server/server.properties', '/home/mdindex/amoeba.properties')
run('... | if not exists('/data/mdindex/jars'):
run('mkdir -p /data/mdindex/jars')
put('../build/libs/amoeba-all.jar', '/data/mdindex/jars/') | identifier_body |
utils.py | from fabric.api import *
from fabric.contrib.files import exists
import fabric
counter = 0
@roles('master')
def start_spark():
run('/home/mdindex/scripts/startSystems.sh')
@roles('master')
def stop_spark():
run('/home/mdindex/scripts/stopSystems.sh')
@roles('master')
def start_zookeeper():
run('/home/md... |
if before:
cmd = "{}; dtach -n `mktemp -u /tmp/{}.XXXX` {}".format(
before, sockname, cmd)
else:
cmd = "dtach -n `mktemp -u /tmp/{}.XXXX` {}".format(sockname, cmd)
if use_sudo:
return sudo(cmd)
else:
return run(cmd)
@runs_once
def build_jar():
local('cd ... | print "Install dtach first !"
return | conditional_block |
utils.py | from fabric.api import *
from fabric.contrib.files import exists
import fabric
counter = 0
@roles('master')
def start_spark():
run('/home/mdindex/scripts/startSystems.sh')
@roles('master')
def stop_spark():
run('/home/mdindex/scripts/stopSystems.sh')
@roles('master')
def start_zookeeper():
run('/home/md... | ():
if not exists('/data/mdindex/jars'):
run('mkdir -p /data/mdindex/jars')
put('../build/libs/amoeba-all.jar', '/data/mdindex/jars/')
@serial
def update_config():
global counter
put('server/server.properties', '/home/mdindex/amoeba.properties')
run('echo "MACHINE_ID = %d" >> /home/mdindex/... | update_master_jar | identifier_name |
utils.py | from fabric.api import *
from fabric.contrib.files import exists
import fabric
counter = 0
@roles('master')
def start_spark():
run('/home/mdindex/scripts/startSystems.sh')
@roles('master')
def stop_spark():
run('/home/mdindex/scripts/stopSystems.sh')
@roles('master')
def start_zookeeper():
run('/home/md... | run('mv /data/mdindex/tpchd100/download_data.sh ~/') | def parallel_shell(): | random_line_split |
event.rs | use collections::borrow::Cow;
use ::data::grid;
use ::data::shapes::tetromino::{Shape,RotatedShape,Rotation};
use ::game::data::Input;
//TODO: Document when the events triggers. If one triggers before or after mutation of the structure
///Events which can occur ingame.
///These should get signaled by the game state ... | player: P,
current: Rotation,
target: Rotation,
cause: RotationCause,
},
PlayerCollidedOnMovement{//TODO: Implement
player: P,
current: grid::PosAxis,
target: grid::PosAxis,
cause: RotationCause,
},
PlayerRotated{//TODO: Implement
player: P,
old: Rotation,
new: Rotation,
cause: RotationCause... | random_line_split | |
event.rs | use collections::borrow::Cow;
use ::data::grid;
use ::data::shapes::tetromino::{Shape,RotatedShape,Rotation};
use ::game::data::Input;
//TODO: Document when the events triggers. If one triggers before or after mutation of the structure
///Events which can occur ingame.
///These should get signaled by the game state ... | {
NewAfterImprint,
Desync,
Other(Option<Cow<'static,str>>)
}
#[derive(Clone,Debug,Serialize,Deserialize)]
pub enum ShapeImprintCause<P>{
PlayerInflicted(P),
Desync,
Other(Option<Cow<'static,str>>)
}
| ShapeChangeCause | identifier_name |
contact.js | import React from 'react';
const Contact = () => ({
contactNext(){
var data = $("#questionInput").val();
if(data) | else{
alert("Please enter your email.");
}
},
contactEnter(event){
if(event.key == 'Enter') {
var data = $("#questionInput").val();
if(data){
Session.set('contact', data);
FlowRouter.go("/register/6");
}else{
alert("Please enter your email.");
}
}
... | {
Session.set('contact', data);
FlowRouter.go("/register/6");
} | conditional_block |
contact.js | import React from 'react';
const Contact = () => ({
contactNext(){
var data = $("#questionInput").val();
if(data){
Session.set('contact', data);
FlowRouter.go("/register/6");
}else{
alert("Please enter your email.");
}
},
contactEnter(event){
if(event.key == 'Enter') {
... | }
});
export default Contact; | random_line_split | |
contact.js | import React from 'react';
const Contact = () => ({
contactNext(){
var data = $("#questionInput").val();
if(data){
Session.set('contact', data);
FlowRouter.go("/register/6");
}else{
alert("Please enter your email.");
}
},
contactEnter(event){
if(event.key == 'Enter') {
... | () {
return (
<div id="jiyuu">
<h2 className="question">What's your email?</h2>
<div id="question-card" className="form-group">
<div id="questionInputContain">
<input id="questionInput" type="text" onKeyPress={this.contactEnter.bind(this)} className="form-control"/>
... | render | identifier_name |
contact.js | import React from 'react';
const Contact = () => ({
contactNext() | ,
contactEnter(event){
if(event.key == 'Enter') {
var data = $("#questionInput").val();
if(data){
Session.set('contact', data);
FlowRouter.go("/register/6");
}else{
alert("Please enter your email.");
}
}
},
render() {
return (
<div id="jiyuu">
... | {
var data = $("#questionInput").val();
if(data){
Session.set('contact', data);
FlowRouter.go("/register/6");
}else{
alert("Please enter your email.");
}
} | identifier_body |
io.py | ## begin license ##
#
# "Weightless" is a High Performance Asynchronous Networking Library. See http://weightless.io
#
# Copyright (C) 2012-2013, 2017, 2020-2021 Seecr (Seek You Too B.V.) https://seecr.nl
#
# This file is part of "Weightless"
#
# "Weightless" is free software; you can redistribute it and/or modify
# it... | return _ContextMngrOrDecorated(streamName='stdin', replacement=inStream) | random_line_split | |
io.py | ## begin license ##
#
# "Weightless" is a High Performance Asynchronous Networking Library. See http://weightless.io
#
# Copyright (C) 2012-2013, 2017, 2020-2021 Seecr (Seek You Too B.V.) https://seecr.nl
#
# This file is part of "Weightless"
#
# "Weightless" is free software; you can redistribute it and/or modify
# it... |
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
with self:
return func(*args, **kwargs)
return wrapper
def __enter__(self):
mockStream, self._back = _set_replaced_stream(self._streamName, self._replacement)
return mockSt... | self._streamName = streamName
self._replacement = replacement | identifier_body |
io.py | ## begin license ##
#
# "Weightless" is a High Performance Asynchronous Networking Library. See http://weightless.io
#
# Copyright (C) 2012-2013, 2017, 2020-2021 Seecr (Seek You Too B.V.) https://seecr.nl
#
# This file is part of "Weightless"
#
# "Weightless" is free software; you can redistribute it and/or modify
# it... | (*args, **kwargs):
with self:
return func(*args, **kwargs)
return wrapper
def __enter__(self):
mockStream, self._back = _set_replaced_stream(self._streamName, self._replacement)
return mockStream
def __exit__(self, exc_type, exc_value, traceback):
se... | wrapper | identifier_name |
io.py | ## begin license ##
#
# "Weightless" is a High Performance Asynchronous Networking Library. See http://weightless.io
#
# Copyright (C) 2012-2013, 2017, 2020-2021 Seecr (Seek You Too B.V.) https://seecr.nl
#
# This file is part of "Weightless"
#
# "Weightless" is free software; you can redistribute it and/or modify
# it... |
return _ContextMngrOrDecorated(streamName='stderr')
def stdout_replaced(*func_arg):
if func_arg:
return _ContextMngrOrDecorated(streamName='stdout')(*func_arg)
return _ContextMngrOrDecorated(streamName='stdout')
def stdin_replaced(inStream=None):
return _ContextMngrOrDecorated(streamName='std... | return _ContextMngrOrDecorated(streamName='stderr')(*func_arg) | conditional_block |
add_comment.ts | /**
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | } | random_line_split | |
add_comment.ts | /**
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
export async function newReviewCommentThread(
currFilePath,
serverRoot,
commentString,
reviewHash,
lineNumber?
) {
const body: Record<string, string> = {
comment: commentString,
reviewHash: reviewHash,
};
if (lineNumber) {
body.line = lineNumber;
}
httpGitRequest(
'addReviewComment... | {
const body: Record<string, string> = {
comment: commentString,
parent: parentHash,
};
httpGitRequest(
'addDetachedComment',
'POST',
currFilePath,
serverRoot,
body
).then(response => {
console.log(response);
});
} | identifier_body |
add_comment.ts | /**
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | (
currFilePath,
serverRoot,
commentString,
parentHash
) {
const body: Record<string, string> = {
comment: commentString,
parent: parentHash,
};
httpGitRequest(
'addDetachedComment',
'POST',
currFilePath,
serverRoot,
body
).then(response => {
console.log(response);
});
}... | newDetachedCommentReply | identifier_name |
add_comment.ts | /**
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
httpGitRequest(
'addDetachedComment',
'POST',
currFilePath,
serverRoot,
body
).then(response => {
console.log(response);
});
}
export async function newDetachedCommentReply(
currFilePath,
serverRoot,
commentString,
parentHash
) {
const body: Record<string, string> = {
comme... | {
body.line = lineNumber;
} | conditional_block |
create_routine_dialog_controller.js | chromeMyAdmin.controller("CreateRoutineDialogController", ["$scope", "Events", "mySQLClientService", "typeService", "sqlExpressionService", "targetObjectService", function($scope, Events, mySQLClientService, typeService, sqlExpressionService, targetObjectService) {
"use strict";
var onShowDialog = function() {... |
p.push(type);
if (param.typeOption) {
p.push(param.typeOption);
}
params.push(p.join(" "));
});
sql += params.join(", ") + ") ";
if (!$scope.isProcedure()) {
sql += "RETURNS ";
var type = $scope.returnTypeNa... | {
type += "(" + param.typeLength + ")";
} | conditional_block |
create_routine_dialog_controller.js | chromeMyAdmin.controller("CreateRoutineDialogController", ["$scope", "Events", "mySQLClientService", "typeService", "sqlExpressionService", "targetObjectService", function($scope, Events, mySQLClientService, typeService, sqlExpressionService, targetObjectService) {
"use strict";
var onShowDialog = function() {... | $scope.isErrorMessageVisible = function() {
return $scope.errorMessage.length > 0;
};
$scope.initialize = function() {
resetErrorMessage();
assignEventHandlers();
setupItems();
};
$scope.aceLoaded = function(editor) {
$scope.editor = editor;
editor.s... | $scope.errorMessage = "";
};
| random_line_split |
M33_turbstats.py | '''
Run a variety of turbulent statistics on the full M33 cube.
This will use a TON of memory. Recommend running on a cluster.
File structure setup to work on cedar in scratch space.
Saves the outputs for later use
'''
from spectral_cube import SpectralCube
from astropy.io import fits
from os.path import join as os... | scf.save_results(out_path("scf_m33_14B088.pkl"), keep_data=False)
del scf | random_line_split | |
M33_turbstats.py |
'''
Run a variety of turbulent statistics on the full M33 cube.
This will use a TON of memory. Recommend running on a cluster.
File structure setup to work on cedar in scratch space.
Saves the outputs for later use
'''
from spectral_cube import SpectralCube
from astropy.io import fits
from os.path import join as o... |
if run_vca:
log.info("Running VCA")
# Avoid loading in multiple times
try:
cube.shape
except NameError:
cube = SpectralCube.read(cube_name, memmap=False)
# Run VCA over a number of channel sizes.
# First one keeps the original channel width.
chan_widths = [None, 0.4 * u.... | log.info("Running Stat Moments")
mom0 = fits.open(mom0_name)[0]
# Run with a couple of different radii
# Beam size (close to it)
radii = [7, 14, 21] * u.pix
for radius in radii:
log.info("StatMoments radius: {}".format(radius))
moments = StatMoments(mom0, radius=radius).run()
... | conditional_block |
SkeletonBeliefPropagation.py | import numpy as np
''' Belief Propagation on tree'''
class Node:
children = []
parent = -1
pos = -1
index = -1
depth = 0
msgsDown = {}
msgUp = -1
psi = -1
belief = -1
def __init__(self, parent_=-1, index_=-1, children_=[], pos_=-1, depth_=0):
self.index = index_
self.pos = pos_
self.parent = parent... | (self, hypothesis):
if np.any(self.belief >= 0):
self.reset()
leaves = self.getLeaves()
oldLeaves = set()
while np.any(self.belief < 0):
newLeaves = set()
for l in leaves:
l.calcPsi(hypothesis)
l.calcMessageUp()
if np.any(l.msgUp != -1):
oldLeaves.add(l)
if np.any(l.parent != -1... | calcAll | identifier_name |
SkeletonBeliefPropagation.py | import numpy as np
''' Belief Propagation on tree'''
class Node:
children = []
parent = -1
pos = -1
index = -1
depth = 0
msgsDown = {}
msgUp = -1
psi = -1
belief = -1
def __init__(self, parent_=-1, index_=-1, children_=[], pos_=-1, depth_=0):
self.index = index_
self.pos = pos_
self.parent = parent... |
def calcMessageUp(self):
for kid in self.children:
if np.all(kid.msgUp == -1):
return
tmpMsg = 1
# print '-'
tmpMsg *= self.psi
# print self.psi
if self.children != []:
for kid in self.children:
# print np.asarray(kid.msgUp).T[0], tmpMsg
# tmpMsg *= np.asarray(kid.msgUp).T[0]
# tmpM... | pass | identifier_body |
SkeletonBeliefPropagation.py | import numpy as np
''' Belief Propagation on tree'''
class Node:
children = []
parent = -1
pos = -1
index = -1
depth = 0
msgsDown = {}
msgUp = -1
psi = -1
belief = -1
def __init__(self, parent_=-1, index_=-1, children_=[], pos_=-1, depth_=0):
self.index = index_
self.pos = pos_
self.parent = parent... |
if self.children != []:
for kid in self.children:
if np.any(kid.msgUp == -1):
self.belief = -1
break
else:
# self.belief *= np.asarray(kid.msgUp).T[0]
self.belief *= kid.msgUp[0]
if np.all(self.belief >= 0):
self.belief /= np.sum(self.belief)
def updateLeaves(self):
self.ca... | for c in self.parent.msgsDown.keys():
if c == self.index:
# self.belief *= np.array(self.parent.msgsDown[c]).T[0]
self.belief *= self.parent.msgsDown[c][0]
break | conditional_block |
SkeletonBeliefPropagation.py | import numpy as np
''' Belief Propagation on tree'''
class Node:
children = []
parent = -1
pos = -1
index = -1
depth = 0
msgsDown = {}
msgUp = -1
psi = -1
belief = -1
def __init__(self, parent_=-1, index_=-1, children_=[], pos_=-1, depth_=0):
self.index = index_
self.pos = pos_
self.parent = parent... |
def calcTotalBelief(self):
if self.children == []:
return np.max(self.belief)
else:
belief = 1
for kids in self.children:
belief *= kids.calcTotalBelief()
return belief
def calcAll(self, hypothesis):
if np.any(self.belief >= 0):
self.reset()
leaves = self.getLeaves()
oldLeaves = se... | if self.children != []:
for c in self.children:
c.reset() | random_line_split |
CommonConstants.ts | export class | {
public static readonly Links = {
standaloneCreateLearnMore: 'https://go.microsoft.com/fwlink/?linkid=848756',
pythonLearnMore: 'https://go.microsoft.com/fwlink/?linkid=852196',
clientAffinityLearnMore: 'https://go.microsoft.com/fwlink/?linkid=798249',
FTPAccessLearnMore: 'https://go.microsoft.com/f... | CommonConstants | identifier_name |
CommonConstants.ts | export class CommonConstants {
public static readonly Links = {
standaloneCreateLearnMore: 'https://go.microsoft.com/fwlink/?linkid=848756',
pythonLearnMore: 'https://go.microsoft.com/fwlink/?linkid=852196',
clientAffinityLearnMore: 'https://go.microsoft.com/fwlink/?linkid=798249',
FTPAccessLearnMore:... |
public static readonly Kinds = {
linux: 'linux',
aseV2: 'ASEV2',
container: 'container',
functionApp: 'functionapp',
botapp: 'botapp',
elastic: 'elastic', // only applies to server farm
};
public static readonly ApiVersions = {
websiteApiVersion20180201: '2018-02-01',
armBatchApi... | random_line_split | |
workforce3.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;
extern crate itertools;
use gurobi::*;
use itertools::*;
mod workforce;
use workforce::make_model;
fn main() {
let mut env = Env::new("workforce3.log").unwrap();
env.set(param::LogToConsole, 0).unwrap();
let mut model = m... | random_line_split | |
workforce3.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;
extern crate itertools;
use gurobi::*;
use itertools::*;
mod workforce;
use workforce::make_model;
fn main() | &constrs[..],
RepeatN::new(1.0, constrs.len()).collect_vec().as_slice())
.unwrap();
svars.cloned().collect_vec()
};
model.optimize().unwrap();
println!("slack variables: ");
for slack in slacks {
let value = slack.get(&model,... | {
let mut env = Env::new("workforce3.log").unwrap();
env.set(param::LogToConsole, 0).unwrap();
let mut model = make_model(&env).unwrap();
model.optimize().unwrap();
match model.status().unwrap() {
Status::Infeasible => {
let mut model = model.copy().unwrap();
model.set(attr::ModelName, "assi... | identifier_body |
workforce3.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;
extern crate itertools;
use gurobi::*;
use itertools::*;
mod workforce;
use workforce::make_model;
fn main() {
let mut env = Env::new("... |
}
}
| {
println!("Optimization is stopped with status {:?}", status);
} | conditional_block |
workforce3.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;
extern crate itertools;
use gurobi::*;
use itertools::*;
mod workforce;
use workforce::make_model;
fn | () {
let mut env = Env::new("workforce3.log").unwrap();
env.set(param::LogToConsole, 0).unwrap();
let mut model = make_model(&env).unwrap();
model.optimize().unwrap();
match model.status().unwrap() {
Status::Infeasible => {
let mut model = model.copy().unwrap();
model.set(attr::ModelName, "a... | main | identifier_name |
json.rs | extern crate serde_json;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Lines};
use data::{Data, Number};
use expr::Expr;
use row::Row;
use source::{Source, SourceError};
pub struct JsonSource {
lines: Lines<BufReader<File>>,
}
impl JsonSource {
pub fn new(filename: &str)... | }
serde_json::Value::String(s) => Data::String(s),
_ => continue,
};
row.fields.insert(Expr::Column(key), val);
}
return Some(Ok(row));
}
}
#[cfg(test)]
mod tests {
use super::*;
use row::make_rows;
use source::ope... | Data::Number(Number::Float(n.as_f64().unwrap()))
} | random_line_split |
json.rs | extern crate serde_json;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Lines};
use data::{Data, Number};
use expr::Expr;
use row::Row;
use source::{Source, SourceError};
pub struct JsonSource {
lines: Lines<BufReader<File>>,
}
impl JsonSource {
pub fn | (filename: &str) -> Result<Source, SourceError> {
let file = File::open(filename)?;
let reader = BufReader::new(file);
Ok(Box::new(JsonSource { lines: reader.lines() }))
}
}
impl Iterator for JsonSource {
type Item = Result<Row, SourceError>;
fn next(&mut self) -> Option<Self::Item>... | new | identifier_name |
WorkspacesContactsPhoneNumbers.js | /*
INPUT:
* workspaceId
* contactId
DESCRIPTION
An editable list of phone numbers (`workspacesContactsPhoneNumbers`) owned by contactId.
*/
define([
"dojo/_base/declare"
, "dijit/form/ValidationTextBox"
, "put-selector/put"
, "hotplate/hotClientDojo/dgridWidgets/commonMixins"
, "hotplate/hotClientDojo/widgets/E... |
*/ |
var CountrySelect = declare( 'bd/DialCode', Select, {
name: "dialCode",
options: countryOptions
}); | random_line_split |
index.js | var log4js = require("log4js"),
log = log4js.getLogger("megapis-worker"),
request = require("request"),
cheerio = require("cheerio"),
_ = require("lodash"),
async = require("async"),
util = require("util");
var MegapisWorker = require("megapis-worker").MegapisWorker;
function | (config) {
PrimeBooksWorker.super_.call(this, config);
}
util.inherits(PrimeBooksWorker, MegapisWorker);
exports.createWorker = function(config) {
return new PrimeBooksWorker(config);
};
PrimeBooksWorker.prototype.getConfigKeys = function() {
return ["urls", "output"];
};
PrimeBooksWorker.prototype.run... | PrimeBooksWorker | identifier_name |
index.js | var log4js = require("log4js"),
log = log4js.getLogger("megapis-worker"),
request = require("request"),
cheerio = require("cheerio"),
_ = require("lodash"),
async = require("async"),
util = require("util");
var MegapisWorker = require("megapis-worker").MegapisWorker;
function PrimeBooksWorke... | author: author,
url: url
};
}
});
forEachCallback();
});
}, function(err) {
next(err, byUrl);
});
},... | //log.debug("exclude "+url+"="+_.includes(exclude, url));
if (!_.includes(exclude, asin)) {
byUrl[url] = {
asin: asin,
title: title, | random_line_split |
index.js | var log4js = require("log4js"),
log = log4js.getLogger("megapis-worker"),
request = require("request"),
cheerio = require("cheerio"),
_ = require("lodash"),
async = require("async"),
util = require("util");
var MegapisWorker = require("megapis-worker").MegapisWorker;
function PrimeBooksWorke... |
util.inherits(PrimeBooksWorker, MegapisWorker);
exports.createWorker = function(config) {
return new PrimeBooksWorker(config);
};
PrimeBooksWorker.prototype.getConfigKeys = function() {
return ["urls", "output"];
};
PrimeBooksWorker.prototype.run = function(callback) {
var self = this;
async.water... | {
PrimeBooksWorker.super_.call(this, config);
} | identifier_body |
Mi9Controller.js | /**
* Mi9Controller
*
* @description :: Server-side logic for managing mi9s
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
/**
* `Mi9Controller.index()`
*/
index: function(req, res) {
//sails.log.debug(req.body)
if (req.body ... | var json = []
for(var i in req.body.payload){
//sails.log.debug(i)
var src = req.body.payload[i]
if (src.episodeCount && src.episodeCount>0){
var obj = {}
if(src.image && src.image.showImage){
obj.image = src.image.showI... | res.send({
"error": "Could not decode request: JSON parsing failed"
})
} else { | random_line_split |
Mi9Controller.js | /**
* Mi9Controller
*
* @description :: Server-side logic for managing mi9s
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
/**
* `Mi9Controller.index()`
*/
index: function(req, res) {
//sails.log.debug(req.body)
if (req.body ... |
}
return res.json({
response: json
});
}
}
}
| {
var obj = {}
if(src.image && src.image.showImage){
obj.image = src.image.showImage
}
obj.slug = src.slug
obj.title = src.title
json.push(obj)
} | conditional_block |
models.py | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
class Location(models.Model):
address = models.CharField(blank=True)
latitude = models.DecimalField(max_digits=10, decimal_places=6)
longitude = models.DecimalField(max_digits=10, decimal_... | app_label = 'locations'
get_latest_by = 'updated'
ordering = ['updated']
verbose_name = 'location'
verbose_name_plural = 'Locations' | identifier_body | |
models.py | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
class Location(models.Model):
address = models.CharField(blank=True)
latitude = models.DecimalField(max_digits=10, decimal_places=6)
longitude = models.DecimalField(max_digits=10, decimal_... | (self):
return reverse('location-detail', args=[str(self.id)])
def __str__(self):
return '{id: %d, latitude: %d, longitude: %d}' % (
self.id,
self.latitude,
self.longitude
)
class Meta:
app_label = 'locations'
get_latest_by = 'updated... | get_absolute_url | identifier_name |
models.py | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
class Location(models.Model):
address = models.CharField(blank=True)
latitude = models.DecimalField(max_digits=10, decimal_places=6)
longitude = models.DecimalField(max_digits=10, decimal_... | ordering = ['updated']
verbose_name = 'location'
verbose_name_plural = 'Locations' | app_label = 'locations'
get_latest_by = 'updated' | random_line_split |
forms.py | # Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from wtforms import validators
from ..forms import ModelForm
from digits import utils
class | (ModelForm):
"""
Defines the form used to create a new ImageModelJob
"""
crop_size = utils.forms.IntegerField(
'Crop Size',
validators=[
validators.NumberRange(min=1),
validators.Optional()
],
tooltip=("If specified, during training a random squar... | ImageModelForm | identifier_name |
forms.py | # Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from wtforms import validators
from ..forms import ModelForm
from digits import utils
class ImageModelForm(ModelForm):
"""
Defines the form used to create a new ImageModelJob
"""
crop_size = ... | ],
tooltip=("Standard deviation of a shift that will be performed during "
"preprocessing, assuming [0 1] pixel-value range.")
) | default=0.06,
validators=[
validators.NumberRange(min=0, max=0.5) | random_line_split |
forms.py | # Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from wtforms import validators
from ..forms import ModelForm
from digits import utils
class ImageModelForm(ModelForm):
| ],
default='image',
tooltip="Subtract the mean file or mean pixel for this dataset from each image."
)
aug_flip = utils.forms.SelectField(
'Flipping',
choices=[
('none', 'None'),
('fliplr', 'Horizontal'),
('flipud', 'Vertical'),
... | """
Defines the form used to create a new ImageModelJob
"""
crop_size = utils.forms.IntegerField(
'Crop Size',
validators=[
validators.NumberRange(min=1),
validators.Optional()
],
tooltip=("If specified, during training a random square crop will be "
... | identifier_body |
exceptions.ts | import {ListWrapper, List} from 'angular2/src/facade/collection';
import {stringify, BaseException, isBlank} from 'angular2/src/facade/lang';
function findFirstClosedCycle(keys: List<any>): List<any> {
var res = [];
for (var i = 0; i < keys.length; ++i) {
if (ListWrapper.contains(res, keys[i])) {
res.pus... | (): string { return this.message; }
}
| toString | identifier_name |
exceptions.ts | import {ListWrapper, List} from 'angular2/src/facade/collection';
import {stringify, BaseException, isBlank} from 'angular2/src/facade/lang';
function findFirstClosedCycle(keys: List<any>): List<any> {
var res = [];
for (var i = 0; i < keys.length; ++i) {
if (ListWrapper.contains(res, keys[i])) {
res.pus... | * ]);
*
* injector.asyncGet(String).then((v) => expect(v).toBe('Value: 3'));
* expect(() => {
* injector.get(String);
* }).toThrowError(AsycBindingError);
* ```
*
* The above example throws because `String` depends on `Number` which is async. If any binding in
* the dependency graph is async then the graph ... | random_line_split | |
exceptions.ts | import {ListWrapper, List} from 'angular2/src/facade/collection';
import {stringify, BaseException, isBlank} from 'angular2/src/facade/lang';
function findFirstClosedCycle(keys: List<any>): List<any> {
var res = [];
for (var i = 0; i < keys.length; ++i) {
if (ListWrapper.contains(res, keys[i])) {
res.pus... | else {
signature.push(ListWrapper.map(parameter, stringify).join(' '));
}
}
this.message = "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" +
signature.join(', ') + "). " +
'Make sure they all have valid type or annotations.';
}
toStrin... | {
signature.push('?');
} | conditional_block |
exceptions.ts | import {ListWrapper, List} from 'angular2/src/facade/collection';
import {stringify, BaseException, isBlank} from 'angular2/src/facade/lang';
function findFirstClosedCycle(keys: List<any>): List<any> {
var res = [];
for (var i = 0; i < keys.length; ++i) {
if (ListWrapper.contains(res, keys[i])) {
res.pus... |
}
/**
* Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the
* {@link Injector} does not have a {@link Binding} for {@link Key}.
*
* @exportedAs angular2/di_errors
*/
export class NoBindingError extends AbstractBindingError {
// TODO(tbosch): Can't do key:Key as this results in a... | { return this.message; } | identifier_body |
releaseStatsRequest.tsx | ';
import {displayCrashFreePercent, getCrashFreePercent, roundDuration} from '../../utils';
import {sessionTerm} from '../../utils/sessionTerm';
import {EventType, YAxis} from './chart/releaseChartControls';
import {getInterval, getReleaseEventView} from './chart/utils';
const omitIgnoredProps = (props: Props) =>
... |
this.setState({
reloading: false,
data,
});
};
fetchCountData = async (type: YAxis) => {
const {api, yAxis} = this.props;
const response = await api.requestPromise(this.statsPath, {
query: {
...this.baseQueryParams,
type,
},
});
const transformedD... | {
return;
} | conditional_block |
releaseStatsRequest.tsx | atters';
import {displayCrashFreePercent, getCrashFreePercent, roundDuration} from '../../utils';
import {sessionTerm} from '../../utils/sessionTerm';
import {EventType, YAxis} from './chart/releaseChartControls';
import {getInterval, getReleaseEventView} from './chart/utils';
const omitIgnoredProps = (props: Props)... | users: {
seriesName: sessionTerm['crash-free-users'],
data: [],
color: CHART_PALETTE[1][0],
},
sessions: {
seriesName: sessionTerm['crash-free-sessions'],
data: [],
color: CHART_PALETTE[1][1],
},
};
const calculateDatePercentage = (respons... | responseUsersData,
responseSessionsData
): Omit<Data, 'crashFreeTimeBreakdown'> {
const chartData: ChartData = { | random_line_split |
releaseStatsRequest.tsx | ';
import {displayCrashFreePercent, getCrashFreePercent, roundDuration} from '../../utils';
import {sessionTerm} from '../../utils/sessionTerm';
import {EventType, YAxis} from './chart/releaseChartControls';
import {getInterval, getReleaseEventView} from './chart/utils';
const omitIgnoredProps = (props: Props) =>
... |
componentWillUnmount() {
this.unmounting = true;
}
private unmounting: boolean = false;
fetchData = async () => {
let data: Data | null = null;
const {yAxis, hasHealthData, hasDiscover, hasPerformance} = this.props;
if (!hasHealthData && !hasDiscover && !hasPerformance) {
return;
... | {
if (isEqual(omitIgnoredProps(prevProps), omitIgnoredProps(this.props))) {
return;
}
this.fetchData();
} | identifier_body |
releaseStatsRequest.tsx | string;
selection: GlobalSelection;
location: Location;
yAxis: YAxis;
eventType: EventType;
children: (renderProps: ReleaseStatsRequestRenderProps) => React.ReactNode;
hasHealthData: boolean;
hasDiscover: boolean;
hasPerformance: boolean;
};
type State = {
reloading: boolean;
errored: boolean;
da... | transformSessionDurationData | identifier_name | |
TestAsinpi.rs | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by app... |
#pragma version(1)
#pragma rs java_package_name(android.renderscript.cts)
// Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime.
float __attribute__((kernel)) testAsinpiFloatFloat(float inV) {
return asinpi(inV);
}
float2 __attribute__((kernel)) testAsinpiFloat2Float2(float2 inV) {
... | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | random_line_split |
plot2.py | #!/usr/bin/env python2
from glob import glob
import re
import matplotlib.pyplot as plt
import numpy as np
from sys import argv
def get_a1(pattern):
a1 = {}
for fit_file in glob(pattern):
with open(fit_file) as f:
line = f.readline()
coeffs = line.split(' ')
fit_par... |
a1[fit_params[0]].append((float(fit_params[1]), float(coeffs[1])))
# Sort and remove the soring hints
for key in a1.keys():
a1[key] = sorted(a1[key], key=lambda x: x[0])
a1[key] = dict(y=map(lambda x: float(x[1]), a1[key]),
x=map(lambda x: float(x[0]), a1[ke... | a1[fit_params[0]] = [] | conditional_block |
plot2.py | #!/usr/bin/env python2
from glob import glob |
def get_a1(pattern):
a1 = {}
for fit_file in glob(pattern):
with open(fit_file) as f:
line = f.readline()
coeffs = line.split(' ')
fit_params = fit_file.split('-')
if fit_params[0] not in a1:
a1[fit_params[0]] = []
a1[fit_pa... | import re
import matplotlib.pyplot as plt
import numpy as np
from sys import argv | random_line_split |
plot2.py | #!/usr/bin/env python2
from glob import glob
import re
import matplotlib.pyplot as plt
import numpy as np
from sys import argv
def get_a1(pattern):
|
def plot_a1():
a1 = get_a1(argv[1])
fig, ax = plt.subplots()
for domain in sorted(a1.keys(), key=lambda x: float(x)):
ax.plot(a1[domain]['x'], a1[domain]['y'],
label='%s pi' % (domain))
ax.legend(loc=0)
fig.savefig('a1.png', dpi=300)
plt.show()
if __name__ == '__mai... | a1 = {}
for fit_file in glob(pattern):
with open(fit_file) as f:
line = f.readline()
coeffs = line.split(' ')
fit_params = fit_file.split('-')
if fit_params[0] not in a1:
a1[fit_params[0]] = []
a1[fit_params[0]].append((float(fit_... | identifier_body |
plot2.py | #!/usr/bin/env python2
from glob import glob
import re
import matplotlib.pyplot as plt
import numpy as np
from sys import argv
def get_a1(pattern):
a1 = {}
for fit_file in glob(pattern):
with open(fit_file) as f:
line = f.readline()
coeffs = line.split(' ')
fit_par... | ():
a1 = get_a1(argv[1])
fig, ax = plt.subplots()
for domain in sorted(a1.keys(), key=lambda x: float(x)):
ax.plot(a1[domain]['x'], a1[domain]['y'],
label='%s pi' % (domain))
ax.legend(loc=0)
fig.savefig('a1.png', dpi=300)
plt.show()
if __name__ == '__main__':
plo... | plot_a1 | identifier_name |
test_logdir.py | #!/usr/bin/python
import apt_pkg
import logging
import os
import mock
import sys
import tempfile
import unittest
sys.path.insert(0, "..")
from unattended_upgrade import _setup_logging
class | :
dry_run = False
debug = False
class TestLogdir(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp()
apt_pkg.init()
self.mock_options = MockOptions()
def test_logdir(self):
# test log
logdir = os.path.join(self.tempdir, "mylog")
apt_p... | MockOptions | identifier_name |
test_logdir.py | #!/usr/bin/python
import apt_pkg
import logging
import os
import mock
import sys
import tempfile
import unittest
sys.path.insert(0, "..")
from unattended_upgrade import _setup_logging
class MockOptions:
dry_run = False
debug = False
class TestLogdir(unittest.TestCase):
def setUp(self):
self.tem... | logging.basicConfig(level=logging.DEBUG)
unittest.main() | conditional_block | |
test_logdir.py | #!/usr/bin/python
import apt_pkg
import logging
import os
import mock
import sys
import tempfile
import unittest
sys.path.insert(0, "..")
from unattended_upgrade import _setup_logging
class MockOptions:
|
class TestLogdir(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp()
apt_pkg.init()
self.mock_options = MockOptions()
def test_logdir(self):
# test log
logdir = os.path.join(self.tempdir, "mylog")
apt_pkg.config.set("Unattended-Upgrade::LogD... | dry_run = False
debug = False | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.