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 |
|---|---|---|---|---|
translate-contributors.py | all candidate replacements to the user and awaits user response. In this
# mode, the user may also input a custom name. This is the default.
#
# (2) Non-interactive mode: For each invalid author name, this script replaces
# the name with the first valid candidate it can find. If there is none, it
# uses the original n... |
# Translate each invalid author by searching for possible candidates from Github and JIRA
# In interactive mode, this script presents the user with a list of choices and have the user
# select from this list. Additionally, the user may also choose to enter a custom name.
# In non-interactive mode, this script picks th... | random_line_split | |
translate-contributors.py | all candidate replacements to the user and awaits user response. In this
# mode, the user may also input a custom name. This is the default.
#
# (2) Non-interactive mode: For each invalid author name, this script replaces
# the name with the first valid candidate it can find. If there is none, it
# uses the original n... | if e.status_code == 404:
warnings.append("Issue %s not found!" % issue)
continue
raise e
jira_assignee = jira_issue.fields.assignee
if jira_assignee:
user_name = jira_assignee.name
display_name = jira_assignee.displayName
... | candidates = []
# First check for full name of Github user
github_name = get_github_name(author, github_client)
if github_name:
candidates.append((github_name, "Full name of Github user %s" % author))
else:
candidates.append((NOT_FOUND, "No full name found for Github user %s" % author))
... | identifier_body |
translate-contributors.py | all candidate replacements to the user and awaits user response. In this
# mode, the user may also input a custom name. This is the default.
#
# (2) Non-interactive mode: For each invalid author name, this script replaces
# the name with the first valid candidate it can find. If there is none, it
# uses the original n... | (author, issues):
candidates = []
# First check for full name of Github user
github_name = get_github_name(author, github_client)
if github_name:
candidates.append((github_name, "Full name of Github user %s" % author))
else:
candidates.append((NOT_FOUND, "No full name found for Githu... | generate_candidates | identifier_name |
translate-contributors.py | all candidate replacements to the user and awaits user response. In this
# mode, the user may also input a custom name. This is the default.
#
# (2) Non-interactive mode: For each invalid author name, this script replaces
# the name with the first valid candidate it can find. If there is none, it
# uses the original n... |
else:
candidates.append((NOT_FOUND, "No assignee found for %s" % issue))
# Guard against special characters in candidate names
# Note that the candidate name may already be in unicode (JIRA returns this)
for i, (candidate, source) in enumerate(candidates):
try:
candi... | candidates.append(
(NOT_FOUND, "No full name found for %s assignee %s" % (issue, user_name))) | conditional_block |
gal-file.py | import pandas as pd
import os
# -*- coding: utf-8 -*-
from flutype.data_management.fill_master import Master
import numpy as np
def print_full(x):
pd.set_option('display.max_rows', len(x))
print(x)
pd.reset_option('display.max_rows')
def extract_peptide_batch(ma):
gal_lig_fix = ma.read_gal_ligand("170... | (gal_file):
virus_map = {}
for i in range(1,33):
if i <= 12:
virus_map[i] = "Ach1"
elif 12 < i <= 24:
virus_map[i] = "Cal2"
elif 24 < i:
virus_map[i] = "Pan3"
for key in virus_map.keys():
gal_file.loc[gal_file["Block"]== key , "Name"] ... | three_viruses_gal | identifier_name |
gal-file.py | import pandas as pd
import os
# -*- coding: utf-8 -*-
from flutype.data_management.fill_master import Master
import numpy as np
def print_full(x):
pd.set_option('display.max_rows', len(x))
print(x)
pd.reset_option('display.max_rows')
def extract_peptide_batch(ma):
gal_lig_fix = ma.read_gal_ligand("170... |
return gal_file
####################################################################
if __name__ == "__main__":
ma_path = "../master_uncomplete/"
ma = Master(ma_path)
#peptide_batch = extract_peptide_batch(ma)
# print_full(peptide_batch)
#fp = os.path.join(ma.collections_path,"170725_N13","... | gal_file.loc[gal_file["Block"]== key , "Name"] =virus_map[key] | conditional_block |
gal-file.py | import pandas as pd
import os
# -*- coding: utf-8 -*-
from flutype.data_management.fill_master import Master
import numpy as np
def print_full(x):
pd.set_option('display.max_rows', len(x))
print(x)
pd.reset_option('display.max_rows')
def extract_peptide_batch(ma):
gal_lig_fix = ma.read_gal_ligand("170... |
for key in virus_map.keys():
gal_file.loc[gal_file["Block"]== key , "Name"] =virus_map[key]
return gal_file
####################################################################
if __name__ == "__main__":
ma_path = "../master_uncomplete/"
ma = Master(ma_path)
#peptide_batch = extract_p... | random_line_split | |
gal-file.py | import pandas as pd
import os
# -*- coding: utf-8 -*-
from flutype.data_management.fill_master import Master
import numpy as np
def print_full(x):
pd.set_option('display.max_rows', len(x))
print(x)
pd.reset_option('display.max_rows')
def extract_peptide_batch(ma):
gal_lig_fix = ma.read_gal_ligand("170... |
return gal_file
def three_viruses_gal(gal_file):
virus_map = {}
for i in range(1,33):
if i <= 12:
virus_map[i] = "Ach1"
elif 12 < i <= 24:
virus_map[i] = "Cal2"
elif 24 < i:
virus_map[i] = "Pan3"
for key in virus_map.keys():
gal... | a = []
b = []
for i in range(shape[1]):
for ii in range(shape[0]):
a.append(i )
b.append(ii )
gal_file["row_factor"] = 0
gal_file["column_factor"] = 0
print(a)
print(b)
for block_num,block_factor in enumerate(a):
gal_file.loc[gal_file["Block"] == b... | identifier_body |
response.rs | //! Client Responses
use std::num::FromPrimitive;
use std::io::{BufferedReader, IoResult};
use header;
use header::common::{ContentLength, TransferEncoding};
use header::common::transfer_encoding::Encoding::Chunked;
use net::{NetworkStream, HttpStream};
use http::{read_status_line, HttpReader, RawStatus};
use http::Ht... |
/// Unwraps the Request to return the NetworkStream underneath.
pub fn unwrap(self) -> Box<NetworkStream + Send> {
self.body.unwrap().unwrap()
}
}
impl Reader for Response {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
self.body.read(buf)
}
}
#[cfg(test)]
... | {
&self.status_raw
} | identifier_body |
response.rs | //! Client Responses
use std::num::FromPrimitive;
use std::io::{BufferedReader, IoResult};
use header;
use header::common::{ContentLength, TransferEncoding};
use header::common::transfer_encoding::Encoding::Chunked;
use net::{NetworkStream, HttpStream};
use http::{read_status_line, HttpReader, RawStatus};
use http::Ht... | else if headers.has::<ContentLength>() {
match headers.get::<ContentLength>() {
Some(&ContentLength(len)) => SizedReader(stream, len),
None => unreachable!()
}
} else {
debug!("neither Transfer-Encoding nor Content-Length");
EofRea... | {
match headers.get::<TransferEncoding>() {
Some(&TransferEncoding(ref codings)) => {
if codings.len() > 1 {
debug!("TODO: #2 handle other codings: {}", codings);
};
if codings.contains(&Chunked) {
... | conditional_block |
response.rs | //! Client Responses
use std::num::FromPrimitive;
use std::io::{BufferedReader, IoResult};
use header;
use header::common::{ContentLength, TransferEncoding};
use header::common::transfer_encoding::Encoding::Chunked;
use net::{NetworkStream, HttpStream};
use http::{read_status_line, HttpReader, RawStatus};
use http::Ht... | (&self) -> &RawStatus {
&self.status_raw
}
/// Unwraps the Request to return the NetworkStream underneath.
pub fn unwrap(self) -> Box<NetworkStream + Send> {
self.body.unwrap().unwrap()
}
}
impl Reader for Response {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint... | status_raw | identifier_name |
response.rs | //! Client Responses
use std::num::FromPrimitive;
use std::io::{BufferedReader, IoResult};
use header;
use header::common::{ContentLength, TransferEncoding};
use header::common::transfer_encoding::Encoding::Chunked;
use net::{NetworkStream, HttpStream};
use http::{read_status_line, HttpReader, RawStatus};
use http::Ht... | /// A response for a client request to a remote server.
pub struct Response<S = HttpStream> {
/// The status from the server.
pub status: status::StatusCode,
/// The headers from the server.
pub headers: header::Headers,
/// The HTTP version of this response from the server.
pub version: version... | use HttpResult;
use HttpError::HttpStatusError;
| random_line_split |
storage-data-util.js | "use strict";
var _getSert = require("../getsert");
var generateCode = require("../../../src/utils/code-generator");
class StorageDataUtil {
getSert(input) {
var ManagerType = require("../../../src/managers/master/storage-manager");
return _getSert(input, ManagerType, (data) => {
return... | () {
return this.getNewData()
.then((data) => {
return this.getSert(data);
});
}
getTestData() {
var data = {
code: 'UT/STO/01',
name: 'Storage Unit Test',
description: ''
};
return this.getSert(data);
... | getRandomTestData | identifier_name |
storage-data-util.js | "use strict";
var _getSert = require("../getsert");
var generateCode = require("../../../src/utils/code-generator");
class StorageDataUtil {
getSert(input) {
var ManagerType = require("../../../src/managers/master/storage-manager");
return _getSert(input, ManagerType, (data) => {
return... | data.code = code;
data.name = `name[${code}]`;
data.description = `storage description [${code}]`;
return Promise.resolve(data);
}
getRandomTestData() {
return this.getNewData()
.then((data) => {
return this.getSert(data);
});
... | var Model = require('bateeq-models').master.Storage;
var data = new Model();
var code = generateCode();
| random_line_split |
__init__.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may n... | DataFrame-based machine learning APIs to let users quickly assemble and configure practical
machine learning pipelines.
"""
from pyspark.ml.base import Estimator, Model, Transformer
from pyspark.ml.pipeline import Pipeline, PipelineModel
__all__ = ["Transformer", "Estimator", "Model", "Pipeline", "PipelineModel"... |
"""
| random_line_split |
deriving-zero.rs | // Copyright 2012-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-MI... | (int);
#[deriving(Zero)]
struct C(int, int);
#[deriving(Zero)]
struct D { a: int }
#[deriving(Zero)]
struct E { a: int, b: int }
#[deriving(Zero)]
struct Lots {
d: u8,
e: char,
f: f64,
g: (f32, char),
h: @mut (int, int),
i: bool,
j: (),
}
pub fn main() {
let lots: Lots = Zero::zero();
... | B | identifier_name |
deriving-zero.rs | // Copyright 2012-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-MI... | {
let lots: Lots = Zero::zero();
assert!(lots.is_zero());
} | identifier_body | |
deriving-zero.rs | // Copyright 2012-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-MI... | struct B(int);
#[deriving(Zero)]
struct C(int, int);
#[deriving(Zero)]
struct D { a: int }
#[deriving(Zero)]
struct E { a: int, b: int }
#[deriving(Zero)]
struct Lots {
d: u8,
e: char,
f: f64,
g: (f32, char),
h: @mut (int, int),
i: bool,
j: (),
}
pub fn main() {
let lots: Lots = Zero::... |
#[deriving(Zero)]
struct A;
#[deriving(Zero)] | random_line_split |
schema-helper.js | import Mirage from 'ember-cli-mirage';
import Schema from 'ember-cli-mirage/orm/schema';
import Model from 'ember-cli-mirage/orm/model';
import Db from 'ember-cli-mirage/db';
export default {
setup() | baz: Mirage.belongsTo()
}),
baz: Model.extend({
quuxes: Mirage.hasMany()
}),
quux: Model.extend({
zomgs: Mirage.hasMany()
}),
zomg: Model.extend({
lol: Mirage.belongsTo()
}),
lol: Model,
roflCopter: Model
});
return this.sche... | {
let db = new Db();
this.schema = new Schema(db);
this.schema.registerModels({
wordSmith: Model.extend({
blogPosts: Mirage.hasMany()
}),
blogPost: Model.extend({
wordSmith: Mirage.belongsTo(),
fineComments: Mirage.hasMany()
}),
fineComment: Model.extend... | identifier_body |
schema-helper.js | import Mirage from 'ember-cli-mirage';
import Schema from 'ember-cli-mirage/orm/schema';
import Model from 'ember-cli-mirage/orm/model';
import Db from 'ember-cli-mirage/db';
export default {
| () {
let db = new Db();
this.schema = new Schema(db);
this.schema.registerModels({
wordSmith: Model.extend({
blogPosts: Mirage.hasMany()
}),
blogPost: Model.extend({
wordSmith: Mirage.belongsTo(),
fineComments: Mirage.hasMany()
}),
fineComment: Model.ext... | setup | identifier_name |
schema-helper.js | import Mirage from 'ember-cli-mirage';
import Schema from 'ember-cli-mirage/orm/schema';
import Model from 'ember-cli-mirage/orm/model';
import Db from 'ember-cli-mirage/db';
export default {
setup() {
let db = new Db();
this.schema = new Schema(db);
this.schema.registerModels({
wordSmith: Model.e... | }),
blogPost: Model.extend({
wordSmith: Mirage.belongsTo(),
fineComments: Mirage.hasMany()
}),
fineComment: Model.extend({
blogPost: Mirage.belongsTo()
}),
greatPhoto: Model,
foo: Model.extend({
bar: Mirage.belongsTo()
}),
bar: Model... | blogPosts: Mirage.hasMany() | random_line_split |
clustering.py | # -*- coding: utf-8 -*-
import re
import requests
import base64
import struct
import random
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from dateutil.parser import parse
class Tweet(object):
def __init__(self, status):
self.screen_name = status['screen_name']
self.tex... | (self, classification):
self.classification = classification
@property
def vector(self):
val = extract_brainstate(self.text)
if val == None:
return (1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
else:
return val
@property
def theta(self):
return abs(self... | classify | identifier_name |
clustering.py | # -*- coding: utf-8 -*-
import re
import requests
import base64
import struct
import random
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from dateutil.parser import parse
class Tweet(object):
def __init__(self, status):
self.screen_name = status['screen_name']
self.tex... |
else:
return u'<@{}: {} [{}]>'.format(self.screen_name, self.text[:20], self.classification)
def get_tweets(hashtag):
url = u'http://loklak.org:9000/api/search.json?q={}&minified=true'.format(hashtag)
resp = requests.get(url)
data = resp.json()['statuses']
tweets = []
for stat... | return u'<@{}: {} {} [{}]>'.format(self.screen_name, self.text[:20], self.vector,
self.classification) | conditional_block |
clustering.py | # -*- coding: utf-8 -*-
import re
import requests
import base64
import struct
import random
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from dateutil.parser import parse
class Tweet(object):
def __init__(self, status):
self.screen_name = status['screen_name']
self.tex... |
@property
def color(self):
overall_density = self.theta + self.alpha + self.beta
r = int(self.alpha / overall_density * 255)
g = int(self.beta / overall_density * 255)
b = int(self.theta / overall_density * 255)
return u'#%02x%02x%02x' % (r, g, b)
def __str__(self)... | return abs(self.vector[3]) | identifier_body |
clustering.py | # -*- coding: utf-8 -*-
import re
import requests
import base64
import struct
import random
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from dateutil.parser import parse
class Tweet(object):
def __init__(self, status):
self.screen_name = status['screen_name']
self.tex... | model = KMeans(n_clusters=2)
results = model.fit_predict(scaled_vectors)
for result, brain in zip(results, brains):
brain.classify(result)
return model, results
def find_latest(tweets):
latest = {}
for t in tweets:
if t.screen_name in latest.keys():
if latest[t.scree... | return cooked_brains
def cluster_brains(brains):
vectors = [t.vector for t in brains]
scaled_vectors = scale(vectors) | random_line_split |
ui.ts | import { Actions, Store } from '../../../../src/core';
import ui from '../../../../src/core/reducers/ui';
import suite from '../../_suite';
suite('ui', ({ expect }) => {
const global = true;
const ID = '5';
const state: Store.UI = {
breadcrumbs: {
global,
[ID]: 'yeah',
}
};
describe('upd... | const reducer = ui(state, <any>{});
expect(reducer).to.eql(state);
});
});
}); | random_line_split | |
bignum.rs | base[0] = v;
$name { size: 1, base: base }
}
/// Makes a bignum from `u64` value.
pub fn from_u64(mut v: u64) -> $name {
use mem;
let mut base = [0; $n];
let mut sz = 0;
while v > 0 {
... | retsz = i + sz; | random_line_split | |
home.panel.js | fleetManager.panel.Home = function (config) {
config = config || {};
Ext.apply(config, {
baseCls: 'modx-formpanel',
layout: 'anchor',
/*
stateful: true,
stateId: 'fleetmanager-panel-home',
stateEvents: ['tabchange'],
getState:function() {return {activeTab:this.items.indexOf(this.getActiveTab())};},
... | xtype: 'fleetmanager-grid-items',
cls: 'main-wrapper',
}]
}]
}]
});
fleetManager.panel.Home.superclass.constructor.call(this, config);
};
Ext.extend(fleetManager.panel.Home, MODx.Panel);
Ext.reg('fleetmanager-panel-home', fleetManager.panel.Home); | cls: 'panel-desc',
}, { | random_line_split |
shr.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::num::Wrapping;
use core::ops::Shr;
// macro_rules! sh_impl {
// ($t:ty, $f:ty) => (
// #[stable(feature = "rust1", since = "1.0.0")]
// impl Shl<$f> for Wrapping<$t> {
// type Output = ... |
}
| {
shr_test!( u8, 0x80, 8, 0x00 ); // panicked at 'shift operation overflowed'
} | identifier_body |
shr.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::num::Wrapping;
use core::ops::Shr;
// macro_rules! sh_impl {
// ($t:ty, $f:ty) => (
// #[stable(feature = "rust1", since = "1.0.0")]
// impl Shl<$f> for Wrapping<$t> {
// type Output = ... | () {
shr_test!( u8, 0x80, 8, 0x00 ); // panicked at 'shift operation overflowed'
}
}
| shr_test2 | identifier_name |
shr.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::num::Wrapping;
use core::ops::Shr;
// macro_rules! sh_impl {
// ($t:ty, $f:ty) => (
// #[stable(feature = "rust1", since = "1.0.0")]
// impl Shl<$f> for Wrapping<$t> {
// type Output = ... | shr_test!( u8, 0x80, 1, 0x40 );
shr_test!( u8, 0x80, 2, 0x20 );
shr_test!( u8, 0x80, 3, 0x10 );
shr_test!( u8, 0x80, 4, 0x08 );
shr_test!( u8, 0x80, 5, 0x04 );
shr_test!( u8, 0x80, 6, 0x02 );
shr_test!( u8, 0x80, 7, 0x01 );
}
#[test]
#[should_panic]
fn shr_test2() {
shr_test!( u8, 0x80, 8, 0x00... | #[test]
fn shr_test1() {
shr_test!( u8, 0x80, 0, 0x80 ); | random_line_split |
test2_unicode.py | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import unittest
from streamsx.topology.topology import *
from streamsx.topology.tester import Tester
from streamsx.topology import context
from streamsx.topology.context import ConfigParams
from streamsx import rest
import streamsx.ec as ... | ud.append("Arsenal hammered 5-1 by Bayern again")
s = topo.source(ud, name=u'façade')
sas = s.as_string()
sd = s.map(lambda s : {'val': s + u"_test_it!"})
tester = Tester(topo)
tester.contents(s, ud)
tester.contents(sas, ud)
dud = []
for v in ud:
... | ud = []
ud.append(u'⡍⠔⠙⠖ ⡊ ⠙⠕⠝⠰⠞ ⠍⠑⠁⠝ ⠞⠕ ⠎⠁⠹ ⠹⠁⠞ ⡊ ⠅⠝⠪⠂ ⠕⠋ ⠍⠹')
ud.append(u'2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm')
ud.append(u'многоязычных') | random_line_split |
test2_unicode.py | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import unittest
from streamsx.topology.topology import *
from streamsx.topology.tester import Tester
from streamsx.topology import context
from streamsx.topology.context import ConfigParams
from streamsx import rest
import streamsx.ec as ... | nfig)
def test_view_name(self):
"""
Test view names that are unicode.
"""
if self.test_ctxtype == context.ContextTypes.STANDALONE:
return self.skipTest("Skipping unicode view tests for standalone.")
view_names = [u"®®®®", u"™¬⊕⇔"]
topo = Topology()
... | .test(self.test_ctxtype, self.test_co | conditional_block |
test2_unicode.py | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import unittest
from streamsx.topology.topology import *
from streamsx.topology.tester import Tester
from streamsx.topology import context
from streamsx.topology.context import ConfigParams
from streamsx import rest
import streamsx.ec as ... | sd = s.map(lambda s : {'val': s + u"_test_it!"})
tester = Tester(topo)
tester.contents(s, ud)
tester.contents(sas, ud)
dud = []
for v in ud:
dud.append({'val': v + u"_test_it!"})
tester.contents(sd, dud)
tester.test(self.test_ctxtype, self.tes... | _multiprocess_can_split_ = True
def setUp(self):
Tester.setup_standalone(self)
def test_strings(self):
""" Test strings that are unicode.
Includes a stream name to verify it
does not cause an error, but under the covers
the actual name will be a mangled vers... | identifier_body |
test2_unicode.py | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import unittest
from streamsx.topology.topology import *
from streamsx.topology.tester import Tester
from streamsx.topology import context
from streamsx.topology.context import ConfigParams
from streamsx import rest
import streamsx.ec as ... | in job.get_views():
view_names.append(view.name)
self.assertIn(u"®®®®", view_names)
self.assertIn(u"™¬⊕⇔", view_names)
class TestDistributedUnicode(TestUnicode):
def setUp(self):
Tester.setup_distributed(self)
class TestSasUnicode(TestUnicode):
def setUp(self):
Test... | for view | identifier_name |
crime.client.routes.js | (function () {
'use strict';
angular
.module('crimes.routes')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider'];
function routeConfig($stateProvider) {
$stateProvider
.state('crimes', {
abstract: true,
url: '/crimes',
template: '<ui-view/>'
})
... | pageTitle: 'Crimes List'
}
})
.state('crimes.view', {
url: '/:crimeId',
templateUrl: '/modules/crimes/client/views/view-crimes.client.view.html',
controller: 'CrimesController',
controllerAs: 'vm',
resolve: {
crimeResolve: getCrime
... | templateUrl: '/modules/crimes/client/views/list-crimes.client.view.html',
controller: 'CrimesListController',
controllerAs: 'vm',
data: { | random_line_split |
crime.client.routes.js | (function () {
'use strict';
angular
.module('crimes.routes')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider'];
function routeConfig($stateProvider) | controllerAs: 'vm',
resolve: {
crimeResolve: getCrime
},
data: {
pageTitle: 'Crimes {{ crimeResolve.title }}'
}
});
}
getCrime.$inject = ['$stateParams', 'CrimesService'];
function getCrime($stateParams, CrimesService) {
return CrimesService... | {
$stateProvider
.state('crimes', {
abstract: true,
url: '/crimes',
template: '<ui-view/>'
})
.state('crimes.list', {
url: '',
templateUrl: '/modules/crimes/client/views/list-crimes.client.view.html',
controller: 'CrimesListController',
contr... | identifier_body |
crime.client.routes.js | (function () {
'use strict';
angular
.module('crimes.routes')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider'];
function routeConfig($stateProvider) {
$stateProvider
.state('crimes', {
abstract: true,
url: '/crimes',
template: '<ui-view/>'
})
... | ($stateParams, CrimesService) {
return CrimesService.get({
crimeId: $stateParams.crimeId
}).$promise;
}
}());
| getCrime | identifier_name |
bump-jetbrains-pkgs.py | #!/usr/bin/env python3
import os
import traceback
import glob
from multiprocessing import Pool, Process, Lock
import subprocess
import requests
import portage
from terminaltables import AsciiTable
DEBUG=0
if 'DEBUG' in os.environ:
DEBUG = os.environ['DEBUG']
PORTDIR_OVERLAY=os.path.realpath(os.path.dirname(os.... | is_dup = 0
for update in new_updates:
if update['loc_slot'] == latest_rem_slot:
is_dup = 1
break
if not is_dup:
new_updates.append({
'cat': cat,
'pn': pn,
'loc_slot': latest_loc_s... | latest_loc_slot = pdb.aux_get(latest_loc_pkg, ["SLOT"])[0]
latest_rem_slot = remote_versions[code]['latest_slot']
latest_rem_ver = remote_versions[code][latest_rem_slot]
if portage.vercmp(latest_loc_ver, latest_rem_ver) < 0:
# check for duplicates | random_line_split |
bump-jetbrains-pkgs.py | #!/usr/bin/env python3
import os
import traceback
import glob
from multiprocessing import Pool, Process, Lock
import subprocess
import requests
import portage
from terminaltables import AsciiTable
DEBUG=0
if 'DEBUG' in os.environ:
DEBUG = os.environ['DEBUG']
PORTDIR_OVERLAY=os.path.realpath(os.path.dirname(os.... |
def run_cmd(cmd):
pn = os.path.basename(os.getcwd())
print(f"> \033[94m{pn}\033[0m: `\033[93m{cmd}\033[0m`")
err = os.system(cmd)
if err:
print(f"{pn}: command '{cmd}' failed with code {err}")
return err
def update_pkg(cat, pn, loc_slot, loc_ver, rem_slot, rem_ver):
global GIT_LOCK,... | print(f"You pressed '{y}', bailing...")
exit(0) | conditional_block |
bump-jetbrains-pkgs.py | #!/usr/bin/env python3
import os
import traceback
import glob
from multiprocessing import Pool, Process, Lock
import subprocess
import requests
import portage
from terminaltables import AsciiTable
DEBUG=0
if 'DEBUG' in os.environ:
DEBUG = os.environ['DEBUG']
PORTDIR_OVERLAY=os.path.realpath(os.path.dirname(os.... |
def update_pkg(cat, pn, loc_slot, loc_ver, rem_slot, rem_ver):
global GIT_LOCK, PKG_LOCKS, PORTDIR_OVERLAY
cat_pn = f"{cat}/{pn}"
os.chdir(f"{PORTDIR_OVERLAY}/{cat_pn}")
PKG_LOCKS[cat_pn].acquire()
new_slot = False if loc_slot == rem_slot else True
if new_slot: # bump into a new slot
... | pn = os.path.basename(os.getcwd())
print(f"> \033[94m{pn}\033[0m: `\033[93m{cmd}\033[0m`")
err = os.system(cmd)
if err:
print(f"{pn}: command '{cmd}' failed with code {err}")
return err | identifier_body |
bump-jetbrains-pkgs.py | #!/usr/bin/env python3
import os
import traceback
import glob
from multiprocessing import Pool, Process, Lock
import subprocess
import requests
import portage
from terminaltables import AsciiTable
DEBUG=0
if 'DEBUG' in os.environ:
DEBUG = os.environ['DEBUG']
PORTDIR_OVERLAY=os.path.realpath(os.path.dirname(os.... | ( codes ):
payload = {
'code': ','.join(codes),
'latest': 'false',
'type': 'release'
}
r = requests.get('https://data.services.jetbrains.com/products/releases', params=payload)
json=r.json()
# [code][slot]
versions = {}
for c in codes:
versions[c] = {}
... | get_version | identifier_name |
struct-order-of-eval-4.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
const VAL: u32 = 0x89AB_CDEF;
let w = W { wrapped: VAL };
let s = S {
_f1: { event(0x01); 23 },
f0: { event(0x02); w },
};
assert_eq!(s.f0.wrapped, VAL);
let actual = event_log();
let expect = 0x01_02;
assert!(expect == actual,
"expect: 0x{:x} actual: 0x{... | main | identifier_name |
struct-order-of-eval-4.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
static LOG: AtomicUsize = AtomicUsize::new(0);
fn event_log() -> usize {
LOG.load(Ordering::SeqCst)
}
fn event(tag: u8) {
let old_log = LOG.load(Ordering::SeqCst);
let new_log = (old_log << 8) + tag as usize;
LOG.store(new_log, Ordering::SeqCst);
}
| {
const VAL: u32 = 0x89AB_CDEF;
let w = W { wrapped: VAL };
let s = S {
_f1: { event(0x01); 23 },
f0: { event(0x02); w },
};
assert_eq!(s.f0.wrapped, VAL);
let actual = event_log();
let expect = 0x01_02;
assert!(expect == actual,
"expect: 0x{:x} actual: 0x{:x}... | identifier_body |
struct-order-of-eval-4.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // even when no Drop-implementations are involved.
#![feature(const_fn)]
use std::sync::atomic::{Ordering, AtomicUsize};
struct W { wrapped: u32 }
struct S { f0: W, _f1: i32 }
pub fn main() {
const VAL: u32 = 0x89AB_CDEF;
let w = W { wrapped: VAL };
let s = S {
_f1: { event(0x01); 23 },
... | // except according to those terms.
// Checks that struct-literal expression order-of-eval is as expected | random_line_split |
upload.user.logo.service.js | (function () {
'use strict';
angular
.module('app')
.service('UploadUserLogoService', UploadUserLogoService);
function UploadUserLogoService($http, $log, TokenService, UserService, $rootScope) {
this.uploadImage = uploadImage;
////
/**
* Upload Image
... | a, callback) {
let userToken = TokenService.get();
let request = {
method: 'POST',
url: '/api/user/avatar',
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'Autoriza... | age(formdat | identifier_name |
upload.user.logo.service.js | (function () {
'use strict';
angular
.module('app')
.service('UploadUserLogoService', UploadUserLogoService);
function UploadUserLogoService($http, $log, TokenService, UserService, $rootScope) | let request = {
method: 'POST',
url: '/api/user/avatar',
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'Autorization': userToken
},
data: formda... | {
this.uploadImage = uploadImage;
////
/**
* Upload Image
* @description For correct uploading we must send FormData object
* With 'transformRequest: angular.identity' prevents Angular to do anything on our data (like serializing it).
* By setting ‘Content-... | identifier_body |
upload.user.logo.service.js | (function () {
'use strict';
angular
.module('app')
.service('UploadUserLogoService', UploadUserLogoService);
function UploadUserLogoService($http, $log, TokenService, UserService, $rootScope) {
this.uploadImage = uploadImage;
////
/**
* Upload Image
... | };
let goodResponse = function successCallback(response) {
let res = response.data;
if (res.success) {
let currentUser = UserService.get();
currentUser.avatarUrl = res.data.avatarUrl;
UserService.save(cu... | 'Content-Type': undefined,
'Autorization': userToken
},
data: formdata | random_line_split |
upload.user.logo.service.js | (function () {
'use strict';
angular
.module('app')
.service('UploadUserLogoService', UploadUserLogoService);
function UploadUserLogoService($http, $log, TokenService, UserService, $rootScope) {
this.uploadImage = uploadImage;
////
/**
* Upload Image
... | };
$http(request).then(goodResponse, badResponse);
}
}
})(); | callback(response);
}
| conditional_block |
hawkular.py | import re
from widgetastic_patternfly import Input, BootstrapSelect
from wrapanapi.hawkular import Hawkular
from cfme.common import TopologyMixin
from cfme.common.provider import DefaultEndpoint, DefaultEndpointForm
from cfme.utils.appliance import Navigatable
from cfme.utils.appliance.implementations.ui import navig... |
@variable(alias='db')
def num_messaging(self):
return self._num_db_generic('middleware_messagings')
@num_messaging.variant('ui')
def num_messaging_ui(self, reload_data=True):
self.load_details(refresh=reload_data)
return int(self.get_detail("Relationships", "Middleware Messagi... | self.load_details(refresh=reload_data)
return int(self.get_detail("Relationships", "Middleware Domains")) | identifier_body |
hawkular.py | import re
from widgetastic_patternfly import Input, BootstrapSelect
from wrapanapi.hawkular import Hawkular
from cfme.common import TopologyMixin
from cfme.common.provider import DefaultEndpoint, DefaultEndpointForm
from cfme.utils.appliance import Navigatable
from cfme.utils.appliance.implementations.ui import navig... | (prov_config, prov_key, appliance=None):
credentials_key = prov_config['credentials']
credentials = HawkularProvider.process_credential_yaml_key(credentials_key)
endpoints = {}
endpoints[HawkularEndpoint.name] = HawkularEndpoint(
**prov_config['endpoints'][HawkularEndpoint.na... | from_config | identifier_name |
hawkular.py | import re
from widgetastic_patternfly import Input, BootstrapSelect
from wrapanapi.hawkular import Hawkular
| from cfme.common.provider import DefaultEndpoint, DefaultEndpointForm
from cfme.utils.appliance import Navigatable
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.varmeth import variable
from . import MiddlewareProvider
from . import _get_providers_page, _db_select_query
from . import d... | from cfme.common import TopologyMixin | random_line_split |
hawkular.py | import re
from widgetastic_patternfly import Input, BootstrapSelect
from wrapanapi.hawkular import Hawkular
from cfme.common import TopologyMixin
from cfme.common.provider import DefaultEndpoint, DefaultEndpointForm
from cfme.utils.appliance import Navigatable
from cfme.utils.appliance.implementations.ui import navig... |
@is_refreshed.variant('db')
def is_refreshed_db(self):
ems = self.appliance.db.client['ext_management_systems']
dates = self.appliance.db.client.session.query(ems.created_on,
ems.updated_on).filter(ems.name == self.name).first()
return dates.updat... | return False | conditional_block |
conf.py | # -*- coding: utf-8 -*-
from __future__ import division
# -*- coding: utf-8 -*-
#
# Sphinx documentation build configuration file, created by
# sphinx-quickstart.py on Sat Mar 8 21:47:50 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, ... | (env, sig, signode):
if not sig.startswith('.'):
dec_sig = '.. %s::' % sig
signode += addnodes.desc_name(dec_sig, dec_sig)
return sig
m = dir_sig_re.match(sig)
if not m:
signode += addnodes.desc_name(sig, sig)
return sig
name, args = m.groups()
dec_name = '.. ... | parse_directive | identifier_name |
conf.py | # -*- coding: utf-8 -*-
from __future__ import division
# -*- coding: utf-8 -*-
#
# Sphinx documentation build configuration file, created by
# sphinx-quickstart.py on Sat Mar 8 21:47:50 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, ... |
m = dir_sig_re.match(sig)
if not m:
signode += addnodes.desc_name(sig, sig)
return sig
name, args = m.groups()
dec_name = '.. %s::' % name
signode += addnodes.desc_name(dec_name, dec_name)
signode += addnodes.desc_addname(args, args)
return name
def parse_role(env, sig, si... | dec_sig = '.. %s::' % sig
signode += addnodes.desc_name(dec_sig, dec_sig)
return sig | conditional_block |
conf.py | # -*- coding: utf-8 -*-
from __future__ import division
# -*- coding: utf-8 -*-
#
# Sphinx documentation build configuration file, created by
# sphinx-quickstart.py on Sat Mar 8 21:47:50 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, ... | from sphinx.ext.autodoc import cut_lines
app.connect('autodoc-process-docstring', cut_lines(4, what=['module']))
app.add_description_unit('directive', 'dir', 'pair: %s; directive', parse_directive)
app.add_description_unit('role', 'role', 'pair: %s; role', parse_role)
app.add_description_unit('confval',... | identifier_body | |
conf.py | # -*- coding: utf-8 -*-
from __future__ import division
# -*- coding: utf-8 -*-
#
# Sphinx documentation build configuration file, created by
# sphinx-quickstart.py on Sat Mar 8 21:47:50 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, ... | from sphinx.ext.autodoc import cut_lines
app.connect('autodoc-process-docstring', cut_lines(4, what=['module']))
app.add_description_unit('directive', 'dir', 'pair: %s; directive', parse_directive)
app.add_description_unit('role', 'role', 'pair: %s; role', parse_role)
app.add_description_unit('confv... |
def setup(app): | random_line_split |
ols_table.py | """Example: statsmodels.OLS
"""
from statsmodels.datasets.longley import load
import statsmodels.api as sm
from statsmodels.iolib.table import SimpleTable, default_txt_fmt
import numpy as np
data = load()
data_orig = (data.endog.copy(), data.exog.copy())
#.. Note: In this example using zscored/standardized variable... | txt_fmt1 = default_txt_fmt
numformat = '%10.4f'
txt_fmt1 = dict(data_fmts=[numformat])
rowstubs = data.names[1:] + ['const']
headers = ['all'] + ['drop %s' % name for name in data.names[1:]]
tabl = SimpleTable(resparams, headers, rowstubs, txt_fmt=txt_fmt1)
nanstring = numformat % np.nan
nn = len(nanstring)
nanrep = '... | if rescale == 1:
pass
if rescale == 3:
resparams[:-1, :] *= rescale_ratio[:, None]
| random_line_split |
ols_table.py | """Example: statsmodels.OLS
"""
from statsmodels.datasets.longley import load
import statsmodels.api as sm
from statsmodels.iolib.table import SimpleTable, default_txt_fmt
import numpy as np
data = load()
data_orig = (data.endog.copy(), data.exog.copy())
#.. Note: In this example using zscored/standardized variable... |
if rescale == 3:
resparams[:-1, :] *= rescale_ratio[:, None]
txt_fmt1 = default_txt_fmt
numformat = '%10.4f'
txt_fmt1 = dict(data_fmts=[numformat])
rowstubs = data.names[1:] + ['const']
headers = ['all'] + ['drop %s' % name for name in data.names[1:]]
tabl = SimpleTable(resparams, headers, rowstubs, txt_fmt=txt_f... | pass | conditional_block |
fbinter_wfs_buildings_alk.py | # -*- coding: utf-8 -*-
from qgis.core import NULL
from mole3.project import config
from mole3.oeq_global import OeQ_get_bld_id, isnull
from qgis.PyQt import QtGui, QtCore
def load(self=None):
self.load_wfs()
return True
def | (self=None):
from mole3.project import config
from qgis.PyQt.QtCore import QVariant
from qgis.core import QgsField
from mole3.qgisinteraction.layer_interaction import add_attributes_if_not_exists
from mole3.oeq_global import OeQ_get_bld_id
layer = self.layer()
#print layer.name()
if lay... | preflight | identifier_name |
fbinter_wfs_buildings_alk.py | # -*- coding: utf-8 -*-
from qgis.core import NULL
from mole3.project import config
from mole3.oeq_global import OeQ_get_bld_id, isnull
from qgis.PyQt import QtGui, QtCore
def load(self=None):
self.load_wfs()
return True
def preflight(self=None):
from mole3.project import config
from qgis.PyQt.QtCor... |
count += 1
layer.commitChanges()
# create building_ids
add_attributes_if_not_exists(layer, [QgsField(config.building_id_key,QVariant.String)])
layer.updateFields()
features = layer.getFeatures()
layer.startEditing()
for i in features:
i[config.building_id_key] = OeQ_ge... | layer.renameAttribute(count,cf[1])
break | conditional_block |
fbinter_wfs_buildings_alk.py | # -*- coding: utf-8 -*-
from qgis.core import NULL
from mole3.project import config
from mole3.oeq_global import OeQ_get_bld_id, isnull
from qgis.PyQt import QtGui, QtCore
def load(self=None):
self.load_wfs()
return True
def preflight(self=None):
from mole3.project import config
from qgis.PyQt.QtCor... | id = feature[config.building_id_key] #necessary to safe dependency check
flr = feature['FLRS_ALK'] # necessary to safe dependency check
usage = feature['FUNC_ALK'] # necessary to safe dependency check
kind = feature['KIND_ALK'] # necessary to safe dependency check
... | from qgis.PyQt.QtCore import QVariant
from qgis.core import QgsDistanceArea, QgsCoordinateReferenceSystem
ar = NULL
per = NULL
id = NULL
flr = NULL
usage = NULL
kind = NULL
gkn = NULL
da_engine=QgsDistanceArea()
#print (QgsCoordinateReferenceSystem(int(config.project_crs.split(':... | identifier_body |
fbinter_wfs_buildings_alk.py | # -*- coding: utf-8 -*-
from qgis.core import NULL
from mole3.project import config
from mole3.oeq_global import OeQ_get_bld_id, isnull
from qgis.PyQt import QtGui, QtCore
def load(self=None):
self.load_wfs()
return True
def preflight(self=None):
from mole3.project import config
from qgis.PyQt.QtCor... |
def evaluation(self=None, parameters={},feature=None):
from qgis.PyQt.QtCore import QVariant
from qgis.core import QgsDistanceArea, QgsCoordinateReferenceSystem
ar = NULL
per = NULL
id = NULL
flr = NULL
usage = NULL
kind = NULL
gkn = NULL
da_engine=QgsDistanceArea()
#print (... | layer.updateFeature(i)
layer.commitChanges()
return True | random_line_split |
jimp.ts | import * as jimp from "jimp"
type ResizeProps = {
width: number
mime: "image/jpeg" | "image/png" | "image/webp" | "image/avif"
options: {
background?: string
rotate: number
quality: number
progressive?: boolean
}
}
class JimpAdapter {
readImage: Promise<jimp>
constructor(imagePath: string)... | (): Promise<{ height: number; width: number }> {
return this.readImage.then((image) => ({
width: image.bitmap.width,
height: image.bitmap.height,
}))
}
resize({
width,
mime,
options,
}: ResizeProps): Promise<{
width: number
height: number
data: Buffer
}> {
return ... | metadata | identifier_name |
jimp.ts | import * as jimp from "jimp"
type ResizeProps = {
width: number
mime: "image/jpeg" | "image/png" | "image/webp" | "image/avif"
options: {
background?: string
rotate: number
quality: number
progressive?: boolean
}
}
class JimpAdapter {
readImage: Promise<jimp>
constructor(imagePath: string)... | else {
resolve({
data,
width,
height: this.bitmap.height,
})
}
})
})
})
}
}
module.exports = (imagePath: string): JimpAdapter => {
return new JimpAdapter(imagePath)
}
| {
reject(err)
} | conditional_block |
jimp.ts | import * as jimp from "jimp"
type ResizeProps = { | quality: number
progressive?: boolean
}
}
class JimpAdapter {
readImage: Promise<jimp>
constructor(imagePath: string) {
this.readImage = jimp.read(imagePath)
}
metadata(): Promise<{ height: number; width: number }> {
return this.readImage.then((image) => ({
width: image.bitmap.width,
... | width: number
mime: "image/jpeg" | "image/png" | "image/webp" | "image/avif"
options: {
background?: string
rotate: number | random_line_split |
test_hashes.py | import json
import argparse
import logging
import glob
# Logging Information
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(levelname)s: %(message)s')
fh = logging.FileHandler('test_hashes.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHand... | logger.debug("Removing hashes from " + filename)
with open(filename,'r') as file:
for line in file.readlines():
hashes.remove(json.loads(line.strip())["md5"])
if len(hashes) == 0:
logger.info("VirusShare_00" + str(hash_num).zfill(3) + ".ldjson is consistent with hashfile")
else:
log... | hashes.add(line.strip())
for filename in glob.glob("../analyses/VirusShare_00" + str(hash_num).zfill(3) + ".*"): | random_line_split |
test_hashes.py | import json
import argparse
import logging
import glob
# Logging Information
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(levelname)s: %(message)s')
fh = logging.FileHandler('test_hashes.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHand... |
if len(hashes) == 0:
logger.info("VirusShare_00" + str(hash_num).zfill(3) + ".ldjson is consistent with hashfile")
else:
logger.error("VirusShare_00" + str(hash_num).zfill(3) + ".ldjson is inconsistent with hashfile")
| hashes.remove(json.loads(line.strip())["md5"]) | conditional_block |
download_cms_data.py | from io import BytesIO
from hashlib import sha1
from os.path import isdir, join, abspath, dirname
from zipfile import ZipFile, ZIP_DEFLATED
from urllib.request import urlopen
import hydrus.constants as c
class WrongSha1Error(Exception): |
URL = (
# "https://www.qualitynet.org/dcs/BlobServer",
"http://www.qualitynet.org/dcs/BlobServer"
"?blobkey=id"
"&blobnocache=true"
"&blobwhere="
"{blob}"
"&blobheader=multipart%2Foctet-stream"
"&blobheadername1=Content-Disposition"
"&blobheadervalue1=attachment%3Bfilename%3D"
... | pass | identifier_body |
download_cms_data.py | from io import BytesIO
from hashlib import sha1
from os.path import isdir, join, abspath, dirname
from zipfile import ZipFile, ZIP_DEFLATED
from urllib.request import urlopen
import hydrus.constants as c
class | (Exception): pass
URL = (
# "https://www.qualitynet.org/dcs/BlobServer",
"http://www.qualitynet.org/dcs/BlobServer"
"?blobkey=id"
"&blobnocache=true"
"&blobwhere="
"{blob}"
"&blobheader=multipart%2Foctet-stream"
"&blobheadername1=Content-Disposition"
"&blobheadervalue1=attachment%3... | WrongSha1Error | identifier_name |
download_cms_data.py | from io import BytesIO
from hashlib import sha1
from os.path import isdir, join, abspath, dirname
from zipfile import ZipFile, ZIP_DEFLATED
from urllib.request import urlopen
import hydrus.constants as c
class WrongSha1Error(Exception): pass
URL = (
# "https://www.qualitynet.org/dcs/BlobServer",
"http://ww... | download_cms_data(
1228890641889,
'SAS_All_Data_Dec2016_suppressd.zip',
'8b9a23afd3e9b88427aa9932557d17cd0b4be640',
)
download_cms_data(
1228890620679,
'SAS_Data-Input_Oct2016.zip',
'62ab0e94811842f3212196e203cd95374fbb10d4',
) | conditional_block | |
download_cms_data.py | from io import BytesIO
from hashlib import sha1
from os.path import isdir, join, abspath, dirname
from zipfile import ZipFile, ZIP_DEFLATED
from urllib.request import urlopen
import hydrus.constants as c
class WrongSha1Error(Exception): pass
URL = (
# "https://www.qualitynet.org/dcs/BlobServer",
"http://ww... | hash = sha1(bio.read()).hexdigest()
if hash == exp_hash:
print('Extracting to', abspath(DEST))
with ZipFile(bio, compression=ZIP_DEFLATED) as z:
z.extractall(path=DEST)
else:
raise WrongSh... | bio.seek(0) | random_line_split |
specimen-files.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SpecimenFilesComponent } from './specimen-files.component';
import {NgxPaginationModule} from 'ngx-pagination';
import {RobustLinkComponent} from '../../shared/robust-link/robust-link.component';
import {HttpClientTestingModule} from '@... | component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
}); | }));
beforeEach(() => {
fixture = TestBed.createComponent(SpecimenFilesComponent); | random_line_split |
error.ts | import * as util from './util';
interface IErrorMessage {
[index: number]: string;
}
export enum ErrorCode {
E32 = 32,
E37 = 37,
E208 = 208,
E348 = 348,
E444 = 444,
E488 = 488,
}
export const ErrorMessage: IErrorMessage = {
32: 'No file name',
37: 'No write since last change (add ! to override)',
... | util.showError(this.toString());
}
toString(): string {
return 'E' + this.code.toString() + ': ' + this.message;
}
} |
display(): void { | random_line_split |
error.ts | import * as util from './util';
interface IErrorMessage {
[index: number]: string;
}
export enum ErrorCode {
E32 = 32,
E37 = 37,
E208 = 208,
E348 = 348,
E444 = 444,
E488 = 488,
}
export const ErrorMessage: IErrorMessage = {
32: 'No file name',
37: 'No write since last change (add ! to override)',
... | (): string {
return 'E' + this.code.toString() + ': ' + this.message;
}
}
| toString | identifier_name |
error.ts | import * as util from './util';
interface IErrorMessage {
[index: number]: string;
}
export enum ErrorCode {
E32 = 32,
E37 = 37,
E208 = 208,
E348 = 348,
E444 = 444,
E488 = 488,
}
export const ErrorMessage: IErrorMessage = {
32: 'No file name',
37: 'No write since last change (add ! to override)',
... |
throw new Error('unknown error code: ' + code);
}
get code(): number {
return this._code;
}
get message(): string {
return this._message;
}
display(): void {
util.showError(this.toString());
}
toString(): string {
return 'E' + this.code.toString() + ': ' + this.message;
}
}
| {
return new VimError(code, ErrorMessage[code]);
} | conditional_block |
bad_migration_1.rs | use std::fmt::{self, Display};
use postgres::{self, GenericConnection};
use trek::migration::Migration;
// this migration is expected to fail when run
#[derive(Debug)]
pub struct BadMigration1 {
name: String
}
impl BadMigration1 {
pub fn new() -> Self {
BadMigration1 {
name: "BadMigration1"... | (&self, transaction: &GenericConnection) -> postgres::Result<()> {
try!(transaction.execute("rargle blargle", &[]));
Ok(())
}
}
impl Display for BadMigration1 {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{}", self.name)
}
}
| down | identifier_name |
bad_migration_1.rs | use std::fmt::{self, Display};
use postgres::{self, GenericConnection};
use trek::migration::Migration;
// this migration is expected to fail when run
#[derive(Debug)]
pub struct BadMigration1 {
name: String
}
impl BadMigration1 {
pub fn new() -> Self {
BadMigration1 {
name: "BadMigration1"... |
}
impl Display for BadMigration1 {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{}", self.name)
}
}
| {
try!(transaction.execute("rargle blargle", &[]));
Ok(())
} | identifier_body |
bad_migration_1.rs | use std::fmt::{self, Display};
use postgres::{self, GenericConnection}; | name: String
}
impl BadMigration1 {
pub fn new() -> Self {
BadMigration1 {
name: "BadMigration1".to_owned(),
}
}
}
impl Migration for BadMigration1 {
fn up(&self, transaction: &GenericConnection) -> postgres::Result<()> {
try!(transaction.execute("rargle blargle", &[]... | use trek::migration::Migration;
// this migration is expected to fail when run
#[derive(Debug)]
pub struct BadMigration1 { | random_line_split |
MapLayersPicker.js | import React, { PropTypes } from 'react';
export default class MapLayersPicker extends React.Component {
static propTypes = {
title: PropTypes.string,
layers: PropTypes.array.isRequired,
onLayerChange: PropTypes.func
};
static defaultProps = {
title: 'Map Layers'
};
constructor (props) |
render () {
return (
<div className='map-layers-picker'>
<div className='map-layers-picker-section'>
<div className='map-layers-picker-header'>{ this.props.title }</div>
{ this.props.layers.map(layer => this.renderCheckbox(layer)) }
</div>
</div>
);
}
handleChange (key, checked) {
co... | {
super(props);
} | identifier_body |
MapLayersPicker.js | import React, { PropTypes } from 'react';
export default class | extends React.Component {
static propTypes = {
title: PropTypes.string,
layers: PropTypes.array.isRequired,
onLayerChange: PropTypes.func
};
static defaultProps = {
title: 'Map Layers'
};
constructor (props) {
super(props);
}
render () {
return (
<div className='map-layers-picker'>
<div c... | MapLayersPicker | identifier_name |
MapLayersPicker.js | import React, { PropTypes } from 'react';
export default class MapLayersPicker extends React.Component {
static propTypes = {
title: PropTypes.string,
layers: PropTypes.array.isRequired,
onLayerChange: PropTypes.func
};
static defaultProps = {
title: 'Map Layers'
};
constructor (props) {
super(props)... | </div>
);
}
} | checked={ checked }
/>
<label htmlFor={ key } className={ iconType } dangerouslySetInnerHTML={{ __html: decodeURIComponent(name) }}></label>
{ this.props.children } | random_line_split |
MapLayersPicker.js | import React, { PropTypes } from 'react';
export default class MapLayersPicker extends React.Component {
static propTypes = {
title: PropTypes.string,
layers: PropTypes.array.isRequired,
onLayerChange: PropTypes.func
};
static defaultProps = {
title: 'Map Layers'
};
constructor (props) {
super(props)... |
}
renderCheckbox (config) {
let {
key,
name,
icon,
iconSize,
iconType,
checked
} = config;
iconType = iconType || '';
return (
<div className='map-layers-picker-checkbox' key={ key }>
{ icon ?
<svg
width={ iconSize[0] }
height={ iconSize[1] }
className={ `${ ... | {
this.props.onLayerChange(key, checked);
} | conditional_block |
hdf.py | """Functions for accessing HDF5 files."""
from __future__ import division
from __future__ import print_function
import re
import h5py as h5
import numpy as np
import six
from six.moves import range
from ..utils import filter_regex, to_list
def _ls(item, recursive=False, groups=False, level=0):
keys = []
i... |
else:
break
def _to_dict(data):
if isinstance(data, np.ndarray):
data = [data]
return dict(zip(range(len(data)), data))
def read_from(reader, nb_sample=None):
from .utils import stack_dict
data = dict()
nb_seen = 0
is_dict = True
for data_batch in r... | file_idx = 0
nb_seen = 0 | conditional_block |
hdf.py | """Functions for accessing HDF5 files."""
from __future__ import division
from __future__ import print_function
import re
import h5py as h5
import numpy as np
import six
from six.moves import range
from ..utils import filter_regex, to_list
def _ls(item, recursive=False, groups=False, level=0):
keys = []
i... |
def hnames_to_names(hnames):
"""Flattens `dict` `hnames` of hierarchical names.
Converts hierarchical `dict`, e.g. hnames={'a': ['a1', 'a2'], 'b'}, to flat
list of keys for accessing HDF5 file, e.g. ['a/a1', 'a/a2', 'b']
"""
names = []
for key, value in six.iteritems(hnames):
if isin... | """Write data in dict `data` to HDF5 file."""
is_root = isinstance(filename, str)
group = h5.File(filename, 'w') if is_root else filename
for key, value in six.iteritems(data):
if isinstance(value, dict):
key_group = group.create_group(key)
write_data(value, key_group)
... | identifier_body |
hdf.py | """Functions for accessing HDF5 files."""
from __future__ import division
from __future__ import print_function
import re
import h5py as h5
import numpy as np
import six
from six.moves import range
from ..utils import filter_regex, to_list
def _ls(item, recursive=False, groups=False, level=0):
keys = []
i... | if name not in h5_file:
raise ValueError('%s does not exist!' % name)
h5_file.close()
if nb_sample:
# Select the first k files s.t. the total sample size is at least
# nb_sample. Only these files will be shuffled.
_data_files = []
nb_seen = 0
for data... |
# Check if names exist
h5_file = h5.File(data_files[0], 'r')
for name in names: | random_line_split |
hdf.py | """Functions for accessing HDF5 files."""
from __future__ import division
from __future__ import print_function
import re
import h5py as h5
import numpy as np
import six
from six.moves import range
from ..utils import filter_regex, to_list
def _ls(item, recursive=False, groups=False, level=0):
keys = []
i... | (hnames):
"""Flattens `dict` `hnames` of hierarchical names.
Converts hierarchical `dict`, e.g. hnames={'a': ['a1', 'a2'], 'b'}, to flat
list of keys for accessing HDF5 file, e.g. ['a/a1', 'a/a2', 'b']
"""
names = []
for key, value in six.iteritems(hnames):
if isinstance(value, dict):
... | hnames_to_names | identifier_name |
db.rs | redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the i... |
/// Writes and removes the values into the database and updates the cache.
fn extend_with_option_cache<K, T, R>(&mut self, col: Option<u32>, cache: &mut Cache<K, Option<T>>, values: HashMap<K, Option<T>>, policy: CacheUpdatePolicy) where
K: Key<T, Target = R> + Hash + Eq,
T: rlp::Encodable,
R: Deref<Target = [u8... | {
match policy {
CacheUpdatePolicy::Overwrite => {
for (key, value) in values.into_iter() {
self.write(col, &key, &value);
cache.insert(key, value);
}
},
CacheUpdatePolicy::Remove => {
for (key, value) in &values {
self.write(col, key, value);
cache.remove(key);
}
},
... | identifier_body |
db.rs | // Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along w... | // 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 later version.
| random_line_split | |
db.rs | redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the i... | <T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>, value: &T) where T: rlp::Encodable, R: Deref<Target = [u8]> {
self.put(col, &key.key(), &rlp::encode(value));
}
fn delete<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>) where T: rlp::Encodable, R: Deref<Target = [u8]> {
self.delete(col, ... | write | identifier_name |
nailgun_client.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import errno
import ... |
elif chunk_type == ChunkType.STDERR:
self._write_flush(self._stderr, payload)
elif chunk_type == ChunkType.EXIT:
self._write_flush(self._stdout)
self._write_flush(self._stderr)
return int(payload)
elif chunk_type == ChunkType.PID:
self.remote_pi... | self._write_flush(self._stdout, payload) | conditional_block |
nailgun_client.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import errno
import ... | (self):
"""Creates a socket, connects it to the nailgun and returns the connected socket.
:returns: a connected `socket.socket`.
:raises: `NailgunClient.NailgunConnectionError` on failure to connect.
"""
sock = RecvBufferedSocket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
try:
soc... | try_connect | identifier_name |
nailgun_client.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import errno
import ... | self._maybe_stop_input_writer()
def execute(self, working_dir, main_class, *arguments, **environment):
# Send the nailgun request.
self.send_request(self._sock, working_dir, main_class, *arguments, **environment)
# Process the remainder of the nailgun session.
return self._process_session()
... | """Process the outputs of the nailgun session."""
try:
for chunk_type, payload in self.iter_chunks(self._sock, return_bytes=True):
if chunk_type == ChunkType.STDOUT:
self._write_flush(self._stdout, payload)
elif chunk_type == ChunkType.STDERR:
self._write_flush(self._stderr... | identifier_body |
nailgun_client.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import errno
import ... | :param string host: the nailgun server to contact (defaults to '127.0.0.1')
:param int port: the port the nailgun server is listening on (defaults to the default nailgun
port: 2113)
:param file ins: a file to read command standard input from (defaults to stdin) - can be None
... | """Creates a nailgun client that can be used to issue zero or more nailgun commands.
| random_line_split |
setup.py | #
# This file is part of shogen.
#
# shogen is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# shogen is distributed in the ho... | # Copyright (c) 2014, Sven Thiele <sthiele78@gmail.com>
| random_line_split | |
binary_sensor.py | """Support for MyQ gateways."""
from pymyq.const import (
DEVICE_STATE as MYQ_DEVICE_STATE,
DEVICE_STATE_ONLINE as MYQ_DEVICE_STATE_ONLINE,
KNOWN_MODELS,
MANUFACTURER,
)
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
BinarySensorEntity,
)
from homeassistant.help... | (self):
"""Return a unique, Home Assistant friendly identifier for this entity."""
return self._device.device_id
@property
def device_info(self):
"""Return the device_info of the device."""
device_info = {
"identifiers": {(DOMAIN, self._device.device_id)},
... | unique_id | identifier_name |
binary_sensor.py | """Support for MyQ gateways."""
from pymyq.const import (
DEVICE_STATE as MYQ_DEVICE_STATE,
DEVICE_STATE_ONLINE as MYQ_DEVICE_STATE_ONLINE,
KNOWN_MODELS,
MANUFACTURER,
)
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
BinarySensorEntity,
)
from homeassistant.help... |
# Not all devices report online so assume True if its missing
return self._device.device_json[MYQ_DEVICE_STATE].get(
MYQ_DEVICE_STATE_ONLINE, True
)
@property
def available(self) -> bool:
"""Entity is always available."""
return True
@property
def ... | return False | conditional_block |
binary_sensor.py | """Support for MyQ gateways."""
from pymyq.const import (
DEVICE_STATE as MYQ_DEVICE_STATE,
DEVICE_STATE_ONLINE as MYQ_DEVICE_STATE_ONLINE,
KNOWN_MODELS,
MANUFACTURER,
)
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
BinarySensorEntity,
)
from homeassistant.help... | if model:
device_info["model"] = model
return device_info | random_line_split | |
binary_sensor.py | """Support for MyQ gateways."""
from pymyq.const import (
DEVICE_STATE as MYQ_DEVICE_STATE,
DEVICE_STATE_ONLINE as MYQ_DEVICE_STATE_ONLINE,
KNOWN_MODELS,
MANUFACTURER,
)
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
BinarySensorEntity,
)
from homeassistant.help... | # Not all devices report online so assume True if its missing
return self._device.device_json[MYQ_DEVICE_STATE].get(
MYQ_DEVICE_STATE_ONLINE, True
)
@property
def available(self) -> bool:
"""Entity is always available."""
return True
@property
def un... | """Representation of a MyQ gateway."""
_attr_device_class = DEVICE_CLASS_CONNECTIVITY
def __init__(self, coordinator, device):
"""Initialize with API object, device id."""
super().__init__(coordinator)
self._device = device
@property
def name(self):
"""Return the name ... | identifier_body |
labelsTable.tsx | import * as React from "react";
import { Link } from 'react-router-dom'
import { useQuery } from 'react-query';
import { firstBy } from 'thenby';
import { fetchRules } from '../../../utils/evidence/ruleAPIs';
import { DataTable, Spinner } from '../../../../Shared/index';
import { getCheckIcon } from '../../../helpers/... |
const formattedRows = rulesData.rules.map(rule => {
const { name, id, state, optimal, label } = rule;
const ruleLink = (
<Link className="data-link" to={{ pathname: `/activities/${activityId}/semantic-labels/${prompt.id}/${id}`, state: { rule: rule, conjunction: prompt.conjunction } }}>View</Li... | {
return [];
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.