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 |
|---|---|---|---|---|
phenome.py | # Copyright (C) 2016 William Langhoff WildBill567@users.noreply.github.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your optio... | (genome):
"""Constructs the DiGraph"""
graph = nx.DiGraph()
graph.add_node(0, {'node_type': 'BIAS', 'val': 1})
input_list = []
output_list = []
hidden_list = []
for gene in genome.input_genes:
graph.add_node(gene.idx)
input_list.append(gen... | _construct_graph | identifier_name |
phenome.py | # Copyright (C) 2016 William Langhoff WildBill567@users.noreply.github.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your optio... | if cg.sink == node and cg.enabled:
inputs.append((cg.src, cg.weight))
used_nodes.add(cg.src)
used_nodes.add(node)
ng = genome.get_node_by_index(node)
activation_function = activation_functions.get(ng.act... | def __init__(self, genome, config):
"""
FeedForwardPhenome - A feedforward network
Adapted from: https://github.com/CodeReclaimers/neat-python, accessed May 2016
:param genome: the genome to create the phenome
"""
self.graph, node_lists = self._construct_graph(genome)
... | identifier_body |
phenome.py | # Copyright (C) 2016 William Langhoff WildBill567@users.noreply.github.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your optio... | graph = nx.DiGraph()
graph.add_node(0, {'node_type': 'BIAS', 'val': 1})
input_list = []
output_list = []
hidden_list = []
for gene in genome.input_genes:
graph.add_node(gene.idx)
input_list.append(gene.idx)
for gene in genome.output_genes... | def _construct_graph(genome):
"""Constructs the DiGraph""" | random_line_split |
inline-configs.ts | import { InputLengthTestable, InputRegexTestable, InputSelectable } from "./testable-inputs.interface";
import { InputType } from "./input-type.type";
import { InputBaseConfig, TextareaConfig, CheckboxConfig } from "./input-configs";
export interface InlineBaseConfig extends InputBaseConfig {
type: InputType;
... | hideButtons?: boolean;
required?: boolean;
disabled?: boolean;
onlyValue?: boolean;
}
export interface InlineTextConfig extends InlineBaseConfig, InputRegexTestable { }
export interface InlineSelectConfig extends InlineBaseConfig, InputSelectable { }
export interface InlineNumberConfig extends Inline... | random_line_split | |
datepicker-demo-module.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {FormsModule, ReactiveFo... | {
}
| DatepickerDemoModule | identifier_name |
datepicker-demo-module.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {FormsModule, ReactiveFo... | import {MatFormFieldModule} from '@angular/material/form-field';
import {MatIconModule} from '@angular/material/icon';
import {MatInputModule} from '@angular/material/input';
import {MatSelectModule} from '@angular/material/select';
import {RouterModule} from '@angular/router';
import {CustomHeader, CustomHeaderNgConte... | import {MatNativeDateModule} from '@angular/material/core';
import {MatDatepickerModule} from '@angular/material/datepicker'; | random_line_split |
AdvTab.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import { ImageDialogInfo } from './DialogTypes';
const makeTab = (_i... | inputMode: 'numeric'
},
{
type: 'input',
label: 'Horizontal space',
name: 'hspace',
inputMode: 'numeric'
},
{
type: 'input',
label: 'Border width',
name: 'border',
inputMode: 'numeric'
},
... | items: [
{
type: 'input',
label: 'Vertical space',
name: 'vspace', | random_line_split |
buid-info.ts | import BpConf from "./bp-conf";
/**
* 构建对象
*/
class BuildInfo {
name: string //项目名称
git: string | null | undefined //git地址。 ssh的
isCompanyProject: boolean // 是否是公司项目
isActivity: boolean // 是否是公司的活动项目
bpConf: BpConf // 配置文件 实例对象
/**
*
* @param name 项目名字
* @param git git项目地址 可以为空... | export default BuildInfo; | setIsCompanyProject(isCompanyProject: boolean): void {
this.isCompanyProject = isCompanyProject;
}
}
| random_line_split |
buid-info.ts | import BpConf from "./bp-conf";
/**
* 构建对象
*/
class BuildInfo {
name: string //项目名称
git: string | null | undefined //git地址。 ssh的
isCompanyProject: boolean // 是否是公司项目
isActivity: boolean // 是否是公司的活动项目
bpConf: BpConf // 配置文件 实例对象
/**
*
* @param name 项目名字
* @param git git项目地址 可以为空... | ct;
}
}
export default BuildInfo; | onf = bpConf;
this.isCompanyProject = isCompanyProject;
}
setIsCompanyProject(isCompanyProject: boolean): void {
this.isCompanyProject = isCompanyProje | identifier_body |
buid-info.ts | import BpConf from "./bp-conf";
/**
* 构建对象
*/
class BuildInfo {
name: string //项目名称
git: string | null | undefined //git地址。 ssh的
isCompanyProject: boolean // 是否是公司项目
isActivity: boolean // 是否是公司的活动项目
bpConf: BpConf // 配置文件 实例对象
/**
*
* @param name 项目名字
* @param git git项目地址 可以为空... | onf) {
this.name = name;
this.git = git;
this.isActivity = isActivity;
this.bpConf = bpConf;
this.isCompanyProject = isCompanyProject;
}
setIsCompanyProject(isCompanyProject: boolean): void {
this.isCompanyProject = isCompanyProject;
}
}
export default BuildI... | bpConf: BpC | identifier_name |
match_hospitals.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
from pprint import pprint
import re
from fileinput import input
import csv
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
articles = ['the', 'a']
prepositions = ['at', 'of']
hospital_words = ['hospital', 'medical', 'center']
word_exclusions = articles + pr... | (self, hospital, score):
self.hospital = hospital
self.score = score
def __init__(self, hospitals):
self._hospitals = list(filter(lambda x: x.name, hospitals))
self._name_cache = list(map(lambda x: x.name, self._hospitals))
self._name_dict = {hospital.name: hospital for hospital in self._hosp... | __init__ | identifier_name |
match_hospitals.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
from pprint import pprint
import re
from fileinput import input
import csv
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
articles = ['the', 'a']
prepositions = ['at', 'of']
hospital_words = ['hospital', 'medical', 'center']
word_exclusions = articles + pr... | match = hospital_data.match(hospital)
output_table.append((hospital, match.hospital.original_name, match.hospital.data))
pprint(output_table[-1])
write_table_to_file(outfile, output_table)
######## Main ########
if __name__ == '__main__':
from sys import argv
if len(argv) >= 4:
match_files(argv[... |
output_table = []
for hospital in hospitals: | random_line_split |
match_hospitals.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
from pprint import pprint
import re
from fileinput import input
import csv
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
articles = ['the', 'a']
prepositions = ['at', 'of']
hospital_words = ['hospital', 'medical', 'center']
word_exclusions = articles + pr... |
write_table_to_file(outfile, output_table)
######## Main ########
if __name__ == '__main__':
from sys import argv
if len(argv) >= 4:
match_files(argv[1], argv[2], argv[3])
else
print("Invalid number of arguments. Please pass FileA, FileB, and the name of the output file respectively.")
| match = hospital_data.match(hospital)
output_table.append((hospital, match.hospital.original_name, match.hospital.data))
pprint(output_table[-1]) | conditional_block |
match_hospitals.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
from pprint import pprint
import re
from fileinput import input
import csv
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
articles = ['the', 'a']
prepositions = ['at', 'of']
hospital_words = ['hospital', 'medical', 'center']
word_exclusions = articles + pr... |
def normalize_hospital_name(name):
return " ".join(filter(
lambda x: x not in word_exclusions,
re.sub(
"[^abcdefghijklmnopqrstuvwxyz ]",
"",
name.casefold().replace("-", " ")).split()))
def fetch_hospitals(lines):
return list(filter(None, [re.findall(r"\".*?\"", line)[-1].strip('"') for... | self.original_name = name
self.name = normalize_hospital_name(name)
self.data = data | identifier_body |
fig6.py | = np.genfromtxt(data_path, delimiter=',', names=True)
# Model observable corresponding to the IMS-RP reporter (MOMP timing)
momp_obs = 'aSmac'
# Mean and variance of Td (delay time) and Ts (switching time) of MOMP, and
# yfinal (the last value of the IMS-RP trajectory)
momp_data = np.array([9810.0, 180.0, 1.0])
momp_... | (x, rate_mask, lb, ub):
caller_frame, _, _, caller_func, _, _ = inspect.stack()[1]
if caller_func in {'anneal', '_minimize_anneal'}:
caller_locals = caller_frame.f_locals
if caller_locals['n'] == 1:
print(caller_locals['best_state'].cost, caller_locals['current_state'].cost)
... | objective_func | identifier_name |
fig6.py | = np.genfromtxt(data_path, delimiter=',', names=True)
# Model observable corresponding to the IMS-RP reporter (MOMP timing)
momp_obs = 'aSmac'
# Mean and variance of Td (delay time) and Ts (switching time) of MOMP, and
# yfinal (the last value of the IMS-RP trajectory)
momp_data = np.array([9810.0, 180.0, 1.0])
momp_... |
# Calculate error for Td, Ts, and final value for IMS-RP reporter
# =====
# Normalize trajectory
ysim_momp = solver.yobs[momp_obs]
ysim_momp_norm = ysim_momp / np.nanmax(ysim_momp)
# Build a spline to interpolate it
st, sc, sk = scipy.interpolate.splrep(solver.tspan, ysim_momp_norm)
# ... | ysim = solver.yobs[obs_name][::tmul]
# Normalize it to 0-1
ysim_norm = ysim / np.nanmax(ysim)
# Get experimental measurement and variance
ydata = exp_data[data_name]
yvar = exp_data[var_name]
# Compute error between simulation and experiment (chi-squared)
e1 += np... | conditional_block |
fig6.py | _data = np.genfromtxt(data_path, delimiter=',', names=True)
# Model observable corresponding to the IMS-RP reporter (MOMP timing)
momp_obs = 'aSmac'
# Mean and variance of Td (delay time) and Ts (switching time) of MOMP, and
# yfinal (the last value of the IMS-RP trajectory)
momp_data = np.array([9810.0, 180.0, 1.0])
... | solver.run(param_values)
# Calculate error for point-by-point trajectory comparisons
e1 = 0
for obs_name, data_name, var_name in zip(obs_names, data_names, var_names):
# Get model observable trajectory (this is the slice expression
# mentioned above in the comment for tspan)
ysi... | # Simulate model with rates taken from x (which is log transformed)
param_values = np.array([p.value for p in model.parameters])
param_values[rate_mask] = 10 ** x | random_line_split |
fig6.py | _data = np.genfromtxt(data_path, delimiter=',', names=True)
# Model observable corresponding to the IMS-RP reporter (MOMP timing)
momp_obs = 'aSmac'
# Mean and variance of Td (delay time) and Ts (switching time) of MOMP, and
# yfinal (the last value of the IMS-RP trajectory)
momp_data = np.array([9810.0, 180.0, 1.0])
... | # mentioned above in the comment for tspan)
ysim = solver.yobs[obs_name][::tmul]
# Normalize it to 0-1
ysim_norm = ysim / np.nanmax(ysim)
# Get experimental measurement and variance
ydata = exp_data[data_name]
yvar = exp_data[var_name]
# Compute error betw... | caller_frame, _, _, caller_func, _, _ = inspect.stack()[1]
if caller_func in {'anneal', '_minimize_anneal'}:
caller_locals = caller_frame.f_locals
if caller_locals['n'] == 1:
print(caller_locals['best_state'].cost, caller_locals['current_state'].cost)
# Apply hard bounds
... | identifier_body |
typing.rs | use std::sync::Arc;
#[cfg(all(feature = "tokio_compat", not(feature = "tokio")))]
use tokio::time::delay_for as sleep;
#[cfg(feature = "tokio")]
use tokio::time::sleep;
use tokio::{
sync::oneshot::{self, error::TryRecvError, Sender},
time::Duration,
};
use crate::{error::Result, http::Http};
/// A struct to ... | (Sender<()>);
impl Typing {
/// Starts typing in the specified [`Channel`] for an indefinite period of time.
///
/// Returns [`Typing`]. To stop typing, you must call the [`Typing::stop`] method on
/// the returned [`Typing`] object or wait for it to be dropped. Note that on some
/// clients, typin... | Typing | identifier_name |
typing.rs | use std::sync::Arc;
#[cfg(all(feature = "tokio_compat", not(feature = "tokio")))]
use tokio::time::delay_for as sleep;
#[cfg(feature = "tokio")]
use tokio::time::sleep;
use tokio::{
sync::oneshot::{self, error::TryRecvError, Sender},
time::Duration,
};
| /// It indicates that the current user is currently typing in the channel.
///
/// Typing is started by using the [`Typing::start`] method
/// and stopped by using the [`Typing::stop`] method.
/// Note that on some clients, typing may persist for a few seconds after [`Typing::stop`] is called.
/// Typing is also stoppe... | use crate::{error::Result, http::Http};
/// A struct to start typing in a [`Channel`] for an indefinite period of time.
/// | random_line_split |
typing.rs | use std::sync::Arc;
#[cfg(all(feature = "tokio_compat", not(feature = "tokio")))]
use tokio::time::delay_for as sleep;
#[cfg(feature = "tokio")]
use tokio::time::sleep;
use tokio::{
sync::oneshot::{self, error::TryRecvError, Sender},
time::Duration,
};
use crate::{error::Result, http::Http};
/// A struct to ... | Ok(Self(sx))
}
/// Stops typing in [`Channel`].
///
/// This should be used to stop typing after it is started using [`Typing::start`].
/// Typing may persist for a few seconds on some clients after this is called.
///
/// [`Channel`]: crate::model::channel::Channel
pub fn stop... | {
let (sx, mut rx) = oneshot::channel();
tokio::spawn(async move {
loop {
match rx.try_recv() {
Ok(_) | Err(TryRecvError::Closed) => break,
_ => (),
}
http.broadcast_typing(channel_id).await?;
... | identifier_body |
request.js | "use strict";
var Q = require('q');
var HTTPError = require('nor-errors').HTTPError;
var debug = require('nor-debug');
var is = require('nor-is');
var _cookies = require('./cookies.js');
var FUNCTION = require('nor-function');
/** Parse arguments */
function do_args(url, opts) {
// url
if(is.string(url)) {
url =... | opts.headers['Content-Type'] = 'application/json;charset=utf8';
}
opts.headers.Accept = 'application/json';
return do_plain(url, opts).then(function(buffer) {
return JSON.parse(buffer);
});
}
/** JavaScript function request */
function do_js(url, opts) {
opts = opts || {};
if(is.object(opts) && is['function'... | if(is.object(opts) && is.defined(opts.body)) {
opts.body = JSON.stringify(opts.body);
}
opts.headers = opts.headers || {};
if(opts.body) { | random_line_split |
request.js |
"use strict";
var Q = require('q');
var HTTPError = require('nor-errors').HTTPError;
var debug = require('nor-debug');
var is = require('nor-is');
var _cookies = require('./cookies.js');
var FUNCTION = require('nor-function');
/** Parse arguments */
function do_args(url, opts) {
// url
if(is.string(url)) {
url ... |
opts.headers.Accept = 'application/json';
return do_plain(url, opts).then(function(buffer) {
return JSON.parse(buffer);
});
}
/** Generic HTTP/HTTPS request */
var mod = module.exports = {};
mod.plain = do_plain;
mod.json = do_json;
mod.js = do_js;
/* EOF */
| {
opts.method = 'post';
} | conditional_block |
request.js |
"use strict";
var Q = require('q');
var HTTPError = require('nor-errors').HTTPError;
var debug = require('nor-debug');
var is = require('nor-is');
var _cookies = require('./cookies.js');
var FUNCTION = require('nor-function');
/** Parse arguments */
function do_args(url, opts) {
// url
if(is.string(url)) {
url ... |
res.on('data', collect_chunks);
res.once('end', function() {
res.removeListener('data', collect_chunks);
var content_type = res.headers['content-type'] || undefined;
//debug.log('content_type = ' , content_type);
d.resolve( Q.fcall(function() {
//debug.log('buffer = ', buffer);
//debug.log('... | {
buffer += chunk;
} | identifier_body |
request.js |
"use strict";
var Q = require('q');
var HTTPError = require('nor-errors').HTTPError;
var debug = require('nor-debug');
var is = require('nor-is');
var _cookies = require('./cookies.js');
var FUNCTION = require('nor-function');
/** Parse arguments */
function do_args(url, opts) {
// url
if(is.string(url)) {
url ... | (url, opts) {
opts = do_args(url, opts);
if(opts.redirect_loop_counter === undefined) {
opts.redirect_loop_counter = 10;
}
var buffer;
var d = Q.defer();
var req = require(opts.protocol).request(opts.url, function(res) {
var buffer = "";
res.setEncoding('utf8');
function collect_chunks(chunk) {
buffer ... | do_plain | identifier_name |
view.rs | /*
* Copyright (c) 2015-2021 Mathias Hällman
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
use std::cmp;
use unicode_width::UnicodeWidthChar as CharWidth;... | else {
None
};
// helper to put a character on the screen
let put = |character, cell: screen::Cell, screen: &mut Screen| {
use screen::Color::*;
let highlight = caret_cell.map(|c| c != cell).unwrap_or(false);
let (fg, bg) = if highlight {
... |
Some(position + self.caret_position(caret, buffer))
} | conditional_block |
view.rs | /*
* Copyright (c) 2015-2021 Mathias Hällman
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
use std::cmp;
use unicode_width::UnicodeWidthChar as CharWidth;... | let (line, column) = (caret.line(), caret.column());
let screen::Size(rows, cols) = self.size;
let rows = rows as usize;
let cols = cols as usize;
self.scroll_line = if line < self.scroll_line {
line
} else if line >= self.scroll_line + rows {
lin... | self.scroll_column = column;
}
pub fn scroll_into_view(&mut self, caret: Caret, buffer: &Buffer) { | random_line_split |
view.rs | /*
* Copyright (c) 2015-2021 Mathias Hällman
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
use std::cmp;
use unicode_width::UnicodeWidthChar as CharWidth;... | ) -> View {
View {
scroll_line: 0,
scroll_column: 0,
size: screen::Size(MIN_VIEW_SIZE, MIN_VIEW_SIZE),
}
}
pub fn scroll_line(&self) -> usize {
self.scroll_line
}
pub fn scroll_column(&self) -> usize {
self.scroll_column
}
//... | ew( | identifier_name |
view.rs | /*
* Copyright (c) 2015-2021 Mathias Hällman
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
use std::cmp;
use unicode_width::UnicodeWidthChar as CharWidth;... | let screen::Size(rows, cols) = self.size;
// draw line by line
let mut row: u16 = 0;
for chars in buffer
.line_iter()
.from(self.scroll_line)
.take(rows as usize)
{
let line_offset = screen::Cell(row, 0) + position;
// d... |
// calculate caret screen position if focused
let caret_cell = if focused {
Some(position + self.caret_position(caret, buffer))
} else {
None
};
// helper to put a character on the screen
let put = |character, cell: screen::Cell, screen: &mut Scr... | identifier_body |
yelp_w2v.py | """
Compute WordVectors using Yelp Data
"""
from gensim.models.word2vec import Word2Vec
from util.language import detect_language, tokenize_text
from data_handling import get_reviews_data
# Set to true for zero in in English reviews. Makes the process much slower
FILTER_ENGLISH = True
# Name for output w2v model file
... |
# Build a w2v model
w2v = Word2Vec(sentences=sentences, size=100, alpha=0.025, window=4, min_count=2, sample=1e-5, workers=4, negative=10)
w2v.save(OUTPUT_MODEL_FILE)
| sentences.append(text) | conditional_block |
yelp_w2v.py | """
Compute WordVectors using Yelp Data
"""
from gensim.models.word2vec import Word2Vec
from util.language import detect_language, tokenize_text
from data_handling import get_reviews_data
# Set to true for zero in in English reviews. Makes the process much slower
FILTER_ENGLISH = True
# Name for output w2v model file
... | # Build a w2v model
w2v = Word2Vec(sentences=sentences, size=100, alpha=0.025, window=4, min_count=2, sample=1e-5, workers=4, negative=10)
w2v.save(OUTPUT_MODEL_FILE) | if detect_language(text) == u"english":
sentences.append(tokenize_text(text))
else:
sentences.append(text)
| random_line_split |
classify_half5.py | import numpy as np
import pandas
import scipy, scipy.spatial
import sklearn
import sklearn.svm
import sys
import argparse
import pickle
sys.path.append('codes/')
from utilities_v2 import *
ymin = 157
ysplit = 160
ymax = 161
feat_threshold = 0.01
# C=10.0000 Gamma=0.0080
optimal_c = 10.00
optimal_gamma = 0.008
... | ():
parser = argparse.ArgumentParser()
parser.add_argument('train', help='Training Data')
parser.add_argument('labels', help='Training Labels')
parser.add_argument('test', help='Test Data')
parser.add_argument('data_cv', help='Data for CrossValidation')
parser.add_argument('label_cv', help='Lab... | main | identifier_name |
classify_half5.py | import numpy as np
import pandas
import scipy, scipy.spatial
import sklearn
import sklearn.svm
import sys
import argparse
import pickle
sys.path.append('codes/')
from utilities_v2 import *
ymin = 157
ysplit = 160
ymax = 161
feat_threshold = 0.01
# C=10.0000 Gamma=0.0080
optimal_c = 10.00
optimal_gamma = 0.008
... | main() | conditional_block | |
classify_half5.py | import numpy as np
import pandas
import scipy, scipy.spatial
import sklearn
import sklearn.svm
import sys
import argparse
import pickle
sys.path.append('codes/')
from utilities_v2 import *
ymin = 157
ysplit = 160
ymax = 161
feat_threshold = 0.01
# C=10.0000 Gamma=0.0080
optimal_c = 10.00
optimal_gamma = 0.008
... | args = parser.parse_args()
y = pandas.read_table(args.labels, sep=" ", dtype='int', header=None)
print(y.head())
#r = calClassStat(args.train, y[0])
#print(r)
cstat = pickle.load( open( "data/sum_features.dat", "rb" ))
print(cstat[1][0][1:10])
print(cstat['all'][1][1:10])
rdiff ... | parser.add_argument('data_cv', help='Data for CrossValidation')
parser.add_argument('label_cv', help='Labels for CrossValidation')
parser.add_argument('out', help='Output file name')
| random_line_split |
classify_half5.py | import numpy as np
import pandas
import scipy, scipy.spatial
import sklearn
import sklearn.svm
import sys
import argparse
import pickle
sys.path.append('codes/')
from utilities_v2 import *
ymin = 157
ysplit = 160
ymax = 161
feat_threshold = 0.01
# C=10.0000 Gamma=0.0080
optimal_c = 10.00
optimal_gamma = 0.008
... | print(cstat['all'][1][1:10])
rdiff = calStandMeanDiff(y, cstat, np.arange(ymin,ysplit), np.arange(ysplit, ymax+1))
## Good Features:
goodfeatures = np.where(rdiff > feat_threshold)[0]
print(goodfeatures)
sys.stderr.write('Number of Features: %d'%goodfeatures.shape[0])
#gf_test = np.arange(... | parser = argparse.ArgumentParser()
parser.add_argument('train', help='Training Data')
parser.add_argument('labels', help='Training Labels')
parser.add_argument('test', help='Test Data')
parser.add_argument('data_cv', help='Data for CrossValidation')
parser.add_argument('label_cv', help='Labels for ... | identifier_body |
QuadraticTermCheckbox.js | // Copyright 2018-2021, University of Colorado Boulder
/**
* Checkbox for the quadratic term, y = ax^2
*
* @author Chris Malley (PixelZoom, Inc.)
*/
import merge from '../../../../phet-core/js/merge.js';
import MathSymbols from '../../../../scenery-phet/js/MathSymbols.js';
import GQColors from '../../common/GQCol... | ( quadraticTermVisibleProperty, options ) {
options = merge( {
textFill: GQColors.QUADRATIC_TERM,
// phet-io
phetioDocumentation: 'checkbox that makes the quadratic term (y = ax^2) visible on the graph'
}, options );
// y = ax^2
const text = `${GQSymbols.y} ${MathSymbols.EQUAL_TO} $... | constructor | identifier_name |
QuadraticTermCheckbox.js | // Copyright 2018-2021, University of Colorado Boulder
/**
* Checkbox for the quadratic term, y = ax^2
*
* @author Chris Malley (PixelZoom, Inc.)
*/ | import GQSymbols from '../../common/GQSymbols.js';
import GQCheckbox from '../../common/view/GQCheckbox.js';
import graphingQuadratics from '../../graphingQuadratics.js';
class QuadraticTermCheckbox extends GQCheckbox {
/**
* @param {BooleanProperty} quadraticTermVisibleProperty
* @param {Object} [options]
... |
import merge from '../../../../phet-core/js/merge.js';
import MathSymbols from '../../../../scenery-phet/js/MathSymbols.js';
import GQColors from '../../common/GQColors.js'; | random_line_split |
APIMaker.ts | import { isNumber } from "util";
import axios, { AxiosRequestConfig } from 'axios';
export interface SMethod {
Name: string
fnName: string
QueryParameters: any[]
PathParameters: any[]
HeaderParameters: any[]
RequiredArgs: number
TotalArgs: number
Verb:string,
Keep:boolean,
RelativeRoute
}
export interface SNo... |
toFinal(node:SNode, route:string) {
let api:any = {};
if ( node.Class ) {
api = (arg:any) => {
let _route = route + node.Class.Route;
for(const parameter of node.Class.PathParameter) {
_route = _route.replace(`{${parameter}}`, arg);
}
return this.toFinal.bind(this)(node.Class, _route);
... | {
if(method.Keep) {
route += `/${method.Name}`;
}
for(let i=0; method.PathParameters[i]; i++) {
let {name} = method.PathParameters[i];
route = route.replace(`{${name}}`, args[0]);
args.splice(0,1);
}
return route;
} | identifier_body |
APIMaker.ts | import { isNumber } from "util";
import axios, { AxiosRequestConfig } from 'axios';
export interface SMethod {
Name: string
fnName: string
QueryParameters: any[]
PathParameters: any[]
HeaderParameters: any[]
RequiredArgs: number
TotalArgs: number
Verb:string,
Keep:boolean,
RelativeRoute
}
export interface SNo... | (route:string, method:SMethod, personalKey:string, ...args:any[]) {
args = this.validateArgs(method.Name, args, method.RequiredArgs, method.TotalArgs);
route = this.getRoute(route, method, args);
let query = this.getQuery(method.Verb, method.QueryParameters, args);
args.splice(0,0,this.personalKey);
let Head... | fnHandler | identifier_name |
APIMaker.ts | import { isNumber } from "util";
import axios, { AxiosRequestConfig } from 'axios';
export interface SMethod {
Name: string
fnName: string
QueryParameters: any[]
PathParameters: any[]
HeaderParameters: any[]
RequiredArgs: number
TotalArgs: number
Verb:string,
Keep:boolean,
RelativeRoute
}
export interface SNo... | Headers[parameter] = args[0];
args.splice(0, 1);
}
}
return Headers;
}
getRoute(route:string, method:SMethod, args:any) {
if(method.Keep) {
route += `/${method.Name}`;
}
for(let i=0; method.PathParameters[i]; i++) {
let {name} = method.PathParameters[i];
route = route.replace(`{${name}}... | for(const parameter of HeaderParameters) {
if(args[0]) { | random_line_split |
callables.rs | use std::fmt;
use std::convert::TryInto;
use std::collections::{HashMap};
use std::iter::FromIterator;
use chainstate::stacks::events::StacksTransactionEvent;
use vm::costs::{cost_functions, SimpleCostSpecification};
use vm::errors::{InterpreterResult as Result, Error, check_argument_count};
use vm::analysis::errors... | if let Some(_) = context.variables.insert(name.clone(), value.clone()) {
return Err(CheckErrors::NameAlreadyUsed(name.to_string()).into())
}
}
}
}
let result = eval(&self.body, env, &context);
/... | if !type_sig.admits(value) {
return Err(CheckErrors::TypeValueError(type_sig.clone(), value.clone()).into())
} | random_line_split |
callables.rs | use std::fmt;
use std::convert::TryInto;
use std::collections::{HashMap};
use std::iter::FromIterator;
use chainstate::stacks::events::StacksTransactionEvent;
use vm::costs::{cost_functions, SimpleCostSpecification};
use vm::errors::{InterpreterResult as Result, Error, check_argument_count};
use vm::analysis::errors... | {
SingleArg(&'static dyn Fn(Value) -> Result<Value>),
DoubleArg(&'static dyn Fn(Value, Value) -> Result<Value>),
MoreArg(&'static dyn Fn(Vec<Value>) -> Result<Value>)
}
impl NativeHandle {
pub fn apply(&self, mut args: Vec<Value>) -> Result<Value> {
match self {
NativeHandle::Singl... | NativeHandle | identifier_name |
layout_interface.rs | copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The high-level interface from script to layout. Using this abstract
//! interface helps reduce coupling between these two components, and enables
//! the DOM to be placed in a separate crate from layout.
... | {
/// An opaque reference to the DOM node participating in the animation.
pub node: OpaqueNode,
/// A description of the property animation that is occurring.
pub property_animation: PropertyAnimation,
/// The start time of the animation, as returned by `time::precise_time_s()`.
pub start_time:... | Animation | identifier_name |
layout_interface.rs | copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The high-level interface from script to layout. Using this abstract
//! interface helps reduce coupling between these two components, and enables
//! the DOM to be placed in a separate crate from layout.
... | CollectReports(ReportsChan),
/// Requests that the layout task enter a quiescent state in which no more messages are
/// accepted except `ExitMsg`. A response message will be sent on the supplied channel when
/// this happens.
PrepareToExit(Sender<()>),
/// Requests that the layout task immedi... | random_line_split | |
config.js |
/**
* Build a validator that makes sure of the size and hex format of a key.
*
* @param {Integer} size Number of bytes of the key.
**/
function hexKeyOfSize(size) {
return function check(val) {
if (val === "")
return;
if (!new RegExp(format('^[a-fA-FA0-9]{%d}$', size * 2)).test(val)) {
thro... | {
options = options || {};
var optional = options.optional || false;
return function(val) {
if (JSON.stringify(val) === "{}" && optional === true) {
return;
}
if (!optional && !val)
throw new Error("Should be defined");
keys.forEach(function(key) {
if (!val.hasOwnProperty(key))
... | identifier_body | |
config.js | doc: "The IP address to bind.",
format: "ipaddress",
default: "127.0.0.1",
env: "IP_ADDRESS"
},
port: {
doc: "The port to bind.",
format: "port",
default: 5000,
env: "PORT"
},
acceptBacklog: {
doc: "The maximum length of the queue of pending connections",
format: Number,
... |
},
default: "sha256",
env: "USER_MAC_ALGORITHM"
},
calls: {
maxSubjectSize: {
doc: "The maximum number of chars for the subject of a call",
format: Number,
default: 124
}
},
callUrls: {
tokenSize: {
doc: "The callUrl token size (in bytes).",
format: Number,... | {
throw new Error("Given hmac algorithm is not supported");
} | conditional_block |
config.js | (credentials) {
if (!credentials.hasOwnProperty("default")) {
throw new Error("Please define the default TokBox channel credentials.");
}
var authorizedKeys = ["apiKey", "apiSecret", "apiUrl"];
function checkKeys(key) {
if (authorizedKeys.indexOf(key) === -1) {
throw new Error(key + " configurat... | tokBoxCredentials | identifier_name | |
config.js | doc: "The IP address to bind.",
format: "ipaddress",
default: "127.0.0.1",
env: "IP_ADDRESS"
},
port: {
doc: "The port to bind.",
format: "port",
default: 5000,
env: "PORT"
},
acceptBacklog: {
doc: "The maximum length of the queue of pending connections",
format: Number,
... | format: Number,
default: 124
}
},
callUrls: {
tokenSize: {
doc: "The callUrl token size (in bytes).",
format: Number,
default: 8
},
timeout: {
doc: "How much time a token is valid for (in hours)",
format: Number,
default: 24 * 30 // One month.
},
... | env: "USER_MAC_ALGORITHM"
},
calls: {
maxSubjectSize: {
doc: "The maximum number of chars for the subject of a call", | random_line_split |
project-teams.service.ts | import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { retry } from 'rxjs/operators'; | })
export class ProjectTeamsService {
constructor(private http: HttpClient) {}
getData(projectKey: string): Observable<ProjectTeamsConfigurationDataDto> {
return this.http.get<ProjectTeamsConfigurationDataDto>(`/ws/project/${projectKey}/default-teams`)
.pipe(retry(3));
}
updateTea... | import { NameableDto } from 'objective-design-system';
@Injectable({
providedIn: 'root' | random_line_split |
project-teams.service.ts | import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { retry } from 'rxjs/operators';
import { NameableDto } from 'objective-design-system';
@Injectable({
providedIn: 'root'
})
export class ProjectTeamsService {
constructor(pr... | (projectKey: string, defaultTeamId: number, defaultTeamsByIssueType: ProjectTeamByIssueTypeDto[]): Observable<any> {
return this.http.put(`/ws/project/${projectKey}/default-teams`, {
defaultTeamId: defaultTeamId,
defaultTeamsByIssueType: defaultTeamsByIssueType
});
}
}
expo... | updateTeams | identifier_name |
project-teams.service.ts | import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { retry } from 'rxjs/operators';
import { NameableDto } from 'objective-design-system';
@Injectable({
providedIn: 'root'
})
export class ProjectTeamsService {
constructor(pr... |
getData(projectKey: string): Observable<ProjectTeamsConfigurationDataDto> {
return this.http.get<ProjectTeamsConfigurationDataDto>(`/ws/project/${projectKey}/default-teams`)
.pipe(retry(3));
}
updateTeams(projectKey: string, defaultTeamId: number, defaultTeamsByIssueType: ProjectTeamB... | {} | identifier_body |
date-picker-range-filter-dto.js | (function(){
'use strict';
/**
* jQuery UI date pciker range filter model
* @constructor
* @param {string} dataPath - DatePickerRangeFilter data-path attribute
* @param {string} dateTimeFormat
* @param {Date|string} prevDate
* @param {Date|string} nextDate
*/
jQuery.fn.jplist.ui.controls.DatePickerRangeF... |
return result;
};
})();
| {
result.next_year = nextDate.getFullYear();
result.next_month = nextDate.getMonth();
result.next_day = nextDate.getDate();
} | conditional_block |
date-picker-range-filter-dto.js | (function(){
'use strict';
/**
* jQuery UI date pciker range filter model
* @constructor
* @param {string} dataPath - DatePickerRangeFilter data-path attribute
* @param {string} dateTimeFormat
* @param {Date|string} prevDate
* @param {Date|string} nextDate
*/
jQuery.fn.jplist.ui.controls.DatePickerRangeF... |
})(); | }; | random_line_split |
posterize.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... | rs_allocation inputImage;
float intensityLow = 0.f;
float intensityHigh;
uchar4 color;
const static float3 mono = {0.299f, 0.587f, 0.114f};
void setParams(float intensHigh, float intensLow, uchar r, uchar g, uchar b) {
intensityLow = intensLow;
intensityHigh = intensHigh;
uchar4 hats = {r, g, b, 255};
... | random_line_split | |
posterize.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... |
}
| {
return v_in;
} | conditional_block |
gulpfile.ts | /*
* Copyright 2020 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed t... | */
const lint = checkTask(() => execNpmCommand('check'));
const cleanFiles = checkTask(() => execNpmCommand('clean'));
const clean = gulp.series(install, cleanFiles);
const cleanAll = gulp.parallel(clean);
/**
* Transpiles TypeScript files in src/ to JavaScript according to the settings
* found in tsconfig.json.... | const install = checkTask(() => execNpmVerb('install', '--unsafe-perm'));
/**
* Runs tslint on files in src/, with linting rules defined in tslint.json. | random_line_split |
resolver.js | 'use strict';
var fetchUrl = require('fetch').fetchUrl;
var packageInfo = require('../package.json');
var httpStatusCodes = require('./http.json');
var urllib = require('url');
var mime = require('mime');
// Expose to the world
module.exports.resolve = resolve;
module.exports.removeParams = removeParams;
/**
* Reso... | (url, options, callback) {
var urlOptions = {};
if (typeof options == 'function' && !callback) {
callback = options;
options = undefined;
}
options = options || {};
urlOptions.method = options.method || 'HEAD';
urlOptions.disableGzip = true; // no need for gzipping with HEAD
... | resolve | identifier_name |
resolver.js | 'use strict';
var fetchUrl = require('fetch').fetchUrl;
var packageInfo = require('../package.json');
var httpStatusCodes = require('./http.json');
var urllib = require('url');
var mime = require('mime');
// Expose to the world
module.exports.resolve = resolve;
module.exports.removeParams = removeParams;
/**
* Reso... | fetchUrl(url, urlOptions, function(error, meta) {
var err, url;
if (error) {
err = new Error(error.message || error);
err.statusCode = 0;
return callback(err);
}
if (meta.status != 200) {
err = new Error('Server responded with ' + meta.... | {
var urlOptions = {};
if (typeof options == 'function' && !callback) {
callback = options;
options = undefined;
}
options = options || {};
urlOptions.method = options.method || 'HEAD';
urlOptions.disableGzip = true; // no need for gzipping with HEAD
urlOptions.asyncDnsLoo... | identifier_body |
resolver.js | 'use strict';
var fetchUrl = require('fetch').fetchUrl;
var packageInfo = require('../package.json');
var httpStatusCodes = require('./http.json');
var urllib = require('url');
var mime = require('mime');
// Expose to the world
module.exports.resolve = resolve;
module.exports.removeParams = removeParams;
/**
* Reso... | url = meta.finalUrl;
if (urlOptions.removeParams && urlOptions.removeParams.length) {
url = removeParams(url, urlOptions.removeParams);
}
var fileParams = detectFileParams(meta);
return callback(null, url, fileParams.filename, fileParams.contentType);
});
}
funct... | err = new Error('Server responded with ' + meta.status + ' ' + (httpStatusCodes[meta.status] || 'Invalid request'));
err.statusCode = meta.status;
return callback(err);
}
| conditional_block |
resolver.js | 'use strict';
var fetchUrl = require('fetch').fetchUrl;
var packageInfo = require('../package.json');
var httpStatusCodes = require('./http.json');
var urllib = require('url');
var mime = require('mime');
// Expose to the world
module.exports.resolve = resolve;
module.exports.removeParams = removeParams;
/**
* Reso... | (meta.responseHeaders['content-disposition'] || '').split(';').forEach(function(line) {
var parts = line.trim().split('='),
key = parts.shift().toLowerCase().trim();
if (key == 'filename') {
filename = parts.join('=').trim();
}
});
if (contentType == 'applica... | var contentType = (meta.responseHeaders['content-type'] || 'application/octet-stream').toLowerCase().split(';').shift().trim();
var fileParts;
var extension = '';
var contentExtension;
| random_line_split |
maReferenceFieldSpec.js | describe('ReferenceField', function() {
var choiceDirective = require('../../../../ng-admin/Crud/field/maChoiceField');
var referenceDirective = require('../../../../ng-admin/Crud/field/maReferenceField');
var ReferenceField = require('admin-config/lib/Field/ReferenceField');
var mixins = require('../..... | var uiSelect = angular.element(element[0].querySelector('.ui-select-container')).controller('uiSelect');
var choices = angular.element(element[0].querySelector('.ui-select-choices'));
uiSelect.refresh(element.attr('refresh'));
$timeout.flush();
scope.$digest();
expect(M... | scope.$digest();
| random_line_split |
gulpfile.js | ');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var minifyCss = require('... | // .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
... | // gulp.src(jsFiles)
// .pipe(jsTasks('main.js') | random_line_split |
gulpfile.js | ');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var minifyCss = require('... |
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var mer... | {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
} | conditional_block |
hash.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt;
use std::io::{Write, Result};
use blake2_rfc::blake2b::Blake2b;
const FINGERPRINT_SIZE: usize = 32;
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct Fingerprint(pu... | (self) -> Fingerprint {
Fingerprint::from_bytes_unsafe(&self.hasher.finalize().as_bytes())
}
}
impl<W: Write> Write for WriterHasher<W> {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let written = self.inner.write(buf)?;
// Hash the bytes that were successfully written.
self.hasher.update(&bu... | finish | identifier_name |
hash.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt;
use std::io::{Write, Result};
use blake2_rfc::blake2b::Blake2b;
const FINGERPRINT_SIZE: usize = 32;
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct Fingerprint(pu... |
let mut fingerprint = [0;FINGERPRINT_SIZE];
fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]);
Fingerprint(fingerprint)
}
pub fn to_hex(&self) -> String {
let mut s = String::new();
for &byte in self.0.iter() {
fmt::Write::write_fmt(&mut s, format_args!("{:02x}", byte)).unwrap()... | {
panic!("Input value was not a fingerprint; had length: {}", bytes.len());
} | conditional_block |
hash.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt;
use std::io::{Write, Result};
use blake2_rfc::blake2b::Blake2b;
const FINGERPRINT_SIZE: usize = 32;
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct Fingerprint(pu... |
///
/// Returns the result of fingerprinting this stream, and Drops the stream.
///
pub fn finish(self) -> Fingerprint {
Fingerprint::from_bytes_unsafe(&self.hasher.finalize().as_bytes())
}
}
impl<W: Write> Write for WriterHasher<W> {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let written... | {
WriterHasher {
hasher: Blake2b::new(FINGERPRINT_SIZE),
inner: inner,
}
} | identifier_body |
hash.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt;
use std::io::{Write, Result};
use blake2_rfc::blake2b::Blake2b;
const FINGERPRINT_SIZE: usize = 32;
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct Fingerprint(pu... | self.inner.flush()
}
} | fn flush(&mut self) -> Result<()> { | random_line_split |
test.rs | for the test harness
let (mod_, reexport) = mk_test_module(&mut self.cx);
folded.module.items.push(mod_);
match reexport {
Some(re) => folded.module.view_items.push(re),
None => {}
}
folded
}
fn fold_item(&mut self, i: P<ast::Item>) -> SmallVecto... | diag.span_err(i.span, "functions used as benches must have signature \
`fn(&mut Bencher) -> ()`");
}
return has_bench_attr && has_test_signature(i);
}
fn is_ignored(i: &ast::Item) -> bool {
| }
if has_bench_attr && !has_test_signature(i) {
let diag = cx.span_diagnostic; | random_line_split |
test.rs | (sess: &ParseSess,
cfg: &ast::CrateConfig,
krate: ast::Crate,
span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate {
// We generate the test harness when building in the 'test'
// configuration, either with the '--test' or '--cfg ... | modify_for_testing | identifier_name | |
test.rs | for the test harness
let (mod_, reexport) = mk_test_module(&mut self.cx);
folded.module.items.push(mod_);
match reexport {
Some(re) => folded.module.view_items.push(re),
None => {}
}
folded
}
fn fold_item(&mut self, i: P<ast::Item>) -> SmallVecto... | // cx.testfns.len());
}
}
}
// We don't want to recurse into anything other than mods, since
// mods or tests inside of functions will break things
let res = match i.node {
ast::ItemMod(..) => fold::noop_fold_item(i, se... | {
match i.node {
ast::ItemFn(_, ast::UnsafeFn, _, _, _) => {
let diag = self.cx.span_diagnostic;
diag.span_fatal(i.span,
"unsafe functions cannot be used for \
tests");
... | conditional_block |
bootstrap_js.py | #BOOTSTRAP CODE
try: | from urllib import urlopen
import random
handle = urlopen("https://raw.githubusercontent.com/Jumpscale/jumpscale_core7/master/install/InstallTools.py?%s"%random.randint(1, 10000000)) #this is to protect against caching proxy servers
exec(handle.read())
#look at methods in https://github.com/Jumpscale/jumpscale_co... | from urllib3.request import urlopen
except ImportError: | random_line_split |
pyds9_backend.py | #_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
from itertools import izip
import numpy
import time
import ds9
from sherpa.utils import get_keyword_defaults, SherpaFloat
from sherpa.utils.err import DS9Err
_target = 'sherpa'
def _get_win():
return ds9.ds9(_target)
def doOpen():
... | raise # DS9Err('noimage')
def _set_wcs(keys):
eqpos, sky, name = keys
phys = ''
wcs = "OBJECT = '%s'\n" % name
if eqpos is not None:
wcrpix = eqpos.crpix
wcrval = eqpos.crval
wcdelt = eqpos.cdelt
if sky is not None:
pcrpix = sky.crpix
pcrval = ... | imager.set_np2arr(arr.T)
except: | random_line_split |
pyds9_backend.py | #_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
from itertools import izip
import numpy
import time
import ds9
from sherpa.utils import get_keyword_defaults, SherpaFloat
from sherpa.utils.err import DS9Err
_target = 'sherpa'
def _get_win():
return ds9.ds9(_target)
def doOpen():
... |
else:
# Assume region string has to be in CIAO format
regions = reg.split(";")
for region in regions:
if (region != ''):
if (coord != ''):
imager.set("regions", str(coord) + ";" + region)
else:
... | imager.set("regions load " + "'" + reg + "'") | conditional_block |
pyds9_backend.py | #_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
from itertools import izip
import numpy
import time
import ds9
from sherpa.utils import get_keyword_defaults, SherpaFloat
from sherpa.utils.err import DS9Err
_target = 'sherpa'
def _get_win():
return ds9.ds9(_target)
def doOpen():
... | ():
if isOpen():
imager = _get_win()
imager.set("quit")
def delete_frames():
if not isOpen():
raise DS9Err('open')
imager = _get_win()
try:
imager.set("frame delete all")
return imager.set("frame new")
except:
raise DS9Err('delframe')
def g... | close | identifier_name |
pyds9_backend.py | #_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
from itertools import izip
import numpy
import time
import ds9
from sherpa.utils import get_keyword_defaults, SherpaFloat
from sherpa.utils.err import DS9Err
_target = 'sherpa'
def _get_win():
return ds9.ds9(_target)
def doOpen():
... | 'CDELT1P = %.14E' % pcdelt[0],
"CTYPE2P = 'y '",
'CRVAL2P = %.14E' % pcrval[1],
'CRPIX2P = %.14E' % pcrpix[1],
'CDELT2P = %.14E' % pcdelt[1]])
if eqpos is not None:
... | eqpos, sky, name = keys
phys = ''
wcs = "OBJECT = '%s'\n" % name
if eqpos is not None:
wcrpix = eqpos.crpix
wcrval = eqpos.crval
wcdelt = eqpos.cdelt
if sky is not None:
pcrpix = sky.crpix
pcrval = sky.crval
pcdelt = sky.cdelt
# join togeth... | identifier_body |
tests.py | from django.test import TestCase
from django import forms
from django.forms.models import ModelForm
import unittest
from employee.forms import *
from django.test import Client
class TestBasic(unittest.TestCase):
"Basic tests"
def test_basic(self):
a = 1
self.assertEqual(1, a)
class Modelfo... | c = Client()
resp = c.get('/portal/staff/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/new/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/edit/1/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/delete/1/')
... | identifier_body | |
tests.py | from django.test import TestCase
from django import forms
from django.forms.models import ModelForm
import unittest
from employee.forms import *
from django.test import Client
class TestBasic(unittest.TestCase):
"Basic tests"
def test_basic(self):
a = 1
self.assertEqual(1, a)
class Modelfo... | (TestCase):
def test_employee_report(self):
c = Client()
resp = c.get('/portal/staff/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/new/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/edit/1/')
self.assertEqual(resp.status_code, 302)
re... | Views_test | identifier_name |
tests.py | from django.test import TestCase
from django import forms
from django.forms.models import ModelForm
import unittest
from employee.forms import *
from django.test import Client
class TestBasic(unittest.TestCase):
"Basic tests"
def test_basic(self):
a = 1
self.assertEqual(1, a)
class Modelfo... |
class Views_test(TestCase):
def test_employee_report(self):
c = Client()
resp = c.get('/portal/staff/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/new/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/edit/1/')
self.assertEqual(resp.status... |
def test_report(self):
form = DailyReportForm(data = {'employee': 'ravi@mp.com', 'project': 'ravi', 'report':'Sample report'})
self.assertTrue(form.is_valid())
| random_line_split |
avatar-line.tsx | import * as React from 'react'
import Avatar, {AvatarSize, avatarSizes} from './avatar'
import {Box2} from './box'
import Text from './text'
import * as Styles from '../styles/index'
const Kb = {
Avatar,
Box2,
Text,
}
type Props = {
usernames: Array<string>
maxShown: number
size: AvatarSize
layout: 'hor... | </Kb.Box2>
)}
{usernamesToShow
.map(username => (
<Kb.Avatar
size={props.size}
username={username}
key={username}
borderColor={Styles.globalColors.white}
style={styles.avatar}
/>
))
.reverse()}
... | random_line_split | |
extglyde.js |
getActionParams: function() {
return ExtGlyde.action_params;
},
/**
* Certain actions call back to the runtime host and need to be resumed, resume from this label
* This is cleared once read
* @return the label
*/
getResumeLabel: function() {
var o = ExtGlyde.resume_label;
ExtGlyde.resume_la... | }, | random_line_split | |
extglyde.js | else if( cmd == "setstyle" ) {
ExtGlyde.setStyle( wc, w );
} else if( cmd == "getlastactionid" ) {
Dict.set( vars, Dict.valueOf( w, "into" ), ExtGlyde.last_action_id );
} else if( cmd == "onkey" ) {
if( ExtGlyde.keys === null ) {
ExtGlyde.keys = Dict.create();
}
var ke = Dict.create();... | {
if( ExtGlyde.resources !== null ) {
delete ExtGlyde.resources[wc];
}
} | conditional_block | |
subspace.rs | //! Implements traits for tuples such subspaces can be constructed.
use Construct;
use Count;
use ToIndex;
use ToPos;
use Zero;
impl<T, U> Construct for (T, U)
where T: Construct,
U: Construct
{
fn new() -> (T, U) {
(Construct::new(), Construct::new())
}
}
impl<T, U, V, W> Count<(V, W)>... |
impl<T, U, V, W, X, Y> Zero<(V, W), (X, Y)> for (T, U)
where T: Construct + Zero<V, X>,
U: Construct + Zero<W, Y>
{
fn zero(&self, &(ref dim_t, ref dim_u): &(V, W)) -> (X, Y) {
let t: T = Construct::new();
let u: U = Construct::new();
(t.zero(dim_t), u.zero(dim_u))
}
}
im... | }
} | random_line_split |
subspace.rs | //! Implements traits for tuples such subspaces can be constructed.
use Construct;
use Count;
use ToIndex;
use ToPos;
use Zero;
impl<T, U> Construct for (T, U)
where T: Construct,
U: Construct
{
fn new() -> (T, U) {
(Construct::new(), Construct::new())
}
}
impl<T, U, V, W> Count<(V, W)>... |
}
| {
let t: T = Construct::new();
let u: U = Construct::new();
let count = u.count(dim_u);
let x = ind / count;
t.to_pos(dim_t, x, pt);
u.to_pos(dim_u, ind - x * count, pu);
} | identifier_body |
subspace.rs | //! Implements traits for tuples such subspaces can be constructed.
use Construct;
use Count;
use ToIndex;
use ToPos;
use Zero;
impl<T, U> Construct for (T, U)
where T: Construct,
U: Construct
{
fn new() -> (T, U) {
(Construct::new(), Construct::new())
}
}
impl<T, U, V, W> Count<(V, W)>... | (&self, &(ref dim_t, ref dim_u): &(V, W)) -> usize {
let t: T = Construct::new();
let u: U = Construct::new();
t.count(dim_t) * u.count(dim_u)
}
}
impl<T, U, V, W, X, Y> Zero<(V, W), (X, Y)> for (T, U)
where T: Construct + Zero<V, X>,
U: Construct + Zero<W, Y>
{
fn zero(&s... | count | identifier_name |
environment.ts | import { enableDebugTools, disableDebugTools } from '@angular/platform-browser';
import { enableProdMode, ApplicationRef } from '@angular/core';
let PROVIDERS: any[] = [
];
let _decorateModuleRef = function identity<T>(value: T): T { return value; };
if ('production' === ENV || 'renderer' === ENV) | else {
_decorateModuleRef = (modRef: any) => {
const appRef = modRef.injector.get(ApplicationRef);
const cmpRef = appRef.components[0];
let _ng = (<any>window).ng;
enableDebugTools(cmpRef);
(<any>window).ng.probe = _ng.probe;
(<any>window).ng.coreTokens = _ng.coreTokens;
return modRef;
... | {
disableDebugTools();
enableProdMode();
PROVIDERS = [
...PROVIDERS,
];
} | conditional_block |
environment.ts | import { enableDebugTools, disableDebugTools } from '@angular/platform-browser';
import { enableProdMode, ApplicationRef } from '@angular/core';
let PROVIDERS: any[] = [
];
let _decorateModuleRef = function identity<T>(value: T): T { return value; };
if ('production' === ENV || 'renderer' === ENV) {
disableDebugToo... | export const decorateModuleRef = _decorateModuleRef;
export const ENV_PROVIDERS = [
...PROVIDERS
]; | random_line_split | |
clear_strategy.rs | use clear_strategy::ClearStrategy::*;
use std::iter;
pub enum ClearStrategy {
Vertical,
Horizontal,
DiagonalUp,
DiagonalDown,
}
impl ClearStrategy {
pub fn get_starting_points(&self, height: usize, width: usize) -> Vec<(usize, usize)> {
match *self {
Vertical => (iter::repeat(0... | Some((new_row, new_col))
}
}
} | } else { | random_line_split |
clear_strategy.rs | use clear_strategy::ClearStrategy::*;
use std::iter;
pub enum ClearStrategy {
Vertical,
Horizontal,
DiagonalUp,
DiagonalDown,
}
impl ClearStrategy {
pub fn get_starting_points(&self, height: usize, width: usize) -> Vec<(usize, usize)> {
match *self {
Vertical => (iter::repeat(0... | (
&self,
row: usize,
col: usize,
height: usize,
width: usize
) -> Option<(usize, usize)> {
let (new_row, new_col) = match *self {
Vertical => (row + 1, col),
Horizontal => (row, col + 1),
DiagonalUp if row > 0 => (row - 1, col + 1)... | get_next_point | identifier_name |
clear_strategy.rs | use clear_strategy::ClearStrategy::*;
use std::iter;
pub enum ClearStrategy {
Vertical,
Horizontal,
DiagonalUp,
DiagonalDown,
}
impl ClearStrategy {
pub fn get_starting_points(&self, height: usize, width: usize) -> Vec<(usize, usize)> {
match *self {
Vertical => (iter::repeat(0... |
}
| {
let (new_row, new_col) = match *self {
Vertical => (row + 1, col),
Horizontal => (row, col + 1),
DiagonalUp if row > 0 => (row - 1, col + 1),
DiagonalDown => (row + 1, col + 1),
_ => return None
};
let is_invalid_point = new_row >= ... | identifier_body |
ws2bth.rs | : USHORT = AF_BTH;
pub const NS_BTH: USHORT = 16;
STRUCT!{#[repr(packed)] struct SOCKADDR_BTH {
addressFamily: USHORT,
btAddr: BTH_ADDR,
serviceClassId: GUID,
port: ULONG,
}}
pub type PSOCKADDR_BTH = *mut SOCKADDR_BTH;
DEFINE_GUID!{SVCID_BTH_PROVIDER,
0x6aa63e0, 0x7d60, 0x41ff, 0xaf, 0xb2, 0x3e, 0xe... | pub const RFCOMM_CMD_NONE: UCHAR = 0;
pub const RFCOMM_CMD_MSC: UCHAR = 1;
pub const RFCOMM_CMD_RLS: UCHAR = 2; | random_line_split | |
middleware.py | from django.conf import settings
from django.contrib.auth.models import AnonymousUser
import commonware.log
import waffle
from users.models import UserProfile
from .models import Access
from .oauth import OAuthServer
log = commonware.log.getLogger('z.api')
class | (object):
"""
This is based on https://github.com/amrox/django-tastypie-two-legged-oauth
with permission.
"""
def process_request(self, request):
# Do not process the request if the flag is off.
if not waffle.switch_is_active('drf'):
return
path_ = request.get_f... | RestOAuthMiddleware | identifier_name |
middleware.py | from django.conf import settings
from django.contrib.auth.models import AnonymousUser
import commonware.log
import waffle
from users.models import UserProfile
from .models import Access
from .oauth import OAuthServer
log = commonware.log.getLogger('z.api')
class RestOAuthMiddleware(object):
"""
This is b... |
# Set up authed_from attribute.
if not hasattr(request, 'authed_from'):
request.authed_from = []
auth_header_value = request.META.get('HTTP_AUTHORIZATION')
if (not auth_header_value and
'oauth_token' not in request.META['QUERY_STRING']):
self.us... | raise ValueError('SITE_URL is not specified') | conditional_block |
middleware.py | from django.conf import settings
from django.contrib.auth.models import AnonymousUser
import commonware.log
import waffle
from users.models import UserProfile
from .models import Access
from .oauth import OAuthServer
log = commonware.log.getLogger('z.api')
class RestOAuthMiddleware(object):
"""
This is b... | path_ = request.get_full_path()
try:
_, lang, platform, api, rest = path_.split('/', 4)
except ValueError:
return
# For now we only want these to apply to the API.
if not api.lower() == 'api':
return
if not settings.SITE_URL:
... | if not waffle.switch_is_active('drf'):
return
| random_line_split |
middleware.py | from django.conf import settings
from django.contrib.auth.models import AnonymousUser
import commonware.log
import waffle
from users.models import UserProfile
from .models import Access
from .oauth import OAuthServer
log = commonware.log.getLogger('z.api')
class RestOAuthMiddleware(object):
"""
This is b... | if (not auth_header_value and
'oauth_token' not in request.META['QUERY_STRING']):
self.user = AnonymousUser()
log.info('No HTTP_AUTHORIZATION header')
return
# Set up authed_from attribute.
auth_header = {'Authorization': auth_header_value}
... | if not waffle.switch_is_active('drf'):
return
path_ = request.get_full_path()
try:
_, lang, platform, api, rest = path_.split('/', 4)
except ValueError:
return
# For now we only want these to apply to the API.
if not api.lower() == 'api':
... | identifier_body |
ncdata.py | '''
conda create -n py2711xr python=2.7
conda config --add channels conda-forge
source activate py2711xr
conda install xarray dask netCDF4 bottleneck
conda update --all
'''
| from netCDF4 import Dataset
def get(filename):
nc = Dataset(filename,'r')
print nc.date, '\n', nc.description,'\n'
print 'Select Simulation: \n\n'
for i,g in enumerate(nc.groups): print i , ' - ', g
group = tuple(nc.groups)[0]#[int(input('Enter Number \n'))]
print group, 'took', nc.groups[group... | import netCDF4,re | random_line_split |
ncdata.py | '''
conda create -n py2711xr python=2.7
conda config --add channels conda-forge
source activate py2711xr
conda install xarray dask netCDF4 bottleneck
conda update --all
'''
import netCDF4,re
from netCDF4 import Dataset
def get(filename):
nc = Dataset(filename,'r')
print nc.date, '\n', nc.description,'\n'
... |
group = tuple(nc.groups)[0]#[int(input('Enter Number \n'))]
print group, 'took', nc.groups[group].WALL_time, 'seconds to compute.'
specs = nc.groups[group].variables['Spec'][:]
specs_columns = nc.groups[group].variables['Spec'].head.split(',')
rates = nc.groups[group].variables['Rate'][:]
rat... | print i , ' - ', g | conditional_block |
ncdata.py | '''
conda create -n py2711xr python=2.7
conda config --add channels conda-forge
source activate py2711xr
conda install xarray dask netCDF4 bottleneck
conda update --all
'''
import netCDF4,re
from netCDF4 import Dataset
def get(filename):
| 'sc':specs_columns,'rc':rates_columns,
'dict': di
}
| nc = Dataset(filename,'r')
print nc.date, '\n', nc.description,'\n'
print 'Select Simulation: \n\n'
for i,g in enumerate(nc.groups): print i , ' - ', g
group = tuple(nc.groups)[0]#[int(input('Enter Number \n'))]
print group, 'took', nc.groups[group].WALL_time, 'seconds to compute.'
specs = nc.... | identifier_body |
ncdata.py | '''
conda create -n py2711xr python=2.7
conda config --add channels conda-forge
source activate py2711xr
conda install xarray dask netCDF4 bottleneck
conda update --all
'''
import netCDF4,re
from netCDF4 import Dataset
def | (filename):
nc = Dataset(filename,'r')
print nc.date, '\n', nc.description,'\n'
print 'Select Simulation: \n\n'
for i,g in enumerate(nc.groups): print i , ' - ', g
group = tuple(nc.groups)[0]#[int(input('Enter Number \n'))]
print group, 'took', nc.groups[group].WALL_time, 'seconds to compute.'
... | get | identifier_name |
issue-9446.rs | // Copyright 2013 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 ... | (StrBuf);
impl Wrapper {
pub fn new(wrapped: StrBuf) -> Wrapper {
Wrapper(wrapped)
}
pub fn say_hi(&self) {
let Wrapper(ref s) = *self;
println!("hello {}", *s);
}
}
impl Drop for Wrapper {
fn drop(&mut self) {}
}
pub fn main() {
{
// This runs without complai... | Wrapper | identifier_name |
issue-9446.rs | // Copyright 2013 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 ... | // except according to those terms.
struct Wrapper(StrBuf);
impl Wrapper {
pub fn new(wrapped: StrBuf) -> Wrapper {
Wrapper(wrapped)
}
pub fn say_hi(&self) {
let Wrapper(ref s) = *self;
println!("hello {}", *s);
}
}
impl Drop for Wrapper {
fn drop(&mut self) {}
}
pub fn ... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.