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 |
|---|---|---|---|---|
clear_bits_geq.rs | use word::{Word, ToWord, UnsignedWord};
/// Clears all bits of `x` at position >= `bit`.
///
/// # Panics
///
/// If `bit >= bit_size()`.
///
/// # Intrinsics:
/// - BMI 2.0: bzhi.
///
/// # Examples
///
/// ```
/// use bitwise::word::*;
///
/// assert_eq!(0b1111_0010u8.clear_bits_geq(5u8), 0b0001_0010u8);
/// assert_... |
}
| {
clear_bits_geq(self, n)
} | identifier_body |
test_rule_001.py |
import os
import unittest
from vsg.rules import package
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_001_test_input.vhd'))
dIndentMap = utils.read_indent_file()
lExpected = []
lExpected.append('')
... | (unittest.TestCase):
def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
self.oFile.set_indent_map(dIndentMap)
def test_rule_001(self):
oRule = package.rule_001()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'package')
... | test_package_rule | identifier_name |
test_rule_001.py | import os
import unittest
from vsg.rules import package
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_001_test_input.vhd'))
|
class test_package_rule(unittest.TestCase):
def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
self.oFile.set_indent_map(dIndentMap)
def test_rule_001(self):
oRule = package.rule_001()
self.assertTrue(oRule)
self.assertEqual(oRule... | dIndentMap = utils.read_indent_file()
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sTestDir, 'rule_001_test_input.fixed.vhd'), lExpected) | random_line_split |
test_rule_001.py |
import os
import unittest
from vsg.rules import package
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_001_test_input.vhd'))
dIndentMap = utils.read_indent_file()
lExpected = []
lExpected.append('')
... |
def test_fix_rule_001(self):
oRule = package.rule_001()
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
| oRule = package.rule_001()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'package')
self.assertEqual(oRule.identifier, '001')
lExpected = [6]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations... | identifier_body |
binary-tree-tilt.py | # Time: O(n)
# Space: O(n)
# Given a binary tree, return the tilt of the whole tree.
#
# The tilt of a tree node is defined as the absolute difference
# between the sum of all left subtree node values and
# the sum of all right subtree node values. Null node has tilt 0.
#
# The tilt of the whole tree is defined as th... | (root, tilt):
if not root:
return 0, tilt
left, tilt = postOrderTraverse(root.left, tilt)
right, tilt = postOrderTraverse(root.right, tilt)
tilt += abs(left-right)
return left+right+root.val, tilt
return postOrderTraverse(root, 0)[1]
| postOrderTraverse | identifier_name |
binary-tree-tilt.py | # Time: O(n)
# Space: O(n)
# Given a binary tree, return the tilt of the whole tree.
#
# The tilt of a tree node is defined as the absolute difference
# between the sum of all left subtree node values and
# the sum of all right subtree node values. Null node has tilt 0.
#
# The tilt of the whole tree is defined as th... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def postOrderT... | # the range of 32-bit integer.
| random_line_split |
binary-tree-tilt.py | # Time: O(n)
# Space: O(n)
# Given a binary tree, return the tilt of the whole tree.
#
# The tilt of a tree node is defined as the absolute difference
# between the sum of all left subtree node values and
# the sum of all right subtree node values. Null node has tilt 0.
#
# The tilt of the whole tree is defined as th... |
return postOrderTraverse(root, 0)[1]
| if not root:
return 0, tilt
left, tilt = postOrderTraverse(root.left, tilt)
right, tilt = postOrderTraverse(root.right, tilt)
tilt += abs(left-right)
return left+right+root.val, tilt | identifier_body |
binary-tree-tilt.py | # Time: O(n)
# Space: O(n)
# Given a binary tree, return the tilt of the whole tree.
#
# The tilt of a tree node is defined as the absolute difference
# between the sum of all left subtree node values and
# the sum of all right subtree node values. Null node has tilt 0.
#
# The tilt of the whole tree is defined as th... |
left, tilt = postOrderTraverse(root.left, tilt)
right, tilt = postOrderTraverse(root.right, tilt)
tilt += abs(left-right)
return left+right+root.val, tilt
return postOrderTraverse(root, 0)[1]
| return 0, tilt | conditional_block |
test_uniform.py | import unittest
from chainer import cuda
from chainer import initializers
from chainer import testing
from chainer.testing import attr
import numpy
@testing.parameterize(*testing.product({
'target': [
initializers.Uniform,
initializers.LeCunUniform,
initializers.HeUniform,
initial... | initializer = self.target(scale=self.scale, dtype=self.dtype)
w = initializers.generate_array(initializer, self.shape, xp)
self.assertIs(cuda.get_array_module(w), xp)
self.assertTupleEqual(w.shape, self.shape)
self.assertEqual(w.dtype, self.dtype)
def test_shaped_initializer... | def test_initializer_gpu(self):
w = cuda.cupy.empty(self.shape, dtype=self.dtype)
self.check_initializer(w)
def check_shaped_initializer(self, xp): | random_line_split |
test_uniform.py | import unittest
from chainer import cuda
from chainer import initializers
from chainer import testing
from chainer.testing import attr
import numpy
@testing.parameterize(*testing.product({
'target': [
initializers.Uniform,
initializers.LeCunUniform,
initializers.HeUniform,
initial... |
def check_shaped_initializer(self, xp):
initializer = self.target(scale=self.scale, dtype=self.dtype)
w = initializers.generate_array(initializer, self.shape, xp)
self.assertIs(cuda.get_array_module(w), xp)
self.assertTupleEqual(w.shape, self.shape)
self.assertEqual(w.dtype... | w = cuda.cupy.empty(self.shape, dtype=self.dtype)
self.check_initializer(w) | identifier_body |
test_uniform.py | import unittest
from chainer import cuda
from chainer import initializers
from chainer import testing
from chainer.testing import attr
import numpy
@testing.parameterize(*testing.product({
'target': [
initializers.Uniform,
initializers.LeCunUniform,
initializers.HeUniform,
initial... | (unittest.TestCase):
scale = 0.1
def check_initializer(self, w):
initializer = self.target(scale=self.scale)
initializer(w)
self.assertTupleEqual(w.shape, self.shape)
self.assertEqual(w.dtype, self.dtype)
def test_initializer_cpu(self):
w = numpy.empty(self.shape, ... | TestUniform | identifier_name |
app.js | // We need to import the CSS so that webpack will load it.
// The MiniCssExtractPlugin is used to separate it out into
// its own CSS file.
import "../css/app.css"
// webpack automatically bundles all modules in your
// entry points. Those entry points can be configured
// in "webpack.config.js".
//
// Import deps wit... |
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {
hooks,
params: {_csrf_token: csrfToken},
/* metadata: {
click: (e, el) => {
return {
svelteID: el.closest('[phx-hook="svelte-component"]').id
}
... |
window.addEventListener('phx:hook:svelte', (e) => {
Object.values(liveSocket.main.viewHooks)
.filter(x => x.el.id == e.detail.svelteID)[0]._instance.serverEvent(e.detail)
}) | random_line_split |
alarm_mutex.rs | use std::io::prelude::*;
use std::time::{Instant, Duration};
use std::cmp::Ord;
use std::thread;
use std::sync::{Mutex, Arc};
struct Alarm {
seconds: Duration,
time: Instant,
message: String,
}
impl Alarm {
fn new(s: u64, m: String) -> Self {
let s = Duration::from_secs(s);
Alarm {
... | }
}
} | Ok(mut alarm_vec) => {
alarm_vec.push(Alarm::new(seconds, message));
alarm_vec.sort_by(|a, b| b.time.cmp(&a.time));
},
Err(e) => panic!(format!("failed to lock mutex: {}", e)), | random_line_split |
alarm_mutex.rs | use std::io::prelude::*;
use std::time::{Instant, Duration};
use std::cmp::Ord;
use std::thread;
use std::sync::{Mutex, Arc};
struct Alarm {
seconds: Duration,
time: Instant,
message: String,
}
impl Alarm {
fn new(s: u64, m: String) -> Self {
let s = Duration::from_secs(s);
Alarm {
... |
fn main() {
let alarms = Arc::new(Mutex::new(Vec::<Alarm>::new()));
start_alarm_thread(alarms.clone());
loop {
let mut line = String::new();
print!("Alarm> ");
match std::io::stdout().flush() {
Ok(()) => {},
Err(error) => panic!(format!("error wh... | {
thread::spawn(move || {
loop {
let alarm = alarm_list.lock().unwrap().pop();
match alarm {
Some(a) => {
let now = Instant::now();
if a.time <= now {
thread::yield_now();
} else {
... | identifier_body |
alarm_mutex.rs | use std::io::prelude::*;
use std::time::{Instant, Duration};
use std::cmp::Ord;
use std::thread;
use std::sync::{Mutex, Arc};
struct Alarm {
seconds: Duration,
time: Instant,
message: String,
}
impl Alarm {
fn | (s: u64, m: String) -> Self {
let s = Duration::from_secs(s);
Alarm {
seconds: s,
time: Instant::now() + s,
message: m,
}
}
}
type AlarmList = Arc<Mutex<Vec<Alarm>>>;
fn start_alarm_thread(alarm_list: AlarmList) {
thread::spawn(move || {
loop... | new | identifier_name |
classgr__file__source.js | [ "work", "classgr__file__source.html#a498f0bb7a704de43e3c1ffb61fed0d1d", null ],
[ "gr_make_file_source", "classgr__file__source.html#a36b4dde5a3a25390d460c7e6b4cdd1df", null ]
]; | var classgr__file__source =
[
[ "gr_file_source", "classgr__file__source.html#ad237a93ac0cdf390d52ecaf5ba47a01a", null ],
[ "~gr_file_source", "classgr__file__source.html#a6f48f666cf2ce07f32be02f08561ff24", null ],
[ "seek", "classgr__file__source.html#a0a206ac10dccf0e7b8faabd836a20846", null ], | random_line_split | |
sumAction.ts | module Plywood {
export class SumAction extends Action {
static fromJS(parameters: ActionJS): SumAction {
return new SumAction(Action.jsToValue(parameters));
}
constructor(parameters: ActionValue) {
super(parameters, dummyObject);
this._ensureAction("sum");
this._checkExpressionTy... |
var pattern: Expression[];
if (pattern = expression.getExpressionPattern('add')) {
return Expression.add(pattern.map(ex => preEx.sum(ex).distribute()));
}
if (pattern = expression.getExpressionPattern('subtract')) {
return Expression.subtract(pattern.map(ex => preEx.sum(ex).dis... | {
var value = expression.value;
if (value === 0) return Expression.ZERO;
return expression.multiply(preEx.count()).simplify();
} | conditional_block |
sumAction.ts | module Plywood {
export class | extends Action {
static fromJS(parameters: ActionJS): SumAction {
return new SumAction(Action.jsToValue(parameters));
}
constructor(parameters: ActionValue) {
super(parameters, dummyObject);
this._ensureAction("sum");
this._checkExpressionTypes('NUMBER');
}
public getOutpu... | SumAction | identifier_name |
sumAction.ts | module Plywood {
export class SumAction extends Action {
static fromJS(parameters: ActionJS): SumAction {
return new SumAction(Action.jsToValue(parameters));
}
constructor(parameters: ActionValue) {
super(parameters, dummyObject);
this._ensureAction("sum");
this._checkExpressionTy... |
Action.register(SumAction);
} | random_line_split | |
makemessages.py | """Jinja2's i18n functionality is not exactly the same as Django's.
In particular, the tags names and their syntax are different:
1. The Django ``trans`` tag is replaced by a _() global.
2. The Django ``blocktrans`` tag is called ``trans``.
(1) isn't an issue, since the whole ``makemessages`` process is based on
... | (makemessages.Command):
def handle(self, *args, **options):
old_endblock_re = trans_real.endblock_re
old_block_re = trans_real.block_re
# Extend the regular expressions that are used to detect
# translation blocks with an "OR jinja-syntax" clause.
trans_real.endblock_re = re... | Command | identifier_name |
makemessages.py | """Jinja2's i18n functionality is not exactly the same as Django's.
In particular, the tags names and their syntax are different:
1. The Django ``trans`` tag is replaced by a _() global.
2. The Django ``blocktrans`` tag is called ``trans``.
(1) isn't an issue, since the whole ``makemessages`` process is based on
... | old_endblock_re = trans_real.endblock_re
old_block_re = trans_real.block_re
# Extend the regular expressions that are used to detect
# translation blocks with an "OR jinja-syntax" clause.
trans_real.endblock_re = re.compile(
trans_real.endblock_re.pattern + '|' + r"""^\s*endt... | identifier_body | |
makemessages.py | """Jinja2's i18n functionality is not exactly the same as Django's.
In particular, the tags names and their syntax are different:
1. The Django ``trans`` tag is replaced by a _() global.
2. The Django ``blocktrans`` tag is called ``trans``.
(1) isn't an issue, since the whole ``makemessages`` process is based on
... | for once: It's simply a matter of extending two regular expressions.
Credit for the approach goes to:
http://stackoverflow.com/questions/2090717/getting-translation-strings-for-jinja2-templates-integrated-with-django-1-x
"""
import re
from django.core.management.commands import makemessages
from django.utils.translati... | We are currently doing that last thing. It turns out there we are lucky | random_line_split |
drums_rnn_create_dataset.py | # Copyright 2022 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
if __name__ == '__main__':
console_entry_point()
| tf.disable_v2_behavior()
tf.app.run(main) | identifier_body |
drums_rnn_create_dataset.py | # Copyright 2022 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | console_entry_point() | conditional_block | |
drums_rnn_create_dataset.py | # Copyright 2022 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | ():
tf.disable_v2_behavior()
tf.app.run(main)
if __name__ == '__main__':
console_entry_point()
| console_entry_point | identifier_name |
drums_rnn_create_dataset.py | # Copyright 2022 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
flags = tf.app.flags
FLAGS = tf.app.flags.FLAGS
flags.DEFINE_string('input', None, 'TFRecord to read NoteSequence protos from.')
flags.DEFINE_string(
'output_dir', None,
'Directory to write training and eval TFRecord files. The TFRecord files '
'are populated with SequenceExample protos.')
flags.DEFINE_flo... | from magenta.pipelines import pipeline
import tensorflow.compat.v1 as tf | random_line_split |
color.rs | //! Color
use image::Rgb;
use math::Vec3f;
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum Color {
Black,
White,
Red, | Cyan,
Magenta,
Yellow,
Azure,
Orange,
Gray,
Brightorange,
DarkGreen,
SkyBlue,
Brown,
DarkBrown,
CornflowerBlue,
Rgb(Vec3f),
}
impl Color {
pub fn vec3f(&self) -> Vec3f {
match *self {
Color::Black => Vec3f { x: 0.0, y: 0.0, z: 0.0},... | Green,
Blue, | random_line_split |
color.rs | //! Color
use image::Rgb;
use math::Vec3f;
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum Color {
Black,
White,
Red,
Green,
Blue,
Cyan,
Magenta,
Yellow,
Azure,
Orange,
Gray,
Brightorange,
DarkGreen,
SkyBlue,
Brown,
DarkBrown,
Cornflow... |
}
| {
Color::Black
} | identifier_body |
color.rs | //! Color
use image::Rgb;
use math::Vec3f;
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum | {
Black,
White,
Red,
Green,
Blue,
Cyan,
Magenta,
Yellow,
Azure,
Orange,
Gray,
Brightorange,
DarkGreen,
SkyBlue,
Brown,
DarkBrown,
CornflowerBlue,
Rgb(Vec3f),
}
impl Color {
pub fn vec3f(&self) -> Vec3f {
match *self {
Colo... | Color | identifier_name |
objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType2.ts | // Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those
// parameters pairwise identical, have identical type parameter constraints, identical number of parameters with identical kind(required,
// optional or rest) and types, and identical ... | }; // not a construct signature, function called new
function foo1b(x: B<Date>);
function foo1b(x: B<Date>); // error
function foo1b(x: any) { }
function foo1c(x: C<Date>);
function foo1c(x: C<Date>); // error
function foo1c(x: any) { }
function foo2(x: I<Date>);
function foo2(x: I<Date>); // error
function foo2(x:... | { return null; } | identifier_body |
objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType2.ts | // Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those
// parameters pairwise identical, have identical type parameter constraints, identical number of parameters with identical kind(required,
// optional or rest) and types, and identical ... |
interface I2 {
new<T extends Date>(x: T): RegExp;
}
var a: { new<T extends Date>(x: T): T }
var b = { new<T extends Date>(x: T) { return null; } }; // not a construct signature, function called new
function foo1b(x: B<Date>);
function foo1b(x: B<Date>); // error
function foo1b(x: any) { }
function foo1c(x: C<Da... | } | random_line_split |
objectTypesIdentityWithGenericConstructSignaturesDifferingByReturnType2.ts | // Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those
// parameters pairwise identical, have identical type parameter constraints, identical number of parameters with identical kind(required,
// optional or rest) and types, and identical ... | (x: any) { } | foo15 | identifier_name |
GameTime.py | import discord
from discord.ext import commands
import time
import datetime
import pytz
class GameTime(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def time(self, ctx):
"""Displays current game time."""
locationName = self.bo... |
def get_rawtime():
return datetime.datetime.now(pytz.timezone('UTC'))
def get_gametime():
months = [
"Hammer",
"Alturiak",
"Ches",
"Tarsakh",
"Mirtul",
"Kythorn",
"Flamerule",
"Eleasis",
"Eleint",
"Marpenoth",
"Uktar",... | def suffix(d):
return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th') | random_line_split |
GameTime.py | import discord
from discord.ext import commands
import time
import datetime
import pytz
class GameTime(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def time(self, ctx):
|
def suffix(d):
return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
def get_rawtime():
return datetime.datetime.now(pytz.timezone('UTC'))
def get_gametime():
months = [
"Hammer",
"Alturiak",
"Ches",
"Tarsakh",
"Mirtul",
"Kyth... | """Displays current game time."""
locationName = self.bot.db.get_val("ServerInfo", "")
print(type(locationName))
print(locationName['CityName'])
embed = discord.Embed(title="Current time in {}".format(locationName['CityName']),description=get_gametime())
await ctx.send(embed=embe... | identifier_body |
GameTime.py | import discord
from discord.ext import commands
import time
import datetime
import pytz
class GameTime(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def time(self, ctx):
"""Displays current game time."""
locationName = self.bo... | ():
months = [
"Hammer",
"Alturiak",
"Ches",
"Tarsakh",
"Mirtul",
"Kythorn",
"Flamerule",
"Eleasis",
"Eleint",
"Marpenoth",
"Uktar",
"Nightal"]
aDate = datetime(2020, 10, 18, tzinfo=pytz.timezone('UTC'))
bDate =... | get_gametime | identifier_name |
GameTime.py | import discord
from discord.ext import commands
import time
import datetime
import pytz
class GameTime(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def time(self, ctx):
"""Displays current game time."""
locationName = self.bo... |
else:
gametime_hour = gametime.hour-12 if gametime.hour > 12 else gametime.hour
time_decor = "PM" if gametime.hour > 12 else "AM"
gametime_minute = "0{}".format(gametime.minute) if gametime.minute < 10 else gametime.minute
return "{}:{} {} UTC | {}{} of {}".format(gametime_hour, gamet... | gametime_hour = 12
time_decor = "AM" | conditional_block |
renew_service.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from pyramid.view import view_config
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.view import BasicView
from pontus.form import Form... |
@view_config(
name='renewsellingticketsservice',
context=SellingTicketsService,
renderer='pontus:templates/views_templates/grid.pt',
)
class RenewSellingTicketsServiceViewMultipleView(MultipleView):
title = _('Renew the sellingtickets service')
name = 'renewsellingticketsservice'
viewid =... | title = _('Renew the sellingtickets service')
schema = select(SellingTicketsServiceSchema(factory=SellingTicketsService,
editable=True),
['title'])
behaviors = [RenewSellingTicketsService, Cancel]
formid = 'formrenewsellingticketsservice'
... | identifier_body |
renew_service.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from pyramid.view import view_config
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.view import BasicView
from pontus.form import Form... |
class RenewSellingTicketsServiceView(FormView):
title = _('Renew the sellingtickets service')
schema = select(SellingTicketsServiceSchema(factory=SellingTicketsService,
editable=True),
['title'])
behaviors = [RenewSellingTicketsService, C... | return result | random_line_split |
renew_service.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from pyramid.view import view_config
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.view import BasicView
from pontus.form import Form... | (BasicView):
title = 'Alert for renew'
name = 'alertforrenew'
template = 'lac:views/services_processes/selling_tickets_service/templates/alert_renew.pt'
def update(self):
result = {}
values = {'context': self.context}
body = self.content(args=values, template=self.template)['bod... | RenewSellingTicketsServiceViewStudyReport | identifier_name |
L0MSBuildLocation.ts | import ma = require('vsts-task-lib/mock-answer');
import tmrm = require('vsts-task-lib/mock-run');
import path = require('path');
let taskPath = path.join(__dirname, '..', 'xamarinios.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);
process.env['HOME']='/user/home'; //replace with mock of setVar... | tr.setInput('provProfileUuid', '');
tr.setInput('buildToolLocation', '/home/bin/msbuild');
// provide answers for task mock
let a: ma.TaskLibAnswers = <ma.TaskLibAnswers>{
"getVariable": {
"HOME": "/user/home"
},
"which": {
"nuget": "/home/bin/nuget"
},
"exec": {
"/home/bin/... | tr.setInput('runNugetRestore', 'true'); //boolean
tr.setInput('iosSigningIdentity', ''); | random_line_split |
input-errors.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// 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 agree... |
}
}
| {
this.errorText = changes.errorText.currentValue;
} | conditional_block |
input-errors.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// 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 agree... | */
ngOnInit(): void {
if (this.formControl) {
this.initErrorMessages();
this.errorKeys = Object.keys(this.errorMessages);
}
}
/**
* Initialize some common errors if they aren't set.
*/
protected initErrorMessages(): void {
this.errorMessag... | constructor(private translate: TranslateService) { }
/**
* Component is being initialized. | random_line_split |
input-errors.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// 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 agree... |
/**
* Component being changed.
*/
ngOnChanges(changes: { [name: string]: SimpleChange }): void {
if (changes.errorText) {
this.errorText = changes.errorText.currentValue;
}
}
}
| {
this.errorMessages = this.errorMessages || {};
this.errorMessages.required = this.errorMessages.required || this.translate.instant('core.required');
this.errorMessages.email = this.errorMessages.email || this.translate.instant('core.login.invalidemail');
this.errorMessages.date = this... | identifier_body |
input-errors.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// 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 agree... | (changes: { [name: string]: SimpleChange }): void {
if (changes.errorText) {
this.errorText = changes.errorText.currentValue;
}
}
}
| ngOnChanges | identifier_name |
test_annotation.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ():
x = relay.Var("x")
call = relay.annotation.on_device(x, "cuda")
assert isinstance(call, relay.Call)
assert len(call.args) == 1
assert call.args[0] == x
assert call.attrs.virtual_device.device_type_int == 2 # ie kDLCUDA
assert call.attrs.virtual_device.virtual_device_id == 0
assert c... | test_on_device_via_string | identifier_name |
test_annotation.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
def test_function_on_device():
x = relay.Var("x")
y = relay.Var("y")
f = relay.Function([x, y], relay.add(x, y))
func = relay.annotation.function_on_device(f, ["cpu", "cuda"], "cuda")
assert isinstance(func, relay.Function)
assert len(func.attrs["param_virtual_devices"]) == 2
assert func.... | x = relay.Var("x")
call = relay.annotation.on_device(x, "cuda", constrain_result=False, constrain_body=False)
assert call.attrs.virtual_device.device_type_int == -1 # ie kInvalidDeviceType
assert not call.attrs.constrain_body
assert not call.attrs.constrain_result | identifier_body |
test_annotation.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | assert len(call.args) == 1
assert call.args[0] == x
assert call.attrs.virtual_device.device_type_int == 2 # ie kDLCUDA
assert call.attrs.virtual_device.virtual_device_id == 0
assert call.attrs.virtual_device.target is None
assert call.attrs.virtual_device.memory_scope == ""
assert call.attr... | call = relay.annotation.on_device(x, "cuda")
assert isinstance(call, relay.Call) | random_line_split |
test_annotation.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | import sys
sys.exit(pytest.main([__file__] + sys.argv[1:])) | conditional_block | |
adapters.rs | ::sync::{Arc, RwLock};
use std::thread;
use std::io;
use chain::{self, ChainAdapter};
use core::core::{self, Output};
use core::core::hash::{Hash, Hashed};
use core::core::target::Difficulty;
use p2p::{self, NetAdapter, Server, PeerStore, PeerData, State};
use pool;
use secp::pedersen::Commitment;
use util::OneTime;
u... | (&self, peer_addrs: Vec<SocketAddr>) -> Result<(), p2p::Error> {
debug!("Received {} peer addrs, saving.", peer_addrs.len());
for pa in peer_addrs {
if let Ok(e) = self.peer_store.exists_peer(pa) {
if e {
continue;
}
}
let peer = PeerData {
addr: pa,
capabilities: p2p::UNKNOWN,
use... | peer_addrs_received | identifier_name |
adapters.rs | ::sync::{Arc, RwLock};
use std::thread;
use std::io;
use chain::{self, ChainAdapter};
use core::core::{self, Output};
use core::core::hash::{Hash, Hashed};
use core::core::target::Difficulty;
use p2p::{self, NetAdapter, Server, PeerStore, PeerData, State};
use pool;
use secp::pedersen::Commitment;
use util::OneTime;
u... | peer_store: Arc<PeerStore>,
tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,
syncer: OneTime<Arc<sync::Syncer>>,
}
impl NetAdapter for NetToChainAdapter {
fn total_difficulty(&self) -> Difficulty {
self.chain.total_difficulty()
}
fn transaction_received(&self, tx: core::Transaction) -> Result... | random_line_split | |
adapters.rs | sync::{Arc, RwLock};
use std::thread;
use std::io;
use chain::{self, ChainAdapter};
use core::core::{self, Output};
use core::core::hash::{Hash, Hashed};
use core::core::target::Difficulty;
use p2p::{self, NetAdapter, Server, PeerStore, PeerData, State};
use pool;
use secp::pedersen::Commitment;
use util::OneTime;
use... |
fn headers_received(&self, bhs: Vec<core::BlockHeader>) -> Result<(), p2p::Error> {
// try to add each header to our header chain
let mut added_hs = vec![];
for bh in bhs {
let res = self.chain.process_block_header(&bh, self.chain_opts());
match res {
Ok(_) => {
added_hs.push(bh.hash());
}
... | {
let bhash = b.hash();
debug!("Received block {} from network, going to process.", bhash);
// pushing the new block through the chain pipeline
let res = self.chain.process_block(b, self.chain_opts());
if let Err(e) = res {
debug!("Block {} refused by chain: {:?}", bhash, e);
return Err(p2p::Erro... | identifier_body |
px_mkfw.py | #!/usr/bin/env python
############################################################################
#
# Copyright (C) 2012, 2013 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... | parser.add_argument("--prototype", action="store", help="read a prototype description from a file")
parser.add_argument("--board_id", action="store", help="set the board ID required")
parser.add_argument("--board_revision", action="store", help="set the board revision required")
parser.add_argument("--version", action=... |
# Parse commandline
parser = argparse.ArgumentParser(description="Firmware generator for the PX autopilot system.") | random_line_split |
px_mkfw.py | #!/usr/bin/env python
############################################################################
#
# Copyright (C) 2012, 2013 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... | ():
proto = {}
proto['magic'] = "PX4FWv1"
proto['board_id'] = 0
proto['board_revision'] = 0
proto['version'] = ""
proto['summary'] = ""
proto['description'] = ""
proto['git_identity'] = ""
proto['build_time'] = 0
proto['image'] = bytes()
proto['image_size'] = 0
return proto
# Parse commandline
parser = a... | mkdesc | identifier_name |
px_mkfw.py | #!/usr/bin/env python
############################################################################
#
# Copyright (C) 2012, 2013 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... |
# Parse commandline
parser = argparse.ArgumentParser(description="Firmware generator for the PX autopilot system.")
parser.add_argument("--prototype", action="store", help="read a prototype description from a file")
parser.add_argument("--board_id", action="store", help="set the board ID required")
parser.add_argumen... | proto = {}
proto['magic'] = "PX4FWv1"
proto['board_id'] = 0
proto['board_revision'] = 0
proto['version'] = ""
proto['summary'] = ""
proto['description'] = ""
proto['git_identity'] = ""
proto['build_time'] = 0
proto['image'] = bytes()
proto['image_size'] = 0
return proto | identifier_body |
px_mkfw.py | #!/usr/bin/env python
############################################################################
#
# Copyright (C) 2012, 2013 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... |
if args.description != None:
desc['description'] = str(args.description)
if args.git_identity != None:
cmd = " ".join(["git", "--git-dir", args.git_identity + "/.git", "describe", "--always", "--dirty"])
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
desc['git_identity'] = str(p.read().strip(... | desc['summary'] = str(args.summary) | conditional_block |
account_move.py | from odoo import models, fields
class | (models.Model):
_inherit = "account.move"
def _get_tax_factor(self):
tax_factor = super()._get_tax_factor()
doc_letter = self.l10n_latam_document_type_id.l10n_ar_letter
# if we receive B invoices, then we take out 21 of vat
# this use of case if when company is except on vat for... | AccountMove | identifier_name |
account_move.py | from odoo import models, fields
class AccountMove(models.Model):
_inherit = "account.move"
def _get_tax_factor(self):
tax_factor = super()._get_tax_factor()
doc_letter = self.l10n_latam_document_type_id.l10n_ar_letter
# if we receive B invoices, then we take out 21 of vat
# th... | inherit = "account.move.line"
def _compute_price(self):
# ver nota en get_taxes_values
invoice = self.move_id
invoice_date = invoice.invoice_date or fields.Date.context_today(self)
# hacemos try porque al llamarse desde acciones de servidor da error
try:
self.env... | identifier_body | |
account_move.py | from odoo import models, fields
class AccountMove(models.Model):
_inherit = "account.move"
def _get_tax_factor(self):
tax_factor = super()._get_tax_factor()
doc_letter = self.l10n_latam_document_type_id.l10n_ar_letter
# if we receive B invoices, then we take out 21 of vat
# th... | """
invoice_date = self.invoice_date or fields.Date.context_today(self)
# hacemos try porque al llamarse desde acciones de servidor da error
try:
self.env.context.invoice_date = invoice_date
self.env.context.invoice_company = self.company_id
except Excepti... | impuesto con código python (por ej. para ARBA).
Aparentemente no se puede cambiar el contexto a cosas que se llaman
desde un onchange (ver https://github.com/odoo/odoo/issues/7472)
entonces usamos este artilugio | random_line_split |
account_move.py | from odoo import models, fields
class AccountMove(models.Model):
_inherit = "account.move"
def _get_tax_factor(self):
tax_factor = super()._get_tax_factor()
doc_letter = self.l10n_latam_document_type_id.l10n_ar_letter
# if we receive B invoices, then we take out 21 of vat
# th... |
return tax_factor
def get_taxes_values(self):
"""
Hacemos esto para disponer de fecha de factura y cia para calcular
impuesto con código python (por ej. para ARBA).
Aparentemente no se puede cambiar el contexto a cosas que se llaman
desde un onchange (ver https://gi... | tax_factor = 1.0 / 1.21 | conditional_block |
DefaultObjects.js | /*jslint browser: true, sloppy: true */
/*global UNIVERSE, THREE */
/**
A set of default objects to add to the Universe Object Library
@constructor
@param {UNIVERSE.Universe} universe - A Universe instance to use the default objects in | universe.setObjectInLibrary("default_ground_object_geometry", new THREE.SphereGeometry(200, 20, 10));
universe.setObjectInLibrary("default_ground_object_material", new THREE.MeshBasicMaterial({
color : 0xCC0000
}));
universe.setObjectInLibrary("default_ground_track_material", new THREE.MeshBasi... | */
UNIVERSE.DefaultObjects = function (universe) { | random_line_split |
batalha.py | import pokemon
import random
import re
import display
class Batalha:
def __init__(self, pokeList = []):
self.display = display.Display()
self.pkmn = []
if (len(pokeList) == 0):
self.pkmn.append(pokemon.Pokemon())
self.pkmn.append(pokemon.Pokemon())
else:
self.pkmn = pokeList
self.turno = self.Ini... | arquivo.close()
return tab
def StabBonus(self, atk):
atacando = self.pkmn[self.turno]
if (atk.getTyp() == atacando.getTyp1() or atk.getTyp() == atacando.getTyp2()): return 1.5
return 1
def CriticalHit(self):
atacando = self.pkmn[self.turno]
critical = (atacando.getSpd()/512);
temp = random.uniform(0... | tab[i] = [float(j) for j in tab[i]]
i+= 1
line = arquivo.readline() | random_line_split |
batalha.py | import pokemon
import random
import re
import display
class Batalha:
def __init__(self, pokeList = []):
self.display = display.Display()
self.pkmn = []
if (len(pokeList) == 0):
self.pkmn.append(pokemon.Pokemon())
self.pkmn.append(pokemon.Pokemon())
else:
self.pkmn = pokeList
self.turno = self.Ini... |
def isOver(self):
return not (self.pkmn[0].isAlive() and self.pkmn[1].isAlive())
def showResults(self):
if (not self.pkmn[0].isAlive() and not self.pkmn[1].isAlive()):
self.display.showTie()
elif (self.pkmn[0].isAlive()):
self.display.showWinner(self.pkmn[0])
else: self.display.showWinner(self.pkmn... | x = random.uniform(0, 1)
return x <= atk.getAcu() * 0.01 | identifier_body |
batalha.py | import pokemon
import random
import re
import display
class Batalha:
def __init__(self, pokeList = []):
self.display = display.Display()
self.pkmn = []
if (len(pokeList) == 0):
self.pkmn.append(pokemon.Pokemon())
self.pkmn.append(pokemon.Pokemon())
else:
self.pkmn = pokeList
self.turno = self.Ini... | (self, atk):
x = random.uniform(0, 1)
return x <= atk.getAcu() * 0.01
def isOver(self):
return not (self.pkmn[0].isAlive() and self.pkmn[1].isAlive())
def showResults(self):
if (not self.pkmn[0].isAlive() and not self.pkmn[1].isAlive()):
self.display.showTie()
elif (self.pkmn[0].isAlive()):
self.di... | isHit | identifier_name |
batalha.py | import pokemon
import random
import re
import display
class Batalha:
def __init__(self, pokeList = []):
self.display = display.Display()
self.pkmn = []
if (len(pokeList) == 0):
self.pkmn.append(pokemon.Pokemon())
self.pkmn.append(pokemon.Pokemon())
else:
self.pkmn = pokeList
self.turno = self.Ini... |
else: self.display.atkInvalido()
def EscolheAtaqueInteligente(self):
#Para maximizar o dano, deve-se maximizar a Base X Tipo X STAB
true = 1
tab = self.TypeChart('tabela.txt')
atacando = self.pkmn[self.turno]
defendendo = self.pkmn[(self.turno + 1) % 2]
BaseXType = 0
lista = atacando.getAtkList()... | if (atacando.getAtks(number - 1).ppCheck()):
return number - 1
self.display.ppInsuficiente()
escolheu = 0 | conditional_block |
extension_waypoint_generator.py | """Implements the WaypointGenerator interface. Returns waypoints from a KML
file. All WaypointGenerator implementations should have two methods:
get_current_waypoint(self, x_m, y_m) -> (float, float)
get_raw_waypoint(self) -> (float, float)
reached(self, x_m, y_m) -> bool
next(self)
done(self) -> bo... | return self._extension_waypoint
def next(self):
"""Goes to the next waypoint."""
super(ExtensionWaypointGenerator, self).next()
self._extension_waypoint = self._get_extended_waypoint()
def reached(self, x_m, y_m):
"""Returns True if the current waypoint has been reached... | super(ExtensionWaypointGenerator, self).__init__(waypoints)
self._extension_waypoint = waypoints[0]
def get_current_waypoint(self, x_m, y_m):
"""Returns the current waypoint as projected BEYOND_M past.""" | random_line_split |
extension_waypoint_generator.py | """Implements the WaypointGenerator interface. Returns waypoints from a KML
file. All WaypointGenerator implementations should have two methods:
get_current_waypoint(self, x_m, y_m) -> (float, float)
get_raw_waypoint(self) -> (float, float)
reached(self, x_m, y_m) -> bool
next(self)
done(self) -> bo... | (self, x_m, y_m):
"""Returns True if the current waypoint has been reached."""
if super(ExtensionWaypointGenerator, self).reached(x_m, y_m):
return True
# Because the car is trying to go for the extension, the car might
# pass the actual waypoint and keep on driving, so check... | reached | identifier_name |
extension_waypoint_generator.py | """Implements the WaypointGenerator interface. Returns waypoints from a KML
file. All WaypointGenerator implementations should have two methods:
get_current_waypoint(self, x_m, y_m) -> (float, float)
get_raw_waypoint(self) -> (float, float)
reached(self, x_m, y_m) -> bool
next(self)
done(self) -> bo... |
# Because the car is trying to go for the extension, the car might
# pass the actual waypoint and keep on driving, so check if it's close
# to the extension as well
distance_m_2 = (
(x_m - self._extension_waypoint[0]) ** 2
+ (y_m - self._extension_waypoint[1]) **... | return True | conditional_block |
extension_waypoint_generator.py | """Implements the WaypointGenerator interface. Returns waypoints from a KML
file. All WaypointGenerator implementations should have two methods:
get_current_waypoint(self, x_m, y_m) -> (float, float)
get_raw_waypoint(self) -> (float, float)
reached(self, x_m, y_m) -> bool
next(self)
done(self) -> bo... |
def get_current_waypoint(self, x_m, y_m):
"""Returns the current waypoint as projected BEYOND_M past."""
return self._extension_waypoint
def next(self):
"""Goes to the next waypoint."""
super(ExtensionWaypointGenerator, self).next()
self._extension_waypoint = self._get... | super(ExtensionWaypointGenerator, self).__init__(waypoints)
self._extension_waypoint = waypoints[0] | identifier_body |
shortcuts.py | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.template imp... | raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
return obj_list
def resolve_url(to, *args, **kwargs):
"""
Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.... | "First argument to get_list_or_404() must be a Model, Manager, or "
"QuerySet, not '%s'." % klass__name
)
obj_list = list(queryset.filter(*args, **kwargs))
if not obj_list: | random_line_split |
shortcuts.py | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.template imp... | (klass, *args, **kwargs):
"""
Use filter() to return a list of objects, or raise a Http404 exception if
the list is empty.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the filter() query.
"""
queryset = _get_queryset(klass)
... | get_list_or_404 | identifier_name |
shortcuts.py | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.template imp... |
def _get_queryset(klass):
"""
Return a QuerySet or a Manager.
Duck typing in action: any class with a `get()` method (for
get_object_or_404) or a `filter()` method (for get_list_or_404) might do
the job.
"""
# If it is a model class or anything else with ._default_manager
if hasattr(k... | """
Return an HttpResponseRedirect to the appropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve the name.
... | identifier_body |
shortcuts.py | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.template imp... |
# Next try a reverse URL resolution.
try:
return reverse(to, args=args, kwargs=kwargs)
except NoReverseMatch:
# If this is a callable, re-raise.
if callable(to):
raise
# If this doesn't "feel" like a URL, re-raise.
if '/' not in to and '.' not in to:
... | return to | conditional_block |
Errors.py | #=======================================================================
#
# Python Lexical Analyser
#
# Exception classes
#
#=======================================================================
import exceptions
class PlexError(exceptions.Exception):
message = ""
class PlexTypeError(PlexError, TypeError):
... |
class InvalidRegex(PlexError):
pass
class InvalidToken(PlexError):
def __init__(self, token_number, message):
PlexError.__init__(self, "Token number %d: %s" % (token_number, message))
class InvalidScanner(PlexError):
pass
class AmbiguousAction(PlexError):
message = "Two tokens with different actions can mat... | pass | identifier_body |
Errors.py | #=======================================================================
#
# Python Lexical Analyser
#
# Exception classes
#
#=======================================================================
import exceptions
|
class PlexValueError(PlexError, ValueError):
pass
class InvalidRegex(PlexError):
pass
class InvalidToken(PlexError):
def __init__(self, token_number, message):
PlexError.__init__(self, "Token number %d: %s" % (token_number, message))
class InvalidScanner(PlexError):
pass
class AmbiguousAction(PlexError):
m... | class PlexError(exceptions.Exception):
message = ""
class PlexTypeError(PlexError, TypeError):
pass | random_line_split |
Errors.py | #=======================================================================
#
# Python Lexical Analyser
#
# Exception classes
#
#=======================================================================
import exceptions
class PlexError(exceptions.Exception):
message = ""
class PlexTypeError(PlexError, TypeError):
... | (PlexError, ValueError):
pass
class InvalidRegex(PlexError):
pass
class InvalidToken(PlexError):
def __init__(self, token_number, message):
PlexError.__init__(self, "Token number %d: %s" % (token_number, message))
class InvalidScanner(PlexError):
pass
class AmbiguousAction(PlexError):
message = "Two tokens ... | PlexValueError | identifier_name |
image.rs | use std::io::{ Result, Write};
use core::color::Color;
/// Types that can be converted to a [u8; 4] RGBA.
trait ToRGBA255 {
fn rgba255(&self) -> [u8; 4];
}
impl ToRGBA255 for Color {
fn rgba255(&self) -> [u8; 4] {
let f = |x: f32| (x * 255.0) as u8;
[ f(self.channels()[0]),
f(self.c... | Ok(())
}
pub fn set(&mut self, x: usize, y: usize, c: &Color) {
self._data[x + (y * self._width)] = *c;
}
}
// ------------------------
// Spectrum
// ------------------------ | random_line_split | |
image.rs | use std::io::{ Result, Write};
use core::color::Color;
/// Types that can be converted to a [u8; 4] RGBA.
trait ToRGBA255 {
fn rgba255(&self) -> [u8; 4];
}
impl ToRGBA255 for Color {
fn rgba255(&self) -> [u8; 4] {
let f = |x: f32| (x * 255.0) as u8;
[ f(self.channels()[0]),
f(self.c... | <T>(&self, out: &mut T) -> Result<()>
where T: Write {
//
try!(write!(out, "P6 {} {} 255 ", self._width, self._height));
for color in &self._data {
let channels = &color.rgba255()[0..3];
try!(out.write_all(&channels));
}
Ok(())
}
pub fn se... | writeppm | identifier_name |
factor_int.rs | // http://rosettacode.org/wiki/Factors_of_an_integer
fn | () {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
}
/// Compute the factors of an integer
/// This method uses a simple check on each value between 1 and sqrt(x) to find
/// pairs of factors
fn fac... | main | identifier_name |
factor_int.rs | // http://rosettacode.org/wiki/Factors_of_an_integer
fn main() {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
} | /// Compute the factors of an integer
/// This method uses a simple check on each value between 1 and sqrt(x) to find
/// pairs of factors
fn factor_int(x: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new();
let bound: i32 = (x as f64).sqrt().floor() as i32;
for i in 1i32..bound {
if x % i ... | random_line_split | |
factor_int.rs | // http://rosettacode.org/wiki/Factors_of_an_integer
fn main() {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
}
/// Compute the factors of an integer
/// This method uses a simple check on each va... |
}
factors
}
#[test]
fn test() {
let result = factor_int(78i32);
assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]);
}
| {
factors.push(i);
factors.push(x / i);
} | conditional_block |
factor_int.rs | // http://rosettacode.org/wiki/Factors_of_an_integer
fn main() |
/// Compute the factors of an integer
/// This method uses a simple check on each value between 1 and sqrt(x) to find
/// pairs of factors
fn factor_int(x: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new();
let bound: i32 = (x as f64).sqrt().floor() as i32;
for i in 1i32..bound {
if x % ... | {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
} | identifier_body |
origin.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::sync::Arc;
use url::{Host, Url};
use url::Origin as UrlOrigin;
/// A representation of an [origin](https... | (&self) -> Origin {
Origin {
inner: self.inner.clone(),
}
}
}
| alias | identifier_name |
origin.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::sync::Arc;
use url::{Host, Url};
use url::Origin as UrlOrigin;
/// A representation of an [origin](https... |
/// https://html.spec.whatwg.org/multipage/#same-origin
pub fn same_origin(&self, other: &Origin) -> bool {
self.inner == other.inner
}
pub fn copy(&self) -> Origin {
Origin {
inner: Arc::new((*self.inner).clone()),
}
}
pub fn alias(&self) -> Origin {
... | {
match *self.inner {
UrlOrigin::Tuple(_, ref host, _) => Some(host),
UrlOrigin::Opaque(..) => None,
}
} | identifier_body |
origin.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::sync::Arc;
use url::{Host, Url};
use url::Origin as UrlOrigin;
/// A representation of an [origin](https... | } | } | random_line_split |
cad2xls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## @copyright
# Software License Agreement (BSD License)
#
# Copyright (c) 2017, Jorge De La Cruz, Carmen Castano.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the followi... | print >>f, self.part.Name+"\t"+self.part.Label
self.i += 1
f.close()
print('The txt file has been created successfully!')
if __name__ == '__main__':
data = GetParameters()
data.loadCAD()
data.writeTxt()
| def __init__(self):
self.filePath = '/home/jdelacruz/Downloads/KonzeptB_lang090715.stp'
def loadCAD(self):
print('Starting to load the CAD file, please be patient!...')
Import.open(self.filePath)
self.handler = App.ActiveDocument
self.parts = self.handler.Objects
pri... | identifier_body |
cad2xls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## @copyright
# Software License Agreement (BSD License)
#
# Copyright (c) 2017, Jorge De La Cruz, Carmen Castano.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the followi... | data = GetParameters()
data.loadCAD()
data.writeTxt() | conditional_block | |
cad2xls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## @copyright
# Software License Agreement (BSD License)
#
# Copyright (c) 2017, Jorge De La Cruz, Carmen Castano.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the followi... | (self):
print('Starting to load the CAD file, please be patient!...')
Import.open(self.filePath)
self.handler = App.ActiveDocument
self.parts = self.handler.Objects
print('CAD model loaded!')
def writeTxt(self):
f = open('data.txt','a')
print >>f, 'Name \t La... | loadCAD | identifier_name |
cad2xls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## @copyright
# Software License Agreement (BSD License)
#
# Copyright (c) 2017, Jorge De La Cruz, Carmen Castano.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the followi... | self.names[self.i] = self.part.Name
self.labels[self.i] = self.part.Label
print >>f, self.part.Name+"\t"+self.part.Label
self.i += 1
f.close()
print('The txt file has been created successfully!')
if __name__ == '__main__':
data = GetParameters()
... | for self.part in self.parts: | random_line_split |
reforms.py | # -*- coding: utf-8 -*-
"""Reforms controller"""
import collections
from .. import contexts, conv, model, wsgihelpers
@wsgihelpers.wsgify
def | (req):
ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
assert req.method == 'GET', req.method
params = req.GET
inputs = dict(
context = params.get('context'),
)
data, errors = conv.pipe(
conv.struct(
dict(
... | api1_reforms | identifier_name |
reforms.py | # -*- coding: utf-8 -*-
"""Reforms controller"""
import collections
from .. import contexts, conv, model, wsgihelpers
@wsgihelpers.wsgify
def api1_reforms(req):
ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
assert req.method == 'GET', req.method
params =... | apiVersion = 1,
context = inputs.get('context'),
error = collections.OrderedDict(sorted(dict(
code = 400, # Bad Request
errors = [conv.jsonify_value(errors)],
message = ctx._(u'Bad parameters in request'),
... | random_line_split | |
reforms.py | # -*- coding: utf-8 -*-
"""Reforms controller"""
import collections
from .. import contexts, conv, model, wsgihelpers
@wsgihelpers.wsgify
def api1_reforms(req):
ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
assert req.method == 'GET', req.method
params =... |
build_reform_function_by_key = model.build_reform_function_by_key
declared_reforms_key = build_reform_function_by_key.keys() \
if build_reform_function_by_key is not None \
else None
reforms = collections.OrderedDict(sorted({
reform_key: reform.name
for reform_key, reform i... | return wsgihelpers.respond_json(ctx,
collections.OrderedDict(sorted(dict(
apiVersion = 1,
context = inputs.get('context'),
error = collections.OrderedDict(sorted(dict(
code = 400, # Bad Request
errors = [conv.jsonify_va... | conditional_block |
reforms.py | # -*- coding: utf-8 -*-
"""Reforms controller"""
import collections
from .. import contexts, conv, model, wsgihelpers
@wsgihelpers.wsgify
def api1_reforms(req):
| context = inputs.get('context'),
error = collections.OrderedDict(sorted(dict(
code = 400, # Bad Request
errors = [conv.jsonify_value(errors)],
message = ctx._(u'Bad parameters in request'),
).iteritems())),
... | ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
assert req.method == 'GET', req.method
params = req.GET
inputs = dict(
context = params.get('context'),
)
data, errors = conv.pipe(
conv.struct(
dict(
context ... | identifier_body |
display_bernoulli_model.py | from __future__ import division
import numpy as np
import argparse
import matplotlib.pyplot as plt
from matplotlib.colors import colorConverter
from mpl_toolkits.axes_grid1 import ImageGrid
import matplotlib.cm as cm
from amitgroup.stats import bernoullimm
def | (args):
means = np.load('%s_means.npy' % args.save_path)
S_clusters = np.load('%s_S_clusters.npy' % args.save_path)
means = means.reshape( *( S_clusters.shape + ( int(means.size/S_clusters.size),)))
if True:
plt.close('all')
fig = plt.figure(1, (6, 6))
grid = ImageGrid(fig... | main | identifier_name |
display_bernoulli_model.py | from __future__ import division
import numpy as np
import argparse
import matplotlib.pyplot as plt
from matplotlib.colors import colorConverter
from mpl_toolkits.axes_grid1 import ImageGrid
import matplotlib.cm as cm
from amitgroup.stats import bernoullimm
def main(args):
means = np.load('%s_means.npy' % args.sav... |
except:
import pdb; pdb.set_trace()
plt.savefig('%s' % args.display_bernoulli_parts
,bbox_inches='tight')
if __name__ == "__main__":
parser = argparse.ArgumentParser("""Clustering and output for... | a.toggle(all=False) | conditional_block |
display_bernoulli_model.py | from __future__ import division
import numpy as np
import argparse
import matplotlib.pyplot as plt
from matplotlib.colors import colorConverter
from mpl_toolkits.axes_grid1 import ImageGrid
import matplotlib.cm as cm
from amitgroup.stats import bernoullimm
def main(args):
| grid[i*ncols].spines['left'].set_color('red')
grid[i*ncols].spines['right'].set_color('red')
for a in grid[i*ncols].axis.values():
a.toggle(all=False)
except:
import pdb; pdb.set_trace()
for j in xrange(ncols-1):... | means = np.load('%s_means.npy' % args.save_path)
S_clusters = np.load('%s_S_clusters.npy' % args.save_path)
means = means.reshape( *( S_clusters.shape + ( int(means.size/S_clusters.size),)))
if True:
plt.close('all')
fig = plt.figure(1, (6, 6))
grid = ImageGrid(fig, 111, # sim... | identifier_body |
display_bernoulli_model.py | from __future__ import division
import numpy as np
import argparse
import matplotlib.pyplot as plt
from matplotlib.colors import colorConverter
from mpl_toolkits.axes_grid1 import ImageGrid
import matplotlib.cm as cm
from amitgroup.stats import bernoullimm
def main(args):
means = np.load('%s_means.npy' % args.sav... | ,bbox_inches='tight')
if __name__ == "__main__":
parser = argparse.ArgumentParser("""Clustering and output for bernoulli data with paired spectrum data""")
parser.add_argument('--save_path',type=str,default='',help='path to save the trained models to')
parser.add... |
plt.savefig('%s' % args.display_bernoulli_parts | random_line_split |
chksumtree.py | #!/usr/bin/python
import sys
import pickle
import os
import hashlib
import pprint
import time
from optparse import OptionParser
VERSION=1.0
def parseOptions():
usage = """
%prog [options]\n
Scrub a given directory by calculating the md5 hash of every file and compare
it with... |
def _checkfile(self, in_file, options):
'''
Add new files, check existing files, and update modified files.
'''
in_file_cksum = {'stat': os.stat(in_file),
'md5': md5sum(in_file, options.read_buffer)}
if options.verbose: print in_... | if in_file.startswith(self.path):
rel_path = in_file[len(self.path):].lstrip("/")
else:
rel_path = in_file.lstrip("/")
return rel_path | identifier_body |
chksumtree.py | #!/usr/bin/python
import sys
import pickle
import os
import hashlib
import pprint
import time
from optparse import OptionParser
VERSION=1.0
def parseOptions():
usage = """
%prog [options]\n
Scrub a given directory by calculating the md5 hash of every file and compare
it with... | if in_file.startswith(self.path):
rel_path = in_file[len(self.path):].lstrip("/")
else:
rel_path = in_file.lstrip("/")
return rel_path
def _checkfile(self, in_file, options):
'''
Add new files, check existing files, and update modifie... | random_line_split | |
chksumtree.py | #!/usr/bin/python
import sys
import pickle
import os
import hashlib
import pprint
import time
from optparse import OptionParser
VERSION=1.0
def parseOptions():
usage = """
%prog [options]\n
Scrub a given directory by calculating the md5 hash of every file and compare
it with... | ():
options = parseOptions()
pprint.pprint(options)
chksums = Treechksum(options,
options.data_file,
options.path)
chksums.compute(options)
if not options.dryrun: chksums.save()
if __name__ == '__main__':
main()
| main | identifier_name |
chksumtree.py | #!/usr/bin/python
import sys
import pickle
import os
import hashlib
import pprint
import time
from optparse import OptionParser
VERSION=1.0
def parseOptions():
usage = """
%prog [options]\n
Scrub a given directory by calculating the md5 hash of every file and compare
it with... |
return rel_path
def _checkfile(self, in_file, options):
'''
Add new files, check existing files, and update modified files.
'''
in_file_cksum = {'stat': os.stat(in_file),
'md5': md5sum(in_file, options.read_buffer)}
if op... | rel_path = in_file.lstrip("/") | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.