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 |
|---|---|---|---|---|
event_store.js | import { EventBus } from '../wires/event_bus';
class EventStore {
constructor(storeAdapter) {
this.adapter = storeAdapter;
}
appendToStream(streamId, expectedVersion, events) {
if (events.length === 0) {
return;
}
events.forEach(function(event) {
thi... | (streamId) {
var version = 0,
events = [],
records = this.readEventStream(streamId, 0, null);
records.forEach(function(r) {
version = r.version;
events.push(r.data);
});
return new EventStream(streamId, events, version);
}
readEve... | loadEventStream | identifier_name |
Repairpply.js | // JavaScript Document
var flag1=true;
var flag2=true;
$(function () {
/*********************/
$.ajax({
type : 'POST',
dataType : 'json',
url : 'baseNeiName.do',
async : true,
cache : false,
error : function(request) {
bootbox.alert({
message : "请求异常",
size : 's... | size : 'small'
});
return 0;
}
else if(baselist=="请选择"){
bootbox.alert({
message : "请选择基地",
size : 'small'
});
return 0;
}
else if(reason==""){
bootbox.alert({
message : "请填写原因",
size : 'small'
});
return 0;
}
if (!flag1) {
... | random_line_split | |
dtrun.py | #
# Copyright (C) 2001 Andrew T. Csillag <drew_csillag@geocities.com>
#
# You may distribute under the terms of either the GNU General
# Public License or the SkunkWeb License, as specified in the
# README file.
#
import os
import DT
import sys
import time
import marshal
import stat
def phf... |
ns=dumb()
text = d(ns)
et = time.time()
print text
print 'elapsed time:', et - bt
| pass | identifier_body |
dtrun.py | #
# Copyright (C) 2001 Andrew T. Csillag <drew_csillag@geocities.com>
#
# You may distribute under the terms of either the GNU General
# Public License or the SkunkWeb License, as specified in the
# README file.
#
import os
import DT
import sys
import time
import marshal
import stat
def phf... | bt = time.time()
fname=sys.argv[1]
mtime=os.stat(fname)[stat.ST_MTIME]
cform=sys.argv[1]+'.dtcc'
try:
cmtime=os.stat(cform)[stat.ST_MTIME]
comp_form=marshal.load(open(cform))
except:
comp_form=None
cmtime=-1
d=DT.DT(open(fname).read(), fname, comp_form, mtime, cmt... | conditional_block | |
dtrun.py | #
# Copyright (C) 2001 Andrew T. Csillag <drew_csillag@geocities.com>
#
# You may distribute under the terms of either the GNU General
# Public License or the SkunkWeb License, as specified in the
# README file.
#
import os
import DT
import sys
import time
import marshal
import stat
def phf... | et = time.time()
print text
print 'elapsed time:', et - bt | random_line_split | |
dtrun.py | #
# Copyright (C) 2001 Andrew T. Csillag <drew_csillag@geocities.com>
#
# You may distribute under the terms of either the GNU General
# Public License or the SkunkWeb License, as specified in the
# README file.
#
import os
import DT
import sys
import time
import marshal
import stat
def phf... | : pass
ns=dumb()
text = d(ns)
et = time.time()
print text
print 'elapsed time:', et - bt
| dumb | identifier_name |
templateresponse.py | import logging
from xml.dom.minidom import *
from jinja2 import Environment, Template
from edge.dateutility import DateUtility
from edge.opensearch.response import Response
class TemplateResponse(Response):
def __init__(self):
super(TemplateResponse, self).__init__()
self.env = Environment()
... | return self.template.render(self.variables).replace('\n', '') | conditional_block | |
templateresponse.py | import logging
from xml.dom.minidom import *
from jinja2 import Environment, Template
from edge.dateutility import DateUtility
from edge.opensearch.response import Response
class TemplateResponse(Response):
def __init__(self):
super(TemplateResponse, self).__init__()
self.env = Environment()
... | (self, pretty=False):
logging.debug('TemplateResponse.generate is called.')
if pretty:
try :
xmlStr = self.template.render(self.variables).encode('utf-8').replace('\n', '')
except Exception as e:
logging.debug("Problem generating template ... | generate | identifier_name |
templateresponse.py | import logging
from xml.dom.minidom import *
from jinja2 import Environment, Template
from edge.dateutility import DateUtility
from edge.opensearch.response import Response
class TemplateResponse(Response):
| document = xml.dom.minidom.parseString(xmlStr)
return document.toprettyxml()
else:
return self.template.render(self.variables).replace('\n', '')
| def __init__(self):
super(TemplateResponse, self).__init__()
self.env = Environment()
self.env.trim_blocks = True
self.env.autoescape = True
self.variables = {}
self.env.filters['convertISOTime'] = DateUtility.convertISOTime
def setTemplate(self, template):
s... | identifier_body |
templateresponse.py | import logging
from xml.dom.minidom import *
from jinja2 import Environment, Template
from edge.dateutility import DateUtility
from edge.opensearch.response import Response
| self.env = Environment()
self.env.trim_blocks = True
self.env.autoescape = True
self.variables = {}
self.env.filters['convertISOTime'] = DateUtility.convertISOTime
def setTemplate(self, template):
self.template = self.env.from_string(template)
def generate(self,... | class TemplateResponse(Response):
def __init__(self):
super(TemplateResponse, self).__init__() | random_line_split |
run.ts | import pkgConf from "pkg-conf";
import { ApplicationFunction, Options, ServerOptions } from "./types";
import { Probot } from "./index";
import { setupAppFactory } from "./apps/setup";
import { getLog, GetLogOptions } from "./helpers/get-log";
import { readCliOptions } from "./bin/read-cli-options";
import { readEnvOp... | (
appFnOrArgv: ApplicationFunction | string[],
additionalOptions?: AdditionalOptions
) {
require("dotenv").config();
const envOptions = readEnvOptions(additionalOptions?.env);
const cliOptions = Array.isArray(appFnOrArgv)
? readCliOptions(appFnOrArgv)
: {};
const {
// log options
logLevel:... | run | identifier_name |
run.ts | import pkgConf from "pkg-conf";
import { ApplicationFunction, Options, ServerOptions } from "./types";
import { Probot } from "./index";
import { setupAppFactory } from "./apps/setup";
import { getLog, GetLogOptions } from "./helpers/get-log";
import { readCliOptions } from "./bin/read-cli-options";
import { readEnvOp... | webhookProxy,
// probot options
appId,
privateKey,
redisConfig,
secret,
baseUrl,
// others
args,
} = { ...envOptions, ...cliOptions };
const logOptions: GetLogOptions = {
level,
logFormat,
logLevelInString,
logMessageKey,
sentryDsn,
};
const log = getL... | {
require("dotenv").config();
const envOptions = readEnvOptions(additionalOptions?.env);
const cliOptions = Array.isArray(appFnOrArgv)
? readCliOptions(appFnOrArgv)
: {};
const {
// log options
logLevel: level,
logFormat,
logLevelInString,
logMessageKey,
sentryDsn,
// serv... | identifier_body |
run.ts | import pkgConf from "pkg-conf";
import { ApplicationFunction, Options, ServerOptions } from "./types";
import { Probot } from "./index";
import { setupAppFactory } from "./apps/setup";
import { getLog, GetLogOptions } from "./helpers/get-log";
import { readCliOptions } from "./bin/read-cli-options";
import { readEnvOp... | );
}
}
// Workaround for setup (#1512)
// When probot is started for the first time, it gets into a setup mode
// where `appId` and `privateKey` are not present. The setup mode gets
// these credentials. In order to not throw an error, we set the values
// to anything, as the Prob... | } else if (!privateKey) {
throw new Error(
"Certificate is missing, and is required to run in production mode. " +
"To resolve, ensure either the PRIVATE_KEY or PRIVATE_KEY_PATH environment variable is set and contains a valid certificate" | random_line_split |
run.ts | import pkgConf from "pkg-conf";
import { ApplicationFunction, Options, ServerOptions } from "./types";
import { Probot } from "./index";
import { setupAppFactory } from "./apps/setup";
import { getLog, GetLogOptions } from "./helpers/get-log";
import { readCliOptions } from "./bin/read-cli-options";
import { readEnvOp... | await server.start();
return server;
}
server = new Server(serverOptions);
await server.load(appFnOrArgv);
await server.start();
return server;
}
| {
const pkg = await pkgConf("probot");
const combinedApps: ApplicationFunction = async (app) => {
await server.load(defaultApp);
if (Array.isArray(pkg.apps)) {
for (const appPath of pkg.apps) {
const appFn = await resolveAppFunction(appPath);
await server.load(appFn);
... | conditional_block |
deb.rs | use std::process::Command;
use datatype::{Error, Package, UpdateResultCode};
use package_manager::package_manager::{InstallOutcome, parse_package};
/// Returns a list of installed DEB packages with
/// `dpkg-query -f='${Package} ${Version}\n' -W`.
pub fn installed_packages() -> Result<Vec<Package>, Error> {
Comm... | }
}
| {
let output = try!(Command::new("dpkg").arg("-E").arg("-i").arg(path)
.output()
.map_err(|e| (UpdateResultCode::GENERAL_ERROR, format!("{:?}", e))));
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
m... | identifier_body |
deb.rs | use std::process::Command;
use datatype::{Error, Package, UpdateResultCode};
use package_manager::package_manager::{InstallOutcome, parse_package};
/// Returns a list of installed DEB packages with
/// `dpkg-query -f='${Package} ${Version}\n' -W`.
pub fn installed_packages() -> Result<Vec<Package>, Error> {
Comm... | Ok((UpdateResultCode::ALREADY_PROCESSED, stdout))
} else {
Ok((UpdateResultCode::OK, stdout))
}
}
_ => {
let out = format!("stdout: {}\nstderr: {}", stdout, stderr);
Err((UpdateResultCode::INSTALL_FAILED, out))
}
... |
match output.status.code() {
Some(0) => {
if (&stdout).contains("already installed") { | random_line_split |
deb.rs | use std::process::Command;
use datatype::{Error, Package, UpdateResultCode};
use package_manager::package_manager::{InstallOutcome, parse_package};
/// Returns a list of installed DEB packages with
/// `dpkg-query -f='${Package} ${Version}\n' -W`.
pub fn installed_packages() -> Result<Vec<Package>, Error> {
Comm... |
_ => {
let out = format!("stdout: {}\nstderr: {}", stdout, stderr);
Err((UpdateResultCode::INSTALL_FAILED, out))
}
}
}
| {
if (&stdout).contains("already installed") {
Ok((UpdateResultCode::ALREADY_PROCESSED, stdout))
} else {
Ok((UpdateResultCode::OK, stdout))
}
} | conditional_block |
deb.rs | use std::process::Command;
use datatype::{Error, Package, UpdateResultCode};
use package_manager::package_manager::{InstallOutcome, parse_package};
/// Returns a list of installed DEB packages with
/// `dpkg-query -f='${Package} ${Version}\n' -W`.
pub fn | () -> Result<Vec<Package>, Error> {
Command::new("dpkg-query").arg("-f='${Package} ${Version}\n'").arg("-W")
.output()
.map_err(|e| Error::Package(format!("Error fetching packages: {}", e)))
.and_then(|c| {
String::from_utf8(c.stdout)
.map_err(|e| Error::Parse(for... | installed_packages | identifier_name |
vendor.service.ts | Shader Collection
2610555297, // Iron Banner
2648860054, // Iron Lord
2668878854, // Vanguard Quartermaster
2680694281, // The Speaker
2762206170, // Postmaster
2796397637, // Agent of the Nine
3003633346, // Hunter Vanguard
3301500998, // Emblem Collection
3611686524, // Dead Orbit
3658200622, // ... | (vendor: Vendor, store: D1Store, vendorDef: VendorDefinition) {
return (
vendor &&
vendor.expires > Date.now() &&
vendor.factionLevel === factionLevel(store, vendorDef.summary.factionHash) &&
vendor.factionAligned === factionAligned(store, vendorDef.summary.factionHash)
);
}
function loadVendor(
... | cachedVendorUpToDate | identifier_name |
vendor.service.ts | Shader Collection
2610555297, // Iron Banner
2648860054, // Iron Lord
2668878854, // Vanguard Quartermaster
2680694281, // The Speaker
2762206170, // Postmaster
2796397637, // Agent of the Nine
3003633346, // Hunter Vanguard
3301500998, // Emblem Collection
3611686524, // Dead Orbit
3658200622, // ... | else {
mergedVendor.categories.push(category);
}
});
});
mergedVendor.allItems = mergedVendor.categories.flatMap((i) => i.saleItems);
return mergedVendor;
}
function mergeCategory(
mergedCategory: {
index: number;
title: string;
saleItems: VendorSaleItem[];
},
otherCategory... | {
mergeCategory(existingCategory, category);
} | conditional_block |
vendor.service.ts | number;
costs: { value: number; itemHash: number }[];
failureIndexes: number[];
unlockStatuses: { isSet: boolean }[];
}[];
categoryIndex: number;
}[];
}
interface VendorDefinition {
hash: number;
summary: {
vendorName: string;
factionHash: number;
factionIcon?: string;
... | {
const def = vendorDef.summary;
const createdVendor: Vendor = {
def: vendorDef,
hash: vendorDef.hash,
name: def.vendorName,
icon: def.factionIcon || def.vendorIcon,
nextRefreshDate: vendor.nextRefreshDate,
cacheKeys: {
[store.id]: {
expires: vendor.expires,
factionLeve... | identifier_body | |
vendor.service.ts | (
vendorList.flatMap((vendorDef) =>
fetchVendor(vendorDef, characters, account, defs, buckets)
)
)
);
return _.keyBy(vendors, (v) => v.hash);
})();
loadingTracker.addPromise(reloadPromise);
return reloadPromise;
};
}
async function fetchVendor(
vendo... | 'icon',
'itemHash'
),
})) | random_line_split | |
ifr_gain_machine.py | # http://github.com/ratt-ru/CubiCal
# This code is distributed under the terms of GPLv2, see LICENSE.md for details
from __future__ import print_function
import numpy as np
from numpy.ma import masked_array
from cubical import param_db
from cubical.tools import logger, ModColor
log = logger.getLogger("gain_machine")
... |
ddh = subdict['ifrgains:DDH__']
# promote corr1,corr2 axes in flags, to make them into a proper mask
fl = np.empty(ddh.shape, bool)
fl[:] = subdict['ifrgains:flags__'][...,np.newaxis,np.newaxis]
ddh = masked_array(ddh, fl, fill_value=0)
mdh = masked_array(subdict['ifrgai... | return | conditional_block |
ifr_gain_machine.py | numpy.ma import masked_array
from cubical import param_db
from cubical.tools import logger, ModColor
log = logger.getLogger("gain_machine")
class IfrGainMachine(object):
"""
Interferometer-based gain machine.
Note that this class is outside of the normal gain machine hierarchy. It wraps all the
... | reload | identifier_name | |
ifr_gain_machine.py | # http://github.com/ratt-ru/CubiCal
# This code is distributed under the terms of GPLv2, see LICENSE.md for details
from __future__ import print_function
import numpy as np
from numpy.ma import masked_array
from cubical import param_db
from cubical.tools import logger, ModColor
log = logger.getLogger("gain_machine")
... | # reset off-diagonal values, if needed
if ifrgain_opts["apply-2x2"]:
print(ModColor.Str(
" using full 2x2 BBCs. You'd better know what you're doing!",col="green"), file=log(0))
else:
... | print(" using one mean value across band", file=log(0))
self._ifrgain[np.newaxis,...] = self._ifrgain.mean(axis=0) | random_line_split |
ifr_gain_machine.py | # http://github.com/ratt-ru/CubiCal
# This code is distributed under the terms of GPLv2, see LICENSE.md for details
from __future__ import print_function
import numpy as np
from numpy.ma import masked_array
from cubical import param_db
from cubical.tools import logger, ModColor
log = logger.getLogger("gain_machine")
... |
def apply(self, obser_arr, freq_slice):
"""
Applies IFR-based gains (if any) to input data
Args:
obser_arr: data array (shape ntime,nfreq,nant,nant,ncorr,ncorr)
freq_slice: frequency slice in data array
"""
# IFR gains are freq,ant,ant,cor... | """Returns True if we're computing output IFR gains"""
return self._ifrgains_grid is not None | identifier_body |
variable3x5x8.rs |
pub fn bits_used_for_label(label: u64) -> u8 {
if label & 0b1 != 0 {
3 + 1
} else if label & 0b10 != 0 {
5 + 2
} else {
8 + 2
}
}
pub fn bits_used_for_number(number: u32) -> u8 {
match number {
n if n < 8 => 3 + 1,
n if n < 33 => 5 + 2,
_ => 8 + 2
}
}
pub fn compress(number: u32) -> u64 ... | (label: u64) -> u32 {
match bits_used_for_label(label) {
4 => {
match (label >> 1) & 0b111 {
0b000 => 1,
0b001 => 0,
n => n as u32
}
},
7 => {
match (label >> 2) & 0b1_1111 {
0b0_0000 => 0,
n => (n + 1) as u32
}
},
10 => {
match (label >> 2) & 0b1111_1111 {
0... | decompress | identifier_name |
variable3x5x8.rs | pub fn bits_used_for_label(label: u64) -> u8 {
if label & 0b1 != 0 {
3 + 1
} else if label & 0b10 != 0 {
5 + 2
} else {
8 + 2
}
}
pub fn bits_used_for_number(number: u32) -> u8 {
match number {
n if n < 8 => 3 + 1,
n if n < 33 => 5 + 2,
_ => 8 + 2
}
}
pub fn compress(number: u32) -> u64 {... | },
_ => unreachable!()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_compress_decompress() {
for i in range(0, 257) {
assert_eq!(i, decompress(compress(i)))
}
}
} | 0b0000_0000 => 0,
n => (n + 1) as u32
} | random_line_split |
variable3x5x8.rs |
pub fn bits_used_for_label(label: u64) -> u8 {
if label & 0b1 != 0 {
3 + 1
} else if label & 0b10 != 0 {
5 + 2
} else {
8 + 2
}
}
pub fn bits_used_for_number(number: u32) -> u8 |
pub fn compress(number: u32) -> u64 {
if number == 1 {
return 1;
}
match bits_used_for_number(number) {
4 => {
match number {
0 => 0b0011,
n => ((n << 1) | 0b1) as u64
}
},
7 => {
match number {
0 => 0b000_0010,
n => (((n - 1) << 2) | 0b10) as u64
}
},
10 => {
match numb... | {
match number {
n if n < 8 => 3 + 1,
n if n < 33 => 5 + 2,
_ => 8 + 2
}
} | identifier_body |
strings.js | define( | locatorUrl: "URL Trình mã hóa địa lý",
geocoderOptions: "Tùy chọn của trình mã hóa địa lý",
autoComplete: "Tự động hoàn tất",
maxLocations: "Vị trí tối đa",
minCharacters: "Ký tự tối đa",
searchDelay: "Trì hoãn tìm kiếm",
placeholder: "Trình giữ chỗ",
routeOptions: "Tùy chọn định tuyến",... | ({
routeUrl: "URL tuyến đường", | random_line_split |
timer.rs | use super::RW;
use super::thread::Handler;
use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl};
use mio_orig::{self, EventLoop, Token, EventSet};
use std::time::{Instant, Duration};
/// A Timer generating event after a given time
///
/// Use `MiocoHandle::select()` to wait for an event, or `rea... | fn should_resume(&self) -> bool {
trace!("Timer: should_resume? {}",
self.timeout <= Instant::now());
self.timeout <= Instant::now()
}
}
impl EventSourceTrait for TimerCore {
fn register(&mut self,
event_loop: &mut EventLoop<Handler>,
token: To... | self.rc.io_ref().timeout
}
}
impl TimerCore { | random_line_split |
timer.rs | use super::RW;
use super::thread::Handler;
use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl};
use mio_orig::{self, EventLoop, Token, EventSet};
use std::time::{Instant, Duration};
/// A Timer generating event after a given time
///
/// Use `MiocoHandle::select()` to wait for an event, or `rea... |
}
impl EventedImpl for Timer {
type Raw = TimerCore;
fn shared(&self) -> &RcEventSource<TimerCore> {
&self.rc
}
}
impl Timer {
/// Read a timer to block on it until it is done.
///
/// Returns current time
///
/// TODO: Return wakeup time instead
pub fn read(&mut self) ->... | {
Timer::new()
} | identifier_body |
timer.rs | use super::RW;
use super::thread::Handler;
use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl};
use mio_orig::{self, EventLoop, Token, EventSet};
use std::time::{Instant, Duration};
/// A Timer generating event after a given time
///
/// Use `MiocoHandle::select()` to wait for an event, or `rea... |
}
false
}
fn reregister(&mut self,
event_loop: &mut EventLoop<Handler>,
token: Token,
interest: EventSet) -> bool {
if let Some(timeout) = self.mio_timeout {
event_loop.clear_timeout(timeout);
}
self.regi... | {
panic!("Could not create mio::Timeout: {:?}", reason);
} | conditional_block |
timer.rs | use super::RW;
use super::thread::Handler;
use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl};
use mio_orig::{self, EventLoop, Token, EventSet};
use std::time::{Instant, Duration};
/// A Timer generating event after a given time
///
/// Use `MiocoHandle::select()` to wait for an event, or `rea... | (&mut self, event_loop: &mut EventLoop<Handler>, _token: Token) {
if let Some(timeout) = self.mio_timeout {
event_loop.clear_timeout(timeout);
}
}
}
unsafe impl Send for Timer {}
| deregister | identifier_name |
aggregation.d.ts | export interface IAggregationOptions {
distinct: boolean;
separator: string;
}
export declare class | {
constructor();
static first(rows: any[], getValue: (row: any) => any): any;
static last(rows: any[], getValue: (row: any) => any): any;
static max(rows: any[], getValue: (row: any) => any): any;
static min(rows: any[], getValue: (row: any) => any): any;
static minMax(rows: any[], getValue: (row: any) => any): ... | Aggregation | identifier_name |
aggregation.d.ts | export interface IAggregationOptions {
distinct: boolean; | export declare class Aggregation {
constructor();
static first(rows: any[], getValue: (row: any) => any): any;
static last(rows: any[], getValue: (row: any) => any): any;
static max(rows: any[], getValue: (row: any) => any): any;
static min(rows: any[], getValue: (row: any) => any): any;
static minMax(rows: any[]... | separator: string;
}
| random_line_split |
js-itm.js | }
return radlat2;
}
/**
* Un-project Transverse Mercator eastings and northings back to latitude and longtitude.
*
* @param {JSITM.Point} point
* @return {JSITM.LatLng} latitude and longtitude on the refernced ellipsoid's surface
*/
JSITM.TM.prototype.unproject = function(point){
//
//Input: - _
... | {
var str = new String(num);
while (str.length < len) {
str = '0' + str;
}
return str;
} | identifier_body | |
js-itm.js | M.Point}
*/
JSITM.Translation.prototype.translate = function(point){
return new JSITM.Point(point.x + this.dx, point.y + this.dy, point.z + this.dz);
}
/**
* Returns an new Translation with inverse values.
* @return {JSITM.Translation}
*/
JSITM.Translation.prototype.inverse = function(){
return new JSITM.T... |
return radlat2;
}
/**
* Un-project Transverse Mercator eastings and northings back to latitude and longtitude.
*
* @param {JSITM.Point} point
* @return {JSITM.LatLng} latitude and longtitude on the refernced ellipsoid's surface
*/
JSITM.TM.prototype.unproject = function(point){
//
//Input: - _
... | {
radlat2 = ((y - this.n0 - M) / this.af0) + radlat1;
M = this.Marc(radlat2);
radlat1 = radlat2;
} | conditional_block |
js-itm.js | (n, precision){
var m = Math.pow(10, precision || 0);
return Math.round(n * m) / m;
}
return round(this.lat, this.precision) + " " + round(this.lng, this.precision);
}
/**
* Creates a new LatLng by converting coordinates from a source ellipsoid to a target one. <p>
* This process involve... | round | identifier_name | |
js-itm.js | * Un-project Transverse Mercator eastings and northings back to latitude and longtitude.
*
* @param {JSITM.Point} point
* @return {JSITM.LatLng} latitude and longtitude on the refernced ellipsoid's surface
*/
JSITM.TM.prototype.unproject = function(point){
//
//Input: - _
//Compute Et
var Et... | return str;
}
var p = precision || 6;
| random_line_split | |
IfcDiscreteAccessoryType.g.ts |
import {BaseIfc} from "./BaseIfc"
import {IfcGloballyUniqueId} from "./IfcGloballyUniqueId.g"
import {IfcOwnerHistory} from "./IfcOwnerHistory.g"
import {IfcLabel} from "./IfcLabel.g"
import {IfcText} from "./IfcText.g"
import {IfcRelAssigns} from "./IfcRelAssigns.g"
import {IfcRelNests} from "./IfcRelNests.g"
import ... | () : string {
var parameters = new Array<string>();
parameters.push(BaseIfc.toStepValue(this.GlobalId))
parameters.push(BaseIfc.toStepValue(this.OwnerHistory))
parameters.push(BaseIfc.toStepValue(this.Name))
parameters.push(BaseIfc.toStepValue(this.Description))
parameters.push(BaseIfc.toStepValue(thi... | getStepParameters | identifier_name |
IfcDiscreteAccessoryType.g.ts | import {BaseIfc} from "./BaseIfc"
import {IfcGloballyUniqueId} from "./IfcGloballyUniqueId.g"
import {IfcOwnerHistory} from "./IfcOwnerHistory.g"
import {IfcLabel} from "./IfcLabel.g"
import {IfcText} from "./IfcText.g"
import {IfcRelAssigns} from "./IfcRelAssigns.g"
import {IfcRelNests} from "./IfcRelNests.g"
import {... | /**
* http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcdiscreteaccessorytype.htm
*/
export class IfcDiscreteAccessoryType extends IfcElementComponentType {
PredefinedType : IfcDiscreteAccessoryTypeEnum
constructor(globalId : IfcGloballyUniqueId, predefinedType : IfcDiscreteAccessoryTypeEnum) {
... | import {IfcDiscreteAccessoryTypeEnum} from "./IfcDiscreteAccessoryTypeEnum.g"
import {IfcElementComponentType} from "./IfcElementComponentType.g"
| random_line_split |
justpremiumBidAdapter.js | import { registerBidder } from '../src/adapters/bidderFactory.js'
import { deepAccess } from '../src/utils.js';
const BIDDER_CODE = 'justpremium'
const ENDPOINT_URL = 'https://pre.ads.justpremium.com/v/2.0/t/xhr'
const JP_ADAPTER_VERSION = '1.7'
const pixels = []
export const spec = {
code: BIDDER_CODE,
time: 600... |
function getWebsiteDim () {
let top
try {
top = window.top
} catch (e) {
top = window
}
return {
screenWidth: top.screen.width,
screenHeight: top.screen.height,
innerWidth: top.innerWidth,
innerHeight: top.innerHeight
}
}
registerBidder(spec)
| {
const a = array.concat()
for (let i = 0; i < a.length; ++i) {
for (let j = i + 1; j < a.length; ++j) {
if (a[i] === a[j]) {
a.splice(j--, 1)
}
}
}
return a
} | identifier_body |
justpremiumBidAdapter.js | import { registerBidder } from '../src/adapters/bidderFactory.js'
import { deepAccess } from '../src/utils.js';
const BIDDER_CODE = 'justpremium'
const ENDPOINT_URL = 'https://pre.ads.justpremium.com/v/2.0/t/xhr'
const JP_ADAPTER_VERSION = '1.7'
const pixels = []
export const spec = {
code: BIDDER_CODE,
time: 600... | sizes[zone] = sizes[zone] || []
sizes[zone].push.apply(sizes[zone], b.mediaTypes && b.mediaTypes.banner && b.mediaTypes.banner.sizes)
})
if (deepAccess(validBidRequests[0], 'userId.pubcid')) {
payload.pubcid = deepAccess(validBidRequests[0], 'userId.pubcid')
} else if (deepAccess(validBid... | validBidRequests.forEach(b => {
const zone = b.params.zone
const sizes = payload.sizes | random_line_split |
justpremiumBidAdapter.js | import { registerBidder } from '../src/adapters/bidderFactory.js'
import { deepAccess } from '../src/utils.js';
const BIDDER_CODE = 'justpremium'
const ENDPOINT_URL = 'https://pre.ads.justpremium.com/v/2.0/t/xhr'
const JP_ADAPTER_VERSION = '1.7'
const pixels = []
export const spec = {
code: BIDDER_CODE,
time: 600... |
if (syncOptions.iframeEnabled) {
pixels.push({
type: 'iframe',
url: url
})
}
return pixels
},
}
function findBid (params, bids) {
const tagId = params.zone
if (bids[tagId]) {
let len = bids[tagId].length
while (len--) {
if (passCond(params, bids[tagId][len])... | {
url = url + '&usPrivacy=' + encodeURIComponent(uspConsent)
} | conditional_block |
justpremiumBidAdapter.js | import { registerBidder } from '../src/adapters/bidderFactory.js'
import { deepAccess } from '../src/utils.js';
const BIDDER_CODE = 'justpremium'
const ENDPOINT_URL = 'https://pre.ads.justpremium.com/v/2.0/t/xhr'
const JP_ADAPTER_VERSION = '1.7'
const pixels = []
export const spec = {
code: BIDDER_CODE,
time: 600... | () {
let top
try {
top = window.top
} catch (e) {
top = window
}
return {
screenWidth: top.screen.width,
screenHeight: top.screen.height,
innerWidth: top.innerWidth,
innerHeight: top.innerHeight
}
}
registerBidder(spec)
| getWebsiteDim | identifier_name |
congruences.py | import primes as py
def lcm(a, b):
return a * b / gcd(a, b)
def gcd(a, b):
while b != 0:
(a, b) = (b, a % b)
return a
# Returns two integers x, y such that gcd(a, b) = ax + by
def egcd(a, b):
if a == 0:
return (0, 1)
else:
y, x = egcd(b % a, a)
return (x - (b ... | return solutions | if value % m == 0:
solutions.append(i)
| random_line_split |
congruences.py | import primes as py
def lcm(a, b):
return a * b / gcd(a, b)
def gcd(a, b):
while b != 0:
(a, b) = (b, a % b)
return a
# Returns two integers x, y such that gcd(a, b) = ax + by
def | (a, b):
if a == 0:
return (0, 1)
else:
y, x = egcd(b % a, a)
return (x - (b // a) * y, y)
# Returns an integer x such that ax = 1(mod m)
def modInverse(a, m):
x, y = egcd(a, m)
if gcd(a, m) == 1:
return x % m
# Reduces linear congruence to form x = b(mod m)
def reduceCo... | egcd | identifier_name |
congruences.py | import primes as py
def lcm(a, b):
return a * b / gcd(a, b)
def gcd(a, b):
while b != 0:
(a, b) = (b, a % b)
return a
# Returns two integers x, y such that gcd(a, b) = ax + by
def egcd(a, b):
if a == 0:
return (0, 1)
else:
y, x = egcd(b % a, a)
return (x - (b ... |
# Returns the incongruent solutions to the linear congruence ax = b(mod m)
def linCongr(a, b, m):
solutions = set()
if (b % gcd(a, m) == 0):
numSols = gcd(a, m)
sol = (b * egcd(a, m)[0] / numSols) % m
for i in xrange(0, numSols):
... | gcdAB = gcd(a, b)
a /= gcdAB
b /= gcdAB
m /= gcd(gcdAB, m)
modinv = modInverse(a, m)
b *= modinv
return (1, b, m) | identifier_body |
congruences.py | import primes as py
def lcm(a, b):
return a * b / gcd(a, b)
def gcd(a, b):
while b != 0:
(a, b) = (b, a % b)
return a
# Returns two integers x, y such that gcd(a, b) = ax + by
def egcd(a, b):
if a == 0:
return (0, 1)
else:
y, x = egcd(b % a, a)
return (x - (b ... |
if not isRedundant:
finalCongruences.append(newCongruences[k])
return crt(finalCongruences)
# Returns incongruents solutions to a polynomial congruence
def polyCongr(coefficients, m):
solutions = []
for i in xrange(m):
value = 0
... | if newCongruences[l][2] % newCongruences[k][2] == 0:
isRedundant = True | conditional_block |
loadNotifications.js | (function($) {
// Templates
var notificationTemplate = _.template("\
<% for (var i = 0; i < notifications.length; i++) { %>\
<% var notification = notifications[i]; %>\ | </a>\
</div>\
<div class='notification-meta'>\
<a href='<%= notification.user_url %>'><%= notification.user_name %></a>\
<%= notification.message %>\
<% if (notification.item_name) { %>\
<a href='<%= notification.item_url %>'><%= notifica... | <li class='notification' data-next='<%= notification.next %>'>\
<div class='user-thumbnail pull-left'>\
<a href='<%= notification.user_url %>'>\
<img src='<%= notification.user_avatar %>' />\ | random_line_split |
bootstrap.inject.ts | Factory';
import { Player } from './youtube/Player';
import { PlayerConfig, PlayerData, PlayerType } from './youtube/PlayerConfig';
import { v4 as uuidv4 } from 'uuid';
declare interface YTWindow {
yt: {
player?: {
Application?: {
create?: Function
}
}
config_?: {
TIMING_AFT_KEY... | if (fn.toString().indexOf('video_id') !== -1) {
this[key] = function(...args: any[]) {
if (args.length > 0) {
const config = args[0];
if (config && config.hasOwnProperty("autoplay")) {
autoplay = config["autopl... | {
win._yt_player[key] = function(...args: any[]) {
const constructor = this.constructor.toString();
const match = constructor.match(/this\.([a-zA-Z0-9$_]+)\=[^;]+\.autoplay/);
let autoplay = true;
if (match && match[1]) {
Object.defineProperty(this, match[1]... | conditional_block |
bootstrap.inject.ts | Factory';
import { Player } from './youtube/Player';
import { PlayerConfig, PlayerData, PlayerType } from './youtube/PlayerConfig';
import { v4 as uuidv4 } from 'uuid';
declare interface YTWindow {
yt: {
player?: {
Application?: {
create?: Function
}
}
config_?: {
TIMING_AFT_KEY... | if (servicePort.isDisposed()) {
if (fn) {
return fn(playerConfig);
}
return;
}
let elementId = playerConfig.attrs.id;
let playerId = uuidv4();
// Wait for any blockers e.g. loading of settings.
await servicePort.call("settings#ensureLoaded");
// Send a beforecreate event to the co... | random_line_split | |
errors.py | from __future__ import unicode_literals
import six
from rbtools.utils.encoding import force_unicode
class APIError(Exception):
def __init__(self, http_status, error_code, rsp=None, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.http_status = http_status
self.error_code ... | (Exception):
"""An exception for caching errors."""
class ServerInterfaceError(Exception):
def __init__(self, msg, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.msg = msg
def __str__(self):
"""Return the error message as a unicode string.
Returns:
... | CacheError | identifier_name |
errors.py | from __future__ import unicode_literals
import six
from rbtools.utils.encoding import force_unicode
class APIError(Exception):
def __init__(self, http_status, error_code, rsp=None, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.http_status = http_status
self.error_code ... |
class AuthorizationError(APIError):
pass
class BadRequestError(APIError):
def __str__(self):
lines = [super(BadRequestError, self).__str__()]
if self.rsp and 'fields' in self.rsp:
lines.append('')
for field, error in six.iteritems(self.rsp['fields']):
... | return code_str
| random_line_split |
errors.py | from __future__ import unicode_literals
import six
from rbtools.utils.encoding import force_unicode
class APIError(Exception):
def __init__(self, http_status, error_code, rsp=None, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.http_status = http_status
self.error_code ... |
if self.rsp and 'err' in self.rsp:
return '%s (%s)' % (self.rsp['err']['msg'], code_str)
else:
return code_str
class AuthorizationError(APIError):
pass
class BadRequestError(APIError):
def __str__(self):
lines = [super(BadRequestError, self).__str__()]
... | code_str += ', API Error %d' % self.error_code | conditional_block |
errors.py | from __future__ import unicode_literals
import six
from rbtools.utils.encoding import force_unicode
class APIError(Exception):
def __init__(self, http_status, error_code, rsp=None, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.http_status = http_status
self.error_code ... |
class CacheError(Exception):
"""An exception for caching errors."""
class ServerInterfaceError(Exception):
def __init__(self, msg, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.msg = msg
def __str__(self):
"""Return the error message as a unicode string.
... | lines = [super(BadRequestError, self).__str__()]
if self.rsp and 'fields' in self.rsp:
lines.append('')
for field, error in six.iteritems(self.rsp['fields']):
lines.append(' %s: %s' % (field, '; '.join(error)))
return '\n'.join(lines) | identifier_body |
default.js | export default {
customColors:{
charBackground:"#FFFFFF",
char: "#000000",
charReverse: "#FFFFFF",
primaryComplementary: "#00CCFF",
primaryBackground: "#FFFFFF",
item: {
boost: "#2b90d9", | tootButton: "#FF5500",
link: "#1b95e0",
},
colors: {
primary: "#FF3300",
//secondary;
grey0: "#657786",
grey1: "#2b90d9",
grey2: "#8899a6",
//grey3;
//grey4;
//grey5;
//greyOutline;
//searchBg;
//success;
... | favourite: "#ffd27d",
bookmark: "#4c6ef5",
none: "#8899a6"
}, | random_line_split |
test_operator.py | from __future__ import print_function, absolute_import, division
import numpy as np
from numba.cuda.testing import unittest
from numba import cuda
import operator
class TestOperatorModule(unittest.TestCase):
""" | def foo(a, b):
i = 0
a[i] = op(a[i], b[i])
a = np.ones(1)
b = np.ones(1)
res = a.copy()
foo[1, 1](res, b)
np.testing.assert_equal(res, op(a, b))
def test_add(self):
self.operator_template(operator.add)
def test_sub(self):
... | Test if operator module is supported by the CUDA target.
"""
def operator_template(self, op):
@cuda.jit | random_line_split |
test_operator.py | from __future__ import print_function, absolute_import, division
import numpy as np
from numba.cuda.testing import unittest
from numba import cuda
import operator
class TestOperatorModule(unittest.TestCase):
"""
Test if operator module is supported by the CUDA target.
"""
def operator_template(self, ... |
def test_sub(self):
self.operator_template(operator.sub)
def test_mul(self):
self.operator_template(operator.mul)
def test_truediv(self):
self.operator_template(operator.truediv)
if __name__ == '__main__':
unittest.main()
| self.operator_template(operator.add) | identifier_body |
test_operator.py | from __future__ import print_function, absolute_import, division
import numpy as np
from numba.cuda.testing import unittest
from numba import cuda
import operator
class TestOperatorModule(unittest.TestCase):
"""
Test if operator module is supported by the CUDA target.
"""
def operator_template(self, ... | unittest.main() | conditional_block | |
test_operator.py | from __future__ import print_function, absolute_import, division
import numpy as np
from numba.cuda.testing import unittest
from numba import cuda
import operator
class TestOperatorModule(unittest.TestCase):
"""
Test if operator module is supported by the CUDA target.
"""
def operator_template(self, ... | (a, b):
i = 0
a[i] = op(a[i], b[i])
a = np.ones(1)
b = np.ones(1)
res = a.copy()
foo[1, 1](res, b)
np.testing.assert_equal(res, op(a, b))
def test_add(self):
self.operator_template(operator.add)
def test_sub(self):
self.operator... | foo | identifier_name |
index.ts | // RenderAction -> render -> render to DOM
import { A, O, Handler } from 'boa-core';
import { _do } from 'rxjs/operator/do';
import { filter } from 'rxjs/operator/filter';
import { share } from 'rxjs/operator/share';
import { DOM } from './dom';
import { create, VDOM } from 'boa-vdom';
type DOMOptions = {
root: str... | ),
() => false // remove all
)
);
};
return { handler };
};
export { init }; | random_line_split | |
invite.js |
'use strict';
var async = require('async');
var nconf = require('nconf');
var validator = require('validator');
var db = require('./../database');
var meta = require('../meta');
var emailer = require('../emailer');
var translator = require('../translator');
var utils = require('../utils');
module.exports = function... | (uid, email, callback) {
async.waterfall([
function (next) {
db.setRemove('invitation:uid:' + uid, email, next);
},
function (next) {
db.setCount('invitation:uid:' + uid, next);
},
function (count, next) {
if (count === 0) {
return db.setRemove('invitation:uids', uid, next);
}
... | deleteFromReferenceList | identifier_name |
invite.js |
'use strict';
var async = require('async');
var nconf = require('nconf');
var validator = require('validator');
var db = require('./../database');
var meta = require('../meta');
var emailer = require('../emailer');
var translator = require('../translator');
var utils = require('../utils');
module.exports = function... |
};
| {
async.waterfall([
function (next) {
db.setRemove('invitation:uid:' + uid, email, next);
},
function (next) {
db.setCount('invitation:uid:' + uid, next);
},
function (count, next) {
if (count === 0) {
return db.setRemove('invitation:uids', uid, next);
}
setImmediate(next);
... | identifier_body |
invite.js |
'use strict';
var async = require('async');
var nconf = require('nconf');
var validator = require('validator');
var db = require('./../database');
var meta = require('../meta');
var emailer = require('../emailer');
var translator = require('../translator');
var utils = require('../utils');
module.exports = function... |
setImmediate(next);
},
], callback);
}
};
| {
return db.setRemove('invitation:uids', uid, next);
} | conditional_block |
invite.js | 'use strict';
var async = require('async');
var nconf = require('nconf');
var validator = require('validator');
var db = require('./../database');
var meta = require('../meta');
var emailer = require('../emailer');
var translator = require('../translator');
var utils = require('../utils');
module.exports = function ... | };
User.getInvitingUsers = function (callback) {
db.getSetMembers('invitation:uids', callback);
};
User.getAllInvites = function (callback) {
var uids;
async.waterfall([
User.getInvitingUsers,
function (_uids, next) {
uids = _uids;
async.map(uids, User.getInvites, next);
},
function (inv... | random_line_split | |
sched.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | /// Lock the calling thread to CPU `cpu_index`
pub fn set_cpu_affinity(cpu_index: usize) -> Result<(), nix::Error> {
let pid = nix::unistd::Pid::from_raw(0);
let mut cpuset = nix::sched::CpuSet::new();
cpuset.set(cpu_index)?;
nix::sched::sched_setaffinity(pid, &cpuset)?;
Ok(())
} | random_line_split | |
sched.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | {
let pid = nix::unistd::Pid::from_raw(0);
let mut cpuset = nix::sched::CpuSet::new();
cpuset.set(cpu_index)?;
nix::sched::sched_setaffinity(pid, &cpuset)?;
Ok(())
} | identifier_body | |
sched.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | (cpu_index: usize) -> Result<(), nix::Error> {
let pid = nix::unistd::Pid::from_raw(0);
let mut cpuset = nix::sched::CpuSet::new();
cpuset.set(cpu_index)?;
nix::sched::sched_setaffinity(pid, &cpuset)?;
Ok(())
}
| set_cpu_affinity | identifier_name |
a23e88f06478_add_commentset_fields.py | """Add commentset fields.
Revision ID: a23e88f06478
Revises: 284c10efdbce
Create Date: 2021-03-22 02:54:30.416806
"""
from alembic import op
from sqlalchemy.sql import column, table
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a23e88f06478'
down_revision = '284c10efdbce'
branch_labels... | ():
op.drop_column('commentset_membership', 'is_muted')
op.drop_column('commentset', 'last_comment_at')
| downgrade | identifier_name |
a23e88f06478_add_commentset_fields.py | """Add commentset fields.
Revision ID: a23e88f06478
Revises: 284c10efdbce
Create Date: 2021-03-22 02:54:30.416806
"""
from alembic import op
from sqlalchemy.sql import column, table
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a23e88f06478'
down_revision = '284c10efdbce'
branch_labels... | op.drop_column('commentset', 'last_comment_at') |
def downgrade():
op.drop_column('commentset_membership', 'is_muted') | random_line_split |
a23e88f06478_add_commentset_fields.py | """Add commentset fields.
Revision ID: a23e88f06478
Revises: 284c10efdbce
Create Date: 2021-03-22 02:54:30.416806
"""
from alembic import op
from sqlalchemy.sql import column, table
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a23e88f06478'
down_revision = '284c10efdbce'
branch_labels... | )
)
def downgrade():
op.drop_column('commentset_membership', 'is_muted')
op.drop_column('commentset', 'last_comment_at')
| op.add_column(
'commentset',
sa.Column('last_comment_at', sa.TIMESTAMP(timezone=True), nullable=True),
)
op.add_column(
'commentset_membership',
sa.Column(
'is_muted',
sa.Boolean(),
nullable=False,
server_default=sa.sql.expression.f... | identifier_body |
app.py | adpilot.nl/static/graph/farm-month.png'>Projected profits: (min)"+str(0)+"mil - (max)"+str(0)+"mil </a>"
def isk(extractors):
extractorID = "40519"
injectorID = "40520"
plexID = "44992"
priceList = []
url = "http://api.eve-central.com/api/marketstat/json?regionlimit=10000002&typeid="
try:
prices = requests.get... | random_line_split | ||
app.py | _app.op['get_characters_character_id_skillqueue'](character_id=row[0])
result = client.request(charTrain)
training = json.loads(result.raw)
cur = db.query("INSERT INTO cache_table (character_id,char_queue) VALUES (%s,%s) ON DUPLICATE KEY UPDATE char_queue=%s",[row[0],result.raw,result.raw])
else:
training... | return "User! :-)" | identifier_body | |
app.py | '](character_ids=[row[0]])
result = client.request(charName)
charName = json.loads(result.raw)[0].get('character_name')
print "Character "+charName
#Get character location
if ready:
charLocation = esi_app.op['get_characters_character_id_location'](character_id=row[0])
result = client.request(charLocati... | register | identifier_name | |
app.py | ['sell']['fivePercent']
injectorsMonth = 3.888
profit = round(((injectorsMonth * (injectorPrice - extractorPrice)) - (plexPrice * 500))/1000000,2)
nonoptimal = round(((injectorsMonth * (injectorPricen - extractorPricen)) - (plexPricen * 500))/1000000,2)
return "<a href='https://market.madpilot.nl/static/graph... |
else:
location = json.loads(cache[3])
sol = esi_app.op['get_universe_systems_system_id'](system_id=location.get('solar_system_id'))
sol = json.loads(client.request(sol).raw).get('name')
#Get current training skill + queue
if ready:
charTrain = esi_app.op['get_characters_character_id_skillqueue'](cha... | charLocation = esi_app.op['get_characters_character_id_location'](character_id=row[0])
result = client.request(charLocation)
location = json.loads(result.raw)
sol = esi_app.op['get_universe_systems_system_id'](system_id=location.get('solar_system_id'))
sol = json.loads(client.request(sol).raw).get('name')
... | conditional_block |
multiwindow.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::thread::Thread;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cf... | context.draw_frame(color);
window.swap_buffers();
window.wait_events().next();
}
} | unsafe { window.make_current() };
let context = support::load(&window);
while !window.is_closed() { | random_line_split |
multiwindow.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::thread::Thread;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cf... | }
#[cfg(feature = "window")]
fn run(window: glutin::Window, color: (f32, f32, f32, f32)) {
unsafe { window.make_current() };
let context = support::load(&window);
while !window.is_closed() {
context.draw_frame(color);
window.swap_buffers();
window.wait_events().next();
}
}
| {
let window1 = glutin::Window::new().unwrap();
let window2 = glutin::Window::new().unwrap();
let window3 = glutin::Window::new().unwrap();
let t1 = Thread::scoped(move || {
run(window1, (0.0, 1.0, 0.0, 1.0));
});
let t2 = Thread::scoped(move || {
run(window2, (0.0, 0.0, 1.0, 1... | identifier_body |
multiwindow.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::thread::Thread;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cf... | (window: glutin::Window, color: (f32, f32, f32, f32)) {
unsafe { window.make_current() };
let context = support::load(&window);
while !window.is_closed() {
context.draw_frame(color);
window.swap_buffers();
window.wait_events().next();
}
}
| run | identifier_name |
entity.ts | import {
ENTITY_ADD,
ENTITIES_FETCH,
ENTITIES_FETCH_FAILED,
ENTITIES_FETCH_DONE,
ENTITY_IMPORT_TO_SPACE_FETCH,
ENTITY_IMPORT_TO_SPACE_DONE,
ENTITY_IMPORT_TO_SPACE_FAIL
} from '../constants/action-types';
export default function | (state: any = {
all: [],
userEntities: [],
current: null,
fetching: false,
error: false,
addedToSpace: false
}, action: any) {
switch (action.type) {
case ENTITY_ADD:
return Object.assign({}, state, {
instances: [
...state.instances,
act... | entities | identifier_name |
entity.ts | import {
ENTITY_ADD,
ENTITIES_FETCH,
ENTITIES_FETCH_FAILED,
ENTITIES_FETCH_DONE,
ENTITY_IMPORT_TO_SPACE_FETCH,
ENTITY_IMPORT_TO_SPACE_DONE,
ENTITY_IMPORT_TO_SPACE_FAIL
} from '../constants/action-types';
export default function entities (state: any = {
all: [],
userEntities: [],
... | }; | random_line_split | |
entity.ts | import {
ENTITY_ADD,
ENTITIES_FETCH,
ENTITIES_FETCH_FAILED,
ENTITIES_FETCH_DONE,
ENTITY_IMPORT_TO_SPACE_FETCH,
ENTITY_IMPORT_TO_SPACE_DONE,
ENTITY_IMPORT_TO_SPACE_FAIL
} from '../constants/action-types';
export default function entities (state: any = {
all: [],
userEntities: [],
... | return Object.assign({}, state, {
error: action.err
})
case ENTITY_IMPORT_TO_SPACE_FETCH:
return Object.assign({}, state, {
addedToSpace: false,
fetching: true
})
case ENTITY_IMPORT_TO_SPACE_DONE:
return Object.assign({}, state, {
... | {
switch (action.type) {
case ENTITY_ADD:
return Object.assign({}, state, {
instances: [
...state.instances,
action.data
]
})
case ENTITIES_FETCH:
return Object.assign({}, state, {
all: [],
fetching: true
... | identifier_body |
urls.py | """cmput404project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... | url(r'^admin/', admin.site.urls),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
] | url(r'^', include('service.urls')),
url(r'^docs/', include('rest_framework_docs.urls')), | random_line_split |
field.js | var cx = require('classnames');
var blacklist = require('blacklist');
var React = require('react');
module.exports = React.createClass({
displayName: 'Field',
getDefaultProps() {
return {
d: null,
t: null,
m: null,
label: ''
}
},
renderError() {
if(!this.props.error) retur... |
return (
<label className={cn}>
{this.props.label}
</label>
);
},
render() {
var props = blacklist(this.props, 'label', 'error', 'children', 'd', 't', 'm');
props.className = cx('u-field', {
'g-row': this.props.d,
'u-field-row': this.props.d,
'u-field-err': t... | {
return (
<label className={cn}> </label>
);
} | conditional_block |
field.js | var cx = require('classnames');
var blacklist = require('blacklist');
var React = require('react');
module.exports = React.createClass({
displayName: 'Field',
getDefaultProps() {
return {
d: null,
t: null,
m: null,
label: ''
}
},
| () {
if(!this.props.error) return null;
return <span className="error">{this.props.error}</span>;
},
renderLabel() {
var cn = cx('label', this.props.d ? `g-${this.props.d}` : null);
if(!this.props.label) {
return (
<label className={cn}> </label>
);
}
return (
... | renderError | identifier_name |
field.js | var cx = require('classnames');
var blacklist = require('blacklist');
var React = require('react');
module.exports = React.createClass({
displayName: 'Field',
getDefaultProps() {
return {
d: null,
t: null,
m: null,
label: ''
}
},
renderError() {
if(!this.props.error) retur... | },
renderLabel() {
var cn = cx('label', this.props.d ? `g-${this.props.d}` : null);
if(!this.props.label) {
return (
<label className={cn}> </label>
);
}
return (
<label className={cn}>
{this.props.label}
</label>
);
},
render() {
var prop... | return <span className="error">{this.props.error}</span>; | random_line_split |
field.js | var cx = require('classnames');
var blacklist = require('blacklist');
var React = require('react');
module.exports = React.createClass({
displayName: 'Field',
getDefaultProps() {
return {
d: null,
t: null,
m: null,
label: ''
}
},
renderError() | ,
renderLabel() {
var cn = cx('label', this.props.d ? `g-${this.props.d}` : null);
if(!this.props.label) {
return (
<label className={cn}> </label>
);
}
return (
<label className={cn}>
{this.props.label}
</label>
);
},
render() {
var props =... | {
if(!this.props.error) return null;
return <span className="error">{this.props.error}</span>;
} | identifier_body |
test_mirna.py | from resolwe.flow.models import Data
from resolwe.test import tag_process, with_resolwe_host
from resolwe_bio.utils.test import KBBioProcessTestCase
class MicroRNATestCase(KBBioProcessTestCase):
@with_resolwe_host
@tag_process("workflow-mirna")
def test_mirna_workflow(self):
# Prepare data for al... | },
"alignment": {
"genome": bowtie2_index.pk,
"alignment_options": {
"mode": "--local",
"speed": "--very-sensitive",
"L": 8,
"rep_mode": "k",
"k_reports": 5,
... | with self.preparation_stage():
inputs = {
"src": "genome_rsem.fa.gz",
"species": "Homo sapiens",
"build": "fake_genome_RSEM",
}
ref_seq = self.run_process("upload-fasta-nucl", inputs)
bowtie2_index = self.run_process("bowtie... | identifier_body |
test_mirna.py | from resolwe.flow.models import Data
from resolwe.test import tag_process, with_resolwe_host
from resolwe_bio.utils.test import KBBioProcessTestCase
class MicroRNATestCase(KBBioProcessTestCase):
@with_resolwe_host
@tag_process("workflow-mirna")
def test_mirna_workflow(self):
# Prepare data for al... | "allow_multi_overlap": True,
},
"assay_type": "non_specific",
}
# Run process and assert.
self.run_process("workflow-mirna", inputs)
workflow = Data.objects.filter(process__slug="feature_counts").last()
# check featureCount summary
... | random_line_split | |
test_mirna.py | from resolwe.flow.models import Data
from resolwe.test import tag_process, with_resolwe_host
from resolwe_bio.utils.test import KBBioProcessTestCase
class | (KBBioProcessTestCase):
@with_resolwe_host
@tag_process("workflow-mirna")
def test_mirna_workflow(self):
# Prepare data for aligning the reads with bowtie2 and annotation file for featureCounts.
with self.preparation_stage():
inputs = {
"src": "genome_rsem.fa.gz",... | MicroRNATestCase | identifier_name |
test.js | 'use strict';
const AWS = require('aws-sdk'); | console.log(x.replace('/delegationset/', ''));
return;
const route53 = new AWS.Route53();
route53.listHostedZones({}).promise()
.then(response => {
console.log(response);
return response.HostedZones.find(hostedZone => {
return hostedZone.Name === 'manapaho.com.';
});
})
.catch(err => {
con... |
let x = "/delegationset/NHKXBB6SHGKLN"; | random_line_split |
les_request.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity. | // 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.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTA... |
// Parity is free software: you can redistribute it and/or modify | random_line_split |
les_request.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 la... | {
/// Requesting headers.
Headers,
/// Requesting block bodies.
Bodies,
/// Requesting transaction receipts.
Receipts,
/// Requesting proofs of state trie nodes.
StateProofs,
/// Requesting contract code by hash.
Codes,
/// Requesting header proofs (from the CHT).
HeaderProofs,
}
/// Encompasses all possi... | Kind | identifier_name |
__init__.py | # Backend loading
# Based on the Django cache framework
# https://github.com/django/django/blob/5d263dee304fdaf95e18d2f0619d6925984a7f02/django/core/cache/__init__.py
import sys
from importlib import import_module
import warnings
from django.utils import six
from django.utils.module_loading import import_string
from ... |
def get_search_backends(with_auto_update=False):
# For backwards compatibility
return (backend for _, backend in get_search_backends_with_name(with_auto_update=with_auto_update))
| if with_auto_update and _backend_requires_auto_update(backend, params) is False:
continue
yield backend, get_search_backend(backend) | conditional_block |
__init__.py | # Backend loading
# Based on the Django cache framework
# https://github.com/django/django/blob/5d263dee304fdaf95e18d2f0619d6925984a7f02/django/core/cache/__init__.py
import sys
from importlib import import_module
import warnings
from django.utils import six
from django.utils.module_loading import import_string
from ... |
class InvalidSearchBackendError(ImproperlyConfigured):
pass
def get_search_backend_config():
search_backends = getattr(settings, 'WAGTAILSEARCH_BACKENDS', {})
# Make sure the default backend is always defined
search_backends.setdefault('default', {
'BACKEND': 'wagtail.wagtailsearch.backends... | from django.conf import settings | random_line_split |
__init__.py | # Backend loading
# Based on the Django cache framework
# https://github.com/django/django/blob/5d263dee304fdaf95e18d2f0619d6925984a7f02/django/core/cache/__init__.py
import sys
from importlib import import_module
import warnings
from django.utils import six
from django.utils.module_loading import import_string
from ... | (backend='default', **kwargs):
backend = backend
search_backends = get_search_backend_config()
# Try to find the backend
try:
# Try to get the WAGTAILSEARCH_BACKENDS entry for the given backend name first
conf = search_backends[backend]
except KeyError:
try:
# Tr... | get_search_backend | identifier_name |
__init__.py | # Backend loading
# Based on the Django cache framework
# https://github.com/django/django/blob/5d263dee304fdaf95e18d2f0619d6925984a7f02/django/core/cache/__init__.py
import sys
from importlib import import_module
import warnings
from django.utils import six
from django.utils.module_loading import import_string
from ... |
def import_backend(dotted_path):
"""
Theres two formats for the dotted_path.
One with the backend class (old) and one without (new)
eg:
old: wagtail.wagtailsearch.backends.elasticsearch.ElasticsearchSearchBackend
new: wagtail.wagtailsearch.backends.elasticsearch
If a new style dotted... | search_backends = getattr(settings, 'WAGTAILSEARCH_BACKENDS', {})
# Make sure the default backend is always defined
search_backends.setdefault('default', {
'BACKEND': 'wagtail.wagtailsearch.backends.db',
})
return search_backends | identifier_body |
untrusted_rlp.rs | given bytes RLP. The bytes
pub fn from(header_bytes: &[u8]) -> Result<PayloadInfo, DecoderError> {
match header_bytes.first().cloned() {
None => Err(DecoderError::RlpIsTooShort),
Some(0...0x7f) => Ok(PayloadInfo::new(0, 1)),
Some(l @ 0x80...0xb7) => Ok(PayloadInfo::new(1... | {
pub fn new(bytes: &'a [u8]) -> UntrustedRlp<'a> {
UntrustedRlp {
bytes: bytes,
offset_cache: Cell::new(OffsetCache::new(usize::max_value(), 0)),
count_cache: Cell::new(None),
}
}
pub fn as_raw(&'view self) -> &'a [u8] {
self.bytes
}
pub... | random_line_split | |
untrusted_rlp.rs | ayloadInfo::new(1, l as usize - 0xc0)),
Some(l @ 0xf8...0xff) => {
let len_of_len = l as usize - 0xf7;
calculate_payload_info(header_bytes, len_of_len)
}
// we cant reach this place, but rust requires _ to be implemented
_ => {
... | payload_info | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.