file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
OnLoadDirective.ts | namespace JustinCredible.TheWeek.Directives {
/**
* A directive for handling an element's onload event (eg an image tag).
*
* http://stackoverflow.com/questions/11868393/angularjs-inputtext-ngchange-fires-while-the-value-is-changing
*/
export class OnLoadDirective implements ng.IDirective ... |
constructor(
private $parse: ng.IParseService) {
// Ensure that the link function is bound to this instance so we can
// access instance variables like $parse. AngularJs normally executes
// the link function in the context of the global scope.
this... | {
return ["$parse"];
} | identifier_body |
OnLoadDirective.ts | namespace JustinCredible.TheWeek.Directives {
/**
* A directive for handling an element's onload event (eg an image tag).
*
* http://stackoverflow.com/questions/11868393/angularjs-inputtext-ngchange-fires-while-the-value-is-changing
*/
export class OnLoadDirective implements ng.IDirective ... | public static ID = "onLoad";
public static get $inject(): string[] {
return ["$parse"];
}
constructor(
private $parse: ng.IParseService) {
// Ensure that the link function is bound to this instance so we can
// access instance variables ... |
//#region Injection
| random_line_split |
OnLoadDirective.ts | namespace JustinCredible.TheWeek.Directives {
/**
* A directive for handling an element's onload event (eg an image tag).
*
* http://stackoverflow.com/questions/11868393/angularjs-inputtext-ngchange-fires-while-the-value-is-changing
*/
export class OnLoadDirective implements ng.IDirective ... | (
private $parse: ng.IParseService) {
// Ensure that the link function is bound to this instance so we can
// access instance variables like $parse. AngularJs normally executes
// the link function in the context of the global scope.
this.link = _.bind(this.l... | constructor | identifier_name |
view.js | function BxTimelineView(oOptions) {
this._sActionsUri = oOptions.sActionUri;
this._sActionsUrl = oOptions.sActionUrl;
this._sObjName = oOptions.sObjName == undefined ? 'oTimelineView' : oOptions.sObjName;
this._iOwnerId = oOptions.iOwnerId == undefined ? 0 : oOptions.iOwnerId;
this._sAnimationEffect = ... |
if(oLink)
this.loadingInItem(oLink, true);
jQuery.get (
this._sActionsUrl + 'get_comments',
oData,
function(oData) {
if(oLink)
$this.loadingInItem(oLink, false);
if(!oData.content)
return;
oComments.html($(oData.content).hide()).ch... | {
oComments.bx_anim('toggle', this._sAnimationEffect, this._iAnimationSpeed);
return;
} | conditional_block |
view.js | function BxTimelineView(oOptions) |
BxTimelineView.prototype = new BxTimelineMain();
BxTimelineView.prototype.changePage = function(oElement, iStart, iPerPage) {
this._oRequestParams.start = iStart;
this._oRequestParams.per_page = iPerPage;
this._getPosts(oElement, 'page');
};
BxTimelineView.prototype.changeFilter = function(oLink) {
va... | {
this._sActionsUri = oOptions.sActionUri;
this._sActionsUrl = oOptions.sActionUrl;
this._sObjName = oOptions.sObjName == undefined ? 'oTimelineView' : oOptions.sObjName;
this._iOwnerId = oOptions.iOwnerId == undefined ? 0 : oOptions.iOwnerId;
this._sAnimationEffect = oOptions.sAnimationEffect == undef... | identifier_body |
view.js | function BxTimelineView(oOptions) {
this._sActionsUri = oOptions.sActionUri;
this._sActionsUrl = oOptions.sActionUrl;
this._sObjName = oOptions.sObjName == undefined ? 'oTimelineView' : oOptions.sObjName;
this._iOwnerId = oOptions.iOwnerId == undefined ? 0 : oOptions.iOwnerId;
this._sAnimationEffect = ... | oView.find('.bx-tl-empty').show();
});
},
'json'
);
};
BxTimelineView.prototype.showMoreContent = function(oLink) {
$(oLink).parent('span').next('span').show().prev('span').remove();
this.reloadMasonry();
};
BxTimelineView.prototype.sho... | return;
}
$this.destroyMasonry();
oView.find('.bx-tl-load-more').hide(); | random_line_split |
view.js | function | (oOptions) {
this._sActionsUri = oOptions.sActionUri;
this._sActionsUrl = oOptions.sActionUrl;
this._sObjName = oOptions.sObjName == undefined ? 'oTimelineView' : oOptions.sObjName;
this._iOwnerId = oOptions.iOwnerId == undefined ? 0 : oOptions.iOwnerId;
this._sAnimationEffect = oOptions.sAnimationEffe... | BxTimelineView | identifier_name |
akPu3CaloJetSequence15_cff.py | import FWCore.ParameterSet.Config as cms
from HeavyIonsAnalysis.JetAnalysis.jets.akPu3CaloJetSequence_PbPb_mc_cff import *
#PU jets: type 15
akPu3Calomatch15 = akPu3Calomatch.clone(src = cms.InputTag("akPu3CaloJets15"))
akPu3Caloparton15 = akPu3Caloparton.clone(src = cms.InputTag("akPu3CaloJets15"))
akPu3Calocorr15 =... | akPu3CaloJetSequence15 = cms.Sequence(akPu3Calomatch15
*
akPu3Caloparton15
*
akPu3Calocorr15
*
akPu3Calo... | genPartonMatch = cms.InputTag("akPu3Caloparton15"),
)
akPu3CaloJetAnalyzer15 = akPu3CaloJetAnalyzer.clone(jetTag = cms.InputTag("akPu3CalopatJets15"), doSubEvent = cms.untracked.bool(True) ) | random_line_split |
action_registry_test.py | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | (self):
"""Do some sanity checks on the action registry."""
self.assertEqual(
len(action_registry.Registry.get_all_actions()), 3)
| test_action_registry | identifier_name |
action_registry_test.py | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
def test_action_registry(self):
"""Do some sanity checks on the action registry."""
self.assertEqual(
len(action_registry.Registry.get_all_actions()), 3) | random_line_split | |
action_registry_test.py | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | """Test for the action registry."""
def test_action_registry(self):
"""Do some sanity checks on the action registry."""
self.assertEqual(
len(action_registry.Registry.get_all_actions()), 3) | identifier_body | |
app.module.ts | import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, PreloadAllModules } from '@angular/router';
import { removeNgStyles, createNewHosts, creat... | (store: StoreType) {
const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
// save state
const state = this.appState._state;
store.state = state;
// recreate root elements
store.disposeOldHosts = createNewHosts(cmpLocation);
// save input values
store.restore... | hmrOnDestroy | identifier_name |
app.module.ts | import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, PreloadAllModules } from '@angular/router';
import { removeNgStyles, createNewHosts, creat... | state: InternalStateType,
restoreInputValues: () => void,
disposeOldHosts: () => void
};
/**
* `AppModule` is the main entry point into Angular2's bootstraping process
*/
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AddNewWordComponent,
AppComponent,
HomeComponent,
StatsComponen... | AppState
];
type StoreType = { | random_line_split |
app.module.ts | import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, PreloadAllModules } from '@angular/router';
import { removeNgStyles, createNewHosts, creat... |
this.appRef.tick();
delete store.state;
delete store.restoreInputValues;
}
hmrOnDestroy(store: StoreType) {
const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
// save state
const state = this.appState._state;
store.state = state;
// recreate root el... | {
let restoreInputValues = store.restoreInputValues;
setTimeout(restoreInputValues);
} | conditional_block |
staging.py | """Production settings and globals."""
from base import *
########## HOST CONFIGURATION
# See: https://docs.djangoproject.com/en/1.5/releases/1.5/#allowed-hosts-required-in-production
MAIN_HOST = ['openbilanci.staging.deppsviluppo.org',]
# Allowed hosts expansion: needed for servizi ai Comuni
HOSTS_COMUNI = [
'novar... |
PATH_PREVENTIVI = BILANCI_PATH+"/%s/%s/Preventivo/%s.html"
PATH_CONSUNTIVI = BILANCI_PATH+"/%s/%s/Consuntivo/%s.html"
BILANCI_RAW_DB = 'bilanci_raw' |
BILANCI_PATH = "/home/open_bilanci/dati/bilanci_subset"
OUTPUT_FOLDER = '../scraper_project/scraper/output/'
LISTA_COMUNI = 'listacomuni.csv'
LISTA_COMUNI_PATH = OUTPUT_FOLDER + LISTA_COMUNI | random_line_split |
staging.py | """Production settings and globals."""
from base import *
########## HOST CONFIGURATION
# See: https://docs.djangoproject.com/en/1.5/releases/1.5/#allowed-hosts-required-in-production
MAIN_HOST = ['openbilanci.staging.deppsviluppo.org',]
# Allowed hosts expansion: needed for servizi ai Comuni
HOSTS_COMUNI = [
'novar... |
SHOW_TOOLBAR_CALLBACK = show_toolbar
DEBUG_TOOLBAR_PATCH_SETTINGS=False
########## END TOOLBAR CONFIGURATION
BILANCI_PATH = "/home/open_bilanci/dati/bilanci_subset"
OUTPUT_FOLDER = '../scraper_project/scraper/output/'
LISTA_COMUNI = 'listacomuni.csv'
LISTA_COMUNI_PATH = OUTPUT_FOLDER + LISTA_COMUNI
PATH_PREVENTIVI... | print("IP Address for debug-toolbar: " + request.META['REMOTE_ADDR'])
return True | identifier_body |
staging.py | """Production settings and globals."""
from base import *
########## HOST CONFIGURATION
# See: https://docs.djangoproject.com/en/1.5/releases/1.5/#allowed-hosts-required-in-production
MAIN_HOST = ['openbilanci.staging.deppsviluppo.org',]
# Allowed hosts expansion: needed for servizi ai Comuni
HOSTS_COMUNI = [
'novar... | (request):
print("IP Address for debug-toolbar: " + request.META['REMOTE_ADDR'])
return True
SHOW_TOOLBAR_CALLBACK = show_toolbar
DEBUG_TOOLBAR_PATCH_SETTINGS=False
########## END TOOLBAR CONFIGURATION
BILANCI_PATH = "/home/open_bilanci/dati/bilanci_subset"
OUTPUT_FOLDER = '../scraper_project/scraper/output/... | show_toolbar | identifier_name |
tooltip.ts | export let Tooltip = {
show(element: any, text: string) {
this.element = element;
if(this.tooltipVisible) {
// Hide any visible tooltips
this.hide();
}
let tooltip = this.getTooltip();
// element.parentNode.insertBefore(tooltip, element.nextSibling);... | else {
tooltip.style.top = pageScroll + (elementPosition.top - (tooltipHeight + offset)) + 'px';
tooltip.classList.remove('bottom');
tooltip.classList.add('top');
}
}
}; | {
tooltip.style.top = pageScroll + (elementPosition.top + (elementHeight + offset)) + 'px';
tooltip.classList.remove('top');
tooltip.classList.add('bottom');
} | conditional_block |
tooltip.ts | export let Tooltip = {
show(element: any, text: string) {
this.element = element;
if(this.tooltipVisible) {
// Hide any visible tooltips
this.hide();
}
let tooltip = this.getTooltip();
// element.parentNode.insertBefore(tooltip, element.nextSibling);... | ,
getTooltip() {
if(!this.tooltip) {
let holder = document.createElement('span');
holder.classList.add('tooltip');
this.tooltip = holder;
}
return this.tooltip;
},
addTooltipStyle(element: any, tooltip: any) {
let offset = 6;
le... | {
document.body.removeChild(this.getTooltip());
this.tooltipVisible = false;
this.tooltip = null;
document.removeEventListener('mouseup', this.onMouseUpHandler);
document.removeEventListener('scroll', this.onPageScrollHandler);
} | identifier_body |
tooltip.ts | export let Tooltip = {
show(element: any, text: string) {
this.element = element;
if(this.tooltipVisible) {
// Hide any visible tooltips
this.hide();
}
let tooltip = this.getTooltip();
// element.parentNode.insertBefore(tooltip, element.nextSibling);... | () {
if(!this.tooltip) {
let holder = document.createElement('span');
holder.classList.add('tooltip');
this.tooltip = holder;
}
return this.tooltip;
},
addTooltipStyle(element: any, tooltip: any) {
let offset = 6;
let tooltipWidth = ... | getTooltip | identifier_name |
tooltip.ts | export let Tooltip = {
show(element: any, text: string) {
this.element = element;
if(this.tooltipVisible) {
// Hide any visible tooltips
this.hide();
}
let tooltip = this.getTooltip();
// element.parentNode.insertBefore(tooltip, element.nextSibling);... | holder.classList.add('tooltip');
this.tooltip = holder;
}
return this.tooltip;
},
addTooltipStyle(element: any, tooltip: any) {
let offset = 6;
let tooltipWidth = tooltip.offsetWidth;
let tooltipHeight = tooltip.offsetHeight;
let elementP... | getTooltip() {
if(!this.tooltip) {
let holder = document.createElement('span');
| random_line_split |
test_versions.js | import SagaTester from 'redux-saga-tester';
import * as versionsApi from 'amo/api/versions';
import versionsReducer, {
fetchVersions,
loadVersions,
} from 'amo/reducers/versions';
import versionsSaga from 'amo/sagas/versions';
import apiReducer from 'core/reducers/api';
import { createStubErrorHandler } from 'test... |
it('calls the API to fetch versions', async () => {
const state = sagaTester.getState();
const versions = { results: [fakeVersion] };
mockApi
.expects('getVersions')
.withArgs({
api: state.api,
page,
slug,
})
.once()
.resolv... | {
sagaTester.dispatch(
fetchVersions({
errorHandlerId: errorHandler.id,
...params,
}),
);
} | identifier_body |
test_versions.js | import SagaTester from 'redux-saga-tester';
import * as versionsApi from 'amo/api/versions';
import versionsReducer, {
fetchVersions,
loadVersions,
} from 'amo/reducers/versions';
import versionsSaga from 'amo/sagas/versions';
import apiReducer from 'core/reducers/api';
import { createStubErrorHandler } from 'test... | (params) {
sagaTester.dispatch(
fetchVersions({
errorHandlerId: errorHandler.id,
...params,
}),
);
}
it('calls the API to fetch versions', async () => {
const state = sagaTester.getState();
const versions = { results: [fakeVersion] };
mockApi
... | _fetchVersions | identifier_name |
test_versions.js | import SagaTester from 'redux-saga-tester';
import * as versionsApi from 'amo/api/versions';
import versionsReducer, {
fetchVersions,
loadVersions,
} from 'amo/reducers/versions';
import versionsSaga from 'amo/sagas/versions';
import apiReducer from 'core/reducers/api';
import { createStubErrorHandler } from 'test... | page,
slug,
})
.once()
.resolves(versions);
_fetchVersions({ page, slug });
const expectedAction = loadVersions({ slug, versions });
const loadAction = await sagaTester.waitFor(expectedAction.type);
expect(loadAction).toEqual(expectedAction);
... |
mockApi
.expects('getVersions')
.withArgs({
api: state.api, | random_line_split |
DataDocumentType.js | a,g);return a}); | // All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.17/esri/copyright.txt for details.
//>>built
define("esri/dijit/metadata/types/gemini/base/DataDocumentType","dojo/_base/declare dojo/_base/lang dojo/has ./GeminiDocumentType ./DataRoot dojo/i18n!../../../nls/... | random_line_split | |
fix_sensor_config_key.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import emission.core.get_database as edb
def fix_key(check_field, new_key):... |
fix_key("data.battery_status", "background/battery")
fix_key("data.latitude", "background/location")
fix_key("data.zzaEh", "background/motion_activity")
fix_key("data.currState", "statemachine/transition")
| udb.insert(entry)
tdb.remove(entry["_id"]) | conditional_block |
fix_sensor_config_key.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import emission.core.get_database as edb
def | (check_field, new_key):
print("First entry for "+new_key+" is %s" % list(edb.get_timeseries_db().find(
{"metadata.key": "config/sensor_config",
check_field: {"$exists": True}}).sort(
"metadata/write_ts").... | fix_key | identifier_name |
fix_sensor_config_key.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import emission.core.get_database as edb
def fix_key(check_field, new_key):... | check_field: {"$exists": True}}).sort(
"metadata/write_ts").limit(1)))
udb = edb.get_usercache_db()
tdb = edb.get_timeseries_db()
for i, entry in enumerate(edb.get_timeseries_db().find(
{"metadata... | {"metadata.key": "config/sensor_config", | random_line_split |
fix_sensor_config_key.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import emission.core.get_database as edb
def fix_key(check_field, new_key):... |
fix_key("data.battery_status", "background/battery")
fix_key("data.latitude", "background/location")
fix_key("data.zzaEh", "background/motion_activity")
fix_key("data.currState", "statemachine/transition")
| print("First entry for "+new_key+" is %s" % list(edb.get_timeseries_db().find(
{"metadata.key": "config/sensor_config",
check_field: {"$exists": True}}).sort(
"metadata/write_ts").limit(1)))
udb = edb.get... | identifier_body |
base.py | """
Base/mixin classes for the spatial backend database operations and the
`SpatialRefSys` model the backend.
"""
import re
from django.contrib.gis import gdal
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
class BaseSpatialOperations(object):
"""
This module holds... |
raise Exception('Could not get OSR SpatialReference from WKT: %s\nError:\n%s' % (self.wkt, msg))
else:
raise Exception('GDAL is not installed.')
@property
def ellipsoid(self):
"""
Returns a tuple of the ellipsoid parameters:
(semimajor axis, semimino... | self._srs = gdal.SpatialReference(self.proj4text)
return self.srs
except Exception as msg:
pass | random_line_split |
base.py | """
Base/mixin classes for the spatial backend database operations and the
`SpatialRefSys` model the backend.
"""
import re
from django.contrib.gis import gdal
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
class BaseSpatialOperations(object):
"""
This module holds... |
def spatial_ref_sys(self):
raise NotImplementedError('subclasses of BaseSpatialOperations must a provide spatial_ref_sys() method')
@python_2_unicode_compatible
class SpatialRefSysMixin(object):
"""
The SpatialRefSysMixin is a class used by the database-dependent
SpatialRefSys objects to redu... | raise NotImplementedError('subclasses of BaseSpatialOperations must a provide geometry_columns() method') | identifier_body |
base.py | """
Base/mixin classes for the spatial backend database operations and the
`SpatialRefSys` model the backend.
"""
import re
from django.contrib.gis import gdal
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
class BaseSpatialOperations(object):
"""
This module holds... |
@property
def linear_units(self):
"Returns the linear units."
if gdal.HAS_GDAL:
return self.srs.linear_units
elif self.geographic:
return None
else:
m = self.units_regex.match(self.wkt)
return m.group('unit')
@property
de... | m = self.units_regex.match(self.wkt)
return m.group('unit_name') | conditional_block |
base.py | """
Base/mixin classes for the spatial backend database operations and the
`SpatialRefSys` model the backend.
"""
import re
from django.contrib.gis import gdal
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
class BaseSpatialOperations(object):
"""
This module holds... | (self, lvalue, lookup_type, value, field):
raise NotImplementedError('subclasses of BaseSpatialOperations must a provide spatial_lookup_sql() method')
# Routines for getting the OGC-compliant models.
def geometry_columns(self):
raise NotImplementedError('subclasses of BaseSpatialOperations must... | spatial_lookup_sql | identifier_name |
TransitionExampleGroupExplorer.js | import React, { Component } from 'react'
import { Form, Grid, Image, Transition } from 'shengnian-ui-react'
const transitions = [
'scale',
'fade', 'fade up', 'fade down', 'fade left', 'fade right',
'horizontal flip', 'vertical flip',
'drop',
'fly left', 'fly right', 'fly up', 'fly down',
'swing left', 'swi... | <Form.Button content={visible ? 'Unmount' : 'Mount'} onClick={this.handleVisibility} />
</Grid.Column>
<Grid.Column>
<Transition.Group animation={animation} duration={duration}>
{visible && <Image centered size='small' src='/assets/images/leaves/4.png' />}
</Tr... | step={100}
type='range'
value={duration}
/> | random_line_split |
TransitionExampleGroupExplorer.js | import React, { Component } from 'react'
import { Form, Grid, Image, Transition } from 'shengnian-ui-react'
const transitions = [
'scale',
'fade', 'fade up', 'fade down', 'fade left', 'fade right',
'horizontal flip', 'vertical flip',
'drop',
'fly left', 'fly right', 'fly up', 'fly down',
'swing left', 'swi... | extends Component {
state = { animation: transitions[0], duration: 500, visible: true }
handleChange = (e, { name, value }) => this.setState({ [name]: value })
handleVisibility = () => this.setState({ visible: !this.state.visible })
render() {
const { animation, duration, visible } = this.state
ret... | TransitionExampleSingleExplorer | identifier_name |
keymap.rs | //! Keymap support
use std;
use std::ptr;
use libc::c_void;
use remacs_macros::lisp_fn;
use crate::{
buffers::current_buffer,
data::{aref, fset, indirect_function, set},
eval::{autoload_do_load, unbind_to},
indent::indent_to,
keyboard,
keyboard::lucid_event_type_list_p,
lisp::LispObject,... |
/// Return the parent keymap of KEYMAP.
/// If KEYMAP has no parent, return nil.
#[lisp_fn(name = "keymap-parent", c_name = "keymap_parent")]
pub fn keymap_parent_lisp(keymap: LispObject) -> LispObject {
keymap_parent(keymap, true)
}
/// Check whether MAP is one of MAPS parents.
#[no_mangle]
pub extern "C" fn ke... | {
let map = get_keymap(keymap, true, autoload);
let mut current = Qnil;
for elt in map.iter_tails(LispConsEndChecks::off, LispConsCircularChecks::off) {
current = elt.cdr();
if keymapp(current) {
return current;
}
}
get_keymap(current, false, autoload)
} | identifier_body |
keymap.rs | //! Keymap support
use std;
use std::ptr;
use libc::c_void;
use remacs_macros::lisp_fn;
use crate::{
buffers::current_buffer,
data::{aref, fset, indirect_function, set},
eval::{autoload_do_load, unbind_to},
indent::indent_to,
keyboard,
keyboard::lucid_event_type_list_p,
lisp::LispObject,... | else if binding.is_vector() {
if let Some(binding_vec) = binding.as_vectorlike() {
for c in 0..binding_vec.pseudovector_size() {
map_keymap_item(fun, args, c.into(), aref(binding, c), data);
}
}
} else if bindin... | {
map_keymap_item(fun, args, car, cdr, data);
} | conditional_block |
keymap.rs | //! Keymap support
use std;
use std::ptr;
use libc::c_void;
use remacs_macros::lisp_fn;
use crate::{
buffers::current_buffer,
data::{aref, fset, indirect_function, set},
eval::{autoload_do_load, unbind_to},
indent::indent_to,
keyboard,
keyboard::lucid_event_type_list_p,
lisp::LispObject,... |
/// Construct and return a new keymap, of the form (keymap CHARTABLE . ALIST).
/// CHARTABLE is a char-table that holds the bindings for all characters
/// without modifiers. All entries in it are initially nil, meaning
/// "command undefined". ALIST is an assoc-list which holds bindings for
/// function keys, mouse... | } | random_line_split |
keymap.rs | //! Keymap support
use std;
use std::ptr;
use libc::c_void;
use remacs_macros::lisp_fn;
use crate::{
buffers::current_buffer,
data::{aref, fset, indirect_function, set},
eval::{autoload_do_load, unbind_to},
indent::indent_to,
keyboard,
keyboard::lucid_event_type_list_p,
lisp::LispObject,... | (
key: LispObject,
accept_default: bool,
no_remap: bool,
mut position: LispObject,
) -> LispObject {
if key.is_vector() && position.is_nil() {
let key = key.force_vector();
if key.len() == 0 {
return Qnil;
}
// Mouse events may have a symbolic prefix indi... | key_binding | identifier_name |
mod.rs | use std::cmp::Ordering;
| ///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::orderings::ordering_from_str;
/// use std::cmp::Ordering;
///
/// assert_eq!(ordering_from_str("Equal"), Some(Ordering::Equal));
/// assert_eq!(ordering_from_str("Less"), Some(Ordering::Less));
//... | pub(crate) const ORDERINGS: [Ordering; 3] = [Ordering::Equal, Ordering::Less, Ordering::Greater];
/// Converts a `&str` to a `Ordering`.
///
/// If the `&str` does not represent a valid `Ordering`, `None` is returned. | random_line_split |
mod.rs | use std::cmp::Ordering;
pub(crate) const ORDERINGS: [Ordering; 3] = [Ordering::Equal, Ordering::Less, Ordering::Greater];
/// Converts a `&str` to a `Ordering`.
///
/// If the `&str` does not represent a valid `Ordering`, `None` is returned.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///... | (src: &str) -> Option<Ordering> {
match src {
"Equal" => Some(Ordering::Equal),
"Less" => Some(Ordering::Less),
"Greater" => Some(Ordering::Greater),
_ => None,
}
}
/// This module contains iterators that generate `Ordering`s without repetition.
pub mod exhaustive;
/// This modu... | ordering_from_str | identifier_name |
mod.rs | use std::cmp::Ordering;
pub(crate) const ORDERINGS: [Ordering; 3] = [Ordering::Equal, Ordering::Less, Ordering::Greater];
/// Converts a `&str` to a `Ordering`.
///
/// If the `&str` does not represent a valid `Ordering`, `None` is returned.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///... |
/// This module contains iterators that generate `Ordering`s without repetition.
pub mod exhaustive;
/// This module contains iterators that generate `Ordering`s randomly.
pub mod random;
| {
match src {
"Equal" => Some(Ordering::Equal),
"Less" => Some(Ordering::Less),
"Greater" => Some(Ordering::Greater),
_ => None,
}
} | identifier_body |
suite.py | #!/usr/bin/python
# #
# Copyright 2012-2019 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Res... | for fn in glob.glob('%s*' % log_fn):
os.remove(fn) | conditional_block | |
suite.py | #!/usr/bin/python
# #
# Copyright 2012-2019 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Res... | sys.exit(2)
else:
for fn in glob.glob('%s*' % log_fn):
os.remove(fn) | random_line_split | |
crm_lead.py | # -*- encoding: utf-8 -*-
###############################################################################
# #
# Copyright (C) 2016 Trustcode - www.trustcode.com.br #
# Danimar Ribeiro <danimaribeiro@gmail.co... |
return partner_ids
| partner_ids[lead.id] = partner.parent_id.id
lead.partner_id = partner.parent_id.id | conditional_block |
crm_lead.py | # -*- encoding: utf-8 -*-
###############################################################################
# #
# Copyright (C) 2016 Trustcode - www.trustcode.com.br #
# Danimar Ribeiro <danimaribeiro@gmail.co... | partner_ids = super(CrmLead, self).handle_partner_assignation(
action=action, partner_id=partner_id, context=context)
for lead in self:
partner_id = partner_ids[lead.id]
partner = self.env['res.partner'].browse(partner_id)
if partner.parent_id:
pa... | identifier_body | |
crm_lead.py | # Copyright (C) 2016 Trustcode - www.trustcode.com.br #
# Danimar Ribeiro <danimaribeiro@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
... | # -*- encoding: utf-8 -*-
###############################################################################
# # | random_line_split | |
crm_lead.py | # -*- encoding: utf-8 -*-
###############################################################################
# #
# Copyright (C) 2016 Trustcode - www.trustcode.com.br #
# Danimar Ribeiro <danimaribeiro@gmail.co... | (self, action='create',
partner_id=False, context=None):
partner_ids = super(CrmLead, self).handle_partner_assignation(
action=action, partner_id=partner_id, context=context)
for lead in self:
partner_id = partner_ids[lead.id]
partn... | handle_partner_assignation | identifier_name |
run.py | import sys
import os
import numpy as np
sys.path.append(os.path.join(os.getcwd(), ".."))
from run_utils import run_kmc, parse_input
from ParameterJuggler import ParameterSet
def main():
controller, path, app, cfg, n_procs = parse_input(sys.argv)
| heights = ParameterSet(cfg, "confiningSurfaceHeight\s*=\s*(.*)\;")
heights.initialize_set([20.])
diffusions = ParameterSet(cfg, "diffuse\s*=\s*(.*)\;")
diffusions.initialize_set([3])
controller.register_parameter_set(alpha_values)
controller.register_parameter_set(heights)
controller.regis... | alpha_values = ParameterSet(cfg, "alpha\s*=\s*(.*)\;")
alpha_values.initialize_set(np.linspace(0.5, 2, 16))
| random_line_split |
run.py | import sys
import os
import numpy as np
sys.path.append(os.path.join(os.getcwd(), ".."))
from run_utils import run_kmc, parse_input
from ParameterJuggler import ParameterSet
def main():
|
if __name__ == "__main__":
main()
| controller, path, app, cfg, n_procs = parse_input(sys.argv)
alpha_values = ParameterSet(cfg, "alpha\s*=\s*(.*)\;")
alpha_values.initialize_set(np.linspace(0.5, 2, 16))
heights = ParameterSet(cfg, "confiningSurfaceHeight\s*=\s*(.*)\;")
heights.initialize_set([20.])
diffusions = ParameterSet(cfg, "... | identifier_body |
run.py | import sys
import os
import numpy as np
sys.path.append(os.path.join(os.getcwd(), ".."))
from run_utils import run_kmc, parse_input
from ParameterJuggler import ParameterSet
def main():
controller, path, app, cfg, n_procs = parse_input(sys.argv)
alpha_values = ParameterSet(cfg, "alpha\s*=\s*(.*)\;")
a... | main() | conditional_block | |
run.py | import sys
import os
import numpy as np
sys.path.append(os.path.join(os.getcwd(), ".."))
from run_utils import run_kmc, parse_input
from ParameterJuggler import ParameterSet
def | ():
controller, path, app, cfg, n_procs = parse_input(sys.argv)
alpha_values = ParameterSet(cfg, "alpha\s*=\s*(.*)\;")
alpha_values.initialize_set(np.linspace(0.5, 2, 16))
heights = ParameterSet(cfg, "confiningSurfaceHeight\s*=\s*(.*)\;")
heights.initialize_set([20.])
diffusions = ParameterS... | main | identifier_name |
error.rs | extern crate hyper;
extern crate serde_json as json;
extern crate serde_qs as qs;
use params::to_snakecase;
use std::error;
use std::fmt;
use std::io;
use std::num::ParseIntError;
/// An error encountered when communicating with the Stripe API.
#[derive(Debug)]
pub enum Error {
/// An error reported by Stripe.
... |
}
impl error::Error for RequestError {
fn description(&self) -> &str {
self.message.as_ref().map(|s| s.as_str()).unwrap_or(
"request error",
)
}
}
#[doc(hidden)]
#[derive(Deserialize)]
pub struct ErrorObject {
pub error: RequestError,
}
/// An error encountered when communica... | {
write!(f, "{}({})", self.error_type, self.http_status)?;
if let Some(ref message) = self.message {
write!(f, ": {}", message)?;
}
Ok(())
} | identifier_body |
error.rs | extern crate hyper;
extern crate serde_json as json;
extern crate serde_qs as qs;
use params::to_snakecase;
use std::error;
use std::fmt;
use std::io;
use std::num::ParseIntError;
/// An error encountered when communicating with the Stripe API.
#[derive(Debug)]
pub enum Error {
/// An error reported by Stripe.
... |
/// The type of error returned.
#[serde(rename = "type")]
pub error_type: ErrorType,
/// A human-readable message providing more details about the error.
/// For card errors, these messages can be shown to end users.
#[serde(default)]
pub message: Option<String>,
/// For card errors, ... | #[serde(skip_deserializing)]
pub http_status: u16, | random_line_split |
error.rs | extern crate hyper;
extern crate serde_json as json;
extern crate serde_qs as qs;
use params::to_snakecase;
use std::error;
use std::fmt;
use std::io;
use std::num::ParseIntError;
/// An error encountered when communicating with the Stripe API.
#[derive(Debug)]
pub enum Error {
/// An error reported by Stripe.
... | (&self) -> Option<&error::Error> {
match *self {
WebhookError::BadHeader(ref err) => Some(err),
WebhookError::BadSignature => None,
WebhookError::BadTimestamp(_) => None,
WebhookError::BadParse(ref err) => Some(err),
}
}
}
| cause | identifier_name |
file.rs | use bytes;
use std;
use std::io::Read;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
pub fn list_dir(path: &Path) -> Vec<String> |
pub fn contents(path: &Path) -> bytes::Bytes {
let mut contents = Vec::new();
std::fs::File::open(path)
.and_then(|mut f| f.read_to_end(&mut contents))
.expect("Error reading file");
bytes::Bytes::from(contents)
}
pub fn is_executable(path: &Path) -> bool {
std::fs::metadata(path)
.expect("Gettin... | {
let mut v: Vec<_> = std::fs::read_dir(path)
.unwrap_or_else(|err| panic!("Listing dir {:?}: {:?}", path, err))
.map(|entry| {
entry
.expect("Error reading entry")
.file_name()
.to_string_lossy()
.to_string()
})
.collect();
v.sort();
v
} | identifier_body |
file.rs | use bytes;
use std;
use std::io::Read;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
pub fn list_dir(path: &Path) -> Vec<String> {
let mut v: Vec<_> = std::fs::read_dir(path)
.unwrap_or_else(|err| panic!("Listing dir {:?}: {:?}", path, err))
.map(|entry| {
entry
.expect("Error rea... | (path: &Path) -> bytes::Bytes {
let mut contents = Vec::new();
std::fs::File::open(path)
.and_then(|mut f| f.read_to_end(&mut contents))
.expect("Error reading file");
bytes::Bytes::from(contents)
}
pub fn is_executable(path: &Path) -> bool {
std::fs::metadata(path)
.expect("Getting file metadata")... | contents | identifier_name |
file.rs | use bytes;
use std;
use std::io::Read;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
| .map(|entry| {
entry
.expect("Error reading entry")
.file_name()
.to_string_lossy()
.to_string()
})
.collect();
v.sort();
v
}
pub fn contents(path: &Path) -> bytes::Bytes {
let mut contents = Vec::new();
std::fs::File::open(path)
.and_then(|mut f| f.read_to... | pub fn list_dir(path: &Path) -> Vec<String> {
let mut v: Vec<_> = std::fs::read_dir(path)
.unwrap_or_else(|err| panic!("Listing dir {:?}: {:?}", path, err)) | random_line_split |
index.tsx | import * as React from "react";
import * as ReactDOM from "react-dom";
import { hashHistory } from "react-router";
import configureStore from "./store/configureStore";
import { syncHistoryWithStore } from "react-router-redux";
import { createClient } from "../common/worker";
import { ElectronClient } from "../common/el... | document.getElementById("root"),
);
});
} | random_line_split | |
index.tsx | import * as React from "react";
import * as ReactDOM from "react-dom";
import { hashHistory } from "react-router";
import configureStore from "./store/configureStore";
import { syncHistoryWithStore } from "react-router-redux";
import { createClient } from "../common/worker";
import { ElectronClient } from "../common/el... | {
m.hot.accept("./root", () => {
// tslint:disable-next-line:variable-name
const NewRoot = require("./root").default;
const newRoutes = buildRoutes();
ReactDOM.render(
<AppContainer>
<NewRoot store={store} history={history} routes={newRoutes} />
... | conditional_block | |
project.rs | /*
* project.rs: Commands to save/load projects.
* Copyright (C) 2019 Oddcoder
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option... |
}
| {
let mut core = Core::new_no_colors();
core.stderr = Writer::new_buf();
core.stdout = Writer::new_buf();
let mut load = Load::new();
let mut save = Save::new();
core.io.open("malloc://0x500", IoMode::READ | IoMode::WRITE).unwrap();
core.io.open_at("malloc://0x133... | identifier_body |
project.rs | /*
* project.rs: Commands to save/load projects.
* Copyright (C) 2019 Oddcoder
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option... | (&mut self, core: &mut Core, args: &[String]) {
if args.len() != 1 {
expect(core, args.len() as u64, 1);
return;
}
let mut file = match File::open(&args[0]) {
Ok(file) => file,
Err(e) => return error_msg(core, "Failed to open file", &e.to_string())... | run | identifier_name |
project.rs | /*
* project.rs: Commands to save/load projects.
* Copyright (C) 2019 Oddcoder
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option... | core.stdout = Writer::new_buf();
let mut load = Load::new();
let mut save = Save::new();
core.io.open("malloc://0x500", IoMode::READ | IoMode::WRITE).unwrap();
core.io.open_at("malloc://0x1337", IoMode::READ | IoMode::WRITE, 0x31000).unwrap();
core.io.map(0x31000, 0xfff31... | random_line_split | |
test.ts | /*
* @license Apache-2.0
* | * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES ... | * Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); | random_line_split |
persistable.rs | use std::marker::PhantomData;
use expression::Expression;
use query_builder::{QueryBuilder, BuildQueryResult};
use query_source::{Table, Column};
use types::NativeSqlType;
/// Represents that a structure can be used to to insert a new row into the database.
/// Implementations can be automatically generated by
/// [`... | () -> Self::Columns {
<&'a U>::columns()
}
fn values(self) -> Self::Values {
InsertValues {
values: &*self,
_marker: PhantomData,
}
}
}
pub struct InsertValues<'a, T, U: 'a> {
values: &'a [U],
_marker: PhantomData<T>,
}
impl<'a, T, U> Expression fo... | columns | identifier_name |
persistable.rs | use std::marker::PhantomData;
use expression::Expression;
use query_builder::{QueryBuilder, BuildQueryResult};
use query_source::{Table, Column};
use types::NativeSqlType;
/// Represents that a structure can be used to to insert a new row into the database.
/// Implementations can be automatically generated by
/// [`... |
}
| {
Self::name().to_string()
} | identifier_body |
persistable.rs | use std::marker::PhantomData;
use expression::Expression;
use query_builder::{QueryBuilder, BuildQueryResult};
use query_source::{Table, Column};
use types::NativeSqlType;
/// Represents that a structure can be used to to insert a new row into the database.
/// Implementations can be automatically generated by
/// [`... | T: Table,
&'a U: Insertable<T>,
{
type SqlType = <<&'a U as Insertable<T>>::Columns as InsertableColumns<T>>::SqlType;
fn to_sql(&self, out: &mut QueryBuilder) -> BuildQueryResult {
self.to_insert_sql(out)
}
fn to_insert_sql(&self, out: &mut QueryBuilder) -> BuildQueryResult {
... | _marker: PhantomData<T>,
}
impl<'a, T, U> Expression for InsertValues<'a, T, U> where | random_line_split |
persistable.rs | use std::marker::PhantomData;
use expression::Expression;
use query_builder::{QueryBuilder, BuildQueryResult};
use query_source::{Table, Column};
use types::NativeSqlType;
/// Represents that a structure can be used to to insert a new row into the database.
/// Implementations can be automatically generated by
/// [`... |
try!(record.values().to_insert_sql(out));
}
Ok(())
}
}
impl<C: Column<Table=T>, T: Table> InsertableColumns<T> for C {
type SqlType = <Self as Expression>::SqlType;
fn names(&self) -> String {
Self::name().to_string()
}
}
| {
out.push_sql(", ");
} | conditional_block |
scripts.js | exports.BattleScripts = {
init: function() {
for (var i in this.data.Pokedex) {
var hp = this.modData('Pokedex', i).baseStats.hp;
var spd = this.modData('Pokedex', i).baseStats.atk; | var def = this.modData('Pokedex', i).baseStats.def;
var spa = this.modData('Pokedex', i).baseStats.spa;
var spd = this.modData('Pokedex', i).baseStats.spd;
var spe = this.modData('Pokedex', i).baseStats.spe;
this.modData('Pokedex', i).baseStats.hp = spe;
this.modData('Pokedex', i).baseStats.atk = spa;
this.modData('Pok... | random_line_split | |
webpack.config.js | var path = require("path");
var webpack = require("webpack");
var HtmlWebpackPlugin = require('html-webpack-plugin');
// start webpack in production mode by inlining the node env: `NODE_ENV=production webpack -p` (linux) or set NODE_ENV=production&&webpack -p (windows)
var isProd = process.env.NODE_ENV == "production"... |
module.exports = {
debug : !isProd,
devtool : isProd ? 'source-map' : 'eval-source-map', // see http://webpack.github.io/docs/configuration.html#devtool
entry: commonEntry,
output: output,
plugins: plugins,
devServer: {
port: PORT,
contentBase: './public',
stats: 'mini... | {
plugins.push(
new webpack.NoErrorsPlugin(), // Only emit files when there are no errors
new webpack.optimize.UglifyJsPlugin(), // http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
new CopyWebpackPlugin([{
from: __dirname + '/public' // Copy assets from the publi... | conditional_block |
webpack.config.js | var path = require("path");
var webpack = require("webpack");
var HtmlWebpackPlugin = require('html-webpack-plugin');
// start webpack in production mode by inlining the node env: `NODE_ENV=production webpack -p` (linux) or set NODE_ENV=production&&webpack -p (windows)
var isProd = process.env.NODE_ENV == "production"... | proxy: {
'/api/*': {
target: 'http://127.0.0.1:8080',
secure: false
},
'/eventbus/*': {
target: 'http://127.0.0.1:8080',
secure: false,
ws: true
}
}
},
jshint: {
... | random_line_split | |
__init__.py | # (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> and others
#
# This file is part of Ansible
#
# Ansible 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 Foun... | )
callback_loader = PluginLoader(
'CallbackModule',
'ansible.plugins.callback',
C.DEFAULT_CALLBACK_PLUGIN_PATH,
'callback_plugins',
)
connection_loader = PluginLoader(
'Connection',
'ansible.plugins.connections',
C.DEFAULT_CONNECTION_PLUGIN_PATH,
'connection_plugins',
aliases={'par... | C.DEFAULT_CACHE_PLUGIN_PATH,
'cache_plugins', | random_line_split |
__init__.py | # (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> and others
#
# This file is part of Ansible
#
# Ansible 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 Foun... | (self, name, suffixes=None):
''' Find a plugin named name '''
if not suffixes:
if self.class_name:
suffixes = ['.py']
else:
suffixes = ['.py', '']
potential_names = frozenset('%s%s' % (name, s) for s in suffixes)
for full_name in ... | find_plugin | identifier_name |
__init__.py | # (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> and others
#
# This file is part of Ansible
#
# Ansible 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 Foun... |
action_loader = PluginLoader(
'ActionModule',
'ansible.plugins.action',
C.DEFAULT_ACTION_PLUGIN_PATH,
'action_plugins',
required_base_class='ActionBase',
)
cache_loader = PluginLoader(
'CacheModule',
'ansible.plugins.cache',
C.DEFAULT_CACHE_PLUGIN_PATH,
'cache_plugins',
)
callbac... | '''
PluginLoader loads plugins from the configured plugin directories.
It searches for plugins by iterating through the combined list of
play basedirs, configured paths, and the python path.
The first match is used.
'''
def __init__(self, class_name, package, config, subdir, aliases={}, requir... | identifier_body |
__init__.py | # (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> and others
#
# This file is part of Ansible
#
# Ansible 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 Foun... |
action_loader = PluginLoader(
'ActionModule',
'ansible.plugins.action',
C.DEFAULT_ACTION_PLUGIN_PATH,
'action_plugins',
required_base_class='ActionBase',
)
cache_loader = PluginLoader(
'CacheModule',
'ansible.plugins.cache',
C.DEFAULT_CACHE_PLUGIN_PATH,
'cache_plugins',
)
callbac... | matches = glob.glob(os.path.join(i, "*.py"))
matches.sort()
for path in matches:
name, ext = os.path.splitext(os.path.basename(path))
if name.startswith("_"):
continue
if path not in self._module_cache:
self... | conditional_block |
breakpoint.py | '''
Created on Jun 11, 2011
@author: mkiyer
'''
class | (object):
def __init__(self):
self.name = None
self.seq5p = None
self.seq3p = None
self.chimera_names = []
@property
def pos(self):
"""
return position of break along sequence measured from 5' -> 3'
"""
return len(self.seq5p)
@static... | Breakpoint | identifier_name |
breakpoint.py | '''
Created on Jun 11, 2011 | @author: mkiyer
'''
class Breakpoint(object):
def __init__(self):
self.name = None
self.seq5p = None
self.seq3p = None
self.chimera_names = []
@property
def pos(self):
"""
return position of break along sequence measured from 5' -> 3'
"""
... | random_line_split | |
breakpoint.py | '''
Created on Jun 11, 2011
@author: mkiyer
'''
class Breakpoint(object):
def __init__(self):
self.name = None
self.seq5p = None
self.seq3p = None
self.chimera_names = []
@property
def pos(self):
"""
return position of break along sequence measured fr... |
def to_list(self):
fields = [self.name, self.seq5p, self.seq3p]
fields.append(','.join(self.chimera_names))
return fields | b = Breakpoint()
b.name = fields[0]
b.seq5p = fields[1]
b.seq3p = fields[2]
b.chimera_names = fields[3].split(',')
return b | identifier_body |
promoted_errors.rs | // 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | random_line_split | |
promoted_errors.rs | // Copyright 2018 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 ... | {
println!("{}", 0u32 - 1);
let _x = 0u32 - 1;
//~^ WARN const_err
println!("{}", 1/(1-1));
//~^ WARN const_err
let _x = 1/(1-1);
//~^ WARN const_err
//~| WARN const_err
println!("{}", 1/(false as u32));
//~^ WARN const_err
let _x = 1/(false as u32);
//~^ WARN const_err
... | identifier_body | |
promoted_errors.rs | // Copyright 2018 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 ... | () {
println!("{}", 0u32 - 1);
let _x = 0u32 - 1;
//~^ WARN const_err
println!("{}", 1/(1-1));
//~^ WARN const_err
let _x = 1/(1-1);
//~^ WARN const_err
//~| WARN const_err
println!("{}", 1/(false as u32));
//~^ WARN const_err
let _x = 1/(false as u32);
//~^ WARN const_er... | main | identifier_name |
lib.rs | extern crate yassy;
extern crate gnuplot;
use yassy::utils;
use yassy::utils::*;
use self::gnuplot::*;
pub fn | (nt: usize, nppt: usize, nn: usize, fs: f64, fhabs: &[f64], outname: &str) {
// The axis of fhabs has nn/2+1 points, representing frequencies from 0 to fl/2,
// or i*(fl/2)/(nn/2) = i*fl/nn = i*fs*(nppt-1)/nn for i=0..nn/2. (Because
// fl=1/Tl=fs*(nppt-1)) We are only interested in
// frequencies up to... | plot_ampl_spec | identifier_name |
lib.rs | extern crate yassy;
extern crate gnuplot;
use yassy::utils;
use yassy::utils::*;
use self::gnuplot::*;
pub fn plot_ampl_spec(nt: usize, nppt: usize, nn: usize, fs: f64, fhabs: &[f64], outname: &str) | {
// The axis of fhabs has nn/2+1 points, representing frequencies from 0 to fl/2,
// or i*(fl/2)/(nn/2) = i*fl/nn = i*fs*(nppt-1)/nn for i=0..nn/2. (Because
// fl=1/Tl=fs*(nppt-1)) We are only interested in
// frequencies up to around fi=60KHz, or i= 60KHz*nn/(fs*(nppt-1)).
let npptf64=nppt as f6... | identifier_body | |
lib.rs | extern crate yassy;
extern crate gnuplot;
use yassy::utils;
use yassy::utils::*;
use self::gnuplot::*;
pub fn plot_ampl_spec(nt: usize, nppt: usize, nn: usize, fs: f64, fhabs: &[f64], outname: &str) {
// The axis of fhabs has nn/2+1 points, representing frequencies from 0 to fl/2,
// or i*(fl/2)/(nn/2) = i*f... | let ntf64=nt as f64;
// Find index such that the horizontal axis of the plot is fmax, i.e.
// i = fmax*nn/(fs*(nppt-1))
let fac = (nn as f64)/(fs*(npptf64-1f64));
let i_fi = (60000f64*fac).round();
println!("fac: {}", fac);
println!("i_fi: {}", i_fi);
let mut f = vec![0f64; nn/2+1];
... | // frequencies up to around fi=60KHz, or i= 60KHz*nn/(fs*(nppt-1)).
let npptf64=nppt as f64; | random_line_split |
log.py | """
Logger classes for the ZAP CLI.
.. moduleauthor:: Daniel Grunwell (grunny)
"""
import logging
import sys
from termcolor import colored
class ColorStreamHandler(logging.StreamHandler):
"""
StreamHandler that prints color. This is used by the console client.
"""
level_map = {
logging.DEB... | (self, name):
super(ConsoleLogger, self).__init__(name)
self.setLevel(logging.DEBUG)
self.addHandler(ColorStreamHandler(sys.stdout))
# Save the current logger
default_logger_class = logging.getLoggerClass()
# Console logging for CLI
logging.setLoggerClass(ConsoleLogger)
console = logging.getLo... | __init__ | identifier_name |
log.py | """
Logger classes for the ZAP CLI.
.. moduleauthor:: Daniel Grunwell (grunny)
"""
import logging
import sys
from termcolor import colored
class ColorStreamHandler(logging.StreamHandler):
"""
StreamHandler that prints color. This is used by the console client.
"""
level_map = {
logging.DEB... |
else:
prefix = str('[' + record.levelname + ']').ljust(18)
record.msg = prefix + record.msg
logging.StreamHandler.emit(self, record)
class ConsoleLogger(logging.Logger):
"""Log to the console with some color decorations."""
def __init__(self, name):
super(Console... | color, attr = self.level_map[record.levelno]
prefix = colored(str('[' + record.levelname + ']').ljust(18), color, attrs=attr)
if hasattr(record, 'highlight') and record.highlight:
record.msg = colored(record.msg, color, attrs=['bold', 'reverse']) | conditional_block |
log.py | """
Logger classes for the ZAP CLI.
.. moduleauthor:: Daniel Grunwell (grunny)
"""
import logging
import sys
from termcolor import colored
class ColorStreamHandler(logging.StreamHandler):
"""
StreamHandler that prints color. This is used by the console client.
"""
level_map = {
logging.DEB... |
def emit(self, record):
colorize = 'console' in globals() and getattr(console, 'colorize', False)
if self.is_tty and colorize:
color, attr = self.level_map[record.levelno]
prefix = colored(str('[' + record.levelname + ']').ljust(18), color, attrs=attr)
if hasat... | """is the stream a tty?"""
isatty = getattr(self.stream, 'isatty', None)
return isatty and isatty() | identifier_body |
log.py | """
Logger classes for the ZAP CLI.
.. moduleauthor:: Daniel Grunwell (grunny)
"""
import logging
import sys
from termcolor import colored
class ColorStreamHandler(logging.StreamHandler):
"""
StreamHandler that prints color. This is used by the console client.
"""
level_map = {
logging.DEB... | # Save the current logger
default_logger_class = logging.getLoggerClass()
# Console logging for CLI
logging.setLoggerClass(ConsoleLogger)
console = logging.getLogger('zap')
# Restore the previous logger
logging.setLoggerClass(default_logger_class) | self.setLevel(logging.DEBUG)
self.addHandler(ColorStreamHandler(sys.stdout))
| random_line_split |
SendTestEmail.controller.js | angular.module("umbraco").controller("SendTestEmailController.Controller", function ($scope, assetsService, $http, $routeParams, notificationsService) {
$scope.loading = false;
$scope.init = function () {
if ($scope.model.value == null || $scope.model.value == "") {
// Set default if nothin... | $scope.sendTestEmail = function () {
$scope.loading = true;
if ($scope.model.value.recipient != "") {
$http.post("/base/PerplexMail/SendTestMail?id=" + $routeParams.id, { EmailAddresses: _.pluck($scope.model.value.recipients, 'value'), EmailNodeId: $routeParams.id, Tags: $scope.model.va... | }
};
| random_line_split |
karma.conf.js | // Karma configuration
// Generated on Wed Sep 21 2016 00:37:04 GMT+0900 (KST)
module.exports = function (config) {
var configuration = {
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://... |
config.set()
}
| {
configuration.browsers = ['Chrome_travis_ci'];
} | conditional_block |
karma.conf.js | // Karma configuration
// Generated on Wed Sep 21 2016 00:37:04 GMT+0900 (KST)
module.exports = function (config) {
var configuration = {
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://... | } | if (process.env.TRAVIS) {
configuration.browsers = ['Chrome_travis_ci'];
}
config.set() | random_line_split |
__init__.py | #-*- coding: utf-8 -*-
# Author: Matt Earnshaw <matt@earnshaw.org.uk>
from __future__ import absolute_import | from sunpy.io import UnrecognizedFileTypeError
class Plotman(object):
""" Wraps a MainWindow so PlotMan instances can be created via the CLI.
Examples
--------
from sunpy.gui import Plotman
plots = Plotman("data/examples")
plots.show()
"""
def __init__(self, *path... | import os
import sys
import sunpy
from PyQt4.QtGui import QApplication
from sunpy.gui.mainwindow import MainWindow | random_line_split |
__init__.py | #-*- coding: utf-8 -*-
# Author: Matt Earnshaw <matt@earnshaw.org.uk>
from __future__ import absolute_import
import os
import sys
import sunpy
from PyQt4.QtGui import QApplication
from sunpy.gui.mainwindow import MainWindow
from sunpy.io import UnrecognizedFileTypeError
class Plotman(object):
""" Wraps a MainWin... |
def open_files(self, inputs):
VALID_EXTENSIONS = [".jp2", ".fits", ".fts"]
to_open = []
# Determine files to process
for input_ in inputs:
if os.path.isfile(input_):
to_open.append(input_)
elif os.path.isdir(input_):
... | """ *paths: directories containing FITS paths
or FITS paths to be opened in PlotMan """
self.app = QApplication(sys.argv)
self.main = MainWindow()
self.open_files(paths) | identifier_body |
__init__.py | #-*- coding: utf-8 -*-
# Author: Matt Earnshaw <matt@earnshaw.org.uk>
from __future__ import absolute_import
import os
import sys
import sunpy
from PyQt4.QtGui import QApplication
from sunpy.gui.mainwindow import MainWindow
from sunpy.io import UnrecognizedFileTypeError
class Plotman(object):
""" Wraps a MainWin... |
elif os.path.isdir(input_):
for file_ in os.listdir(input_):
to_open.append(file_)
else:
raise IOError("Path " + input_ + " does not exist.")
# Load files
for filepath in to_open:
name, ext = os.path.splitext(filep... | to_open.append(input_) | conditional_block |
__init__.py | #-*- coding: utf-8 -*-
# Author: Matt Earnshaw <matt@earnshaw.org.uk>
from __future__ import absolute_import
import os
import sys
import sunpy
from PyQt4.QtGui import QApplication
from sunpy.gui.mainwindow import MainWindow
from sunpy.io import UnrecognizedFileTypeError
class Plotman(object):
""" Wraps a MainWin... | (self):
self.main.show()
self.app.exec_()
if __name__=="__main__":
from sunpy.gui import Plotman
plots = Plotman(sunpy.AIA_171_IMAGE)
plots.show()
| show | identifier_name |
nodejs.py | #!/usr/bin/env python
# Copyright 2016 DIANA-HEP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
tmp = tempfile.NamedTemporaryFile(delete=False)
if isinstance(vegaSpec, dict):
vegaSpec = json.dump(tmp, vegaSpec)
else:
tmp.write(vegaSpec)
tmp.close()
if outputFile is None:
vg2x = subprocess.Popen([cmd, tmp.name], stdout=subprocess.PIPE, env=dict(
os.envir... | raise IOError("Nodejs Package Manager 'npm' must be installed to use nodejs.write function.") | conditional_block |
nodejs.py | #!/usr/bin/env python
# Copyright 2016 DIANA-HEP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | if isinstance(vegaSpec, dict):
vegaSpec = json.dump(tmp, vegaSpec)
else:
tmp.write(vegaSpec)
tmp.close()
if outputFile is None:
vg2x = subprocess.Popen([cmd, tmp.name], stdout=subprocess.PIPE, env=dict(
os.environ, PATH=npmbin + ":" + os.environ.get("PATH", "")))
... |
tmp = tempfile.NamedTemporaryFile(delete=False)
| random_line_split |
nodejs.py | #!/usr/bin/env python
# Copyright 2016 DIANA-HEP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | (vegaSpec, outputFile, format=None):
"""Use the 'vega' package in Nodejs to write to SVG or PNG files.
Unlike interactive plotting, this does not require a round trip through a web browser, but it does require a
Nodejs installation on your computer (to evaluate the Javascript).
To install the prerequi... | write | identifier_name |
nodejs.py | #!/usr/bin/env python
# Copyright 2016 DIANA-HEP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | """Use the 'vega' package in Nodejs to write to SVG or PNG files.
Unlike interactive plotting, this does not require a round trip through a web browser, but it does require a
Nodejs installation on your computer (to evaluate the Javascript).
To install the prerequisites on an Ubuntu system, do
# ... | identifier_body | |
schedule-service.spec.ts | import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {inject, TestBed} from '@angular/core/testing';
import {ScheduleService} from './schedule-service';
import {HTTP_INTERCEPTORS} from '@angular/common/http';
import {ErrorInterceptor} from '../shared/http-error-interceptor... | req.flush('', { status: 204, statusText: 'Not content' });
});
it('should return a day time frame schedule', () => {
const service = TestBed.get(ScheduleService);
const httpMock = TestBed.get(HttpTestingController);
const applianceId = ApplianceTestdata.getApplianceId();
service.getSchedules(ap... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.