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 |
|---|---|---|---|---|
commands.py | , state,
p=lambda i: i>0, type='positive integer', *L)
def getNonNegativeInt(irc, msg, args, state, *L):
getInt(irc, msg, args, state,
p=lambda i: i>=0, type='non-negative integer', *L)
def getIndex(irc, msg, args, state):
getInt(irc, msg, args, state, type='index')
if state.args[-1... |
def nickInChannel(irc, msg, args, state):
originalArgs = state.args[:]
inChannel(irc, msg, args, state)
state.args = originalArgs
if args[0] not in irc.state.channels[state.channel].users:
state.error('%s is not in %s.' % (args[0], state.channel), Raise=True)
state.args.append(args.pop(0))... | channel = args[0]
if irc.isChannel(channel):
if channel in irc.state.channels:
if msg.nick in irc.state.channels[channel].users:
state.args.append(args.pop(0))
else:
state.error('You must be in %s.' % channel, Raise=True)
else:
stat... | identifier_body |
commands.py | args[0] not in irc.state.channels[state.channel].users:
state.error('%s is not in %s.' % (args[0], state.channel), Raise=True)
state.args.append(args.pop(0))
def getChannelOrNone(irc, msg, args, state):
try:
getChannel(irc, msg, args, state)
except callbacks.ArgumentError:
state.ar... | self.spec = spec # for repr
if isinstance(spec, tuple):
assert spec, 'tuple spec must not be empty.'
self.args = spec[1:]
self.converter = getConverter(spec[0]) | random_line_split | |
commands.py | , state,
p=lambda i: i>0, type='positive integer', *L)
def getNonNegativeInt(irc, msg, args, state, *L):
getInt(irc, msg, args, state,
p=lambda i: i>=0, type='non-negative integer', *L)
def getIndex(irc, msg, args, state):
getInt(irc, msg, args, state, type='index')
if state.args[-1... |
def getBanmask(irc, msg, args, state):
getHostmask(irc, msg, args, state)
if not state.channel:
getChannel(irc, msg, args, state)
banmaskstyle = conf.supybot.protocols.irc.banmask
state.args[-1] = banmaskstyle.makeBanmask(state.args[-1])
def getUser(irc, msg, args, state):
try:
st... | try:
hostmask = irc.state.nickToHostmask(args[0])
state.args.append(hostmask)
del args[0]
except KeyError:
state.errorInvalid('nick or hostmask', args[0]) | conditional_block |
textArea.tsx | import React, {PureComponent, ChangeEvent} from 'react';
import mergeClassNames from 'classnames';
import TextareaAutosize from 'react-textarea-autosize';
import enhanceWithClickOutside from '../enhanceWithClickOutside/index';
import { PickDefaultProps } from '../../types';
export interface TextAreaProps {
/*... |
}
private readonly handleOnClick = () => {
this.setState({
isFocused: true
});
}
public readonly handleClickOutside = () => {
this.setState({
isFocused: false
});
}
}
//
// Add the click-outside functionality to the TextArea component.
//
e... | {
onChange(e.target.value);
} | conditional_block |
textArea.tsx | import React, {PureComponent, ChangeEvent} from 'react';
import mergeClassNames from 'classnames';
import TextareaAutosize from 'react-textarea-autosize';
import enhanceWithClickOutside from '../enhanceWithClickOutside/index';
import { PickDefaultProps } from '../../types';
export interface TextAreaProps {
/*... | /**
* Optional number to set the minRows of the TextArea if not expanded
*/
readonly minRows?: number;
/**
* Optional number to set the expandedRows of the TextArea if expanded
*/
readonly expandedRows?: number;
}
interface TextAreaTheme {
readon... | random_line_split | |
textArea.tsx | import React, {PureComponent, ChangeEvent} from 'react';
import mergeClassNames from 'classnames';
import TextareaAutosize from 'react-textarea-autosize';
import enhanceWithClickOutside from '../enhanceWithClickOutside/index';
import { PickDefaultProps } from '../../types';
export interface TextAreaProps {
/*... | (): JSX.Element {
const {
placeholder,
className,
theme,
disabled,
minRows,
expandedRows,
value
} = this.props;
const classNames = mergeClassNames(
className,
theme!.textArea,
... | render | identifier_name |
functions_f.js | var searchData=
[
['readonlyprototype',['ReadOnlyPrototype',['../classv8_1_1FunctionTemplate.html#a91d2e0643e8c5a53ab1d75f7766c2422',1,'v8::FunctionTemplate']]],
['release',['Release',['../classv8_1_1PersistentValueMapBase.html#a9ffa7a4e0c59121c0471d71c04112966',1,'v8::PersistentValueMapBase']]],
['remove',['Remo... | ]; | ['rethrow',['ReThrow',['../classv8_1_1TryCatch.html#ab8c3a1dbb38e6fd00e37436034daf707',1,'v8::TryCatch']]],
['runmicrotasks',['RunMicrotasks',['../classv8_1_1Isolate.html#ac3cbe2a1632eb863912640dcfc98b6c8',1,'v8::Isolate']]] | random_line_split |
driftscatter.py | import ctypes
import random
import math
import numpy
import stats
import constants
#energy = mesh.bandstructure.random_
ext = ctypes.cdll.LoadLibrary("c_optimized/driftscatter.so")
def randomElectronMovement(particle,electric_field,density_func,mesh,reaper):
# global avg_lifetime
# lifetime = .001#lifetime(cell)
|
# scatter(mesh,particle)
#check for out of bounds
# this needs to be changed, we should
# do all momentum changes BEFORE movement
# this guarantees that we are on the mesh.
#if(dot(e.dx,e.dx) > meanpathlength**2):
# e.dx = array([0.,0.])
# e.momentum += array([0,0])#scatter(e.momentum,e.pos,mesh)
#if(p.lifetim... | p = particle
dt = mesh.dt
p.momentum += drift(mesh,electric_field,p)*dt
dx = (p.momentum*dt/mesh.length_scale)/p.mass
#stats.avg_dx += numpy.linalg.norm(dx)
#stats.avg_momentum += numpy.linalg.norm(p.momentum)
#p.dx += dx
p.pos += dx | identifier_body |
driftscatter.py | import ctypes
import random
import math
import numpy
import stats
import constants
#energy = mesh.bandstructure.random_
ext = ctypes.cdll.LoadLibrary("c_optimized/driftscatter.so")
def randomElectronMovement(particle,electric_field,density_func,mesh,reaper):
# global avg_lifetime
# lifetime = .001#lifetime(cell)
p ... |
def drift(mesh,func,particle):
p = particle
force = func[p.id]*(p.charge/10)*mesh.charge_particle/mesh.length_scale #self force?
#stats.avg_force += numpy.linalg.norm(force)
return force
| print "scatter"
mag = numpy.sqrt(numpy.dot(particle.momentum,particle.momentum))
theta = random.random()*2*numpy.pi
particle.momentum = mag*numpy.cos(theta),mag*numpy.sin(theta) | conditional_block |
driftscatter.py | import ctypes
import random
import math
import numpy
import stats
import constants
#energy = mesh.bandstructure.random_
ext = ctypes.cdll.LoadLibrary("c_optimized/driftscatter.so")
def | (particle,electric_field,density_func,mesh,reaper):
# global avg_lifetime
# lifetime = .001#lifetime(cell)
p = particle
dt = mesh.dt
p.momentum += drift(mesh,electric_field,p)*dt
dx = (p.momentum*dt/mesh.length_scale)/p.mass
#stats.avg_dx += numpy.linalg.norm(dx)
#stats.avg_momentum += numpy.linalg.norm(p.momentu... | randomElectronMovement | identifier_name |
driftscatter.py | import ctypes
import random
import math
import numpy
import stats
import constants
#energy = mesh.bandstructure.random_
ext = ctypes.cdll.LoadLibrary("c_optimized/driftscatter.so")
def randomElectronMovement(particle,electric_field,density_func,mesh,reaper): | p.momentum += drift(mesh,electric_field,p)*dt
dx = (p.momentum*dt/mesh.length_scale)/p.mass
#stats.avg_dx += numpy.linalg.norm(dx)
#stats.avg_momentum += numpy.linalg.norm(p.momentum)
#p.dx += dx
p.pos += dx
# scatter(mesh,particle)
#check for out of bounds
# this needs to be changed, we should
# do all moment... | # global avg_lifetime
# lifetime = .001#lifetime(cell)
p = particle
dt = mesh.dt | random_line_split |
gen_sample.rs | use async_trait::*;
use futures::channel::mpsc::{channel, Receiver, Sender};
use futures::executor::LocalPool;
use futures::sink::SinkExt;
use futures::stream::StreamExt;
use futures::task::LocalSpawnExt;
use macro_test::gen_sample::*;
use pasta_core::Scriptor;
use std::collections::HashSet;
use std::ops::Range;
struc... | let (mut s, mut rx) = TestScriptor::new();
spawner
.spawn_local(async move {
s.tags_mut().insert("通常トーク".to_owned());
s.tags_mut().insert("お昼過ぎ".to_owned());
walk(&mut s, JT::START).await;
})
.unwrap();
let left = pool.run_until(async move { rx.n... | _mut().insert("お昼過ぎ".to_owned());
let jump = walk_one(&mut s, JT::START).await;
let jump = walk_one(&mut s, jump).await;
walk_one(&mut s, jump).await;
})
.unwrap();
let act = pool.run_until(async move { rx.next().await.unwrap() });
let mut right: String = Def... | identifier_body |
gen_sample.rs | use async_trait::*;
use futures::channel::mpsc::{channel, Receiver, Sender};
use futures::executor::LocalPool;
use futures::sink::SinkExt;
use futures::stream::StreamExt;
use futures::task::LocalSpawnExt;
use macro_test::gen_sample::*;
use pasta_core::Scriptor;
use std::collections::HashSet;
use std::ops::Range;
struc... |
impl TestScriptor {
pub fn new() -> (Self, Receiver<String>) {
let (tx, rx) = channel(0);
(
Self {
tags: Default::default(),
talk: Default::default(),
tx: tx,
},
rx,
)
}
}
#[async_trait]
impl Scriptor f... | random_line_split | |
gen_sample.rs | use async_trait::*;
use futures::channel::mpsc::{channel, Receiver, Sender};
use futures::executor::LocalPool;
use futures::sink::SinkExt;
use futures::stream::StreamExt;
use futures::task::LocalSpawnExt;
use macro_test::gen_sample::*;
use pasta_core::Scriptor;
use std::collections::HashSet;
use std::ops::Range;
struc... | {
tags: HashSet<String>,
talk: String,
tx: Sender<String>,
}
impl TestScriptor {
pub fn new() -> (Self, Receiver<String>) {
let (tx, rx) = channel(0);
(
Self {
tags: Default::default(),
talk: Default::default(),
tx: tx,
... | TestScriptor | identifier_name |
pipes.js | import { isBlank, isPresent } from 'angular2/src/facade/lang';
import { BaseException } from 'angular2/src/facade/exceptions';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import * as cd from 'angular2/src/core/change_detection/pipes';
export class ProtoPipes {
constructor(
/**
... | {
constructor(proto, injector) {
this.proto = proto;
this.injector = injector;
/** @internal */
this._config = {};
}
get(name) {
var cached = StringMapWrapper.get(this._config, name);
if (isPresent(cached))
return cached;
var p = this.prot... | Pipes | identifier_name |
pipes.js | import { isBlank, isPresent } from 'angular2/src/facade/lang';
import { BaseException } from 'angular2/src/facade/exceptions';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import * as cd from 'angular2/src/core/change_detection/pipes';
export class ProtoPipes { | constructor(
/**
* Map of {@link PipeMetadata} names to {@link PipeMetadata} implementations.
*/
config) {
this.config = config;
this.config = config;
}
static fromProviders(providers) {
var config = {};
providers.forEach(b => config[b.name] = ... | random_line_split | |
pipes.js | import { isBlank, isPresent } from 'angular2/src/facade/lang';
import { BaseException } from 'angular2/src/facade/exceptions';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import * as cd from 'angular2/src/core/change_detection/pipes';
export class ProtoPipes {
constructor(
/**
... |
return res;
}
}
| {
StringMapWrapper.set(this._config, name, res);
} | conditional_block |
pipes.js | import { isBlank, isPresent } from 'angular2/src/facade/lang';
import { BaseException } from 'angular2/src/facade/exceptions';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import * as cd from 'angular2/src/core/change_detection/pipes';
export class ProtoPipes {
constructor(
/**
... |
get(name) {
var provider = this.config[name];
if (isBlank(provider))
throw new BaseException(`Cannot find pipe '${name}'.`);
return provider;
}
}
export class Pipes {
constructor(proto, injector) {
this.proto = proto;
this.injector = injector;
/**... | {
var config = {};
providers.forEach(b => config[b.name] = b);
return new ProtoPipes(config);
} | identifier_body |
phase5.py | import json
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.utils import timezone
from django.shortcuts import render_to_response
from cir.models import *
import claim_views
from cir.phase_control import PHASE_CONTROL
import utils
def get_statement_comment_list(r... |
return HttpResponse(json.dumps(response), mimetype='application/json')
def view_vote_result(request):
author = request.user
forum = Forum.objects.get(id = request.session['forum_id'])
response = {}
context = {}
context["entries"] = ForumVote.objects.filter(forum = forum)
response["vote_res... | response["my_num_support"] = ForumVote.objects.filter(forum = forum, support = True, author = author).count()
response["my_num_oppose"] = ForumVote.objects.filter(forum = forum, support = False, author = author).count() | conditional_block |
phase5.py | import json
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.utils import timezone
from django.shortcuts import render_to_response
from cir.models import *
import claim_views
from cir.phase_control import PHASE_CONTROL
import utils
def get_statement_comment_list(r... | (request):
reason = request.REQUEST.get('reason')
author = request.user
forum = Forum.objects.get(id = request.session['forum_id'])
support = True
if (request.REQUEST.get('support') == "false"): support = False
vote, created = ForumVote.objects.get_or_create(forum = forum, author = author)
... | vote_issue | identifier_name |
phase5.py | import json
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.utils import timezone
from django.shortcuts import render_to_response
from cir.models import *
import claim_views
from cir.phase_control import PHASE_CONTROL
import utils
def get_statement_comment_list(r... |
def render_support_bar(request):
author = request.user
forum = Forum.objects.get(id = request.session['forum_id'])
response = {}
response["num_support"] = ForumVote.objects.filter(forum = forum, support = True).count()
response["num_oppose"] = ForumVote.objects.filter(forum = forum, support = Fals... | reason = request.REQUEST.get('reason')
author = request.user
forum = Forum.objects.get(id = request.session['forum_id'])
support = True
if (request.REQUEST.get('support') == "false"): support = False
vote, created = ForumVote.objects.get_or_create(forum = forum, author = author)
vote.reason = r... | identifier_body |
phase5.py | import json
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.utils import timezone
from django.shortcuts import render_to_response
from cir.models import *
import claim_views
from cir.phase_control import PHASE_CONTROL
import utils
| thread_comments = ForumComment.objects.filter(forum = forum)
print thread_comments
context['comments'] = thread_comments
response['forum_comment'] = render_to_string("phase5/forum-comment.html", context)
return HttpResponse(json.dumps(response), mimetype='application/json')
def put_statement_commen... | def get_statement_comment_list(request):
response = {}
context = {}
forum = Forum.objects.get(id = request.session['forum_id']) | random_line_split |
main.rs | use std::env;
fn first_factor(product: u64) -> u64 {
let mut primes = Vec::new();
for i in 2..(product + 1) {
if !primes.iter().any(|p| i % p == 0) { // is prime
if product % i == 0 {
return i;
}
primes.push(i);
}
}
1
}
fn largest_... |
fn main() {
match env::args().nth(1) {
None => println!("Needs a first argument"),
Some(string) => match string.parse::<u64>() {
Ok(product) => println!("{}", largest_prime(product)),
Err(_) => println!("First argument must be an int"),
}
}
}
| {
let mut remaining = product;
let mut primes = Vec::new();
loop {
let factor = first_factor(remaining);
primes.push(factor);
remaining = remaining / factor;
if factor == 1 {
break;
}
}
let mut max_prime = 1;
for p in primes {
if p > m... | identifier_body |
main.rs | use std::env;
fn first_factor(product: u64) -> u64 {
let mut primes = Vec::new();
for i in 2..(product + 1) {
if !primes.iter().any(|p| i % p == 0) { // is prime
if product % i == 0 {
return i;
}
primes.push(i);
}
}
1
}
fn | (product: u64) -> u64 {
let mut remaining = product;
let mut primes = Vec::new();
loop {
let factor = first_factor(remaining);
primes.push(factor);
remaining = remaining / factor;
if factor == 1 {
break;
}
}
let mut max_prime = 1;
for p in pri... | largest_prime | identifier_name |
main.rs | use std::env;
fn first_factor(product: u64) -> u64 {
let mut primes = Vec::new();
for i in 2..(product + 1) {
if !primes.iter().any(|p| i % p == 0) { // is prime
if product % i == 0 {
return i;
}
primes.push(i);
}
}
1
}
fn largest_... | let mut remaining = product;
let mut primes = Vec::new();
loop {
let factor = first_factor(remaining);
primes.push(factor);
remaining = remaining / factor;
if factor == 1 {
break;
}
}
let mut max_prime = 1;
for p in primes {
if p > max... | random_line_split | |
limited-debuginfo.rs | // Copyright 2013-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-MI... | (a: int, b: int) {
let some_variable = Struct { a: 11, b: 22 };
let some_other_variable = 23i;
zzz(); // #break
}
fn some_other_function(a: int, b: int) -> bool { true }
| some_function | identifier_name |
limited-debuginfo.rs | // Copyright 2013-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-MI... |
fn zzz() {()}
fn some_function(a: int, b: int) {
let some_variable = Struct { a: 11, b: 22 };
let some_other_variable = 23i;
zzz(); // #break
}
fn some_other_function(a: int, b: int) -> bool { true }
| {
some_function(101, 202);
some_other_function(1, 2);
} | identifier_body |
limited-debuginfo.rs | // Copyright 2013-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-MI... | // Make sure there is no information about locals
// gdb-command:info locals
// gdb-check:No locals.
// gdb-command:continue
#![allow(unused_variables)]
struct Struct {
a: i64,
b: i32
}
fn main() {
some_function(101, 202);
some_other_function(1, 2);
}
fn zzz() {()}
fn some_function(a: int, b: int... | // gdb-check:[...]void[...]some_other_function([...]);
// gdb-check:[...]void[...]zzz([...]);
// gdb-command:run
| random_line_split |
explorerViewModel.ts | /common/editor';
import { ResourceMap } from 'vs/base/common/map';
import { isLinux } from 'vs/base/common/platform';
export enum StatType {
FILE,
FOLDER,
ANY
}
export class FileStat implements IFileStat {
public resource: URI;
public name: string;
public mtime: number;
public etag: string;
public isDirectory... | (newParent: NewStat | move | identifier_name |
explorerViewModel.ts | children if present
if (stat.isDirectory) {
// isDirectoryResolved is a very important indicator in the stat model that tells if the folder was fully resolved
// the folder is fully resolved if either it has a list of children or the client requested this by using the resolveTo
// array of resource path to... | public getResource(): URI { | random_line_split | |
explorerViewModel.ts | /common/editor';
import { ResourceMap } from 'vs/base/common/map';
import { isLinux } from 'vs/base/common/platform';
export enum StatType {
FILE,
FOLDER,
ANY
}
export class FileStat implements IFileStat {
public resource: URI;
public name: string;
public mtime: number;
public etag: string;
public isDirectory... |
/**
* Removes a child element from this folder.
*/
public removeChild(child: FileStat): void {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i].resource.toString() === child.resource.toString()) {
this.children.splice(i, 1);
break;
}
}
this.hasChildren = this.children.l... | {
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
if ((type === StatType.FILE && child.isDirectory) || (type === StatType.FOLDER && !child.isDirectory)) {
continue;
}
// Check for Identity
if (child.name === name) {
return true;
}
// Also consider compar... | identifier_body |
explorerViewModel.ts | /common/editor';
import { ResourceMap } from 'vs/base/common/map';
import { isLinux } from 'vs/base/common/platform';
export enum StatType {
FILE,
FOLDER,
ANY
}
export class FileStat implements IFileStat {
public resource: URI;
public name: string;
public mtime: number;
public etag: string;
public isDirectory... |
// Stop merging when a folder is not resolved to avoid loosing local data
const mergingDirectories = disk.isDirectory || local.isDirectory;
if (mergingDirectories && local.isDirectoryResolved && !disk.isDirectoryResolved) {
return;
}
// Properties
local.resource = disk.resource;
local.name = disk.na... | {
return; // Merging only supported for stats with the same resource
} | conditional_block |
createCollaborationReducer.js | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distribut... | * with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import ACTION_NAMES from '../actions/collaborationsActions'
const initialState = {
createCollaborationPending: false,
createCollaborationSuccessful: false,
createCollaborationError: null
}
let createHandlers = {
[ACTION_NAMES.... | *
* You should have received a copy of the GNU Affero General Public License along | random_line_split |
createCollaborationReducer.js | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distribut... | else {
return state
}
}
| {
return createHandlers[action.type](state, action)
} | conditional_block |
BayesUpdating.py | # Add any code that updates the current probability
# values of any of the nodes here.
# For example, here is a method that updates the probability of
# a single node, where this node is assumed to have a single parent.
def update_node_with_one_parent(n):
'''
For all possible values pv of the current node,
... |
def gen_cartesian_product(sets):
'''Return the cartesian product of a list of sets.
For example: [['a','b'],[0,1],[7,8,9]] should give a 12 element set of triples.'''
if len(sets)==1:
return map(lambda set: [set], sets[0])
subproduct = gen_cartesian_product(sets[1:])
prod = []
for e... | conditional = n.name+'='+str(pv)+'|'+parent.name+'='+str(ppv)
n.current_prob[pv] += n.p[conditional] * parent.current_prob[ppv] | conditional_block |
BayesUpdating.py | # Add any code that updates the current probability
# values of any of the nodes here.
# For example, here is a method that updates the probability of
# a single node, where this node is assumed to have a single parent.
def update_node_with_one_parent(n):
'''
For all possible values pv of the current node,
... | parent_vector_prob = reduce(lambda a,b:a*b, map(lambda p, pv:p.current_prob[pv], n.parents, ppv_tuple))
n.current_prob[pv] += n.p[conditional] * parent_vector_prob
#update_node_with_one_parent(nodeB)
| '''
For all possible values pv of the current node,
For all possible values ppv of each of the parents,
Look up the conditional probability of pv given ppv.
and multiply it by the current prob. of that parent state (ppv)
and accumulate these to get the current probability of pv.
'''... | identifier_body |
BayesUpdating.py | # Add any code that updates the current probability
# values of any of the nodes here.
# For example, here is a method that updates the probability of
# a single node, where this node is assumed to have a single parent.
def update_node_with_one_parent(n):
'''
For all possible values pv of the current node,
... | For all possible values pv of the current node,
For all possible values ppv of each of the parents,
Look up the conditional probability of pv given ppv.
and multiply it by the current prob. of that parent state (ppv)
and accumulate these to get the current probability of pv.
'''
... | def update_node_with_k_parents(n):
''' | random_line_split |
BayesUpdating.py | # Add any code that updates the current probability
# values of any of the nodes here.
# For example, here is a method that updates the probability of
# a single node, where this node is assumed to have a single parent.
def update_node_with_one_parent(n):
'''
For all possible values pv of the current node,
... | (sets):
'''Return the cartesian product of a list of sets.
For example: [['a','b'],[0,1],[7,8,9]] should give a 12 element set of triples.'''
if len(sets)==1:
return map(lambda set: [set], sets[0])
subproduct = gen_cartesian_product(sets[1:])
prod = []
for elt in sets[0]:
new_... | gen_cartesian_product | identifier_name |
test.js |
// for tests need to install mocha:
// npm install -g mocha
//
// then to run a test
//
// mocha test.js
//
var assert = require("assert");
require('./index')
// the values are arrays of elements.
describe('groupby',function(){
it("should sort items into buckets. return an object - put each item of an array... | ;
assert.deepEqual(sortkeys(obj,comparator_desc),sorteddesc);
})
})
describe('objtokvarr',function(){
it("should convert object to array of objects of key and value",function(){
var obj={aa:123};
var kva=[ {k:'aa',v:123} ];
assert.deepEqual(objtokvarr(obj),kva);
})
it("should be able to use define... | {return a==b?0:(a>b?-1:1)} | identifier_body |
test.js |
// for tests need to install mocha:
// npm install -g mocha
//
// then to run a test
//
// mocha test.js
//
var assert = require("assert");
require('./index')
// the values are arrays of elements.
describe('groupby',function(){
it("should sort items into buckets. return an object - put each item of an array... | (a,b) {return a==b?0:(a>b?-1:1)};
assert.deepEqual(sortkeys(obj,comparator_desc),sorteddesc);
})
})
describe('objtokvarr',function(){
it("should convert object to array of objects of key and value",function(){
var obj={aa:123};
var kva=[ {k:'aa',v:123} ];
assert.deepEqual(objtokvarr(obj),kva);
})
... | comparator_desc | identifier_name |
test.js | // for tests need to install mocha:
// npm install -g mocha
//
// then to run a test
//
// mocha test.js
//
var assert = require("assert");
require('./index')
// the values are arrays of elements.
describe('groupby',function(){
it("should sort items into buckets. return an object - put each item of an array ... | })
describe('sortobjkey',function(){
it("should sort object's keys by value is desc order",function(){
var obj={aa:{f:2},bb:{f:1},cc:{f:3}};
var sorted={cc:{f:3},aa:{f:2},bb:{f:1}};
assert.deepEqual(sortobjkey(obj,'f'),sorted);
})
})
describe('sortkeys',function(){
it("should sort object's keys by thei... | random_line_split | |
website_event_ticket_details.js | odoo.define('website_event.ticket_details', function (require) {
var publicWidget = require('web.public.widget');
publicWidget.registry.ticketDetailsWidget = publicWidget.Widget.extend({
selector: '.o_wevent_js_ticket_details',
events: {
'click .o_wevent_registration_btn': '_onTicke... | }
});
return publicWidget.registry.ticketDetailsWidget;
}); | _onTicketQuantityChange: function (){
this.$('button.btn-primary').attr('disabled', this._getTotalTicketCount() === 0); | random_line_split |
website_event_ticket_details.js | odoo.define('website_event.ticket_details', function (require) {
var publicWidget = require('web.public.widget');
publicWidget.registry.ticketDetailsWidget = publicWidget.Widget.extend({
selector: '.o_wevent_js_ticket_details',
events: {
'click .o_wevent_registration_btn': '_onTicke... |
},
/**
* @private
*/
_onTicketQuantityChange: function (){
this.$('button.btn-primary').attr('disabled', this._getTotalTicketCount() === 0);
}
});
return publicWidget.registry.ticketDetailsWidget;
});
| {
$(ev.currentTarget).toggleClass('btn-primary text-left pl-0');
$(ev.currentTarget).siblings().toggleClass('d-none');
this.$('.close').toggleClass('d-none');
} | conditional_block |
MainProcessSingleton.js | /* 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 strict";
const { utils: Cu, interfaces: Ci, classes: Cc, results: Cr } = Components;
Cu.import("resource://... |
MainProcessSingleton.prototype = {
classID: Components.ID("{0636a680-45cb-11e4-916c-0800200c9a66}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
Ci.nsISupportsWeakReference]),
logConsoleMessage: function(message) {
let logMsg = message.data;
logMsg.wra... | {} | identifier_body |
MainProcessSingleton.js | /* 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 strict";
const { utils: Cu, interfaces: Ci, classes: Cc, results: Cr } = Components;
Cu.import("resource://... | Services.obs.addObserver(this, "xpcom-shutdown", false);
// Load this script early so that console.* is initialized
// before other frame scripts.
Services.mm.loadFrameScript("chrome://global/content/browser-content.js", true);
Services.ppmm.loadProcessScript("chrome://global/content/proc... | random_line_split | |
MainProcessSingleton.js | /* 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 strict";
const { utils: Cu, interfaces: Ci, classes: Cc, results: Cr } = Components;
Cu.import("resource://... | () {}
MainProcessSingleton.prototype = {
classID: Components.ID("{0636a680-45cb-11e4-916c-0800200c9a66}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
Ci.nsISupportsWeakReference]),
logConsoleMessage: function(message) {
let logMsg = message.data;
logMs... | MainProcessSingleton | identifier_name |
informant.rs | ::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering};
use std::time::{Instant, Duration};
use io::{TimerToken, IoContext, IoHandler};
use isatty::{stdout_isatty};
use ethsync::{SyncProvider, ManageNetwork};
use util::{Uint, RwLock, Mutex, H256, Colour, Bytes};
use ethcore::client::*;
use ethcore::service::Cl... | let mut write_report = self.report.write();
let report = self.client.report();
let paint = |c: Style, t: String| match self.with_color && stdout_isatty() {
true => format!("{}", c.paint(t)),
false => t,
};
info!(target: "import", "{} {} {} {}",
match importing {
true => match snapshot_sync {... | random_line_split | |
informant.rs | ::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering};
use std::time::{Instant, Duration};
use io::{TimerToken, IoContext, IoHandler};
use isatty::{stdout_isatty};
use ethsync::{SyncProvider, ManageNetwork};
use util::{Uint, RwLock, Mutex, H256, Colour, Bytes};
use ethcore::client::*;
use ethcore::service::Cl... | (
client: Arc<Client>,
sync: Option<Arc<SyncProvider>>,
net: Option<Arc<ManageNetwork>>,
snapshot: Option<Arc<SnapshotService>>,
rpc_stats: Option<Arc<RpcStats>>,
with_color: bool,
) -> Self {
Informant {
report: RwLock::new(None),
last_tick: RwLock::new(Instant::now()),
with_color: with_color,
... | new | identifier_name |
informant.rs | ::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering};
use std::time::{Instant, Duration};
use io::{TimerToken, IoContext, IoHandler};
use isatty::{stdout_isatty};
use ethsync::{SyncProvider, ManageNetwork};
use util::{Uint, RwLock, Mutex, H256, Colour, Bytes};
use ethcore::client::*;
use ethcore::service::Cl... |
}
impl Informant {
/// Make a new instance potentially `with_color` output.
pub fn new(
client: Arc<Client>,
sync: Option<Arc<SyncProvider>>,
net: Option<Arc<ManageNetwork>>,
snapshot: Option<Arc<SnapshotService>>,
rpc_stats: Option<Arc<RpcStats>>,
with_color: bool,
) -> Self {
Informant {
report:... | {
self.as_secs() * 1000 + self.subsec_nanos() as u64 / 1_000_000
} | identifier_body |
util.py | (self, key):
"""Add a key.
If it is new, return True otherwise False.
"""
if key in self._data:
return False
self._data[key] = 1
removed = self._q.getput(key)
if removed is not None:
del self._data[removed]
return True
def traceba... | add | identifier_name | |
util.py | progress meter."""
REPORT_INTERVAL = 1000
def __init__(self, ofile, units="lines"):
self.ofile = ofile
self.units = units
self._counter = 0
self.reset(0)
def reset(self, n):
self.t0 = time.time()
self.last_report = n
def advance(self, num=0, inc=1):
... | return True | identifier_body | |
util.py | if not (isinstance(infile, str) or hasattr(infile, "read")):
# not a file: stop
configobj.ConfigObj.__init__(self, infile, **kw)
return
# open file
if hasattr(infile, "read"):
f = infile
f.seek(0) # rewind to start of file
else... | return text | conditional_block | |
util.py | :
iso += "T00:00:00"
# only append timezone if none is there already
if not iso.endswith("Z") and not re.match(r".*[+-]\d\d:\d\d$", iso):
if utc:
iso += "Z"
else:
iso += tzstr()
return parseDate(iso)
class ProgressMeter:
"""A simple textual progress mete... | """Start the timer."""
self.t0 = time.time()
def throttle(self):
"""Sleep for an appropriate time.
If that time would be less than 'min_sleep_sec' (see constructor),
don't actually perform the sleep. Therefore, it should be safe
to call this in a (relatively) tight ... | self.min_sleep_sec = min_sleep_sec
def start(self): | random_line_split |
debounce.py | """Debounce helper."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from logging import Logger
from typing import Any
from homeassistant.core import HassJob, HomeAssistant, callback
class Debouncer:
"""Class to rate limit calls to a specific command."""
... | immediate: indicate if the function needs to be called right away and
wait <cooldown> until executing next invocation.
function: optional and can be instantiated later.
"""
self.hass = hass
self.logger = logger
self._function = function
self.coo... | """Initialize debounce.
| random_line_split |
debounce.py | """Debounce helper."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from logging import Logger
from typing import Any
from homeassistant.core import HassJob, HomeAssistant, callback
class Debouncer:
"""Class to rate limit calls to a specific command."""
... |
@callback
def _schedule_timer(self) -> None:
"""Schedule a timer."""
self._timer_task = self.hass.loop.call_later(
self.cooldown,
lambda: self.hass.async_create_task(self._handle_timer_finish()),
)
| """Cancel any scheduled call."""
if self._timer_task:
self._timer_task.cancel()
self._timer_task = None
self._execute_at_end_of_timer = False | identifier_body |
debounce.py | """Debounce helper."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from logging import Logger
from typing import Any
from homeassistant.core import HassJob, HomeAssistant, callback
class Debouncer:
"""Class to rate limit calls to a specific command."""
... | (
self,
hass: HomeAssistant,
logger: Logger,
*,
cooldown: float,
immediate: bool,
function: Callable[..., Awaitable[Any]] | None = None,
) -> None:
"""Initialize debounce.
immediate: indicate if the function needs to be called right away and
... | __init__ | identifier_name |
debounce.py | """Debounce helper."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from logging import Logger
from typing import Any
from homeassistant.core import HassJob, HomeAssistant, callback
class Debouncer:
"""Class to rate limit calls to a specific command."""
... |
return
# Locked means a call is in progress. Any call is good, so abort.
if self._execute_lock.locked():
return
if not self.immediate:
self._execute_at_end_of_timer = True
self._schedule_timer()
return
async with self._exec... | self._execute_at_end_of_timer = True | conditional_block |
textArea.py | """
The ``ui.TextArea`` class implements a standard multi-line input field.
The ``setCharacterWidth()`` method sets the width of the input field, in
characters, while ``setVisibleLines()`` sets the height of the field, in lines.
Use the ``getText()`` method to retrieve the field's current text, and
``setText()`` to s... | (self, text):
TextArea.setText(self, text)
self.autoHeight()
| setText | identifier_name |
textArea.py | """
The ``ui.TextArea`` class implements a standard multi-line input field.
The ``setCharacterWidth()`` method sets the width of the input field, in
characters, while ``setVisibleLines()`` sets the height of the field, in lines.
Use the ``getText()`` method to retrieve the field's current text, and
``setText()`` to s... |
def done(self):
Window.alert("Ctrl-enter!")
class AutoTextArea(TextArea):
def __init__(self, doneHandler):
TextArea.__init__(self)
self.doneHandler = doneHandler #this handler will be called when user press ctrl-enter
def onBrowserEvent(self, event):
if event.type == "ke... | VerticalPanel.__init__(self)
self.setSpacing("10px")
field = TextArea()
field.setCharacterWidth(20)
field.setVisibleLines(4)
self.add(field)
self.add(AutoTextArea(self)) | identifier_body |
textArea.py | """
The ``ui.TextArea`` class implements a standard multi-line input field.
The ``setCharacterWidth()`` method sets the width of the input field, in
characters, while ``setVisibleLines()`` sets the height of the field, in lines.
Use the ``getText()`` method to retrieve the field's current text, and
``setText()`` to s... |
newHeight = str(16*(2+c)) + "px"
self.setHeight(newHeight)
def setText(self, text):
TextArea.setText(self, text)
self.autoHeight()
| fsize = 9
a = float(len(i)*fsize) / float((self.getOffsetWidth()/fsize)*fsize)
b = int(math.ceil(a))
c += max(1,b) | conditional_block |
textArea.py | """
The ``ui.TextArea`` class implements a standard multi-line input field.
The ``setCharacterWidth()`` method sets the width of the input field, in
characters, while ``setVisibleLines()`` sets the height of the field, in lines.
Use the ``getText()`` method to retrieve the field's current text, and
``setText()`` to s... |
class AutoTextArea(TextArea):
def __init__(self, doneHandler):
TextArea.__init__(self)
self.doneHandler = doneHandler #this handler will be called when user press ctrl-enter
def onBrowserEvent(self, event):
if event.type == "keydown":
if event.keyCode == 13 and event.ctrlKe... | random_line_split | |
pdb_dist-filter.py | #!/usr/bin/env python
# Copyright 2007, Michael J. Harms
# This program is distributed under General Public License v. 3. See the file
# COPYING for a copy of the license.
__author__ = "Michael J. Harms"
__date__ = "070709"
__description__ = \
"""
pdb_dist-filter.py
Takes pdb file and calculates the distance betw... |
# Parse command line if called from command line
if __name__ == "__main__":
main()
| f = open(pdb_file,'r')
pdb = f.readlines()
f.close()
# Perform analysis
dist = distFilter(pdb,residue,atom,column,select)
# dump output to stdout
out = ["%10i%10.3F\n" % (i,d) for i, d in enumerate(dist)]
out.insert(0,"%10s%10s\n" % (" ","dist"))
print "... | conditional_block |
pdb_dist-filter.py | #!/usr/bin/env python
# Copyright 2007, Michael J. Harms
# This program is distributed under General Public License v. 3. See the file
# COPYING for a copy of the license.
__author__ = "Michael J. Harms"
__date__ = "070709"
__description__ = \
"""
pdb_dist-filter.py
Takes pdb file and calculates the distance betw... | if len(pdb) == 0:
err = "pdb file does not contain any atoms of type \"%s\"" % atom
raise IOError(err)
# Pull residue coordinates
res_coord = [extractCoor(l) for l in pdb if l[22:26] == "%4i" % residue][0]
# Pull selected residue coordinates
try:
na_coord = [extractCoor(l... | atom = "%-3s" % (atom.strip())
# Grab only "atom" lines out of pdb
pdb = [l for l in pdb if l[0:4] == "ATOM" and l[13:16] == atom]
| random_line_split |
pdb_dist-filter.py | #!/usr/bin/env python
# Copyright 2007, Michael J. Harms
# This program is distributed under General Public License v. 3. See the file
# COPYING for a copy of the license.
__author__ = "Michael J. Harms"
__date__ = "070709"
__description__ = \
"""
pdb_dist-filter.py
Takes pdb file and calculates the distance betw... | try:
na_coord = [extractCoor(l) for l in pdb
if l[column[0]:column[1]] == select]
except IndexError:
err = "Invalid column defined by line[%i:%i]" % (column[0],column[1])
raise IOErro(err)
if len(na_coord) == 0:
err = "Column line[%i:%i] does not con... | """
Calculate the distance between "residue" "atom" and the "atom" of residues
that have column defined by "column" == "select". Default is to compare
nitrogen of "residue" to nitrogens or residues with b-factor == NA.
"""
# Make sure atom entry is in correct format
atom = "%-3s" % (atom.st... | identifier_body |
pdb_dist-filter.py | #!/usr/bin/env python
# Copyright 2007, Michael J. Harms
# This program is distributed under General Public License v. 3. See the file
# COPYING for a copy of the license.
__author__ = "Michael J. Harms"
__date__ = "070709"
__description__ = \
"""
pdb_dist-filter.py
Takes pdb file and calculates the distance betw... | (pdb,residue,atom="N",column=[60,66],select=" NA"):
"""
Calculate the distance between "residue" "atom" and the "atom" of residues
that have column defined by "column" == "select". Default is to compare
nitrogen of "residue" to nitrogens or residues with b-factor == NA.
"""
# Make sure a... | distFilter | identifier_name |
leaf.js | /**
* @class PrettyJSON.view.Leaf
* @extends Backbone.View
*
* @author #rbarriga
* @version 0.1
*
*/
PrettyJSON.view.Leaf = Backbone.View.extend({
tagName:'span',
data:null,
level:0,
path:'',
type:'string',
isLast: true,
events: {
"mouseover .leaf-container": "mouseover",
"m... | var view = this;
while (view){
var td = view.parentTd;
if(td)
this.tds.push(td);
view = view.parent;
}
},
toggleTdPath:function(show){
this.getTds();
_.each(this.tds,function(td){
show ?
td.a... | this.toggleTdPath(false);
this.trigger("mouseout",e);
},
getTds:function(){
this.tds = []; | random_line_split |
base.py | #
# 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 | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#... | #
# http://www.apache.org/licenses/LICENSE-2.0
# | random_line_split |
base.py | #
# 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 in writing, software
# distributed under ... | (Struct):
task = Required(Task)
instance = Required(Integer)
role = Required(String)
announce = Announcer
environment = Required(String)
health_check_config = Default(HealthCheckConfig, HealthCheckConfig())
lifecycle = LifecycleConfig
... | MesosTaskInstance | identifier_name |
base.py | #
# 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 in writing, software
# distributed under ... |
# The executorConfig populated inside of TaskConfig.
class MesosTaskInstance(Struct):
task = Required(Task)
instance = Required(Integer)
role = Required(String)
announce = Announcer
environment = Required(String)
health_check_config = Default(He... | primary_port = Default(String, 'http')
# Portmap can either alias two ports together, e.g.
# aurora <= http
# Or it can be used to alias static ports to endpoints, e.g.
# http <= 80
# https <= 443
# aurora <= https
portmap = Default(Map(String, String), {
'aurora': '{{primary_port}}'
}... | identifier_body |
paraiso_light.py | # -*- coding: utf-8 -*-
"""
pygments.styles.paraiso_light
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Paraíso (Light) by Jan T. Sott
Pygments template by Jan T. Sott (https://github.com/idleberg)
Created with Base16 Builder by Chris Kempson
(https://github.com/chriskempson/base16-builder).
:copyright: ... | Style):
default_style = ''
background_color = BACKGROUND
highlight_color = SELECTION
background_color = BACKGROUND
highlight_color = SELECTION
styles = {
# No corresponding class for the following:
Text: FOREGROUND, # class: ''
Whitespace: ... | araisoLightStyle( | identifier_name |
paraiso_light.py | # -*- coding: utf-8 -*-
"""
pygments.styles.paraiso_light
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Paraíso (Light) by Jan T. Sott
Pygments template by Jan T. Sott (https://github.com/idleberg)
Created with Base16 Builder by Chris Kempson
(https://github.com/chriskempson/base16-builder).
:copyright: ... |
Keyword: PURPLE, # class: 'k'
Keyword.Constant: "", # class: 'kc'
Keyword.Declaration: "", # class: 'kd'
Keyword.Namespace: AQUA, # class: 'kn'
Keyword.Pseudo: "", # class: 'kp'
Keyword.Rese... | efault_style = ''
background_color = BACKGROUND
highlight_color = SELECTION
background_color = BACKGROUND
highlight_color = SELECTION
styles = {
# No corresponding class for the following:
Text: FOREGROUND, # class: ''
Whitespace: "", ... | identifier_body |
paraiso_light.py | # -*- coding: utf-8 -*-
"""
pygments.styles.paraiso_light
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Paraíso (Light) by Jan T. Sott
Pygments template by Jan T. Sott (https://github.com/idleberg)
Created with Base16 Builder by Chris Kempson
(https://github.com/chriskempson/base16-builder).
:copyright: ... | String.Single: "", # class: 's1'
String.Symbol: "", # class: 'ss'
Generic: "", # class: 'g'
Generic.Deleted: RED, # class: 'gd',
Generic.Emph: "italic", ... | String.Escape: ORANGE, # class: 'se'
String.Heredoc: "", # class: 'sh'
String.Interpol: ORANGE, # class: 'si'
String.Other: "", # class: 'sx'
String.Regex: "", # class: 'sr' | random_line_split |
config.ts | import {Type} from '@angular/core';
export type RouterConfig = Route[];
export interface Route {
path?: string;
terminal?: boolean;
component?: Type|string;
outlet?: string;
canActivate?: any[];
canDeactivate?: any[];
redirectTo?: string;
children?: Route[];
}
export function validateConfig(config: R... | (route: Route): void {
if (!!route.redirectTo && !!route.children) {
throw new Error(
`Invalid configuration of route '${route.path}': redirectTo and children cannot be used together`);
}
if (!!route.redirectTo && !!route.component) {
throw new Error(
`Invalid configuration of route '${rou... | validateNode | identifier_name |
config.ts | import {Type} from '@angular/core';
export type RouterConfig = Route[];
export interface Route {
path?: string;
terminal?: boolean;
component?: Type|string;
outlet?: string;
canActivate?: any[];
canDeactivate?: any[];
redirectTo?: string;
children?: Route[];
}
export function validateConfig(config: R... | `Invalid configuration of route '${route.path}': component, redirectTo, children must be provided`);
}
if (route.path === undefined) {
throw new Error(`Invalid route configuration: routes must have path specified`);
}
if (route.path.startsWith('/')) {
throw new Error(
`Invalid route conf... | throw new Error( | random_line_split |
config.ts | import {Type} from '@angular/core';
export type RouterConfig = Route[];
export interface Route {
path?: string;
terminal?: boolean;
component?: Type|string;
outlet?: string;
canActivate?: any[];
canDeactivate?: any[];
redirectTo?: string;
children?: Route[];
}
export function validateConfig(config: R... |
if (route.redirectTo === undefined && !route.component && !route.children) {
throw new Error(
`Invalid configuration of route '${route.path}': component, redirectTo, children must be provided`);
}
if (route.path === undefined) {
throw new Error(`Invalid route configuration: routes must have path ... | {
throw new Error(
`Invalid configuration of route '${route.path}': redirectTo and component cannot be used together`);
} | conditional_block |
config.ts | import {Type} from '@angular/core';
export type RouterConfig = Route[];
export interface Route {
path?: string;
terminal?: boolean;
component?: Type|string;
outlet?: string;
canActivate?: any[];
canDeactivate?: any[];
redirectTo?: string;
children?: Route[];
}
export function validateConfig(config: R... | } | {
if (!!route.redirectTo && !!route.children) {
throw new Error(
`Invalid configuration of route '${route.path}': redirectTo and children cannot be used together`);
}
if (!!route.redirectTo && !!route.component) {
throw new Error(
`Invalid configuration of route '${route.path}': redirectTo... | identifier_body |
main.js | $(function(){
//阅读全文按钮
$('.post-permalink .btn').click(function(){
});
//留言版-显示表情包
$tog=true;
$('.face-img').click(function(){
if($tog){
$('.exp-box').show();
}else{
$('.exp-box').hide();
}
$tog=!$tog;
});
//留言板-留言:转换表情
$arr_face=[];
$all_face=[];
$msg_face=[];
for($i=0; $i< $('.exp-box li'... | this);
$.ajax(
{
url:'index.php?r=message/ref',
type:'post',
dataType: "json",
data:{
id:$idData
},
success:function(str){
if(str.code == 0){
//顶值+1
$accNum=$_this.html().replace(/\(\d+\)/,function(str2){
str2=str2.substring(1,str2.length-1);
str2++;
... | tr("messageid");
$_this=$( | conditional_block |
main.js | $(function(){
//阅读全文按钮
$('.post-permalink .btn').click(function(){
});
//留言版-显示表情包
$tog=true;
$('.face-img').click(function(){
if($tog){
$('.exp-box').show();
}else{
$('.exp-box').hide();
}
$tog=!$tog;
});
//留言板-留言:转换表情
$arr_face=[];
$all_face=[];
$msg_face=[];
for($i=0; $i< $('.exp-box li'... | i]+'">';
}
}
return $n;
} | '+$arr2[$ | identifier_name |
main.js | $(function(){
//阅读全文按钮
$('.post-permalink .btn').click(function(){
});
//留言版-显示表情包
$tog=true;
$('.face-img').click(function(){
if($tog){
$('.exp-box').show();
}else{
$('.exp-box').hide();
}
$tog=!$tog;
});
//留言板-留言:转换表情
$arr_face=[];
$all_face=[];
$msg_face=[];
for($i=0; $i< $('.exp-box li'... | //顶值+1
$accNum=$_this.html().replace(/\(\d+\)/,function(str2){
str2=str2.substring(1,str2.length-1);
str2++;
return '('+str2+')';
});
//重新给顶-赋值
$_this.html($accNum);
}else{
return false;
}
}
}
);
});
//留言板-点击“踩”按钮
$('.ref').click(function(){... | },
success:function(str){
if(str.code == 0){ | random_line_split |
main.js | $(function(){
//阅读全文按钮
$('.post-permalink .btn').click(function(){
});
//留言版-显示表情包
$tog=true;
$('.face-img').click(function(){
if($tog){
$('.exp-box').show();
}else{
$('.exp-box').hide();
}
$tog=!$tog;
});
//留言板-留言:转换表情
$arr_face=[];
$all_face=[];
$msg_face=[];
for($i=0; $i< $('.exp-box li'... |
return $n;
} | identifier_body | |
prism-custom-class.ts | let customClass: null | {
[key: string]: string
} = null;
const classList = [
'pre',
'code',
'inline',
'token',
'keyword',
'selector-tag',
'title',
'section',
'doctag',
'name',
'strong',
'comment',
'string',
'built_in',
'literal',
'type',
'addition',
'tag',
'quote',
'selector... | 'operator',
'constant',
'attr-value',
'attr-name',
'class-name',
'builtin',
'property',
'selector',
'at',
'decorator',
'template-string',
'boolean',
'function-variable'
]; // Must be equal to: Alyle-UI/tools/src/html-loader/prism-custom-class.ts
export const prismCustomClass = () => {
if (!c... | random_line_split | |
prism-custom-class.ts |
let customClass: null | {
[key: string]: string
} = null;
const classList = [
'pre',
'code',
'inline',
'token',
'keyword',
'selector-tag',
'title',
'section',
'doctag',
'name',
'strong',
'comment',
'string',
'built_in',
'literal',
'type',
'addition',
'tag',
'quote',
'selecto... |
return customClass;
};
| {
customClass = {};
classList.forEach((className, index) => {
customClass![className] = `tt${(index * 11 + 11).toString(36)}`;
});
} | conditional_block |
operator-multidispatch.rs | // run-pass
// Test that we can overload the `+` operator for points so that two
// points can be added, and a point can be added to an integer.
use std::ops;
#[derive(Debug,PartialEq,Eq)]
struct Point {
x: isize,
y: isize
}
impl ops::Add for Point {
type Output = Point;
fn add(self, other: Point) -... | {
let mut p = Point {x: 10, y: 20};
p = p + Point {x: 101, y: 102};
assert_eq!(p, Point {x: 111, y: 122});
p = p + 1;
assert_eq!(p, Point {x: 112, y: 123});
} | identifier_body | |
operator-multidispatch.rs | // run-pass
// Test that we can overload the `+` operator for points so that two
// points can be added, and a point can be added to an integer.
use std::ops;
#[derive(Debug,PartialEq,Eq)]
struct Point {
x: isize,
y: isize
}
impl ops::Add for Point {
type Output = Point;
fn add(self, other: Point) -... | (self, other: isize) -> Point {
Point {x: self.x + other,
y: self.y + other}
}
}
pub fn main() {
let mut p = Point {x: 10, y: 20};
p = p + Point {x: 101, y: 102};
assert_eq!(p, Point {x: 111, y: 122});
p = p + 1;
assert_eq!(p, Point {x: 112, y: 123});
}
| add | identifier_name |
operator-multidispatch.rs | // run-pass
// Test that we can overload the `+` operator for points so that two
// points can be added, and a point can be added to an integer.
use std::ops;
#[derive(Debug,PartialEq,Eq)]
struct Point {
x: isize,
y: isize
}
impl ops::Add for Point {
type Output = Point;
fn add(self, other: Point) -... | assert_eq!(p, Point {x: 112, y: 123});
} | p = p + Point {x: 101, y: 102};
assert_eq!(p, Point {x: 111, y: 122});
p = p + 1; | random_line_split |
hostname.rs | #![crate_name = "uu_hostname"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alan Andrade <alan.andradec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Synced with:
*
* https://www.opensource.appl... |
fn xgethostname() -> String {
let namelen = 256usize;
let mut name : Vec<u8> = repeat(0).take(namelen).collect();
let err = unsafe {
gethostname (name.as_mut_ptr() as *mut libc::c_char,
namelen as libc::size_t)
};
if err != 0 {
panic!("Canno... | {
version();
println!("");
println!("Usage:");
println!(" {} [OPTION]... [HOSTNAME]", program);
println!("");
print!("{}", options.usage("Print or set the system's host name."));
} | identifier_body |
hostname.rs | #![crate_name = "uu_hostname"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alan Andrade <alan.andradec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Synced with:
*
* https://www.opensource.appl... | () -> String {
let namelen = 256usize;
let mut name : Vec<u8> = repeat(0).take(namelen).collect();
let err = unsafe {
gethostname (name.as_mut_ptr() as *mut libc::c_char,
namelen as libc::size_t)
};
if err != 0 {
panic!("Cannot determine hostn... | xgethostname | identifier_name |
hostname.rs | #![crate_name = "uu_hostname"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alan Andrade <alan.andradec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Synced with:
*
* https://www.opensource.appl... | show_error!("{}", f);
return 1;
}
}
} else {
if matches.opt_present("s") {
let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.');
let ci = it.next();
... | if len > 0 {
println!("{}", &output[0 .. len - 1]);
}
}
Err(f) => { | random_line_split |
libraries.processor.ts | ////////////////////////////////////////////////////////////////////////////////////////////////////
/// NOTE: This file is also used in the Script Lab Samples project. ///
/// Please be sure that any changes that you make here are also copied to there. ///
/// See "co... |
if (/\.ts$|\.js$/i.test(resolvedUrlPath)) {
/*
* Don't add Office.js to the rest of the script references --
* it is special because of how it needs to be *outside* of the iframe,
* whereas the rest of the script references need to be inside the iframe.
... | {
return linkReferences.push(resolvedUrlPath);
} | conditional_block |
libraries.processor.ts | ////////////////////////////////////////////////////////////////////////////////////////////////////
/// NOTE: This file is also used in the Script Lab Samples project. ///
/// Please be sure that any changes that you make here are also copied to there. ///
/// See "co... | officeJS = resolvedUrlPath;
return null;
}
return scriptReferences.push(resolvedUrlPath);
}
return scriptReferences.push(resolvedUrlPath);
}
} | */
if (/(?:office|office.debug).js$/.test(resolvedUrlPath.toLowerCase())) { | random_line_split |
libraries.processor.ts | ////////////////////////////////////////////////////////////////////////////////////////////////////
/// NOTE: This file is also used in the Script Lab Samples project. ///
/// Please be sure that any changes that you make here are also copied to there. ///
/// See "co... | return linkReferences.push(resolvedUrlPath);
}
if (/\.ts$|\.js$/i.test(resolvedUrlPath)) {
/*
* Don't add Office.js to the rest of the script references --
* it is special because of how it needs to be *outside* of the iframe,
* whereas the re... | {
if (text == null || text.trim() === '') {
return null;
}
text = text.trim();
let isNotScriptOrStyle =
/^#.*|^\/\/.*|^\/\*.*|.*\*\/$.*/im.test(text) ||
/^@types/.test(text) ||
/^dt~/.test(text) ||
/\.d\.ts$/i.test(text);
... | identifier_body |
libraries.processor.ts | ////////////////////////////////////////////////////////////////////////////////////////////////////
/// NOTE: This file is also used in the Script Lab Samples project. ///
/// Please be sure that any changes that you make here are also copied to there. ///
/// See "co... | (text: string) {
if (text == null || text.trim() === '') {
return null;
}
text = text.trim();
let isNotScriptOrStyle =
/^#.*|^\/\/.*|^\/\*.*|.*\*\/$.*/im.test(text) ||
/^@types/.test(text) ||
/^dt~/.test(text) ||
/\.d\.ts$/i.t... | processLibrary | identifier_name |
eventsRequest.tsx | /actionCreators/indicator';
import {canIncludePreviousPeriod} from 'app/views/events/utils/canIncludePreviousPeriod';
import {doEventsRequest} from 'app/actionCreators/events';
import {t} from 'app/locale';
import SentryTypes from 'app/sentryTypes';
import LoadingPanel from '../loadingPanel';
type RenderProps = {
l... | extends React.PureComponent<EventsRequestProps, EventsRequestState> {
static propTypes = {
/**
* API client instance
*/
api: PropTypes.object.isRequired,
organization: SentryTypes.Organization.isRequired,
/**
* List of project ids to query
*/
project: PropTypes.arrayOf(PropT... | EventsRequest | identifier_name |
eventsRequest.tsx | app/actionCreators/indicator';
import {canIncludePreviousPeriod} from 'app/views/events/utils/canIncludePreviousPeriod';
import {doEventsRequest} from 'app/actionCreators/events';
import {t} from 'app/locale';
import SentryTypes from 'app/sentryTypes';
import LoadingPanel from '../loadingPanel';
type RenderProps = {
... | timeAggregatedData?: Series | {};
};
type EventsRequestPartialProps = {
api: Client;
organization: Organization;
project?: number[];
environment?: string[];
period?: string;
start?: any;
end?: any;
interval?: string;
field?: string[];
referenceEvent?: string;
limit?: number;
query?: string;... | timeseriesTotals?: object;
originalPreviousTimeseriesData?: EventsStatsData | null;
previousTimeseriesData?: Series | null; | random_line_split |
eventsRequest.tsx | /actionCreators/indicator';
import {canIncludePreviousPeriod} from 'app/views/events/utils/canIncludePreviousPeriod';
import {doEventsRequest} from 'app/actionCreators/events';
import {t} from 'app/locale';
import SentryTypes from 'app/sentryTypes';
import LoadingPanel from '../loadingPanel';
type RenderProps = {
l... |
return {
seriesName: 'Previous Period',
data: this.calculateTotalsPerTimestamp(
previous,
(_timestamp, _countArray, i) => current[i][0] * 1000
),
};
};
/**
* Aggregate all counts for each time stamp
*/
transformAggregatedTimeseries = (
data: EventsStatsData,
... | {
return null;
} | conditional_block |
login.ts | ///<reference path='refs.ts'/>
//declare var Windows:any;
module TDev.Login
{
export function show(hash: string = null): boolean {
// Cloud.isOnline should be checked prior to call this api
if (/skipLogin/.test(document.URL)) {
HTML.showErrorNotification("skipLogin specified; won't log... |
var hereUrl = window.location.href;
if (/^x-wmapp/.test(hereUrl)) hereUrl = "https://www.touchdevelop.com/app/current.error#wp8login";
hereUrl = hereUrl.replace(/#modal.*/, "");
if (hash)
hereUrl = hereUrl.replace(/#.*/, "") + "#" + hash
var url = Cloud.getServiceUr... | {
var uid = Cloud.getUserId()
if (uid) addParameters = "&u=" + encodeURIComponent(uid)
} | conditional_block |
login.ts | ///<reference path='refs.ts'/>
//declare var Windows:any;
module TDev.Login
{
export function | (hash: string = null): boolean {
// Cloud.isOnline should be checked prior to call this api
if (/skipLogin/.test(document.URL)) {
HTML.showErrorNotification("skipLogin specified; won't login")
return false;
}
var addParameters = "";
var m = /u=\w+/.exec(d... | show | identifier_name |
login.ts | ///<reference path='refs.ts'/>
//declare var Windows:any;
module TDev.Login
{
export function show(hash: string = null): boolean | if (hash)
hereUrl = hereUrl.replace(/#.*/, "") + "#" + hash
var url = Cloud.getServiceUrl() + "/oauth/dialog?response_type=token&client_id=" +
encodeURIComponent(Cloud.lite ? "webapp2" : "webapp") +
"&redirect_uri=" + encodeURIComponent(hereUrl) +
"&identi... | {
// Cloud.isOnline should be checked prior to call this api
if (/skipLogin/.test(document.URL)) {
HTML.showErrorNotification("skipLogin specified; won't login")
return false;
}
var addParameters = "";
var m = /u=\w+/.exec(document.URL);
if (m)
... | identifier_body |
login.ts | ///<reference path='refs.ts'/>
//declare var Windows:any;
module TDev.Login
{
export function show(hash: string = null): boolean {
// Cloud.isOnline should be checked prior to call this api
if (/skipLogin/.test(document.URL)) {
HTML.showErrorNotification("skipLogin specified; won't log... | } | ProgressOverlay.show("signing in...")
Util.navigateInWindow(url);
return true;
} | random_line_split |
lars.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
def __repr__(self):
return f'{class_name(self)}(momentum={self.momentum}, weight_decay={self.weight_decay}, ' \
f'tc={self.tc}, eps={self.eps})'
| p_norm = jn.linalg.norm(p.value)
g_norm = jn.linalg.norm(g)
trust_ratio = self.tc * p_norm / (g_norm + self.weight_decay * p_norm + self.eps)
local_lr = lr * jn.maximum(jn.logical_or(p_norm == 0, g_norm == 0), trust_ratio)
m.value = self.momentum * m.value + local_lr * (g... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.