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 |
|---|---|---|---|---|
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | {
let t = format!("{} {}", Colour::Red.bold().paint("test"), Colour::White.normal().paint("again"));
let after = kill_color(&t);
assert_eq!(after, "test again");
} | identifier_body | |
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | lazy_static! {
static ref RE: Regex = Regex::new("\x1b\\[[^m]+m").unwrap();
}
RE.replace_all(s, "")
}
#[test]
fn should_remove_colour() {
let before = "test";
let after = kill_color(&Colour::Red.bold().paint(before));
assert_eq!(after, "test");
}
#[test]
fn should_remove_multiple_colour() {
let t = format!("... | }
fn kill_color(s: &str) -> String { | random_line_split |
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
ret
};
builder.format(format);
builder.init().expect("Logger initialized only once.");
Ok(logs)
}
fn kill_color(s: &str) -> String {
lazy_static! {
static ref RE: Regex = Regex::new("\x1b\\[[^m]+m").unwrap();
}
RE.replace_all(s, "")
}
#[test]
fn should_remove_colour() {
let before = "test";
let af... | {
// duplicate INFO/WARN output to console
println!("{}", ret);
} | conditional_block |
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (config: &Config) -> Result<Arc<RotatingLogger>, String> {
use rlog::*;
let mut levels = String::new();
let mut builder = LogBuilder::new();
// Disable ws info logging by default.
builder.filter(Some("ws"), LogLevelFilter::Warn);
// Disable rustls info logging by default.
builder.filter(Some("rustls"), LogLevel... | setup_log | identifier_name |
key_generator.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | () {
let args = Arguments::from_args();
let result = generate_json(&args.passphrase, &args.seed).unwrap();
println!(
"{}",
serde_json::to_string_pretty(&result).expect("Couldn't convert json object to string")
);
}
fn generate_json(passphrase: &str, seed: &str) -> anyhow::Result<serde_... | main | identifier_name |
key_generator.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | );
assert_eq!(
json["consensus_pub_key"].as_str().unwrap(),
r_keys.consensus.public_key().to_hex()
);
} | json["service_pub_key"].as_str().unwrap(),
r_keys.service.public_key().to_hex() | random_line_split |
Ontology.py | 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 option) any later version.
This program is distributed in the hope that it will be use... | (self, source_database, name, linkedAttribute, descriptionAttribute, id=None, levelAttribute=None ):
"""
"source_database" is the source database id where this entity is described
"name" is the name for the ontology. It must be UNIQUE! There cannot be different ontologies with the same name
... | __init__ | identifier_name |
Ontology.py | 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 option) any later version.
This program is distributed in the hope that it will be use... |
def linkedAttrID2ID(self, attr_id):
return self._attrID2id[attr_id]
def get_descendants(self, ontologyElementID):
"""
Gets all the descendants, using the "is_a" relation
"""
if self.precalculated_descendants.has_key(ontologyElementID):
return... | return self.all_ids | identifier_body |
Ontology.py | 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 option) any later version.
This program is distributed in the hope that it will be use... |
def __init__(self, source_database, name, linkedAttribute, descriptionAttribute, id=None, levelAttribute=None ):
"""
"source_database" is the source database id where this entity is described
"name" is the name for the ontology. It must be UNIQUE! There cannot be different ontologies w... |
Each ontology as a "linkedAttribute", which is the primary attribute to represent the ontology (for example, taxID for taxonomy), and a "descriptionAttribute", which is an attribute that describes the external entity element
""" | random_line_split |
Ontology.py | 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 option) any later version.
This program is distributed in the hope that it will be use... |
else:
if current_descendant_id not in result:
result.add(current_descendant_id)
result.update(self.get_descendants(current_descendant_id))
# result.update(self.get_descendants(current_descendant_id))
else:
... | sys.stderr.write("Ontology has a loop. An element %s [%s] is a child of itself?\n" %(current_descendant_id,self.linked_attribute_values[current_descendant_id]))
return result | conditional_block |
tcp_client.rs | (rx: mpsc::Receiver<Packet>, tx: mpsc::Sender<Packet>, handle: &Handle) -> IoFuture<()> {
// Use `gen_keypair` to generate random keys
// Client constant keypair for examples/tests
let client_pk = PublicKey([252, 72, 40, 127, 213, 13, 0, 95,
13, 230, 176, 49, 69, 252, 220, 132,... | env_logger::init().unwrap();
let (tx, rx) = mpsc::channel(1);
let mut core = Core::new().unwrap();
let handle = core.handle();
let client = create_client(rx, tx.clone(), &handle);
// variant 1. send packets in the same thread, combine with select(...)
let packet_sender = future::loop_fn(t... | identifier_body | |
tcp_client.rs | 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 with Tox. If not, see <http://www.gnu.org/licenses/>.
*/
extern crate tox;
extern crate futures;
exte... | 2 => {
// remote tcp relay server
let server_pk_bytes = FromHex::from_hex("461FA3776EF0FA655F1A05477DF1B3B614F7D6B124F7DB1DD4FE3C08B03B640F").unwrap();
let server_pk = PublicKey::from_slice(&server_pk_bytes).unwrap();
let addr = "130.133.110.14:33445".parse().unwr... | // local tcp relay server from example
let addr = "0.0.0.0:12345".parse().unwrap();
// Server constant PK for examples/tests
let server_pk = PublicKey([177, 185, 54, 250, 10, 168, 174,
148, 0, 93, 99, 13, 131, 131, 239,
... | conditional_block |
tcp_client.rs | 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 with Tox. If not, see <http://www.gnu.org/licenses/>.
*/
extern crate tox;
extern crate futures;
exte... | {
| in() | identifier_name |
tcp_client.rs | is a IO error
// Since we pass a copy of tx as arg (to send PongResponses), the client will live untill IO error
// Comment out pong responser and client will be destroyed when there will be no messages to send
fn create_client(rx: mpsc::Receiver<Packet>, tx: mpsc::Sender<Packet>, handle: &Handle) -> IoFuture<()> {
... | 192, 117, 0, 225, 119, 43, 48, 117,
84, 109, 112, 57, 243, 216, 4, 171,
185, 111, 33, 146, 221, 31, 77, 118]); | random_line_split | |
data_preparation_trip_advisor.py | # Ravi Makhija
# data_preparation_trip_advisor.py
# Version 4.2
#
# Description:
# This script takes as input the json files generated
# from scraping TRIP ADVISOR, and initiates the following
# data preparation sequence:
# 1) Converts json to csv, making each row of the
# csv a unique review with restaurant in... |
elif user_proceed_response.lower() == 'q':
print 'Aborting data preparation sequence.'
break
elif user_proceed_response.lower() == 'dc' or user_proceed_response.lower() == 'nashville':
if user_proceed_response.lower() == 'dc':
my_restaurant_location = 'Washington, DC'
... | current_user_prompt = '\nPlease enter one of "DC", "Nashville", or "q": ' | conditional_block |
data_preparation_trip_advisor.py | # Ravi Makhija
# data_preparation_trip_advisor.py
# Version 4.2
#
# Description:
# This script takes as input the json files generated
# from scraping TRIP ADVISOR, and initiates the following
# data preparation sequence:
# 1) Converts json to csv, making each row of the
# csv a unique review with restaurant in... | # data_preparation_lib/update_geocode_lookup_table.py
# data_preparation_lib/clean_and_feature_generation_trip_advisor.py
# data_preparation_lib/change_extension_to_csv
#
# References:
# Problem: Importing functions from other files for use in this script.
# http://stackoverflow.com/questions/4383571/impo... | #
# Script Dependencies:
# data_preparation_lib/json_to_csv_trip_advisor.py | random_line_split |
errors.rs | //! Representations of various client errors
use hyper::{self, http, StatusCode};
use serde_json::Error as SerdeError;
use std::{error::Error as StdError, fmt, string::FromUtf8Error};
use futures_util::io::Error as IoError;
/// Represents the result of all docker operations
pub type Result<T> = std::result::Result<T... |
}
impl From<FromUtf8Error> for Error {
fn from(error: FromUtf8Error) -> Error {
Error::Encoding(error)
}
}
impl fmt::Display for Error {
fn fmt(
&self,
f: &mut fmt::Formatter,
) -> fmt::Result {
write!(f, "Docker Error: ")?;
match self {
Error::Serd... | {
Error::IO(error)
} | identifier_body |
errors.rs | //! Representations of various client errors
use hyper::{self, http, StatusCode};
use serde_json::Error as SerdeError;
use std::{error::Error as StdError, fmt, string::FromUtf8Error};
use futures_util::io::Error as IoError;
/// Represents the result of all docker operations
pub type Result<T> = std::result::Result<T... | (error: http::uri::InvalidUri) -> Self {
let http_error: http::Error = error.into();
http_error.into()
}
}
impl From<IoError> for Error {
fn from(error: IoError) -> Error {
Error::IO(error)
}
}
impl From<FromUtf8Error> for Error {
fn from(error: FromUtf8Error) -> Error {
... | from | identifier_name |
errors.rs |
use hyper::{self, http, StatusCode};
use serde_json::Error as SerdeError;
use std::{error::Error as StdError, fmt, string::FromUtf8Error};
use futures_util::io::Error as IoError;
/// Represents the result of all docker operations
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
... | //! Representations of various client errors | random_line_split | |
errors.rs | //! Representations of various client errors
use hyper::{self, http, StatusCode};
use serde_json::Error as SerdeError;
use std::{error::Error as StdError, fmt, string::FromUtf8Error};
use futures_util::io::Error as IoError;
/// Represents the result of all docker operations
pub type Result<T> = std::result::Result<T... |
Error::Fault { code, message } => write!(f, "{}: {}", code, message),
Error::ConnectionNotUpgraded => write!(
f,
"expected the docker host to upgrade the HTTP connection but it did not"
),
}
}
}
impl StdError for Error {
fn source(&se... | {
write!(f, "Response doesn't have the expected format: {}", cause)
} | conditional_block |
down_pic_thread.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-09-01 22:26:01
# @Author : Your Name (you@example.org)
# @Link : http://example.org
# @Version : $Id$
import os
import threading
import requests
import lxml
from threading import Thread
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdef... | equests.get(url, stream=True)
soup = BeautifulSoup(r.text, 'lxml')
myimg = [img.get('src') for img in soup.find(id='brand-waterfall').find_all('img')] # 查询id下所有img元素
print 'myimg:', myimg
for img in myimg:
pic_name = pic_path + str(t) + '.jpg'
# img_src = img.get('src')
print 'img: ', img
# self.download_p... | identifier_body | |
down_pic_thread.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-09-01 22:26:01
# @Author : Your Name (you@example.org)
# @Link : http://example.org
# @Version : $Id$
import os
import threading
import requests
import lxml
from threading import Thread
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdef... | myimg = [img.get('src') for img in soup.find(id='brand-waterfall').find_all('img')] # 查询id下所有img元素
print 'myimg:', myimg
for img in myimg:
pic_name = pic_path + str(t) + '.jpg'
# img_src = img.get('src')
print 'img: ', img
# self.download_pic(URL1,img,pic_name) #request Url,img src,picture name
w = Worker... | random_line_split | |
down_pic_thread.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-09-01 22:26:01
# @Author : Your Name (you@example.org)
# @Link : http://example.org
# @Version : $Id$
import os
import threading
import requests
import lxml
from threading import Thread
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdef... | y:
u = self.url + self.img
r = requests.get(u, stream=True)
with open(self.filename, 'wb') as fd:
for chunk in r.iter_content(4096):
fd.write(chunk)
except Exception, e:
raise
def get_imgs(url):
t = 1
r = requests.get(url, stream=True)
soup = BeautifulSoup(r.text, 'lxml')
myimg = [img.get('... | tr | identifier_name |
down_pic_thread.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-09-01 22:26:01
# @Author : Your Name (you@example.org)
# @Link : http://example.org
# @Version : $Id$
import os
import threading
import requests
import lxml
from threading import Thread
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdef... | t) + '.jpg'
# img_src = img.get('src')
print 'img: ', img
# self.download_pic(URL1,img,pic_name) #request Url,img src,picture name
w = Worker(URL1, img, pic_name)
w.start()
t += 1
get_imgs(URL)
| conditional_block | |
group.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (&self, view: &View) -> usize {
let midpoint = vec2_div(vec2_add(self.extents[0], self.extents[1]), [2, 2]);
let mouse_dist = view.mouse_dist(midpoint);
vec2_square_len(mouse_dist) as usize
}
}
| mouse_dist | identifier_name |
group.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | let image = ::image::load_from_memory(&data).expect("load image");
// TODO: Would be great to move off thread.
let image =
Texture::from_image(texture_context, &image.to_rgba(), &texture_settings)
.expect("texture");
... | random_line_split | |
pidPyart.py | print_function
import pyart
from rdkit.sping.pid import *
from rdkit.sping.PDF import pdfmetrics
import Fontmapping # helps by mapping pid font classes to Pyart font names
# note for now I'm just going to do the standard PDF fonts & forget the rest
class PyartCanvas(Canvas):
"note the default face is 'times'... | 'arial':'Helvetica'
}
try:
face = piddle_font_map[string.lower(font.face)]
except:
return 'Helvetica'
name = face + '-'
if font.bold and face in ['Courier','Helvetica','Times']:
name = name + 'Bold'
if font.italic and ... | """Attempts to return proper font name.
PDF uses a standard 14 fonts referred to
by name. Default to self.defaultFont('Helvetica').
The dictionary allows a layer of indirection to
support a standard set of PIDDLE font names."""
piddle_font_map = {
'Times':'Times',
... | identifier_body |
pidPyart.py | print_function
import pyart
from rdkit.sping.pid import *
from rdkit.sping.PDF import pdfmetrics
import Fontmapping # helps by mapping pid font classes to Pyart font names
# note for now I'm just going to do the standard PDF fonts & forget the rest
class PyartCanvas(Canvas):
"note the default face is 'times'... |
path = pyart.VectorPath(len(pointlist)+1)
if closed:
path.moveto_closed(pointlist[0][0], pointlist[0][1])
else:
path.moveto_open(pointlist[0][0], pointlist[0][1])
for pt in pointlist[1:]:
path.lineto(pt[0],pt[1])
if closed:
... | self._pycan.gstate.stroke_width = eWidth | conditional_block |
pidPyart.py | import print_function
import pyart
from rdkit.sping.pid import *
from rdkit.sping.PDF import pdfmetrics
import Fontmapping # helps by mapping pid font classes to Pyart font names
# note for now I'm just going to do the standard PDF fonts & forget the rest
class PyartCanvas(Canvas):
"note the default face is ... | elif font.italic and face == 'Times':
name = name + 'Italic'
if name == 'Times-':
name = name + 'Roman'
# symbol and ZapfDingbats cannot be modified!
#trim and return
if name[-1] == '-':
name = name[0:-1]
return name
def stringW... | if font.bold and face in ['Courier','Helvetica','Times']:
name = name + 'Bold'
if font.italic and face in ['Courier', 'Helvetica']:
name = name + 'Oblique' | random_line_split |
pidPyart.py | print_function
import pyart
from rdkit.sping.pid import *
from rdkit.sping.PDF import pdfmetrics
import Fontmapping # helps by mapping pid font classes to Pyart font names
# note for now I'm just going to do the standard PDF fonts & forget the rest
class PyartCanvas(Canvas):
"note the default face is 'times'... | (self, s, font=None):
if not font:
font = self.defaultFont
fontname = Fontmapping.getPdfName(font)
return pdfmetrics.stringwidth(s, fontname) * font.size * 0.001
def fontAscent(self, font=None):
if not font:
font = self.defaultFont
fontname = Fon... | stringWidth | identifier_name |
cpu_util.py | """
Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
| RockStor 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 with this program... | RockStor 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 2 of the License,
or (at your option) any later version.
| random_line_split |
cpu_util.py | """
Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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 2 of the License,
or (at your option) any la... | (GenericSProbeView):
serializer_class = CPUMetricSerializer
model_obj = CPUMetric
| CPUMetricView | identifier_name |
cpu_util.py | """
Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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 2 of the License,
or (at your option) any la... | serializer_class = CPUMetricSerializer
model_obj = CPUMetric | identifier_body | |
colors.js | ({
// local representation of all CSS3 named colors, companion to dojo.colors. To be used where descriptive information
// is required for each color, such as a palette widget, and not for specifying color programatically.
//Note: due to the SVG 1.0 spec additions, some of these are alternate spellings for the same c... | goldenrod: "kullanruskea",
gray: "harmaa",
green: "vihreä",
greenyellow: "vihreänkeltainen",
grey: "harmaa", // same as gray
honeydew: "hunajameloninvihreä",
hotpink: "pinkki",
indianred: "kirkkaanpunainen",
indigo: "indigo",
ivory: "norsunluu",
khaki: "khaki",
lavender: "laventeli",
lavenderblush: "laventelinpunainen"... | gainsboro: "gainsboro",
ghostwhite: "lakananvalkoinen",
gold: "kulta", | random_line_split |
activities.py | # -*- coding: utf-8 -*-
# * Authors:
# * TJEBBES Gaston <g.t@majerti.fr>
# * Arezki Feth <f.a@majerti.fr>;
# * Miotte Julien <j.m@majerti.fr>;
import os
from pyramid.httpexceptions import HTTPFound
from autonomie.forms.admin import (
ActivityConfigSchema,
)
from autonomie.models.activity import (
... | config.add_route(ACTIVITY_URL, ACTIVITY_URL)
config.add_admin_view(AdminActivitiesView, parent=AccompagnementIndexView) | identifier_body | |
activities.py | # -*- coding: utf-8 -*-
# * Authors:
# * TJEBBES Gaston <g.t@majerti.fr>
# * Arezki Feth <f.a@majerti.fr>;
# * Miotte Julien <j.m@majerti.fr>;
import os
from pyramid.httpexceptions import HTTPFound
from autonomie.forms.admin import (
ActivityConfigSchema,
)
from autonomie.models.activity import (
... | 'modes': [mode.appstruct() for mode in modes],
'actions': self._recursive_action_appstruct(actions)
}
self._add_pdf_img_to_appstruct('activity', activity_appstruct)
form.set_appstruct(activity_appstruct)
def submit_success(self, activity_appstruct):
"""
... | activity_appstruct = {
'footer': self.request.config.get("activity_footer", ""),
'types': [type_.appstruct() for type_ in types], | random_line_split |
activities.py | # -*- coding: utf-8 -*-
# * Authors:
# * TJEBBES Gaston <g.t@majerti.fr>
# * Arezki Feth <f.a@majerti.fr>;
# * Miotte Julien <j.m@majerti.fr>;
import os
from pyramid.httpexceptions import HTTPFound
from autonomie.forms.admin import (
ActivityConfigSchema,
)
from autonomie.models.activity import (
... | (self, activity_appstruct):
"""
Handle successfull activity configuration
"""
self.store_pdf_conf(activity_appstruct, 'activity')
# We delete the elements that are no longer in the appstruct
self.disable_types(activity_appstruct)
self.disable_actions(activity_... | submit_success | identifier_name |
transformer_vae_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... | (self):
batch_size = 3
input_length = 5
target_length = 16
vocab_size = 9
hparams = transformer_vae.transformer_ae_small()
hparams.bottleneck_kind = "dvq"
hparams.dp_strength = 0
p_hparams = problem_hparams.test_problem_hparams(vocab_size,
... | testTransformerAEOnDVQ | identifier_name |
transformer_vae_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... | import tensorflow as tf
class TransformerVaeTest(tf.test.TestCase):
def testTransformerAEOnDVQ(self):
batch_size = 3
input_length = 5
target_length = 16
vocab_size = 9
hparams = transformer_vae.transformer_ae_small()
hparams.bottleneck_kind = "dvq"
hparams.dp_strength = 0
p_hparams ... | random_line_split | |
transformer_vae_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... | tf.test.main() | conditional_block | |
transformer_vae_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... | tf.train.create_global_step()
model = transformer_vae.TransformerAE(hparams, tf.estimator.ModeKeys.TRAIN,
p_hparams)
logits, _ = model(features)
with self.test_session() as session:
session.run(tf.global_variables_initializer())
logits_val = session.... | batch_size = 3
input_length = 5
target_length = 16
vocab_size = 9
hparams = transformer_vae.transformer_ae_small()
hparams.bottleneck_kind = "dvq"
hparams.dp_strength = 0
p_hparams = problem_hparams.test_problem_hparams(vocab_size,
vocab_s... | identifier_body |
jquery.validate-ca.js | /*
* Translated default messages for the jQuery validation plugin.
* Locale: ES (Spanish; Español)
*/
(function ($) {
$.extend($.validator.messages, {
required: "Aquest camp és obligatori.",
remote: "Per favor, emplena aquest camp.",
email: "Per favor, escriu una adreça de correu vàlida",
url: "Per favor, e... | range: $.validator.format("Per favor, escriu un valor entre {0} i {1}."),
max: $.validator.format("Per favor, escriu un valor menor o igual a {0}."),
min: $.validator.format("Per favor, escriu un valor major o igual a {0}.")
});
}(jQuery)); | maxlength: $.validator.format("Per favor, no escrigues més de {0} caràcters."),
minlength: $.validator.format("Per favor, no escrigues menys de {0} caràcters."),
rangelength: $.validator.format("Per favor, escriu un valor entre {0} i {1} caràcters."), | random_line_split |
IonParserBinaryRaw.ts | null;
case IonBinary.TB_CLOB:
case IonBinary.TB_BLOB:
if (this.isNull()) {
return null;
}
this.load_value();
return this._curr!;
default:
throw new Error("Current value is not a blob or clob.");
}
}
booleanValue(): boolean | null {
switch... | annotation_len = this.readVarUnsignedInt();
t._as = t._in.position();
t._in.skip(annotation_len);
t._ae = t._in.position(); | random_line_split | |
IonParserBinaryRaw.ts | in);
}
private readVarSignedInt(): number {
return ParserBinaryRaw._readVarSignedIntFrom(this._in);
}
private readUnsignedIntAsBigInt(): JSBI {
return ParserBinaryRaw._readUnsignedIntAsBigIntFrom(this._in, this._len);
}
private readUnsignedIntAsNumber(): number {
return ParserBinaryRaw._readU... | this._curr = Decimal.ZERO;
} e | conditional_block | |
IonParserBinaryRaw.ts | (input: BinarySpan, numberOfBytes): number | null {
let tempBuf: DataView;
switch (numberOfBytes) {
case 0:
return 0.0;
case 4:
tempBuf = new DataView(input.chunk(4).buffer);
return tempBuf.getFloat32(0, false);
case 8:
tempBuf = new DataView(input.chunk(8).buff... | _readFloatFrom | identifier_name | |
IonParserBinaryRaw.ts | private readVarUnsignedInt(): number {
return ParserBinaryRaw._readVarUnsignedIntFrom(this._in);
}
private readVarSignedInt(): number {
return ParserBinaryRaw._readVarSignedIntFrom(this._in);
}
private readUnsignedIntAsBigInt(): JSBI {
return ParserBinaryRaw._readUnsignedIntAsBigIntFrom(this._in... | if (this._curr != undefined) {
return;
} // current value is already loaded
if (this.isNull()) {
return;
}
switch (this._raw_type) {
case IonBinary.TB_BOOL:
break;
case IonBinary.TB_INT:
this._curr = this._readIntegerMagnitude();
break;
case IonB... | identifier_body | |
service_worker_micro_benchmark.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page
from telemetry import story
class ServiceWorkerBenchmarkPage(page.Page):
"""Page for workload to measure some spe... | """Page set for micro benchmarking of each functions with ServiceWorker"""
def __init__(self):
super(ServiceWorkerMicroBenchmarkPageSet, self).__init__(
archive_data_file='data/service_worker_micro_benchmark.json',
cloud_storage_bucket=story.PUBLIC_BUCKET)
# pylint: disable=line-too-long
... | identifier_body | |
service_worker_micro_benchmark.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page
from telemetry import story
class ServiceWorkerBenchmarkPage(page.Page):
"""Page for workload to measure some spe... | (story.StorySet):
"""Page set for micro benchmarking of each functions with ServiceWorker"""
def __init__(self):
super(ServiceWorkerMicroBenchmarkPageSet, self).__init__(
archive_data_file='data/service_worker_micro_benchmark.json',
cloud_storage_bucket=story.PUBLIC_BUCKET)
# pylint: disab... | ServiceWorkerMicroBenchmarkPageSet | identifier_name |
service_worker_micro_benchmark.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page
from telemetry import story
class ServiceWorkerBenchmarkPage(page.Page):
"""Page for workload to measure some spe... |
# pylint: disable=line-too-long
# The latest code of localhost:8091 is from:
# https://github.com/horo-t/Service-Worker-Performance/tree/fix-flakyness
# (rev: 0cc35c2398526665399ca99fe53147ff81101408)
# TODO(falken): House the code in GoogleChrome's GitHub repository.
# pylint: enable=C0301
... |
def __init__(self):
super(ServiceWorkerMicroBenchmarkPageSet, self).__init__(
archive_data_file='data/service_worker_micro_benchmark.json',
cloud_storage_bucket=story.PUBLIC_BUCKET) | random_line_split |
GLRenderManager.ts | The most common use of this is standard 2d sprite rendering,
* and the TextureAtlasRenderer is added by default as a shared
* renderer. Sprites, StaticImages and Tilemaps (core gameobjects)
* can all use the same renderer/shader combination and be drawn as
* part of the same batch.
*
* Custom gameobjects c... |
//set default gl state
gl.enable(gl.BLEND);
this._switchBlendMode(gl, this._currentBlendMode);
//shader manager
this._shaderManager.init(gl, "TextureAtlasShader");
//camera matrix
this.camMatrix = new Float32Array( [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ] );
this._camMatrixOffset = new Kiwi.Geom.Matrix... | {
this.scaleViewport( gl, Kiwi.Stage.SCALE_NONE, this._game.stage.width, this._game.stage.height );
} | conditional_block |
GLRenderManager.ts | }
private _filtersEnabled: boolean = false;
/**
* Performs initialisation required for single game instance -
* happens once, at bootup. Sets global GL state.
* Initialises managers for shaders and textures.
* Instantiates the default shared renderer (`TextureAtlasRenderer`)
* @method _init
* @priva... | gl.bindTexture(gl.TEXTURE_2D, this._currentTextureAtlas.glTextureWrapper.texture);
}*/
}
private _sequence: any[]; | random_line_split | |
GLRenderManager.ts | case Kiwi.Stage.SCALE_STRETCH:
break;
case Kiwi.Stage.SCALE_NONE:
width = this._game.stage.width;
height = this._game.stage.height;
break;
default:
break;
}
gl.viewport(offset.x, offset.y, width, height);
}
/**
* Performs initialisation required when switching to a diffe... | {
// Acquire renderer
var rendererSwitched = false;
if (batch[0].entity.glRenderer !== this._currentRenderer) {
rendererSwitched = true;
this._switchRenderer(gl, batch[0].entity);
}
// Clear renderer for fresh data
this._currentRenderer.clear(gl, { camMatrix: this.camMatrix });
// Call re... | identifier_body | |
GLRenderManager.ts | () {
this._textureManager = new GLTextureManager();
this._shaderManager = new Kiwi.Shaders.ShaderManager();
//this.filters = new Kiwi.Filters.GLFilterManager(this._game, this._shaderManager);
this._init();
}
/**
* The type of object that this is.
* @method objType
* @return {string} "GLRender... | boot | identifier_name | |
loadcsv.py | from django.core.management.base import BaseCommand, CommandError
from cellcounter.main.models import CellImage, SimilarLookingGroup, CellType
import csv
class dialect(csv.Dialect):
pass
class Command(BaseCommand):
args = '<csvfile1 csvfile2 ...>'
help = 'Loads images and descriptions from specified csv f... | for filename in args:
file_ = csv.DictReader(open(filename), dialect="excel-tab")
for line in file_:
try:
celltype = CellType.objects.get(readable_name = line["CellType"])
except:
print "Cell Type not found:" + line["C... | identifier_body | |
loadcsv.py | from django.core.management.base import BaseCommand, CommandError
from cellcounter.main.models import CellImage, SimilarLookingGroup, CellType
import csv
class dialect(csv.Dialect):
pass
class Command(BaseCommand):
args = '<csvfile1 csvfile2 ...>'
help = 'Loads images and descriptions from specified csv f... | (self, *args, **options):
for filename in args:
file_ = csv.DictReader(open(filename), dialect="excel-tab")
for line in file_:
try:
celltype = CellType.objects.get(readable_name = line["CellType"])
except:
pri... | handle | identifier_name |
loadcsv.py | from django.core.management.base import BaseCommand, CommandError
from cellcounter.main.models import CellImage, SimilarLookingGroup, CellType
import csv
class dialect(csv.Dialect):
pass
class Command(BaseCommand):
args = '<csvfile1 csvfile2 ...>'
help = 'Loads images and descriptions from specified csv f... | try:
celltype = CellType.objects.get(readable_name = line["CellType"])
except:
print "Cell Type not found:" + line["CellType"]
ci = CellImage(title = line["Title"],
description = line["Descriptio... | def handle(self, *args, **options):
for filename in args:
file_ = csv.DictReader(open(filename), dialect="excel-tab")
for line in file_: | random_line_split |
loadcsv.py | from django.core.management.base import BaseCommand, CommandError
from cellcounter.main.models import CellImage, SimilarLookingGroup, CellType
import csv
class dialect(csv.Dialect):
pass
class Command(BaseCommand):
args = '<csvfile1 csvfile2 ...>'
help = 'Loads images and descriptions from specified csv f... | file_ = csv.DictReader(open(filename), dialect="excel-tab")
for line in file_:
try:
celltype = CellType.objects.get(readable_name = line["CellType"])
except:
print "Cell Type not found:" + line["CellType"]
ci = Cel... | conditional_block | |
overview.ts | /**
* Copyright 1999-2019 Seata.io Group.
*
* 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... | });
};
export default (state = initialState, action: any) => {
switch (action.type) {
case SET_OVERVIEW:
return { ...state, ...action.data };
default:
return state;
}
};
export { getData }; | dispatch({
type: SET_OVERVIEW,
data: {
data,
}, | random_line_split |
routes.js | /**
* Route Mappings
* (sails.config.routes)
*
* Your routes map URLs to views and controllers.
*
* If Sails receives a URL that doesn't match any of the routes below,
* it will check for matching files (images, scripts, stylesheets, etc.)
* in your assets directory. e.g. `http://localhost:1337/images/foo.jpg`... | 'POST /post-comment': 'PostController.commentToPost'
/***************************************************************************
* *
* Custom routes here... *
* ... | random_line_split | |
EVLA_pipe_fluxgains.py | ######################################################################
#
# Copyright (C) 2013
# Associated Universities, Inc. Washington DC, USA,
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Library General Public License as published by
# the Free Software Fo... | listmodels=False
usescratch=scratch
setjy()
except:
logprint('no data found for field ' + str(myfield)+" spw "+str(myspw), logfileout='logs/fluxgains.log')
ii=ii+1
tb.close()
logprint ("Making gain tables for flux density bootstrapping"... | for myfield in fields:
spws = field_spws[myfield]
for myspw in spws:
reference_frequency = center_frequencies[myspw]
EVLA_band = find_EVLA_band(reference_frequency)
logprint ("Center freq for spw "+str(myspw)+" = "+str(reference_frequency)+", observing band = "+EVLA_b... | conditional_block |
EVLA_pipe_fluxgains.py | ######################################################################
#
# Copyright (C) 2013
# Associated Universities, Inc. Washington DC, USA,
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Library General Public License as published by
# the Free Software Fo... |
ii=0
for fields in standard_source_fields:
for myfield in fields:
spws = field_spws[myfield]
for myspw in spws:
reference_frequency = center_frequencies[myspw]
EVLA_band = find_EVLA_band(reference_frequency)
logprint ("Center freq for spw "+str(myspw)+" = "+str(r... | standard_source_fields = find_standards(positions) | random_line_split |
outlet.ts | import { ENV } from '@ember/-internals/environment';
import { guidFor } from '@ember/-internals/utils';
import { assert } from '@ember/debug';
import EngineInstance from '@ember/engine/instance';
import { _instrumentStart } from '@ember/instrumentation';
import { assign } from '@ember/polyfills';
import {
Bounds,
C... | }
}
getDestroyable(state: OutletInstanceState): Option<Destroyable> {
if (ENV._DEBUG_RENDER_TREE) {
return state;
} else {
return null;
}
}
}
const OUTLET_MANAGER = new OutletComponentManager();
export class OutletComponentDefinition
implements
ComponentDefinition<OutletDefini... |
state.environment.extra.debugRenderTree.didRender(state.outlet!, bounds); | random_line_split |
outlet.ts | import { ENV } from '@ember/-internals/environment';
import { guidFor } from '@ember/-internals/utils';
import { assert } from '@ember/debug';
import EngineInstance from '@ember/engine/instance';
import { _instrumentStart } from '@ember/instrumentation';
import { assign } from '@ember/polyfills';
import {
Bounds,
C... | (state: OutletInstanceState): Option<Destroyable> {
if (ENV._DEBUG_RENDER_TREE) {
return state;
} else {
return null;
}
}
}
const OUTLET_MANAGER = new OutletComponentManager();
export class OutletComponentDefinition
implements
ComponentDefinition<OutletDefinitionState, OutletInstanceSt... | getDestroyable | identifier_name |
outlet.ts | import { ENV } from '@ember/-internals/environment';
import { guidFor } from '@ember/-internals/utils';
import { assert } from '@ember/debug';
import EngineInstance from '@ember/engine/instance';
import { _instrumentStart } from '@ember/instrumentation';
import { assign } from '@ember/polyfills';
import {
Bounds,
C... | else {
// an outlet has no hooks
return CONSTANT_TAG;
}
}
didRenderLayout(state: OutletInstanceState, bounds: Bounds): void {
state.finalize();
if (ENV._DEBUG_RENDER_TREE) {
state.environment.extra.debugRenderTree.didRender(state, bounds);
if (state.engine) {
state.en... | {
// returning a const tag skips the update hook (VM BUG?)
return createTag();
} | conditional_block |
outlet.ts | import { ENV } from '@ember/-internals/environment';
import { guidFor } from '@ember/-internals/utils';
import { assert } from '@ember/debug';
import EngineInstance from '@ember/engine/instance';
import { _instrumentStart } from '@ember/instrumentation';
import { assign } from '@ember/polyfills';
import {
Bounds,
C... |
};
const WRAPPED_OUTLET_MANAGER = new WrappedOutletComponentManager();
return new OutletComponentDefinition(outletView.state, WRAPPED_OUTLET_MANAGER);
} else {
return new OutletComponentDefinition(outletView.state);
}
}
| {
// to add GUID id and class
element.setAttribute('class', 'ember-view');
element.setAttribute('id', guidFor(component));
} | identifier_body |
event_factory.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.utils import timezone
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.utils import override_settings
import six
from happenings.models import Event
@override_settings(CALENDAR_... | (created_by, title, description, all_day=False,
start_date=None, end_date=None, categories=None, tags=None,
repeat='NEVER', end_repeat=None, full=True, utc=False):
"""
A factory method for creating events. If start_date is supplied,
end_date must also be supplied, and they ... | create_event | identifier_name |
event_factory.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.utils import timezone
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.utils import override_settings
import six
from happenings.models import Event
@override_settings(CALENDAR_... | if hasattr(response, 'content'):
is_response = True
content = response.content
else:
is_response = False
content = response
if isinstance(content, six.text_type):
content = content.encode('utf-8')
content = content.replace(b'\... | random_line_split | |
event_factory.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.utils import timezone
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.utils import override_settings
import six
from happenings.models import Event
@override_settings(CALENDAR_... |
def clean_whitespace(self, response):
"""Remove all newlines and all occurances of multiple spaces."""
if hasattr(response, 'content'):
is_response = True
content = response.content
else:
is_response = False
content = response
if isi... | cls.user.delete() | identifier_body |
event_factory.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.utils import timezone
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.utils import override_settings
import six
from happenings.models import Event
@override_settings(CALENDAR_... |
else:
content = content.decode('utf-8')
return content
def create_event(created_by, title, description, all_day=False,
start_date=None, end_date=None, categories=None, tags=None,
repeat='NEVER', end_repeat=None, full=True, utc=False):
"""
A factory... | response.content = content | conditional_block |
spark2tfrecords.py | #!/usr/bin/env python3
"""
Justin Tan 2017
Reads parquet file, conducts preprocessing, outputs to TfRecords
spark-submit --name spark2tf --jars /home/jtan/gpu/jtan/spark/ecosystem/spark/spark-tensorflow-connector/target/spark-tensorflow-connector-1.0-SNAPSHOT.jar,/home/jtan/gpu/jtan/spark/ecosystem/spark/spark-tensorf... | trainCols = [col for col in df.columns if col not in specialCols]
assembler = VectorAssembler(inputCols=trainCols, outputCol='trainFeatures')
df = assembler.transform(df)
# Train-test split
df_train, df_test = df.randomSplit([0.9, 0.1], seed=42)
# Normalization - unit variance, zero mean
#... | from pyspark.ml.stat import Correlation
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.feature import StandardScaler
subexclude = ['weight', 'index']
excludecols = [col for col in df_pqt.columns for subcol in subexclude if subcol in col]
df = df_pqt.drop(*excludecols)
print('Cor... | identifier_body |
spark2tfrecords.py | #!/usr/bin/env python3
"""
Justin Tan 2017
Reads parquet file, conducts preprocessing, outputs to TfRecords
spark-submit --name spark2tf --jars /home/jtan/gpu/jtan/spark/ecosystem/spark/spark-tensorflow-connector/target/spark-tensorflow-connector-1.0-SNAPSHOT.jar,/home/jtan/gpu/jtan/spark/ecosystem/spark/spark-tensorf... | (df, trainCols, specialCols, col2unpack='scaledFeatures'):
from pyspark.sql.functions import udf, col
from pyspark.sql.types import ArrayType, DoubleType
def to_array(col):
def to_array_(v):
return v.toArray().tolist()
return udf(to_array_, ArrayType(DoubleType()))(col)
unp... | unpack_vectorCol | identifier_name |
spark2tfrecords.py | #!/usr/bin/env python3
"""
Justin Tan 2017
Reads parquet file, conducts preprocessing, outputs to TfRecords
spark-submit --name spark2tf --jars /home/jtan/gpu/jtan/spark/ecosystem/spark/spark-tensorflow-connector/target/spark-tensorflow-connector-1.0-SNAPSHOT.jar,/home/jtan/gpu/jtan/spark/ecosystem/spark/spark-tensorf... |
def rm_correlated(df_corr):
d_corr = get_top_abs_correlations(df_corr, n = 128)
corr_pairs = [tupl for tupl in list(d_corr[d_corr > 0.99999].index)]
top001_left = [tupl[0] for tupl in corr_pairs]
top001_right = [tupl[1] for tupl in corr_pairs]
[print(feature) for feature in list(set(top001_right))... | au_corr = df_corr.abs().unstack()
labels_to_drop = get_redundant_pairs(df_corr.columns)
au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False)
return au_corr[0:n] | random_line_split |
spark2tfrecords.py | #!/usr/bin/env python3
"""
Justin Tan 2017
Reads parquet file, conducts preprocessing, outputs to TfRecords
spark-submit --name spark2tf --jars /home/jtan/gpu/jtan/spark/ecosystem/spark/spark-tensorflow-connector/target/spark-tensorflow-connector-1.0-SNAPSHOT.jar,/home/jtan/gpu/jtan/spark/ecosystem/spark/spark-tensorf... |
return pairs_to_drop
def get_top_abs_correlations(df_corr, n=50):
au_corr = df_corr.abs().unstack()
labels_to_drop = get_redundant_pairs(df_corr.columns)
au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False)
return au_corr[0:n]
def rm_correlated(df_corr):
d_corr = get_top... | pairs_to_drop.add((cols[i], cols[j])) | conditional_block |
indexOf-test.js | (function () {
"use strict";
require('../bufferjs/indexOf');
var assert = require('assert');
// Test the static version, Buffer needle
function test1() {
var haystack = new Buffer(10)
, needle = new Buffer(1);
needle[0] = haystack[0] = 255;
assert.equal(Buffer.indexOf(haystack, needle), ... | assert.equal(Buffer.indexOf(haystack, needle, 6), 7);
assert.equal(haystack.indexOf(needle, 8), 10);
}
test1();
test2();
testFromSpecifiedIndex();
console.log("Done. `indexOf` tests passed!");
}()); | assert.equal(haystack.indexOf(needle), 0);
assert.equal(Buffer.indexOf(haystack, needle, 1), 3);
assert.equal(haystack.indexOf(needle, 4), 5); | random_line_split |
indexOf-test.js | (function () {
"use strict";
require('../bufferjs/indexOf');
var assert = require('assert');
// Test the static version, Buffer needle
function | () {
var haystack = new Buffer(10)
, needle = new Buffer(1);
needle[0] = haystack[0] = 255;
assert.equal(Buffer.indexOf(haystack, needle), 0);
assert.equal(Buffer.indexOf(haystack, new Buffer(haystack.length)), -1);
}
// Test the OO version, String needle
function test2() {
var haystac... | test1 | identifier_name |
indexOf-test.js | (function () {
"use strict";
require('../bufferjs/indexOf');
var assert = require('assert');
// Test the static version, Buffer needle
function test1() |
// Test the OO version, String needle
function test2() {
var haystack = new Buffer(20)
, needle = '\r\n'
, index = 5;
haystack.write(needle, index);
assert.equal(haystack.indexOf(needle), index);
assert.equal(haystack.indexOf('should not be found'), -1);
}
// Test starting from a... | {
var haystack = new Buffer(10)
, needle = new Buffer(1);
needle[0] = haystack[0] = 255;
assert.equal(Buffer.indexOf(haystack, needle), 0);
assert.equal(Buffer.indexOf(haystack, new Buffer(haystack.length)), -1);
} | identifier_body |
schema.py | import logging
from marshmallow import ValidationError, post_load
from marshmallow_jsonapi import Schema, fields
from timeswitch.auth.dao import User
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
LOGGER = logging.getLogger(__name_... | (text):
return text.replace('_', '-')
class UserSchema(Schema):
id = fields.String(dump_only=True, required=True)
name = fields.String(required=True)
password = fields.String(load_only=True, required=False, attribute="password_clear")
new_password = fields.String(load_only=True, required=False)
... | dasherize | identifier_name |
schema.py | import logging
from marshmallow import ValidationError, post_load
from marshmallow_jsonapi import Schema, fields
from timeswitch.auth.dao import User
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
LOGGER = logging.getLogger(__name_... |
@post_load
def make_user(self, data):
return User(**data)
def handle_error(self, exc, data):
raise ValidationError('An error occurred with input: {0} \n {1}'.format(data, str(exc)))
class Meta:
type_ = 'users'
# inflect = dasherize | password = fields.String(load_only=True, required=False, attribute="password_clear")
new_password = fields.String(load_only=True, required=False)
email = fields.Email(required=False)
last_loggin = fields.String(required=False)
privilege = fields.String(required=False) | random_line_split |
schema.py | import logging
from marshmallow import ValidationError, post_load
from marshmallow_jsonapi import Schema, fields
from timeswitch.auth.dao import User
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
LOGGER = logging.getLogger(__name_... | type_ = 'users'
# inflect = dasherize | identifier_body | |
keys.rs | use crypto;
use crypto::mac::Mac;
use gmp::Mpz;
use num::FromPrimitive;
use rand;
use std::io::Write;
use util;
lazy_static! {
static ref DH_GENERATOR: Mpz = Mpz::from_u64(0x2).unwrap();
static ref DH_PRIME: Mpz = Mpz::from_bytes_be(&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9,
0x0f... | } | pub fn recv_key(&self) -> &[u8] {
&self.recv_key
} | random_line_split |
keys.rs | use crypto;
use crypto::mac::Mac;
use gmp::Mpz;
use num::FromPrimitive;
use rand;
use std::io::Write;
use util;
lazy_static! {
static ref DH_GENERATOR: Mpz = Mpz::from_u64(0x2).unwrap();
static ref DH_PRIME: Mpz = Mpz::from_bytes_be(&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9,
0x0f... | () -> PrivateKeys {
let key_data = util::rand_vec(&mut rand::thread_rng(), 95);
Self::new_with_key(&key_data)
}
pub fn new_with_key(key_data: &[u8]) -> PrivateKeys {
let private_key = Mpz::from_bytes_be(key_data);
let public_key = DH_GENERATOR.powm(&private_key, &DH_PRIME);
... | new | identifier_name |
keys.rs | use crypto;
use crypto::mac::Mac;
use gmp::Mpz;
use num::FromPrimitive;
use rand;
use std::io::Write;
use util;
lazy_static! {
static ref DH_GENERATOR: Mpz = Mpz::from_u64(0x2).unwrap();
static ref DH_PRIME: Mpz = Mpz::from_bytes_be(&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9,
0x0f... |
}
| {
&self.recv_key
} | identifier_body |
valid.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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 a... | '*',
'* @example',
'* var target = {',
'* \'a\': \'beep\'',
'* };',
'* var source = {',
'* \'a\': \'boop\',',
'* \'b\': \'bap\'',
'* };',
'*',
'* var out = merge( target, source );',
'* // returns {\'a\':\'boop\', \'b\':\'bap\'}',
'*/',
'var merge = mergefcn( defaults );'
].join... | '* @returns {Object} merged (target) object', | random_line_split |
viewexpctrlmap.comp.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { SharedVariableService } from "../../../../_service/sharedvariable-service";
import { ActionBtnProp } from '../../../../_model/action_buttons';
import { Subscription } from 'rxjs/Subscription';
import { ECMService } from "../../../../_service/expense... |
expandDetails(event) {
var that = this;
if (event.details && event.details.length > 0) { return; }
try {
event.loading = false;
this._ecmservice.getExpenseCtrlMap({
"flag": "ccdetails", "cmpid": that.loginUser.cmpid,
"fy": that.logi... | {
this.getExpenseCtrlMap(event.first, (event.first + event.rows));
} | identifier_body |
viewexpctrlmap.comp.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { SharedVariableService } from "../../../../_service/sharedvariable-service";
import { ActionBtnProp } from '../../../../_model/action_buttons';
import { Subscription } from 'rxjs/Subscription';
import { ECMService } from "../../../../_service/expense... |
}, err => {
this._msg.Show(messageType.error, "Error", err);
console.log(err);
}, () => {
// console.log("Complete");
})
} catch (error) {
}
}
openECMDetails(row) {
if (row.islocked) {
this... | {
that._msg.Show(messageType.info, "info", "Record Not Found");
return;
} | conditional_block |
viewexpctrlmap.comp.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { SharedVariableService } from "../../../../_service/sharedvariable-service";
import { ActionBtnProp } from '../../../../_model/action_buttons';
import { Subscription } from 'rxjs/Subscription';
import { ECMService } from "../../../../_service/expense... | }
getExpenseCtrlMap(from: number, to: number) {
var that = this;
this._ecmservice.getAllExpenseCtrlMap({
"flag": "grid", "cmpid": that.loginUser.cmpid, "fy": that.loginUser.fy, "from": from, "to": to
}).subscribe(expctrlmap => {
that.totalRecords = expctrlmap.da... | console.log("Error");
}, () => {
// console.log("Complete");
}); | random_line_split |
viewexpctrlmap.comp.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { SharedVariableService } from "../../../../_service/sharedvariable-service";
import { ActionBtnProp } from '../../../../_model/action_buttons';
import { Subscription } from 'rxjs/Subscription';
import { ECMService } from "../../../../_service/expense... | (evt) {
if (evt === "add") {
this._router.navigate(['/master/expensecontrolcentermap/add']);
}
}
fillStatusDropDown() {
var that = this;
this._userService.getMenuDetails({
"flag": "trashrights", "ptype": "mst", "mtype": "ecm",
"uid": this.log... | actionBarEvt | identifier_name |
metadata.rs | extern crate env_logger;
extern crate gluon_base as base;
extern crate gluon_parser as parser;
extern crate gluon_check as check;
use base::metadata::{Metadata, MetadataEnv};
use base::symbol::Symbol;
use check::metadata::metadata;
mod support;
struct MockEnv;
impl MetadataEnv for MockEnv {
fn get_metadata(&se... |
#[test]
fn propagate_metadata_type_record() {
let _ = env_logger::init();
let text = r#"
/// A test type
type Test = Int
{ Test }
"#;
let (mut expr, result) = support::typecheck_expr(text);
assert!(result.is_ok(), "{}", result.unwrap_err());
let metadata = metadata(&MockEnv, &mut expr);
ass... | {
let _ = env_logger::init();
let text = r#"
/// The identity function
let id x = x
{ id }
"#;
let (mut expr, result) = support::typecheck_expr(text);
assert!(result.is_ok(), "{}", result.unwrap_err());
let metadata = metadata(&MockEnv, &mut expr);
assert_eq!(metadata.module.get("id"),
... | identifier_body |
metadata.rs | extern crate env_logger;
extern crate gluon_base as base;
extern crate gluon_parser as parser;
extern crate gluon_check as check;
use base::metadata::{Metadata, MetadataEnv};
use base::symbol::Symbol;
use check::metadata::metadata;
mod support;
struct | ;
impl MetadataEnv for MockEnv {
fn get_metadata(&self, _id: &Symbol) -> Option<&Metadata> {
None
}
}
#[test]
fn propagate_metadata_let_in() {
let _ = env_logger::init();
let text = r#"
/// The identity function
let id x = x
id
"#;
let (mut expr, result) = support::typecheck_expr(text);
... | MockEnv | identifier_name |
metadata.rs | extern crate env_logger;
extern crate gluon_base as base;
extern crate gluon_parser as parser;
extern crate gluon_check as check;
use base::metadata::{Metadata, MetadataEnv};
use base::symbol::Symbol;
use check::metadata::metadata;
mod support;
struct MockEnv;
impl MetadataEnv for MockEnv {
fn get_metadata(&se... | let _ = env_logger::init();
let text = r#"
/// The identity function
let id x = x
id
"#;
let (mut expr, result) = support::typecheck_expr(text);
assert!(result.is_ok(), "{}", result.unwrap_err());
let metadata = metadata(&MockEnv, &mut expr);
assert_eq!(metadata,
Metadata {
... | }
}
#[test]
fn propagate_metadata_let_in() { | random_line_split |
typeConverters.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (
workspaceEdit: vscode.WorkspaceEdit,
client: ITypeScriptServiceClient,
edits: Iterable<Proto.FileCodeEdits>
): vscode.WorkspaceEdit {
for (const edit of edits) {
for (const textChange of edit.textChanges) {
workspaceEdit.replace(client.toResource(edit.fileName),
Range.fromTextSpan(textChange),
... | withFileCodeEdits | identifier_name |
typeConverters.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | export namespace Location {
export const fromTextSpan = (resource: vscode.Uri, tsTextSpan: Proto.TextSpan): vscode.Location =>
new vscode.Location(resource, Range.fromTextSpan(tsTextSpan));
}
export namespace TextEdit {
export const fromCodeEdit = (edit: Proto.CodeEdit): vscode.TextEdit =>
new vscode.TextEdit(
... | });
}
| random_line_split |
typeConverters.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
| {
for (const edit of edits) {
for (const textChange of edit.textChanges) {
workspaceEdit.replace(client.toResource(edit.fileName),
Range.fromTextSpan(textChange),
textChange.newText);
}
}
return workspaceEdit;
} | identifier_body |
conf.py | # -*- coding: utf-8 -*-
#
# libmypaint documentation build configuration file, created by
# sphinx-quickstart2 on Wed Jun 13 23:40:45 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
#... | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referrin... | #html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
| random_line_split |
main.js | // main.js
var React = require('react');
var ReactDOM = require('react-dom');
var LinkedStateMixin = require('react-addons-linked-state-mixin');
var moment = require('moment');
var Location = React.createClass({
onDrag: function(e){
e.key = this.props.i
e.min = this.props.o - (this.props.o * this.props.v)
e.ma... |
},
onClick: function(e){
var d= e.clientY-20;
this.createLocation(d,1,false)
},
createLocation: function(d,v,p){
var v = v||1.0
var st = this.state;
st.controls.push({y:Math.max(0,d), o:d, v:v, p:p})
this.requestBrevit(d, st.controls.length-1, this.setBrevit)
this.setState(st);
},
removeLocation... | {
this.requestBrevit(e.clientY, e.key, this.setBrevit);
} | conditional_block |
main.js | // main.js
var React = require('react');
var ReactDOM = require('react-dom');
var LinkedStateMixin = require('react-addons-linked-state-mixin');
var moment = require('moment');
var Location = React.createClass({
onDrag: function(e){
e.key = this.props.i
e.min = this.props.o - (this.props.o * this.props.v)
e.ma... | document.getElementById('brevit')
); | }
});
ReactDOM.render(
<Brevit />, | random_line_split |
all_6d.js | ['msmastererror',['MSMasterError',['../class_m_s_master_error.html',1,'']]],
['msmastersplitter',['MSMasterSplitter',['../class_m_s_master_splitter.html',1,'MSMasterSplitter'],['../class_m_s_master_splitter_abb9f371e43978f5d0c8746d35e8debb4.html#abb9f371e43978f5d0c8746d35e8debb4',1,'MSMasterSplitter::MSMasterSplitt... | var searchData=
[
['msmaster_5ferror_5fcode',['MSMASTER_ERROR_CODE',['../class_m_s_master_error_aa1deb878016117b72d744363b49a16e4.html#aa1deb878016117b72d744363b49a16e4',1,'MSMasterError']]], | random_line_split | |
views.py | from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import user_passes_test
from django.utils.importlib import import_module
from djangae.core.pa... |
txn()
def _clear_old_events():
from google.appengine.api.datastore import Query, Delete, Get
query = Query("centaur_event", keys_only=True)
query["created <= "] = timezone.now() - timedelta(days=30)
old_event_keys = list(query.Run(limit=EVENT_BATCH_SIZE))
old_events = filter(None, Get(old_ev... | _error = Error.objects.get(pk=error_id)
_error.event_count -= events_removed
_error.save() | identifier_body |
views.py | from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import user_passes_test
from django.utils.importlib import import_module
from djangae.core.pa... |
Delete(to_delete)
if len(old_event_keys) == EVENT_BATCH_SIZE or len(to_delete) < len(old_events):
# In case we didn't clear everything, run again to find more old events.
defer(_clear_old_events, _queue=CLEANUP_QUEUE)
| defer(_update_error_count, error_id, data['count'], _queue=CLEANUP_QUEUE)
to_delete.extend(data['event_keys']) | conditional_block |
views.py | from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import user_passes_test
from django.utils.importlib import import_module
from djangae.core.pa... |
def timestamp(datetime):
""" Returns UTC timestamp, this is included in python3 but not 2"""
return calendar.timegm(datetime.timetuple())
@permission_decorator
def index(request):
errors = Error.objects.all()
# Filter by user email
if request.GET.get('user', None):
errors_pks = [e.erro... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.