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 |
|---|---|---|---|---|
mod.rs | //! Types related to database connections
mod statement_cache;
mod transaction_manager;
use std::fmt::Debug;
use crate::backend::Backend;
use crate::deserialize::FromSqlRow;
use crate::expression::QueryMetadata;
use crate::query_builder::{AsQuery, QueryFragment, QueryId};
use crate::result::*;
#[doc(hidden)]
pub us... |
}
| {
self.as_any().is::<T>()
} | identifier_body |
json_body_parser.rs | use serialize::{Decodable, json};
use request::Request;
use typemap::Key;
use plugin::{Plugin, Pluggable};
use std::io;
use std::io::{Read, ErrorKind}; |
impl<'mw, 'conn, D> Plugin<Request<'mw, 'conn, D>> for JsonBodyParser {
type Error = io::Error;
fn eval(req: &mut Request<D>) -> Result<String, io::Error> {
let mut s = String::new();
try!(req.origin.read_to_string(&mut s));
Ok(s)
}
}
pub trait JsonBody {
fn json_as<T: Decodab... |
// Plugin boilerplate
struct JsonBodyParser;
impl Key for JsonBodyParser { type Value = String; } | random_line_split |
json_body_parser.rs | use serialize::{Decodable, json};
use request::Request;
use typemap::Key;
use plugin::{Plugin, Pluggable};
use std::io;
use std::io::{Read, ErrorKind};
// Plugin boilerplate
struct | ;
impl Key for JsonBodyParser { type Value = String; }
impl<'mw, 'conn, D> Plugin<Request<'mw, 'conn, D>> for JsonBodyParser {
type Error = io::Error;
fn eval(req: &mut Request<D>) -> Result<String, io::Error> {
let mut s = String::new();
try!(req.origin.read_to_string(&mut s));
Ok(s)
... | JsonBodyParser | identifier_name |
logs.contribution.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
});
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(LogOutputChannels, LifecyclePhase.Restored);
| {
watcher.dispose();
disposable.dispose();
outputChannelRegistry.registerChannel({ id, label, file, log: true });
} | conditional_block |
logs.contribution.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | this.registerLogChannel(Constants.telemetryLogChannelId, nls.localize('telemetryLog', "Telemetry"), URI.file(join(this.environmentService.logsPath, `telemetry.log`)));
}
};
registerTelemetryChannel(this.logService.getLevel());
this.logService.onDidChangeLogLevel(registerTelemetryChannel);
}
private asyn... | if (level === LogLevel.Trace && !Registry.as<IOutputChannelRegistry>(OutputExt.OutputChannels).getChannel(Constants.telemetryLogChannelId)) { | random_line_split |
logs.contribution.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): void {
this.registerLogChannel(Constants.userDataSyncLogChannelId, nls.localize('userDataSyncLog', "Preferences Sync"), this.environmentService.userDataSyncLogResource);
this.registerLogChannel(Constants.rendererLogChannelId, nls.localize('rendererLog', "Window"), this.environmentService.logFile);
}
private ... | registerCommonContributions | identifier_name |
logs.contribution.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
private registerNativeContributions(): void {
this.registerLogChannel(Constants.mainLogChannelId, nls.localize('mainLog', "Main"), URI.file(join(this.environmentService.logsPath, `main.log`)));
this.registerLogChannel(Constants.sharedLogChannelId, nls.localize('sharedLog', "Shared"), URI.file(join(this.environme... | {
this.instantiationService.createInstance(LogsDataCleaner);
const workbenchActionsRegistry = Registry.as<IWorkbenchActionRegistry>(WorkbenchActionExtensions.WorkbenchActions);
const devCategory = nls.localize('developer', "Developer");
workbenchActionsRegistry.registerWorkbenchAction(SyncActionDescriptor.from... | identifier_body |
WebSocket.ts | ///<reference path='refs.ts'/>
module TDev.RT {
//? A web socket message
//@ stem("msg") ctx(general) dbgOnly
export class WebSocketMessage
extends RTValue {
private stringData:string;
private binaryData:any;
private err: string;
constructor() {
super()
... | (ws: WebSocket, rt : Runtime) {
var w = new WebSocket_(ws, rt);
w.attachEvents()
return w;
}
private attachEvents() {
this.ws.addEventListener("error", ev => {
App.logEvent(App.DEBUG, "ws", "error: " + ev.message, undefined);
... | mk | identifier_name |
WebSocket.ts | ///<reference path='refs.ts'/>
module TDev.RT {
//? A web socket message
//@ stem("msg") ctx(general) dbgOnly
export class WebSocketMessage
extends RTValue {
private stringData:string;
private binaryData:any;
private err: string;
constructor() {
super()
... |
public toString() {
return this.ready_state() + " " + this.ws.url;
}
//? Displays the request to the wall
public post_to_wall(s: IStackFrame): void {
super.post_to_wall(s);
}
}
} | this.sendPacket(buf.buffer);
} | random_line_split |
WebSocket.ts | ///<reference path='refs.ts'/>
module TDev.RT {
//? A web socket message
//@ stem("msg") ctx(general) dbgOnly
export class WebSocketMessage
extends RTValue {
private stringData:string;
private binaryData:any;
private err: string;
constructor() {
super()
... |
public toString() {
return this.ready_state() + " " + this.ws.url;
}
//? Displays the request to the wall
public post_to_wall(s: IStackFrame): void {
super.post_to_wall(s);
}
}
}
| {
this.sendPacket(buf.buffer);
} | identifier_body |
reporter.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 cssparser::SourceLocation; | use msg::constellation_msg::PipelineId;
use script_traits::ConstellationControlMsg;
use servo_url::ServoUrl;
use std::sync::{Mutex, Arc};
use style::error_reporting::{ParseErrorReporter, ContextualParseError};
#[derive(HeapSizeOf, Clone)]
pub struct CSSErrorReporter {
pub pipelineid: PipelineId,
// Arc+Mutex c... | use ipc_channel::ipc::IpcSender;
use log; | random_line_split |
reporter.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 cssparser::SourceLocation;
use ipc_channel::ipc::IpcSender;
use log;
use msg::constellation_msg::PipelineId;
u... |
//TODO: report a real filename
let _ = self.script_chan.lock().unwrap().send(
ConstellationControlMsg::ReportCSSError(self.pipelineid,
"".to_owned(),
location.line,
... | {
info!("Url:\t{}\n{}:{} {}",
url.as_str(),
location.line,
location.column,
error.to_string())
} | conditional_block |
reporter.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 cssparser::SourceLocation;
use ipc_channel::ipc::IpcSender;
use log;
use msg::constellation_msg::PipelineId;
u... | (&self,
url: &ServoUrl,
location: SourceLocation,
error: ContextualParseError) {
if log_enabled!(log::LogLevel::Info) {
info!("Url:\t{}\n{}:{} {}",
url.as_str(),
location.line,
location.... | report_error | identifier_name |
trailing_whitespace.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import tokenize
from builtins import range
from collections import defaultdict... |
def has_exception(self, line_number, exception_start, exception_end=None):
exception_end = exception_end or exception_start
for start, end in self._exception_map.get(line_number, ()):
if start <= exception_start and exception_end <= end:
return True
return False
def nits(self):
for l... |
def __init__(self, *args, **kw):
super(TrailingWhitespace, self).__init__(*args, **kw)
self._exception_map = self.build_exception_map(self.python_file.tokens) | random_line_split |
trailing_whitespace.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import tokenize
from builtins import range
from collections import defaultdict... | (self):
for line_number, line in self.python_file.enumerate():
stripped_line = line.rstrip()
if stripped_line != line and not self.has_exception(line_number,
len(stripped_line), len(line)):
yield self.error('T200', 'Line has trailing whitespace.', line_number)
if line.rstrip().en... | nits | identifier_name |
trailing_whitespace.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import tokenize
from builtins import range
from collections import defaultdict... |
def __init__(self, *args, **kw):
super(TrailingWhitespace, self).__init__(*args, **kw)
self._exception_map = self.build_exception_map(self.python_file.tokens)
def has_exception(self, line_number, exception_start, exception_end=None):
exception_end = exception_end or exception_start
for start, end... | """Generates a set of ranges where we accept trailing slashes, specifically within comments
and strings.
"""
exception_ranges = defaultdict(list)
for token in tokens:
token_type, _, token_start, token_end = token[0:4]
if token_type in (tokenize.COMMENT, tokenize.STRING):
if token_... | identifier_body |
trailing_whitespace.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import tokenize
from builtins import range
from collections import defaultdict... |
return False
def nits(self):
for line_number, line in self.python_file.enumerate():
stripped_line = line.rstrip()
if stripped_line != line and not self.has_exception(line_number,
len(stripped_line), len(line)):
yield self.error('T200', 'Line has trailing whitespace.', line_numb... | return True | conditional_block |
metalink.py | ")
file_.setAttribute("name", pkg.filename)
self.files.appendChild(file_)
for tag, db_attr, attrs in (
('identity', 'name', ()),
('size', 'size', ()),
('version', 'version', ()),
('description', 'desc', ()),
('hash',... | eeds_sig( | identifier_name | |
metalink.py | '] = elem.text
elif elem.tag.endswith("description"):
element['description'] = elem.text
elif elem.tag.endswith("hash"):
element['hash'] = elem.text
elif elem.tag.endswith("url"):
try:
element['urls'].append(elem.tex... |
def __iter__(self):
for v in self.pkgs.values():
yield v
def __len__(self):
return len(self.pkgs)
class DownloadQueue(object):
""" Represents a download queue """
def __init__(self):
self.dbs = list()
self.sync_pkgs = list()
def __bool__(self):
... | eturn pkg.name in self.pkgs
| identifier_body |
metalink.py | version'] = elem.text
elif elem.tag.endswith("description"):
element['description'] = elem.text
elif elem.tag.endswith("hash"):
element['hash'] = elem.text
elif elem.tag.endswith("url"):
try:
element['urls'].append(e... | return len(self.pkgs)
class DownloadQueue(object):
""" Represents a download queue """
def __init__(self):
self.dbs = list()
self.sync_pkgs = list()
def __bool__(self):
return bool(self.dbs or self.sync_pkgs)
def __nonzero__(self):
return self.dbs or self.syn... | random_line_split | |
metalink.py | '] = elem.text
elif elem.tag.endswith("description"):
element['description'] = elem.text
elif elem.tag.endswith("hash"):
element['hash'] = elem.text
elif elem.tag.endswith("url"):
try:
element['urls'].append(elem.tex... |
for pkg, urls, sigs in download_queue.sync_pkgs:
metalink.add_sync_pkg(pkg, urls, sigs)
return metalink
class Metalink(object):
""" Metalink class """
def __init__(self):
self.doc = minidom.getDOMImplementation().createDocument(None, "metalink", None)
self.doc.documentElement... | etalink.add_db(database, sigs)
| conditional_block |
mod.rs | //! Translators for various architectures to Falcon IL.
//!
//! Translators in Falcon do not lift individual instructions, but instead lift
//! basic blocks. This is both more performant than lifting individual
//! instructions, and allows Falcon to deal with weird cases such as the delay
//! slot in the MIPS architect... | control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
translation_results.insert(
block_address,
BlockTranslationResult::new(
vec![(block_address, control_flow_graph)],
... | let mut control_flow_graph = ControlFlowGraph::new();
let block_index = control_flow_graph.new_block()?.index(); | random_line_split |
mod.rs | //! Translators for various architectures to Falcon IL.
//!
//! Translators in Falcon do not lift individual instructions, but instead lift
//! basic blocks. This is both more performant than lifting individual
//! instructions, and allows Falcon to deal with weird cases such as the delay
//! slot in the MIPS architect... | }
/// A generic translation trait, implemented by various architectures.
pub trait Translator {
/// Translates a basic block
fn translate_block(
&self,
bytes: &[u8],
address: u64,
options: &Options,
) -> Result<BlockTranslationResult>;
/// Translates a function
fn ... | {
let block_index = {
let block = control_flow_graph.new_block()?;
block.intrinsic(il::Intrinsic::new(
instruction.mnemonic.clone(),
format!("{} {}", instruction.mnemonic, instruction.op_str),
Vec::new(),
None,
None,
instructio... | identifier_body |
mod.rs | //! Translators for various architectures to Falcon IL.
//!
//! Translators in Falcon do not lift individual instructions, but instead lift
//! basic blocks. This is both more performant than lifting individual
//! instructions, and allows Falcon to deal with weird cases such as the delay
//! slot in the MIPS architect... | (
control_flow_graph: &mut il::ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<()> {
let block_index = {
let block = control_flow_graph.new_block()?;
block.intrinsic(il::Intrinsic::new(
instruction.mnemonic.clone(),
format!("{} {}", instruction.mnemonic,... | unhandled_intrinsic | identifier_name |
build.rs | extern crate gcc;
use std::path::PathBuf;
use std::env;
const LIB_NAME: &'static str = "libctxswtch.a";
fn main() {
let arch =
if cfg!(target_arch = "x86_64") {
"x86_64"
} else if cfg!(target_arch = "i686") {
"i686"
} else if cfg!(target_arch = "arm") {
... | else {
panic!("Unsupported architecture: {}", env::var("TARGET").unwrap());
};
let src_path = &["src", "asm", arch, "_context.S"].iter().collect::<PathBuf>();
gcc::compile_library(LIB_NAME, &[src_path.to_str().unwrap()]);
// seems like this line is no need actually
// println!("cargo:ru... | {
"mipsel"
} | conditional_block |
build.rs | extern crate gcc;
use std::path::PathBuf;
use std::env;
const LIB_NAME: &'static str = "libctxswtch.a";
fn | () {
let arch =
if cfg!(target_arch = "x86_64") {
"x86_64"
} else if cfg!(target_arch = "i686") {
"i686"
} else if cfg!(target_arch = "arm") {
"arm"
} else if cfg!(target_arch = "mips") {
"mips"
} else if cfg!(target_arch = "mip... | main | identifier_name |
build.rs | extern crate gcc;
use std::path::PathBuf;
use std::env;
const LIB_NAME: &'static str = "libctxswtch.a";
fn main() | }
| {
let arch =
if cfg!(target_arch = "x86_64") {
"x86_64"
} else if cfg!(target_arch = "i686") {
"i686"
} else if cfg!(target_arch = "arm") {
"arm"
} else if cfg!(target_arch = "mips") {
"mips"
} else if cfg!(target_arch = "mipsel... | identifier_body |
build.rs | extern crate gcc;
use std::path::PathBuf;
use std::env;
const LIB_NAME: &'static str = "libctxswtch.a"; | if cfg!(target_arch = "x86_64") {
"x86_64"
} else if cfg!(target_arch = "i686") {
"i686"
} else if cfg!(target_arch = "arm") {
"arm"
} else if cfg!(target_arch = "mips") {
"mips"
} else if cfg!(target_arch = "mipsel") {
... |
fn main() {
let arch = | random_line_split |
browser.js | export const browserVersions = () => {
let u = navigator.userAgent
return { | mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, // android终端或者uc浏览器
iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
iPad: u.indexOf('iPad') > -1, // 是否iPad
webA... | // 移动终端浏览器版本信息
trident: u.indexOf('Trident') > -1, // IE内核
presto: u.indexOf('Presto') > -1, // opera内核
webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核 | random_line_split |
env_check.py | import os | from android_build_system.pre_checks.base import BaseCheck
from android_build_system.config import AAPT, ZIPALIGN
class EnvCheck(BaseCheck):
def __init__(self):
super().__init__("Env check")
def _check(self):
return os.environ.get("ANDROID_HOME", None) is not None
class AAPTCheck(BaseCheck)... | import shutil
| random_line_split |
env_check.py | import os
import shutil
from android_build_system.pre_checks.base import BaseCheck
from android_build_system.config import AAPT, ZIPALIGN
class EnvCheck(BaseCheck):
def __init__(self):
super().__init__("Env check")
def _check(self):
return os.environ.get("ANDROID_HOME", None) is not None
c... | (BaseCheck):
def __init__(self):
super().__init__("Binary 'aapt' found")
def _check(self):
return AAPT is not None
class ZIPALIGNCheck(BaseCheck):
def __init__(self):
super().__init__("Binary 'zipalgn' found")
def _check(self):
return ZIPALIGN is not None
class CmdC... | AAPTCheck | identifier_name |
env_check.py | import os
import shutil
from android_build_system.pre_checks.base import BaseCheck
from android_build_system.config import AAPT, ZIPALIGN
class EnvCheck(BaseCheck):
|
class AAPTCheck(BaseCheck):
def __init__(self):
super().__init__("Binary 'aapt' found")
def _check(self):
return AAPT is not None
class ZIPALIGNCheck(BaseCheck):
def __init__(self):
super().__init__("Binary 'zipalgn' found")
def _check(self):
return ZIPALIGN is not... | def __init__(self):
super().__init__("Env check")
def _check(self):
return os.environ.get("ANDROID_HOME", None) is not None | identifier_body |
loggerconfig.py | LOG_SETTINGS = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'detailed': {
'format': '%(asctime)s | %(process)d | %(levelname)s | %(filename)s | %(lineno)d | %(funcName)s | %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'simpl... | 'hydrosys4': {
'handlers':['access_file_handler'],
'propagate': False,
'level':'DEBUG'
},
'exception': {
'handlers': ['exception_file_handler'],
'level': 'ERROR',
'propagate': False
}
}
} | 'interval': 1,
'delay': True
}
},
'loggers': { | random_line_split |
keypair.js | /*
* Copyright 2016 Joyent, Inc., All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, mod... | (kr, opts) {
SDCKeyPair.call(this, kr, opts);
mod_assert.buffer(opts.privateData, 'options.privateData');
this.lkp_privateData = opts.privateData;
mod_assert.string(opts.privateFormat, 'options.privateFormat');
this.lkp_privateFormat = opts.privateFormat;
this.lkp_locked = true;
}
mod_util.inherits(SDCLockedKeyP... | SDCLockedKeyPair | identifier_name |
keypair.js | /*
* Copyright 2016 Joyent, Inc., All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, mod... |
return (mod_httpsig.createSigner({ sign: rsign }));
};
SDCKeyPair.prototype.createSign = function (opts) {
mod_assert.object(opts, 'options');
mod_assert.optionalString(opts.algorithm, 'options.algorithm');
mod_assert.optionalString(opts.keyId, 'options.keyId');
mod_assert.string(opts.user, 'options.user');
mod... | {
sign(data, function (err, res) {
if (res)
res.keyId = keyId;
cb(err, res);
});
} | identifier_body |
keypair.js | /*
* Copyright 2016 Joyent, Inc., All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, mod... |
var key = this.skp_private;
var keyId = this.getKeyId();
var alg = opts.algorithm;
var algParts = alg ? alg.toLowerCase().split('-') : [];
if (algParts[0] && algParts[0] !== key.type) {
throw (new Error('Requested algorithm ' + alg + ' is ' +
'not supported with a key of type ' + key.type));
}
var sel... | {
throw (new Error('Private key for this key pair is ' +
'unavailable (because, e.g. only a public key was ' +
'found and no matching private half)'));
} | conditional_block |
keypair.js | /*
* Copyright 2016 Joyent, Inc., All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, mod... | var sign = this.createSign(opts);
var user = opts.user;
if (opts.subuser) {
if (opts.mantaSubUser)
user += '/' + opts.subuser;
else
user += '/users/' + opts.subuser;
}
var keyId = '/' + user + '/keys/' + this.getKeyId();
function rsign(data, cb) {
sign(data, function (err, res) {
if (res)
res... | random_line_split | |
ccseg.py | from tfs import *
from pylab import *
from numpy import *
import glob, os
import nibabel as nib
matplotlib.interactive(True)
session = tf.InteractiveSession()
dataPath = './corpusCallosum/'
# Class to serve up segmented images
def computePad(dims,depth):
y1=y2=x1=x2=0;
y,x = [numpy.ceil(dims[i]/float(2**depth))... | (self,paths):
image,truth = paths
image = nib.load(image).get_data(); truth = nib.load(truth).get_data()
slicesWithValues = [unique(s) for s in where(truth>0)]
sliceAxis = argmin([len(s) for s in slicesWithValues])
slicesWithValues = slicesWithValues[sliceAxis]
slc = repeat(-1,3); slc[sliceAxis] = slicesWit... | getSlices | identifier_name |
ccseg.py | from tfs import *
from pylab import *
from numpy import *
import glob, os
import nibabel as nib
matplotlib.interactive(True)
session = tf.InteractiveSession()
dataPath = './corpusCallosum/'
# Class to serve up segmented images
def computePad(dims,depth):
y1=y2=x1=x2=0;
y,x = [numpy.ceil(dims[i]/float(2**depth))... |
images = [self.getSlices(self.paths[i]) for i in batch]
return list(zip(*images))
class Container(object):
def __init__(self,dataPath,reserve=2,**args):
self.dataPath = dataPath
images = glob.glob(os.path.join(dataPath,'?????.nii.gz'))
images = [(i,i.replace('.nii.gz','_cc.nii.gz')) for i in images]
... | batch = random.choice(arange(0,len(self.paths)),miniBatch) | conditional_block |
ccseg.py | from tfs import *
from pylab import *
from numpy import *
import glob, os
import nibabel as nib
matplotlib.interactive(True)
session = tf.InteractiveSession()
dataPath = './corpusCallosum/'
# Class to serve up segmented images
def computePad(dims,depth):
y1=y2=x1=x2=0;
y,x = [numpy.ceil(dims[i]/float(2**depth))... |
train(session=session,trainingData=data.train,testingData=data.test,truth=y_,input=x,cost=loss,trainingStep=trainStep,accuracy=accuracy,iterations=trainingIterations,miniBatch=2,trainDict=trainDict,testDict=testDict,logName=logName)
# Make a figure
# Get a couple of examples
batch = data.test.next_batch(2)
ex = arr... | random_line_split | |
ccseg.py | from tfs import *
from pylab import *
from numpy import *
import glob, os
import nibabel as nib
matplotlib.interactive(True)
session = tf.InteractiveSession()
dataPath = './corpusCallosum/'
# Class to serve up segmented images
def computePad(dims,depth):
y1=y2=x1=x2=0;
y,x = [numpy.ceil(dims[i]/float(2**depth))... |
def next_batch(self,miniBatch=None):
if miniBatch is None or miniBatch==len(self.paths):
batch = arange(0,len(self.paths))
else:
batch = random.choice(arange(0,len(self.paths)),miniBatch)
images = [self.getSlices(self.paths[i]) for i in batch]
return list(zip(*images))
class Container(object):
d... | image,truth = paths
image = nib.load(image).get_data(); truth = nib.load(truth).get_data()
slicesWithValues = [unique(s) for s in where(truth>0)]
sliceAxis = argmin([len(s) for s in slicesWithValues])
slicesWithValues = slicesWithValues[sliceAxis]
slc = repeat(-1,3); slc[sliceAxis] = slicesWithValues[0]
if ... | identifier_body |
lex.py | import operator
import ply.lex as lex
from jpp.parser.operation import Operation
from jpp.parser.expression import SimpleExpression
reserved = {
'extends': 'EXTENDS',
'import': 'IMPORT',
'local': 'LOCAL',
'imported': 'IMPORTED',
'user_input': 'USER_INPUT',
}
NAME_TOK = 'NAME'
tokens = [
'IN... |
def t_MUL_OP(t):
r"""
\*|//|/|%
"""
return _create_operation_token(t)
def t_INVERT(t):
"""
~
"""
return _create_operation_token(t)
def t_FUNC(t):
"""
bool|abs
"""
return _create_operation_token(t)
def t_INTEGER(t):
r"""
\d+
"""
t.value = SimpleExp... | r"""
\*\*
"""
return _create_operation_token(t) | identifier_body |
lex.py | import operator
import ply.lex as lex
from jpp.parser.operation import Operation
from jpp.parser.expression import SimpleExpression
reserved = {
'extends': 'EXTENDS',
'import': 'IMPORT',
'local': 'LOCAL',
'imported': 'IMPORTED',
'user_input': 'USER_INPUT',
}
NAME_TOK = 'NAME'
tokens = [
'IN... | (t):
r"""
-
"""
t.value = Operation(t.value, operator.sub)
return t
def t_POW(t):
r"""
\*\*
"""
return _create_operation_token(t)
def t_MUL_OP(t):
r"""
\*|//|/|%
"""
return _create_operation_token(t)
def t_INVERT(t):
"""
~
"""
return _create_oper... | t_MINUS | identifier_name |
lex.py | import operator
import ply.lex as lex
from jpp.parser.operation import Operation
from jpp.parser.expression import SimpleExpression
reserved = {
'extends': 'EXTENDS',
'import': 'IMPORT',
'local': 'LOCAL',
'imported': 'IMPORTED',
'user_input': 'USER_INPUT',
}
NAME_TOK = 'NAME'
tokens = [
'IN... | t_SEMICOLON = ';'
def _create_operation_token(t):
t.value = Operation(t.value)
return t
def t_BIT_SHIFT_OPS(t):
"""
<<|>>
"""
return _create_operation_token(t)
def t_COMPARISON_OP(t):
"""
<|<=|==|!=|>=
"""
return _create_operation_token(t)
def t_BITWISE_OPS(t):
r"""
... | t_RBRAC = r'\]'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_COMMA = ',' | random_line_split |
one-of-component.js | /* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
/* eslint-disable import/no-mutable-exports */
// This function will deliver an error message to the browser console when all of the props passed in are undefined (fals... | }
export default oneOfComponent; | }; | random_line_split |
one-of-component.js | /* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
/* eslint-disable import/no-mutable-exports */
// This function will deliver an error message to the browser console when all of the props passed in are undefined (fals... |
const allowedComponentFound = allowedComponents.indexOf(componentType) > -1;
if (!allowedComponentFound && !hasWarned[control]) {
/* eslint-disable max-len */
warning(
false,
`[Design System React] ${control} requires that prop '${propName}' is an instance of one of the following components: ${allo... | {
componentType = props[propName].type.displayName;
} | conditional_block |
nbb.rs | //! A Non-blocking buffer implementation
use alloc::raw_vec::RawVec;
use core::ptr;
use interrupts::no_interrupts;
use super::stream::*;
/// A non-blocking circular buffer for use
/// by interrupt handlers
pub struct NonBlockingBuffer {
// A buffer
buffer: RawVec<char>,
// index of the front of the bu... | buffer: RawVec::with_capacity(cap),
front: 0,
size: 0,
}
}
}
impl InputStream for NonBlockingBuffer {
type Output = Option<char>;
/// Get the next character in the stream if there is one
fn get(&mut self) -> Option<char> {
no_interrupts(|| {
... | NonBlockingBuffer { | random_line_split |
nbb.rs | //! A Non-blocking buffer implementation
use alloc::raw_vec::RawVec;
use core::ptr;
use interrupts::no_interrupts;
use super::stream::*;
/// A non-blocking circular buffer for use
/// by interrupt handlers
pub struct NonBlockingBuffer {
// A buffer
buffer: RawVec<char>,
// index of the front of the bu... |
}
impl InputStream for NonBlockingBuffer {
type Output = Option<char>;
/// Get the next character in the stream if there is one
fn get(&mut self) -> Option<char> {
no_interrupts(|| {
if self.size > 0 {
let i = self.front;
self.front = (self.front + 1) %... | {
NonBlockingBuffer {
buffer: RawVec::with_capacity(cap),
front: 0,
size: 0,
}
} | identifier_body |
nbb.rs | //! A Non-blocking buffer implementation
use alloc::raw_vec::RawVec;
use core::ptr;
use interrupts::no_interrupts;
use super::stream::*;
/// A non-blocking circular buffer for use
/// by interrupt handlers
pub struct NonBlockingBuffer {
// A buffer
buffer: RawVec<char>,
// index of the front of the bu... | (&mut self, c: char) {
no_interrupts(|| {
if self.size < self.buffer.cap() {
let next = (self.front + self.size) % self.buffer.cap();
unsafe {
ptr::write(self.buffer.ptr().offset(next as isize), c);
}
self.size += 1;... | put | identifier_name |
nbb.rs | //! A Non-blocking buffer implementation
use alloc::raw_vec::RawVec;
use core::ptr;
use interrupts::no_interrupts;
use super::stream::*;
/// A non-blocking circular buffer for use
/// by interrupt handlers
pub struct NonBlockingBuffer {
// A buffer
buffer: RawVec<char>,
// index of the front of the bu... | else {
None
}
})
}
}
impl Iterator for NonBlockingBuffer {
type Item = char;
fn next(&mut self) -> Option<char> {
self.get()
}
}
impl OutputStream<char> for NonBlockingBuffer {
/// Put the given character at the end of the buffer.
///
/// If th... | {
let i = self.front;
self.front = (self.front + 1) % self.buffer.cap();
self.size -= 1;
unsafe { Some(ptr::read(self.buffer.ptr().offset(i as isize))) }
} | conditional_block |
metadata_definitions.py | # coding=utf-8
"""InaSAFE Disaster risk tool by Australian Aid - Flood Raster Impact on
Population.
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 |
__author__ = 'Rizky Maulana Nugraha'
from safe.common.utilities import OrderedDict
from safe.defaults import (
default_minimum_needs,
default_gender_postprocessor,
age_postprocessor,
minimum_needs_selector)
from safe.impact_functions.impact_function_metadata import \
ImpactFunctionMetadata
from s... | the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
""" | random_line_split |
metadata_definitions.py | # coding=utf-8
"""InaSAFE Disaster risk tool by Australian Aid - Flood Raster Impact on
Population.
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 Fou... | 'detailed_description': tr(
'The population subject to inundation exceeding a '
'threshold (default 1m) is calculated and returned as a '
'raster layer. In addition the total number of affected '
'people and the required needs based on the user... | """Return metadata as a dictionary.
This is a static method. You can use it to get the metadata in
dictionary format for an impact function.
:returns: A dictionary representing all the metadata for the
concrete impact function.
:rtype: dict
"""
dict_meta = {... | identifier_body |
metadata_definitions.py | # coding=utf-8
"""InaSAFE Disaster risk tool by Australian Aid - Flood Raster Impact on
Population.
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 Fou... | ():
"""Return metadata as a dictionary.
This is a static method. You can use it to get the metadata in
dictionary format for an impact function.
:returns: A dictionary representing all the metadata for the
concrete impact function.
:rtype: dict
"""
d... | as_dict | identifier_name |
mode-ruby.js | line.match(/^.*[\{\(\[]\s*$/);
var startingClassOrMethod = line.match(/^\s*(class|def|module)\s.*$/);
var startingDoBlock = line.match(/.*do(\s*|\s+\|.*\|\s*)$/);
var startingConditional = line.match(/^\s*(if|else)\s*/)
if (match || startingClassOrMethod || startingDoBlo... | this.$id = "ace/mode/ruby";
}).call(Mode.prototype);
exports.Mode = Mode;
});
__ace_shadowed__.define('ace/mode/ruby_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules =... | random_line_split | |
mode-ruby.js | |next|not|or|private|protected|public|" +
"redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield"
);
var buildinConstants = (
"true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" +
"RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING"
)... | {
if (session.getLine(row - 2).search(/\S/) == -1) {
session.foldWidgets[row - 1] = "start";
session.foldWidgets[row + 1] = "";
return "";
}
} | conditional_block | |
MTLLoader.d.ts | import {
Material,
LoadingManager,
Mapping,
Loader,
BufferGeometry,
Side,
Texture,
Vector2,
Wrapping,
} from '../../../src/Three';
export interface MaterialCreatorOptions {
/**
* side: Which side to apply the material
* THREE.FrontSide (default), THREE.BackSide, THREE.... | {
constructor(baseUrl?: string, options?: MaterialCreatorOptions);
baseUrl: string;
options: MaterialCreatorOptions;
materialsInfo: { [key: string]: MaterialInfo };
materials: { [key: string]: Material };
private materialsArray: Material[];
nameLookup: { [key: s... | MaterialCreator | identifier_name |
MTLLoader.d.ts | import {
Material,
LoadingManager,
Mapping,
Loader,
BufferGeometry,
Side,
Texture,
Vector2,
Wrapping,
} from '../../../src/Three';
export interface MaterialCreatorOptions {
/**
* side: Which side to apply the material
* THREE.FrontSide (default), THREE.BackSide, THREE.... | */
invertTrProperty?: boolean;
}
export class MTLLoader extends Loader {
constructor(manager?: LoadingManager);
materialOptions: MaterialCreatorOptions;
load(
url: string,
onLoad: (materialCreator: MTLLoader.MaterialCreator) => void,
onProgress?: (event: ProgressEvent) => ... | * Default: false | random_line_split |
sin.rs | //! Implements vertical (lane-wise) floating-point `sin`.
| #[inline]
pub fn sin(self) -> Self {
use crate::codegen::math::float::sin::Sin;
Sin::sin(self)
}
/// Sine of `self * PI`.
#[inline]
pub fn sin_pi(self) -> Self {
use crate::codegen::math::float::sin_... | macro_rules! impl_math_float_sin {
([$elem_ty:ident; $elem_count:expr]: $id:ident | $test_tt:tt) => {
impl $id {
/// Sine. | random_line_split |
pin_bindings_content_test.tsx | import * as React from "react";
import { PinBindingsContent } from "../pin_bindings_content";
import { mount } from "enzyme";
import { bot } from "../../../__test_support__/fake_state/bot";
import {
buildResourceIndex,
} from "../../../__test_support__/resource_index_builder";
import {
fakeSequence, fakePinBinding,... | fakeSequence1, fakeSequence2, fakePinBinding1, fakePinBinding2,
]).index;
bot.hardware.gpio_registry = {
10: "1",
11: "2"
};
return {
dispatch: jest.fn(),
resources: resources,
firmwareHardware: undefined,
};
}
it("renders", () => {
const p = fakeProps(... | {
const fakeSequence1 = fakeSequence();
fakeSequence1.body.id = 1;
fakeSequence1.body.name = "Sequence 1";
const fakeSequence2 = fakeSequence();
fakeSequence2.body.id = 2;
fakeSequence2.body.name = "Sequence 2";
const fakePinBinding1 = fakePinBinding();
fakePinBinding1.body =
({ ... | identifier_body |
pin_bindings_content_test.tsx | import * as React from "react";
import { PinBindingsContent } from "../pin_bindings_content";
import { mount } from "enzyme";
import { bot } from "../../../__test_support__/fake_state/bot";
import {
buildResourceIndex, | } from "../../../__test_support__/resource_index_builder";
import {
fakeSequence, fakePinBinding,
} from "../../../__test_support__/fake_state/resources";
import { PinBindingsContentProps } from "../interfaces";
import {
SpecialPinBinding,
PinBindingType,
PinBindingSpecialAction,
} from "farmbot/dist/resources/... | random_line_split | |
pin_bindings_content_test.tsx | import * as React from "react";
import { PinBindingsContent } from "../pin_bindings_content";
import { mount } from "enzyme";
import { bot } from "../../../__test_support__/fake_state/bot";
import {
buildResourceIndex,
} from "../../../__test_support__/resource_index_builder";
import {
fakeSequence, fakePinBinding,... | (): PinBindingsContentProps {
const fakeSequence1 = fakeSequence();
fakeSequence1.body.id = 1;
fakeSequence1.body.name = "Sequence 1";
const fakeSequence2 = fakeSequence();
fakeSequence2.body.id = 2;
fakeSequence2.body.name = "Sequence 2";
const fakePinBinding1 = fakePinBinding();
fake... | fakeProps | identifier_name |
seekbar.component.tsx | import * as React from 'react';
import { duration } from 'moment';
export default class Seekbar extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
hovered: null,
mouseX: null
};
this.seek = this.seek.bind(this);
... | (event: React.MouseEvent<any>) {
const offset = event.nativeEvent.offsetX;
const target = event.target as HTMLElement;
const elWidth = target.offsetWidth;
let hours;
let minutes;
let seconds;
const hoverValue = duration(1000 * (offset * this.props.duration) / el... | handleHover | identifier_name |
seekbar.component.tsx | import * as React from 'react';
import { duration } from 'moment';
export default class Seekbar extends React.Component<any, any> {
constructor(props: any) |
public shouldComponentUpdate(nextProps: any) {
return nextProps.duration > 0;
}
public seek(offset: number, element: HTMLElement) {
const seekTo = (offset * this.props.duration) / element.offsetWidth;
this.props.playerSeek(seekTo);
}
public handleHover(event: React.MouseE... | {
super(props);
this.state = {
hovered: null,
mouseX: null
};
this.seek = this.seek.bind(this);
this.handleHoverOut = this.handleHoverOut.bind(this);
this.handleHover = this.handleHover.bind(this);
} | identifier_body |
seekbar.component.tsx | import * as React from 'react';
import { duration } from 'moment';
export default class Seekbar extends React.Component<any, any> { | hovered: null,
mouseX: null
};
this.seek = this.seek.bind(this);
this.handleHoverOut = this.handleHoverOut.bind(this);
this.handleHover = this.handleHover.bind(this);
}
public shouldComponentUpdate(nextProps: any) {
return nextProps.duration > 0;... | constructor(props: any) {
super(props);
this.state = { | random_line_split |
macro_rules.rs | the context choose how to interpret the result.
// Weird, but useful for X-macros.
return Box::new(ParserAnyMacro {
parser: RefCell::new(p),
// Pass along the original expansion site and the name of the macro
// so we can prin... | Some(_) => {
cx.span_err(sp, "sequence repetition followed by another \
sequence repetition, which is not allowed"); | random_line_split | |
macro_rules.rs | let ret = self.parser.borrow_mut().parse_pat();
self.ensure_complete_parse(false);
Some(ret)
}
fn make_items(self: Box<ParserAnyMacro<'a>>) -> Option<SmallVector<P<ast::Item>>> {
let mut ret = SmallVector::zero();
while let Some(item) = self.parser.borrow_mut().parse_item() {
... | {
// lhs is going to be like MatchedNonterminal(NtTT(TtDelimited(...))), where the entire lhs is
// those tts. Or, it can be a "bare sequence", not wrapped in parens.
match lhs {
&MatchedNonterminal(NtTT(ref inner)) => match &**inner {
&TtDelimited(_, ref tts) => {
check_... | identifier_body | |
macro_rules.rs | (named_matches) => {
let rhs = match *rhses[i] {
// okay, what's your transcriber?
MatchedNonterminal(NtTT(ref tt)) => {
match **tt {
// ignore delimiters
TtDelimited(_, ref delimed) =... | {
// iii. Else, T is a complex NT.
match seq.separator {
// If T has the form $(...)U+ or $(...)U* for some token U,
// run the algorithm on the contents with F set to U. If it
// accepts, continue, else, reject.
... | conditional_block | |
macro_rules.rs | }
impl<'a> MacResult for ParserAnyMacro<'a> {
fn make_expr(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Expr>> {
let ret = self.parser.borrow_mut().parse_expr();
self.ensure_complete_parse(true);
Some(ret)
}
fn make_pat(self: Box<ParserAnyMacro<'a>>) -> Option<P<ast::Pat>> {
... | <'cx>(cx: &'cx ExtCtxt,
sp: Span,
name: ast::Ident,
imported_from: Option<ast::Ident>,
arg: &[ast::TokenTree],
lhses: &[Rc<NamedMatch>],
rhses: &[Rc<NamedMatch>])
... | generic_extension | identifier_name |
__init__.py | from contextlib import contextmanager
import logging
import os.path
import traceback
from kazoo.client import KazooClient
from kazoo.exceptions import (
LockTimeout,
NodeExistsError,
NoNodeError,
KazooException,
ZookeeperError,
)
from kazoo.retry import KazooRetry, RetryFailedError
from mastermind.... | if data[0] != check:
logger.error(
'Lock {lock_id} has inconsistent data: {current_data}, '
'expected {expected_data}'.format(
lock_id=lockid,
current_data=... | try:
if check:
data = self.client.get(self.lock_path_prefix + lockid) | random_line_split |
__init__.py | from contextlib import contextmanager
import logging
import os.path
import traceback
from kazoo.client import KazooClient
from kazoo.exceptions import (
LockTimeout,
NodeExistsError,
NoNodeError,
KazooException,
ZookeeperError,
)
from kazoo.retry import KazooRetry, RetryFailedError
from mastermind.... |
if failed_locks:
holders = []
for f in failed_locks:
# TODO: fetch all holders with 1 transaction request
holders.append((f, self.client.get(self.lock_path_prefix + f)))
foreign_holders = [(l, h) for l, h in holders if h[0] != data]
... | failed_locks.append(locks[i]) | conditional_block |
__init__.py | from contextlib import contextmanager
import logging
import os.path
import traceback
from kazoo.client import KazooClient
from kazoo.exceptions import (
LockTimeout,
NodeExistsError,
NoNodeError,
KazooException,
ZookeeperError,
)
from kazoo.retry import KazooRetry, RetryFailedError
from mastermind.... | (object):
RETRIES = 2
LOCK_TIMEOUT = 3
def __init__(self, host='127.0.0.1:2181', lock_path_prefix='/mastermind/locks/'):
self.client = KazooClient(host, timeout=3)
logger.info('Connecting to zookeeper host {}, lock_path_prefix: {}'.format(
host, lock_path_prefix))
try:
... | ZkSyncManager | identifier_name |
__init__.py | from contextlib import contextmanager
import logging
import os.path
import traceback
from kazoo.client import KazooClient
from kazoo.exceptions import (
LockTimeout,
NodeExistsError,
NoNodeError,
KazooException,
ZookeeperError,
)
from kazoo.retry import KazooRetry, RetryFailedError
from mastermind.... |
def put_task(self, task):
group_id = task['group']
q = LockingQueue(self.client, self.lock_path_prefix, group_id)
return q.put(self._serialize(task))
def put_all(self, tasks):
for task in tasks:
self.put_task(task)
def list(self):
for group_id in self.... | self.client = KazooClient(host, timeout=3)
logger.info('Connecting to zookeeper host {}, lock_path_prefix: {}'.format(
host, lock_path_prefix))
try:
self.client.start()
except Exception as e:
logger.error(e)
raise
self.lock_path_prefix = h... | identifier_body |
LogisticClassifier.py | import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# Datos de Prueba
data = [("me gusta comer en la cafeteria".split(), "SPANISH"),
("Give it to me".split(), "ENGLISH"),
("No creo que sea una buena idea".split(), "SPANISH"),
... |
return model
if __name__ == "__main__":
torch.manual_seed(1)
# Diccionario {Word:ID}
word_to_ix = {}
for sent, _ in data + test_data:
for word in sent:
if word not in word_to_ix:
word_to_ix[word] = len(word_to_ix)
#print(word_to_ix)
#### Vars
VOCAB_... | bow_vec = autograd.Variable(make_bow_vector(instance, word_to_ix))
log_probs = model(bow_vec)
print(log_probs) | conditional_block |
LogisticClassifier.py | import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# Datos de Prueba
data = [("me gusta comer en la cafeteria".split(), "SPANISH"),
("Give it to me".split(), "ENGLISH"),
("No creo que sea una buena idea".split(), "SPANISH"),
... |
def make_target(label, label_to_ix):
return torch.LongTensor([label_to_ix[label]])
def train_model(model,data):
for epoch in range(100):
for instance, label in data:
model.zero_grad()
bow_vec = autograd.Variable(make_bow_vector(instance, word_to_ix))
target = auto... | vec = torch.zeros(len(word_to_ix))
for word in sentence:
vec[word_to_ix[word]] += 1
return vec.view(1, -1) | identifier_body |
LogisticClassifier.py | import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# Datos de Prueba
data = [("me gusta comer en la cafeteria".split(), "SPANISH"),
("Give it to me".split(), "ENGLISH"),
("No creo que sea una buena idea".split(), "SPANISH"),
... |
if __name__ == "__main__":
torch.manual_seed(1)
# Diccionario {Word:ID}
word_to_ix = {}
for sent, _ in data + test_data:
for word in sent:
if word not in word_to_ix:
word_to_ix[word] = len(word_to_ix)
#print(word_to_ix)
#### Vars
VOCAB_SIZE = len(word_to... | print(log_probs)
return model | random_line_split |
LogisticClassifier.py | import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# Datos de Prueba
data = [("me gusta comer en la cafeteria".split(), "SPANISH"),
("Give it to me".split(), "ENGLISH"),
("No creo que sea una buena idea".split(), "SPANISH"),
... | (nn.Module):
def __init__(self, num_labels, vocab_size):
super(BoWClassifier, self).__init__()
# (Tamanio Entrada TE, Tamanio Salida TS) Dimensiones: A=TS*TE x=TE b=TS
self.linear = nn.Linear(vocab_size, num_labels) # Logistic Regression solo es: y = Ax + b
def forward(self, bow_vec):
... | BoWClassifier | identifier_name |
trait-inheritance-visibility.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() {
f(&0)
}
| {
assert_eq!(x.f(), 10);
} | identifier_body |
trait-inheritance-visibility.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 ... | }
trait Quux: traits::Foo { }
impl<T:traits::Foo> Quux for T { }
// Foo is not in scope but because Quux is we can still access
// Foo's methods on a Quux bound typaram
fn f<T:Quux>(x: &T) {
assert_eq!(x.f(), 10);
}
pub fn main() {
f(&0)
} | impl Foo for isize { fn f(&self) -> isize { 10 } } | random_line_split |
trait-inheritance-visibility.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 ... | (&self) -> isize { 10 } }
}
trait Quux: traits::Foo { }
impl<T:traits::Foo> Quux for T { }
// Foo is not in scope but because Quux is we can still access
// Foo's methods on a Quux bound typaram
fn f<T:Quux>(x: &T) {
assert_eq!(x.f(), 10);
}
pub fn main() {
f(&0)
}
| f | identifier_name |
sample.angular1_5.component.js | /**
* @memberof moduleName
* @ngdoc controller
* @name XxxxController
*/
class SampleController {
/**
* Constrctor : inyección de servicios ...
* @memberof ActividadesController
* @function constructor
* @param $scope {service} scope del controller
*/
construct... | //controllerAs: '$ctrl', valor por defecto
bindings: {}
}) //Fin del componente y del objeto que lo define | random_line_split | |
sample.angular1_5.component.js | /**
* @memberof moduleName
* @ngdoc controller
* @name XxxxController
*/
class SampleController {
/**
* Constrctor : inyección de servicios ...
* @memberof ActividadesController
* @function constructor
* @param $scope {service} scope del controller
*/
construct... | ) {
this.name = "Sample"
this.value = parent.value
} // Fin del $onInit
} // Fin del controller SampleController
angular.module('moduleName')
/**
* Componente responsable de los datos de ...
* @memberof moduleName
* @ngdoc component
* @name .....
*/
.component("sample", {
require: ... | nInit ( | identifier_name |
WebcamManagerFixture.js | //var defaultCamerTagId = 'camerTagId';
var preTakeButtonsId = 'myPreTakeButtonsId';
var postTakeButtonsId = 'myPostTakeButtonsId';
var myCameraTagsId = {
cameraTagId: 'myCameraTagId',
resultTagId: 'myResultTagId',
photoBooth: 'myphotoBoothId',
preTakeButtonsId: preTakeButtonsId,
postTakeButtonsId:... | window.Audio = function () {
this.autoplay;
this.src;
this.play = function () {
}
};
} | conditional_block | |
WebcamManagerFixture.js | //var defaultCamerTagId = 'camerTagId';
var preTakeButtonsId = 'myPreTakeButtonsId';
var postTakeButtonsId = 'myPostTakeButtonsId';
var myCameraTagsId = {
cameraTagId: 'myCameraTagId',
resultTagId: 'myResultTagId',
photoBooth: 'myphotoBoothId',
preTakeButtonsId: preTakeButtonsId,
postTakeButtonsId:... | var defaultIsShutterSoundEnabledTrue = true;
var isShutterSoundEnabledFalse = false;
var onErrorEventCallback = function (errorMessage) {
};
var htmlTagVisibilitySyle = {
style: {
display: undefined
}
};
var htmlSecondTagVisibilitySyle = {
style: {
display: undefined
}
};
var defaultWebc... | random_line_split | |
test_bounce.py | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""Test cases for bounce message generation
"""
from twisted.trial import unittest
from twisted.mail import bounce
import cStringIO
import email.message
import email.parser
| """
testcases for bounce message generation
"""
def testBounceFormat(self):
from_, to, s = bounce.generateBounce(cStringIO.StringIO('''\
From: Moshe Zadka <moshez@example.com>
To: nonexistent@example.org
Subject: test
'''), 'moshez@example.com', 'nonexistent@example.org')
self.assertEq... | class BounceTests(unittest.TestCase): | random_line_split |
test_bounce.py | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""Test cases for bounce message generation
"""
from twisted.trial import unittest
from twisted.mail import bounce
import cStringIO
import email.message
import email.parser
class BounceTests(unittest.TestCase):
"""
testcases for bounce ... | (self):
pass
| testBounceMIME | identifier_name |
test_bounce.py | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""Test cases for bounce message generation
"""
from twisted.trial import unittest
from twisted.mail import bounce
import cStringIO
import email.message
import email.parser
class BounceTests(unittest.TestCase):
"""
testcases for bounce ... |
def testBounceMIME(self):
pass
| from_, to, s = bounce.generateBounce(cStringIO.StringIO('''\
From: Moshe Zadka <moshez@example.com>
To: nonexistent@example.org
Subject: test
'''), 'moshez@example.com', 'nonexistent@example.org')
self.assertEqual(from_, '')
self.assertEqual(to, 'moshez@example.com')
emailParser = email.parser.... | identifier_body |
directives.js | /**
* @module
* @description
* Common directives shipped with Angular.
*/
import { CONST_EXPR } from './facade/lang';
import { NgClass } from './directives/ng_class';
import { NgFor } from './directives/ng_for';
import { NgIf } from './directives/ng_if';
import { NgStyle } from './directives/ng_style';
import { NgS... | * ```
*/
export const CORE_DIRECTIVES = CONST_EXPR([NgClass, NgFor, NgIf, NgStyle, NgSwitch, NgSwitchWhen, NgSwitchDefault]);
//# sourceMappingURL=directives.js.map | * ...
* } | random_line_split |
message_queue.rs | // Copyright 2014 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 ... | <T> {
inner: Arc<mpsc::Queue<T>>,
noshare: marker::NoSync,
}
pub struct Consumer<T> {
inner: Arc<mpsc::Queue<T>>,
noshare: marker::NoSync,
}
impl<T: Send> Consumer<T> {
pub fn pop(&self) -> PopResult<T> {
match self.inner.pop() {
mpsc::Inconsistent => Inconsistent,
... | Producer | identifier_name |
message_queue.rs | // Copyright 2014 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 |
use std::kinds::marker;
use std::sync::Arc;
use std::sync::mpsc_queue as mpsc;
pub use self::PopResult::{Inconsistent, Empty, Data};
pub enum PopResult<T> {
Inconsistent,
Empty,
Data(T),
}
pub fn queue<T: Send>() -> (Consumer<T>, Producer<T>) {
let a = Arc::new(mpsc::Queue::new());
(Consumer { i... | // <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. | random_line_split |
message_queue.rs | // Copyright 2014 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 struct Producer<T> {
inner: Arc<mpsc::Queue<T>>,
noshare: marker::NoSync,
}
pub struct Consumer<T> {
inner: Arc<mpsc::Queue<T>>,
noshare: marker::NoSync,
}
impl<T: Send> Consumer<T> {
pub fn pop(&self) -> PopResult<T> {
match self.inner.pop() {
mpsc::Inconsistent => Incon... | {
let a = Arc::new(mpsc::Queue::new());
(Consumer { inner: a.clone(), noshare: marker::NoSync },
Producer { inner: a, noshare: marker::NoSync })
} | identifier_body |
client.rs | #![feature(core, io, test)]
extern crate hyper;
extern crate test;
use std::fmt;
use std::old_io::net::ip::Ipv4Addr;
use hyper::server::{Request, Response, Server};
use hyper::header::Headers;
use hyper::Client;
fn listen() -> hyper::server::Listening {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 0);
s... | (_r: Request, res: Response) {
static BODY: &'static [u8] = b"Benchmarking hyper vs others!";
let mut res = try_return!(res.start());
try_return!(res.write_all(BODY));
try_return!(res.end());
}
#[derive(Clone)]
struct Foo;
impl hyper::header::Header for Foo {
fn header_name() -> &'static str {
... | handle | identifier_name |
client.rs | #![feature(core, io, test)]
extern crate hyper;
extern crate test;
use std::fmt;
use std::old_io::net::ip::Ipv4Addr;
use hyper::server::{Request, Response, Server};
use hyper::header::Headers;
use hyper::Client;
fn listen() -> hyper::server::Listening {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 0);
s... | {
let mut listening = listen();
let s = format!("http://{}/", listening.socket);
let url = s.as_slice();
let mut client = Client::new();
let mut headers = Headers::new();
headers.set(Foo);
b.iter(|| {
client.get(url).header(Foo).send().unwrap().read_to_string().unwrap();
});
... | identifier_body | |
client.rs | #![feature(core, io, test)]
extern crate hyper;
extern crate test;
use std::fmt;
use std::old_io::net::ip::Ipv4Addr;
use hyper::server::{Request, Response, Server};
use hyper::header::Headers;
use hyper::Client;
fn listen() -> hyper::server::Listening {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 0);
s... | }
#[bench]
fn bench_hyper(b: &mut test::Bencher) {
let mut listening = listen();
let s = format!("http://{}/", listening.socket);
let url = s.as_slice();
let mut client = Client::new();
let mut headers = Headers::new();
headers.set(Foo);
b.iter(|| {
client.get(url).header(Foo).send(... | random_line_split | |
vector.ts | /**
* @license
* Copyright 2019 Google Inc.
* 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... | result *= array[i];
}
return result;
}
export function min<Out extends TypedArray, A extends TypedArray, B extends TypedArray>(
out: Out, a: A, b: B) {
const rank = out.length;
for (let i = 0; i < rank; ++i) {
out[i] = Math.min(a[i], b[i]);
}
return out;
}
export function max<Out extends Typed... | export function prod(array: ArrayLike<number>) {
let result = 1;
for (let i = 0, length = array.length; i < length; ++i) { | random_line_split |
vector.ts | /**
* @license
* Copyright 2019 Google Inc.
* 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 function max<Out extends TypedArray, A extends TypedArray, B extends TypedArray>(
out: Out, a: A, b: B) {
const rank = out.length;
for (let i = 0; i < rank; ++i) {
out[i] = Math.max(a[i], b[i]);
}
return out;
}
export const kEmptyFloat32Vec = new Float32Array(0);
export const kEmptyFloat64Vec ... | {
const rank = out.length;
for (let i = 0; i < rank; ++i) {
out[i] = Math.min(a[i], b[i]);
}
return out;
} | identifier_body |
vector.ts | /**
* @license
* Copyright 2019 Google Inc.
* 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... |
return out;
}
export function subtract<Out extends TypedArray, A extends TypedArray, B extends TypedArray>(
out: Out, a: A, b: B) {
const rank = out.length;
for (let i = 0; i < rank; ++i) {
out[i] = a[i] - b[i];
}
return out;
}
export function multiply<Out extends TypedArray, A extends TypedArray, B ... | {
out[i] = a[i] + b[i];
} | conditional_block |
vector.ts | /**
* @license
* Copyright 2019 Google Inc.
* 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... | <Out extends TypedArray, A extends TypedArray, B extends TypedArray>(
out: Out, a: A, b: B) {
const rank = out.length;
for (let i = 0; i < rank; ++i) {
out[i] = Math.min(a[i], b[i]);
}
return out;
}
export function max<Out extends TypedArray, A extends TypedArray, B extends TypedArray>(
out: Out, a... | min | identifier_name |
raw.rs | use std::borrow::Cow;
use std::fmt;
use http::buf::MemSlice;
/// A raw header value.
#[derive(Clone, PartialEq, Eq)]
pub struct Raw(Lines);
impl Raw {
/// Returns the amount of lines.
#[inline]
pub fn len(&self) -> usize {
match self.0 {
Lines::One(..) => 1,
Lines::Many(ref... | (val: Vec<u8>) -> Raw {
Raw(Lines::One(Line::from(val)))
}
}
impl From<&'static str> for Raw {
fn from(val: &'static str) -> Raw {
Raw(Lines::One(Line::Static(val.as_bytes())))
}
}
impl From<&'static [u8]> for Raw {
fn from(val: &'static [u8]) -> Raw {
Raw(Lines::One(Line::Stat... | from | identifier_name |
raw.rs | use std::borrow::Cow;
use std::fmt;
use http::buf::MemSlice;
/// A raw header value.
#[derive(Clone, PartialEq, Eq)]
pub struct Raw(Lines);
impl Raw {
/// Returns the amount of lines.
#[inline]
pub fn len(&self) -> usize {
match self.0 {
Lines::One(..) => 1,
Lines::Many(ref... | #[derive(Debug, Clone, PartialEq, Eq)]
enum Line {
Static(&'static [u8]),
Owned(Vec<u8>),
Shared(MemSlice),
}
fn eq<A: AsRef<[u8]>, B: AsRef<[u8]>>(a: &[A], b: &[B]) -> bool {
if a.len() != b.len() {
false
} else {
for (a, b) in a.iter().zip(b.iter()) {
if a.as_ref() != ... | enum Lines {
One(Line),
Many(Vec<Line>),
}
| random_line_split |
raw.rs | use std::borrow::Cow;
use std::fmt;
use http::buf::MemSlice;
/// A raw header value.
#[derive(Clone, PartialEq, Eq)]
pub struct Raw(Lines);
impl Raw {
/// Returns the amount of lines.
#[inline]
pub fn len(&self) -> usize {
match self.0 {
Lines::One(..) => 1,
Lines::Many(ref... |
/// Append a line to this `Raw` header value.
pub fn push(&mut self, val: &[u8]) {
self.push_line(maybe_literal(val.into()));
}
fn push_line(&mut self, line: Line) {
let lines = ::std::mem::replace(&mut self.0, Lines::Many(Vec::new()));
match lines {
Lines::One(one... | {
RawLines {
inner: &self.0,
pos: 0,
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.