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 |
|---|---|---|---|---|
thisplace.py | thisplace: Human-readable addresses for every 3x3m square on the earth's surface.
The simplest way to use this module are the `four_words` and `decode`
functions. For more see `WordHasher`.
"""
import random
import geohash
def get_words(fname):
lines = open(fname)
words = []
for word in lines:
wo... | """ | random_line_split | |
thisplace.py | bluebird', 'bravo', 'bulldog', 'burger',
'butter', 'california', 'carbon', 'cardinal', 'carolina', 'carpet', 'cat',
'ceiling', 'charlie', 'chicken', 'coffee', 'cola', 'cold', 'colorado',
'comet', 'connecticut', 'crazy', 'cup', 'dakota', 'december', 'delaware',
'delta', 'diet', 'don', 'do... | to_rugbits | identifier_name | |
thisplace.py | = get_words("words/google-ngram-list-4096")
# current best list for the three word hash
WORDNET_LEMMAS = get_words("words/wordnet-list")
# Human friendly word list, taken directly from humanhash project
# these are the best words but there are not enough of
# them so we only use them for the six word hash
HUMAN_WORDL... |
def geo_to_int(self, geo_hash):
"""Decode `geo_hash` to an integer"""
base = len(self._symbols)
number = 0
for symbol in geo_hash:
number = number*base + self._decode_symbols[symbol]
return number
def int_to_geo(self, integer):
"""Encode `integer` ... | """Decode `words` to latitude and longitude"""
words = words.split("-")
if len(words) == 3:
i = self.rugbits_to_int([self.three_wordlist.index(w) for w in words])
elif len(words) == 4:
i = self.quads_to_int([self.four_wordlist.index(w) for w in words])
i = se... | identifier_body |
thisplace.py | = get_words("words/google-ngram-list-4096")
# current best list for the three word hash
WORDNET_LEMMAS = get_words("words/wordnet-list")
# Human friendly word list, taken directly from humanhash project
# these are the best words but there are not enough of
# them so we only use them for the six word hash
HUMAN_WORDL... |
elif len(words) == 6:
i = self.bytes_to_int([self.six_wordlist.index(w) for w in words])
i = self.unpad(i)
else:
raise RuntimeError("Do not know how to decode a set of %i words."%(len(words)))
geo_hash = self.int_to_geo(i)
return geohash.decode(geo... | i = self.quads_to_int([self.four_wordlist.index(w) for w in words])
i = self.unpad(i) | conditional_block |
eigen.py | # This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.sparse.linalg` namespace for importing the functions
# included below.
import warnings
from . import _eigen
__all__ = [ # noqa: F822
'ArpackError', 'ArpackNoConvergence',
'eigs', 'eigsh', 'lobpcg', 'svds', 'arpack'... |
else:
msg = (f"Please use `{name}` from the `scipy.sparse.linalg` namespace,"
" the `scipy.sparse.linalg.eigen` namespace is deprecated.")
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
return getattr(_eigen, name)
| msg = (f'The module `scipy.sparse.linalg.eigen.{name}` is '
'deprecated. All public names must be imported directly from '
'the `scipy.sparse.linalg` namespace.') | conditional_block |
eigen.py | # This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.sparse.linalg` namespace for importing the functions
# included below.
import warnings
from . import _eigen
__all__ = [ # noqa: F822
'ArpackError', 'ArpackNoConvergence',
'eigs', 'eigsh', 'lobpcg', 'svds', 'arpack'... | (name):
if name not in __all__ and name not in eigen_modules:
raise AttributeError(
"scipy.sparse.linalg.eigen is deprecated and has no attribute "
f"{name}. Try looking in scipy.sparse.linalg instead.")
if name in eigen_modules:
msg = (f'The module `scipy.sparse.linalg.... | __getattr__ | identifier_name |
eigen.py | # This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.sparse.linalg` namespace for importing the functions
# included below.
import warnings
from . import _eigen
__all__ = [ # noqa: F822
'ArpackError', 'ArpackNoConvergence',
'eigs', 'eigsh', 'lobpcg', 'svds', 'arpack'... |
def __getattr__(name):
if name not in __all__ and name not in eigen_modules:
raise AttributeError(
"scipy.sparse.linalg.eigen is deprecated and has no attribute "
f"{name}. Try looking in scipy.sparse.linalg instead.")
if name in eigen_modules:
msg = (f'The module `sc... | return __all__ | identifier_body |
eigen.py | # This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.sparse.linalg` namespace for importing the functions
# included below.
import warnings
from . import _eigen
__all__ = [ # noqa: F822
'ArpackError', 'ArpackNoConvergence',
'eigs', 'eigsh', 'lobpcg', 'svds', 'arpack'... | msg = (f"Please use `{name}` from the `scipy.sparse.linalg` namespace,"
" the `scipy.sparse.linalg.eigen` namespace is deprecated.")
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
return getattr(_eigen, name) | random_line_split | |
ServerSetup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... | #expand all ~'s in the list
path_append = [os.path.expanduser(path) for path in path_append]
sys.path.extend(path_append)
if ServerConfig.get('pypath_prepend'):
path_prepend = ServerConfig['pypath_prepend'].split(':')
path_prepend.reverse()
for path in path_prepe... | random_line_split | |
ServerSetup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... |
def normalizeUrlList(url_list):
"""Add necessary default entries that the user did not enter."""
for dict in url_list:
if not dict.get('kp.app_object'):
dict['kp.app_object'] = 'application'
def normalizeWsgiVars(WsgiConfig):
"""Put WSGI config data in a state ... | """Use ServerConfig to add to the python path."""
if ServerConfig.get('pypath_append'):
path_append = ServerConfig['pypath_append'].split(':')
#expand all ~'s in the list
path_append = [os.path.expanduser(path) for path in path_append]
sys.path.extend(path_append)
if ServerC... | identifier_body |
ServerSetup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... | (WsgiConfig):
"""Put WSGI config data in a state that the server expects."""
WsgiConfig['wsgi_ver'] = tuple(WsgiConfig['wsgi_ver'].split('.'))
def initializeLogger(consolename='kamaelia'):
"""This sets up the logging system."""
formatter = logging.Formatter('%(levelname)s/%(name)s: %(message)s')
... | normalizeWsgiVars | identifier_name |
ServerSetup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... |
def normalizeWsgiVars(WsgiConfig):
"""Put WSGI config data in a state that the server expects."""
WsgiConfig['wsgi_ver'] = tuple(WsgiConfig['wsgi_ver'].split('.'))
def initializeLogger(consolename='kamaelia'):
"""This sets up the logging system."""
formatter = logging.Formatter('%(lev... | if not dict.get('kp.app_object'):
dict['kp.app_object'] = 'application' | conditional_block |
stringtie.py | #!/usr/bin/env python3
# Version 1.0
# Author Alexis Blanchet-Cohen
# Date: 09/06/2014
import argparse
import glob
import os
import subprocess
import util
# Read the command line arguments.
parser = argparse.ArgumentParser(description="Generates stringtie scripts.")
parser.add_argument("-s", "--scriptsDirectory", he... | util.cdMainScriptsDirectory()
# Process the command line arguments.
scriptsDirectory = os.path.abspath(args.scriptsDirectory)
inputDirectory = os.path.abspath(args.inputDirectory)
outputDirectory = os.path.abspath(args.outputDirectory)
# Read configuration files
config = util.readConfigurationFiles()
header = confi... | # If not in the main scripts directory, cd to the main scripts directory, if it exists. | random_line_split |
stringtie.py | #!/usr/bin/env python3
# Version 1.0
# Author Alexis Blanchet-Cohen
# Date: 09/06/2014
import argparse
import glob
import os
import subprocess
import util
# Read the command line arguments.
parser = argparse.ArgumentParser(description="Generates stringtie scripts.")
parser.add_argument("-s", "--scriptsDirectory", he... |
scriptName = "stringtie_" + sample + ".sh"
script = open(scriptName, "w")
if header:
util.writeHeader(script, config, "stringtie")
script.write("stringtie \\\n")
script.write(os.path.relpath(os.path.join(inputDirectory, sample, sample + "Aligned.sortedByCoord.out.bam")) + " \\\n")
scri... | os.makedirs(os.path.join(outputDirectory, sample)) | conditional_block |
services.py | from .models import *
from django.db.models import Count, F, Max, Sum
# Game info services
def get_median_points(game_id):
return median_value(Team.objects.filter(play__game__id=game_id) \
.exclude(play__team__points__isnull=True),
'play__team__points')
def get_pl... |
elif count > 0:
return sum(values[count / 2 - 1:count / 2 + 1]) / 2.0
else:
return 0
| return values[int(round(count / 2))] | conditional_block |
services.py | from .models import *
from django.db.models import Count, F, Max, Sum
# Game info services
def get_median_points(game_id):
|
def get_play_count(game_id):
return Play.objects.filter(game__id=game_id).count()
def get_game_list():
games = Game.objects.all() \
.annotate(plays=Count('play__id')) \
.annotate(last_played=Max('play__date')) \
.order_by('-plays')
return games
def get_game_players(game_id):
... | return median_value(Team.objects.filter(play__game__id=game_id) \
.exclude(play__team__points__isnull=True),
'play__team__points') | identifier_body |
services.py | from .models import *
from django.db.models import Count, F, Max, Sum
# Game info services
def get_median_points(game_id):
return median_value(Team.objects.filter(play__game__id=game_id) \
.exclude(play__team__points__isnull=True),
'play__team__points')
def get_pl... | (player_id):
# XXX: That distinct() is probably not working as expected
# But there are not counterexamples in the current data set
plays_ids = get_play_ids(player_id)
return Player.objects.filter(team__play__id__in=plays_ids) \
.exclude(id=player_id) \
.values('name', 'team__play__id') ... | get_player_mates | identifier_name |
services.py | from .models import *
from django.db.models import Count, F, Max, Sum
# Game info services
def get_median_points(game_id):
return median_value(Team.objects.filter(play__game__id=game_id) \
.exclude(play__team__points__isnull=True),
'play__team__points')
def get_pl... |
# Helper methods
def get_play_ids(player_id):
return Play.objects.filter(team__players__id=player_id).values('id').distinct()
def median_value(queryset, term):
count = queryset.count()
values = queryset.values_list(term, flat=True).order_by(term)
if count % 2 == 1:
return values[int(round(cou... | .values('name') \
.annotate(count=Count('name')) \
.order_by('-count')
| random_line_split |
MissingPersonForm.py | # Created: 12/12/2011
# Copyright: (c) Don Ferguson 2011
# Licence:
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ver... |
email = row2.getValue("E_Mail")
if email == 'none':
email = " "
arcpy.AddWarning("No e-mail address provided for Lead Agency")
row2 = rows2.next()
del rows2
del row2
row = rows.next()
del rows
del row
Callback = "If you have information please call: " + st... | Phone = " "
arcpy.AddWarning("No Phone number provided for Lead Agency") | conditional_block |
MissingPersonForm.py | #
# Created: 12/12/2011
# Copyright: (c) Don Ferguson 2011
# Licence:
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | # GNU General Public License for more details.
#
# The GNU General Public License can be found at
# <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import arcpy
from datetime import datetime
#workspc = arcpy.GetParameterAsText(0... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | random_line_split |
overlay.js | /**
* @module popoff/overlay
*
* Because overlay-component is hopelessly out of date.
* This is modern rewrite.
*/
const Emitter = require('events').EventEmitter;
const inherits = require('inherits');
const extend = require('xtend/mutable');
module.exports = Overlay;
/**
* Initialize a new `Overlay`.
*
* ... | function Overlay(options) {
if (!(this instanceof Overlay)) return new Overlay(options);
Emitter.call(this);
extend(this, options);
if (!this.container) {
this.container = document.body || document.documentElement;
}
//create overlay element
this.element = document.createElement('div');
this.element.class... | random_line_split | |
overlay.js | /**
* @module popoff/overlay
*
* Because overlay-component is hopelessly out of date.
* This is modern rewrite.
*/
const Emitter = require('events').EventEmitter;
const inherits = require('inherits');
const extend = require('xtend/mutable');
module.exports = Overlay;
/**
* Initialize a new `Overlay`.
*
* ... | }
}
inherits(Overlay, Emitter);
//close overlay by click
Overlay.prototype.closable = true;
/**
* Show the overlay.
*
* Emits "show" event.
*
* @return {Overlay}
* @api public
*/
Overlay.prototype.show = function () {
this.emit('show');
this.container.appendChild(this.element);
//class removed in a ... | {
if (!(this instanceof Overlay)) return new Overlay(options);
Emitter.call(this);
extend(this, options);
if (!this.container) {
this.container = document.body || document.documentElement;
}
//create overlay element
this.element = document.createElement('div');
this.element.classList.add('popoff-overlay')... | identifier_body |
overlay.js | /**
* @module popoff/overlay
*
* Because overlay-component is hopelessly out of date.
* This is modern rewrite.
*/
const Emitter = require('events').EventEmitter;
const inherits = require('inherits');
const extend = require('xtend/mutable');
module.exports = Overlay;
/**
* Initialize a new `Overlay`.
*
* ... |
//create overlay element
this.element = document.createElement('div');
this.element.classList.add('popoff-overlay');
if (this.closable) {
this.element.addEventListener('click', e => {
this.hide();
});
this.element.classList.add('popoff-closable');
}
}
inherits(Overlay, Emitter);
//close overlay by c... | {
this.container = document.body || document.documentElement;
} | conditional_block |
overlay.js | /**
* @module popoff/overlay
*
* Because overlay-component is hopelessly out of date.
* This is modern rewrite.
*/
const Emitter = require('events').EventEmitter;
const inherits = require('inherits');
const extend = require('xtend/mutable');
module.exports = Overlay;
/**
* Initialize a new `Overlay`.
*
* ... | () {
that.element.removeEventListener('transitionend', end);
that.element.removeEventListener('webkitTransitionEnd', end);
that.element.removeEventListener('otransitionend', end);
that.element.removeEventListener('oTransitionEnd', end);
that.element.removeEventListener('msTransitionEnd', end);
clearInterva... | end | identifier_name |
SampleLights.py |
"""This sample demonstrates some very simple lightning effects."""
import math
import d3d11
import d3d11x
from d3d11c import *
def heightCallback(x, z, byteIndex, data):
return data[byteIndex] * 0.03
class SampleLights(d3d11x.Frame):
def onCreate(self):
#Heightmap.
#self.heightmap = d3d11x.... |
def onRender(self):
#View- and projectionmatrix.
view = self.createLookAt((-50, 25, -50), (0, 0, 0))
projection = self.createProjection(45, 0.1, 300.0)
lights = self.createLights()
#First the heightmap.
self.heightmap.setLights(lights)
#Ad... | lights = []
for i in range(1, 8):
#Each light is little farther than the previous one.
distance = i * 5
lightTime = self.time * (i * 0.5)
#Use sin() and cos() to create a nice little movement pattern.
x = math.sin(lightTime) * distance
z =... | identifier_body |
SampleLights.py |
"""This sample demonstrates some very simple lightning effects."""
import math
import d3d11
import d3d11x
from d3d11c import *
def heightCallback(x, z, byteIndex, data):
return data[byteIndex] * 0.03
class SampleLights(d3d11x.Frame):
def onCreate(self):
#Heightmap.
#self.heightmap = d3d11x.... | sample = SampleLights("Lights - DirectPython 11", __doc__)
sample.mainloop() | conditional_block | |
SampleLights.py |
"""This sample demonstrates some very simple lightning effects."""
import math
import d3d11
import d3d11x
from d3d11c import *
def heightCallback(x, z, byteIndex, data):
return data[byteIndex] * 0.03
class SampleLights(d3d11x.Frame):
def | (self):
#Heightmap.
#self.heightmap = d3d11x.HeightMap(self.device, None, (64, 64), heightCallback, (2, 1, 2), (8, 8), False)
self.heightmap = d3d11x.HeightMap(self.device, d3d11x.getResourceDir("Textures", "heightmap.dds"),
(64, 64), heightCallback, (2, 1, 2), (8, 8), False)
... | onCreate | identifier_name |
SampleLights.py | """This sample demonstrates some very simple lightning effects."""
import math
import d3d11
import d3d11x
from d3d11c import *
def heightCallback(x, z, byteIndex, data):
return data[byteIndex] * 0.03
class SampleLights(d3d11x.Frame):
def onCreate(self):
#Heightmap.
#self.heightmap = d3d11x.H... | self.sphere.render(meshWorld, view, projection)
if __name__ == "__main__":
sample = SampleLights("Lights - DirectPython 11", __doc__)
sample.mainloop() | random_line_split | |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::future::Future;
use crate::call::client::{
CallOption, ClientCStreamReceiver, ClientCStreamSender, ClientDuplexReceiver,
ClientDuplexSender, ClientSStreamReceiver, ClientUnaryReceiver,
};
use crate::call::{Call, Method};
use crate::ch... |
/// Spawn the future into current gRPC poll thread.
///
/// This can reduce a lot of context switching, but please make
/// sure there is no heavy work in the future.
pub fn spawn<F>(&self, f: F)
where
F: Future<Output = ()> + Send + 'static,
{
let kicker = self.kicker.clon... | {
Call::duplex_streaming(&self.channel, method, opt)
} | identifier_body |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::future::Future;
use crate::call::client::{
CallOption, ClientCStreamReceiver, ClientCStreamSender, ClientDuplexReceiver,
ClientDuplexSender, ClientSStreamReceiver, ClientUnaryReceiver,
};
use crate::call::{Call, Method};
use crate::ch... | /// Create an asynchronized client streaming call.
///
/// Client can send a stream of requests and server responds with a single response.
pub fn client_streaming<Req, Resp>(
&self,
method: &Method<Req, Resp>,
opt: CallOption,
) -> Result<(ClientCStreamSender<Req>, ClientCSt... | random_line_split | |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::future::Future;
use crate::call::client::{
CallOption, ClientCStreamReceiver, ClientCStreamSender, ClientDuplexReceiver,
ClientDuplexSender, ClientSStreamReceiver, ClientUnaryReceiver,
};
use crate::call::{Call, Method};
use crate::ch... | {
channel: Channel,
// Used to kick its completion queue.
kicker: Kicker,
}
impl Client {
/// Initialize a new [`Client`].
pub fn new(channel: Channel) -> Client {
let kicker = channel.create_kicker().unwrap();
Client { channel, kicker }
}
/// Create a synchronized unary R... | Client | identifier_name |
config.py | # This file is part of Merlin.
# Merlin is the Copyright (C)2008,2009,2010 of Robin K. Hansen, Elliot Rosemarine, Andreas Jacobsen.
# Individual portions may be copyright by individual contributors, and | # are included in this collective work with permission of the copyright
# owners.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any late... | random_line_split | |
config.py | # This file is part of Merlin.
# Merlin is the Copyright (C)2008,2009,2010 of Robin K. Hansen, Elliot Rosemarine, Andreas Jacobsen.
# Individual portions may be copyright by individual contributors, and
# are included in this collective work with permission of the copyright
# owners.
# This program is free software; ... |
Config = load_config("merlin.cfg") | return config | conditional_block |
config.py | # This file is part of Merlin.
# Merlin is the Copyright (C)2008,2009,2010 of Robin K. Hansen, Elliot Rosemarine, Andreas Jacobsen.
# Individual portions may be copyright by individual contributors, and
# are included in this collective work with permission of the copyright
# owners.
# This program is free software; ... |
Config = load_config("merlin.cfg") | try:
config = configparser()
config.optionxform = str
if len(config.read(path)) != 1:
raise IOError
except StandardError:
# Either couldn't read/find the file, or couldn't parse it.
print "Warning! Could not load %s" % (path,)
raise ImportError
else:
... | identifier_body |
config.py | # This file is part of Merlin.
# Merlin is the Copyright (C)2008,2009,2010 of Robin K. Hansen, Elliot Rosemarine, Andreas Jacobsen.
# Individual portions may be copyright by individual contributors, and
# are included in this collective work with permission of the copyright
# owners.
# This program is free software; ... | (path):
# Load and parse required config file
try:
config = configparser()
config.optionxform = str
if len(config.read(path)) != 1:
raise IOError
except StandardError:
# Either couldn't read/find the file, or couldn't parse it.
print "Warning! Could not lo... | load_config | identifier_name |
VariableParserPath.py | #-*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocols... | #+---------------------------------------------------------------------------+
#+---------------------------------------------------------------------------+
#| Standard library imports |
#+---------------------------------------------------------------------------+
imp... | random_line_split | |
VariableParserPath.py | #-*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocols... | self.variableParserResults.append(variableParserResult)
self._logger.debug(
"After registering new VariablePathResult, Path is {0}".format(
self))
def __str__(self):
return "Path {0} (consumedData={1}, remainingData={2}".format(
self.name, self.consumedDat... | ogger.debug("creation of an invalid parser result.")
| conditional_block |
VariableParserPath.py | #-*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocols... | consumedData.setter
def consumedData(self, consumedData):
self.__consumedData = consumedData
@property
def memory(self):
return self.__memory
@memory.setter
def memory(self, memory):
if memory is None:
raise Exception("Memory cannot be None")
self.__memo... | self.__consumedData
@ | identifier_body |
VariableParserPath.py | #-*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocols... |
return self.__memory
@memory.setter
def memory(self, memory):
if memory is None:
raise Exception("Memory cannot be None")
self.__memory = memory
| self): | identifier_name |
el.js | /*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'templates', 'el', {
button: 'Πρότυπα', | title: 'Πρότυπα Περιεχομένου'
} ); | emptyListMsg: '(Δεν έχουν καθοριστεί πρότυπα)',
insertOption: 'Αντικατάσταση υπάρχοντων περιεχομένων',
options: 'Επιλογές Προτύπου',
selectPromptMsg: 'Παρακαλώ επιλέξτε πρότυπο για εισαγωγή στο πρόγραμμα', | random_line_split |
sleeper.test.js | import sinon from 'sinon';
import expect from 'expect';
import sleeper from '..';
describe('sleeper', () => {
it('should be a function', () => {
expect(sleeper).toEqual(expect.any(Function));
});
it('should expose the Resource constructor', () => {
expect(sleeper.Resource).toEqual(expect.any(Function));
});
... |
return u;
}
}
return false;
}
// Index
server.respondWith('GET', multi, (r) => {
reply(r, users);
});
// Create
server.respondWith('POST', multi, (r) => {
reply(r, user(null, JSON.parse(r.requestBody)));
});
// Read
server.respondWith('GET', single, (r, id) => {
reply(r, us... | {
users.splice(i, 1);
} | conditional_block |
sleeper.test.js | import sinon from 'sinon';
import expect from 'expect';
import sleeper from '..';
describe('sleeper', () => {
it('should be a function', () => {
expect(sleeper).toEqual(expect.any(Function));
});
it('should expose the Resource constructor', () => {
expect(sleeper.Resource).toEqual(expect.any(Function));
});
... |
// get(id), set(id, user), create(null, user), delete(id, false)
function user(id, update) {
if (!id) {
users.push({ id: id = ++counter + '' });
}
for (let i = users.length, u; i--;) {
u = users[i];
if (u.id === id) {
if (update) {
u = users[i] = update;
u.id = id;
}
... | {
json = json || { success: false };
xhr.respond(
json.status || (json.success === false ? 500 : 200),
{ 'Content-Type': 'application/json' },
JSON.stringify(json)
);
} | identifier_body |
sleeper.test.js | import sinon from 'sinon';
import expect from 'expect';
import sleeper from '..';
describe('sleeper', () => {
it('should be a function', () => {
expect(sleeper).toEqual(expect.any(Function));
});
it('should expose the Resource constructor', () => {
expect(sleeper.Resource).toEqual(expect.any(Function));
});
... | k1: 'v1',
k2: 'v2'
};
api.param('k', 'v');
api.param(vals);
expect(api.query).toEqual({
k: 'v',
k1: 'v1',
k2: 'v2'
});
});
it('should return the value for a key when given (key)', () => {
let api = sleeper('/api/users');
api.query = {
k1: 'v1',
k2: 'v2'
};
... | random_line_split | |
sleeper.test.js | import sinon from 'sinon';
import expect from 'expect';
import sleeper from '..';
describe('sleeper', () => {
it('should be a function', () => {
expect(sleeper).toEqual(expect.any(Function));
});
it('should expose the Resource constructor', () => {
expect(sleeper.Resource).toEqual(expect.any(Function));
});
... | (id, update) {
if (!id) {
users.push({ id: id = ++counter + '' });
}
for (let i = users.length, u; i--;) {
u = users[i];
if (u.id === id) {
if (update) {
u = users[i] = update;
u.id = id;
}
if (update === false) {
users.splice(i, 1);
}
return u;
}
}... | user | identifier_name |
seen.js | const Commando = require('discord.js-commando');
const toDDHHMMSS = require('../../util/toDDHHMMSS.js');
class Seen extends Commando.Command {
constructor(client) {
super(client, {
name: 'seen',
aliases: ['seen', 'lastplayed', 'played'],
group: '7dtd',
guildOnly: true,
memberName: '... | var date = "Last login on " + day + " " + month + " " + year + " at " + hours + ":" + minutes;
embed.addField(timeSinceOnline, date, true);
amountOfLines += 1;
}
}
if (amountOfLines > 10) {
client.logger.debug("COMMAND seen: too many results found! " + msg.au... | {
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
],
player = body[i],
lastonline = player.lastonline,
d = new Date(lastonline),
month = monthNam... | conditional_block |
seen.js | const Commando = require('discord.js-commando');
const toDDHHMMSS = require('../../util/toDDHHMMSS.js');
class | extends Commando.Command {
constructor(client) {
super(client, {
name: 'seen',
aliases: ['seen', 'lastplayed', 'played'],
group: '7dtd',
guildOnly: true,
memberName: 'seen',
description: 'Tells you when a player was last online',
details: "Shows dateTime",
examples... | Seen | identifier_name |
seen.js | const Commando = require('discord.js-commando');
const toDDHHMMSS = require('../../util/toDDHHMMSS.js');
class Seen extends Commando.Command {
constructor(client) {
super(client, {
name: 'seen',
aliases: ['seen', 'lastplayed', 'played'],
group: '7dtd',
guildOnly: true,
memberName: '... | return msg.channel.send("Player not found! (Mistyped?)");
}
return msg.channel.send({
embed
})
}
// Taken from https://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site
function timeSince(date) {
var se... | if (amountOfLines == 0) { | random_line_split |
seen.js | const Commando = require('discord.js-commando');
const toDDHHMMSS = require('../../util/toDDHHMMSS.js');
class Seen extends Commando.Command {
constructor(client) {
super(client, {
name: 'seen',
aliases: ['seen', 'lastplayed', 'played'],
group: '7dtd',
guildOnly: true,
memberName: '... | var amountOfLines = 0; // Amount of results
for (var i = 0; i < body.length; i++) {
var playername = body[i].name;
if (playername.toLocaleUpperCase().includes(args)) {
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "Septemb... | {
const client = msg.client;
const sevendtdServer = msg.guild.sevendtdServer
if (!sevendtdServer) {
return msg.channel.send("No 7DTD Server initialized. Please set up your server before using commands")
}
sevendtdServer.getPlayersLocation()
.then(function(response) {
buildMsg(r... | identifier_body |
options.rs | use scaly::containers::Ref;
use scaly::memory::Region;
use scaly::Equal;
use scaly::Page;
use scaly::{Array, String, Vector};
pub struct | {
pub files: Ref<Vector<String>>,
pub output_name: Option<String>,
pub directory: Option<String>,
pub repl: bool,
}
impl Options {
pub fn parse_arguments(
_pr: &Region,
_rp: *mut Page,
_ep: *mut Page,
arguments: Ref<Vector<String>>,
) -> Ref<Options> {
l... | Options | identifier_name |
options.rs | use scaly::containers::Ref;
use scaly::memory::Region;
use scaly::Equal;
use scaly::Page;
use scaly::{Array, String, Vector};
pub struct Options {
pub files: Ref<Vector<String>>,
pub output_name: Option<String>,
pub directory: Option<String>,
pub repl: bool,
}
impl Options {
pub fn parse_arguments... | if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-o")) {
arg = args.next();
output_name = Some(*arg.unwrap());
continue;
}
}
{
let _r_1 = Region::create(&_r);
... | break;
}
{
let _r_1 = Region::create(&_r); | random_line_split |
options.rs | use scaly::containers::Ref;
use scaly::memory::Region;
use scaly::Equal;
use scaly::Page;
use scaly::{Array, String, Vector};
pub struct Options {
pub files: Ref<Vector<String>>,
pub output_name: Option<String>,
pub directory: Option<String>,
pub repl: bool,
}
impl Options {
pub fn parse_arguments... |
}
{
let _r_1 = Region::create(&_r);
if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-r")) {
repl = true;
continue;
}
}
files.add(*arg.unwrap());
}
R... | {
arg = args.next();
directory = Some(*arg.unwrap());
continue;
} | conditional_block |
migrant.py | #!/usr/bin/env python
import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):
with gzip.open(filename) as file:
content = file.read()
return content
def read_plain(filename):
with open(filename) as file:
... | content = json.loads(read(file))
identifier = binascii.unhexlify(
os.path.basename(file).split('.', 1)[0]).decode()
content['_id'] = identifier
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file))
content['updated_at'] = mtime
collection.save(content) | conditional_block | |
migrant.py | #!/usr/bin/env python
import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):
with gzip.open(filename) as file:
content = file.read()
return content
def read_plain(filename):
|
readers = {
b'application/x-gzip': read_gzip,
b'text/plain': read_plain,
}
def read(filename):
type = magic.from_file(filename, mime=True)
return readers[type](filename).decode()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-m', help='path to moita co... | with open(filename) as file:
content = file.read()
return content | identifier_body |
migrant.py | #!/usr/bin/env python
import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):
with gzip.open(filename) as file:
content = file.read()
return content
def read_plain(filename):
with open(filename) as file:
... |
identifier = binascii.unhexlify(
os.path.basename(file).split('.', 1)[0]).decode()
content['_id'] = identifier
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file))
content['updated_at'] = mtime
collection.save(content) | random_line_split | |
migrant.py | #!/usr/bin/env python
import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):
with gzip.open(filename) as file:
content = file.read()
return content
def | (filename):
with open(filename) as file:
content = file.read()
return content
readers = {
b'application/x-gzip': read_gzip,
b'text/plain': read_plain,
}
def read(filename):
type = magic.from_file(filename, mime=True)
return readers[type](filename).decode()
if __name__ == '__main__'... | read_plain | identifier_name |
mod.rs | use bindgen::callbacks::*;
#[derive(Debug)]
struct EnumVariantRename;
impl ParseCallbacks for EnumVariantRename {
fn enum_variant_name(
&self,
_enum_name: Option<&str>,
original_variant_name: &str,
_variant_value: EnumVariantValue,
) -> Option<String> {
Some(format!("RE... | (
&self,
_name: &str,
derive_trait: DeriveTrait,
) -> Option<ImplementsTrait> {
if derive_trait == DeriveTrait::Hash {
Some(ImplementsTrait::No)
} else {
Some(ImplementsTrait::Yes)
}
}
}
pub fn lookup(cb: &str) -> Box<dyn ParseCallbacks> {... | blocklisted_type_implements_trait | identifier_name |
mod.rs | use bindgen::callbacks::*;
#[derive(Debug)]
struct EnumVariantRename;
impl ParseCallbacks for EnumVariantRename {
fn enum_variant_name(
&self,
_enum_name: Option<&str>,
original_variant_name: &str,
_variant_value: EnumVariantValue,
) -> Option<String> {
Some(format!("RE... |
}
pub fn lookup(cb: &str) -> Box<dyn ParseCallbacks> {
match cb {
"enum-variant-rename" => Box::new(EnumVariantRename),
"blocklisted-type-implements-trait" => {
Box::new(BlocklistedTypeImplementsTrait)
}
_ => panic!("Couldn't find name ParseCallbacks: {}", cb),
}
}
| {
if derive_trait == DeriveTrait::Hash {
Some(ImplementsTrait::No)
} else {
Some(ImplementsTrait::Yes)
}
} | identifier_body |
mod.rs | use bindgen::callbacks::*;
#[derive(Debug)]
struct EnumVariantRename;
impl ParseCallbacks for EnumVariantRename {
fn enum_variant_name(
&self,
_enum_name: Option<&str>,
original_variant_name: &str,
_variant_value: EnumVariantValue,
) -> Option<String> {
Some(format!("RE... |
impl ParseCallbacks for BlocklistedTypeImplementsTrait {
fn blocklisted_type_implements_trait(
&self,
_name: &str,
derive_trait: DeriveTrait,
) -> Option<ImplementsTrait> {
if derive_trait == DeriveTrait::Hash {
Some(ImplementsTrait::No)
} else {
... | }
#[derive(Debug)]
struct BlocklistedTypeImplementsTrait; | random_line_split |
duplex.rs | // Copyright 2012-2013 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... | (&self) -> R {
self.rx.recv()
}
pub fn try_recv(&self) -> Result<R, comm::TryRecvError> {
self.rx.try_recv()
}
pub fn recv_opt(&self) -> Result<R, ()> {
self.rx.recv_opt()
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
use comm::{duplex};
#[test]
pub fn du... | recv | identifier_name |
duplex.rs | // Copyright 2012-2013 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... |
// Allow these methods to be used without import:
impl<S:Send,R:Send> DuplexStream<S, R> {
pub fn send(&self, x: S) {
self.tx.send(x)
}
pub fn send_opt(&self, x: S) -> Result<(), S> {
self.tx.send_opt(x)
}
pub fn recv(&self) -> R {
self.rx.recv()
}
pub fn try_recv(&s... | random_line_split | |
duplex.rs | // Copyright 2012-2013 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... |
pub fn send_opt(&self, x: S) -> Result<(), S> {
self.tx.send_opt(x)
}
pub fn recv(&self) -> R {
self.rx.recv()
}
pub fn try_recv(&self) -> Result<R, comm::TryRecvError> {
self.rx.try_recv()
}
pub fn recv_opt(&self) -> Result<R, ()> {
self.rx.recv_opt()
}
... | {
self.tx.send(x)
} | identifier_body |
getos.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- | #
# LIRIS - Laboratoire d'InfoRmatique en Image et Systèmes d'information
#
# Copyright: 2012 - 2015 Eric Lombardi (eric.lombardi@liris.cnrs.fr), LIRIS (liris.cnrs.fr), CNRS (www.cnrs.fr)
#
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public Lic... | #
# STARLING PROJECT | random_line_split |
getos.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# STARLING PROJECT
#
# LIRIS - Laboratoire d'InfoRmatique en Image et Systèmes d'information
#
# Copyright: 2012 - 2015 Eric Lombardi (eric.lombardi@liris.cnrs.fr), LIRIS (liris.cnrs.fr), CNRS (www.cnrs.fr)
#
#
# This program is free software: you can redistribute it... | elif 'x86_64-with-Ubuntu-12.04' in fullOsVersion:
shortVersion = 'u1204-64'
elif 'Windows-7' in fullOsVersion:
shortVersion = 'w7'
else:
shortVersion = 'unknown'
print shortVersion
| hortVersion = 'u1404-64'
| conditional_block |
icosphere.rs | use std::collections::HashMap;
use std::mem;
use scene::Vertex;
fn | (pos: [f32; 3]) -> Vertex {
use std::f32::consts::{PI};
let u = pos[0].atan2(pos[2]) / (-2.0 * PI);
let u = if u < 0. { u + 1. } else { u };
let v = pos[1].asin() / PI + 0.5;
Vertex::new(pos, [u, v])
}
pub fn generate(recursion: u16) -> (Vec<Vertex>, Vec<u16>) {
let face_count = 20 * 4usize.p... | vertex | identifier_name |
icosphere.rs | use std::collections::HashMap;
use std::mem;
use scene::Vertex;
fn vertex(pos: [f32; 3]) -> Vertex {
use std::f32::consts::{PI};
let u = pos[0].atan2(pos[2]) / (-2.0 * PI);
let u = if u < 0. { u + 1. } else { u };
let v = pos[1].asin() / PI + 0.5;
Vertex::new(pos, [u, v])
}
pub fn generate(recur... | vertex([ 0.0, u, v]),
vertex([ 0.0, -u, -v]),
vertex([ 0.0, u, -v]),
vertex([ v, 0.0, -u]),
vertex([ v, 0.0, u]),
vertex([ -v, 0.0, -u]),
vertex([ -v, 0.0, u]),
]);
let mut index_data: Vec<u16> = Vec::with_capacity(index_count);
index_data.extend_fro... | {
let face_count = 20 * 4usize.pow(recursion as u32);
let edge_count = 3 * face_count / 2;
// Euler's formula
let vertex_count = 2 + edge_count - face_count;
let index_count = face_count * 3;
let t = (1.0 + 5.0_f32.sqrt()) / 2.0;
let n = (1. + t * t).sqrt();
let u = 1. / n;
let v =... | identifier_body |
icosphere.rs | use std::collections::HashMap;
use std::mem;
use scene::Vertex;
fn vertex(pos: [f32; 3]) -> Vertex {
use std::f32::consts::{PI};
let u = pos[0].atan2(pos[2]) / (-2.0 * PI);
let u = if u < 0. { u + 1. } else | ;
let v = pos[1].asin() / PI + 0.5;
Vertex::new(pos, [u, v])
}
pub fn generate(recursion: u16) -> (Vec<Vertex>, Vec<u16>) {
let face_count = 20 * 4usize.pow(recursion as u32);
let edge_count = 3 * face_count / 2;
// Euler's formula
let vertex_count = 2 + edge_count - face_count;
let index_... | { u } | conditional_block |
icosphere.rs | use std::collections::HashMap;
use std::mem;
use scene::Vertex;
fn vertex(pos: [f32; 3]) -> Vertex {
use std::f32::consts::{PI};
let u = pos[0].atan2(pos[2]) / (-2.0 * PI);
let u = if u < 0. { u + 1. } else { u };
let v = pos[1].asin() / PI + 0.5;
Vertex::new(pos, [u, v])
}
pub fn generate(recur... | 5, 11, 4,
11, 10, 2,
10, 7, 6,
7, 1, 8,
// 5 faces around point 3
3, 9, 4,
3, 4, 2,
3, 2, 6,
3, 6, 8,
3, 8, 9,
// 5 adjacent faces
4, 9, 5,
2, 4, 11,
6, 2, 10,
8, 6, 7,
9, 8, 1,
]);
... | // 5 adjacent faces
1, 5, 9, | random_line_split |
test.ts | import { WichmannHill } from '@rng/wichmann-hill';
import { samples25fromSeed1234, stateAfterSeed1234, samplesAfterCorrectedSeed } from './fixture';
describe('rng wichman-hill', function () {
it('compare 25 samples seed=0', () => {
const wh = new WichmannHill();
wh.init(1234); | it('check seed data after setting seed to "1234"', () => {
const wh = new WichmannHill();
wh.init(1234);
expect(wh.seed).toEqual(new Uint32Array(stateAfterSeed1234));
});
it('restore seed should generate same sequence of randoms', () => {
const wh = new WichmannHill(7895);
... | const result = wh.randoms(25);
expect(result).toEqualFloatingPointBinary(samples25fromSeed1234, 23, false, false);
}); | random_line_split |
configCaption.js | descr: Изменение заголовка окна Конфигуратора на более полезное
//author: orefkov, artbear | //help: inplace
//www: https://snegopat.ru/scripts/wiki?name=configCaption.js
//addin: global
/*@
Это скрипт, позволящий заменять заголовок окна Конфигуратора на более информативный.
После подключения скрипта вы сможете настроить заголовок на свой вкус, выводя в нём информацию
о редактируемой базе данных, релизе 1С и ... | random_line_split | |
configCaption.js | : Изменение заголовка окна Конфигуратора на более полезное
//author: orefkov, artbear
//help: inplace
//www: https://snegopat.ru/scripts/wiki?name=configCaption.js
//addin: global
/*@
Это скрипт, позволящий заменять заголовок окна Конфигуратора на более информативный.
После подключения скрипта вы сможете настроить заг... | Настройка заключается в вводе выражения на языке JavaScript, которое будет вычислятся при изменениях
заголовка Конфигуратора. Результат вычисления этого выражения и будет отображён как заголовок основного окна.
В выражении можно использовать следующие переменные и функции:
- mainTitle - штатный основной заголовок
- ma... | (/^\s*|\s*$/g, '')
else if(line.match(re_connectString) && -1 != line.indexOf(строкаСоединения))
return currName
}
return null
}
function macrosПоказатьСтрокуСоединенияИБ()
{
КаталогИБ = НСтр(СтрокаСоединенияИнформационнойБазы(), "File")
if(КаталогИБ)
строкаСоединения = Ката... | identifier_body |
configCaption.js | : Изменение заголовка окна Конфигуратора на более полезное
//author: orefkov, artbear
//help: inplace
//www: https://snegopat.ru/scripts/wiki?name=configCaption.js
//addin: global
/*@
Это скрипт, позволящий заменять заголовок окна Конфигуратора на более информативный.
После подключения скрипта вы сможете настроить заг... | (!строкаСоединения)
return null
Path1C = profileRoot.getValue("Dir/AppData") + "..\\1CEStart\\ibases.v8i"
var file = v8New("Файл", Path1C)
if(!file.Существует() || file.ЭтоКаталог())
{
Message("Файл <"+Path1C + "> не существует.")
return
}
var textDoc = v8New("ТекстовыйД... | {
// удобно юзать из профиля CmdLine\IBName
if | identifier_name |
configCaption.js | оловок окна Конфигуратора на более информативный.
После подключения скрипта вы сможете настроить заголовок на свой вкус, выводя в нём информацию
о редактируемой базе данных, релизе 1С и т.п.
@*/
global.connectGlobals(SelfScript)
var captionExprPath = "ConfigCaption/Expression"
profileRoot.createValue(captionExprPath, ... | conditional_block | ||
lib.rs | ::parser::*;
use cpython::*;
use cpython_ext::Str;
use pyconfigparser::config;
mod exceptions {
use super::*;
py_exception!(cliparser, AmbiguousCommand);
py_exception!(cliparser, CircularReference);
py_exception!(cliparser, MalformedAlias);
py_exception!(cliparser, OptionNotRecognized);
py_exc... | if tuple.len(py) < 3 {
let msg = format!("flag defintion requires at least 3 items");
return Err(PyErr::new::<exc::ValueError, _>(py, msg));
}
let short: String = tuple.get_item(py, 0).extract(py)?;
let long: String = tuple.get_item(py, 1).extract(py)?;
le... | fn extract(py: Python, obj: &'s PyObject) -> PyResult<Self> {
let tuple: PyTuple = obj.extract(py)?; | random_line_split |
lib.rs | pyconfigparser::config;
mod exceptions {
use super::*;
py_exception!(cliparser, AmbiguousCommand);
py_exception!(cliparser, CircularReference);
py_exception!(cliparser, MalformedAlias);
py_exception!(cliparser, OptionNotRecognized);
py_exception!(cliparser, OptionRequiresArgument);
py_exc... | {
return PyErr::new::<exceptions::OptionArgumentInvalid, _>(
py,
(msg, option_name, given, expected),
);
} | conditional_block | |
lib.rs | ::parser::*;
use cpython::*;
use cpython_ext::Str;
use pyconfigparser::config;
mod exceptions {
use super::*;
py_exception!(cliparser, AmbiguousCommand);
py_exception!(cliparser, CircularReference);
py_exception!(cliparser, MalformedAlias);
py_exception!(cliparser, OptionNotRecognized);
py_exc... | (py: Python, package: &str) -> PyResult<PyModule> {
let name = [package, "cliparser"].join(".");
let m = PyModule::new(py, &name)?;
m.add(py, "earlyparse", py_fn!(py, early_parse(args: Vec<String>)))?;
m.add(py, "parseargs", py_fn!(py, parse_args(args: Vec<String>)))?;
m.add(
py,
"pa... | init_module | identifier_name |
lib.rs | ::parser::*;
use cpython::*;
use cpython_ext::Str;
use pyconfigparser::config;
mod exceptions {
use super::*;
py_exception!(cliparser, AmbiguousCommand);
py_exception!(cliparser, CircularReference);
py_exception!(cliparser, MalformedAlias);
py_exception!(cliparser, OptionNotRecognized);
py_exc... | continue;
}
let is_debug = name.starts_with("debug");
let i = command_map.len() as isize;
command_map.insert(name, if is_debug { -i } else { i });
}
}
let lookup = move |name: &str| {
if name.contains(":") {
return None... | {
let cfg = &config.get_cfg(py);
if !strict && !args.is_empty() {
// Expand args[0] from a prefix to a full command name
let mut command_map = BTreeMap::new();
for (i, name) in command_names.into_iter().enumerate() {
let i: isize = i as isize + 1; // avoid using 0
... | identifier_body |
reducers.test.ts | import {
apiKeysLoaded,
apiKeysReducer,
includeExpiredToggled,
initialApiKeysState,
isFetching,
setSearchQuery,
} from './reducers';
import { getMultipleMockKeys } from '../__mocks__/apiKeysMock';
import { reducerTester } from '../../../../test/core/redux/reducerTester';
import { ApiKeysState } from '../..... | reducerTester<ApiKeysState>()
.givenReducer(apiKeysReducer, { ...initialApiKeysState })
.whenActionIsDispatched(setSearchQuery('test query'))
.thenStateShouldEqual({
...initialApiKeysState,
searchQuery: 'test query',
});
});
it('should toggle the includeExpired state', (... | });
});
it('should set search query', () => { | random_line_split |
project.config.ts | import { join } from 'path';
import { SeedConfig } from './seed.config';
import { ExtendPackages } from './seed.config.interfaces';
/**
* This class extends the basic seed configuration, allowing for project specific overrides. A few examples can be found
* below.
*/
export class ProjectConfig extends SeedConfig {... | main: 'moment.js',
defaultExtension: 'js'
}
}
];
this.addPackagesBundles(additionalPackages);
}
} | name:'moment',
path:'node_modules/moment',
packageMeta:{ | random_line_split |
project.config.ts | import { join } from 'path';
import { SeedConfig } from './seed.config';
import { ExtendPackages } from './seed.config.interfaces';
/**
* This class extends the basic seed configuration, allowing for project specific overrides. A few examples can be found
* below.
*/
export class | extends SeedConfig {
PROJECT_TASKS_DIR = join(process.cwd(), this.TOOLS_DIR, 'tasks', 'project');
constructor() {
super();
// this.APP_TITLE = 'Put name of your app here';
/* Enable typeless compiler runs (faster) between typed compiler runs. */
// this.TYPED_COMPILE_INTERVAL = 5;
// Add `N... | ProjectConfig | identifier_name |
all_tests_coverage.py | #!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
if __name__ == '__main__':
coverage.erase()
coverage.start()
unittest.TextTestRunner().run(all_tests.suite())
coverage.stop()
coverage.report([atom.core, atom.http_core, atom.auth, atom.data,
atom.mock_http_core, atom.client, gdata.gauth, gdata.client,
gdata.core, gdata.data, gdata.blogger.data,... | return unittest.TestSuite((atom_tests.core_test.suite(),)) | identifier_body |
all_tests_coverage.py | #!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
__author__ = 'j.s@google.com (Jeff Scudder)'
import unittest
import coverage
import all_tests
import atom.core
import atom.http_core
import atom.mock_http_core
import atom.auth
import atom.client
import gdata.gauth
import gdata.client
import gdata.data
import gdata.blogger.data
import gdata.blogger.client
import gd... |
# This module is used for version 2 of the Google Data APIs. | random_line_split |
all_tests_coverage.py | #!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | ():
return unittest.TestSuite((atom_tests.core_test.suite(),))
if __name__ == '__main__':
coverage.erase()
coverage.start()
unittest.TextTestRunner().run(all_tests.suite())
coverage.stop()
coverage.report([atom.core, atom.http_core, atom.auth, atom.data,
atom.mock_http_core, atom.client, gdata.gauth,... | suite | identifier_name |
all_tests_coverage.py | #!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | coverage.erase()
coverage.start()
unittest.TextTestRunner().run(all_tests.suite())
coverage.stop()
coverage.report([atom.core, atom.http_core, atom.auth, atom.data,
atom.mock_http_core, atom.client, gdata.gauth, gdata.client,
gdata.core, gdata.data, gdata.blogger.data, gdata.blogger.client,
gd... | conditional_block | |
index.ts | import xs from 'xstream';
import { model as history$ } from './history';
import { model as request$ } from './request';
import { model as state$ } from './state';
import { Command, Event, Message } from './message';
import { EntryViewer, State, StateData } from '../type';
const parseInitialState = (state: StateData |... | request$(subject),
state$(subject, state)
)
.map((message) => {
setTimeout(() => subject.shamefullySendNext(message));
return message;
});
const event$ = message$
.filter(isEvent)
.map((event) => event as Event);
return event$;
};
export { model }; | const state: State = parseInitialState(initialState);
const subject = xs.create<Message>();
const message$ = xs.merge<Message>(
command$,
history$(subject), | random_line_split |
index.ts | import xs from 'xstream';
import { model as history$ } from './history';
import { model as request$ } from './request';
import { model as state$ } from './state';
import { Command, Event, Message } from './message';
import { EntryViewer, State, StateData } from '../type';
const parseInitialState = (state: StateData |... |
return {
entry: state.entry,
entryViewer: EntryViewer.create(state.entries),
menu: state.entry === null
};
};
const isEvent = (message: Message): message is Event => {
return message.type === 'state' ||
message.type === 'request' ||
message.type == 'history';
};
const model = (
command$: ... | {
return {
entry: null,
entryViewer: EntryViewer.create([]),
menu: true
};
} | conditional_block |
__init__.py | # http://www.apache.org/licenses/LICENSE-2.0
#
# 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... | # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# | random_line_split | |
__init__.py | , mkdir
from girder.utility._cache import cache, requestCache, rateLimitBuffer
__version__ = '2.5.0'
__license__ = 'Apache 2.0'
VERSION['apiVersion'] = __version__
_quiet = False
_originalStdOut = sys.stdout
_originalStdErr = sys.stderr
class LogLevelFilter(object):
"""
Filter log records based on whether ... |
def format(self, record, *args, **kwargs):
if hasattr(record, 'name') and hasattr(record, 'message'):
if (record.name.startswith('cherrypy.access') or
record.name.startswith('cherrypy.error')):
return record.message
return super(LogFormatter, self).f... | info = '\n'.join((
' Request URL: %s %s' % (cherrypy.request.method.upper(),
cherrypy.url()),
' Query string: ' + cherrypy.request.query_string,
' Remote IP: ' + cherrypy.request.remote.ip
))
return ('%s\n'
'Add... | identifier_body |
__init__.py | , mkdir
from girder.utility._cache import cache, requestCache, rateLimitBuffer
__version__ = '2.5.0'
__license__ = 'Apache 2.0'
VERSION['apiVersion'] = __version__
_quiet = False
_originalStdOut = sys.stdout
_originalStdErr = sys.stderr
class | (object):
"""
Filter log records based on whether they are between a min and max level.
"""
def __init__(self, min, max):
self.minLevel = min
self.maxLevel = max
def filter(self, logRecord):
level = logRecord.levelno
return self.maxLevel >= level >= self.minLevel
c... | LogLevelFilter | identifier_name |
__init__.py | Filter log records based on whether they are between a min and max level.
"""
def __init__(self, min, max):
self.minLevel = min
self.maxLevel = max
def filter(self, logRecord):
level = logRecord.levelno
return self.maxLevel >= level >= self.minLevel
class LogFormatter(... | if color:
data = getattr(TerminalColor, color)(data)
_originalStdOut.write('%s\n' % data)
_originalStdOut.flush() | conditional_block | |
native.ts | import { EventEmitter } from 'events';
import { isElement } from 'toxic-predicate-functions';
import { IVideoKernel } from './base';
export type NativeVideoKernelConfig = {
src: string,
};
let tempCurrentTime: number = 0;
/**
* Native video kernel class for native video player
* It is much simpler than normal ker... | () {
tempCurrentTime = this.video.currentTime;
this.video.src = '';
this.video.removeAttribute('src');
}
public unload() {
// do nothing
}
}
| stopLoad | identifier_name |
native.ts | import { EventEmitter } from 'events';
import { isElement } from 'toxic-predicate-functions';
import { IVideoKernel } from './base';
export type NativeVideoKernelConfig = {
src: string,
};
let tempCurrentTime: number = 0;
/**
* Native video kernel class for native video player
* It is much simpler than normal ker... | this.config = config;
}
public attachMedia() {
// do nothing
}
public destroy() {
if (isElement(this.video)) {
this.stopLoad();
}
}
public load(src: string) {
this.video.setAttribute('src', src);
this.video.src = src;
}
public pause() {
return this.video.pause();
... | this.video = videoElement; | random_line_split |
native.ts | import { EventEmitter } from 'events';
import { isElement } from 'toxic-predicate-functions';
import { IVideoKernel } from './base';
export type NativeVideoKernelConfig = {
src: string,
};
let tempCurrentTime: number = 0;
/**
* Native video kernel class for native video player
* It is much simpler than normal ker... |
public pause() {
return this.video.pause();
}
public play() {
return this.video.play();
}
public refresh() {
this.video.src = this.config.src;
}
public seek(seconds: number) {
this.video.currentTime = seconds;
}
public startLoad(src: string) {
const currentTime = typeof this.... | {
this.video.setAttribute('src', src);
this.video.src = src;
} | identifier_body |
native.ts | import { EventEmitter } from 'events';
import { isElement } from 'toxic-predicate-functions';
import { IVideoKernel } from './base';
export type NativeVideoKernelConfig = {
src: string,
};
let tempCurrentTime: number = 0;
/**
* Native video kernel class for native video player
* It is much simpler than normal ker... |
}
public load(src: string) {
this.video.setAttribute('src', src);
this.video.src = src;
}
public pause() {
return this.video.pause();
}
public play() {
return this.video.play();
}
public refresh() {
this.video.src = this.config.src;
}
public seek(seconds: number) {
this... | {
this.stopLoad();
} | conditional_block |
dmrlink_config.py | Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
####################################################################... | FLAG_1 |= 1 << 5
if CONFIG['SYSTEMS'][section]['LOCAL']['XNL_CALL']:
FLAG_2 |= 1 << 7
if CONFIG['SYSTEMS'][section]['LOCAL']['XNL_CALL'] and CONFIG['SYSTEMS'][section]['LOCAL']['XNL_MASTER']:
FLAG_2 |= 1 << 6
... | if CONFIG['SYSTEMS'][section]['LOCAL']['CSBK_CALL']:
FLAG_1 |= 1 << 7
if CONFIG['SYSTEMS'][section]['LOCAL']['RCM']:
FLAG_1 |= 1 << 6
if CONFIG['SYSTEMS'][section]['LOCAL']['CON_APP']: | random_line_split |
dmrlink_config.py | Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
####################################################################... | (_config_file):
config = ConfigParser.ConfigParser()
if not config.read(_config_file):
sys.exit('Configuration file \''+_config_file+'\' is not a valid configuration file! Exiting...')
CONFIG = {}
CONFIG['GLOBAL'] = {}
CONFIG['REPORTS'] = {}
CONFIG['LOGGER'] = {}
CONFIG... | build_config | identifier_name |
dmrlink_config.py | Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
####################################################################... |
if CONFIG['SYSTEMS'][section]['LOCAL']['TS2_LINK']:
MODE_BYTE |= 1 << 1
else:
MODE_BYTE |= 1 << 0
CONFIG['SYSTEMS'][section]['LOCAL']['MODE'] = chr(MODE_BYTE)
# Construct and store the FLAGS field
i... | MODE_BYTE |= 1 << 2 | conditional_block |
dmrlink_config.py | Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
####################################################################... |
def build_config(_config_file):
config = ConfigParser.ConfigParser()
if not config.read(_config_file):
sys.exit('Configuration file \''+_config_file+'\' is not a valid configuration file! Exiting...')
CONFIG = {}
CONFIG['GLOBAL'] = {}
CONFIG['REPORTS'] = {}
CONFIG['LOGGER... | ipv4 = ''
ipv6 = ''
socket_info = getaddrinfo(_config, None, 0, 0, IPPROTO_UDP)
for item in socket_info:
if item[0] == 2:
ipv4 = item[4][0]
elif item[0] == 30:
ipv6 = item[4][0]
if ipv4:
return ipv4
if ipv6:
return ipv6
return 'in... | identifier_body |
authenticate.ts | import * as express from "express";
import * as rp from "request-promise";
import * as unifi from "@oddbit/unifi";
import * as nx from "@oddbit/nexudus";
import * as debug from "debug"
import * as app from "../app";
const debugLog = debug("unifi-nexudus-hotspot:router:authenticate");
export const router = express.Rou... |
// Check with Nexudus if the provided email/password is an active member
let nexudusCoworker;
const nxPublicApi = new nx.PublicApiClient(app.hotspot.get('nexudus_space_name'), email, password);
try {
nexudusCoworker = await nxPublicApi.getCoworker();
} catch (err) {
debugLog("Erro... | {
redirectUrl = app.hotspot.get("redirect_url");
} | conditional_block |
authenticate.ts | import * as express from "express";
import * as rp from "request-promise";
import * as unifi from "@oddbit/unifi";
import * as nx from "@oddbit/nexudus";
import * as debug from "debug"
import * as app from "../app";
const debugLog = debug("unifi-nexudus-hotspot:router:authenticate");
export const router = express.Rou... | try {
debugLog(`Logging out api user "${apiAdminUser}" from controller ...`);
await unifiController.logout();
} catch (err) {
if (err.statusCode >= 400) {
return next({
message: err.message,
status: err.statusCode
});
}
... | status: err.statusCode
});
}
// The logout response likes to throw a HTTP 302 "error". So we'll catch it and ignore it. | random_line_split |
seh.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Win64 SEH (see http://msdn.microsoft.com/en-us/library/1eyas8tf.aspx)
//!
//! On Windows (currently only on MSVC), the default exception handling
//! ... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.