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
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn main() { // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000...
ABC
identifier_name
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print *the_a_ref // lldb-check:[...]$0 = TheA { x: 0, y: 8970181431921507452 } // lldb-command:print *the_b_ref // lldb-check:[...]$1 = TheB(0, 286331153, 286331153) // lldb-comma...
// gdb-command:print *univariant_ref // gdb-check:$3 = {{4820353753753434}}
random_line_split
borrowed-enum.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} fn zzz() {()}
{ // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b000100010...
identifier_body
hstring.rs
// Copyright © 2015-2017 winapi-rs developers // 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 your option. // All files in the project carrying such notice may not be copied,...
#[cfg(target_arch = "x86")] UNION!{union HSTRING_HEADER_Reserved { [u32; 5], Reserved1 Reserved1_mut: PVOID, Reserved2 Reserved2_mut: [c_char; 20], }} #[cfg(target_arch = "x86_64")] UNION!{union HSTRING_HEADER_Reserved { [u64; 3], Reserved1 Reserved1_mut: PVOID, Reserved2 Reserved2_mut: [c_char;...
//! This interface definition contains typedefs for Windows Runtime data types. use ctypes::c_char; use um::winnt::PVOID; DECLARE_HANDLE!(HSTRING, HSTRING__);
random_line_split
egg_info.py
8) to version number"), ('tag-build=', 'b', "Specify explicit tag to add to version number"), ('no-date', 'D', "Don't include date stamp [default]"), ] boolean_options = ['tag-date'] negative_opt = { 'no-date': 'tag-date', } def initialize_options(self): self.egg_ba...
def finalize_options(self): # Note: we need to capture the current value returned # by `self.tagged_version()`, so we can later update # `self.distribution.metadata.version` without # repercussions. self.egg_name = self.name self.egg_version = self.tagged_version() ...
""" Materialize the value of date into the build tag. Install build keys in a deterministic order to avoid arbitrary reordering on subsequent builds. """ egg_info = collections.OrderedDict() # follow the order these keys would have been added # when PYTHONHASHSEED...
identifier_body
egg_info.py
: tag_build = None tag_date = None @property def name(self): return safe_name(self.distribution.get_name()) def tagged_version(self): return safe_version(self._maybe_tag(self.distribution.get_version())) def _maybe_tag(self, version): """ egg_info may be called...
InfoCommon
identifier_name
egg_info.py
elif char == '?': # Match a name character pat += valid_char elif char == '[': # Character class inner_i = i + 1 # Skip initial !/] chars if inner_i < chunk_len and chunk[inner_i] == '!': ...
last_chunk = c == len(chunks) - 1 # Chunks that are a literal ** are globstars. They match anything. if chunk == '**': if last_chunk: # Match anything if this is the last component pat += '.*' else: # Match '(name/)*' ...
conditional_block
egg_info.py
8) to version number"), ('tag-build=', 'b', "Specify explicit tag to add to version number"), ('no-date', 'D', "Don't include date stamp [default]"), ] boolean_options = ['tag-date'] negative_opt = { 'no-date': 'tag-date', } def initialize_options(self): self.egg_ba...
writer(self, ep.name, os.path.join(self.egg_info, ep.name)) # Get rid of native_libs.txt if it was put there by older bdist_egg nl = os.path.join(self.egg_info, "native_libs.txt") if os.path.exists(nl): self.delete_file(nl) self.find_sources() def find_sour...
ep.require(installer=installer) writer = ep.resolve()
random_line_split
account-verify.ts
import { Component } from '@angular/core'; import {IonicPage, ModalController, NavController, NavParams, ViewController} from 'ionic-angular'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {ToastProvider} from "../../providers/toast/toast"; import {UserProvider} from "../../providers/user/us...
e.log(this.timerRemainSeconds); if (this.timerRemainSeconds > 0) { this.timerRemainSeconds--; this.timerText = this.timerRemainSeconds + "s后再次发送"; this.timerTracker(); } else { this.timerText = "再次发送"; th...
consol
identifier_name
account-verify.ts
import { Component } from '@angular/core'; import {IonicPage, ModalController, NavController, NavParams, ViewController} from 'ionic-angular'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {ToastProvider} from "../../providers/toast/toast"; import {UserProvider} from "../../providers/user/us...
this.provider = this.navParams.get('provider'); this.account = this.navParams.get('account'); console.log(this.account); this.verifyForm = this.formBuilder.group({ 'account': ['', []], 'code': ['', [Validators.required]], }); } ionViewDidLoad() ...
private storage: Storage, private modalCtrl: ModalController, public navParams: NavParams) {
random_line_split
account-verify.ts
import { Component } from '@angular/core'; import {IonicPage, ModalController, NavController, NavParams, ViewController} from 'ionic-angular'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {ToastProvider} from "../../providers/toast/toast"; import {UserProvider} from "../../providers/user/us...
*/ dismiss() { this.viewCtrl.dismiss(); } }
his.modalCtrl.create('account-bind',{'provider':this.provider}); modal.present(); } }).catch(err=>{ }); } /** * 关闭页面 *
conditional_block
sb-admin-2.js
$(function() { $('#side-menu').metisMenu();
}); //Loads the correct sidebar on window load, //collapses the sidebar on window resize. // Sets the min-height of #page-wrapper to window size $(function() { $(window).bind("load resize", function() { topOffset = 50; width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.widt...
random_line_split
control.js
new (winston.transports.File)({ filename: nconf.get('app:log'), level: 'info', 'timestamp':true }) ] } ); var influxClient = influx( { host : nconf.get('influxdb:host'), port : parseInt(nconf.get('influxdb:port')), username : nconf.get('influxdb:user'), password : nconf.ge...
var currentNumOfSMSMessages = 0; var NUM_OF_WARNING_EMAIL_MESSAGES = parseInt (nconf.get('app:number_of_warning_email_messages')); var currentNumOfEmailMessages = 0; var SEND_WARNING_SMS = nconf.get('app:send_warning_sms'); var SEND_WARNING_EMAIL = nconf.get('app:send_warning_email'); var sensorDataParts = []; ...
var NUM_OF_WARNING_SMS_MESSAGES = parseInt (nconf.get('app:number_of_warning_sms_messages'));
random_line_split
control.js
new (winston.transports.File)({ filename: nconf.get('app:log'), level: 'info', 'timestamp':true }) ] } ); var influxClient = influx( { host : nconf.get('influxdb:host'), port : parseInt(nconf.get('influxdb:port')), username : nconf.get('influxdb:user'), password : nconf.ge...
else { logger.warn('Could not send SMS to %s ! Error: ', nconf.get('app:mobile_on_duty'), error); } }); } if ((SEND_WARNING_EMAIL===true) && (currentNumOfEmailMessages < NUM_OF_WARNING_EMAIL_MESSAGES)) { currentNumOfEmailMessages = currentNumOfEmailMessa...
{ logger.info('SMS to %s sent! Message SID: %s', nconf.get('app:mobile_on_duty'), message.sid); }
conditional_block
GeneratedSet.tsx
import React from 'react'; import { DimStore } from '../../inventory/store-types'; import { ArmorSet, LockedItemType, StatTypes, LockedMap } from '../types'; import GeneratedSetButtons from './GeneratedSetButtons'; import GeneratedSetItem from './GeneratedSetItem'; import { powerIndicatorIcon, AppIcon } from '../../she...
const firstValidSet = set.firstValidSet; const stats = _.mapValues(statHashes, (statHash) => defs.Stat.get(statHash)); const totalTier = calculateTotalTier(set.stats); const enabledTier = sumEnabledStats(set.stats, enabledStats); return ( <div className={styles.build} style={style} ref={forwardedRef}>...
{ console.error('No valid sets!'); return null; }
conditional_block
GeneratedSet.tsx
import React from 'react'; import { DimStore } from '../../inventory/store-types'; import { ArmorSet, LockedItemType, StatTypes, LockedMap } from '../types'; import GeneratedSetButtons from './GeneratedSetButtons'; import GeneratedSetItem from './GeneratedSetItem'; import { powerIndicatorIcon, AppIcon } from '../../she...
interface Props { set: ArmorSet; selectedStore?: DimStore; lockedMap: LockedMap; style: React.CSSProperties; statOrder: StatTypes[]; defs: D2ManifestDefinitions; forwardedRef?: React.Ref<HTMLDivElement>; enabledStats: Set<StatTypes>; addLockedItem(lockedItem: LockedItemType): void; removeLockedItem(...
import { Loadout } from 'app/loadout/loadout-types';
random_line_split
float_cmp.rs
#![warn(clippy::float_cmp)] #![allow( unused, clippy::no_effect, clippy::op_ref, clippy::unnecessary_operation, clippy::cast_lossless, clippy::many_single_char_names )] use std::ops::Add; const ZERO: f32 = 0.0; const ONE: f32 = ZERO + 1.0; fn twice<T>(x: T) -> T where T: Add<T, Output = T...
// no error, inside "eq" fn } fn fl_eq(x: f32, y: f32) -> bool { if x.is_nan() { y.is_nan() } else { x == y } // no error, inside "eq" fn } struct X { val: f32, } impl PartialEq for X { fn eq(&self, o: &X) -> bool { if self.val.is_nan() { o.val.is_nan() } else { s...
{ x == y }
conditional_block
float_cmp.rs
#![warn(clippy::float_cmp)] #![allow( unused, clippy::no_effect, clippy::op_ref, clippy::unnecessary_operation, clippy::cast_lossless, clippy::many_single_char_names )] use std::ops::Add; const ZERO: f32 = 0.0; const ONE: f32 = ZERO + 1.0; fn twice<T>(x: T) -> T where T: Add<T, Output = T...
let x: f64 = 1.0; x == 1.0; x != 0f64; // no error, comparison with zero is ok twice(x) != twice(ONE as f64); x < 0.0; // no errors, lower or greater comparisons need no fuzzyness x > 0.0; x <= 0.0; x >= 0.0; let xs: [f32; 1] = [0.0]; let a: *const f32 = xs.as_ptr(); let ...
ONE != 0.0; // no error, comparison with zero is ok twice(ONE) != ONE; ONE as f64 != 2.0; ONE as f64 != 0.0; // no error, comparison with zero is ok
random_line_split
float_cmp.rs
#![warn(clippy::float_cmp)] #![allow( unused, clippy::no_effect, clippy::op_ref, clippy::unnecessary_operation, clippy::cast_lossless, clippy::many_single_char_names )] use std::ops::Add; const ZERO: f32 = 0.0; const ONE: f32 = ZERO + 1.0; fn twice<T>(x: T) -> T where T: Add<T, Output = T...
{ val: f32, } impl PartialEq for X { fn eq(&self, o: &X) -> bool { if self.val.is_nan() { o.val.is_nan() } else { self.val == o.val // no error, inside "eq" fn } } } fn main() { ZERO == 0f32; //no error, comparison with zero is ok 1.0f32 != f32::INF...
X
identifier_name
float_cmp.rs
#![warn(clippy::float_cmp)] #![allow( unused, clippy::no_effect, clippy::op_ref, clippy::unnecessary_operation, clippy::cast_lossless, clippy::many_single_char_names )] use std::ops::Add; const ZERO: f32 = 0.0; const ONE: f32 = ZERO + 1.0; fn twice<T>(x: T) -> T where T: Add<T, Output = T...
struct X { val: f32, } impl PartialEq for X { fn eq(&self, o: &X) -> bool { if self.val.is_nan() { o.val.is_nan() } else { self.val == o.val // no error, inside "eq" fn } } } fn main() { ZERO == 0f32; //no error, comparison with zero is ok 1.0f32 !...
{ if x.is_nan() { y.is_nan() } else { x == y } // no error, inside "eq" fn }
identifier_body
forms.py
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The primar...
self.fields['campaign'].choices = campaign_choices
campaign_choices.append((cp.id, unicode(cp.name)))
conditional_block
forms.py
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The primar...
class DashboardForm(forms.Form): """Dashboard Form""" campaign = forms.ChoiceField(label=_('campaign'), required=False) search_type = forms.ChoiceField(label=_('type'), required=False, choices=list(SEARCH_TYPE), initial=SEARCH_TYPE.D_Last_24_hours) def __init__(s...
super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_action = '/login/' self.helper.form_show_labels = False self.helper.form_class = 'form-inline well' self.helper.layout = Layout( Div( Div('user', css_class='co...
identifier_body
forms.py
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The primar...
), FormActions( Submit('submit', 'Login'), HTML('<a class="btn btn-warning" href="/password_reset/">%s?</a>' % _('Forgot password')), ), ) class DashboardForm(forms.Form): """Dashboard Form""" campaign = forms.ChoiceField(label=_('ca...
Div( Div('user', css_class='col-xs-3'), Div('password', css_class='col-xs-3'),
random_line_split
forms.py
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The primar...
(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_action = '/login/' self.helper.form_show_labels = False self.helper.form_class = 'form-inline well' self.helper.layout = Layout( Div( ...
__init__
identifier_name
fof_content.js
it is a string it is assumed that it is an selector which should be on the page to continue. // If it is a function it must returen true to continue // If it is not set (undefined) then we wait for the selector of the step var handleWaitUntil = function(selector, waitUntilSerialized) { var waitUntil = JSONF.parse(wa...
else { var elements = domElements.map(function(index, el) { return el.outerHTML; }); responseCb({count: elements.length, nodes: jQuery.makeArray(elements)}); } } // Show a custom message // This appears twice in c/content.js because it uses a port and a one-shot ...
{ responseCb({count: 1, nodes: domElements[0].outerHTML}); }
conditional_block
fof_content.js
If it is a string it is assumed that it is an selector which should be on the page to continue. // If it is a function it must returen true to continue // If it is not set (undefined) then we wait for the selector of the step var handleWaitUntil = function(selector, waitUntilSerialized) { var waitUntil = JSONF.parse...
// Wait a little if necessary handleWaitUntil(step.selector, step.waitUntil); currentError = FormFiller.fill(step.selector, step.value, step.beforeData, step.flags, step.meta); // Remember the error if (typeof currentError !== "undefined" && currentError !== null) { L...
if (step.within && step.within !== null) { Logger.info("[content.js] Using within selector " + message.within); } // REMOVE END
random_line_split
test_rpcapi.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Red Hat, 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 # ...
(self): super(CertRpcAPITestCase, self).tearDown() def _test_cert_api(self, method, **kwargs): ctxt = context.RequestContext('fake_user', 'fake_project') rpcapi = cert_rpcapi.CertAPI() expected_retval = 'foo' expected_msg = rpcapi.make_msg(method, **kwargs) expected_...
tearDown
identifier_name
test_rpcapi.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Red Hat, 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 # ...
FLAGS = flags.FLAGS class CertRpcAPITestCase(test.TestCase): def setUp(self): super(CertRpcAPITestCase, self).setUp() def tearDown(self): super(CertRpcAPITestCase, self).tearDown() def _test_cert_api(self, method, **kwargs): ctxt = context.RequestContext('fake_user', 'fake_proje...
from nova import flags from nova.openstack.common import rpc from nova import test
random_line_split
test_rpcapi.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Red Hat, 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 # ...
def test_fetch_ca(self): self._test_cert_api('fetch_ca', project_id='fake_project_id') def test_fetch_crl(self): self._test_cert_api('fetch_crl', project_id='fake_project_id') def test_decrypt_text(self): self._test_cert_api('decrypt_text', project_id=...
self._test_cert_api('generate_x509_cert', user_id='fake_user_id', project_id='fake_project_id')
identifier_body
utils.py
from __future__ import unicode_literals from django.template.defaultfilters import slugify as django_slugify from django.utils.importlib import import_module from unidecode import unidecode # Timezone support with fallback. try: from django.utils.timezone import now except ImportError: from datetime import d...
(choices_string): """ Convert a comma separated choices string to a list. """ return [x.strip() for x in choices_string.split(",") if x.strip()] def html5_field(name, base): """ Takes a Django form field class and returns a subclass of it with the given name as its input type. """ ...
split_choices
identifier_name
utils.py
from __future__ import unicode_literals from django.template.defaultfilters import slugify as django_slugify from django.utils.importlib import import_module from unidecode import unidecode # Timezone support with fallback. try: from django.utils.timezone import now except ImportError: from datetime import d...
slug = "%s-%s" % (slug, i) if not manager.filter(**{slug_field: slug}): break i += 1 return slug def split_choices(choices_string): """ Convert a comma separated choices string to a list. """ return [x.strip() for x in choices_string.split(",") if x.strip()...
slug = slug.rsplit("-", 1)[0]
conditional_block
utils.py
from __future__ import unicode_literals from django.template.defaultfilters import slugify as django_slugify from django.utils.importlib import import_module from unidecode import unidecode # Timezone support with fallback. try: from django.utils.timezone import now except ImportError: from datetime import d...
return [x.strip() for x in choices_string.split(",") if x.strip()] def html5_field(name, base): """ Takes a Django form field class and returns a subclass of it with the given name as its input type. """ return type(str(""), (base,), {"input_type": name}) def import_attr(path): """ G...
""" Convert a comma separated choices string to a list. """
random_line_split
utils.py
from __future__ import unicode_literals from django.template.defaultfilters import slugify as django_slugify from django.utils.importlib import import_module from unidecode import unidecode # Timezone support with fallback. try: from django.utils.timezone import now except ImportError: from datetime import d...
def import_attr(path): """ Given a a Python dotted path to a variable in a module, imports the module and returns the variable in it. """ module_path, attr_name = path.rsplit(".", 1) return getattr(import_module(module_path), attr_name)
""" Takes a Django form field class and returns a subclass of it with the given name as its input type. """ return type(str(""), (base,), {"input_type": name})
identifier_body
main.rs
#![feature(clamp)] use std::{env, fs}; fn main() { let uid = unsafe { geteuid() }; if uid != 0 { panic!("UID {} is not root", uid); }
} } fn run(cmd: &str) { match cmd { "+" => set(percent() + 10), "-" => set(percent() - 10), n if n.parse::<i64>().is_ok() => set(n.parse::<i64>().unwrap()), _ => help(), } } fn help() { println!("brightness +|-|N"); } fn max() -> i64 { read("/sys/class/backlight/in...
let args: Vec<String> = env::args().collect(); match args.as_slice() { [_, x] => run(x), _ => help(),
random_line_split
main.rs
#![feature(clamp)] use std::{env, fs}; fn main() { let uid = unsafe { geteuid() }; if uid != 0 { panic!("UID {} is not root", uid); } let args: Vec<String> = env::args().collect(); match args.as_slice() { [_, x] => run(x), _ => help(), } } fn run(cmd: &str) { match...
fn write(b: i64) { fs::write( "/sys/class/backlight/intel_backlight/brightness", b.to_string(), ) .unwrap(); } #[link(name = "c")] extern "C" { fn geteuid() -> u32; } #[cfg(test)] mod test { use super::*; #[test] fn t_test() { assert_eq!(7500, max()); ass...
{ fs::read_to_string(path) .unwrap_or_else(|_| panic!("Couldn't open file: {}", path)) .trim() .parse::<i64>() .unwrap_or_else(|e| panic!("Failed to read number from `{}`", e)) }
identifier_body
main.rs
#![feature(clamp)] use std::{env, fs}; fn main() { let uid = unsafe { geteuid() }; if uid != 0 { panic!("UID {} is not root", uid); } let args: Vec<String> = env::args().collect(); match args.as_slice() { [_, x] => run(x), _ => help(), } } fn run(cmd: &str) { match...
() { write(5000) } }
t_write
identifier_name
gdata-extension.js
/* Copyright 2010, Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must rep...
random_line_split
gdata-extension.js
/* Copyright 2010, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following dis...
var callbackName = "cb" + new Date().getTime(); var callback = function(evt) { delete window[callbackName]; if (GdataExtension.isAuthorized()) { onAuthorized(); } else if (onNotAuthorized) { onNotAuthorized(); } window.setTimeout(function() { win.close(); }, 100); }; window[c...
{ var windowName = "openrefine" + new Date().getTime(); window.name = windowName; }
conditional_block
router.ts
import * as Router from "universal-router"; import routes from "~/routes";
resolveRoute(context, params) { let { route } = context; // if (typeof route.load === 'function') { // return route.load().then(action => action.default(context, params)); // } //this function will be rendered only once for initial props loading no more! if (typeof route.getInitialProps ===...
export default new Router(routes, {
random_line_split
router.ts
import * as Router from "universal-router"; import routes from "~/routes"; export default new Router(routes, { resolveRoute(context, params)
} if (typeof route.action === "function") { context.props = route.props; return route.action(context, params); } return null; } }); const objectWithoutKey = (object, key) => { return Object.keys(object).reduce((result, propName) => { if (propName !== key) { result[propName] =...
{ let { route } = context; // if (typeof route.load === 'function') { // return route.load().then(action => action.default(context, params)); // } //this function will be rendered only once for initial props loading no more! if (typeof route.getInitialProps === "function" && !route.props) { ...
identifier_body
router.ts
import * as Router from "universal-router"; import routes from "~/routes"; export default new Router(routes, {
(context, params) { let { route } = context; // if (typeof route.load === 'function') { // return route.load().then(action => action.default(context, params)); // } //this function will be rendered only once for initial props loading no more! if (typeof route.getInitialProps === "function" &&...
resolveRoute
identifier_name
router.ts
import * as Router from "universal-router"; import routes from "~/routes"; export default new Router(routes, { resolveRoute(context, params) { let { route } = context; // if (typeof route.load === 'function') { // return route.load().then(action => action.default(context, params)); // } //this...
return null; } }); const objectWithoutKey = (object, key) => { return Object.keys(object).reduce((result, propName) => { if (propName !== key) { result[propName] = object[propName]; } return result; }, {}); };
{ context.props = route.props; return route.action(context, params); }
conditional_block
TransformationEvent.ts
import Event = require('./TypedEvent') ; let TypedEvent = Event.TypedEvent ; let TypedEventArgs = Event.TypedEventArgs ; /** * @brief Events dedicated to notify transformations applied on nodes of the * animated element (translation, rotation, scale...). */ export class TransformationEvent extend...
(value: number, data : TransformationEventArgs) { super(Transformation, value, data) ; } } ; /** * @brief Event arguments for transformations. */ abstract class TransformationEventArgs extends TypedEventArgs { /** * @brief Create a TransformationEventArgs instance. */ co...
constructor
identifier_name
TransformationEvent.ts
import Event = require('./TypedEvent') ; let TypedEvent = Event.TypedEvent ; let TypedEventArgs = Event.TypedEventArgs ; /** * @brief Events dedicated to notify transformations applied on nodes of the * animated element (translation, rotation, scale...). */ export class TransformationEvent extend...
super({}) ; } } ; /** * @brief Enumeration to represent transformations applied on nodes of the * animated element. */ export enum Transformation { PositionChanged, RotationChanged, ScaleChanged } ;
constructor() { // TODO.
random_line_split
Header.js
import React, {PropTypes} from 'react'; import { Link, IndexLink } from 'react-router'; // import {Navbar, Nav, NavItem, NavDropdown, MenuItem} from 'react-bootstrap'; class Header extends React.Component { constructor(props) { super(props); } render()
</div> <div id="itemG"> <a href="#" >マイページ{" "}▼</a> </div> <div id="itemH"> <a href="#" >お客様センター{" "}▼</a> </div> <div id="itemI"> <a href="#" > <span className="glyphicon glyphicon-shopping-cart">(0)</span> </a> ...
{ return ( <div id="container" className="link_box"> <div id="itemA"></div> <div id="itemB"> <Link to="/"> <img src=" http://cdn.dscount.com/images_2016/top/ntop_all02.jpg" alt="dscount"/> </Link> </div> <div id="itemC"> <Link to="/"> ...
identifier_body
Header.js
import React, {PropTypes} from 'react'; import { Link, IndexLink } from 'react-router'; // import {Navbar, Nav, NavItem, NavDropdown, MenuItem} from 'react-bootstrap'; class Header extends React.Component {
(props) { super(props); } render() { return ( <div id="container" className="link_box"> <div id="itemA"></div> <div id="itemB"> <Link to="/"> <img src=" http://cdn.dscount.com/images_2016/top/ntop_all02.jpg" alt="dscount"/> </Link> </div> ...
constructor
identifier_name
Header.js
import React, {PropTypes} from 'react'; import { Link, IndexLink } from 'react-router'; // import {Navbar, Nav, NavItem, NavDropdown, MenuItem} from 'react-bootstrap'; class Header extends React.Component { constructor(props) { super(props); } render() { return ( <div id="container" className="link...
export default Header;
random_line_split
LL.py
def close_handler(event): """ Safely shutdown all processes of this program whenever the window is closed by user. """ sys.exit() def spperr_handler(err): """ Sub-process ping error handler Handles common 'errors' we can expect from Window's ping.exe, which is accessed through a subproc...
""" Creates a box of all equal dimensions to hold the text data at the side of the graph - uniformity! vpos: vertical position float hpos: horizontal position float alpha: strength of the colour float colour: colour of the box string """ return ax1.text(vpos, hpos, '______________.', transfo...
identifier_body
LL.py
string """ return ax1.text(vpos, hpos, '______________.', transform=ax1.transAxes, alpha=0, bbox={'alpha': alpha, 'pad': 5, "fc": fc, "ec": ec, "lw": 2}) def close_handler(event): "...
(err): """ Sub-process ping error handler Handles common 'errors' we can expect from Window's ping.exe, which is accessed through a subprocess. 'errors' refer to unsuccessful pings. """ err_dict = {'Destination host unreachable': 'The destination was unreachable!\nPlease check your internet ' ...
spperr_handler
identifier_name
LL.py
over 15% current average ping elif stdv * 2 >= 0.15 * avg: make_databox(vpos=vpos_tb, hpos=hpos_tb, alpha=a_green, fc="green", ec="gold") return Button(plt.axes([hpos, vpos, 0.02, 0.02]), '', image=unstgd_img, color='None') # Ping is stable elif lo_bound <= ping <= up_bo...
if 200 <= lping <= 499:
random_line_split
LL.py
box string """ return ax1.text(vpos, hpos, '______________.', transform=ax1.transAxes, alpha=0, bbox={'alpha': alpha, 'pad': 5, "fc": fc, "ec": ec, "lw": 2}) def close_handler(event): ...
elif lo_bound <= ping <= up_bound: make_databox(vpos=vpos_tb, hpos=hpos_tb, alpha=a_yellow, fc="yellow", ec="green") return Button(plt.axes([hpos, vpos, 0.02, 0.02]), '', image=stwr_img, color='None') else: if ping <= lo_bound: make_databox(vpos=vpos_...
make_databox(vpos=vpos_tb, hpos=hpos_tb, alpha=a_yellow, fc="yellow", ec="gold") return Button(plt.axes([hpos, vpos, 0.02, 0.02]), '', image=unstgd_img, color='None')
conditional_block
view.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining * DS207: Consider shorter variations of null checks * Full docs: https://gi...
} paramsToHeading() { if (this.anyFacetsSelected() || this.stuckFacet) { return _.compact([ this.facetName('dimension_range'), (this.displayMedium()), this.facetName('price_range') ]).join(' '); } } }); function __guard__(value, transform) { return (typeof value !=...
{ return this.humanizeMedium() || 'Artworks'; }
conditional_block
view.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining * DS207: Consider shorter variations of null checks * Full docs: https://gi...
facetName(facet){ return __guard__(__guard__(this.counts != null ? this.counts[facet] : undefined, x1 => x1[this.params.get(facet)]), x => x.name); } anyFacetsSelected() { return _.any(this.facets, facet => this.params.has(facet)); } humanizeMedium() { // replace the 'slash' in 'film-slash-vide...
} }
random_line_split
view.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining * DS207: Consider shorter variations of null checks * Full docs: https://gi...
(facet){ return __guard__(__guard__(this.counts != null ? this.counts[facet] : undefined, x1 => x1[this.params.get(facet)]), x => x.name); } anyFacetsSelected() { return _.any(this.facets, facet => this.params.has(facet)); } humanizeMedium() { // replace the 'slash' in 'film-slash-video' retur...
facetName
identifier_name
view.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining * DS207: Consider shorter variations of null checks * Full docs: https://gi...
facetName(facet){ return __guard__(__guard__(this.counts != null ? this.counts[facet] : undefined, x1 => x1[this.params.get(facet)]), x => x.name); } anyFacetsSelected() { return _.any(this.facets, facet => this.params.has(facet)); } humanizeMedium() { // replace the 'slash' in 'film-slash-vid...
{ if (this.anyFacetsSelected() || this.stuckFacet) { return this.$el.text(this.paramsToHeading()).show(); } else { return this.$el.text("").hide(); } }
identifier_body
opusabout.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE # PyQt4 includes for python bindings to QT from PyQt4.QtCore import QString, QUrl from PyQt4.QtGui import QDialog, QDesktopServices # UI specific includes from opus_gui.main.views.ui_opusabout impor...
def on_webPushButton_released(self): #print "webPushButton pressed" QDesktopServices.openUrl(QUrl(QString("http://www.urbansim.org/"))) def on_docPushButton_released(self): #print "docPushButton pressed" QDesktopServices.openUrl(QUrl(QString("http://www.urbansim.org/docs/opus-...
QDialog.__init__(self, mainwindow, fl) self.setupUi(self) self.mainwindow = mainwindow
identifier_body
opusabout.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE # PyQt4 includes for python bindings to QT from PyQt4.QtCore import QString, QUrl from PyQt4.QtGui import QDialog, QDesktopServices # UI specific includes from opus_gui.main.views.ui_opusabout impor...
(self): #print "webPushButton pressed" QDesktopServices.openUrl(QUrl(QString("http://www.urbansim.org/"))) def on_docPushButton_released(self): #print "docPushButton pressed" QDesktopServices.openUrl(QUrl(QString("http://www.urbansim.org/docs/opus-userguide/"))) def on_licenseP...
on_webPushButton_released
identifier_name
opusabout.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE # PyQt4 includes for python bindings to QT from PyQt4.QtCore import QString, QUrl from PyQt4.QtGui import QDialog, QDesktopServices # UI specific includes from opus_gui.main.views.ui_opusabout impor...
QDesktopServices.openUrl(QUrl(QString("http://www.gnu.org/copyleft/gpl.html"))) def on_buttonCancel_released(self): #print "cancelPushButton pressed" self.close()
#print "docPushButton pressed" QDesktopServices.openUrl(QUrl(QString("http://www.urbansim.org/docs/opus-userguide/"))) def on_licensePushButton_released(self): #print "licensePushButton pressed"
random_line_split
index.tsx
import React from 'react'; import styled from '@emotion/styled'; import space from 'app/styles/space'; import {getListSymbolStyle, listSymbol} from './utils'; type Props = { children: Array<React.ReactElement>; symbol?: keyof typeof listSymbol | React.ReactElement; className?: string; };
case 'colored-numeric': return 'ol'; default: return 'ul'; } }; const Wrapper = getWrapperComponent(); return ( <Wrapper className={className} {...props}> {!symbol || typeof symbol === 'string' ? children : React.Children.map(children, child => { ...
const List = styled(({children, className, symbol, ...props}: Props) => { const getWrapperComponent = () => { switch (symbol) { case 'numeric':
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] #![feature(never_type)] use std::sync::Arc; use anyhow::Result; use async_trait::async_trait; use context::CoreContext...
(&self) { // No-op by default. } } /// Construct a heads fetcher (function that returns all the heads in the /// repo) that uses the publishing bookmarks as all heads. pub fn bookmark_heads_fetcher( bookmarks: ArcBookmarks, ) -> Arc<dyn Fn(&CoreContext) -> BoxFuture<'static, Result<Vec<ChangesetId>>> +...
drop_caches
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] #![feature(never_type)] use std::sync::Arc; use anyhow::Result; use async_trait::async_trait; use context::CoreContext...
{ Arc::new({ move |ctx: &CoreContext| { bookmarks .list( ctx.clone(), Freshness::MaybeStale, &BookmarkPrefix::empty(), BookmarkKind::ALL_PUBLISHING, &BookmarkPagination::FromStart,...
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] #![feature(never_type)] use std::sync::Arc; use anyhow::Result; use async_trait::async_trait; use context::CoreContext...
bookmarks .list( ctx.clone(), Freshness::MaybeStale, &BookmarkPrefix::empty(), BookmarkKind::ALL_PUBLISHING, &BookmarkPagination::FromStart, std::u64::MAX, ...
Arc::new({ move |ctx: &CoreContext| {
random_line_split
solution.py
class Solution(object): def dfs(self,rooms): # get all gate position queue=[(i,j,0) for i,rows in enumerate(rooms) for j,v in enumerate(rows) if not v] while queue: i,j,depth=queue.pop() # has a min path to gate and update if depth<rooms[i][j]: ...
""" self.bfs(rooms)
""" :type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead.
random_line_split
solution.py
class Solution(object):
queue.append((newi,newj)) def wallsAndGates(self, rooms): """ :type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. """ self.bfs(rooms)
def dfs(self,rooms): # get all gate position queue=[(i,j,0) for i,rows in enumerate(rooms) for j,v in enumerate(rows) if not v] while queue: i,j,depth=queue.pop() # has a min path to gate and update if depth<rooms[i][j]: rooms[i][j]=depth ...
identifier_body
solution.py
class
(object): def dfs(self,rooms): # get all gate position queue=[(i,j,0) for i,rows in enumerate(rooms) for j,v in enumerate(rows) if not v] while queue: i,j,depth=queue.pop() # has a min path to gate and update if depth<rooms[i][j]: rooms[i][...
Solution
identifier_name
solution.py
class Solution(object): def dfs(self,rooms): # get all gate position queue=[(i,j,0) for i,rows in enumerate(rooms) for j,v in enumerate(rows) if not v] while queue: i,j,depth=queue.pop() # has a min path to gate and update if depth<rooms[i][j]: ...
for newi,newj in (i+1,j),(i-1,j),(i,j-1),(i,j+1): if 0<=newi<len(rooms) and 0<=newj<len(rooms[0]) and depth<rooms[newi][newj]: queue.append((newi,newj,depth+1)) def bfs(self,rooms): # get all gate position queue=[(i,j) for i,rows in enumerate(rooms) ...
rooms[i][j]=depth
conditional_block
pargen.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import print_function import argparse import random import math import model import utils import gen default_paraphrase = u"Niestety, psy czasem się mylą. Może ich zgubić choćby zapach palącego papierosy." parser = argparse.ArgumentParser(description='...
float(len(common)) S = 0.5 * math.log(len(a) / c, 2) + 0.5 * math.log(len(b) / c, 2) if S < 1.0: return S * scale return math.exp(-3 * S) * scale start_sentence = args.paraphrase sentence = start_sentence old_similarity = 0.0 # semantic_distance(sentence, start_sentence) print ("Start sentence:", start_sent...
0.0 c =
conditional_block
pargen.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import print_function import argparse import random import math import model import utils import gen default_paraphrase = u"Niestety, psy czasem się mylą. Może ich zgubić choćby zapach palącego papierosy." parser = argparse.ArgumentParser(description='...
: a = set(x.split()) b = set(y.split()) common = a & b if len(common) == 0: return 0.0 c = float(len(common)) S = 0.5 * math.log(len(a) / c, 2) + 0.5 * math.log(len(b) / c, 2) if S < 1.0: return S * scale return math.exp(-3 * S) * scale start_sentence = args.paraphrase sentence = start_sentence...
ic_distance(x, y)
identifier_name
pargen.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import print_function import argparse import random import math import model import utils import gen default_paraphrase = u"Niestety, psy czasem się mylą. Może ich zgubić choćby zapach palącego papierosy." parser = argparse.ArgumentParser(description='...
t_sentence = args.paraphrase sentence = start_sentence old_similarity = 0.0 # semantic_distance(sentence, start_sentence) print ("Start sentence:", start_sentence) print ("Semantic distance", old_similarity) generator = gen.SentenceGenerator(args) generator.favorize(start_sentence.split(), args.favorize_alpha) with ut...
t(x.split()) b = set(y.split()) common = a & b if len(common) == 0: return 0.0 c = float(len(common)) S = 0.5 * math.log(len(a) / c, 2) + 0.5 * math.log(len(b) / c, 2) if S < 1.0: return S * scale return math.exp(-3 * S) * scale star
identifier_body
pargen.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import print_function import argparse import random import math import model import utils import gen default_paraphrase = u"Niestety, psy czasem się mylą. Może ich zgubić choćby zapach palącego papierosy." parser = argparse.ArgumentParser(description='...
prefix = sentence[:removal_start] suffix = sentence[removal_end:] new_sentence = generator.run(session, prefix, suffix, removed_chars) new_similarity = semantic_distance(start_sentence, new_sentence) p = math.exp((new_similarity - old_similarity)/T) print(u"Result {}, generated with T={:.2} ({}...
for i in range(100): T = 0.9 ** (i/ 100. * 10) removed_chars = int(math.ceil(len(sentence) * T)) removal_start = random.randint(0, len(sentence) - removed_chars) removal_end = removal_start + removed_chars
random_line_split
cache_helpers.py
from __future__ import absolute_import from typing import Any # This file needs to be different from cache.py because cache.py # cannot import anything from zerver.models or we'd have an import # loop from django.conf import settings from zerver.models import Message, UserProfile, Stream, get_stream_cache_key, \ R...
def stream_cache_items(items_for_remote_cache, stream): items_for_remote_cache[get_stream_cache_key(stream.name, stream.realm_id)] = (stream,) def client_cache_items(items_for_remote_cache, client): items_for_remote_cache[get_client_cache_key(client.name)] = (client,) def huddle_cache_items(items_for_remote...
items_for_remote_cache[user_profile_by_email_cache_key(user_profile.email)] = (user_profile,) items_for_remote_cache[user_profile_by_id_cache_key(user_profile.id)] = (user_profile,)
identifier_body
cache_helpers.py
from __future__ import absolute_import from typing import Any # This file needs to be different from cache.py because cache.py # cannot import anything from zerver.models or we'd have an import # loop from django.conf import settings from zerver.models import Message, UserProfile, Stream, get_stream_cache_key, \ R...
def fill_remote_cache(cache): remote_cache_time_start = get_remote_cache_time() remote_cache_requests_start = get_remote_cache_requests() items_for_remote_cache = {} # type: Dict[str, Any] (objects, items_filler, timeout, batch_size) = cache_fillers[cache] count = 0 for obj in objects(): ...
random_line_split
cache_helpers.py
from __future__ import absolute_import from typing import Any # This file needs to be different from cache.py because cache.py # cannot import anything from zerver.models or we'd have an import # loop from django.conf import settings from zerver.models import Message, UserProfile, Stream, get_stream_cache_key, \ R...
cache_set_many(items_for_remote_cache, timeout=3600*24*7) logging.info("Succesfully populated %s cache! Consumed %s remote cache queries (%s time)" % \ (cache, get_remote_cache_requests() - remote_cache_requests_start, round(get_remote_cache_time() - remote_cache_tim...
items_filler(items_for_remote_cache, obj) count += 1 if (count % batch_size == 0): cache_set_many(items_for_remote_cache, timeout=3600*24) items_for_remote_cache = {}
conditional_block
cache_helpers.py
from __future__ import absolute_import from typing import Any # This file needs to be different from cache.py because cache.py # cannot import anything from zerver.models or we'd have an import # loop from django.conf import settings from zerver.models import Message, UserProfile, Stream, get_stream_cache_key, \ R...
(items_for_remote_cache, huddle): items_for_remote_cache[huddle_hash_cache_key(huddle.huddle_hash)] = (huddle,) def recipient_cache_items(items_for_remote_cache, recipient): items_for_remote_cache[get_recipient_cache_key(recipient.type, recipient.type_id)] = (recipient,) session_engine = import_module(setting...
huddle_cache_items
identifier_name
ratio.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 https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values related to <ratio>. //! https://drafts.csswg.org/css-values/#ratios use std::fm...
<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { self.0.to_css(dest)?; // Even though 1 could be omitted, we don't per // https://drafts.csswg.org/css-values-4/#ratio-value: // // The second <number> is optional, defaulting to 1. However, ...
to_css
identifier_name
ratio.rs
* License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values related to <ratio>. //! https://drafts.csswg.org/css-values/#ratios use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; /// A generic ...
/* This Source Code Form is subject to the terms of the Mozilla Public
random_line_split
AutoComplete.py
"""AutoComplete.py - An IDLE extension for automatically completing names. This extension can complete either attribute names of file names. It can pop a window with all available names, for the user to select from. """ import os import sys import string from configHandler import idleConf import AutoCompleteWindow f...
self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = None hp = HyperParser(self.editwin, "insert") curline = self.text.get("insert linestart", "insert") i = j = len(curline) if hp.is_in_string() and (not mode or mode==COMPLETE_FILES):...
# Cancel another delayed call, if it exists. if self._delayed_completion_id is not None:
random_line_split
AutoComplete.py
"""AutoComplete.py - An IDLE extension for automatically completing names. This extension can complete either attribute names of file names. It can pop a window with all available names, for the user to select from. """ import os import sys import string from configHandler import idleConf import AutoCompleteWindow f...
(self, name): """Lookup name in a namespace spanning sys.modules and __main.dict__""" namespace = sys.modules.copy() namespace.update(__main__.__dict__) return eval(name, namespace)
get_entity
identifier_name
AutoComplete.py
"""AutoComplete.py - An IDLE extension for automatically completing names. This extension can complete either attribute names of file names. It can pop a window with all available names, for the user to select from. """ import os import sys import string from configHandler import idleConf import AutoCompleteWindow f...
except: return [], [] elif mode == COMPLETE_FILES: if what == "": what = "." try: expandedpath = os.path.expanduser(what) bigl = os.listdir(expandedpath) ...
if what == "": namespace = __main__.__dict__.copy() namespace.update(__main__.__builtins__.__dict__) bigl = eval("dir()", namespace) bigl.sort() if "__all__" in bigl: smalll = eval("__all__", name...
conditional_block
AutoComplete.py
"""AutoComplete.py - An IDLE extension for automatically completing names. This extension can complete either attribute names of file names. It can pop a window with all available names, for the user to select from. """ import os import sys import string from configHandler import idleConf import AutoCompleteWindow f...
j = i while i and curline[i-1] in FILENAME_CHARS + SEPS: i -= 1 comp_what = curline[i:j] elif hp.is_in_code() and (not mode or mode==COMPLETE_ATTRIBUTES): self._remove_autocomplete_window() mode = COMPLETE_ATTRIBUTES while i...
"""Find the completions and create the AutoCompleteWindow. Return True if successful (no syntax error or so found). if complete is True, then if there's nothing to complete and no start of completion, won't open completions and return False. If mode is given, will open a completion list ...
identifier_body
dashboard.js
import { Map } from "immutable"; import { DASHBOARD_QUERY, DASHBOARD_QUERY_ERROR, DASHBOARD_QUERY_REQUEST } from "../actions/dashboard"; const initialState = Map({ loading: false, error: null, results: { drafts: { data: [], more: null }, published: { data: [], more: null }, user_published: { d...
return state.set("loading", true); case DASHBOARD_QUERY: return state.set("loading", false).set("results", action.results); case DASHBOARD_QUERY_ERROR: return state.set("loading", false); default: return state; } }
}); export default function dashboardReducer(state = initialState, action) { switch (action.type) { case DASHBOARD_QUERY_REQUEST:
random_line_split
dashboard.js
import { Map } from "immutable"; import { DASHBOARD_QUERY, DASHBOARD_QUERY_ERROR, DASHBOARD_QUERY_REQUEST } from "../actions/dashboard"; const initialState = Map({ loading: false, error: null, results: { drafts: { data: [], more: null }, published: { data: [], more: null }, user_published: { d...
{ switch (action.type) { case DASHBOARD_QUERY_REQUEST: return state.set("loading", true); case DASHBOARD_QUERY: return state.set("loading", false).set("results", action.results); case DASHBOARD_QUERY_ERROR: return state.set("loading", false); default: return state; } }
identifier_body
dashboard.js
import { Map } from "immutable"; import { DASHBOARD_QUERY, DASHBOARD_QUERY_ERROR, DASHBOARD_QUERY_REQUEST } from "../actions/dashboard"; const initialState = Map({ loading: false, error: null, results: { drafts: { data: [], more: null }, published: { data: [], more: null }, user_published: { d...
(state = initialState, action) { switch (action.type) { case DASHBOARD_QUERY_REQUEST: return state.set("loading", true); case DASHBOARD_QUERY: return state.set("loading", false).set("results", action.results); case DASHBOARD_QUERY_ERROR: return state.set("loading", false); default: ...
dashboardReducer
identifier_name
issue-2935.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 ...
trait it { fn f(&self); } impl it for t { fn f(&self) { } } pub fn main() { // let x = ({a: 4i} as it); // let y = @({a: 4i}); // let z = @({a: 4i} as it); // let z = @({a: true} as it); let z = @(@true as @it); // x.f(); // y.f(); // (*z).f(); error!("ok so far..."); ...
random_line_split
issue-2935.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 x = ({a: 4i} as it); // let y = @({a: 4i}); // let z = @({a: 4i} as it); // let z = @({a: true} as it); let z = @(@true as @it); // x.f(); // y.f(); // (*z).f(); error!("ok so far..."); z.f(); //segfault }
identifier_body
issue-2935.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 ...
(&self) { } } pub fn main() { // let x = ({a: 4i} as it); // let y = @({a: 4i}); // let z = @({a: 4i} as it); // let z = @({a: true} as it); let z = @(@true as @it); // x.f(); // y.f(); // (*z).f(); error!("ok so far..."); z.f(); //segfault }
f
identifier_name
132_palindrome_partitioning_ii.py
# 132. Palindrome Partitioning II QuestionEditorial Solution My Submissions # Total Accepted: 58982 # Total Submissions: 256833 # Difficulty: Hard # Given a string s, partition s such that every substring of the partition is a palindrome. # # Return the minimum cuts needed for a palindrome partitioning of s. # # Fo...
j = 0 while i - j >= 0 and i + j + 1 < n and s[i - j] == s[i + j + 1]: dp[i+j+1] = min(dp[i+j+1], dp[i-j-1] + 1) if i - j - 1 >= 0 else 0 print("2 ", i, j, s[i-j], s[i+j+1], dp) j += 1 return dp[-1] if __name__ =...
dp[i+j] = min(dp[i+j], dp[i-j-1] + 1) if i - j - 1 >= 0 else 0 print("1 ", i, j, s[i-j], s[i+j], dp) j += 1
conditional_block
132_palindrome_partitioning_ii.py
# 132. Palindrome Partitioning II QuestionEditorial Solution My Submissions # Total Accepted: 58982 # Total Submissions: 256833 # Difficulty: Hard # Given a string s, partition s such that every substring of the partition is a palindrome. # # Return the minimum cuts needed for a palindrome partitioning of s. # # Fo...
j += 1 return dp[-1] if __name__ == "__main__": s = "aab" print(s) print(Solution().minCut(s))
""" :type s: str :rtype: int """ n = len(s) if n <= 1: return 0 dp = [ n + 1 for x in xrange(n) ] for i in xrange(n): # i Center, j center len print("i ", i) j = 0 while i - j >= 0 and i + j < n and s[i-j] == s[i+j]:...
identifier_body
132_palindrome_partitioning_ii.py
# 132. Palindrome Partitioning II QuestionEditorial Solution My Submissions # Total Accepted: 58982 # Total Submissions: 256833 # Difficulty: Hard # Given a string s, partition s such that every substring of the partition is a palindrome. # # Return the minimum cuts needed for a palindrome partitioning of s. # # Fo...
j += 1 j = 0 while i - j >= 0 and i + j + 1 < n and s[i - j] == s[i + j + 1]: dp[i+j+1] = min(dp[i+j+1], dp[i-j-1] + 1) if i - j - 1 >= 0 else 0 print("2 ", i, j, s[i-j], s[i+j+1], dp) j += 1 return...
j = 0 while i - j >= 0 and i + j < n and s[i-j] == s[i+j]: dp[i+j] = min(dp[i+j], dp[i-j-1] + 1) if i - j - 1 >= 0 else 0 print("1 ", i, j, s[i-j], s[i+j], dp)
random_line_split
132_palindrome_partitioning_ii.py
# 132. Palindrome Partitioning II QuestionEditorial Solution My Submissions # Total Accepted: 58982 # Total Submissions: 256833 # Difficulty: Hard # Given a string s, partition s such that every substring of the partition is a palindrome. # # Return the minimum cuts needed for a palindrome partitioning of s. # # Fo...
(object): def minCut(self, s): """ :type s: str :rtype: int """ n = len(s) if n <= 1: return 0 dp = [ n + 1 for x in xrange(n) ] for i in xrange(n): # i Center, j center len print("i ", i) j = 0 while i -...
Solution
identifier_name
client.test-d.ts
/* eslint-disable @typescript-eslint/no-empty-function */ import { expectType } from 'tsd'; import { GridFSBucket, MongoClient, MongoClientOptions, MongoError, MongoNetworkError, MongoParseError, ReadPreference, ReadPreferenceMode, W } from '../../../src/index'; // TODO(NODE-3348): Improve the tests...
, promoteBuffers: false, authMechanism: 'SCRAM-SHA-1', forceServerObjectId: false, promiseLibrary: Promise, directConnection: false }; MongoClient.connect(connectionString, options, (err, client?: MongoClient) => { if (err || !client) throw err; const db = client.db('test'); db.collection('test_crud');...
{ return undefined; }
identifier_body
client.test-d.ts
/* eslint-disable @typescript-eslint/no-empty-function */ import { expectType } from 'tsd'; import { GridFSBucket, MongoClient, MongoClientOptions, MongoError, MongoNetworkError, MongoParseError, ReadPreference, ReadPreferenceMode, W } from '../../../src/index'; // TODO(NODE-3348): Improve the tests...
promiseLibrary: Promise, directConnection: false }; MongoClient.connect(connectionString, options, (err, client?: MongoClient) => { if (err || !client) throw err; const db = client.db('test'); db.collection('test_crud'); // Let's close the db client.close(); }); export async function testFunc(): Promise...
promoteBuffers: false, authMechanism: 'SCRAM-SHA-1', forceServerObjectId: false,
random_line_split
client.test-d.ts
/* eslint-disable @typescript-eslint/no-empty-function */ import { expectType } from 'tsd'; import { GridFSBucket, MongoClient, MongoClientOptions, MongoError, MongoNetworkError, MongoParseError, ReadPreference, ReadPreferenceMode, W } from '../../../src/index'; // TODO(NODE-3348): Improve the tests...
(): Promise<MongoClient> { const testClient: MongoClient = await MongoClient.connect(connectionString); return testClient; } MongoClient.connect(connectionString, err => { if (err instanceof MongoError) { expectType<boolean>(err.hasErrorLabel('label')); } }); expectType<Promise<MongoClient>>(MongoClient.c...
testFunc
identifier_name
spherical_harmonics.py
""" Plot spherical harmonics on the surface of the sphere, as well as a 3D polar plot. This example requires scipy. In this example we use the mlab's mesh function: :func:`mayavi.mlab.mesh`. For plotting surfaces this is a very versatile function. The surfaces can be defined as functions of a 2D grid. For each spher...
mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25)) mlab.show()
s = sph_harm(m, n, theta, phi).real mlab.mesh(x - m, y - n, z, scalars=s, colormap='jet') s[s < 0] *= 0.97 s /= s.max() mlab.mesh(s * x - m, s * y - n, s * z + 1.3, scalars=s, colormap='Spectral')
conditional_block
spherical_harmonics.py
""" Plot spherical harmonics on the surface of the sphere, as well as a 3D polar plot. This example requires scipy. In this example we use the mlab's mesh function: :func:`mayavi.mlab.mesh`. For plotting surfaces this is a very versatile function. The surfaces can be defined as functions of a 2D grid. For each spher...
# License: BSD Style. from mayavi import mlab import numpy as np from scipy.special import sph_harm # Create a sphere r = 0.3 pi = np.pi cos = np.cos sin = np.sin phi, theta = np.mgrid[0:pi:101j, 0:2 * pi:101j] x = r * sin(phi) * cos(theta) y = r * sin(phi) * sin(theta) z = r * cos(phi) mlab.figure(1, bgcolor=(1, 1...
the radius of the previous sphere. """ # Author: Gael Varoquaux <gael.varoquaux@normalesup.org> # Copyright (c) 2008, Enthought, Inc.
random_line_split
global_settings.py
import os from openslides.utils.plugins import collect_plugins MODULE_DIR = os.path.realpath(os.path.dirname(os.path.abspath(__file__)))
# Application definition INSTALLED_APPS = [ "openslides.core", "openslides.users", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.staticfiles", "rest_framework", "openslides.agenda", "openslides.topics", "openslides.motions", ...
# This is not set to the docker environment OPENSLIDES_USER_DATA_DIR = "/app/personal_data/var"
random_line_split
test_wiringfastapi_py36.py
from httpx import AsyncClient # Runtime import to avoid syntax errors in samples on Python < 3.5 and reach top-dir import os _TOP_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__file__), '../', )), ) _SAMPLES_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__fi...
return 'Foo' with web.container.service.override(ServiceMock()): response = self._run(self.client.get('/')) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), {'result': 'Foo'}) def test_depends_injection(self): response = sel...
random_line_split
test_wiringfastapi_py36.py
from httpx import AsyncClient # Runtime import to avoid syntax errors in samples on Python < 3.5 and reach top-dir import os _TOP_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__file__), '../', )), ) _SAMPLES_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__fi...
def test_depends_injection(self): response = self._run(self.client.get('/auth', auth=('john_smith', 'secret'))) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), {'username': 'john_smith', 'password': 'secret'})
client: AsyncClient def setUp(self) -> None: super().setUp() self.client = AsyncClient(app=web.app, base_url='http://test') def tearDown(self) -> None: self._run(self.client.aclose()) super().tearDown() def test_depends_marker_injection(self): class ServiceMock: ...
identifier_body
test_wiringfastapi_py36.py
from httpx import AsyncClient # Runtime import to avoid syntax errors in samples on Python < 3.5 and reach top-dir import os _TOP_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__file__), '../', )), ) _SAMPLES_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__fi...
(self) -> None: self._run(self.client.aclose()) super().tearDown() def test_depends_marker_injection(self): class ServiceMock: async def process(self): return 'Foo' with web.container.service.override(ServiceMock()): response = self._run(self...
tearDown
identifier_name
annotate_old_bird_calls.py
""" Annotates Old Bird call detections in the BirdVox-70k archive. The annotations classify clips detected by the Old Bird Tseep and Thrush detectors according to the archive's ground truth call clips. This script must be run from the archive directory. """ from django.db.models import F from django.db.utils import...
annotations = \ model_utils.get_clip_annotations(ground_truth_clip) call_center_freq = annotations[CENTER_FREQ_ANNOTATION_NAME] # Annotate Old Bird clip call center frequency. model_utils.annotate_clip( ...
model_utils.annotate_clip( old_bird_clip, center_index_annotation_info, str(call_center_index), creating_user=user) # Get ground truth clip call center frequency.
random_line_split