file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
InfrastructureAugmenter.js | const fs = require('fs-promise');
const turf = require('turf');
const _ = require('underscore');
const complexify = require('geojson-tools').complexify;
class InfrastructureAugmenter {
constructor(callback) {
this.aggregatedData = null;
this.buildingsGeo = null;
this.landingsGeo = null;
this.landingsGeoByI... | hop.infrastructure.landings.push(c.end);
hop.infrastructure.cable = c.cable;
// console.log(`${c.cable.properties.name} START: ${c.distStart} END: ${c.distEnd} SUM: ${c.distSum}`);
// cables.forEach(c => {
// if (c) {
// console.log(`${c.cable.properties.name} START: ${c.distStart} EN... | random_line_split | |
InfrastructureAugmenter.js | const fs = require('fs-promise');
const turf = require('turf');
const _ = require('underscore');
const complexify = require('geojson-tools').complexify;
class InfrastructureAugmenter {
constructor(callback) {
this.aggregatedData = null;
this.buildingsGeo = null;
this.landingsGeo = null;
this.landingsGeoByI... |
return _.uniq(_.sortBy(cables, cable => cable.distSum), cable => cable.cable.properties.id);
}
function getCableIds(cables) {
let ids = [];
cables.forEach(({cable_id}) => ids.push(parseInt(cable_id)));
return ids;
}
}
}
}
_crossesOcean(points) {
let inside = false;
let ... | {
// get that landing point's id
let cableId = landingNearHop[i].feature.properties.cable_id;
// For each landing point that cable has
for (let k = 0; k < self.aggregatedData.cable[cableId].landing_points.length; k++) {
let landing = self.aggregatedData.cable[cableId].landing_poin... | conditional_block |
InfrastructureAugmenter.js | const fs = require('fs-promise');
const turf = require('turf');
const _ = require('underscore');
const complexify = require('geojson-tools').complexify;
class InfrastructureAugmenter {
constructor(callback) {
this.aggregatedData = null;
this.buildingsGeo = null;
this.landingsGeo = null;
this.landingsGeoByI... | () {
let cables = [];
// For each landing points near the hop
for (let i = 0; i < landingNearHop.length; i++) {
// get that landing point's id
let cableId = landingNearHop[i].feature.properties.cable_id;
// For each landing point that cable has
for (let k = 0; k < self.ag... | getCables | identifier_name |
rks_water_hybgga.py | #!/usr/bin/env python
#JSON {"lot": "RKS/6-31G(d)",
#JSON "scf": "EDIIS2SCFSolver",
#JSON "er": "cholesky",
#JSON "difficulty": 5,
#JSON "description": "Basic RKS DFT example with hyrbid GGA exhange-correlation functional (B3LYP)"}
import numpy as np
from horton import * # pylint: disable=wildcard-import,unused-w... | } | random_line_split | |
init-res-into-things.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn test_rec() {
let i = @mut 0;
{
let a = Box {x: r(i)};
}
assert_eq!(*i, 1);
}
fn test_tag() {
enum t {
t0(r),
}
let i = @mut 0;
{
let a = t0(r(i));
}
assert_eq!(*i, 1);
}
fn test_tup() {
let i = @mut 0;
{
let a = (r(i), 0);
}
... | {
let i = @mut 0;
{
let a = @r(i);
}
assert_eq!(*i, 1);
} | identifier_body |
init-res-into-things.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | struct Box { x: r }
#[unsafe_destructor]
impl Drop for r {
fn drop(&self) {
unsafe {
*(self.i) = *(self.i) + 1;
}
}
}
fn r(i: @mut int) -> r {
r {
i: i
}
}
fn test_box() {
let i = @mut 0;
{
let a = @r(i);
}
assert_eq!(*i, 1);
}
fn test_rec(... | struct r {
i: @mut int,
}
| random_line_split |
init-res-into-things.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let i = @mut 0;
{
let a = (r(i), 0);
}
assert_eq!(*i, 1);
}
fn test_unique() {
let i = @mut 0;
{
let a = ~r(i);
}
assert_eq!(*i, 1);
}
fn test_box_rec() {
let i = @mut 0;
{
let a = @Box {
x: r(i)
};
}
assert_eq!(*i, 1);
}... | test_tup | identifier_name |
visus.js | /**
* Used by InPlaceEdit and Uneditable fields
* @module inputex-visus
*/
var lang = Y.Lang,
inputEx = Y.inputEx;
/**
* Contains the various visualization methods
* @class inputEx.visus
* @static
*/
inputEx.visus = {
/**
* Use a rendering function
* options = {visuType: 'func', func: functi... |
else {
node.innerHTML = v;
}
}
return v;
};
| {
node.innerHTML = "";
node.appendChild(v);
} | conditional_block |
visus.js | /**
* Used by InPlaceEdit and Uneditable fields
* @module inputex-visus
*/
var lang = Y.Lang,
inputEx = Y.inputEx;
/**
* Contains the various visualization methods
* @class inputEx.visus
* @static
*/ | /**
* Use a rendering function
* options = {visuType: 'func', func: function(data) { ...code here...} }
* @method func
*/
"func": function(options, data) {
return options.func(data);
},
/**
* Use Y.Lang.dump
* options = {visuType: 'dump'}
* @method dump
*/
dump: function(option... | inputEx.visus = {
| random_line_split |
conf.py | # Copyright 2018 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchb... | # Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static'] | random_line_split |
MDMC.py | # coding=utf-8
from abc import ABCMeta
import logging
from typing import Iterator
import numpy as np
from mdlmc.topo.topology import NeighborTopology
from ..misc.tools import remember_last_element
from ..LMC.output import CovalentAutocorrelation, MeanSquareDisplacement
from ..cython_exts.LMC.PBCHelper import AtomBo... | :
"""Implementation of the time-dependent Kinetic Monte Carlo Scheme"""
__show_in_config__ = True
__no_config_parameter__ = ["topology", "atom_box", "jumprate_function"]
def __init__(self, topology: "NeighborTopology", *,
atom_box: "AtomBox",
jumprate_function: "JumpR... | KMCLattice | identifier_name |
MDMC.py | # coding=utf-8
from abc import ABCMeta
import logging
from typing import Iterator
import numpy as np
from mdlmc.topo.topology import NeighborTopology
from ..misc.tools import remember_last_element
from ..LMC.output import CovalentAutocorrelation, MeanSquareDisplacement
from ..cython_exts.LMC.PBCHelper import AtomBo... |
def filter_allowed_transitions(start, destination, lattice):
lattice_is_occupied = lattice > 0
occupied_sites, = np.where(lattice_is_occupied)
unoccupied_sites, = np.where(~lattice_is_occupied)
occupied_mask = np.in1d(start, occupied_sites)
unoccupied_mask = np.in1d(destination, unoccupied_sites)... | omega = jumprate_function(*colvars)
# select only jumprates from donors which are occupied
start_occupied_destination_free = filter_allowed_transitions(start, destination, lattice)
omega_allowed = omega[start_occupied_destination_free]
start_allowed = start[start_occupied_destination_fre... | conditional_block |
MDMC.py | # coding=utf-8
from abc import ABCMeta
import logging
from typing import Iterator
import numpy as np
from mdlmc.topo.topology import NeighborTopology
from ..misc.tools import remember_last_element
from ..LMC.output import CovalentAutocorrelation, MeanSquareDisplacement
from ..cython_exts.LMC.PBCHelper import AtomBo... |
@property
def donor_atoms(self):
# TODO: not needed (?)
return self._donor_atoms
@property
def extra_atoms(self):
return self._extra_atoms
@property
def occupied_sites(self):
return np.where(self._lattice > 0)[0]
def jumprate_generator(jumprate_function, lat... | return self._lattice | identifier_body |
MDMC.py | # coding=utf-8
from abc import ABCMeta
import logging
from typing import Iterator
import numpy as np
from mdlmc.topo.topology import NeighborTopology
from ..misc.tools import remember_last_element
from ..LMC.output import CovalentAutocorrelation, MeanSquareDisplacement
from ..cython_exts.LMC.PBCHelper import AtomBo... | autocorr.reset(self.lattice)
msd.reset_displacement()
msd.update_displacement(frame[donor_sites].atom_positions, self.lattice)
if current_frame_number % print_frequency == 0:
auto = autocorr.calculate(self.lattice)
msd_result = ms... | if current_frame_number % reset_frequency == 0: | random_line_split |
test_del_group.py | # -*- coding: utf-8 -*-
from random import randrange
from model.group import Group
import random
import pytest
def test_delete_some_group(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name = "test"))
with pytest.allure.step("Given a group list"):
old_groups = db.... | assert sorted(new_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max) | conditional_block | |
test_del_group.py | # -*- coding: utf-8 -*-
from random import randrange
from model.group import Group
import random
import pytest
def | (app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name = "test"))
with pytest.allure.step("Given a group list"):
old_groups = db.get_group_list()
with pytest.allure.step("When get random group"):
group = random.choice(old_groups)
with pytest.allure.ste... | test_delete_some_group | identifier_name |
test_del_group.py | # -*- coding: utf-8 -*-
from random import randrange
from model.group import Group
import random
import pytest
def test_delete_some_group(app, db, check_ui):
| if len(db.get_group_list()) == 0:
app.group.create(Group(name = "test"))
with pytest.allure.step("Given a group list"):
old_groups = db.get_group_list()
with pytest.allure.step("When get random group"):
group = random.choice(old_groups)
with pytest.allure.step("When I delete %s" %gro... | identifier_body | |
test_del_group.py | # -*- coding: utf-8 -*-
from random import randrange
from model.group import Group
import random
import pytest
def test_delete_some_group(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name = "test"))
with pytest.allure.step("Given a group list"):
old_groups = db.... | if check_ui:
assert sorted(new_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max) | old_groups.remove(group)
assert old_groups == new_groups | random_line_split |
keyframes.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser,... | {
pub selector: KeyframeSelector,
/// `!important` is not allowed in keyframe declarations,
/// so the second value of these tuples is always `Importance::Normal`.
/// But including them enables `compute_style_for_animation_step` to create a `ApplicableDeclarationBlock`
/// by cloning an `Arc<_>` ... | Keyframe | identifier_name |
keyframes.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser,... | let mut results = Vec::new();
match PropertyDeclaration::parse(name, self.context, input, &mut results, true) {
PropertyDeclarationParseResult::ValidOrIgnoredDeclaration => {}
_ => return Err(())
}
Ok(results)
}
} | identifier_body | |
keyframes.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser,... | _ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///... | block.read().declarations.iter().any(|&(ref prop_decl, _)| {
match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}
})
}
| conditional_block |
keyframes.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser,... | Some(KeyframesAnimation {
steps: steps,
properties_changed: animated_properties,
})
}
}
/// Parses a keyframes list, like:
/// 0%, 50% {
/// width: 50%;
/// }
///
/// 40%, 60%, 100% {
/// width: 100%;
/// }
struct KeyframeListParser<'a> {
context: &'a ParserConte... | if steps.last().unwrap().start_percentage.0 != 1. {
steps.push(KeyframesStep::new(KeyframePercentage::new(0.),
KeyframesStepValue::ComputedValues));
}
| random_line_split |
change_detector_ref.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @stable
*/
export declare abstract class ChangeDetectorRef {
/**
* Marks all {@link ChangeDetectionS... | * setInterval(() => {
* this.numberOfTicks ++
* // the following is required, otherwise the view will not be updated
* this.ref.markForCheck();
* }, 1000);
* }
* }
*
* @Component({
* selector: 'app',
* changeDetection: ChangeDetectio... | * constructor(ref: ChangeDetectorRef) { | random_line_split |
p074.rs | //! [Problem 74](https://projecteuler.net/problem=74) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use std::collections::HashMap;
#[derive(Clone)]
enum Length {
Loop(usize),
Chain(usize),
Unknown,
}
fn fa... | () {
let factorial = {
let mut val = [1; 10];
for i in 1..10 {
val[i] = val[i - 1] * (i as u32);
}
val
};
let mut map = iter::repeat(super::Length::Unknown)
.take((factorial[9] * 6 + 1) as usize)
.collect::<V... | len | identifier_name |
p074.rs | //! [Problem 74](https://projecteuler.net/problem=74) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use std::collections::HashMap;
#[derive(Clone)]
enum Length {
Loop(usize),
Chain(usize),
Unknown, | fn fact_sum(mut n: u32, fs: &[u32; 10]) -> u32 {
if n == 0 {
return 1;
}
let mut sum = 0;
while n > 0 {
sum += fs[(n % 10) as usize];
n /= 10;
}
sum
}
fn get_chain_len(n: u32, map: &mut [Length], fs: &[u32; 10]) -> usize {
let mut chain_map = HashMap::new();
let... | }
| random_line_split |
p074.rs | //! [Problem 74](https://projecteuler.net/problem=74) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use std::collections::HashMap;
#[derive(Clone)]
enum Length {
Loop(usize),
Chain(usize),
Unknown,
}
fn fa... |
}
chain_len + loop_len
}
fn solve() -> String {
let limit = 1000000;
let factorial = {
let mut val = [1; 10];
for i in 1..10 {
val[i] = val[i - 1] * (i as u32);
}
val
};
let mut map = vec![Length::Unknown; (factorial[9] * 6 + 1) as usize];
let ... | {
map[key as usize] = Length::Chain(loop_len + chain_len - idx);
} | conditional_block |
test_hive_partition.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... | (self, mock_hive_metastore_hook):
op = HivePartitionSensor(
task_id='hive_partition_check', table='airflow.static_babynames_partitioned', dag=self.dag
)
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
| test_hive_partition_sensor | identifier_name |
test_hive_partition.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... | import os
import unittest
from unittest.mock import patch
from airflow.providers.apache.hive.sensors.hive_partition import HivePartitionSensor
from tests.providers.apache.hive import DEFAULT_DATE, TestHiveEnvironment
from tests.test_utils.mock_hooks import MockHiveMetastoreHook
@unittest.skipIf('AIRFLOW_RUNALL_TESTS... | random_line_split | |
test_hive_partition.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... | op = HivePartitionSensor(
task_id='hive_partition_check', table='airflow.static_babynames_partitioned', dag=self.dag
)
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) | identifier_body | |
util.py | import tornado.web
import json
from tornado_cors import CorsMixin
from common import ParameterFormat, EnumEncoder
class DefaultRequestHandler(CorsMixin, tornado.web.RequestHandler):
CORS_ORIGIN = '*'
def initialize(self):
self.default_format = self.get_argument("format", "json", True)
self.s... |
def write_comment(self, format_type, comment):
default_comment = "--"
if format_type == "conf":
default_comment = "#"
if comment != "NONE":
self.write("\n{} {}\n".format(default_comment, comment))
def write_config(self, output_data):
if self.show_abo... | default_comment = "--"
if format_type == "conf":
default_comment = "#"
self.write("{} Generated by PGConfig {}\n".format(default_comment,
self.version))
self.write("{} http://pgconfig.org\n\n".format(default_comment * 2)) | identifier_body |
util.py | import tornado.web
import json
from tornado_cors import CorsMixin
from common import ParameterFormat, EnumEncoder
class DefaultRequestHandler(CorsMixin, tornado.web.RequestHandler):
CORS_ORIGIN = '*'
def initialize(self):
self.default_format = self.get_argument("format", "json", True)
self.s... |
self.write("{} = {}\n".format(parameter["name"], config_value))
self.write("\n")
def write_alter_system(self, output_data):
if float(self.pg_version) <= 9.3:
self.write("-- ALTER SYSTEM format it's only supported on version 9.4 and higher. Use 'conf' form... | self.write_comment("conf", parameter_comment) | conditional_block |
util.py | import tornado.web
import json
from tornado_cors import CorsMixin
from common import ParameterFormat, EnumEncoder
class DefaultRequestHandler(CorsMixin, tornado.web.RequestHandler):
CORS_ORIGIN = '*'
def initialize(self):
self.default_format = self.get_argument("format", "json", True)
self.s... |
self.write("\n")
def write_alter_system(self, output_data):
if float(self.pg_version) <= 9.3:
self.write("-- ALTER SYSTEM format it's only supported on version 9.4 and higher. Use 'conf' format instead.")
else:
if self.show_about is True:
... |
if parameter_comment != "NONE":
self.write_comment("conf", parameter_comment)
self.write("{} = {}\n".format(parameter["name"], config_value)) | random_line_split |
util.py | import tornado.web
import json
from tornado_cors import CorsMixin
from common import ParameterFormat, EnumEncoder
class DefaultRequestHandler(CorsMixin, tornado.web.RequestHandler):
CORS_ORIGIN = '*'
def initialize(self):
self.default_format = self.get_argument("format", "json", True)
self.s... | (self, message):
self.set_header('Content-Type', 'application/vnd.api+json')
_document = {}
_document["data"] = message
_meta = {}
_meta["copyright"] = "PGConfig API"
_meta["version"] = self.version
_meta["arguments"] = self.request.arguments
_document[... | write_json_api | identifier_name |
test_chart_axis23.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | chart.add_series({'values': '=Sheet1!$B$1:$B$5'})
chart.add_series({'values': '=Sheet1!$C$1:$C$5'})
chart.set_x_axis({'num_format': 'dd/mm/yyyy'})
chart.set_y_axis({'num_format': '0.00%'})
worksheet.insert_chart('E9', chart)
workbook.close()
self.assertExcelEq... | chart.add_series({'values': '=Sheet1!$A$1:$A$5'}) | random_line_split |
test_chart_axis23.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | (self):
self.maxDiff = None
filename = 'chart_axis23.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
... | setUp | identifier_name |
test_chart_axis23.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | """Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [46332160, 47470848]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8,... | identifier_body | |
base.py | from openerp.osv import osv, fields
class IrActionsActWindowMenu(osv.Model):
|
class IrActionsActWindowButton(osv.Model):
_name = 'ir.actions.act_window.button'
_description = 'Button to display'
_order = 'name'
_columns = {
'action_from_id': fields.many2one('ir.actions.act_window', 'from Action',
required=True),
'acti... | _name = 'ir.actions.act_window.menu'
_description = 'Menu on the actions'
_columns = {
'name': fields.char('Label', size=64, required=True, translate=True),
'active': fields.boolean(
'Active', help='if check, this object is always available'),
}
_defaults = {
'activ... | identifier_body |
base.py | from openerp.osv import osv, fields
class IrActionsActWindowMenu(osv.Model):
_name = 'ir.actions.act_window.menu'
_description = 'Menu on the actions'
_columns = {
'name': fields.char('Label', size=64, required=True, translate=True),
'active': fields.boolean(
'Active', help='i... |
return res
class IrActionsActWindow(osv.Model):
_inherit = 'ir.actions.act_window'
_columns = {
'buttons_ids': fields.one2many('ir.actions.act_window.button',
'action_from_id', 'Buttons'),
}
def get_menus_and_buttons(self, cr, uid, ids, context... | random_line_split | |
base.py | from openerp.osv import osv, fields
class IrActionsActWindowMenu(osv.Model):
_name = 'ir.actions.act_window.menu'
_description = 'Menu on the actions'
_columns = {
'name': fields.char('Label', size=64, required=True, translate=True),
'active': fields.boolean(
'Active', help='i... |
if this.visibility_model_name and this.visible_button_method_name:
model = self.pool.get(this.visibility_model_name)
if not getattr(model, this.visible_button_method_name)(
cr, uid, context=context):
continue
menu = t... | continue | conditional_block |
base.py | from openerp.osv import osv, fields
class IrActionsActWindowMenu(osv.Model):
_name = 'ir.actions.act_window.menu'
_description = 'Menu on the actions'
_columns = {
'name': fields.char('Label', size=64, required=True, translate=True),
'active': fields.boolean(
'Active', help='i... | (action_id):
model = self.pool.get(action.read(cr, uid, action_id, ['type'],
context=context)['type'])
return model.read(cr, uid, action_id, [], load="_classic_write",
context=context)
for this in self.browse(cr... | get_action | identifier_name |
lib.rs | // Copyright (C) 2015, Alberto Corona <alberto@0x1a.us>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "lib"]
#![feature(path_relative_from,exit_status)]
extern crate term;
use std::io::prelude::Write;
use ... |
pub fn err(prog: &str, status: Status, mesg: String) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n", prog, mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
}... | {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n",item.display(), mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
} | identifier_body |
lib.rs | // Copyright (C) 2015, Alberto Corona <alberto@0x1a.us>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "lib"]
#![feature(path_relative_from,exit_status)]
extern crate term;
use std::io::prelude::Write;
use ... | ,
};
}
pub fn err(prog: &str, status: Status, mesg: String) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n", prog, mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {}... | {} | conditional_block |
lib.rs | // Copyright (C) 2015, Alberto Corona <alberto@0x1a.us>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "lib"]
#![feature(path_relative_from,exit_status)]
extern crate term;
use std::io::prelude::Write;
use ... | use std::env;
use std::path::{PathBuf,Path};
pub enum Status {
Ok,
Error,
OptError,
ArgError,
}
pub fn exit(status: Status) {
process::exit(status as i32);
}
pub fn set_exit_status(status: Status) {
env::set_exit_status(status as i32);
}
pub fn path_err(status: Status, mesg: String, item: P... | random_line_split | |
lib.rs | // Copyright (C) 2015, Alberto Corona <alberto@0x1a.us>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "lib"]
#![feature(path_relative_from,exit_status)]
extern crate term;
use std::io::prelude::Write;
use ... | (&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
}
| rel_to | identifier_name |
ShiftAction.js | "use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b)... | () { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Action_1 = require("../Action");
var ShiftAction = (function (_super) {
__extends(ShiftAction, _super);
funct... | __ | identifier_name |
ShiftAction.js | "use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b)... | return fn({
n: this.n,
time: this.time,
container: this.container
});
};
return ShiftAction;
}(Action_1.default));
exports.default = ShiftAction;
//# sourceMappingURL=ShiftAction.js.map | _this.n = n;
return _this;
}
ShiftAction.prototype.reduce = function (state) {
var fn = this.fn(state).bind(state); | random_line_split |
ShiftAction.js | "use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b)... |
ShiftAction.prototype.reduce = function (state) {
var fn = this.fn(state).bind(state);
return fn({
n: this.n,
time: this.time,
container: this.container
});
};
return ShiftAction;
}(Action_1.default));
exports.default = ShiftAction;
//# sourceMapp... | {
var time = _a.time, container = _a.container, _b = _a.n, n = _b === void 0 ? 1 : _b;
var _this = _super.call(this, { time: time }) || this;
_this.container = container;
_this.n = n;
return _this;
} | identifier_body |
run.py | #!/usr/bin/env python
"""
Goal: Implement the application entry point.
@authors:
Andrei Sura <sura.andrei@gmail.com>
"""
import argparse
from olass.olass_client import OlassClient
from olass.version import __version__
DEFAULT_SETTINGS_FILE = 'config/settings.py'
def | ():
""" Read args """
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--version",
default=False,
action='store_true',
help="Show the version number")
parser.add_argument("-c", "--config",
defaul... | main | identifier_name |
run.py | #!/usr/bin/env python
"""
Goal: Implement the application entry point.
@authors:
Andrei Sura <sura.andrei@gmail.com>
"""
import argparse
from olass.olass_client import OlassClient
from olass.version import __version__
DEFAULT_SETTINGS_FILE = 'config/settings.py'
def main():
""" Read args """
parser = arg... | main() | conditional_block | |
run.py | #!/usr/bin/env python
"""
Goal: Implement the application entry point.
@authors:
Andrei Sura <sura.andrei@gmail.com>
"""
import argparse
from olass.olass_client import OlassClient
from olass.version import __version__
DEFAULT_SETTINGS_FILE = 'config/settings.py'
def main():
""" Read args """
parser = arg... | interactive=args.interactive,
rows_per_batch=args.rows)
app.run()
if __name__ == "__main__":
main() | app = OlassClient(config_file=args.config, | random_line_split |
run.py | #!/usr/bin/env python
"""
Goal: Implement the application entry point.
@authors:
Andrei Sura <sura.andrei@gmail.com>
"""
import argparse
from olass.olass_client import OlassClient
from olass.version import __version__
DEFAULT_SETTINGS_FILE = 'config/settings.py'
def main():
|
if __name__ == "__main__":
main()
| """ Read args """
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--version",
default=False,
action='store_true',
help="Show the version number")
parser.add_argument("-c", "--config",
default=DEFAUL... | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from sqlalchemy import engine_from_config
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import configure_mappers
import zope.sqlalchemy
# import or define all models here to ensure they are attached to the
# Base.metadata prior to any initia... | Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.
This function will hook the session to the transaction manager which
will take care of committing any changes.
- When using pyramid_tm it will automatically be committed or aborted
depending on whether an exception is raised.
... | random_line_split | |
__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from sqlalchemy import engine_from_config
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import configure_mappers
import zope.sqlalchemy
# import or define all models here to ensure they are attached to the
# Base.metadata prior to any initia... | (config):
"""
Initialize the model for a Pyramid app.
Activate this setup using ``config.include('survivor-pool.models')``.
"""
settings = config.get_settings()
# use pyramid_tm to hook the transaction lifecycle to the request
config.include('pyramid_tm')
session_factory = get_sessio... | includeme | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from sqlalchemy import engine_from_config
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import configure_mappers
import zope.sqlalchemy
# import or define all models here to ensure they are attached to the
# Base.metadata prior to any initia... |
def get_tm_session(session_factory, transaction_manager):
"""
Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.
This function will hook the session to the transaction manager which
will take care of committing any changes.
- When using pyramid_tm it will automatically be commit... | factory = sessionmaker()
factory.configure(bind=engine)
return factory | identifier_body |
Resurgence.tsx | import { Trans } from '@lingui/macro';
import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import HIT_TYPES from 'game/HIT_TYPES';
import { SpellLink } from 'interface';
import { SpellIcon } from 'interface';
import ManaIcon from 'interface/icons/Mana';
import Analyzer, {... | ]),
this.onRelevantHeal,
);
this.addEventListener(
Events.energize.to(SELECTED_PLAYER).spell(SPELLS.RESURGENCE),
this.onResurgenceProc,
);
}
onRelevantHeal(event: HealEvent) {
if (event.tick) {
return;
}
const spellId = event.ability.guid;
if (!this.resu... | SPELLS.HEALING_WAVE,
SPELLS.CHAIN_HEAL,
SPELLS.UNLEASH_LIFE_TALENT,
SPELLS.RIPTIDE, | random_line_split |
Resurgence.tsx | import { Trans } from '@lingui/macro';
import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import HIT_TYPES from 'game/HIT_TYPES';
import { SpellLink } from 'interface';
import { SpellIcon } from 'interface';
import ManaIcon from 'interface/icons/Mana';
import Analyzer, {... |
if (event.hitType === HIT_TYPES.CRIT) {
this.resurgence[spellId].resurgenceTotal +=
SPELLS_PROCCING_RESURGENCE[spellId] * this.manaTracker.maxResource;
this.resurgence[spellId].castAmount += 1;
}
}
onResurgenceProc(event: EnergizeEvent) {
const spellId = event.ability.guid;
i... | {
this.resurgence[spellId] = {
spellId: spellId,
resurgenceTotal: 0,
castAmount: 0,
};
} | conditional_block |
Resurgence.tsx | import { Trans } from '@lingui/macro';
import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import HIT_TYPES from 'game/HIT_TYPES';
import { SpellLink } from 'interface';
import { SpellIcon } from 'interface';
import ManaIcon from 'interface/icons/Mana';
import Analyzer, {... | (options: Options) {
super(options);
this.addEventListener(
Events.heal
.by(SELECTED_PLAYER)
.spell([
SPELLS.HEALING_SURGE,
SPELLS.HEALING_WAVE,
SPELLS.CHAIN_HEAL,
SPELLS.UNLEASH_LIFE_TALENT,
SPELLS.RIPTIDE,
]),
this.onReleva... | constructor | identifier_name |
Resurgence.tsx | import { Trans } from '@lingui/macro';
import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import HIT_TYPES from 'game/HIT_TYPES';
import { SpellLink } from 'interface';
import { SpellIcon } from 'interface';
import ManaIcon from 'interface/icons/Mana';
import Analyzer, {... |
onRelevantHeal(event: HealEvent) {
if (event.tick) {
return;
}
const spellId = event.ability.guid;
if (!this.resurgence[spellId]) {
this.resurgence[spellId] = {
spellId: spellId,
resurgenceTotal: 0,
castAmount: 0,
};
}
if (event.hitType === HIT_TYP... | {
super(options);
this.addEventListener(
Events.heal
.by(SELECTED_PLAYER)
.spell([
SPELLS.HEALING_SURGE,
SPELLS.HEALING_WAVE,
SPELLS.CHAIN_HEAL,
SPELLS.UNLEASH_LIFE_TALENT,
SPELLS.RIPTIDE,
]),
this.onRelevantHeal,
);
... | identifier_body |
serve.js | var path = require('path');
var url = require('url');
var closure = require('closure-util');
var nomnom = require('nomnom');
var log = closure.log;
var options = nomnom.options({
port: {
abbr: 'p',
'default': 4000,
help: 'Port for incoming connections',
metavar: 'PORT'
},
loglevel: {
abbr: ... | }); | process.exit(1);
}); | random_line_split |
debug_runtime.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 run_individual(self, number, repeat=1, min_repeat_ms=0):
ret = self._run_individual(number, repeat, min_repeat_ms)
return ret.strip(",").split(",") if ret else []
def exit(self):
"""Exits the dump folder and all its contents"""
self._remove_dump_root()
| """Run forward execution of the graph with debug
Parameters
----------
input_dict : dict of str to NDArray
List of input values to be feed to
"""
if input_dict:
self.set_input(**input_dict)
# Step 1. Execute the graph
self._run_debug()
... | identifier_body |
debug_runtime.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... |
# Step 1. Execute the graph
self._run_debug()
# Step 2. Dump the output tensors to the dump folder
self.debug_datum.dump_output_tensor()
# Step 3. Dump the Chrome trace to the dump folder
self.debug_datum.dump_chrome_trace()
# Step 4. Display the collected infor... | self.set_input(**input_dict) | conditional_block |
debug_runtime.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... | (self, directory):
"""Create a directory if not exists
Parameters
----------
directory : str
File path to create
"""
if not os.path.exists(directory):
os.makedirs(directory, 0o700)
def _get_dump_path(self, ctx):
"""Make the graph and... | _ensure_dir | identifier_name |
debug_runtime.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... | self._dump_path = None
self._get_output_by_layer = module["get_output_by_layer"]
self._run_individual = module["run_individual"]
graph_runtime.GraphModule.__init__(self, module)
self._create_debug_env(graph_json_str, ctx)
def _format_context(self, ctx):
return str(ct... |
def __init__(self, module, ctx, graph_json_str, dump_root):
self._dump_root = dump_root | random_line_split |
release_push.py | #!/usr/bin/env python
# encoding: utf-8
"""
release_push.py
Created by Jonathan Burke on 2013-12-30.
Copyright (c) 2015 University of Washington. All rights reserved.
"""
#See README-maintainers.html for more information
from release_vars import *
from release_utils import *
from sanity_checks import *
import urll... | ( jsr308_website, afu_website, checker_website, suffix ):
jsr308Check = run_link_checker( jsr308_website, "/tmp/jsr308." + suffix + ".check" )
afuCheck = run_link_checker( afu_website, "/tmp/afu." + suffix + ".check" )
checkerCheck = run_link_checker( checker_website, "/tmp/checker-framework." + s... | check_all_links | identifier_name |
release_push.py | #!/usr/bin/env python
# encoding: utf-8
"""
release_push.py
Created by Jonathan Burke on 2013-12-30.
Copyright (c) 2015 University of Washington. All rights reserved.
"""
#See README-maintainers.html for more information
from release_vars import *
from release_utils import *
from sanity_checks import *
import urll... |
continue_or_exit( msg + "\n" )
if test_mode:
print("Continuing in test mode.")
else:
print("Continuing in release mode.")
check_hg_user()
print( "\nNOTE: Please read all the prompts printed by this script very carefully, as their" )
print( "contents may have changed since the... | msg = "You have chosen release_mode. Please follow the prompts to run a full Checker Framework release" | conditional_block |
release_push.py | #!/usr/bin/env python
# encoding: utf-8
"""
release_push.py
Created by Jonathan Burke on 2013-12-30.
Copyright (c) 2015 University of Washington. All rights reserved.
"""
#See README-maintainers.html for more information
from release_vars import *
from release_utils import *
from sanity_checks import *
import urll... | sys.exit(main(sys.argv)) | random_line_split | |
release_push.py | #!/usr/bin/env python
# encoding: utf-8
"""
release_push.py
Created by Jonathan Burke on 2013-12-30.
Copyright (c) 2015 University of Washington. All rights reserved.
"""
#See README-maintainers.html for more information
from release_vars import *
from release_utils import *
from sanity_checks import *
import urll... |
def read_args(argv):
test = True
if len( argv ) == 2:
if argv[1] == "release":
test = False
else:
print_usage()
else:
if len( argv ) > 2:
print_usage()
raise Exception( "Invalid arguments. " + ",".join(argv) )
return test
def pr... | continue_script = prompt_w_suggestion(msg + " Continue?", "yes", "^(Yes|yes|No|no)$")
if continue_script == "no" or continue_script == "No":
raise Exception( "User elected NOT to continue at prompt: " + msg ) | identifier_body |
SessionEventMap.ts | /*
* (C) Copyright 2017-2022 OpenVidu (https://openvidu.io)
*
* 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 ap... | * This event acts as a global handler for asynchronous errors that may be triggered for multiple reasons and from multiple origins.
* To see the different types of exceptions go to [[ExceptionEventName]].
*/
exception: ExceptionEvent;
} | */
reconnected: never;
/** | random_line_split |
websocket.py | # coding=utf-8
import codecs
import logging
import cherrypy
import tailer
from schema import And, Schema, SchemaError, Use
from ws4py.messaging import TextMessage
from ws4py.websocket import WebSocket
import autosubliminal
from autosubliminal import system
from autosubliminal.core.runner import Runner
from autosubli... | (self, message):
handled = False
# Check for a valid event message structure
if self.check_message_structure(message):
event = message['event']
# Handle a RUN_SCHEDULER event
if event['type'] == RUN_SCHEDULER:
name = event['data']['name']
... | handle_message | identifier_name |
websocket.py | # coding=utf-8
import codecs
import logging
import cherrypy
import tailer
from schema import And, Schema, SchemaError, Use
from ws4py.messaging import TextMessage
from ws4py.websocket import WebSocket
import autosubliminal
from autosubliminal import system
from autosubliminal.core.runner import Runner
from autosubli... |
def handle_message(self, message):
handled = False
# Check for a valid event message structure
if self.check_message_structure(message):
event = message['event']
# Handle a RUN_SCHEDULER event
if event['type'] == RUN_SCHEDULER:
name = ev... | log.warning('Unsupported message received on websocket server: %r', message) | conditional_block |
websocket.py | # coding=utf-8
import codecs
import logging
import cherrypy
import tailer
from schema import And, Schema, SchemaError, Use
from ws4py.messaging import TextMessage
from ws4py.websocket import WebSocket
import autosubliminal
from autosubliminal import system
from autosubliminal.core.runner import Runner
from autosubli... | def check_message_structure(self, message):
try:
MESSAGE_SCHEMA.validate(message)
return True
except SchemaError:
return False
class WebSocketBroadCaster(Runner):
"""
WebSocket broadcaster class for broadcasting data from the server through the websocket... | if not handled:
log.warning('Unsupported message received on websocket server: %r', message)
return handled
| random_line_split |
websocket.py | # coding=utf-8
import codecs
import logging
import cherrypy
import tailer
from schema import And, Schema, SchemaError, Use
from ws4py.messaging import TextMessage
from ws4py.websocket import WebSocket
import autosubliminal
from autosubliminal import system
from autosubliminal.core.runner import Runner
from autosubli... |
def check_message_structure(self, message):
try:
MESSAGE_SCHEMA.validate(message)
return True
except SchemaError:
return False
class WebSocketBroadCaster(Runner):
"""
WebSocket broadcaster class for broadcasting data from the server through the websock... | handled = False
# Check for a valid event message structure
if self.check_message_structure(message):
event = message['event']
# Handle a RUN_SCHEDULER event
if event['type'] == RUN_SCHEDULER:
name = event['data']['name']
if name in au... | identifier_body |
subcriteria_test.tsx | jest.mock("../edit", () => ({
toggleAndEditEqCriteria: jest.fn(),
}));
import React from "react";
import { mount } from "enzyme";
import { toggleAndEditEqCriteria } from "..";
import { CheckboxListProps, SubCriteriaSectionProps } from "../interfaces";
import {
fakePointGroup,
} from "../../../__test_support__/fake... | const fakeProps = (): CheckboxListProps<string> => ({
criteriaKey: "openfarm_slug",
list: [{ label: "label", value: "value" }],
dispatch: jest.fn(),
group: fakePointGroup(),
pointerType: "Plant",
disabled: false,
});
it("toggles criteria", () => {
const p = fakeProps();
const wrap... |
describe("<CheckboxList />", () => { | random_line_split |
specials.py | from djpcms import sites
from djpcms.http import get_http
from djpcms.template import RequestContext, loader
from djpcms.views.baseview import djpcmsview
class badview(djpcmsview):
def __init__(self, template, httphandler):
self.template = template
self.httphandler = httphandler
super... | (request, *args, **kwargs):
http = get_http(sites.settings.HTTP_LIBRARY)
return badview('500.html',
http.HttpResponseServerError).response(request) | http500view | identifier_name |
specials.py | from djpcms import sites
from djpcms.http import get_http
from djpcms.template import RequestContext, loader
from djpcms.views.baseview import djpcmsview
class badview(djpcmsview):
def __init__(self, template, httphandler):
self.template = template
self.httphandler = httphandler
super... |
def http404view(request, *args, **kwargs):
http = get_http(sites.settings.HTTP_LIBRARY)
return badview('404.html',
http.HttpResponseNotFound).response(request)
def http500view(request, *args, **kwargs):
http = get_http(sites.settings.HTTP_LIBRARY)
return badview('500.html',
... | t = loader.get_template(self.template)
c = {'request_path': request.path,
'grid': self.grid960()}
return self.httphandler(t.render(RequestContext(request, c))) | identifier_body |
specials.py | from djpcms import sites
from djpcms.http import get_http
from djpcms.template import RequestContext, loader
from djpcms.views.baseview import djpcmsview
class badview(djpcmsview):
def __init__(self, template, httphandler):
self.template = template
self.httphandler = httphandler
super... | def response(self, request):
t = loader.get_template(self.template)
c = {'request_path': request.path,
'grid': self.grid960()}
return self.httphandler(t.render(RequestContext(request, c)))
def http404view(request, *args, **kwargs):
http = get_http(sites.settings.HTTP_LIBRAR... | random_line_split | |
ng-wig.js | /**
* version: 1.1.10
*/
angular.module('ngWig', ['ngwig-app-templates']);
angular.module('ngWig')
.directive('ngWig', function () {
return {
scope: {
content: '=ngWig'
},
restrict: 'A',
replace: true, | scope.autoexpand = !('autoexpand' in attrs) || attrs['autoexpand'] !== 'off';
scope.toggleEditMode = function () {
scope.editMode = !scope.editMode;
};
scope.execCommand = function (command, options) {
if (command === 'createlink') {
options = prompt('Pl... | templateUrl: 'ng-wig/views/ng-wig.html',
link: function (scope, element, attrs) {
scope.editMode = false; | random_line_split |
ng-wig.js | /**
* version: 1.1.10
*/
angular.module('ngWig', ['ngwig-app-templates']);
angular.module('ngWig')
.directive('ngWig', function () {
return {
scope: {
content: '=ngWig'
},
restrict: 'A',
replace: true,
templateUrl: 'ng-wig/views/ng-wig.html',
link: function (scope... |
$element.bind('blur keyup change paste', viewToModel);
scope.$on('execCommand', function (event, params) {
$element[0].focus();
var ieStyleTextSelection = document.selection,
command = params.command,
options = params.options;
if (ieStyleTextSelection) {
... | {
ctrl.$setViewValue($element.html());
//to support Angular 1.2.x
if (angular.version.minor < 3) {
scope.$apply();
}
} | identifier_body |
ng-wig.js | /**
* version: 1.1.10
*/
angular.module('ngWig', ['ngwig-app-templates']);
angular.module('ngWig')
.directive('ngWig', function () {
return {
scope: {
content: '=ngWig'
},
restrict: 'A',
replace: true,
templateUrl: 'ng-wig/views/ng-wig.html',
link: function (scope... |
if (options !== null) {
scope.$emit('execCommand', {command: command, options: options});
}
};
scope.styles = [
{name: 'Normal text', value: 'p'},
{name: 'Header 1', value: 'h1'},
{name: 'Header 2', value: 'h2'},
{name: 'Header 3... | {
options = prompt('Please enter an image URL to insert', 'http://');
} | conditional_block |
ng-wig.js | /**
* version: 1.1.10
*/
angular.module('ngWig', ['ngwig-app-templates']);
angular.module('ngWig')
.directive('ngWig', function () {
return {
scope: {
content: '=ngWig'
},
restrict: 'A',
replace: true,
templateUrl: 'ng-wig/views/ng-wig.html',
link: function (scope... | (scope, $element, attrs, ctrl) {
var document = $element[0].ownerDocument;
$element.attr('contenteditable', true);
//model --> view
ctrl.$render = function () {
$element.html(ctrl.$viewValue || '');
};
//view --> model
function viewToModel() {
ctrl.$setViewV... | init | identifier_name |
reducers.spec.js | import { expect } from 'chai'
import reducers, { initialState } from 'mobilizations/widgets/__plugins__/pressure/reducers'
import { createAction } from 'mobilizations/widgets/__plugins__/pressure/action-creators/create-action'
import * as t from 'mobilizations/widgets/__plugins__/pressure/action-types'
describe('clie... | expect(nextState).to.have.property('saving', false)
expect(nextState)
.to.have.property('filledPressureWidgets')
.that.deep.equals([1])
}
)
it('should change saving state to false and error state with message when failed', () => {
// state while requesting
const currentInitia... | random_line_split | |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import Animate from 'rc-animate';
import ScrollNumber from './ScrollNumber';
import classNames from 'classnames';
export { ScrollNumberProps } from './ScrollNumber';
export interface BadgeProps {
/** Number to show in badge */
count?: number | st... | () {
const {
count,
showZero,
prefixCls,
scrollNumberPrefixCls,
overflowCount,
className,
style,
children,
dot,
status,
text,
offset,
...restProps,
} = this.props;
const isDot = dot || status;
let displayCount = (count as numb... | render | identifier_name |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import Animate from 'rc-animate';
import ScrollNumber from './ScrollNumber';
import classNames from 'classnames';
export { ScrollNumberProps } from './ScrollNumber';
export interface BadgeProps {
/** Number to show in badge */
count?: number | st... |
const scrollNumber = hidden ? null : (
<ScrollNumber
prefixCls={scrollNumberPrefixCls}
data-show={!hidden}
className={scrollNumberCls}
count={displayCount}
title={count}
style={styleWithOffset}
/>
);
const statusText = (hidden || !text) ? null :... | {
const {
count,
showZero,
prefixCls,
scrollNumberPrefixCls,
overflowCount,
className,
style,
children,
dot,
status,
text,
offset,
...restProps,
} = this.props;
const isDot = dot || status;
let displayCount = (count as number)... | identifier_body |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import Animate from 'rc-animate';
import ScrollNumber from './ScrollNumber';
import classNames from 'classnames';
export { ScrollNumberProps } from './ScrollNumber';
export interface BadgeProps {
/** Number to show in badge */
count?: number | st... | transitionName={children ? `${prefixCls}-zoom` : ''}
transitionAppear
>
{scrollNumber}
</Animate>
{statusText}
</span>
);
}
} | random_line_split | |
OpenStackTenantForm.tsx | import { FunctionComponent } from 'react';
import { StringField, SecretField, FormContainer } from '@waldur/form';
export const OpenStackTenantForm: FunctionComponent<{
translate;
container;
}> = ({ translate, container }) => (
<FormContainer {...container}>
<StringField
name="backend_url"
label... | />
</FormContainer>
); | 'Flavors matching this regex expression will not be pulled from the backend.',
)} | random_line_split |
uva_10407.py | # /* UVa problem: 10407
# * Simple Division
# * Topic: Number Theory
# *
# * Level: challenging
# *
# * Brief problem description:
# * Given a list of numbers, a1, a2, a3.... an compute a number m such that
# * ai mod m = x for some arbitrary x for all ai.
# * In other words, find a congruence class mod... |
def lcm(a, b):
return (a* (b/gcd(a, b)))
def load():
while(1):
line = next(sys.stdin).split()
line = [int(x) for x in line]
line.pop(-1)
if len(line) == 0:
break
yield(line)
for (sequence) in load():
n = len(sequence)
diff = list()
for i in range(0, n-1):
# Now find gcd of all the differences... | if b== 0:
return a
return gcd(b, a%b) | identifier_body |
uva_10407.py | # /* UVa problem: 10407
# * Simple Division
# * Topic: Number Theory
# *
# * Level: challenging
# *
# * Brief problem description:
# * Given a list of numbers, a1, a2, a3.... an compute a number m such that
# * ai mod m = x for some arbitrary x for all ai.
# * In other words, find a congruence class mod... |
if n == 2:
sys.stdout.write("{}\n".format(diff[0]))
else:
# Compute gcd of the differences
#print(diff)
#sys.stdout.write("gcd({}, {}) = {}\n".format(diff[0], diff[1], gcd(diff[0], diff[1])))
m = gcd(diff[0], diff[1])
for i in range(2, n-1):
#sys.stdout.write("gcd({}, {}) = {}\n".format(m, diff[i], gc... | for i in range(0, n-1):
# Now find gcd of all the differences:
diff.append(abs(sequence[i+1] - sequence[i])) #compute the differences | random_line_split |
uva_10407.py | # /* UVa problem: 10407
# * Simple Division
# * Topic: Number Theory
# *
# * Level: challenging
# *
# * Brief problem description:
# * Given a list of numbers, a1, a2, a3.... an compute a number m such that
# * ai mod m = x for some arbitrary x for all ai.
# * In other words, find a congruence class mod... |
return gcd(b, a%b)
def lcm(a, b):
return (a* (b/gcd(a, b)))
def load():
while(1):
line = next(sys.stdin).split()
line = [int(x) for x in line]
line.pop(-1)
if len(line) == 0:
break
yield(line)
for (sequence) in load():
n = len(sequence)
diff = list()
for i in range(0, n-1):
# Now find gcd of... | return a | conditional_block |
uva_10407.py | # /* UVa problem: 10407
# * Simple Division
# * Topic: Number Theory
# *
# * Level: challenging
# *
# * Brief problem description:
# * Given a list of numbers, a1, a2, a3.... an compute a number m such that
# * ai mod m = x for some arbitrary x for all ai.
# * In other words, find a congruence class mod... | ():
while(1):
line = next(sys.stdin).split()
line = [int(x) for x in line]
line.pop(-1)
if len(line) == 0:
break
yield(line)
for (sequence) in load():
n = len(sequence)
diff = list()
for i in range(0, n-1):
# Now find gcd of all the differences:
diff.append(abs(sequence[i+1] - sequence[i])) #com... | load | identifier_name |
hg_upgrader.py | import os
from ..cache import set_cache, get_cache
from ..show_error import show_error
from .vcs_upgrader import VcsUpgrader
class HgUpgrader(VcsUpgrader):
"""
Allows upgrading a local mercurial-repository-based package
"""
cli_name = 'hg'
def retrieve_binary(self):
|
def run(self):
"""
Updates the repository with remote changes
:return: False or error, or True on success
"""
binary = self.retrieve_binary()
if not binary:
return False
args = [binary]
args.extend(self.update_command)
args.appe... | """
Returns the path to the hg executable
:return: The string path to the executable or False on error
"""
name = 'hg'
if os.name == 'nt':
name += '.exe'
binary = self.find_binary(name)
if not binary:
show_error(
u'''
... | identifier_body |
hg_upgrader.py | import os
from ..cache import set_cache, get_cache
from ..show_error import show_error
from .vcs_upgrader import VcsUpgrader
class | (VcsUpgrader):
"""
Allows upgrading a local mercurial-repository-based package
"""
cli_name = 'hg'
def retrieve_binary(self):
"""
Returns the path to the hg executable
:return: The string path to the executable or False on error
"""
name = 'hg'
if... | HgUpgrader | identifier_name |
hg_upgrader.py | import os
from ..cache import set_cache, get_cache
from ..show_error import show_error
from .vcs_upgrader import VcsUpgrader
class HgUpgrader(VcsUpgrader):
"""
Allows upgrading a local mercurial-repository-based package
"""
cli_name = 'hg'
def retrieve_binary(self):
"""
Returns... |
def run(self):
"""
Updates the repository with remote changes
:return: False or error, or True on success
"""
binary = self.retrieve_binary()
if not binary:
return False
args = [binary]
args.extend(self.update_command)
args.appen... | )
return False
return binary | random_line_split |
hg_upgrader.py | import os
from ..cache import set_cache, get_cache
from ..show_error import show_error
from .vcs_upgrader import VcsUpgrader
class HgUpgrader(VcsUpgrader):
"""
Allows upgrading a local mercurial-repository-based package
"""
cli_name = 'hg'
def retrieve_binary(self):
"""
Returns... |
return output.strip()
| return False | conditional_block |
object_test.js | /*
* Copyright 2015 The Closure Compiler 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... | () {
assertTrue(Object.is(4, 4));
assertTrue(Object.is(0, 0));
assertTrue(Object.is('4', '4'));
assertTrue(Object.is('', ''));
assertTrue(Object.is(true, true));
assertTrue(Object.is(false, false));
assertTrue(Object.is(null, null));
assertTrue(Object.is(undefined, undefined));
asser... | testIs | identifier_name |
object_test.js | /*
* Copyright 2015 The Closure Compiler 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... | ,
testAssign_skipsNonEnumerableProperties() {
const from = {'b': 23};
try {
Object.defineProperty(from, 'a', {enumerable: false, value: 42});
} catch (err) {
return; // Object.defineProperty in IE8 test harness exists, always fails
}
assertDeepEquals({'b': 23}, Object.assign({}, from)... | {
if (!Object.create) return;
const proto = {a: 4, b: 5};
const from = Object.create(proto);
from.a = 6;
from.c = 7;
assertDeepEquals({a: 6, c: 7}, Object.assign({}, from));
assertDeepEquals({a: 6, b: 1, c: 7}, Object.assign({b: 1}, from));
} | identifier_body |
object_test.js | /*
* Copyright 2015 The Closure Compiler 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... | assertFalse(Object.is('', false));
}
}); | random_line_split | |
twitter-bot-detail.component.spec.ts | /* tslint:disable max-line-length */
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { JhiDateUtils, JhiDataUtils, JhiEventManager } from 'ng-jhipster'; | import { TwitterBot } from '../../../../../../main/webapp/app/entities/twitter-bot/twitter-bot.model';
describe('Component Tests', () => {
describe('TwitterBot Management Detail Component', () => {
let comp: TwitterBotDetailComponent;
let fixture: ComponentFixture<TwitterBotDetailComponent>;
... | import { GamecraftgatewayTestModule } from '../../../test.module';
import { MockActivatedRoute } from '../../../helpers/mock-route.service';
import { TwitterBotDetailComponent } from '../../../../../../main/webapp/app/entities/twitter-bot/twitter-bot-detail.component';
import { TwitterBotService } from '../../../../../... | random_line_split |
ar-IL.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... |
export default [
'ar-IL',
[['ص', 'م'], u, u],
[['ص', 'م'], u, ['صباحًا', 'مساءً']],
[
['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'],
[
'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس',
'الجمعة', 'السبت'
],
u, ['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت']
],
u,
[
[... | {
if (n === 0) return 0;
if (n === 1) return 1;
if (n === 2) return 2;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 3 && n % 100 <= 10) return 3;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 99) return 4;
return 5;
} | identifier_body |
ar-IL.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | (n: number): number {
if (n === 0) return 0;
if (n === 1) return 1;
if (n === 2) return 2;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 3 && n % 100 <= 10) return 3;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 99) return 4;
return 5;
}
export default [
'ar-IL',
[['ص', 'م'], ... | plural | identifier_name |
ar-IL.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | ],
u,
[
['ي', 'ف', 'م', 'أ', 'و', 'ن', 'ل', 'غ', 'س', 'ك', 'ب', 'د'],
[
'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو',
'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'
],
u
],
u,
[['ق.م', 'م'], u, ['قبل الميلاد', 'ميلادي']],
0,
[5, 6],
['d\u200f/M\u200f/y', 'd... | u, ['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'] | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.