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
addBzptCms.js
/** * cms 新增js */ $(document).ready(function(){ // 数据回显 if(bzptCmsId){ intaddBzptCms(bzptCmsId); } //保存 $("#btn_save").on("click",function(){ addBzptCms.saveData(); }); // //确认 // $("#btn_affirm").on("click",function(){ // addArchives.affirmData(); // }); //返回 $("#btn_back").on("click",function(...
}) } var addBzptCms = { /** * 表单校验 */ check : function(){ if($("#cms_type").val() == null || $("#cms_type").val() == "" || $("#cms_type").val() == undefined){ layer.alert("请选择信息类型"); return false; } if($("#title").val() == null || $("#title").val() == "" || $("#title").val() == undefined){ ...
zptCms/getDetail", data:{id : id}, dataType:"json", type:"post", success:function(res){ if(res.flag){ if(res.bzptCms){ var bzptCms = res.bzptCms; var content = bzptCms.content; $('.summernote').code(content); $('#cms_type').val(bzptCms.cmsType); $('#title').val(bzptCms.title); ...
identifier_body
addBzptCms.js
/** * cms 新增js */ $(document).ready(function(){ // 数据回显 if(bzptCmsId){ intaddBzptCms(bzptCmsId); } //保存 $("#btn_save").on("click",function(){ addBzptCms.saveData(); }); // //确认 // $("#btn_affirm").on("click",function(){ // addArchives.affirmData(); // }); //返回 $("#btn_back").on("click",function(...
失败"); } }, error:function(){ console.log("获取失败"); } }) } var addBzptCms = { /** * 表单校验 */ check : function(){ if($("#cms_type").val() == null || $("#cms_type").val() == "" || $("#cms_type").val() == undefined){ layer.alert("请选择信息类型"); return false; } if($("#title").val() == null ||...
; var content = bzptCms.content; $('.summernote').code(content); $('#cms_type').val(bzptCms.cmsType); $('#title').val(bzptCms.title); } } else { console.log("获取
conditional_block
forms.py
from django import forms from django.contrib.auth.models import Group from common.forms import ModelFormWithHelper from common.helpers import SubmitCancelFormHelper from community.constants import COMMUNITY_ADMIN from community.models import Community, CommunityPage from community.utils import get_groups from users.mo...
group = Group.objects.get(pk=pk) if not self.user.is_group_member(group.name): self.user.join_group(group)
conditional_block
forms.py
from django import forms from django.contrib.auth.models import Group from common.forms import ModelFormWithHelper from common.helpers import SubmitCancelFormHelper from community.constants import COMMUNITY_ADMIN from community.models import Community, CommunityPage from community.utils import get_groups from users.mo...
class AddCommunityPageForm(ModelFormWithHelper): """Form to create new CommunityPage. The author and the community of the page are expected to be provided when initializing the form: * author - currently logged in user, aka the author of the page * community - to which Community the CommunityPage be...
"""Form to edit Community profile""" class Meta: model = Community fields = ('name', 'slug', 'order', 'email', 'mailing_list', 'parent_community', 'website', 'facebook', 'googleplus', 'twitter') helper_class = SubmitCancelFormHelper helper_cancel_h...
identifier_body
forms.py
from django import forms from django.contrib.auth.models import Group from common.forms import ModelFormWithHelper from common.helpers import SubmitCancelFormHelper from community.constants import COMMUNITY_ADMIN from community.models import Community, CommunityPage from community.utils import get_groups from users.mo...
class AddCommunityPageForm(ModelFormWithHelper): """Form to create new CommunityPage. The author and the community of the page are expected to be provided when initializing the form: * author - currently logged in user, aka the author of the page * community - to which Community the CommunityPage belon...
"community.slug %}"
random_line_split
forms.py
from django import forms from django.contrib.auth.models import Group from common.forms import ModelFormWithHelper from common.helpers import SubmitCancelFormHelper from community.constants import COMMUNITY_ADMIN from community.models import Community, CommunityPage from community.utils import get_groups from users.mo...
(self, *args, **kwargs): self.author = kwargs.pop('author') self.community = kwargs.pop('community') super(AddCommunityPageForm, self).__init__(*args, **kwargs) def save(self, commit=True): """Override save to add author and community to the instance""" instance = super(AddC...
__init__
identifier_name
vm.rs
use crate::{builder, ffi, util, Value}; use std; use std::fmt; use libc; use std::sync::Mutex; /// A Ruby virtual machine. pub struct VM; /// We only want to be able to have one `VM` at a time. static mut VM_EXISTS: bool = false; lazy_static! { static ref ACTIVE_VM: Mutex<VM> = Mutex::new(VM::new().expect("fai...
else { ffi::rb_eval_string_wrap }; let result = unsafe { eval_fn(util::c_string(code).as_ptr(), &mut state) }; if state == 0 { Ok(Value::from(result)) } else { Err(ErrorKind::Exception(self.consume_exception())) } } } impl std::ops::Dro...
{ ffi::rb_eval_string_protect }
conditional_block
vm.rs
use crate::{builder, ffi, util, Value}; use std; use std::fmt; use libc; use std::sync::Mutex; /// A Ruby virtual machine. pub struct VM; /// We only want to be able to have one `VM` at a time. static mut VM_EXISTS: bool = false; lazy_static! { static ref ACTIVE_VM: Mutex<VM> = Mutex::new(VM::new().expect("fai...
} /// Gets the current receiver (can be `nil`). pub fn current_receiver(&self) -> Value { unsafe { Value::from(ffi::rb_current_receiver()) } } /// Raises an object and a message. pub fn raise(&self, value: Value, message: &str) -> ! { unsafe { ffi::rb_raise(value.0, util::c_str...
random_line_split
vm.rs
use crate::{builder, ffi, util, Value}; use std; use std::fmt; use libc; use std::sync::Mutex; /// A Ruby virtual machine. pub struct
; /// We only want to be able to have one `VM` at a time. static mut VM_EXISTS: bool = false; lazy_static! { static ref ACTIVE_VM: Mutex<VM> = Mutex::new(VM::new().expect("failed to create Ruby VM")); } // TODO: // Implement hooked variables (rb_define_hooked_variable) // Allows a callback to get/set variable ...
VM
identifier_name
windows.py
from __future__ import division from PyQt5 import QtCore, QtWidgets from pycho.gui.widgets import GLPlotWidget from pycho.world.navigation import DIRECTIONS from pycho.gui.interaction import QT_KEYS, is_left, is_right, is_up, is_down from pycho.world.helpers import box_around import logging xrange = range TURN_BA...
def keyPressEvent(self, event): self._current_handler(self.key_press_handlers)(self, event) def mousePressEvent(self, event): self._current_handler(self.mouse_click_handlers)(self, event) def mouseReleaseEvent(self, event): self._current_handler(self.mouse_release_handlers)(self,...
for timer, time in zip(self.timers, self.timer_times): self.timers.start(time) self.is_paused = False
identifier_body
windows.py
from __future__ import division from PyQt5 import QtCore, QtWidgets from pycho.gui.widgets import GLPlotWidget from pycho.world.navigation import DIRECTIONS from pycho.gui.interaction import QT_KEYS, is_left, is_right, is_up, is_down from pycho.world.helpers import box_around import logging xrange = range TURN_BA...
(self, handlers): level_id = self.game.world.current_level.id if level_id not in handlers: try: return handlers['*'] except KeyError: logging.error('No default handler set as *!') return handlers[level_id] def _defaultMousePressHandl...
_current_handler
identifier_name
windows.py
from __future__ import division from PyQt5 import QtCore, QtWidgets from pycho.gui.widgets import GLPlotWidget from pycho.world.navigation import DIRECTIONS from pycho.gui.interaction import QT_KEYS, is_left, is_right, is_up, is_down from pycho.world.helpers import box_around import logging xrange = range TURN_BA...
self.callbacks = [self.widget.updateGL, self.game.world.clean_up, self.game.world.tick] QtCore.QMetaObject.connectSlotsByName(self) self.paint_timer.start(30, self) self.clean_timer.start(40, self) self.timers = [self.paint_timer, self.clean_timer] self.timer_ti...
self.tick_timer = QtCore.QBasicTimer()
random_line_split
windows.py
from __future__ import division from PyQt5 import QtCore, QtWidgets from pycho.gui.widgets import GLPlotWidget from pycho.world.navigation import DIRECTIONS from pycho.gui.interaction import QT_KEYS, is_left, is_right, is_up, is_down from pycho.world.helpers import box_around import logging xrange = range TURN_BA...
logging.debug('Face movement set to {}'.format(face_movement)) logging.debug('Player is facing {}'.format(self.game.player.facing)) self.game.player.facing = face_movement self.game.world.tick() def map_point_to_game_world(self, x, y): i = int((x / self.widget.width) * se...
return
conditional_block
nucleomediaMoeda.js
nucleomediaApi.controller('moedaCtrl', ['$scope', 'nucleomediaRequest', function ($scope, nucleomediaRequest) { var rootScope = $scope.$root; rootScope.moedas = []; rootScope.carregarMoeda = function (idMoeda) { url = "http://localhost:8080/getMoeda?" + idMoeda + "&cachebuster=" + RandomNumber(); ...
}]);
{ moeda.dataAtualizacao = new Date(moeda.dataAtualizacao); moeda.variacao = parseFloat(moeda.variacao.replace(",", ".")).toPrecision(2); return moeda; }
identifier_body
nucleomediaMoeda.js
nucleomediaApi.controller('moedaCtrl', ['$scope', 'nucleomediaRequest', function ($scope, nucleomediaRequest) { var rootScope = $scope.$root; rootScope.moedas = []; rootScope.carregarMoeda = function (idMoeda) { url = "http://localhost:8080/getMoeda?" + idMoeda + "&cachebuster=" + RandomNumber(); ...
nucleomediaRequest.get(url, carregarComplete); }; rootScope.carregarMoeda(1); rootScope.carregarMoeda(2); function carregarComplete(result) { NormalizaJson(result.moedas.moeda); rootScope.moedas.push(ConverteTipos(result.moedas.moeda)); console.log(rootScope.moedas)...
{ url = "content/moeda_" + idMoeda + "_offline.xml?cachebuster=" + RandomNumber(); }
conditional_block
nucleomediaMoeda.js
nucleomediaApi.controller('moedaCtrl', ['$scope', 'nucleomediaRequest', function ($scope, nucleomediaRequest) { var rootScope = $scope.$root; rootScope.moedas = []; rootScope.carregarMoeda = function (idMoeda) { url = "http://localhost:8080/getMoeda?" + idMoeda + "&cachebuster=" + RandomNumber(); ...
}]);
random_line_split
nucleomediaMoeda.js
nucleomediaApi.controller('moedaCtrl', ['$scope', 'nucleomediaRequest', function ($scope, nucleomediaRequest) { var rootScope = $scope.$root; rootScope.moedas = []; rootScope.carregarMoeda = function (idMoeda) { url = "http://localhost:8080/getMoeda?" + idMoeda + "&cachebuster=" + RandomNumber(); ...
(result) { NormalizaJson(result.moedas.moeda); rootScope.moedas.push(ConverteTipos(result.moedas.moeda)); console.log(rootScope.moedas) } function ConverteTipos(moeda) { moeda.dataAtualizacao = new Date(moeda.dataAtualizacao); moeda.variacao = parseFloat(moeda.variac...
carregarComplete
identifier_name
_post.js
return this.get('deleted_by'); }.property('firstPost', 'deleted_by', 'topic.deleted_by'), postDeletedAt: function() { if (this.get('firstPost')) { return this.get('topic.deleted_at'); } return this.get('deleted_at'); }.property('firstPost', 'deleted_at', 'topic.deleted_at'), url: function() { ...
{ return this.get('topic.deleted_by'); }
conditional_block
_post.js
init: function() { this.set('replyHistory', []); }, shareUrl: function() { var user = Discourse.User.current(); var userSuffix = user ? '?u=' + user.get('username_lower') : ''; if (this.get('firstPost')) { return this.get('topic.url') + userSuffix; } else { return this.get('url')...
@module Discourse **/ Discourse.Post = Discourse.Model.extend({
random_line_split
gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ // https://github.com/ck86/main-bower-files#usage-with-grunt bower: { dev: { dest: 'components/bower', options: { checkExistence: true, debugging: true } } }, sass: { dev: { o...
sourcemap: 'none' }, files: { 'components/scss/style.css': 'components/scss/style.scss' // 'destination': 'source' } }, dist: { options: { style: 'compressed', lineNumbers: false, sourcemap: 'none' }, files: { ...
style: 'compressed', // nested, compact, compressed, expanded // https://github.com/gruntjs/grunt-contrib-sass#linenumbers lineNumbers: true,
random_line_split
test_exception_sink_integration.py
import os import signal import time from contextlib import contextmanager from pants.base.build_environment import get_buildroot from pants.base.exception_sink import ExceptionSink from pants.util.contextutil import temporary_dir from pants.util.dirutil import read_file, safe_file_dump, safe_mkdir, touch from pants_te...
pid_specific_log_file, shared_log_file = self._get_log_file_paths(tmpdir, pants_run) self._assert_unhandled_exception_log_matches( pants_run.pid, read_file(pid_specific_log_file)) self._assert_unhandled_exception_log_matches( pants_run.pid, read_file(shared_log_file)) def _assert_gr...
Exception caught: \\(pants\\.engine\\.scheduler\\.ExecutionError\\) \\(backtrace omitted\\) Exception message: 1 Exception encountered: ResolveError: "this-target-does-not-exist" was not found in namespace ""\\. Did you mean one of: """)
random_line_split
test_exception_sink_integration.py
import os import signal import time from contextlib import contextmanager from pants.base.build_environment import get_buildroot from pants.base.exception_sink import ExceptionSink from pants.util.contextutil import temporary_dir from pants.util.dirutil import read_file, safe_file_dump, safe_mkdir, touch from pants_te...
def test_dumps_traceback_on_sigabrt(self): # SIGABRT sends a traceback to the log file for the current process thanks to # faulthandler.enable(). with self._send_signal_to_waiter_handle(signal.SIGABRT) as (workdir, waiter_run): # Check that the logs show an abort signal and the beginning of a trac...
with self._send_signal_to_waiter_handle(signum) as (workdir, waiter_run): assertRegex(self, waiter_run.stderr_data, """\ timestamp: ([^\n]+) Signal {signum} \\({signame}\\) was raised\\. Exiting with failure\\. """.format(signum=signum, signame=signame)) # Check that the logs show a graceful exit by SIG...
conditional_block
test_exception_sink_integration.py
import os import signal import time from contextlib import contextmanager from pants.base.build_environment import get_buildroot from pants.base.exception_sink import ExceptionSink from pants.util.contextutil import temporary_dir from pants.util.dirutil import read_file, safe_file_dump, safe_mkdir, touch from pants_te...
(self): """Send signals which are handled, but don't get converted into a KeyboardInterrupt.""" signal_names = { signal.SIGQUIT: 'SIGQUIT', signal.SIGTERM: 'SIGTERM', } for (signum, signame) in signal_names.items(): with self._send_signal_to_waiter_handle(signum) as (workdir, waiter_ru...
test_dumps_logs_on_signal
identifier_name
test_exception_sink_integration.py
import os import signal import time from contextlib import contextmanager from pants.base.build_environment import get_buildroot from pants.base.exception_sink import ExceptionSink from pants.util.contextutil import temporary_dir from pants.util.dirutil import read_file, safe_file_dump, safe_mkdir, touch from pants_te...
def test_keyboardinterrupt(self): with self._send_signal_to_waiter_handle(signal.SIGINT) as (_, waiter_run): self.assertIn( 'Interrupted by user:\nUser interrupted execution with control-c!', waiter_run.stderr_data) def _lifecycle_stub_cmdline(self): # Load the testprojects pants-pl...
with self._make_waiter_handle() as (workdir, pid, join): # Send SIGUSR2, then sleep so the signal handler from faulthandler.register() can run. os.kill(pid, signal.SIGUSR2) time.sleep(1) waiter_run = join() self.assert_success(waiter_run) assertRegex(self, waiter_run.stderr_data, ""...
identifier_body
kinematic2.rs
extern crate nalgebra as na; use na::{Point2, RealField, Vector2}; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::{DefaultJointConstraintSet, RevoluteJoint}; use nphysics2d::math::Velocity; use nphysics2d::object::{ Body, BodyPa...
}); /* * Run the simulation. */ testbed.set_ground_handle(Some(ground_handle)); testbed.set_world( mechanical_world, geometrical_world, bodies, colliders, joint_constraints, force_generators, ); testbed.look_at(Point2::new(0.0, 5.0), 60...
{ let platform_x = platform.position().translation.vector.x; let mut vel = *platform.velocity(); vel.linear.y = (time * r!(5.0)).sin() * r!(0.8); if platform_x >= rad * r!(10.0) { vel.linear.x = r!(-1.0); } if platform_x <= -rad *...
conditional_block
kinematic2.rs
extern crate nalgebra as na; use na::{Point2, RealField, Vector2}; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::{DefaultJointConstraintSet, RevoluteJoint}; use nphysics2d::math::Velocity; use nphysics2d::object::{ Body, BodyPa...
.build(BodyPartHandle(ground_handle, 0)); colliders.insert(co); /* * Create boxes */ let num = 10; let rad = r!(0.2); let cuboid = ShapeHandle::new(Cuboid::new(Vector2::repeat(rad))); let collider_desc = ColliderDesc::new(cuboid.clone()).density(r!(1.0)); let shift = (ra...
{ /* * World */ let mechanical_world = DefaultMechanicalWorld::new(Vector2::new(r!(0.0), r!(-9.81))); let geometrical_world = DefaultGeometricalWorld::new(); let mut bodies = DefaultBodySet::new(); let mut colliders = DefaultColliderSet::new(); let joint_constraints = DefaultJointConst...
identifier_body
kinematic2.rs
extern crate nalgebra as na; use na::{Point2, RealField, Vector2}; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::{DefaultJointConstraintSet, RevoluteJoint}; use nphysics2d::math::Velocity; use nphysics2d::object::{ Body, BodyPa...
() { let testbed = Testbed::<f32>::from_builders(0, vec![("Kinematic body", init_world)]); testbed.run() }
main
identifier_name
kinematic2.rs
extern crate nalgebra as na; use na::{Point2, RealField, Vector2}; use ncollide2d::shape::{Ball, Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::{DefaultJointConstraintSet, RevoluteJoint}; use nphysics2d::math::Velocity; use nphysics2d::object::{ Body, BodyPa...
* Setup a kinematic multibody. */ let joint = RevoluteJoint::new(r!(0.0)); let mut mb = MultibodyDesc::new(joint) .body_shift(Vector2::x() * r!(2.0)) .parent_shift(Vector2::new(r!(5.0), r!(2.0))) .build(); mb.set_status(BodyStatus::Kinematic); mb.generalized_velocity_...
/*
random_line_split
importHelpersInAmbientContext.ts
// @importHelpers: true // @target: es5 // @filename: a.d.ts export { }; // Extends declare class C { } declare class D extends C { } // Destructuring interface I { ({descendants, read}?: { descendants?: boolean; read?: any; }): any; } // Object Rest interface Foo { ...
a: number; b: string; } export var { a, ...x } : Foo; } // @filename: tslib.d.ts export declare function __extends(d: Function, b: Function): void; export declare function __assign(t: any, ...sources: any[]): any; export declare function __decorate(decorators: Function[], target: any, key?: string | symbol...
// Object Rest interface Foo {
random_line_split
importHelpersInAmbientContext.ts
// @importHelpers: true // @target: es5 // @filename: a.d.ts export { }; // Extends declare class
{ } declare class D extends C { } // Destructuring interface I { ({descendants, read}?: { descendants?: boolean; read?: any; }): any; } // Object Rest interface Foo { a: number; b: string; } export var { a, ...x } : Foo; // @filename: b.ts export {}; declare namespac...
C
identifier_name
authors_typeahead.js
/* * This file is part of INSPIRE. * Copyright (C) 2015 CERN. * * INSPIRE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ...
'jquery', 'js/jquery_plugin', ], function($, jQueryPlugin) { function AuthorsTypeahead($element) { this.dataEngine = new Bloodhound({ name: 'authors', remote: { url: '/search?cc=HepNames&p=author:%QUERY*&of=recjson&rg=100', filter: function(response) { return $.map(resp...
define([
random_line_split
authors_typeahead.js
/* * This file is part of INSPIRE. * Copyright (C) 2015 CERN. * * INSPIRE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ...
var suggestionTemplate = Hogan.compile( '<strong>{{ full_name }}</strong><br>' ); this.$element.typeahead({ minLength: 3 }, { // after typeahead upgrade to 0.11 can be substituted with: // source: this.engine.ttAdapter(), // https://github.com/twitter/typeahead.js/issues/1...
{ this.dataEngine = new Bloodhound({ name: 'authors', remote: { url: '/search?cc=HepNames&p=author:%QUERY*&of=recjson&rg=100', filter: function(response) { return $.map(response, function(item, idx) { return item.authors; }); } }, datu...
identifier_body
authors_typeahead.js
/* * This file is part of INSPIRE. * Copyright (C) 2015 CERN. * * INSPIRE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ...
($element) { this.dataEngine = new Bloodhound({ name: 'authors', remote: { url: '/search?cc=HepNames&p=author:%QUERY*&of=recjson&rg=100', filter: function(response) { return $.map(response, function(item, idx) { return item.authors; }); } },...
AuthorsTypeahead
identifier_name
test.py
#! /usr/bin/env python # encoding:utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import logging import random import multiprocessing import numpy as np import sklearn from sklearn.naive_bayes import MultinomialNB from sklearn.cross_validation import train_test_split from sklearn.feature_...
print data return data, len(data) def split_data(data, data_label, size=0.2, random=0): train, test, train_label, test_label = train_test_split(data, data_label, test_size=size, random_state=random) return train, test, train_label, test_label def naive_bayes_classifier(train_x, train_y)...
random_line_split
test.py
#! /usr/bin/env python # encoding:utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import logging import random import multiprocessing import numpy as np import sklearn from sklearn.naive_bayes import MultinomialNB from sklearn.cross_validation import train_test_split from sklearn.feature_...
(n,m): # global n, m # load data pos, pos_size = load_data('pos.txt') neg, neg_size = load_data('neg.txt') data = pos + neg #generate labels of pos and neg label = [1] * pos_size + [0] * neg_size #vectorize list==>ndarray vector = Tfidf(data) # split data,trai...
main
identifier_name
test.py
#! /usr/bin/env python # encoding:utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import logging import random import multiprocessing import numpy as np import sklearn from sklearn.naive_bayes import MultinomialNB from sklearn.cross_validation import train_test_split from sklearn.feature_...
def split_data(data, data_label, size=0.2, random=0): train, test, train_label, test_label = train_test_split(data, data_label, test_size=size, random_state=random) return train, test, train_label, test_label def naive_bayes_classifier(train_x, train_y): model = MultinomialNB() model....
data = open(filename, 'r').readlines() #datat is a list for data in data: print data return data, len(data)
identifier_body
test.py
#! /usr/bin/env python # encoding:utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import logging import random import multiprocessing import numpy as np import sklearn from sklearn.naive_bayes import MultinomialNB from sklearn.cross_validation import train_test_split from sklearn.feature_...
else: return max(pro_1), 1, unsplit def main(n,m): # global n, m # load data pos, pos_size = load_data('pos.txt') neg, neg_size = load_data('neg.txt') data = pos + neg #generate labels of pos and neg label = [1] * pos_size + [0] * neg_size #vectori...
return max(pro_0), 0, unsplit
conditional_block
test_ols_sparse.py
import unittest import numpy as np import pysal import pysal.spreg as EC from scipy import sparse from pysal.common import RTOL PEGP = pysal.examples.get_path class
(unittest.TestCase): def setUp(self): db = pysal.open(PEGP('columbus.dbf'),'r') y = np.array(db.by_col("HOVAL")) self.y = np.reshape(y, (49,1)) X = [] X.append(db.by_col("INC")) X.append(db.by_col("CRIME")) self.X = np.array(X).T self.w = pysal.weights...
TestBaseOLS
identifier_name
test_ols_sparse.py
import unittest import numpy as np import pysal import pysal.spreg as EC from scipy import sparse from pysal.common import RTOL PEGP = pysal.examples.get_path class TestBaseOLS(unittest.TestCase): def setUp(self): db = pysal.open(PEGP('columbus.dbf'),'r') y = np.array(db.by_col("HOVAL")) s...
np.testing.assert_allclose(ols.lm_error, \ (4.1508117035117893, 0.041614570655392716),RTOL) np.testing.assert_allclose(ols.lm_lag, \ (0.98279980617162233, 0.32150855529063727),RTOL) np.testing.assert_allclose(ols.lm_sarma, \ (4.3222725729143736, 0.1151941...
np.testing.assert_allclose(ols.koenker_bassett[key], kb[key],RTOL)
conditional_block
test_ols_sparse.py
import unittest import numpy as np import pysal import pysal.spreg as EC from scipy import sparse from pysal.common import RTOL PEGP = pysal.examples.get_path class TestBaseOLS(unittest.TestCase): def setUp(self): db = pysal.open(PEGP('columbus.dbf'),'r') y = np.array(db.by_col("HOVAL")) s...
kb = {'df': 2, 'kb': 2.2700383871478675, 'pvalue': 0.32141595215434604} for key in kb: np.testing.assert_allclose(ols.koenker_bassett[key], kb[key],RTOL) np.testing.assert_allclose(ols.lm_error, \ (4.1508117035117893, 0.041614570655392716),RTOL) np.testing.assert...
white = np.array([5, 2.90606708, 0.71446484]) ols_white = np.array([ols.white['df'], ols.white['wh'], ols.white['pvalue']]) np.testing.assert_allclose(ols_white,white,RTOL) np.testing.assert_equal(ols.k, 3)
random_line_split
test_ols_sparse.py
import unittest import numpy as np import pysal import pysal.spreg as EC from scipy import sparse from pysal.common import RTOL PEGP = pysal.examples.get_path class TestBaseOLS(unittest.TestCase): def setUp(self): db = pysal.open(PEGP('columbus.dbf'),'r') y = np.array(db.by_col("HOVAL")) s...
def test_OLS(self): self.X = sparse.csr_matrix(self.X) ols = EC.OLS(self.y, self.X, self.w, spat_diag=True, moran=True, \ name_y='home value', name_x=['income','crime'], \ name_ds='columbus', nonspat_diag=True, white_test=True) np.testing.assert_all...
self.X = np.hstack((np.ones(self.y.shape),self.X)) self.X = sparse.csr_matrix(self.X) ols = EC.ols.BaseOLS(self.y,self.X) np.testing.assert_allclose(ols.betas, np.array([[ 46.42818268], [ 0.62898397], [ -0.48488854]])) vm = np.array([[ 1.74022453e+02, -6.52060364e+00, -2....
identifier_body
test_verifier.py
# -*- coding: utf-8 -*- import unittest import json from api_health.verifier import Verifier class JsonVerifier(unittest.TestCase): def test_constructor_should_be_smart_about_params(self): simple_json = u'{ "foo": "bar" }' json_dict = json.loads(simple_json) try: v1 = Verifier(...
self.assertTrue(v2.has_property('foo')) def test_should_check_for_json_property(self): simple_json = u'{ "foo": "bar" }' verifier = Verifier(simple_json) self.assertTrue(verifier.has_property('foo')) self.assertTrue(verifier.does_not_have_property('bu')) self.assertF...
self.fail('Verifier() constructor should deal with both ' 'string and object json') self.assertTrue(v1.has_property('foo'))
random_line_split
test_verifier.py
# -*- coding: utf-8 -*- import unittest import json from api_health.verifier import Verifier class JsonVerifier(unittest.TestCase): def test_constructor_should_be_smart_about_params(self):
def test_should_check_for_json_property(self): simple_json = u'{ "foo": "bar" }' verifier = Verifier(simple_json) self.assertTrue(verifier.has_property('foo')) self.assertTrue(verifier.does_not_have_property('bu')) self.assertFalse(verifier.has_property('bleh')) def te...
simple_json = u'{ "foo": "bar" }' json_dict = json.loads(simple_json) try: v1 = Verifier(simple_json) v2 = Verifier(json_dict) except: self.fail('Verifier() constructor should deal with both ' 'string and object json') self.assertT...
identifier_body
test_verifier.py
# -*- coding: utf-8 -*- import unittest import json from api_health.verifier import Verifier class JsonVerifier(unittest.TestCase): def test_constructor_should_be_smart_about_params(self): simple_json = u'{ "foo": "bar" }' json_dict = json.loads(simple_json) try: v1 = Verifier(...
(self): simple_json = u'{ "foo": "bar" }' verifier = Verifier(simple_json) self.assertTrue(verifier.has_property('foo')) self.assertTrue(verifier.does_not_have_property('bu')) self.assertFalse(verifier.has_property('bleh')) def test_should_check_arrays(self): array_j...
test_should_check_for_json_property
identifier_name
table.js
/* * Copyright (C) eZ Systems AS. All rights reserved. * For full copyright and license information view LICENSE file distributed with this source code. */ // **NOTICE:** // THIS IS AN AUTO-GENERATED FILE // DO YOUR MODIFICATIONS IN THE CORRESPONDING .jsx FILE // AND REGENERATE IT WITH: grunt jsx // END OF NOTICE YU...
key: 'eztable' }, render: function () { if (this.props.renderExclusive) { return ( React.createElement(AlloyEditor.ButtonTableEdit, React.__spread({}, this.props)) ); } var css = "ae-button ez-ae-label...
statics: {
random_line_split
table.js
/* * Copyright (C) eZ Systems AS. All rights reserved. * For full copyright and license information view LICENSE file distributed with this source code. */ // **NOTICE:** // THIS IS AN AUTO-GENERATED FILE // DO YOUR MODIFICATIONS IN THE CORRESPONDING .jsx FILE // AND REGENERATE IT WITH: grunt jsx // END OF NOTICE YU...
var css = "ae-button ez-ae-labeled-button"; return ( React.createElement("button", {className: css, onClick: this.props.requestExclusive, tabIndex: this.props.tabIndex}, React.createElement("span", {className: "ez-ae-icon ez-ae-icon-table ae-icon-table"}),...
{ return ( React.createElement(AlloyEditor.ButtonTableEdit, React.__spread({}, this.props)) ); }
conditional_block
vieweditor.container.js
/* @flow */ import { bindActionCreators } from 'redux'; import React from 'react'; import Select from 'react-select'; import { connect } from 'react-redux'; import {map} from 'lodash'; import { getAllBoards } from '../../data/boards'; import {addView} from '../../actions/views'; import {container, form, formLabel, form...
} constructor(props: any) { super(props); this.state = { name: '', selectedBoards: [], }; } buildView() { let {addView: _addView, switchPageToSearch: _switchViewToSearch} = this.props; let {name, selectedBoards} = this.state; let ...
this.setState({name});
random_line_split
google.py
from base import Input from wapiti import get_json class GoogleNews(Input): prefix = 'gn' def fetch(self): return get_json('http://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=' + self.page_title)
else: return super(GoogleNews, self).process(f_res['responseData']['cursor']['estimatedResultCount']) stats = { 'count': lambda f: f } class GoogleSearch(Input): prefix = 'gs' def fetch(self): return get_json('http://ajax.googleapis.com/ajax/services/search/web?v=...
def process(self, f_res): if f_res['responseStatus'] == 403 or not f_res.get('responseData', {}).get('cursor', {}).get('estimatedResultCount', {}): return {}
random_line_split
google.py
from base import Input from wapiti import get_json class GoogleNews(Input): prefix = 'gn' def fetch(self): return get_json('http://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=' + self.page_title) def process(self, f_res): if f_res['responseStatus'] == 403 or not f_res.get('resp...
(Input): prefix = 'gs' def fetch(self): return get_json('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' + self.page_title) def process(self, f_res): if f_res['responseStatus'] == 403 or not f_res['responseData']: return {} else: return super(G...
GoogleSearch
identifier_name
google.py
from base import Input from wapiti import get_json class GoogleNews(Input): prefix = 'gn' def fetch(self): return get_json('http://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=' + self.page_title) def process(self, f_res): if f_res['responseStatus'] == 403 or not f_res.get('resp...
stats = { 'count': lambda f: f }
if f_res['responseStatus'] == 403 or not f_res['responseData']: return {} else: return super(GoogleSearch, self).process(f_res['responseData']['cursor']['estimatedResultCount'])
identifier_body
google.py
from base import Input from wapiti import get_json class GoogleNews(Input): prefix = 'gn' def fetch(self): return get_json('http://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=' + self.page_title) def process(self, f_res): if f_res['responseStatus'] == 403 or not f_res.get('resp...
stats = { 'count': lambda f: f } class GoogleSearch(Input): prefix = 'gs' def fetch(self): return get_json('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' + self.page_title) def process(self, f_res): if f_res['responseStatus'] == 403 or not f_res['respons...
return super(GoogleNews, self).process(f_res['responseData']['cursor']['estimatedResultCount'])
conditional_block
Sound.ts
/// <reference no-default-lib="true"/> /// <reference path="../../CloudParty.d.ts" /> /* * The Sound script will play a sound file a set time after the scene starts. * * Paramters and Customizers * ------------------------------------------- * Delay (Number) * - The time, in seconds, after the scene starts that ...
name: 'playSound', channel: 'SceneControl', message: 'start', script: 'playSound' }); var playing = false; function playSound() { if ( playing === true ) { playing = false; soundStop( 'Sound' ); } playing = true; if ( delay === 0 ) { doPlaySound(); } else...
var max = min + getParam( 'Drop Off' ); // Start the sound track handlerCreate( {
random_line_split
Sound.ts
/// <reference no-default-lib="true"/> /// <reference path="../../CloudParty.d.ts" /> /* * The Sound script will play a sound file a set time after the scene starts. * * Paramters and Customizers * ------------------------------------------- * Delay (Number) * - The time, in seconds, after the scene starts that ...
}
{ playing = false; soundStop( 'Sound' ); }
conditional_block
Sound.ts
/// <reference no-default-lib="true"/> /// <reference path="../../CloudParty.d.ts" /> /* * The Sound script will play a sound file a set time after the scene starts. * * Paramters and Customizers * ------------------------------------------- * Delay (Number) * - The time, in seconds, after the scene starts that ...
{ if ( playing === true ) { playing = false; soundStop( 'Sound' ); } }
identifier_body
Sound.ts
/// <reference no-default-lib="true"/> /// <reference path="../../CloudParty.d.ts" /> /* * The Sound script will play a sound file a set time after the scene starts. * * Paramters and Customizers * ------------------------------------------- * Delay (Number) * - The time, in seconds, after the scene starts that ...
( event ) { if ( playing === true ) { playing = false; soundStop( 'Sound' ); } }
endSound
identifier_name
lib.rs
// Copyright 2014 The Servo Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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 http://opensource.org/licenses/MIT>, at ...
pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("atom", atom::expand_atom); reg.register_macro("ns", atom::expand_ns); }
// NB: This needs to be public or we get a linker error. #[plugin_registrar]
random_line_split
lib.rs
// Copyright 2014 The Servo Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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 http://opensource.org/licenses/MIT>, at ...
(reg: &mut Registry) { reg.register_macro("atom", atom::expand_atom); reg.register_macro("ns", atom::expand_ns); }
plugin_registrar
identifier_name
lib.rs
// Copyright 2014 The Servo Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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 http://opensource.org/licenses/MIT>, at ...
{ reg.register_macro("atom", atom::expand_atom); reg.register_macro("ns", atom::expand_ns); }
identifier_body
flv.d.ts
/* * Copyright (C) 2016 Bilibili. All Rights Reserved. * * @author zheng qian <xqq@xqq.im> * * 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/LICE...
type: string; buffered: TimeRanges; duration: number; volume: number; muted: boolean; currentTime: number; mediaInfo: Object; statisticsInfo: Object; } interface FlvPlayer extends Player { } interface NativePlayer extends Player { } ...
load(): void; unload(): void; play(): void; pause(): void;
random_line_split
mxCompositeLayout.js
/** * $Id: mxCompositeLayout.js,v 1.11 2010-01-02 09:45:15 gaudenz Exp $ * Copyright (c) 2006-2010, JGraph Ltd */ /** * Class: mxCompositeLayout * * Allows to compose multiple layouts into a single layout. The master layout * is the layout that handles move operations if another layout than the first * element...
}; /** * Function: execute * * Implements <mxGraphLayout.execute> by executing all <layouts> in a * single transaction. */ mxCompositeLayout.prototype.execute = function(parent) { var model = this.graph.getModel(); model.beginUpdate(); try { for (var i = 0; i < this.layouts.length; i++) { this.layo...
{ this.layouts[0].move.apply(this.layouts[0], arguments); }
conditional_block
mxCompositeLayout.js
/** * $Id: mxCompositeLayout.js,v 1.11 2010-01-02 09:45:15 gaudenz Exp $ * Copyright (c) 2006-2010, JGraph Ltd */ /** * Class: mxCompositeLayout * * Allows to compose multiple layouts into a single layout. The master layout * is the layout that handles move operations if another layout than the first * element...
; /** * Extends mxGraphLayout. */ mxCompositeLayout.prototype = new mxGraphLayout(); mxCompositeLayout.prototype.constructor = mxCompositeLayout; /** * Variable: layouts * * Holds the array of <mxGraphLayouts> that this layout contains. */ mxCompositeLayout.prototype.layouts = null; /** * Variable: layouts ...
{ mxGraphLayout.call(this, graph); this.layouts = layouts; this.master = master; }
identifier_body
mxCompositeLayout.js
/** * $Id: mxCompositeLayout.js,v 1.11 2010-01-02 09:45:15 gaudenz Exp $ * Copyright (c) 2006-2010, JGraph Ltd */ /** * Class: mxCompositeLayout * * Allows to compose multiple layouts into a single layout. The master layout * is the layout that handles move operations if another layout than the first * element...
(graph, layouts, master) { mxGraphLayout.call(this, graph); this.layouts = layouts; this.master = master; }; /** * Extends mxGraphLayout. */ mxCompositeLayout.prototype = new mxGraphLayout(); mxCompositeLayout.prototype.constructor = mxCompositeLayout; /** * Variable: layouts * * Holds the array of <mxGraph...
mxCompositeLayout
identifier_name
mxCompositeLayout.js
/** * $Id: mxCompositeLayout.js,v 1.11 2010-01-02 09:45:15 gaudenz Exp $ * Copyright (c) 2006-2010, JGraph Ltd */ /** * Class: mxCompositeLayout * * Allows to compose multiple layouts into a single layout. The master layout * is the layout that handles move operations if another layout than the first * element...
*/ mxCompositeLayout.prototype.layouts = null; /** * Variable: layouts * * Reference to the <mxGraphLayouts> that handles moves. If this is null * then the first layout in <layouts> is used. */ mxCompositeLayout.prototype.master = null; /** * Function: moveCell * * Implements <mxGraphLayout.moveCell> by ca...
random_line_split
hig__button-tests.tsx
import * as React from 'react'; import Button, { targets, types, widths, AvailableTargets, AvailableTypes, AvailableWidths } from '@hig/button';
const link = ''; const onClick = emptyFunc; const onBlur = emptyFunc; const onFocus = emptyFunc; const onHover = emptyFunc; const onMouseDown = emptyFunc; const onMouseEnter = emptyFunc; const onMouseLeave = emptyFunc; const onMouseUp = emptyFunc; const stylesheet = emptyFunc; const target = targets.BLANK; const title ...
/** Button */ const emptyFunc = () => {}; const disabled = true; const icon = <div />;
random_line_split
blake2xb.rs
use core::cmp::{min}; use {Blake2b, Hash, ParameterBlock}; use slice_ext::{SliceExt}; use unbuffered; #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub struct Blake2xb { blake2b: Blake2b, parameter_block: ParameterBlock, len: u32, } pub struct Iter { parameter_block: ParameterBlock, block: [u64; 16], block...
(&self) -> usize { self.len as usize } pub fn update(&mut self, data: &[u8]) { self.blake2b.update(data); } pub fn finish(self) -> Iter { let mut block = [0; 16]; block[..8].copy_from_slice(&self.blake2b.finish().into_inner()); let parameter_block = self.parameter_block .set_key_len(0) .set_fanou...
len
identifier_name
blake2xb.rs
use core::cmp::{min}; use {Blake2b, Hash, ParameterBlock}; use slice_ext::{SliceExt}; use unbuffered; #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub struct Blake2xb { blake2b: Blake2b, parameter_block: ParameterBlock, len: u32, } pub struct Iter { parameter_block: ParameterBlock, block: [u64; 16], block...
else { 0 }; (i, Some(i)) } }
{ 1 }
conditional_block
blake2xb.rs
use core::cmp::{min}; use {Blake2b, Hash, ParameterBlock}; use slice_ext::{SliceExt}; use unbuffered; #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub struct Blake2xb { blake2b: Blake2b, parameter_block: ParameterBlock, len: u32, } pub struct Iter { parameter_block: ParameterBlock, block: [u64; 16], block...
Self::with_parameter_block_keyed(len, key, parameter_block) } pub fn with_parameter_block_keyed(len: Option<u32>, key: &[u8], parameter_block: ParameterBlock) -> Self { assert!(len.map(|len| len != 0 && len != u32::max_value()).unwrap_or(true), "len must be >= 1 and <= 2^32 - 2"); Blake2xb { blake2b: Blake...
random_line_split
lib.rs
#![cfg(test)] use ::rand::Rng; use bincode_1::Options; mod membership; mod misc; mod rand; mod sway; pub fn test_same_with_config<T, C, O>(t: &T, bincode_1_options: O, bincode_2_config: C) where T: bincode_2::Encode + bincode_2::Decode + serde::Serialize + serde::de::DeserializeOwned ...
&t, bincode_1::options() .with_little_endian() .with_varint_encoding(), bincode_2::config::legacy() .with_little_endian() .with_variable_int_encoding(), ); test_same_with_config( &t, bincode_1::options() .with_bi...
{ test_same_with_config( &t, // This is the config used internally by bincode 1 bincode_1::options().with_fixint_encoding(), // Should match `::legacy()` bincode_2::config::legacy(), ); // Check a bunch of different configs: test_same_with_config( &t, ...
identifier_body
lib.rs
#![cfg(test)] use ::rand::Rng; use bincode_1::Options; mod membership; mod misc; mod rand; mod sway; pub fn test_same_with_config<T, C, O>(t: &T, bincode_1_options: O, bincode_2_config: C) where T: bincode_2::Encode + bincode_2::Decode + serde::Serialize + serde::de::DeserializeOwned ...
.with_big_endian() .with_variable_int_encoding(), ); test_same_with_config( &t, bincode_1::options() .with_little_endian() .with_varint_encoding(), bincode_2::config::legacy() .with_little_endian() .with_variable_int...
bincode_2::config::legacy()
random_line_split
lib.rs
#![cfg(test)] use ::rand::Rng; use bincode_1::Options; mod membership; mod misc; mod rand; mod sway; pub fn test_same_with_config<T, C, O>(t: &T, bincode_1_options: O, bincode_2_config: C) where T: bincode_2::Encode + bincode_2::Decode + serde::Serialize + serde::de::DeserializeOwned ...
(rng: &mut impl Rng) -> String { let len = rng.gen_range(0..100usize); let mut result = String::with_capacity(len * 4); for _ in 0..len { result.push(rng.gen_range('\0'..char::MAX)); } result }
gen_string
identifier_name
mainThreadDialogs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(options: MainThreadDialogSaveOptions): TPromise<string> { // TODO@joh what about remote dev setup? if (options.defaultUri && options.defaultUri.scheme !== 'file') { return TPromise.wrapError(new Error('Not supported - Save-dialogs can only be opened on `file`-uris.')); } return new TPromise<string>(resolve ...
$showSaveDialog
identifier_name
mainThreadDialogs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
private static _convertOpenOptions(options: MainThreadDialogOpenOptions): Electron.OpenDialogOptions { const result: Electron.OpenDialogOptions = { properties: ['createDirectory'] }; if (options.openLabel) { result.buttonLabel = options.openLabel; } if (options.defaultUri) { result.defaultPath = o...
{ // TODO@joh what about remote dev setup? if (options.defaultUri && options.defaultUri.scheme !== 'file') { return TPromise.wrapError(new Error('Not supported - Save-dialogs can only be opened on `file`-uris.')); } return new TPromise<string>(resolve => { this._windowService.showSaveDialog( MainThrea...
identifier_body
mainThreadDialogs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
// } $showOpenDialog(options: MainThreadDialogOpenOptions): TPromise<string[]> { // TODO@joh what about remote dev setup? if (options.defaultUri && options.defaultUri.scheme !== 'file') { return TPromise.wrapError(new Error('Not supported - Open-dialogs can only be opened on `file`-uris.')); } return ne...
// } dispose(): void {
random_line_split
mainThreadDialogs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
if (options.canSelectFolders) { result.properties.push('openDirectory'); } if (options.canSelectMany) { result.properties.push('multiSelections'); } if (options.filters) { result.filters = []; forEach(options.filters, entry => result.filters.push({ name: entry.key, extensions: entry.value })); ...
{ result.properties.push('openFile'); }
conditional_block
iter-any.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 ...
assert!(!old_iter::any(&Some(1u), is_even)); assert!(old_iter::any(&Some(2u), is_even)); assert!(!old_iter::any(&None::<uint>, is_even)); }
pub fn main() { assert!(![1u, 3u].any(is_even)); assert!([1u, 2u].any(is_even)); assert!(![].any(is_even));
random_line_split
iter-any.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 ...
{ assert!(![1u, 3u].any(is_even)); assert!([1u, 2u].any(is_even)); assert!(![].any(is_even)); assert!(!old_iter::any(&Some(1u), is_even)); assert!(old_iter::any(&Some(2u), is_even)); assert!(!old_iter::any(&None::<uint>, is_even)); }
identifier_body
iter-any.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 ...
(x: &uint) -> bool { (*x % 2) == 0 } pub fn main() { assert!(![1u, 3u].any(is_even)); assert!([1u, 2u].any(is_even)); assert!(![].any(is_even)); assert!(!old_iter::any(&Some(1u), is_even)); assert!(old_iter::any(&Some(2u), is_even)); assert!(!old_iter::any(&None::<uint>, is_even)); }
is_even
identifier_name
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. //! Storage Transactions pub mod commands; pub mod sched_pool; pub mod scheduler; mod actions; pub use actions::{ acquire_pessimistic_lock::acquire_pessimistic_lock, cleanup::cleanup, commit::commit, gc::gc, prewrite::{prewrite, ...
} impl From<ErrorInner> for Error { #[inline] fn from(e: ErrorInner) -> Self { Error(Box::new(e)) } } impl<T: Into<ErrorInner>> From<T> for Error { #[inline] default fn from(err: T) -> Self { let err = err.into(); err.into() } } pub type Result<T> = std::result::Resul...
{ std::error::Error::source(&self.0) }
identifier_body
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. //! Storage Transactions pub mod commands; pub mod sched_pool; pub mod scheduler; mod actions; pub use actions::{ acquire_pessimistic_lock::acquire_pessimistic_lock, cleanup::cleanup, commit::commit, gc::gc, prewrite::{prewrite, ...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { std::error::Error::source(&self.0) } } impl From<ErrorInner> for Error { #[inline] fn from(e: E...
fmt
identifier_name
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. //! Storage Transactions pub mod commands; pub mod sched_pool; pub mod scheduler; mod actions; pub use actions::{ acquire_pessimistic_lock::acquire_pessimistic_lock, cleanup::cleanup, commit::commit, gc::gc, prewrite::{prewrite, ...
pub fn maybe_clone(&self) -> Option<ProcessResult> { match self { ProcessResult::PessimisticLockRes { res: Ok(r) } => { Some(ProcessResult::PessimisticLockRes { res: Ok(r.clone()) }) } _ => None, } } } quick_error! { #[derive(Debug)] p...
impl ProcessResult {
random_line_split
mod.rs
completion::{on_completion, on_resolve_completion_item}, explore_schema_for_type::{on_explore_schema_for_type, ExploreSchemaForType}, goto_definition::{ on_get_source_location_of_type_definition, on_goto_definition, GetSourceLocationOfTypeDefinition, }, graphql_tools::on_graphql_exec...
mod task_queue; use crate::{ code_action::on_code_action,
random_line_split
mod.rs
::{on_search_schema_items, SearchSchemaItems}, server::{ lsp_state::handle_lsp_state_tasks, lsp_state_resources::LSPStateResources, task_queue::TaskQueue, }, shutdown::{on_exit, on_shutdown}, status_reporter::LSPStatusReporter, status_updater::set_initializing_status, text_docume...
let server_capabilities = serde_json::to_value(&server_capabilities)?; let params = connection.initialize(server_capabilities)?; let params: InitializeParams = serde_json::from_value(params)?; Ok(params) } #[derive(Debug)] pub enum Task { InboundMessage(lsp_server::Message), LSPState(lsp_stat...
{ let server_capabilities = ServerCapabilities { // Enable text document syncing so we can know when files are opened/changed/saved/closed text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::Full)), completion_provider: Some(CompletionOptions { resolv...
identifier_body
mod.rs
_items::{on_search_schema_items, SearchSchemaItems}, server::{ lsp_state::handle_lsp_state_tasks, lsp_state_resources::LSPStateResources, task_queue::TaskQueue, }, shutdown::{on_exit, on_shutdown}, status_reporter::LSPStatusReporter, status_updater::set_initializing_status, text_...
< TPerfLogger: PerfLogger + 'static, TSchemaDocumentation: SchemaDocumentation + 'static, >( connection: Connection, mut config: Config, _params: InitializeParams, perf_logger: Arc<TPerfLogger>, extra_data_provider: Box<dyn LSPExtraDataProvider + Send + Sync>, schema_documentation_loader...
run
identifier_name
mod.rs
::{on_search_schema_items, SearchSchemaItems}, server::{ lsp_state::handle_lsp_state_tasks, lsp_state_resources::LSPStateResources, task_queue::TaskQueue, }, shutdown::{on_exit, on_shutdown}, status_reporter::LSPStatusReporter, status_updater::set_initializing_status, text_docume...
Task::InboundMessage(Message::Response(_)) => { // TODO: handle response from the client -> cancel message, etc } } } } fn handle_request<TPerfLogger: PerfLogger + 'static, TSchemaDocumentation: SchemaDocumentation>( lsp_state: Arc<LSPState<TPerfLogger, TSchemaD...
{ handle_lsp_state_tasks(state, lsp_task); }
conditional_block
lib.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
//! ``` #[macro_use] extern crate log; extern crate env_logger; extern crate rand; extern crate ethcore_util as util; extern crate ethcore_rpc as rpc; extern crate ethcore_io as io; extern crate jsonrpc_core; extern crate ws; extern crate ethcore_devtools as devtools; mod authcode_store; mod ws_server; /// Exporte...
//! let io = Arc::new(IoHandler::new().into()); //! let event_loop = RpcEventLoop::spawn(); //! let _server = ServerBuilder::new(queue, "/tmp/authcodes".into()) //! .start("127.0.0.1:8084".parse().unwrap(), event_loop.handler(io)); //! }
random_line_split
SongAlbum.ts
///<reference path='refs.ts'/> module TDev.RT { //? A song album //@ stem("album") walltap cap(media) export class SongAlbum extends RTValue { private _name: string; private _artist: string; private _genre: string = undefined; private _thumbnail: Picture; ...
public initSongsAsync() : Promise { // Songs if (this._songs) return Promise.as(undefined); return Media.songsAsync(this._name) .then(s => this._songs = s); } public toString(): string { return this.name(); } //? Gets album...
{ if (this._genre != undefined) return Promise.as(undefined); return Media.initSongAlbumAsync(this); }
identifier_body
SongAlbum.ts
///<reference path='refs.ts'/> module TDev.RT { //? A song album //@ stem("album") walltap cap(media) export class SongAlbum extends RTValue { private _name: string; private _artist: string; private _genre: string = undefined; private _thumbnail: Picture; ...
} if (this._genre) dc.appendChild(div("item-subtle", this._genre)); d.appendChild(div('item-buttons', HTML.mkRoundButton("svg:play,currentColor", lf("play"), Ticks.songAlbumPlay, () => this.playAsync().done()))); }) return d; ...
{ this._thumbnail.initAsync().done(() => { var c = this._thumbnail.getViewCanvasClone(); c.className = "contact-image"; di.appendChild(c); }); }
conditional_block
SongAlbum.ts
///<reference path='refs.ts'/> module TDev.RT { //? A song album //@ stem("album") walltap cap(media) export class
extends RTValue { private _name: string; private _artist: string; private _genre: string = undefined; private _thumbnail: Picture; private _duration: number = 0; private _songs: Songs; private _art: Picture; private _artInit = false; ...
SongAlbum
identifier_name
SongAlbum.ts
///<reference path='refs.ts'/> module TDev.RT { //? A song album //@ stem("album") walltap cap(media) export class SongAlbum extends RTValue { private _name: string; private _artist: string; private _genre: string = undefined; private _thumbnail: Picture; ...
return this._artist || ''; } //? Gets the duration in seconds //@ returns(number) cachedAsync public duration(r : ResumeCtx) //: number { this.initAsync().done(() => r.resumeVal(this._duration || 0)); } //? Gets the genre of the song ...
{
random_line_split
ttbarGenStudies_cfg.py
the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # X->HH->bbTauTau is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITN...
False, VarParsing.multiplicity.singleton, VarParsing.varType.bool, "Include Sim. Default: False") options.register ('sampleType', 'Fall15MC', VarParsing.multiplicity.singleton, VarParsing.varTyp...
from FWCore.ParameterSet.VarParsing import VarParsing options = VarParsing('analysis') options.register ('isData',
random_line_split
ttbarGenStudies_cfg.py
the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # X->HH->bbTauTau is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITN...
## Events to process process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) ) inputSignal_v2 = cms.untracked.vstring("file:768F5AFB-D771-E511-9ABD-B499BAABD280.root") DYSample = cms.untracked.vstring("/store/user/ccaputo/HHbbtautau/Run2/DYSample_forHT.root") TTBar = cms.untracked.vstring('/store...
process.GlobalTag.globaltag = '76X_mcRun2_asymptotic_RunIIFall15DR76_v1' isMC = True
conditional_block
pie-wrapper.component.ts
//============== Viser饼图包装器 ===================== //Copyright 2019 何镇汐 //Licensed under the MIT license //===================================================== import { Component, Input,OnInit } from '@angular/core'; import { ComponentBase } from "./base/component-base"; import { DataSet } from '@antv/data-set'; impor...
} ) export class PieWrapperComponent extends ComponentBase implements OnInit { /** * 是否环状图,默认为 false */ @Input() isDonut?: boolean; /** * 数据比例尺 */ @Input() scale?; /** * 饼图样式 */ @Input() style?; /** * 标签配置 */ @Input() labelConfig?; /** * 是...
</v-view> <v-legend dataKey="name"></v-legend> `
random_line_split
pie-wrapper.component.ts
//============== Viser饼图包装器 ===================== //Copyright 2019 何镇汐 //Licensed under the MIT license //===================================================== import { Component, Input,OnInit } from '@angular/core'; import { ComponentBase } from "./base/component-base"; import { DataSet } from '@antv/data-set'; impor...
rLabel ) { this.labelConfig = this.getInnerLabelConfig(); return; } this.labelConfig = this.getOutLabelConfig(); } /** * 获取外部标签配置 */ private getOutLabelConfig() { return ['percent', { formatter: ( value, item ) => { retur...
is.isInne
identifier_name
pie-wrapper.component.ts
//============== Viser饼图包装器 ===================== //Copyright 2019 何镇汐 //Licensed under the MIT license //===================================================== import { Component, Input,OnInit } from '@angular/core'; import { ComponentBase } from "./base/component-base"; import { DataSet } from '@antv/data-set'; impor...
* 转换数据 */ toData( model: Model ) { let dataView = new DataSet.View().source( model.data ); dataView.transform( { type: "percent", fields: model.columns, dimension: 'name', as: 'percent' } ); return dataView.rows; } }
} /** * 初始化坐标系 */ private initCoord() { if ( !this.isDonut ) return; if ( !this.radius ) this.radius = 0.75; if ( !this.innerRadius ) this.innerRadius = 0.6; } /**
identifier_body
example.js
/* * Author: Brendan Le Foll <brendan.le.foll@intel.com> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including
* permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS O...
* without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to
random_line_split
lib.rs
//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event //! notification, and other useful utilities for building high performance IO //! apps. //! //! # Goals //! //! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...) //! * Zero allocations //! * A scalable readi...
//! type Message = (); //! //! fn ready(&mut self, event_loop: &mut EventLoop<MyHandler>, token: Token, _: EventSet) { //! match token { //! SERVER => { //! let MyHandler(ref mut server) = *self; //! // Accept and drop the socket immediately, this will close /...
//! impl Handler for MyHandler { //! type Timeout = ();
random_line_split
notices.js
Titanium.include( "../models/notice.js" ); Titanium.include( "../models/product.js" ); Titanium.include( "../helpers/bottom_menu.js" ); var win = Titanium.UI.currentWindow; var tableView, listeners = []; function main() { // HACK: get active tab index. win.tabGroup.addEventListener( "focus", function( e ) { ...
) { var notice = new Notice(); var notices = notice.list(); notice.close(); var product = new Product(); Ti.API.debug( "notices length refresh: " + notices.length ); // can't get multiple products at once :\. for ( var key = 0; key < notices.length; key++ ) ( function ( key ) { ...
refreshMenu(
identifier_name
notices.js
Titanium.include( "../models/notice.js" ); Titanium.include( "../models/product.js" ); Titanium.include( "../helpers/bottom_menu.js" ); var win = Titanium.UI.currentWindow; var tableView, listeners = []; function main() { // HACK: get active tab index. win.tabGroup.addEventListener( "focus", function( e ) { ...
var data = []; for ( var key = 0; key < notices.length; key++ ) ( function ( key ) { if ( listeners[key] ) { clearInterval( listeners[key] ); // clear listener } var row = Titanium.UI.createTableViewRow( { height: 80 } ); var productDat...
alert( "notices must be an object" ); return []; }
conditional_block
notices.js
Titanium.include( "../models/notice.js" ); Titanium.include( "../models/product.js" ); Titanium.include( "../helpers/bottom_menu.js" ); var win = Titanium.UI.currentWindow; var tableView, listeners = []; function main() { // HACK: get active tab index. win.tabGroup.addEventListener( "focus", function( e ) { ...
notice.close(); Titanium.App.Properties.setBool( "noNotices", true ); // go away!. return; } var data = _buildTable( notices ); win.remove( tableView ); tableView = Titanium.UI.createTableView(); tableView.data = []; tableView.setData( data ); win.add( tabl...
tableView.setData( [row] ); win.add( tableView ); indicator.hide();
random_line_split
notices.js
Titanium.include( "../models/notice.js" ); Titanium.include( "../models/product.js" ); Titanium.include( "../helpers/bottom_menu.js" ); var win = Titanium.UI.currentWindow; var tableView, listeners = []; function main() { // HACK: get active tab index. win.tabGroup.addEventListener( "focus", function( e ) { ...
} ); var _openProductUrl = function ( e ) { Titanium.Platform.openURL( notices[key].url ); } productDataView.addEventListener( "click", _openProductUrl ); var image = Titanium.UI.createImageView( { image: notices[key].image, top: 17, ...
if ( typeof notices != "object" ) { alert( "notices must be an object" ); return []; } var data = []; for ( var key = 0; key < notices.length; key++ ) ( function ( key ) { if ( listeners[key] ) { clearInterval( listeners[key] ); // clear listener } ...
identifier_body