file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
lib.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
Stop,
Continue,
}
impl Compilation {
pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
match self {
Compilation::Stop => Compilation::Stop,
Compilation::Continue => next()
}
}
}
// A trait for customising the compilation process. Off... | Compilation | identifier_name |
lib.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
if sess.opts.parse_only ||
sess.opts.show_span.is_some() ||
sess.opts.debugging_opts.ast_json_noexpand {
control.after_parse.stop = Compilation::Stop;
}
if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
control.after_write_deps.stop =... |
fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
let mut control = CompileController::basic(); | random_line_split |
lib.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
.iter().cloned().partition(|&(_, p)| p);
let plugin = sort_lints(plugin);
let builtin = sort_lints(builtin);
let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
.iter().cloned().partition(|&(_, _, ... | {
let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
&(y, _): &(&'static str, Vec<lint::LintId>)| {
x.cmp(y)
});
lints
} | identifier_body |
lib.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
}
return Compilation::Stop;
}
}
/// Returns a version string such as "0.12.0-dev".
pub fn release_str() -> Option<&'static str> {
option_env!("CFG_RELEASE")
}
/// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
pub fn commit_hash_str() -> Option<&'... | {
let input = match input {
Some(input) => input,
None => early_error("no input file provided"),
};
let attrs = attrs.as_ref().unwrap();
let t_outputs = driver::build_output_filenames(input,
... | conditional_block |
training-fas-sif-5.py | # training.py
# This is the training script which will be presented to the participant before they sleep
# or remain awake
#
# TODO
# Libraries - these seem fine and should not need altering.
from psychopy import visual, event, core, misc, data, gui, sound
# Participant needs to press y to continue.
def rea... |
if thisKey=='q':
core.quit()
# Metronome function - This plays the metronome; the timing can also be altered here.
# The timing required needs to be passed to metronome function.
#music = pyglet.resource.media('klack.ogg', streaming=False)
music = sound.Sound(900,secs=0.01) # Just temporary
def ... | user_response=1 | conditional_block |
training-fas-sif-5.py | # training.py
# This is the training script which will be presented to the participant before they sleep
# or remain awake
#
# TODO
# Libraries - these seem fine and should not need altering.
from psychopy import visual, event, core, misc, data, gui, sound
# Participant needs to press y to continue.
def | ():
stim_win.flip()
user_response=None
while user_response==None:
allKeys=event.waitKeys()
for thisKey in allKeys:
if thisKey=='y':
user_response=1
if thisKey=='q':
core.quit()
# Metronome function - This plays the metronome; the timing can also be altered here.
# ... | ready_cont | identifier_name |
training-fas-sif-5.py | # training.py
# This is the training script which will be presented to the participant before they sleep
# or remain awake
#
# TODO
# Libraries - these seem fine and should not need altering.
from psychopy import visual, event, core, misc, data, gui, sound
# Participant needs to press y to continue.
def rea... |
# The metronome alone so the participant can become familiar with
# the speed (no stimuli).
def metronome_alone():
stim_win.flip()
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
# Variables
welcome_message = """Welcome to the training s... | music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
music.play()
core.wait(met_time) | identifier_body |
training-fas-sif-5.py | # training.py
# This is the training script which will be presented to the participant before they sleep
# or remain awake
#
# TODO
# Libraries - these seem fine and should not need altering.
from psychopy import visual, event, core, misc, data, gui, sound
# Participant needs to press y to continue.
def rea... |
# The sample loop
stim_win.flip()
for i in range(len(sample_stim)):
message.setText(sample_stim[i])
stim_win.flip()
core.wait(stim_interval)
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
core.wait(stim_interval)
# Ask participant... | # Welcome the participant.
message.setText(sample_welcome)
ready_cont()
| random_line_split |
util.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Utility traits and functions.
use num::PrimInt;
/// Returns `single` if the given number is 1, or `plural` otherwise.
pub(crate) fn p... |
/// Convert a byte count to a human-readable representation of the byte count
/// using appropriate IEC suffixes.
pub(crate) fn byte_count_iec(size: i64) -> String {
let suffixes = [
" KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB",
];
byte_count(size, " byte", " bytes", &suffixes)
}... | {
const UNIT_LIMIT: i64 = 9999;
match (size, multiple.split_last()) {
(std::i64::MIN..=UNIT_LIMIT, _) | (_, None) => {
format!("{}{}", size, plural(size, unit_single, unit_plural))
}
(size, Some((last_multiple, multiple))) => {
let mut divisor = 1024;
... | identifier_body |
util.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Utility traits and functions.
use num::PrimInt;
/// Returns `single` if the given number is 1, or `plural` otherwise.
pub(crate) fn p... | /// Convert a byte count to a human-readable representation of the byte count
/// using appropriate IEC suffixes.
pub(crate) fn byte_count_iec(size: i64) -> String {
let suffixes = [
" KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB",
];
byte_count(size, " byte", " bytes", &suffixes)
}
... | }
}
}
| random_line_split |
util.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Utility traits and functions.
use num::PrimInt;
/// Returns `single` if the given number is 1, or `plural` otherwise.
pub(crate) fn p... | else { plural }
}
fn byte_count(size: i64, unit_single: &str, unit_plural: &str, multiple: &[&str]) -> String {
const UNIT_LIMIT: i64 = 9999;
match (size, multiple.split_last()) {
(std::i64::MIN..=UNIT_LIMIT, _) | (_, None) => {
format!("{}{}", size, plural(size, unit_single, unit_plural))... | { single } | conditional_block |
util.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Utility traits and functions.
use num::PrimInt;
/// Returns `single` if the given number is 1, or `plural` otherwise.
pub(crate) fn p... | (size: i64) -> String {
let suffixes = [
" KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB",
];
byte_count(size, " byte", " bytes", &suffixes)
}
/// Convert a byte count to a human-readable representation of the byte count
/// using short suffixes.
pub(crate) fn byte_count_short(size: i... | byte_count_iec | identifier_name |
exclusion.ts | import * as util from "./util";
import debug from "debug";
const log = debug("json-property-filter:exclusion");
export function extract(filters: string[]) {
debug("Extract filters");
const extractDebug = log.extend("extract");
const exclusionFilters: string[] = [];
for (let i = filters.length; i--; ... |
return exclusionFilters;
}
export function filter(source: object, filters: string[]) {
log("Apply filters: %o", filters);
const destination = Array.isArray(source) ? [] : {};
apply(source, filters, destination, util.EMPTY_CONTEXT);
return destination;
}
function apply(source: object, filters: ... | {
const value = filters[i];
const firstCharacter = value[0];
if (value.length && firstCharacter === "-") {
extractDebug("Extracting filter: %s", value);
const filterWithoutSymbol = firstCharacter === "-" ? value.substring(1) : value;
exclusionFilters.push(fi... | conditional_block |
exclusion.ts | import * as util from "./util";
import debug from "debug";
const log = debug("json-property-filter:exclusion");
export function extract(filters: string[]) {
debug("Extract filters");
const extractDebug = log.extend("extract");
const exclusionFilters: string[] = [];
for (let i = filters.length; i--; ... | (filters: string[], context: util.Context, propertyName: string) {
const expectedRootPropertiesFilter = context.relativePath !== "" ? context.relativePath + ".*" : "*";
const expectedAllPropertiesFilter = context.relativePath !== "" ? context.relativePath + ".**" : "**";
const relativePath = context.relati... | isFiltered | identifier_name |
exclusion.ts | import * as util from "./util";
import debug from "debug";
const log = debug("json-property-filter:exclusion");
export function extract(filters: string[]) {
debug("Extract filters");
const extractDebug = log.extend("extract");
const exclusionFilters: string[] = [];
for (let i = filters.length; i--; ... |
return (
filters.includes(absolutePath) ||
filters.includes(relativePath) ||
filters.includes(context.absolutePath) ||
filters.includes(context.relativePath) ||
filters.includes(expectedAllPropertiesFilter) ||
filters.includes(expectedRootPropertiesFilter)
);
} | const relativePath = context.relativePath ? `${context.relativePath}.${propertyName}` : propertyName;
const segments = context.segments ? context.segments.concat(propertyName) : [propertyName];
const absolutePath = segments.join("."); | random_line_split |
exclusion.ts | import * as util from "./util";
import debug from "debug";
const log = debug("json-property-filter:exclusion");
export function extract(filters: string[]) |
export function filter(source: object, filters: string[]) {
log("Apply filters: %o", filters);
const destination = Array.isArray(source) ? [] : {};
apply(source, filters, destination, util.EMPTY_CONTEXT);
return destination;
}
function apply(source: object, filters: string[], destination: object, c... | {
debug("Extract filters");
const extractDebug = log.extend("extract");
const exclusionFilters: string[] = [];
for (let i = filters.length; i--; ) {
const value = filters[i];
const firstCharacter = value[0];
if (value.length && firstCharacter === "-") {
extractDebug... | identifier_body |
event-handlers.spec.ts | /**
* Unit tests for The Cave of the Mind
*/
import Game from "../../core/models/game";
import {Monster} from "../../core/models/monster";
import {Artifact} from "../../core/models/artifact";
import {initLiveGame} from "../../core/utils/testing";
import {event_handlers} from "./event-handlers";
import {custom_command... | });
test("power spell effects", () => {
game.triggerEvent("power", 20);
game.queue.run();
expect(game.history.getLastOutput().text).toBe("You hear a loud sonic boom which echoes all around you!");
game.mock_random_numbers = [16];
game.triggerEvent("power", 51);
game.queue.run();
expect(game.history.getLa... | expect(game.artifacts.get(52).room_id).toBe(1);
expect(game.artifacts.get(53).room_id).toBe(2);
expect(game.artifacts.get(54).room_id).toBe(3); | random_line_split |
en_ca.js | /*!
* froala_editor v3.0.0-rc.2 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2019 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'fun... | 'Delete column': 'Delete column',
'Cell': 'Cell',
'Merge cells': 'Merge cells',
'Horizontal split': 'Horizontal split',
'Vertical split': 'Vertical split',
'Cell Background': 'Cell Background',
'Vertical Align': 'Vertical Align',
'Top': 'Top',
'Middle': 'Middle',
... | 'Insert row below': 'Insert row below',
'Delete row': 'Delete row',
'Column': 'Column',
'Insert column before': 'Insert column before',
'Insert column after': 'Insert column after', | random_line_split |
news.ts | 'use strict';
angular.module( 'portailApp' )
.component( 'news',
{
bindings: { edition: '<' },
controller: [ '$sce', 'Popups', '$http', '$q', 'URL_ENT', 'RANDOM_IMAGES', 'currentUser',
function( $sce, Popups, $http, $q, URL_ENT, RANDOM_IMAGES, currentUser ) {
var ctrl = this;
ctrl.ne... |
} )
.then( function( response ) {
ctrl.newsfeed = ctrl.newsfeed.concat( _( response.data ).map( function( item, index ) {
item.trusted_content = $sce.trustAsHtml( item.content );
item.no_image = _( item.image ).isNull();
item.pubDate... | {
return $http.get( URL_ENT + '/api/structures/' + ctrl.user.active_profile().structure_id + '/rss', { params: { 'pubDate>': one_month_ago } } );
} | conditional_block |
news.ts | 'use strict';
angular.module( 'portailApp' )
.component( 'news',
{
bindings: { edition: '<' },
controller: [ '$sce', 'Popups', '$http', '$q', 'URL_ENT', 'RANDOM_IMAGES', 'currentUser',
function( $sce, Popups, $http, $q, URL_ENT, RANDOM_IMAGES, currentUser ) {
var ctrl = this;
ctrl.ne... | }
return item;
} ) );
} );
};
ctrl.config_news_fluxes = function() {
Popups.manage_fluxes( function() {
ctrl.retrieve_news( true );
}, function error() { } );
};
ctrl.$onInit = function() {
... | item.pubDate = moment( new Date( item.pubDate ) ).toDate();
if ( _( item.image ).isNull() ) {
item.image = _( RANDOM_IMAGES ).sample(); | random_line_split |
trail_maker.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Mehmet Atakan Gürkan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed i... | else :
use_rep = False
dummy = random(r)
q = 0.0
for i in range(N) :
X = random() - 0.5
if X>q : DP = -dP
else : DP = dP
if np.fabs(P+DP) > b :
P -= DP
else :
P += DP
trl[i+1] = P
if use_rep :
... | se_rep = True
rep_norm = 1.0/np.sqrt(r)
rep = random(r)-0.5
q = np.sum(rep)*rep_norm * c
| conditional_block |
trail_maker.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Mehmet Atakan Gürkan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed i... | help='bias strength')
parser.add_argument('-b',
type=float, default=3.0e40,
help='radius of boundary')
parser.add_argument('-s',
type=int, default=42,
help='random number seed (default: 42)')
parser.add_argument('--range... | type=int, default=0,
help='repository size (default: 0)')
parser.add_argument('-c',
type=float, default=0.0, | random_line_split |
trail_maker.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Mehmet Atakan Gürkan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed i... |
if args.outputformat == 'undecided' :
if args.outfile == sys.stdout :
outputformat = 'ascii'
else :
outputformat = 'numpy'
else :
outputformat = args.outputformat
if d==1 :
trl = trail_1d(N, r=args.r, c=args.c, b=args.b)
if outputformat == 'ascii' :
for p in trl :
... | ef vec_norm2(a) :
return a[0]*a[0] + a[1]*a[1] + a[2]*a[2]
b2 = b*b
P0x, P0y, P0z = args.P0x, args.P0y, args.P0z
Px, Py, Pz = P0x, P0y, P0z
trl = np.empty((N+1,3))
trl[0] = P0x, P0y, P0z
if r>0 and c!=0.0 : # repository initialization
use_rep = True
rep_norm = 1.0/np.sq... | identifier_body |
trail_maker.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Mehmet Atakan Gürkan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed i... | N, r=0, c=0.0, b=3.0e40) :
def vec_norm2(a) :
return a[0]*a[0] + a[1]*a[1] + a[2]*a[2]
b2 = b*b
P0x, P0y, P0z = args.P0x, args.P0y, args.P0z
Px, Py, Pz = P0x, P0y, P0z
trl = np.empty((N+1,3))
trl[0] = P0x, P0y, P0z
if r>0 and c!=0.0 : # repository initialization
use_rep = T... | rail_3d( | identifier_name |
models.py | from django.db import models
from django.contrib.auth.models import User
from helper_functions import my_strftime
# Create your models here.
#This only contains metadata about this thread (i.e. just the subject for now)
#It is used in a Many-to-Many relationship with User, with a through object that contains the has_... |
last_message = self.message_set.order_by('-time_sent')[0]
return { 'subject' : self.subject, 'last_message' : last_message.getDetail(), 'id' : self.id,
'has_been_read' : has_been_read }
class Message(models.Model):
thread = models.ForeignKey(Thread)
user = models.ForeignKey('... | has_been_read = ThreadMembership.objects.get(user=user, thread=self).has_been_read | conditional_block |
models.py | from django.db import models
from django.contrib.auth.models import User
from helper_functions import my_strftime
# Create your models here.
#This only contains metadata about this thread (i.e. just the subject for now)
#It is used in a Many-to-Many relationship with User, with a through object that contains the has_... | text = models.TextField()
def getDetail(self):
"""Returns dictionary object containing the info of this object"""
return { 'author' : self.user.getInfo(),
'timestamp' : my_strftime(self.time_sent),
'text' : self.text }
class ThreadMembership(models.Model):
u... | thread = models.ForeignKey(Thread)
user = models.ForeignKey('userInfo.UserProfile') #the author of this message
time_sent = models.DateTimeField(auto_now_add=True) | random_line_split |
models.py | from django.db import models
from django.contrib.auth.models import User
from helper_functions import my_strftime
# Create your models here.
#This only contains metadata about this thread (i.e. just the subject for now)
#It is used in a Many-to-Many relationship with User, with a through object that contains the has_... | (self):
"""Returns dictionary object containing the info of this object"""
return { 'author' : self.user.getInfo(),
'timestamp' : my_strftime(self.time_sent),
'text' : self.text }
class ThreadMembership(models.Model):
user = models.ForeignKey('userInfo.UserProfile')
... | getDetail | identifier_name |
models.py | from django.db import models
from django.contrib.auth.models import User
from helper_functions import my_strftime
# Create your models here.
#This only contains metadata about this thread (i.e. just the subject for now)
#It is used in a Many-to-Many relationship with User, with a through object that contains the has_... |
class ThreadMembership(models.Model):
user = models.ForeignKey('userInfo.UserProfile')
thread = models.ForeignKey(Thread)
#Meta data for user's relation to thread
has_been_read = models.BooleanField(default=False)
| """Returns dictionary object containing the info of this object"""
return { 'author' : self.user.getInfo(),
'timestamp' : my_strftime(self.time_sent),
'text' : self.text } | identifier_body |
model.py | """
model.py
by Ted Morin
contains a function to predict 10-year Atrial Fibrilation risks using beta coefficients from
10.1016:S0140-6736(09)60443-8
2010 Development of a Risk Score for Atrial Fibrillation in the Community
Framingham Heart Study
translated and optimized from FHS online risk calculator's javascript
... | pr_intv = pr_intv * 1000.0
# inexplicable conversion
pr_intv = pr_intv / 10.0
# this was done in the js, and the output seems much more realistic than otherwise, but it seems inexplicable!
# perhaps the coefficient shown in FHS's website is erroneous? Or uses the wrong units? It is hard to say.
... | identifier_body | |
model.py | """
model.py
by Ted Morin
contains a function to predict 10-year Atrial Fibrilation risks using beta coefficients from
10.1016:S0140-6736(09)60443-8
2010 Development of a Risk Score for Atrial Fibrillation in the Community
Framingham Heart Study
translated and optimized from FHS online risk calculator's javascript
... | def model(ismale, age, bmi, sbp, antihyp, pr_intv, sigmurm, phf):
# convert seconds to milliseconds as used in regression
pr_intv = pr_intv * 1000.0
# inexplicable conversion
pr_intv = pr_intv / 10.0
# this was done in the js, and the output seems much more realistic than otherwise, but it s... | random_line_split | |
model.py | """
model.py
by Ted Morin
contains a function to predict 10-year Atrial Fibrilation risks using beta coefficients from
10.1016:S0140-6736(09)60443-8
2010 Development of a Risk Score for Atrial Fibrillation in the Community
Framingham Heart Study
translated and optimized from FHS online risk calculator's javascript
... | (ismale, age, bmi, sbp, antihyp, pr_intv, sigmurm, phf):
# convert seconds to milliseconds as used in regression
pr_intv = pr_intv * 1000.0
# inexplicable conversion
pr_intv = pr_intv / 10.0
# this was done in the js, and the output seems much more realistic than otherwise, but it seems inex... | model | identifier_name |
comm.py | import urllib2
import json
import time
import threading
import Queue
from utils import make_random_id, LOGINFO, LOGDEBUG, LOGERROR
class CommBase(object):
def __init__(self):
self.agents = []
def add_agent(self, agent):
self.agents.append(agent)
class HTTPComm(CommBase):
def __init__(s... |
class ThreadedComm(CommBase):
class AgentProxy(object):
def __init__(self, tc):
self.tc = tc
def dispatch_message(self, content):
self.tc.receive_queue.put(content)
def __init__(self, upstream_comm):
super(ThreadedComm, self).__init__()
self.upstream_c... | for a in self.agents:
a.dispatch_message(content) | conditional_block |
comm.py | import urllib2
import json
import time
import threading
import Queue
from utils import make_random_id, LOGINFO, LOGDEBUG, LOGERROR
class | (object):
def __init__(self):
self.agents = []
def add_agent(self, agent):
self.agents.append(agent)
class HTTPComm(CommBase):
def __init__(self, config, url = 'http://localhost:8080/messages'):
super(HTTPComm, self).__init__()
self.config = config
self.lastpoll = ... | CommBase | identifier_name |
comm.py | import urllib2
import json
import time
import threading
import Queue
from utils import make_random_id, LOGINFO, LOGDEBUG, LOGERROR
class CommBase(object):
def __init__(self):
self.agents = []
def add_agent(self, agent):
self.agents.append(agent)
class HTTPComm(CommBase):
def __init__(s... |
class CommThread(threading.Thread):
def __init__(self, threaded_comm, upstream_comm):
threading.Thread.__init__(self)
self._stop = threading.Event()
self.threaded_comm = threaded_comm
self.upstream_comm = upstream_comm
def run(self):
send_queue = self.threaded_comm.send... | random_line_split | |
comm.py | import urllib2
import json
import time
import threading
import Queue
from utils import make_random_id, LOGINFO, LOGDEBUG, LOGERROR
class CommBase(object):
def __init__(self):
self.agents = []
def add_agent(self, agent):
self.agents.append(agent)
class HTTPComm(CommBase):
def __init__(s... |
def post_message(self, content):
self.send_queue.put(content)
def poll_and_dispatch(self):
while not self.receive_queue.empty():
content = self.receive_queue.get()
for a in self.agents:
a.dispatch_message(content)
def start(self):
self.... | super(ThreadedComm, self).__init__()
self.upstream_comm = upstream_comm
self.send_queue = Queue.Queue()
self.receive_queue = Queue.Queue()
self.comm_thread = CommThread(self, upstream_comm)
upstream_comm.add_agent(self.AgentProxy(self)) | identifier_body |
cite_tool.js | var Substance = require('substance');
var Tool = Substance.Surface.Tool;
var _ = require("substance/helpers");
var CiteTool = Tool.extend({
name: "cite",
update: function(surface, sel) {
this.surface = surface; // IMPORTANT!
// Set disabled when not a property selection
if (!surface.isEnabled() || sel... |
this.surface.transaction(function(tx, args) {
tx.set([citation.id, "targets"], newTargets);
return args;
});
}
});
module.exports = CiteTool;
| {
newTargets.push(targetId);
} | conditional_block |
cite_tool.js | var Substance = require('substance');
var Tool = Substance.Surface.Tool;
var _ = require("substance/helpers");
var CiteTool = Tool.extend({
name: "cite",
update: function(surface, sel) {
this.surface = surface; // IMPORTANT!
// Set disabled when not a property selection
if (!surface.isEnabled() || sel... | }
var newState = {
surface: surface,
sel: sel,
disabled: false
};
this.setToolState(newState);
},
// Needs app context in order to request a state switch
createCitation: function(citationTargetType) {
var citation;
var doc = this.context.doc;
var citationType = doc... | random_line_split | |
form.directive.js | /*
* Copyright (C) 2015 Telosys-tools-saas project org. ( http://telosys-tools-saas.github.io/ )
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* ht... | }
};
}); | }); | random_line_split |
form.directive.js | /*
* Copyright (C) 2015 Telosys-tools-saas project org. ( http://telosys-tools-saas.github.io/ )
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* ht... |
});
}
};
}); | {
$inputs.each(function() {
var $input = $(this);
scope.$watch(function() {
return $input.hasClass('ng-invalid') && $input.hasClass('ng-dirty');
}, function(isInvalid) {
... | conditional_block |
Dot.js | var React = require('react-native');
var {
StyleSheet,
View,
Animated,
} = React;
var Dot = React.createClass({
propTypes: {
isPlacedCorrectly: React.PropTypes.bool.isRequired,
},
getInitialState: function() {
return {
scale: new Animated.Value(this.props.isPlacedCorrectly ? 1 : 0.1),
... | return (
<Animated.View style={[styles.dot, {transform: [{scale: this.state.scale}]}]}/>
);
},
});
var styles = StyleSheet.create({
dot: {
backgroundColor: '#FF3366',
width: 6,
height: 6,
borderRadius: 3,
margin: 3,
},
});
module.exports = Dot; |
render: function() {
if (!this.state.visible) {
return null;
} | random_line_split |
debug.py | # -*- coding: utf-8 -*-
## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com
##
## This file is part of Nascent.
##
## Nascent 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 Foundati... | (*args, **kwargs):
""" Will print the file and line before printing. Can be used to find spurrious print statements. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe().f_back)
print(frameinfo.filename, frameinfo.lineno)
pprint(*args, **kwargs)
def info_pprin... | info_print | identifier_name |
debug.py | # -*- coding: utf-8 -*-
## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com
##
## This file is part of Nascent.
##
## Nascent 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 Foundati... |
def pprint_debug(*args, **kwargs):
if do_print:
pprint(*args, **kwargs)
def info_print(*args, **kwargs):
""" Will print the file and line before printing. Can be used to find spurrious print statements. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe(... | """ Change module-level do_print variable to toggle behaviour. """
if 'origin' in kwargs:
del kwargs['origin']
if do_print:
print(*args, **kwargs) | identifier_body |
debug.py | # -*- coding: utf-8 -*-
## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com
##
## This file is part of Nascent.
##
## Nascent 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 Foundati... |
def pprint_debug(*args, **kwargs):
if do_print:
pprint(*args, **kwargs)
def info_print(*args, **kwargs):
""" Will print the file and line before printing. Can be used to find spurrious print statements. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe(... | print(*args, **kwargs) | conditional_block |
debug.py | # -*- coding: utf-8 -*-
## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com
##
## This file is part of Nascent.
##
## Nascent is free software: you can redistribute it and/or modify | ## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Affero General Public License for more details.
##
## You should have received a copy of the GNU Aff... | ## it under the terms of the GNU Affero General Public License as
## published by the Free Software Foundation, either version 3 of the
## License, or (at your option) any later version.
## | random_line_split |
proxy_only_resource.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
class ProxyOnlyResource(Model):
"""Azure proxy only resource. This resource is not tracked by Azure Resource
Manager.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype na... | # regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model | random_line_split |
proxy_only_resource.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | (Model):
"""Azure proxy only resource. This resource is not tracked by Azure Resource
Manager.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:param kind: ... | ProxyOnlyResource | identifier_name |
proxy_only_resource.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | """Azure proxy only resource. This resource is not tracked by Azure Resource
Manager.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:param kind: Kind of resou... | identifier_body | |
auth.guard.ts | import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AppState } from '@genesis/$core/store/app.state';
@Injectable()
export class | implements CanActivate {
constructor(protected _router: Router,
private _appStore: AppState) {}
/**
* Checks that the user is connected and if so, permits the activation of the wanted state. If the user is not
* authenticated, he is redirected toward home page with login inputs presented.
*... | AuthGuard | identifier_name |
auth.guard.ts | import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AppState } from '@genesis/$core/store/app.state';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(protected _router: Router,
... | return canGo;
}
} | random_line_split | |
auth.guard.ts | import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AppState } from '@genesis/$core/store/app.state';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(protected _router: Router,
... |
return canGo;
}
}
| {
this._router.navigate([ '/sign-in' ]);
} | conditional_block |
download.py | import os
from com.googlecode.fascinator.api.indexer import SearchRequest
from com.googlecode.fascinator.api.storage import StorageException
from com.googlecode.fascinator.common.solr import SolrDoc, SolrResult
from org.apache.tapestry5.internal.services import URLEncoderImpl
from org.apache.tapestry5.internal import ... |
# Ensure solr metadata is useable
oid = object.getId()
if self.isIndexed():
self.__metadata = self.__solrData.getResults().get(0)
else:
self.__metadata.getJsonObject().put("id", oid)
#print "URI='%s' OID='%s' PID='%s'" % (uri, object.getId(), payload.get... | self.log.error("Redirecting, object 404: '{}'", uri)
self.response.sendRedirect(context["urlBase"] + fullUri + "/")
return | conditional_block |
download.py | import os
from com.googlecode.fascinator.api.indexer import SearchRequest
from com.googlecode.fascinator.api.storage import StorageException
from com.googlecode.fascinator.common.solr import SolrDoc, SolrResult
from org.apache.tapestry5.internal.services import URLEncoderImpl
from org.apache.tapestry5.internal import ... | basePath = self.portalId + "/" + self.pageName
# Turn our URL into objects
fullUri = URLDecoder.decode(self.request.getAttribute("RequestURI"))
fullUri = self.tapestryUrlDecode(fullUri)
uri = fullUri[len(basePath)+1:]
object, payload = self.__resolve(uri)
if o... | payload = None
# URL basics | random_line_split |
download.py | import os
from com.googlecode.fascinator.api.indexer import SearchRequest
from com.googlecode.fascinator.api.storage import StorageException
from com.googlecode.fascinator.common.solr import SolrDoc, SolrResult
from org.apache.tapestry5.internal.services import URLEncoderImpl
from org.apache.tapestry5.internal import ... | portal = self.page.getPortal()
query = 'id:"%s"' % oid
if self.isDetail() and portal.getSearchQuery():
query += " AND " + portal.getSearchQuery()
req = SearchRequest(query)
req.addParam("fq", 'item_type:"object"')
if self.isDetail():
req.addParam("fq", por... | identifier_body | |
download.py | import os
from com.googlecode.fascinator.api.indexer import SearchRequest
from com.googlecode.fascinator.api.storage import StorageException
from com.googlecode.fascinator.common.solr import SolrDoc, SolrResult
from org.apache.tapestry5.internal.services import URLEncoderImpl
from org.apache.tapestry5.internal import ... | (self):
metadata = self.getMetadata()
if metadata is not None:
return metadata.getList("security_exception")
else:
return []
def getMetadata(self):
return self.__metadata
def isDetail(self):
preview = Boolean.parseBoolean(self.formData.get("previ... | getViewUsers | identifier_name |
ocr.py | """
Runs OCR on a given file.
"""
from os import system, listdir
from PIL import Image
from pytesseract import image_to_string
import editdistance
from constants import DATA_DIR
def classify(image, people_class, max_classify_distance=1, min_nonclassify_distance=3):
""" | dist = editdistance.eval(person, read)
if dist <= max_classify_distance:
if result is not None:
return None
result = people_class[person]
elif max_classify_distance < dist <= min_nonclassify_distance:
return None
return result
def setup_oc... | Runs an OCR classifier on a given image file, drawing from a dictionary
"""
read = image_to_string(Image.open(image)).lower()
result = None
for person in people_class: | random_line_split |
ocr.py | """
Runs OCR on a given file.
"""
from os import system, listdir
from PIL import Image
from pytesseract import image_to_string
import editdistance
from constants import DATA_DIR
def classify(image, people_class, max_classify_distance=1, min_nonclassify_distance=3):
"""
Runs an OCR classifier on a given image... | (raw_data, progress):
"""
Grabs names from a pdf to an image
"""
system("unzip {} -d {}/extract".format(raw_data, DATA_DIR))
base = DATA_DIR + "/extract/"
mainfolder = base + listdir(base)[0]
files = sorted(listdir(mainfolder))
p_bar = progress(len(files))
for index, path in enumerat... | setup_ocr | identifier_name |
ocr.py | """
Runs OCR on a given file.
"""
from os import system, listdir
from PIL import Image
from pytesseract import image_to_string
import editdistance
from constants import DATA_DIR
def classify(image, people_class, max_classify_distance=1, min_nonclassify_distance=3):
"""
Runs an OCR classifier on a given image... | """
Grabs names from a pdf to an image
"""
system("unzip {} -d {}/extract".format(raw_data, DATA_DIR))
base = DATA_DIR + "/extract/"
mainfolder = base + listdir(base)[0]
files = sorted(listdir(mainfolder))
p_bar = progress(len(files))
for index, path in enumerate(files):
p_bar.up... | identifier_body | |
ocr.py | """
Runs OCR on a given file.
"""
from os import system, listdir
from PIL import Image
from pytesseract import image_to_string
import editdistance
from constants import DATA_DIR
def classify(image, people_class, max_classify_distance=1, min_nonclassify_distance=3):
"""
Runs an OCR classifier on a given image... |
elif max_classify_distance < dist <= min_nonclassify_distance:
return None
return result
def setup_ocr(raw_data, progress):
"""
Grabs names from a pdf to an image
"""
system("unzip {} -d {}/extract".format(raw_data, DATA_DIR))
base = DATA_DIR + "/extract/"
mainfolder = ... | if result is not None:
return None
result = people_class[person] | conditional_block |
users.ts | 'use strict';
import * as bcrypt from 'bcryptjs';
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import * as auth from 'passport';
import { Inject } from 'typescript-ioc';
import { ValidationError } from '../../config/errors';
import { UserData } from '../../confi... |
public async generateToken(login: string, password: string): Promise<string> {
const user = await this.get(login);
if (!user) {
throw new ValidationError('User not found');
}
let same;
try {
same = await bcrypt.compare(password, user.password);
... | {
const count = await this.database.redisClient.hdel(`${RedisUserService.USERS_PREFIX}`, login);
if (count === 0) {
throw new NotFoundError('User not found.');
}
} | identifier_body |
users.ts | 'use strict';
import * as bcrypt from 'bcryptjs';
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import * as auth from 'passport';
import { Inject } from 'typescript-ioc';
import { ValidationError } from '../../config/errors';
import { UserData } from '../../confi... | const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, user.login);
if (!exists) {
throw new NotFoundError('User not found.');
}
const oldUser = await this.get(user.login);
user.password = oldUser.password;
await this.databa... | await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async update(user: UserData): Promise<void> { | random_line_split |
users.ts | 'use strict';
import * as bcrypt from 'bcryptjs';
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import * as auth from 'passport';
import { Inject } from 'typescript-ioc';
import { ValidationError } from '../../config/errors';
import { UserData } from '../../confi... |
let same;
try {
same = await bcrypt.compare(password, user.password);
} catch (err) {
throw new ValidationError('Error validating user password');
}
if (!same) {
throw new ValidationError('Invalid username / password');
}
try {... | {
throw new ValidationError('User not found');
} | conditional_block |
users.ts | 'use strict';
import * as bcrypt from 'bcryptjs';
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import * as auth from 'passport';
import { Inject } from 'typescript-ioc';
import { ValidationError } from '../../config/errors';
import { UserData } from '../../confi... | implements UserService {
public static USERS_PREFIX = 'adminUsers';
@Inject private config: Configuration;
@Inject private database: Database;
@Inject private middlewareLoader: MiddlewareLoader;
public async list(): Promise<Array<UserData>> {
const users = await this.database.redisClient.... | RedisUserService | identifier_name |
toast.d.ts | import * as React from "react";
import { IActionProps, IIntentProps, IProps } from "../../common/props";
export interface IToastProps extends IProps, IIntentProps {
/**
* Action to display in a minimal button. The toast is dismissed automatically when the
* user clicks the action button. Note that the `in... | displayName: string;
private timeoutId;
render(): JSX.Element;
componentDidMount(): void;
componentDidUpdate(prevProps: IToastProps): void;
componentWillUnmount(): void;
private maybeRenderActionButton();
private maybeRenderIcon();
private handleActionClick;
private handleCloseCl... | }
export declare class Toast extends React.Component<IToastProps, {}> {
static defaultProps: IToastProps; | random_line_split |
toast.d.ts | import * as React from "react";
import { IActionProps, IIntentProps, IProps } from "../../common/props";
export interface IToastProps extends IProps, IIntentProps {
/**
* Action to display in a minimal button. The toast is dismissed automatically when the
* user clicks the action button. Note that the `in... | extends React.Component<IToastProps, {}> {
static defaultProps: IToastProps;
displayName: string;
private timeoutId;
render(): JSX.Element;
componentDidMount(): void;
componentDidUpdate(prevProps: IToastProps): void;
componentWillUnmount(): void;
private maybeRenderActionButton();
p... | Toast | identifier_name |
index.tsx | import { ArtworkExtraLinks_artwork } from "__generated__/ArtworkExtraLinks_artwork.graphql"
import { AuctionTimerState } from "app/Components/Bidding/Components/Timer"
import { navigate } from "app/navigation/navigate"
import { partnerName } from "app/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName"
import { us... | navigate(`/conditions-of-sale`)
}
renderFAQAndSpecialist = () => {
const {
artwork: { isAcquireable, isOfferable, isInAuction, sale, isForSale },
auctionState,
} = this.props
if (isInAuction && sale && isForSale && auctionState !== AuctionTimerState.CLOSED) {
return (
<>
... | ditionsOfSaleTap() {
| identifier_name |
index.tsx | import { ArtworkExtraLinks_artwork } from "__generated__/ArtworkExtraLinks_artwork.graphql"
import { AuctionTimerState } from "app/Components/Bidding/Components/Timer"
import { navigate } from "app/navigation/navigate"
import { partnerName } from "app/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName"
import { us... | <Spacer mb={1} />
<Sans size="2" color="black60">
Have a question?{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleReadOurAuctionFAQsTap()}
>
Read our auction FAQs
</Text>{" "}
... | .
</Sans> | random_line_split |
index.tsx | import { ArtworkExtraLinks_artwork } from "__generated__/ArtworkExtraLinks_artwork.graphql"
import { AuctionTimerState } from "app/Components/Bidding/Components/Timer"
import { navigate } from "app/navigation/navigate"
import { partnerName } from "app/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName"
import { us... | k({
action_name: Schema.ActionNames.ConditionsOfSale,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
handleConditionsOfSaleTap() {
navigate(`/conditions-of-sale`)
}
renderFAQAndSpecialist = () => {
const {
artwork: { isAcquireable, isO... | igate(`/auction-faq`)
return
}
@trac | identifier_body |
test_cli20_natpool.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
# d... | (self):
"""nat-pool-list."""
resource = 'nat_pools'
cmd = gbp.ListNatPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resource, cmd, True)
def test_show_nat_pool_name(self):
"""nat-pool-show."""
resource = 'nat_pool'
cmd = gbp.ShowNatPool(te... | test_list_nat_pools | identifier_name |
test_cli20_natpool.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
# d... | from gbpclient.tests.unit import test_cli20
class CLITestV20NatPoolJSON(test_cli20.CLITestV20Base):
LOG = logging.getLogger(__name__)
def setUp(self):
super(CLITestV20NatPoolJSON, self).setUp()
def test_create_nat_pool_with_mandatory_params(self):
"""nat-pool-create with all mandatory p... | import sys
from gbpclient.gbp.v2_0 import groupbasedpolicy as gbp | random_line_split |
test_cli20_natpool.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
# d... |
def test_show_nat_pool_name(self):
"""nat-pool-show."""
resource = 'nat_pool'
cmd = gbp.ShowNatPool(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_update_nat_pool(... | """nat-pool-list."""
resource = 'nat_pools'
cmd = gbp.ListNatPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resource, cmd, True) | identifier_body |
depend.js | import { hyphen } from './utils';
/**
* 依赖
*/
export let devDependencies = [];
/**
* 添加依赖
* @param {array|string} dependencies 依赖
*/
export function addDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
if ( devDependen... | return hyphen(name);
}; | random_line_split | |
depend.js | import { hyphen } from './utils';
/**
* 依赖
*/
export let devDependencies = [];
/**
* 添加依赖
* @param {array|string} dependencies 依赖
*/
export function addDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependenci | s.map(dependency => {
if ( devDependencies.indexOf(dependency) === -1 ){
devDependencies.push(dependency);
};
});
};
/**
* 移除依赖
* @param {array|string} dependencies 依赖
*/
export function removeDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
... | es = [dependencies];
};
dependencie | conditional_block |
depend.js | import { hyphen } from './utils';
/**
* 依赖
*/
export let devDependencies = [];
/**
* 添加依赖
* @param {array|string} dependencies 依赖
*/
export function addDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
if ( devDependen... | =[\d])/g, () => '-')
.replace(/_(?=[^\d])/g, () => '');
return hyphen(name);
}; | identifier_body | |
depend.js | import { hyphen } from './utils';
/**
* 依赖
*/
export let devDependencies = [];
/**
* 添加依赖
* @param {array|string} dependencies 依赖
*/
export function addDependency(de | if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
if ( devDependencies.indexOf(dependency) === -1 ){
devDependencies.push(dependency);
};
});
};
/**
* 移除依赖
* @param {array|string} dependencies 依赖
*/
export function removeDependency(dep... | pendencies){
| identifier_name |
__init__.py | """Support for Peewee ORM (https://github.com/coleifer/peewee)."""
from __future__ import annotations
import typing as t
import marshmallow as ma
import muffin
import peewee as pw
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow_peewee import ForeignKey, ModelSchema
from muffin.typing import JS... |
count = await self.meta.manager.count(cqs)
return self.collection.offset(offset).limit(limit), count # type: ignore
async def get(self, request, *, resource=None) -> JSONType:
"""Get resource or collection of resources."""
if resource is not None and resource != "":
re... | cqs._returning = cqs._group_by | conditional_block |
__init__.py | """Support for Peewee ORM (https://github.com/coleifer/peewee)."""
from __future__ import annotations
import typing as t
import marshmallow as ma
import muffin
import peewee as pw
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow_peewee import ForeignKey, ModelSchema
from muffin.typing import JS... |
async def get(self, request, *, resource=None) -> JSONType:
"""Get resource or collection of resources."""
if resource is not None and resource != "":
return await self.dump(request, resource, many=False)
resources = await self.meta.manager.fetchall(self.collection)
re... | """Paginate the collection."""
cqs: pw.Select = self.collection.order_by() # type: ignore
if cqs._group_by:
cqs._returning = cqs._group_by
count = await self.meta.manager.count(cqs)
return self.collection.offset(offset).limit(limit), count # type: ignore | identifier_body |
__init__.py | """Support for Peewee ORM (https://github.com/coleifer/peewee)."""
from __future__ import annotations
import typing as t
import marshmallow as ma
import muffin
import peewee as pw
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow_peewee import ForeignKey, ModelSchema
from muffin.typing import JS... |
# XXX: Patch apispec.MarshmallowPlugin to support ForeignKeyField
MarshmallowPlugin.Converter.field_mapping[ForeignKey] = ("integer", None)
class PWRESTOptions(RESTOptions):
"""Support Peewee."""
model: t.Type[pw.Model]
model_pk: t.Optional[pw.Field] = None
manager: Manager
# Base filters clas... | from muffin_rest.peewee.openapi import PeeweeOpenAPIMixin
from muffin_rest.peewee.sorting import PWSorting | random_line_split |
__init__.py | """Support for Peewee ORM (https://github.com/coleifer/peewee)."""
from __future__ import annotations
import typing as t
import marshmallow as ma
import muffin
import peewee as pw
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow_peewee import ForeignKey, ModelSchema
from muffin.typing import JS... | (self, request, *, resource=None) -> JSONType:
"""Get resource or collection of resources."""
if resource is not None and resource != "":
return await self.dump(request, resource, many=False)
resources = await self.meta.manager.fetchall(self.collection)
return await self.dum... | get | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Copyright(C) 2016 Edouard Lambert
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the... | # This weboob module is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Publ... | random_line_split | |
color.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Color", inherited=True) %>
<% fr... | (context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
CSSColor::parse(context, input).map(SpecifiedValue)
}
// FIXME(#15973): Add servo support for system colors
% if product == "gecko":
<%
# These are actually parsed. See nsCSSProps::kColorKTable
... | parse | identifier_name |
color.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Color", inherited=True) %>
<% fr... |
}
pub mod computed_value {
use cssparser;
pub type T = cssparser::RGBA;
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
RGBA::new(0, 0, 0, 255) // black
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
... | {
self.0.to_css(dest)
} | identifier_body |
color.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Color", inherited=True) %>
<% fr... | #[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
self.0.parsed.to_computed_value(context)
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue(CSSColor {
parsed: Color::RG... | type ComputedValue = computed_value::T;
| random_line_split |
ScreenSprite.js | //-----------------------------------------------------------------------------
/**
* The sprite which covers the entire game screen.
*
* @class ScreenSprite
* @constructor
*/
function | () {
this.initialize.apply(this, arguments);
}
ScreenSprite.prototype = Object.create(PIXI.Container.prototype);
ScreenSprite.prototype.constructor = ScreenSprite;
ScreenSprite.prototype.initialize = function () {
PIXI.Container.call(this);
this._graphics = new PIXI.Graphics();
this.addChild(this._gr... | ScreenSprite | identifier_name |
ScreenSprite.js | //-----------------------------------------------------------------------------
/**
* The sprite which covers the entire game screen.
*
* @class ScreenSprite
* @constructor
*/
function ScreenSprite() {
this.initialize.apply(this, arguments);
}
ScreenSprite.prototype = Object.create(PIXI.Container.prototype);
... |
this._graphics = new PIXI.Graphics();
this.addChild(this._graphics);
this.opacity = 0;
this._red = -1;
this._green = -1;
this._blue = -1;
this._colorText = '';
this.setBlack();
};
/**
* The opacity of the sprite (0 to 255).
*
* @property opacity
* @type Number
*/
Object.definePro... | PIXI.Container.call(this); | random_line_split |
ScreenSprite.js | //-----------------------------------------------------------------------------
/**
* The sprite which covers the entire game screen.
*
* @class ScreenSprite
* @constructor
*/
function ScreenSprite() |
ScreenSprite.prototype = Object.create(PIXI.Container.prototype);
ScreenSprite.prototype.constructor = ScreenSprite;
ScreenSprite.prototype.initialize = function () {
PIXI.Container.call(this);
this._graphics = new PIXI.Graphics();
this.addChild(this._graphics);
this.opacity = 0;
this._red = -1... | {
this.initialize.apply(this, arguments);
} | identifier_body |
ScreenSprite.js | //-----------------------------------------------------------------------------
/**
* The sprite which covers the entire game screen.
*
* @class ScreenSprite
* @constructor
*/
function ScreenSprite() {
this.initialize.apply(this, arguments);
}
ScreenSprite.prototype = Object.create(PIXI.Container.prototype);
... |
};
| {
r = Math.round(r || 0).clamp(0, 255);
g = Math.round(g || 0).clamp(0, 255);
b = Math.round(b || 0).clamp(0, 255);
this._red = r;
this._green = g;
this._blue = b;
this._colorText = Utils.rgbToCssColor(r, g, b);
var graphics = this._graphics;
grap... | conditional_block |
AbstractNavItem.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/exte... |
var _proto = AbstractNavItem.prototype;
_proto.render = function render() {
var _this = this;
var _this$props = this.props,
active = _this$props.active,
className = _this$props.className,
tabIndex = _this$props.tabIndex,
eventKey = _this$props.eventKey,
onSelect =... | {
return _React$Component.apply(this, arguments) || this;
} | identifier_body |
AbstractNavItem.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/exte... | () {
return _React$Component.apply(this, arguments) || this;
}
var _proto = AbstractNavItem.prototype;
_proto.render = function render() {
var _this = this;
var _this$props = this.props,
active = _this$props.active,
className = _this$props.className,
tabIndex = _this$props.t... | AbstractNavItem | identifier_name |
AbstractNavItem.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/exte... | var _default = AbstractNavItem;
exports.default = _default;
module.exports = exports["default"]; |
AbstractNavItem.defaultProps = defaultProps; | random_line_split |
win_msg.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Jon Hawkesworth (@jhawkesworth) <figs@unity.demon.co.uk>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eith... | description: The return code of the API call
returned: always
type: int
sample: 0
runtime_seconds:
description: How long the module took to run on the remote windows host.
returned: success
type: string
sample: 22 July 2016 17:45:51
sent_localtime:
description: local time from window... | sample: 10
rc: | random_line_split |
increment.py | config = ConfigParser.ConfigParser()
config.read(CONFIG)
if not config.has_section(SECTIONS['INCREMENTS']):
config.add_section(SECTIONS['INCREMENTS'])
with open(CONFIG, 'w') as f:
config.write(f)
def read_since_ids(users):
"""
Read max ids of the last downloads
:param users: A list of us... | import ConfigParser
from .settings import SECTIONS, CONFIG
| random_line_split | |
increment.py | import ConfigParser
from .settings import SECTIONS, CONFIG
config = ConfigParser.ConfigParser()
config.read(CONFIG)
if not config.has_section(SECTIONS['INCREMENTS']):
config.add_section(SECTIONS['INCREMENTS'])
with open(CONFIG, 'w') as f:
config.write(f)
def read_since_ids(users):
|
def set_max_ids(max_ids):
"""
Set max ids of the current downloads
:param max_ids: A dictionary mapping users to ids
"""
config.read(CONFIG)
for user, max_id in max_ids.items():
config.set(SECTIONS['INCREMENTS'], user, str(max_id))
with open(CONFIG, 'w') as f:
config.writ... | """
Read max ids of the last downloads
:param users: A list of users
Return a dictionary mapping users to ids
"""
since_ids = {}
for user in users:
if config.has_option(SECTIONS['INCREMENTS'], user):
since_ids[user] = config.getint(SECTIONS['INCREMENTS'], user) + 1
retu... | identifier_body |
increment.py | import ConfigParser
from .settings import SECTIONS, CONFIG
config = ConfigParser.ConfigParser()
config.read(CONFIG)
if not config.has_section(SECTIONS['INCREMENTS']):
config.add_section(SECTIONS['INCREMENTS'])
with open(CONFIG, 'w') as f:
config.write(f)
def read_since_ids(users):
"""
Read ... |
return since_ids
def set_max_ids(max_ids):
"""
Set max ids of the current downloads
:param max_ids: A dictionary mapping users to ids
"""
config.read(CONFIG)
for user, max_id in max_ids.items():
config.set(SECTIONS['INCREMENTS'], user, str(max_id))
with open(CONFIG, 'w') as f... | if config.has_option(SECTIONS['INCREMENTS'], user):
since_ids[user] = config.getint(SECTIONS['INCREMENTS'], user) + 1 | conditional_block |
increment.py | import ConfigParser
from .settings import SECTIONS, CONFIG
config = ConfigParser.ConfigParser()
config.read(CONFIG)
if not config.has_section(SECTIONS['INCREMENTS']):
config.add_section(SECTIONS['INCREMENTS'])
with open(CONFIG, 'w') as f:
config.write(f)
def read_since_ids(users):
"""
Read ... | (user):
if config.has_option(SECTIONS['INCREMENTS'], user):
config.remove_option(SECTIONS['INCREMENTS'], user)
with open(CONFIG, 'w') as f:
config.write(f)
| remove_since_id | identifier_name |
sunburst.js | /*
* Copyright 2013 Google Inc. All Rights Reserved.
* 2015 Hauke Petersen <devel@haukepetersen.de>
*
* 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... | (d) {
updateTable(d);
var percentage = (100 * d.value / totalSize).toPrecision(3);
var percentageString = percentage + "%";
if (percentage < 0.1) {
percentageString = "< 0.1%";
}
d3.select("#expl_per").text(percentageString);
d3.select("#expl_sym").text(d.name);
d3.select("#expl_size").text(d.val... | mouseover | identifier_name |
sunburst.js | /*
* Copyright 2013 Google Inc. All Rights Reserved.
* 2015 Hauke Petersen <devel@haukepetersen.de>
*
* 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... | };
function updateTable(d) {
var table = d3.select("#table");
table.selectAll("tbody").remove();
var body = table.append("tbody");
tableAdd(d, body, 1);
};
function tableAdd(d, body, layer) {
var row = body.append("tr").classed("l" + layer, true);
row.append("td").text(d.name);
row.append(... |
function zoomOut(d) {
d3.event.preventDefault();
console.log("right click", d);
updateChart(cur_view); | random_line_split |
sunburst.js | /*
* Copyright 2013 Google Inc. All Rights Reserved.
* 2015 Hauke Petersen <devel@haukepetersen.de>
*
* 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... |
/* build the branch, now adding the leaf */
e.children.push({'name': dataset[i]['sym'], 'size': dataset[i]['size']});
}
return r;
}
function update(fil) {
cur_view = {};
cur_view = filter(fil);
updateChart(cur_view);
updateTable(cur_view);
}
// bootstrap the whole damn thing
... | {
var child = undefined;
// search for part
for (var k = 0; k < e.children.length; k++) {
if (e.children[k]['name'] == path[j]) {
child = e.children[k];
}
}
if (!child) {
e.children.push({'nam... | conditional_block |
sunburst.js | /*
* Copyright 2013 Google Inc. All Rights Reserved.
* 2015 Hauke Petersen <devel@haukepetersen.de>
*
* 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... | ;
function tableAdd(d, body, layer) {
var row = body.append("tr").classed("l" + layer, true);
row.append("td").text(d.name);
row.append("td").text(d.value).classed("size", true);
if (d.children && layer < 2) {
for (var i = 0; i < d.children.length; i++) {
tableAdd(d.children[i], bod... | {
var table = d3.select("#table");
table.selectAll("tbody").remove();
var body = table.append("tbody");
tableAdd(d, body, 1);
} | identifier_body |
RaceData.js | var RaceData = {
human: {
name: 'Human',
physical: 6,
personal: 6, | genders: 'male|female',
},
dwarf: {
name: 'Dwarf',
physical: 8,
personal: 0,
mental: 4,
magical: 4,
genders: 'male',
defenses: { moist:5 },
},
elf: {
name: 'Elf',
physical: 0,
personal: 6,
mental: 2,
magical: 8,
genders: 'female',
abilities: ['royalR... | mental: 4,
magical: 0, | random_line_split |
ajax.js | jQuery(document).ready(function(){
jQuery("#ResponsiveContactForm").validate({
submitHandler: function(form)
{
jQuery.ajax({
type: "POST",
dataType: "json",
url:MyAjax,
data:{
action: 'ai_action',
fdata : jQuery(document.formValidate).serialize()
},
success:function(respon... | else if(response == 2){
jQuery("#fmsg").slideDown(function(){
jQuery(this).show().delay(8000).slideUp("fast")});
jQuery("#captcha").removeClass("valid").addClass("error");
jQuery("#captcha").next('label.valid').removeClass("valid").addClass("error");
jQuery('#captcha').val... | {
jQuery("#smsg").slideDown(function(){
jQuery('html, body').animate({scrollTop: jQuery("#smsg").offset().top},'fast');
jQuery(this).show().delay(8000).slideUp("fast")});
document.getElementById('ResponsiveContactForm').reset();
refreshCaptcha();
jQuery(".input-xlarge").removeClass... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.