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 (c) 2016 warheadhateus developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be cop... | () {}
}
| it_works | identifier_name |
RGraph.common.annotate.js | | http://www.rgraph.net/license |
* o--------------------------------------------------------------------------------o
*/
RGraph = window.RGraph || {isRGraph: true};
// Module pattern
(function (win, doc, undefined)
{
var RG = RGraph,
ua = na... |
/**
* Shows the mini palette used for annotations
*
* @param object e The event object
*/
RG.ShowPalette =
RG.Showpalette = function (e)
{
var isSafari = navigator.userAgent.indexOf('Safari') ? true : false;
e = RG.FixEventObject(e);
var canvas = e.target.... | obj.context.stroke();
}
}; | random_line_split |
RGraph.common.annotate.js | true};
// Module pattern
(function (win, doc, undefined)
{
var RG = RGraph,
ua = navigator.userAgent,
ma = Math;
/**
* This installs some event handlers
*
* Checking the RGraph.Annotate flag means the annotate code only runs once
*/
RG.Annotating_canvas_onmousedown ... |
annotations = annotations.split('|');
} | conditional_block | |
sodium.rs | extern crate serde;
extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use libc::{c_int, c_ulonglong, size_t};
use self::sodiumoxide::crypto::pwhash;
pub const SALTBYTES: usize = pwhash::SALTBYTES;
sodium_type!(Salt, pwhash::Salt, SALTBYTES);
pub fn gen_salt() -> Salt {
S... | () {
let passwd = b"Correct Horse Battery Staple";
let salt = gen_salt();
let mut key = [0u8; 64];
let key_moderate = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_MOD).unwrap();
let mut key = [0u8; 64];
let key_interactive = pwhash(&mut key, passwd, &s... | pwhash_works_for_interactive_method | identifier_name |
sodium.rs | extern crate serde;
extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use libc::{c_int, c_ulonglong, size_t};
use self::sodiumoxide::crypto::pwhash;
pub const SALTBYTES: usize = pwhash::SALTBYTES;
sodium_type!(Salt, pwhash::Salt, SALTBYTES);
pub fn gen_salt() -> Salt {
S... | mod tests {
use rmp_serde;
use super::*;
#[test]
fn get_salt_works() {
let salt = gen_salt();
assert_eq!(salt[..].len(), SALTBYTES)
}
#[test]
fn salt_serialize_deserialize_works() {
let salt = gen_salt();
let serialized = rmp_serde::to_vec(&salt).unwrap();
... |
#[cfg(test)] | random_line_split |
sodium.rs | extern crate serde;
extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use libc::{c_int, c_ulonglong, size_t};
use self::sodiumoxide::crypto::pwhash;
pub const SALTBYTES: usize = pwhash::SALTBYTES;
sodium_type!(Salt, pwhash::Salt, SALTBYTES);
pub fn gen_salt() -> Salt |
pub fn pwhash<'a>(key: &'a mut [u8], passwd: &[u8], salt: &Salt, key_derivation_method: &KeyDerivationMethod) -> Result<&'a [u8], IndyError> {
let (opslimit, memlimit) = unsafe {
match key_derivation_method {
KeyDerivationMethod::ARGON2I_MOD => (crypto_pwhash_argon2i_opslimit_moderate(), crypt... | {
Salt(pwhash::gen_salt())
} | identifier_body |
mconfcheck.py | from pymongo import MongoClient, ASCENDING
from bson.min_key import MinKey
from bson.max_key import MaxKey
from bson import ObjectId, Timestamp
from chunk import Chunk
from chunk_distribution import ChunkDistribution
from config_parser import ConfigParser
from copy import copy, deepcopy
from dateutil import parser
f... | # all following chunks will also differ. needs to align them again.
# for chunks in izip_longest(*chunk_dists, fillvalue=Chunk()):
# if not all_equal(chunks):
# print 'first diff >'.center(23),
# for ch... | config_parsers = [ ConfigParser(db) for db in self.config_dbs ]
shorturi_len = max( len(puri['short_uri']) for puri in self.parsed_uris )
for collection in self.all_collections:
print collection, '\n'
chunk_dists = [ parser.get_chunk_distribution(collection) for parser in confi... | identifier_body |
mconfcheck.py | from pymongo import MongoClient, ASCENDING
from bson.min_key import MinKey
from bson.max_key import MaxKey
from bson import ObjectId, Timestamp
from chunk import Chunk
from chunk_distribution import ChunkDistribution
from config_parser import ConfigParser
from copy import copy, deepcopy
from dateutil import parser
f... | (self):
""" Constructor: add description to argparser. """
BaseCmdLineTool.__init__(self)
self.argparser.description = 'Performs a health check on config servers and compares them for inconsistencies.'
self.argparser.add_argument('config', action='store', nargs='*', metavar='URI', defau... | __init__ | identifier_name |
mconfcheck.py | from pymongo import MongoClient, ASCENDING
from bson.min_key import MinKey
from bson.max_key import MaxKey
from bson import ObjectId, Timestamp
from chunk import Chunk
from chunk_distribution import ChunkDistribution
from config_parser import ConfigParser
from copy import copy, deepcopy
from dateutil import parser
f... | # check if the chunk distributions disagree on the chunks collection
if not all_equal( chunk_dists ):
diff_found = True
chunk_len = len( str(dict(zip(chunk_dists[0][0].shardkey_fields, chunk_dists[0][0].max))) )
shorturi_len = max(shorturi_len, chu... | print collection, '\n'
chunk_dists = [ parser.get_chunk_distribution(collection) for parser in config_parsers ]
diff_found = False
| random_line_split |
mconfcheck.py | from pymongo import MongoClient, ASCENDING
from bson.min_key import MinKey
from bson.max_key import MaxKey
from bson import ObjectId, Timestamp
from chunk import Chunk
from chunk_distribution import ChunkDistribution
from config_parser import ConfigParser
from copy import copy, deepcopy
from dateutil import parser
f... |
if __name__ == '__main__':
tool = MConfCheckTool()
tool.run() | chunk_dist_generators = [ parser.walk_distributions(collection) for parser in config_parsers ]
# get first element of each generator
current_chunk_dists = [ generator.next() for generator in chunk_dist_generators ]
while not all_equal( current_chunk_dist... | conditional_block |
login.js | var fnObj = {};
var ACTIONS = axboot.actionExtend(fnObj, {
PAGE_SEARCH: function (caller, act, data) {
axboot.ajax({
type: "GET",
url: ["samples", "parent"],
data: caller.searchView.getData(),
callback: function (res) {
caller.gridView01.setDat... | last");
}
}); | .target.addRow({__created__: true}, " | conditional_block |
login.js | var fnObj = {};
var ACTIONS = axboot.actionExtend(fnObj, {
PAGE_SEARCH: function (caller, act, data) {
axboot.ajax({
type: "GET",
url: ["samples", "parent"],
data: caller.searchView.getData(),
callback: function (res) {
caller.gridView01.setDat... |
}
});
}
});
//== view 시작
/**
* searchView
*/
fnObj.searchView = axboot.viewExtend(axboot.searchView, {
initView: function () {
this.target = $(document["searchView0"]);
this.target.attr("onsubmit", "return ACTIONS.dispatch(ACTIONS.PAGE_SEARCH);");
this.filter = $(... | "save": function () {
ACTIONS.dispatch(ACTIONS.PAGE_SAVE);
},
"excel": function () { | random_line_split |
details.component.ts | // Copyright 2020 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
}
}
| {
const value = JSON.stringify(JSON.parse(this.leaderboard.metadata), null, 2);
this.aceEditor.session.setValue(value);
} | conditional_block |
details.component.ts | // Copyright 2020 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... | err => {
this.error = err;
});
}
ngAfterViewInit(): void {
ace.config.set('fontSize', '14px');
ace.config.set('printMarginColumn', 0);
ace.config.set('useWorker', true);
ace.config.set('highlightSelectedWord', true);
ace.config.set('fontFamily', '"Courier New", Courier, mono... | ngOnInit(): void {
this.route.parent.data.subscribe(
d => {
this.leaderboard = d[0];
}, | random_line_split |
details.component.ts | // Copyright 2020 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... | (): void {
ace.config.set('fontSize', '14px');
ace.config.set('printMarginColumn', 0);
ace.config.set('useWorker', true);
ace.config.set('highlightSelectedWord', true);
ace.config.set('fontFamily', '"Courier New", Courier, monospace');
this.aceEditor = ace.edit(this.editor.nativeElement);
th... | ngAfterViewInit | identifier_name |
get.controller.js | 'use strict';
var Bluebird = require('bluebird');
var _ = require('lodash');
var debug = require('debug')('oradbpm:ctrl:get');
var Queue = require('queue-fifo');
var promiseWhile = require('promise-while')(Bluebird);
var error = require('./../../common/error.js');
var PackageDependencyTreeModel = require('./../../mo... | })
.then(function () {
// TODO: download to oradb_modules folder
//console.log(JSON.stringify(deploymentPlan.logPlan()));
deploymentPlan.logPlan();
return Bluebird.resolve();
})
.then(function () {
// TODO: write to file if --save/--save-dev
return Bluebird.resolve();... | })
.then(function () {
//debug(JSON.stringify(packageDependencyTreeRoot.removeCycles()));
return deploymentPlan.resolveConflicts(); | random_line_split |
get.controller.js | 'use strict';
var Bluebird = require('bluebird');
var _ = require('lodash');
var debug = require('debug')('oradbpm:ctrl:get');
var Queue = require('queue-fifo');
var promiseWhile = require('promise-while')(Bluebird);
var error = require('./../../common/error.js');
var PackageDependencyTreeModel = require('./../../mo... | else {
var nearestGlobalNode = nodeToProcess.getNearestGlobal();
deploymentPlan
// run sql and plsql packages in nearest global package
// add deployment to nearest global schema
.getSchema(nearestGlobalNode.packageVersionDefinition.name, nearestGlobalNode.packageVersionDefini... | {
// do not add to deploymentPlan as it is used only on client side and stored within package, that required it as its dependency
//deploymentPlan
// .getSchema(nodeToProcess.packageVersionDefinition.name, nodeToProcess.packageVersionDefinition.version)
// .addProposal(
// n... | conditional_block |
animation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use incremental::R... | {
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if let Some(ref animations) = animations.get(&fragment.node) {
for animation in *animations {
update_style_for_animation(animation, &mut fragment.style, Some(&mut damage));
}
... | identifier_body | |
animation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use incremental::R... | (constellation_chan: &ConstellationChan<ConstellationMsg>,
running_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
expired_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
new_animations_receiver: &Receiver<Animation>,
... | update_animation_state | identifier_name |
animation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use incremental::R... | use time;
/// Processes any new animations that were discovered after style recalculation.
/// Also expire any old animations that have completed, inserting them into `expired_animations`.
pub fn update_animation_state(constellation_chan: &ConstellationChan<ConstellationMsg>,
running_anim... | use script_traits::LayoutMsg as ConstellationMsg;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::mpsc::Receiver;
use style::animation::{Animation, update_style_for_animation}; | random_line_split |
animation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use incremental::R... |
}
for key in keys_to_remove {
running_animations.remove(&key).unwrap();
}
// Add new running animations.
for new_running_animation in new_running_animations {
match running_animations.entry(new_running_animation.node) {
Entry::Vacant(entry) => {
entry.in... | {
*running_animations = animations_still_running
} | conditional_block |
font.rs | ype::FT_Sfnt_Tag;
use freetype::tt_os2::TT_OS2;
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use std::{mem, ptr};
use std::os::raw::{c_char, c_long};
use std::sync::Arc;
use style::computed_values::font_stretch::T as FontStretch;
use style::computed_values::font_weight::... |
fn glyph_h_advance(&self, glyph: GlyphId) -> Option<FractionalPixel> {
assert!(!self.face.is_null());
unsafe {
let res = FT_Load_Glyph(self.face,
glyph as FT_UInt,
GLYPH_LOAD_FLAGS);
if res.succeeded... | {
self.can_do_fast_shaping
} | identifier_body |
font.rs | ype::FT_Sfnt_Tag;
use freetype::tt_os2::TT_OS2;
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use std::{mem, ptr};
use std::os::raw::{c_char, c_long};
use std::sync::Arc;
use style::computed_values::font_stretch::T as FontStretch;
use style::computed_values::font_weight::... | handle: FontContextHandle,
can_do_fast_shaping: bool,
}
impl Drop for FontHandle {
fn drop(&mut self) {
assert!(!self.face.is_null());
unsafe {
if !FT_Done_Face(self.face).succeeded() {
panic!("FT_Done_Face failed");
}
}
}
}
impl FontHand... | random_line_split | |
font.rs | is created using FT_Memory_Face.
font_data: Arc<FontTemplateData>,
face: FT_Face,
handle: FontContextHandle,
can_do_fast_shaping: bool,
}
impl Drop for FontHandle {
fn drop(&mut self) {
assert!(!self.face.is_null());
unsafe {
if !FT_Done_Face(self.face).succeeded() {
... | set_char_size | identifier_name | |
font.rs | ype::FT_Sfnt_Tag;
use freetype::tt_os2::TT_OS2;
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use std::{mem, ptr};
use std::os::raw::{c_char, c_long};
use std::sync::Arc;
use style::computed_values::font_stretch::T as FontStretch;
use style::computed_values::font_weight::... | else {
default_weight
}
} else {
default_weight
}
}
}
}
fn stretchiness(&self) -> FontStretch {
// TODO(pcwalton): Implement this.
FontStretch::Normal
}
fn glyph_index(&s... | {
FontWeight::from_int(weight / 100 * 100).unwrap()
} | conditional_block |
builder.py | from scapy.all import *
from scapy.layers import dhcp6
from time import time
def duid(ll_addr):
return DUID_LLT(lladdr=ll_addr, timeval=time())
def ias(requested, iface, T1=None, T2=None):
return map(lambda r: __build_ia(r, iface, T1, T2), requested)
def options(requested):
return map(__build_option_by_... | return opt
def __option_klass_by_code(code):
return getattr(dhcp6, dhcp6.dhcp6opts_by_code[code]) | elif isinstance(opt, DHCP6OptSNTPServers):
opt.sntpservers.append('2001:500:88:200::10')
| random_line_split |
builder.py | from scapy.all import *
from scapy.layers import dhcp6
from time import time
def duid(ll_addr):
return DUID_LLT(lladdr=ll_addr, timeval=time())
def ias(requested, iface, T1=None, T2=None):
return map(lambda r: __build_ia(r, iface, T1, T2), requested)
def options(requested):
return map(__build_option_by_... |
elif isinstance(opt, DHCP6OptDNSServers):
opt.dnsservers.append('2001:500:88:200::10')
elif isinstance(opt, DHCP6OptSNTPServers):
opt.sntpservers.append('2001:500:88:200::10')
return opt
def __option_klass_by_code(code):
return getattr(dhcp6, dhcp6.dhcp6opts_by_code[code])
| pass | conditional_block |
builder.py | from scapy.all import *
from scapy.layers import dhcp6
from time import time
def duid(ll_addr):
return DUID_LLT(lladdr=ll_addr, timeval=time())
def ias(requested, iface, T1=None, T2=None):
return map(lambda r: __build_ia(r, iface, T1, T2), requested)
def options(requested):
return map(__build_option_by_... | (code):
return getattr(dhcp6, dhcp6.dhcp6opts_by_code[code])
| __option_klass_by_code | identifier_name |
builder.py | from scapy.all import *
from scapy.layers import dhcp6
from time import time
def duid(ll_addr):
return DUID_LLT(lladdr=ll_addr, timeval=time())
def ias(requested, iface, T1=None, T2=None):
return map(lambda r: __build_ia(r, iface, T1, T2), requested)
def options(requested):
return map(__build_option_by_... |
def __option_klass_by_code(code):
return getattr(dhcp6, dhcp6.dhcp6opts_by_code[code])
| opt = __option_klass_by_code(code)()
if isinstance(opt, DHCP6OptClientFQDN):
opt.fqdn = 'testhost.local.'
elif isinstance(opt, DHCP6OptDNSDomains):
pass
elif isinstance(opt, DHCP6OptDNSServers):
opt.dnsservers.append('2001:500:88:200::10')
elif isinstance(opt, DHCP6OptSNTPServer... | identifier_body |
test_auto_TCorrelate.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import TCorrelate
def | ():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
num_threads=dict(nohash=True,
usedefault=True,
),
out_file=dict(argstr='-prefix %s',
name_source='xset',
name_templa... | test_TCorrelate_inputs | identifier_name |
test_auto_TCorrelate.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import TCorrelate
def test_TCorrelate_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedef... |
def test_TCorrelate_outputs():
output_map = dict(out_file=dict(),
)
outputs = TCorrelate.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value | conditional_block |
test_auto_TCorrelate.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import TCorrelate
def test_TCorrelate_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedef... | ),
yset=dict(argstr='%s',
copyfile=False,
mandatory=True,
position=-1,
),
)
inputs = TCorrelate.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def t... | copyfile=False,
mandatory=True,
position=-2, | random_line_split |
test_auto_TCorrelate.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import TCorrelate
def test_TCorrelate_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedef... | output_map = dict(out_file=dict(),
)
outputs = TCorrelate.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value | identifier_body | |
gwcred.py | ###
# Copyright (c) 2005, Ali Afshar
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, a... |
class SBPortal(portal.Portal):
pass
class SBRealm:
__implements__ = portal.IRealm
def __init__(self, userclass):
self.userclass = userclass
def requestAvatar(self, avatarId, mind, *interfaces):
self.cb.cb.log.critical('%s', interfaces)
av = self.userclass(avatarId)
... | random_line_split | |
gwcred.py | ###
# Copyright (c) 2005, Ali Afshar
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, a... |
class SBPublicKeyChecker(object):
""" Public key checker """
__implements__ = (checkers.ICredentialsChecker,)
credentialInterfaces = (ISSHPrivateKey,)
def requestAvatarId(self, credentials):
a = self.cb.getUser(protocol=self.cb.PROTOCOL,
username=credentials.username,
... | return failure.Failure(error.UnauthorizedLogin()) | conditional_block |
gwcred.py | ###
# Copyright (c) 2005, Ali Afshar
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, a... |
class SBPublicKeyChecker(object):
""" Public key checker """
__implements__ = (checkers.ICredentialsChecker,)
credentialInterfaces = (ISSHPrivateKey,)
def requestAvatarId(self, credentials):
a = self.cb.getUser(protocol=self.cb.PROTOCOL,
username=credentials.username,
... | self.cb.log.debug('twisted checker checking %s',
credentials.username)
""" Return an avatar id or return an error """
a = self.cb.getUser(protocol=self.cb.PROTOCOL,
username=credentials.username,
password=credentials.password,
peer=credentials.peer)
if a:
... | identifier_body |
gwcred.py | ###
# Copyright (c) 2005, Ali Afshar
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, a... | (object):
""" Public key checker """
__implements__ = (checkers.ICredentialsChecker,)
credentialInterfaces = (ISSHPrivateKey,)
def requestAvatarId(self, credentials):
a = self.cb.getUser(protocol=self.cb.PROTOCOL,
username=credentials.username,
bl... | SBPublicKeyChecker | identifier_name |
classify.py | # Load pickled data
import pickle
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
import tensorflow as tf
from tensorflow.contrib.layers import flatten
from sklearn.utils import shuffle
class Data:
def __init__(self):
training_file = 'data/train.p'
... |
saver.save(sess, './lenet')
print("Model saved")
if __name__ == "__main__":
main()
| X_train, y_train = shuffle(data.X_train, data.y_train)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train[offset:end], y_train[offset:end]
sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
... | conditional_block |
classify.py | # Load pickled data
import pickle
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
import tensorflow as tf
from tensorflow.contrib.layers import flatten
from sklearn.utils import shuffle
class Data:
def __init__(self):
training_file = 'data/train.p'
... | ():
data = Data()
EPOCHS = 10
BATCH_SIZE = 128
max_classified_id = np.max(data.y_train)
saver, training_operation, accuracy_operation, x, y = train(max_classified_id)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
num_examples = len(data.X_train)
... | main | identifier_name |
classify.py | # Load pickled data
import pickle
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
import tensorflow as tf
from tensorflow.contrib.layers import flatten
from sklearn.utils import shuffle
class Data:
def __init__(self):
training_file = 'data/train.p'
... | for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
total_accuracy += (accuracy * len(batch_x))
return total_accuracy / num_exam... | def evaluate(x, y, X_data, y_data, accuracy_operation, BATCH_SIZE):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session() | random_line_split |
classify.py | # Load pickled data
import pickle
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
import tensorflow as tf
from tensorflow.contrib.layers import flatten
from sklearn.utils import shuffle
class Data:
def __init__(self):
training_file = 'data/train.p'
... |
plt.show()
def LeNet(x, max_labels):
# Hyper parameters
mu = 0
sigma = 0.1
# Convolutional Layer 1: Input = 32x32x3 Output = 28x28x6
conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 6), mean=mu, stddev=sigma), name="v1")
conv1_b = tf.Variable(tf.zeros(6), name="v2")
... | image_with_label = zip(self.X_train, self.y_train)
seen_labels = set()
fig = plt.figure(figsize=(200, 200))
total_unique_labels = len(set(self.y_train))
unique_rows = total_unique_labels // 5 + 1
grid = ImageGrid(fig, 151, # similar to subplot(141)
nrow... | identifier_body |
unsendable-class.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (i:int, j: Gc<String>) -> foo {
foo {
i: i,
j: j
}
}
fn main() {
let cat = "kitty".to_string();
let (tx, _) = channel(); //~ ERROR `core::kinds::Send` is not implemented
tx.send(foo(42, box(GC) (cat))); //~ ERROR `core::kinds::Send` is not implemented
}
| foo | identifier_name |
unsendable-class.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let cat = "kitty".to_string();
let (tx, _) = channel(); //~ ERROR `core::kinds::Send` is not implemented
tx.send(foo(42, box(GC) (cat))); //~ ERROR `core::kinds::Send` is not implemented
}
| {
foo {
i: i,
j: j
}
} | identifier_body |
unsendable-class.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that a class with an unsendable field can't be
// sent
use std::gc::{Gc, GC};
... | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
credit-card.ts | uhn: boolean;
}
const cards: CardDefinition[] = [
{
type: 'maestro',
patterns: [5018, 502, 503, 506, 56, 58, 639, 6220, 67],
format: defaultFormat,
length: [12, 13, 14, 15, 16, 17, 18, 19],
cvvLength: [3],
luhn: true,
}, {
type: 'forbrugsforeningen',
patterns: [600],
format: def... | public static cardType(num: string) {
if (!num) {
return num;
}
const card = this.cardFromNumber(num);
if (card !== null && typeof card !== 'undefined') {
return card.type;
} else {
return null;
}
}
public static formatCardNumber(num: string) {
num = num.replace(/\... |
public static hasTextSelected(target: HTMLInputElement) {
return target.selectionStart !== null && target.selectionStart !== target.selectionEnd;
}
| random_line_split |
credit-card.ts | uhn: boolean;
}
const cards: CardDefinition[] = [
{
type: 'maestro',
patterns: [5018, 502, 503, 506, 56, 58, 639, 6220, 67],
format: defaultFormat,
length: [12, 13, 14, 15, 16, 17, 18, 19],
cvvLength: [3],
luhn: true,
}, {
type: 'forbrugsforeningen',
patterns: [600],
format: def... | (num: string) {
num = num.replace(/\D/g, '');
const card = this.cardFromNumber(num);
if (!card) {
return num;
}
const upperLength = card.length[card.length.length - 1];
num = num.slice(0, upperLength);
if (card.format.global) {
const matches = num.match(card.format);
if ... | formatCardNumber | identifier_name |
credit-card.ts | uhn: boolean;
}
const cards: CardDefinition[] = [
{
type: 'maestro',
patterns: [5018, 502, 503, 506, 56, 58, 639, 6220, 67],
format: defaultFormat,
length: [12, 13, 14, 15, 16, 17, 18, 19],
cvvLength: [3],
luhn: true,
}, {
type: 'forbrugsforeningen',
patterns: [600],
format: def... |
public static luhnCheck(num: string) {
const digits = num.split('').reverse();
let odd = | {
const digit = String.fromCharCode(key);
if (!/^\d+$/.test(digit) || this.hasTextSelected(target)) {
return false;
}
const val = `${target.value}${digit}`;
return val.length <= 4;
} | identifier_body |
credit-card.ts | uhn: boolean;
}
const cards: CardDefinition[] = [
{
type: 'maestro',
patterns: [5018, 502, 503, 506, 56, 58, 639, 6220, 67],
format: defaultFormat,
length: [12, 13, 14, 15, 16, 17, 18, 19],
cvvLength: [3],
luhn: true,
}, {
type: 'forbrugsforeningen',
patterns: [600],
format: def... |
const val = `${target.value}${digit}`;
return val.length <= 4;
}
public static luhnCheck(num: string) {
const digits = num.split('').reverse();
let odd = | {
return false;
} | conditional_block |
utils.py | 'False' if error_msg else 'True',
)
mail.add_header(
X_SIGNATURE_MESSAGE_HEADER,
u'Invalid: {0}'.format(error_msg)
if error_msg else
u'Valid: {0}'.format(sig_from),
)
def get_params(mail, failobj=list(), header='content-type', unquote=True):
'''Get Content-Type... | '''Add pseudo headers to the mail indicating whether the signature
verification was successful.
:param mail: :class:`email.message.Message` the message to entitle
:param sigs: list of :class:`gpgme.Signature`
:param error_msg: `str` containing an error message, the empty
string in... | identifier_body | |
utils.py | # make sure noone smuggles a token in (data from m is untrusted)
del m[X_SIGNATURE_VALID_HEADER]
del m[X_SIGNATURE_MESSAGE_HEADER]
p = get_params(m)
app_pgp_sig = 'application/pgp-signature'
app_pgp_enc = 'application/pgp-encrypted'
# handle OpenPGP signed data
if (m.is_multipart() and
... | decode_header | identifier_name | |
utils.py | ,
u'Invalid: {0}'.format(error_msg)
if error_msg else
u'Valid: {0}'.format(sig_from),
)
def get_params(mail, failobj=list(), header='content-type', unquote=True):
'''Get Content-Type parameters as dict.
RFC 2045 specifies that parameter names are case-insensitive, so
we normal... |
if malformed:
msg = u'Malformed OpenPGP message: {0}'.format(malformed)
content = email.message_from_string(msg.encode('utf-8'))
content.set_charset('utf-8')
m.attach(content)
return m
def message_from_string(s):
'''Reads a mail from the given string.... | add_signature_headers(m, sigs, '') | conditional_block |
utils.py | _HEADER,
u'Invalid: {0}'.format(error_msg)
if error_msg else
u'Valid: {0}'.format(sig_from),
)
def get_params(mail, failobj=list(), header='content-type', unquote=True):
'''Get Content-Type parameters as dict.
RFC 2045 specifies that parameter names are case-insensitive, so
we... | # see if the mail has our preferred type
if types is None:
has_preferred = list(typed_subpart_iterator(
mail, *preferred.split('/')))
body_parts = []
for part in mail.walk():
ctype = part.get_content_type()
if types is not None:
if ctype not in types:
... | has_preferred = False
| random_line_split |
mod.rs | //! Implements a wrapper struct container for internal getter.
#[cfg(test)]
mod test {
use { Getter, Factory, AsFactoryExt };
use std::any::Any;
#[test]
fn should_get_correct_value() {
let factory = create_with_val("HAI");
assert_eq!(factory.take(), "HAI");
}
#[test]
fn c... | () {
let boxany = box create_with_val("HAI") as Box<Any>;
let downcasted = boxany.as_factory_of::<String>().unwrap();
assert_eq!(downcasted.take(), "HAI");
}
fn create_with_val(val: &str) -> Factory<String> {
Factory::new(box ValContainer { val: val.to_string() })
}
st... | should_be_able_to_downcast_from_any | identifier_name |
mod.rs | //! Implements a wrapper struct container for internal getter.
#[cfg(test)]
mod test {
use { Getter, Factory, AsFactoryExt };
use std::any::Any;
#[test]
fn should_get_correct_value() {
let factory = create_with_val("HAI");
assert_eq!(factory.take(), "HAI");
}
#[test]
fn c... |
}
}
| {
box ValContainer {
val: self.val.clone(),
}
} | identifier_body |
mod.rs | //! Implements a wrapper struct container for internal getter.
#[cfg(test)]
mod test {
use { Getter, Factory, AsFactoryExt };
use std::any::Any;
#[test]
fn should_get_correct_value() {
let factory = create_with_val("HAI"); | assert_eq!(factory.take(), "HAI");
}
#[test]
fn cloned_factory_should_get_the_same_value() {
let factory = create_with_val("HAI");
assert_eq!(factory.clone().take(), factory.take());
}
#[test]
fn should_be_able_to_downcast_from_any() {
let boxany = box create_w... | random_line_split | |
ctaFollow.js | "use strict";
var userUtils = require("../../lib/user-utils.js");
module.exports = function(core, config, store) {
core.on("setstate", function(changes) {
var future = store.with(changes),
userId = future.get("user"),
roomId = future.get("nav", "room"),
mode = future.get("nav", "mode"),
cta = future.ge... | !(roomObj && roomObj.guides && roomObj.guides.authorizer && roomObj.guides.authorizer.openRoom === false)) {
changes.app.cta = "follow";
} else if (cta === "follow") {
changes.app.cta = null;
}
}, 400);
}; | changes.app = changes.app || {};
if (roomObj === "missing") {
changes.app.cta = null;
} else if (userId && !userUtils.isGuest(userId) && ((/(visitor|none)/).test(role) || !role) && (/(chat|room)/).test(mode) && | random_line_split |
mbc1.rs | use enum_primitive::FromPrimitive;
use log::{warn, error};
use super::Mapper;
struct BankSelection(u8);
impl BankSelection {
fn set_mode(&mut self, mode: BankMode) {
self.0 = (self.0 & 0b0111_1111) | ((mode as u8) << 7)
}
fn mode(&self) -> BankMode {
BankMode::from_u8((self.0 & 0b1000_000... |
fn upper(&self) -> u8 {
(self.0 & 0b0110_0000) >> 5
}
fn set_lower(&mut self, val: u8) {
self.0 = (self.0 & 0b1110_0000) | (val & 0b0001_1111);
}
fn lower(&self) -> u8 {
self.0 & 0b0001_1111
}
fn rom_bank(&self) -> usize {
let bank = if self.mode() == Ban... | {
self.0 = (self.0 & 0b1001_1111) | ((val << 5) & 0b0110_0000);
} | identifier_body |
mbc1.rs | use enum_primitive::FromPrimitive;
use log::{warn, error};
use super::Mapper;
struct BankSelection(u8);
impl BankSelection {
fn set_mode(&mut self, mode: BankMode) {
self.0 = (self.0 & 0b0111_1111) | ((mode as u8) << 7)
}
fn mode(&self) -> BankMode {
BankMode::from_u8((self.0 & 0b1000_000... | ,
_ => {
error!("Address {:#X} not handled by MBC1", addr);
0xFF
}
}
}
fn write(&mut self, addr: u16, val: u8) {
match addr {
0x0000..=0x1FFF => {
// Writing to this space toggles RAM
// Any val... | {
// Switchable RAM bank
if self.ram_enabled {
self.ram_data[self.ram_index(addr)]
} else {
warn!("Attempted read from RAM address {:X} while RAM is disabled.", addr);
0xFF
}
} | conditional_block |
mbc1.rs | use enum_primitive::FromPrimitive;
use log::{warn, error};
use super::Mapper;
struct BankSelection(u8);
impl BankSelection {
fn set_mode(&mut self, mode: BankMode) {
self.0 = (self.0 & 0b0111_1111) | ((mode as u8) << 7)
}
fn mode(&self) -> BankMode {
BankMode::from_u8((self.0 & 0b1000_000... | } else {
self.ram_data[index] = val;
}
}
},
_ => error!("Attempted to write to address {:#X} not handled by MBC1", addr)
}
}
} | if self.ram_enabled {
let index = self.ram_index(addr);
if index >= self.ram_data.len() {
warn!("Attempted to write to out-of-bounds MBC1 RAM index {}, addr {:X}.", index, addr); | random_line_split |
mbc1.rs | use enum_primitive::FromPrimitive;
use log::{warn, error};
use super::Mapper;
struct | (u8);
impl BankSelection {
fn set_mode(&mut self, mode: BankMode) {
self.0 = (self.0 & 0b0111_1111) | ((mode as u8) << 7)
}
fn mode(&self) -> BankMode {
BankMode::from_u8((self.0 & 0b1000_0000) >> 7).unwrap()
}
fn set_upper(&mut self, val: u8) {
self.0 = (self.0 & 0b1001_1... | BankSelection | identifier_name |
joypad.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... | (&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:08b}", !self.register.bits)
}
}
impl LowerHex for Joypad {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:02x}", !self.register.bits)
}
}
impl UpperHex for Joypad {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{... | fmt | identifier_name |
joypad.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... |
}
impl LowerHex for Joypad {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:02x}", !self.register.bits)
}
}
impl UpperHex for Joypad {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:02X}", !self.register.bits)
}
}
bitflags!(
/// P1 register
///
/// Bits are invert... | {
write!(f, "{:08b}", !self.register.bits)
} | identifier_body |
joypad.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... | _ => P1::empty(),
}
}
fn button(key: &GbKey) -> P1 {
match *key {
GbKey::A => P1::P10,
GbKey::B => P1::P11,
GbKey::Select => P1::P12,
GbKey::Start => P1::P13,
_ => P1::empty(),
}
}
} | GbKey::Down => P1::P13, | random_line_split |
prefs.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use basedir::default_config_dir;
use opts;
use resource_files::resources_dir_path;
use rustc_serialize::json::{Jso... |
pub fn as_i64(&self) -> Option<i64> {
match *self {
PrefValue::Number(x) => Some(x as i64),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match *self {
PrefValue::Number(x) => Some(x as u64),
_ => None,
}
}
}
impl... | {
match *self {
PrefValue::String(ref value) => {
Some(&value)
},
_ => None
}
} | identifier_body |
prefs.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use basedir::default_config_dir;
use opts;
use resource_files::resources_dir_path;
use rustc_serialize::json::{Jso... | (&self, name: &str, value: PrefValue) {
let mut prefs = self.0.write().unwrap();
if let Some(pref) = prefs.get_mut(name) {
pref.set(value);
return;
}
prefs.insert(name.to_owned(), Pref::new(value));
}
pub fn reset(&self, name: &str) -> Arc<PrefValue> {
... | set | identifier_name |
prefs.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use basedir::default_config_dir;
use opts;
use resource_files::resources_dir_path;
use rustc_serialize::json::{Jso... | Pref::WithDefault(ref default, ref override_value) => {
match *override_value {
Some(ref x) => x,
None => default
}
}
}
}
fn set(&mut self, value: PrefValue) {
// TODO - this should error if we try t... | random_line_split | |
app-users.ts | import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
import { Observable } from "rxjs/Observable";
//Import our providers
import { AppSettings } from '../../providers/app-settings/app-settings';
/*
Generated class for the AppUsers provider.
See https://angula... |
//Gets the user by their facebook id
getUserById(userId, token: any) {
if(!token) {
//Grab our user from localstorage
let user = JSON.parse(localStorage.getItem(AppSettings.shushItemName));
token = user.access_token;
}
//Our headers
let headers = new Headers({
access_toke... | { } | identifier_body |
app-users.ts | import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
import { Observable } from "rxjs/Observable";
//Import our providers
import { AppSettings } from '../../providers/app-settings/app-settings';
/*
Generated class for the AppUsers provider.
See https://angula... |
//Call our friend edit
return this.editFriend('user/friend/accept', userId);
}
//Decline a pending friend
declineFriend(userId) {
//Call our friend edit
return this.editFriend('user/friend/decline', userId);
}
//Delete a current friend
deleteFriend(userId) {
//Call our friend edit... | random_line_split | |
app-users.ts | import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
import { Observable } from "rxjs/Observable";
//Import our providers
import { AppSettings } from '../../providers/app-settings/app-settings';
/*
Generated class for the AppUsers provider.
See https://angula... | {
constructor(private http: Http) { }
//Gets the user by their facebook id
getUserById(userId, token: any) {
if(!token) {
//Grab our user from localstorage
let user = JSON.parse(localStorage.getItem(AppSettings.shushItemName));
token = user.access_token;
}
//Our headers
let ... | AppUsers | identifier_name |
BrightContrastFilter.rs | #pragma version(1)
#pragma rs java_package_name(cn.louispeng.imagefilter.renderscript)
// 高亮对比度特效
#include "Clamp.rsh"
// set from the java SDK level
rs_allocation gIn;
rs_allocation gOut;
rs_script gScript;
// The brightness factor.
// Should be in the range [-1.0f, 1.0f].
float gBrightnessFactor = 0.25f;
// The... |
// Modifiy contrast (multiplication)
if (ContrastFactor1 != 1.0f){
// Transform to range [-0.5f, 0.5f]
f3 = f3 - 0.5f;
// Multiply contrast factor
f3 = f3 * ContrastFactor1;
// Transform back to range [0.0f, 1.0f]
f3 = f3 + 0.5f;
f3 = FClamp01Float3(f3);
}
*v_out = ... | f3 = FClamp01Float3(f3);
} | random_line_split |
mnist.py | # Copyright 2016 Anonymous researcher(s)
# This file is part of BinaryNet.
# BinaryNet 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 ... | train_fn,val_fn,
mlp,
batch_size,
LR_start,LR_decay,
num_epochs,
train_set.X,train_set.y,
valid_set.X,valid_set.y,
test_set.X,test_set.y,
save_path,
shuffle_parts) |
binary_net.train(
| random_line_split |
mnist.py | # Copyright 2016 Anonymous researcher(s)
# This file is part of BinaryNet.
# BinaryNet 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 ... |
else:
params = lasagne.layers.get_all_params(mlp, trainable=True)
updates = lasagne.updates.adam(loss_or_grads=loss, params=params, learning_rate=LR)
test_output = lasagne.layers.get_output(mlp, deterministic=True)
test_loss = T.mean(T.sqr(T.maximum(0.,1.-target*test_output... | W = lasagne.layers.get_all_params(mlp, binary=True)
W_grads = binary_net.compute_grads(loss,mlp)
updates = lasagne.updates.adam(loss_or_grads=W_grads, params=W, learning_rate=LR)
updates = binary_net.clipping_scaling(updates,mlp)
# other parameters updates
params =... | conditional_block |
recipe.service.ts | import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable'; | import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { TdmCocktailRecipe } from 'tdm-common';
@Injectable()
export class RecipeService {
// @see https://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/
// This is to prevent the ser... | import 'rxjs/add/operator/do'; | random_line_split |
recipe.service.ts | import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { TdmCocktailRecipe } from ... | (error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
| handleError | identifier_name |
recipe.service.ts | import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { TdmCocktailRecipe } from ... |
getRecipeCount(): Observable<number>{
let url = this.recipesUrl+'/count';
return this.http.get(url).map((obj: any)=>{
return obj.count;
})
}
getRecipeLimit(): Observable<number>{
let url = this.recipesUrl+'/limit';
return this.http.get(url).map((obj: an... | {
this.http.delete(this.recipesUrl + "/" + recipe.id, {
responseType: 'text',
}).subscribe(response => {
this.updateRecipes();
});
} | identifier_body |
index.test.tsx | import * as React from 'react'
import * as R from 'ramda'
import { mount } from 'enzyme'
import { expect } from 'chai'
import { klass } from '~/components/TestHelper'
import { AutomatedPOS } from './index'
const s = require('./style.css')
const txt = 'This is a sentence.'
const component = mount(<A... | })
}) | random_line_split | |
spiderForTECHORANGE.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
from selenium import webdriver
import os
import time
import logging
import re
import random
from cameo.utility import Utility
from... | 使用資訊
def getUseageMessage(self):
return ("- TECHORANGE -\n"
"useage:\n"
"index - download entry page of TECHORANGE \n"
"tag - download not obtained tag page \n"
"news [tag] - download not obtained news [of given tag] \n")
#取得 selenium... | LDER_PATH = u"cameo_res\\source_html"
self.PARSED_RESULT_BASE_FOLDER_PATH = u"cameo_res\\parsed_result"
self.strWebsiteDomain = u"http://buzzorange.com/techorange"
self.dicSubCommandHandler = {
"index":self.downloadIndexPage,
"tag":self.downloadTagPag,
"news":... | identifier_body |
spiderForTECHORANGE.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
from selenium import webdriver
import os
import time
import logging
import re
import random
from cameo.utility import Utility
from... | GivenTagName(strTagName=strObtainedTagName)
else:
#有指定 tag 名稱
self.downloadNewsPageWithGivenTagName(strTagName=strTagName)
#下載 news 頁面 (指定 tag 名稱)
def downloadNewsPageWithGivenTagName(self, strTagName=None):
logging.info("download news page with tag %s"%strTa... | loadNewsPageWith | identifier_name |
spiderForTECHORANGE.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
from selenium import webdriver
import os
import time
import logging
import re
import random
from cameo.utility import Utility
from... | class SpiderForTECHORANGE:
#建構子
def __init__(self):
self.SOURCE_HTML_BASE_FOLDER_PATH = u"cameo_res\\source_html"
self.PARSED_RESULT_BASE_FOLDER_PATH = u"cameo_res\\parsed_result"
self.strWebsiteDomain = u"http://buzzorange.com/techorange"
self.dicSubCommandHandler = {
... | random_line_split | |
spiderForTECHORANGE.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
from selenium import webdriver
import os
import time
import logging
import re
import random
from cameo.utility import Utility
from... | #未指定 tag
lstStrObtainedTagName = self.db.fetchallCompletedObtainedTagName()
for strObtainedTagName in lstStrObtainedTagName:
self.downloadNewsPageWithGivenTagName(strTagName=strObtainedTagName)
else:
#有指定 tag 名稱
self.downloadNewsPageWithG... | e is None:
| conditional_block |
club.page.ts | import * as Models from "../../../models/models";
import {Component, OnInit} from "@angular/core";
import {AppRoutingService} from "../../../context/router.context";
import {ClubService} from "../../../providers/leagues/clubService";
import {CompetitionCache} from "../../../providers/leagues/competitionCache";
import... | (
private logger: Logger,
private clubService: ClubService,
private context: AppRoutingService,
private cache: CompetitionCache) {
this.logger.Notify("club page started");
}
public list: Observable<Models.IGroup<Models.ICompetitorContext>[]>;
public clubSearch($even... | constructor | identifier_name |
club.page.ts | import * as Models from "../../../models/models";
import {Component, OnInit} from "@angular/core";
import {AppRoutingService} from "../../../context/router.context";
import {ClubService} from "../../../providers/leagues/clubService";
import {CompetitionCache} from "../../../providers/leagues/competitionCache";
import... |
public list: Observable<Models.IGroup<Models.ICompetitorContext>[]>;
public clubSearch($event : any): void {
this.logger.Notify("Search passed to region");
this.logger.Notify($event);
}
public ngOnInit(): void {
this.logger.Notify("club-page ngOnInit");
this.loadDeta... | {
this.logger.Notify("club page started");
} | identifier_body |
club.page.ts | import * as Models from "../../../models/models";
import {Component, OnInit} from "@angular/core";
import {AppRoutingService} from "../../../context/router.context";
import {ClubService} from "../../../providers/leagues/clubService";
import {CompetitionCache} from "../../../providers/leagues/competitionCache";
import... | private logger: Logger,
private clubService: ClubService,
private context: AppRoutingService,
private cache: CompetitionCache) {
this.logger.Notify("club page started");
}
public list: Observable<Models.IGroup<Models.ICompetitorContext>[]>;
public clubSearch($event ... | </nx-drawer>
`
})
export class ClubPage implements OnInit {
constructor( | random_line_split |
knobdemo.module.ts | import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {ButtonModule} from 'primeng/button';
import {PanelModule} from 'primeng/panel';
import {TabViewModule} from 'primeng/tabview';
import {KnobModule} from 'primeng/knob';
import {KnobDe... | {}
| KnobDemoModule | identifier_name |
knobdemo.module.ts | import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {ButtonModule} from 'primeng/button';
import {PanelModule} from 'primeng/panel';
import {TabViewModule} from 'primeng/tabview';
import {KnobModule} from 'primeng/knob';
import {KnobDe... | KnobModule,
AppDemoActionsModule,
AppCodeModule
],
declarations: [
KnobDemo
]
})
export class KnobDemoModule {} | KnobDemoRoutingModule,
ButtonModule,
PanelModule,
TabViewModule,
FormsModule, | random_line_split |
detectors.py | """
Feature detection (Szeliski 4.1.1)
"""
import numpy as np
import scipy.signal as sig
import scipy.ndimage as ndi
from compvis.utils import get_patch
def sum_sq_diff(img_0, img_1, u, x, y, x_len, y_len):
"""
Returns the summed square difference between two image patches, using even
weighting across the... | for u_x, u_y in zip(np.ravel(X), np.ravel(Y))])
surface = s.reshape(X.shape)
return surface, X, Y
def harris(img, sigma_d=1, sigma_i=2, alpha=0.06, filter_type='gaussian'):
"""
Returns the Harris interest scores for corner detection.
Parameters :
img : imag... | """
Returns an auto-correlation surface for an image patch with a given range
of displacements.
Parameters :
img : image
u_x_range, u_y_range : ranges of displacements (tuples)
x, y : coordinates of top-left corner of patch
x_le... | identifier_body |
detectors.py | """
Feature detection (Szeliski 4.1.1)
"""
import numpy as np
import scipy.signal as sig
import scipy.ndimage as ndi
from compvis.utils import get_patch
def sum_sq_diff(img_0, img_1, u, x, y, x_len, y_len):
"""
Returns the summed square difference between two image patches, using even
weighting across the... | I_yy = I_y**2
I_xy = I_x * I_y
# Convolve with Gaussian to get auto-correlation matrix
A_xx = ndi.gaussian_filter(I_xx, sigma_i)
A_yy = ndi.gaussian_filter(I_yy, sigma_i)
A_xy = ndi.gaussian_filter(I_xy, sigma_i)
# Harris scores
A_det = A_xx * A_yy - A_xy**2
A_tr = A_xx + A_yy
... | #---
# Outer products
I_xx = I_x**2 | random_line_split |
detectors.py | """
Feature detection (Szeliski 4.1.1)
"""
import numpy as np
import scipy.signal as sig
import scipy.ndimage as ndi
from compvis.utils import get_patch
def sum_sq_diff(img_0, img_1, u, x, y, x_len, y_len):
"""
Returns the summed square difference between two image patches, using even
weighting across the... | (scores, c_robust):
supp_radii = np.zeros(scores.shape)
# Coordinate with highest score
coord_max = np.unravel_index(scores.argmax(), scores.shape)
for i in range(scores.shape[0]):
for j in range(scores.shape[1]):
score = scores[i, j]
if score == 0:
cont... | get_suppression_radii | identifier_name |
detectors.py | """
Feature detection (Szeliski 4.1.1)
"""
import numpy as np
import scipy.signal as sig
import scipy.ndimage as ndi
from compvis.utils import get_patch
def sum_sq_diff(img_0, img_1, u, x, y, x_len, y_len):
"""
Returns the summed square difference between two image patches, using even
weighting across the... | y1 = j+r+1 if j+r+1 < scores.shape[1] else scores.shape[1]-1
candidates = scores[x0:x1, y0:y1]
# If a significantly stronger neighbour is found
if np.count_nonzero(score < c_robust*candidates):
r_found = True
break
... | for j in range(scores.shape[1]):
score = scores[i, j]
if score == 0:
continue
# Skip the highest score (infinite suppression radius)
if (i, j) == coord_max:
continue
# Find suppression radius
r = 0
r_fo... | conditional_block |
issue-2735-3.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
#[unsafe_destructor]
impl<'a> Drop for defer<'a> {
fn drop(&mut self) {
self.b.set(true);
}
}
fn defer(b: &Cell<bool>) -> defer {
defer {
b: b
}
}
pub fn main() {
let dtor_ran = &Cell::new(false);
defer(dtor_ran);
assert!(dtor_ran.get());
} | b: &'a Cell<bool>, | random_line_split |
issue-2735-3.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a> {
b: &'a Cell<bool>,
}
#[unsafe_destructor]
impl<'a> Drop for defer<'a> {
fn drop(&mut self) {
self.b.set(true);
}
}
fn defer(b: &Cell<bool>) -> defer {
defer {
b: b
}
}
pub fn main() {
let dtor_ran = &Cell::new(false);
defer(dtor_ran);
assert!(dtor_ran.get());
}
| defer | identifier_name |
issue-2735-3.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let dtor_ran = &Cell::new(false);
defer(dtor_ran);
assert!(dtor_ran.get());
}
| {
defer {
b: b
}
} | identifier_body |
snoozer-service.js | 'use strict'
/**
* Modules (Electron)
* @constant
*/
const { app, ipcMain } = require('electron')
/**
* Modules (Third party)
* @constant
*/
const logger = require('@sidneys/logger')({ write: true })
const notificationProvider = require('@sidneys/electron-notification-provider')
/**
* Modules (Local)
* @co... | * @public
*/
startSnooze(durationMinutes, menuItem) {
logger.debug('startSnooze')
// Get menuItem state
let isEnabled = menuItem.checked
// Get sibling menuItems
let siblingMenuItemList = menuItem['menu'].items.filter((item) => item.id && item.id.startsWith('snooz... | * | random_line_split |
snoozer-service.js | 'use strict'
/**
* Modules (Electron)
* @constant
*/
const { app, ipcMain } = require('electron')
/**
* Modules (Third party)
* @constant
*/
const logger = require('@sidneys/logger')({ write: true })
const notificationProvider = require('@sidneys/electron-notification-provider')
/**
* Modules (Local)
* @co... |
}
}
/**
* Init
*/
let init = () => {
logger.debug('init')
// Ensure single instance
if (!global.snoozerService) {
global.snoozerService = new SnoozerService()
}
}
/**
* @listens Electron.App#Event:ready
*/
app.once('ready', () => {
logger.debug('app#ready')
init()
})
/**
... | {
this.scheduleSnooze(durationMinutes, menuItem)
} | conditional_block |
snoozer-service.js | 'use strict'
/**
* Modules (Electron)
* @constant
*/
const { app, ipcMain } = require('electron')
/**
* Modules (Third party)
* @constant
*/
const logger = require('@sidneys/logger')({ write: true })
const notificationProvider = require('@sidneys/electron-notification-provider')
/**
* Modules (Local)
* @co... | (isSnoozing) {
logger.debug('onSnooze')
ipcMain.emit('snooze', isSnoozing)
}
/**
* Snooze until indefinitely
*
* @private
*/
infinitySnooze() {
logger.debug('infinitySnooze')
// Set timestamp
this.snoozeUntil = Infinity
// Emit
... | onSnooze | identifier_name |
snoozer-service.js | 'use strict'
/**
* Modules (Electron)
* @constant
*/
const { app, ipcMain } = require('electron')
/**
* Modules (Third party)
* @constant
*/
const logger = require('@sidneys/logger')({ write: true })
const notificationProvider = require('@sidneys/electron-notification-provider')
/**
* Modules (Local)
* @co... |
/**
* Schedule snooze
* @param {Number} durationMinutes - Snooze duration
* @param {Electron.MenuItem} menuItem - Menu item
*
* @private
*/
scheduleSnooze(durationMinutes, menuItem) {
logger.debug('scheduleSnooze')
if (durationMinutes === Infinity) {
... | {
logger.debug('infinitySnooze')
// Set timestamp
this.snoozeUntil = Infinity
// Emit
this.onSnooze(true)
// Notification
const notification = notificationProvider.create({
title: 'Snooze started',
subtitle: 'Snoozing indefinitely.'
... | identifier_body |
rtconfig.py | import os
# toolchains options
ARCH='arm'
CPU='cortex-m4'
CROSS_TOOL='gcc'
# bsp lib config
BSP_LIBRARY_TYPE = None
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
if os.getenv('RTT_ROOT'):
RTT_ROOT = os.getenv('RTT_ROOT')
# cross_tool provides the cross compiler
# EXEC_PATH is the compiler execute... | CFLAGS += ' -e'
CFLAGS += ' --fpu=VFPv4_sp'
CFLAGS += ' --dlib_config "' + EXEC_PATH + '/arm/INC/c/DLib_Config_Normal.h"'
CFLAGS += ' --silent'
AFLAGS = DEVICE
AFLAGS += ' -s+'
AFLAGS += ' -w+'
AFLAGS += ' -r'
AFLAGS += ' --cpu Cortex-M4'
AFLAGS += ' --fpu VFPv4_sp'
AFLAGS +... | CC = 'iccarm'
CXX = 'iccarm'
AS = 'iasmarm'
AR = 'iarchive'
LINK = 'ilinkarm'
TARGET_EXT = 'out'
DEVICE = '-Dewarm'
CFLAGS = DEVICE
CFLAGS += ' --diag_suppress Pa050'
CFLAGS += ' --no_cse'
CFLAGS += ' --no_unroll'
CFLAGS += ' --no_inline'
CFLAGS += ' --no_code_motion'
... | conditional_block |
rtconfig.py | import os
# toolchains options
ARCH='arm'
CPU='cortex-m4'
CROSS_TOOL='gcc'
# bsp lib config
BSP_LIBRARY_TYPE = None
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
if os.getenv('RTT_ROOT'):
RTT_ROOT = os.getenv('RTT_ROOT')
# cross_tool provides the cross compiler
# EXEC_PATH is the compiler execute... | CFLAGS += ' --no_unroll'
CFLAGS += ' --no_inline'
CFLAGS += ' --no_code_motion'
CFLAGS += ' --no_tbaa'
CFLAGS += ' --no_clustering'
CFLAGS += ' --no_scheduling'
CFLAGS += ' --endian=little'
CFLAGS += ' --cpu=Cortex-M4'
CFLAGS += ' -e'
CFLAGS += ' --fpu=VFPv4_sp'
CFLAGS += ' -... | CFLAGS += ' --no_cse' | random_line_split |
sceneParams_0.js | ,
squareness: 0.01,
map: 'white',
landRGB: 13766158,
horizonRGB: 2665099,
skyMap: 'sky1',
},
// sealevel basso
galaxy_glacier: {
cameraPositionY: 50,
seaLevel: -100,
displayText: '<b>CHAPTER FIVE, GALAXY GLACIER</b><br><i>HITTING ... | random_line_split | ||
nico.js | var path = require('path');
var package = require('./package');
var webpack = require('webpack');
var ProgressPlugin = require('webpack/lib/ProgressPlugin');
var inspect = require('util').inspect;
var Busboy = require('busboy');
var chalk = require('chalk');
var webpackMiddleware = require('webpack-dev-middleware');
va... | return true;
};
exports.middlewares = [
{
name: 'upload',
filter: /upload\.do?$/,
handle: function(req, res, next) {
if (req.method === 'POST') {
var busboy = new Busboy({headers: req.headers});
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
con... | return false;
}
| conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.