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 |
|---|---|---|---|---|
call.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
}
| {
let s = r#"{
"data" : "0x1234",
"destination" : "5a39ed1020c04d4d84539975b893a4e7c53eab6c",
"gasLimit" : "0x1748766aa5",
"value" : "0x00"
}"#;
let call: Call = serde_json::from_str(s).unwrap();
assert_eq!(&call.data[..], &[0x12, 0x34]);
assert_eq!(call.destination, MaybeEmpty::Some(Address(Has... | identifier_body |
Signature.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as _ from 'underscore';
import { Letter } from './letter';
| export namespace Signature {
export interface Props {
template: ITemplateModel;
user: IUserDetails;
}
export interface State {
name: string,
signatureHtml: string;
}
}
export class Signature extends React.Component<Signature.Props, Signature.State> {
constructor(props?: Signature.Props, cont... | random_line_split | |
Signature.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as _ from 'underscore';
import { Letter } from './letter';
export namespace Signature {
export interface Props {
template: ITemplateModel;
user: IUserDetails;
}
export interface State {
name: string,
signatureHtml: s... |
public componentDidMount() {
this.assembleSignature.bind(this)(this.props.template, this.props.user);
}
public componentWillReceiveProps(nextProps: Signature.Props) {
this.assembleSignature.bind(this)(nextProps.template, nextProps.user);
}
private assembleSignature(template: ITemplateModel, data: ... | {
super(props, context);
this.state = {
name: '',
signatureHtml: ''
}
} | identifier_body |
Signature.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as _ from 'underscore';
import { Letter } from './letter';
export namespace Signature {
export interface Props {
template: ITemplateModel;
user: IUserDetails;
}
export interface State {
name: string,
signatureHtml: s... | () {
this.assembleSignature.bind(this)(this.props.template, this.props.user);
}
public componentWillReceiveProps(nextProps: Signature.Props) {
this.assembleSignature.bind(this)(nextProps.template, nextProps.user);
}
private assembleSignature(template: ITemplateModel, data: IUserDetails) {
_.templa... | componentDidMount | identifier_name |
p051.rs | //! [Problem 51](https://projecteuler.net/problem=51) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use integer::Integer;
use prime::PrimeSet;
fn compute(num_value: usize) -> u64 {
let radix = 10;
let ps = Prim... | }
} | random_line_split | |
p051.rs | //! [Problem 51](https://projecteuler.net/problem=51) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use integer::Integer;
use prime::PrimeSet;
fn compute(num_value: usize) -> u64 {
let radix = 10;
let ps = Prim... | else { d });
if ps.contains(Integer::from_digits(it, radix as u64)) {
num_prime += 1;
}
}
if num_prime >= num_value {
return p;
}
}
}
unreachable!()
}
fn solve() -> String {
compute(8).to_strin... | { d_dst as u64 } | conditional_block |
p051.rs | //! [Problem 51](https://projecteuler.net/problem=51) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use integer::Integer;
use prime::PrimeSet;
fn compute(num_value: usize) -> u64 {
let radix = 10;
let ps = Prim... |
common::problem!("121313", solve);
#[cfg(test)]
mod tests {
#[test]
fn seven() {
assert_eq!(56003, super::compute(7))
}
}
| {
compute(8).to_string()
} | identifier_body |
p051.rs | //! [Problem 51](https://projecteuler.net/problem=51) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use integer::Integer;
use prime::PrimeSet;
fn compute(num_value: usize) -> u64 {
let radix = 10;
let ps = Prim... | () -> String {
compute(8).to_string()
}
common::problem!("121313", solve);
#[cfg(test)]
mod tests {
#[test]
fn seven() {
assert_eq!(56003, super::compute(7))
}
}
| solve | identifier_name |
Reducers.js | /*
* This file is part of the Kreta package.
*
* (c) Beñat Espiña <benatespina@gmail.com> |
import {combineReducers} from 'redux';
import {routeReducer as routing} from 'react-router-redux';
import {reducer as form} from 'redux-form';
import currentOrganization from './reducers/CurrentOrganization';
import currentProject from './reducers/CurrentProject';
import dashboard from './reducers/Dashboard';
import ... | * (c) Gorka Laucirica <gorka.lauzirika@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/ | random_line_split |
vaadin-grid-tree-column.d.ts | /**
* DO NOT EDIT
*
* This file was automatically generated by
* https://github.com/Polymer/tools/tree/master/packages/gen-typescript-declarations
*
* To modify these typings, edit the source file(s):
* src/vaadin-grid-tree-column.js
*/
// tslint:disable:variable-name Describing an API that's defined else... | extends GridColumnElement {
/**
* JS Path of the property in the item used as text content for the tree toggle.
*/
path: string|null|undefined;
/**
* JS Path of the property in the item that indicates whether the item has child items.
* @attr {string} item-has-children-path
*/
itemHasChildrenP... | GridTreeColumnElement | identifier_name |
vaadin-grid-tree-column.d.ts | /**
* DO NOT EDIT
*
* This file was automatically generated by
* https://github.com/Polymer/tools/tree/master/packages/gen-typescript-declarations
*
* To modify these typings, edit the source file(s):
* src/vaadin-grid-tree-column.js
*/
// tslint:disable:variable-name Describing an API that's defined else... | export {GridTreeColumnElement}; | random_line_split | |
IfcLightIntensityDistribution.g.ts |
import {BaseIfc} from "./BaseIfc"
import {IfcLightDistributionCurveEnum} from "./IfcLightDistributionCurveEnum.g"
import {IfcLightDistributionData} from "./IfcLightDistributionData.g"
/**
* http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifclightintensitydistribution.htm
*/
export class IfcLightIntensity... |
getStepParameters() : string {
var parameters = new Array<string>();
parameters.push(BaseIfc.toStepValue(this.LightDistributionCurve))
parameters.push(BaseIfc.toStepValue(this.DistributionData))
return parameters.join();
}
} | {
super()
this.LightDistributionCurve = lightDistributionCurve
this.DistributionData = distributionData
} | identifier_body |
IfcLightIntensityDistribution.g.ts | import {BaseIfc} from "./BaseIfc"
import {IfcLightDistributionCurveEnum} from "./IfcLightDistributionCurveEnum.g"
import {IfcLightDistributionData} from "./IfcLightDistributionData.g"
/**
* http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifclightintensitydistribution.htm
*/
export class IfcLightIntensityD... | constructor(lightDistributionCurve : IfcLightDistributionCurveEnum, distributionData : Array<IfcLightDistributionData>) {
super()
this.LightDistributionCurve = lightDistributionCurve
this.DistributionData = distributionData
}
getStepParameters() : string {
var parameters = new Array<str... | DistributionData : Array<IfcLightDistributionData>
| random_line_split |
IfcLightIntensityDistribution.g.ts |
import {BaseIfc} from "./BaseIfc"
import {IfcLightDistributionCurveEnum} from "./IfcLightDistributionCurveEnum.g"
import {IfcLightDistributionData} from "./IfcLightDistributionData.g"
/**
* http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifclightintensitydistribution.htm
*/
export class IfcLightIntensity... | () : string {
var parameters = new Array<string>();
parameters.push(BaseIfc.toStepValue(this.LightDistributionCurve))
parameters.push(BaseIfc.toStepValue(this.DistributionData))
return parameters.join();
}
} | getStepParameters | identifier_name |
ContextSettingsWidget.py | from rezgui.qt import QtGui
from rezgui.util import create_pane
from rezgui.mixins.ContextViewMixin import ContextViewMixin
from rezgui.models.ContextModel import ContextModel
from rez.config import config
from rez.vendor import yaml
from rez.vendor.yaml.error import YAMLError
from rez.vendor.schema.schema import Schem... | return
self._update_text()
def apply_changes(self):
def _content_error(title, text):
ret = QtGui.QMessageBox.warning(self, title, text,
QtGui.QMessageBox.Discard,
QtGui.QMessageBox.Cancel... | self._update_text()
def _contextChanged(self, flags=0):
if not (flags & ContextModel.CONTEXT_CHANGED): | random_line_split |
ContextSettingsWidget.py | from rezgui.qt import QtGui
from rezgui.util import create_pane
from rezgui.mixins.ContextViewMixin import ContextViewMixin
from rezgui.models.ContextModel import ContextModel
from rez.config import config
from rez.vendor import yaml
from rez.vendor.yaml.error import YAMLError
from rez.vendor.schema.schema import Schem... | (self, flags=0):
if not (flags & ContextModel.CONTEXT_CHANGED):
return
self._update_text()
def apply_changes(self):
def _content_error(title, text):
ret = QtGui.QMessageBox.warning(self, title, text,
QtGui.QMessageBox.Disca... | _contextChanged | identifier_name |
ContextSettingsWidget.py | from rezgui.qt import QtGui
from rezgui.util import create_pane
from rezgui.mixins.ContextViewMixin import ContextViewMixin
from rezgui.models.ContextModel import ContextModel
from rez.config import config
from rez.vendor import yaml
from rez.vendor.yaml.error import YAMLError
from rez.vendor.schema.schema import Schem... | super(ContextSettingsWidget, self).__init__(parent)
ContextViewMixin.__init__(self, context_model)
self.schema_keys = set(self.schema_dict.iterkeys())
if attributes:
self.schema_keys &= set(attributes)
assert self.schema_keys
schema_dict = dict((k, v) fo... | titles = {
"packages_path": "Search path for Rez packages",
"implicit_packages": "Packages that are implicitly added to the request",
"package_filter": "Package exclusion/inclusion rules"
}
schema_dict = {
"packages_path": [basestring],
"implicit_p... | identifier_body |
ContextSettingsWidget.py | from rezgui.qt import QtGui
from rezgui.util import create_pane
from rezgui.mixins.ContextViewMixin import ContextViewMixin
from rezgui.models.ContextModel import ContextModel
from rez.config import config
from rez.vendor import yaml
from rez.vendor.yaml.error import YAMLError
from rez.vendor.schema.schema import Schem... |
self._update_text()
def apply_changes(self):
def _content_error(title, text):
ret = QtGui.QMessageBox.warning(self, title, text,
QtGui.QMessageBox.Discard,
QtGui.QMessageBox.Cancel)
if r... | return | conditional_block |
imf_tot_gov_rev.js | width = parseInt(d3.select('#chart').style('width'), 10),
width = 900 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.1);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.sc... |
// d3.csv(datafile, function (error, data) {
d3.json(datafile, function (error, data) {
var groupSpacing = 0,
opts = [],
years = [],
cat_names = [];
data.sort(function (a, b) {
return a.year - b.year;
});
data.forEach(function (el) {
if (opts.indexOf(el.name)... | {
return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1);
} | identifier_body |
imf_tot_gov_rev.js | ([height, 0]);
var color = d3.scale.ordinal()
.range(["#4f7184", "#ff6f4a"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format('s'));
// Change D3's SI prefix to more business friendly units
// ... | mouseleave | identifier_name | |
imf_tot_gov_rev.js | width = parseInt(d3.select('#chart').style('width'), 10),
width = 900 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.1);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.sc... |
d3.select("#chart_title")
.text(country_init);
d3.select("body").append("div")
.attr("class", "citation")
.style("width", width + "px")
.html("<small><em>Graphic by: Chris Perry | Source: <a href='" + citation_url + "' target='_blank'>" + citation_text + "</a> and the <a href='... | .attr("x", function (d) { return x1(d.name); })
.attr("y", function (d) { return y(d.value); })
.attr("height", function (d) { return height - y(d.value); })
.style("fill", function (d) { return color(d.name); })
.on("mouseover", mouseover); | random_line_split |
imf_tot_gov_rev.js | width = parseInt(d3.select('#chart').style('width'), 10),
width = 900 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.1);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.sc... |
i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3));
}
return d3_formatPrefixes[8 + i / 3];
};
function d3_formatPrefix(d, i) {
var k = Math.pow(10, Math.abs(8 - i) * 3);
return {
scale: i > 8 ? function (d) { re... | {
value = d3.round(value, d3_format_precision(value, precision));
} | conditional_block |
toolbar.py | # -*- mode: python; indent-tabs-mode: nil; tab-width: 3 -*-
# vim: set tabstop=3 shiftwidth=3 expandtab:
#
# Copyright (C) 2001-2005 Ichiro Fujinaga, Michael Droettboom,
# and Karl MacMillan
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU ... | button = ToggleButtonClass(self, id, bitmap, size=wx.Size(30,30))
button.SetBezelWidth(1)
button.SetUseFocusIndicator(False)
compat_wx.set_tool_tip(button, help_string)
if callback:
compat_wx.handle_event_1(self, wx.EVT_BUTTON, callback, id)
self.sizer.Add(button, flag=wx... | if not toggle:
button = ButtonClass(self, id, bitmap, size=wx.Size(30,30))
else: | random_line_split |
toolbar.py | # -*- mode: python; indent-tabs-mode: nil; tab-width: 3 -*-
# vim: set tabstop=3 shiftwidth=3 expandtab:
#
# Copyright (C) 2001-2005 Ichiro Fujinaga, Michael Droettboom,
# and Karl MacMillan
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU ... |
def AddControl(self, control):
self.sizer.Add(control, flag=wx.ALIGN_CENTER)
self.sizer.SetSizeHints(self)
self.controls.append(control)
def AddSeparator(self):
self.sizer.Add(wx.Panel(self, -1, size=wx.Size(5, 2)))
self.sizer.SetSizeHints(self)
def OnHideToolbar(self, event):... | if not toggle:
button = buttons.GenBitmapTextButton(
self, id, None, text, size=wx.Size(48, 28))
else:
button = buttons.GenBitmapTextToggleButton(
self, id, None, text, size=wx.Size(48,28))
button.SetBitmapLabel(gamera_icons.getToolbarMenuBitmap())
button.Se... | identifier_body |
toolbar.py | # -*- mode: python; indent-tabs-mode: nil; tab-width: 3 -*-
# vim: set tabstop=3 shiftwidth=3 expandtab:
#
# Copyright (C) 2001-2005 Ichiro Fujinaga, Michael Droettboom,
# and Karl MacMillan
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU ... |
self.SetSizeHints(-1, -1, -1, -1, -1, -1)
self.SetSize(wx.Size(self.GetSize().x, 12))
self.Layout()
self.GetParent().Layout()
self.GetParent().Refresh()
def OnShowToolbar(self, event):
self.close_button.Show()
self.open_button.Hide()
for control in self.controls:
... | control.Hide() | conditional_block |
toolbar.py | # -*- mode: python; indent-tabs-mode: nil; tab-width: 3 -*-
# vim: set tabstop=3 shiftwidth=3 expandtab:
#
# Copyright (C) 2001-2005 Ichiro Fujinaga, Michael Droettboom,
# and Karl MacMillan
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU ... | (self, id, text, help_string, callback=None, toggle=0):
if not toggle:
button = buttons.GenBitmapTextButton(
self, id, None, text, size=wx.Size(48, 28))
else:
button = buttons.GenBitmapTextToggleButton(
self, id, None, text, size=wx.Size(48,28))
button.SetBi... | AddMenuTool | identifier_name |
transaction.py | is not empty, the path is outside main opener reach.
# use 'location' value as a key in a vfsmap to find the right 'vfs'
# (cache is currently unused)
self._backupentries = []
self._backupmap = {}
self._backupjournal = "%s.backupfiles" % self.journal
self._backupsfile ... | This is used to allow hooks to view a transaction before commit""" | random_line_split | |
transaction.py | (
journal,
report,
opener,
vfsmap,
entries,
backupentries,
unlink=True,
checkambigfiles=None,
):
for f, o, _ignore in entries:
if o or not unlink:
checkambig = checkambigfiles and (f, "") in checkambigfiles
try:
util.truncatefile(f, ope... | _playback | identifier_name | |
transaction.py | 's first argument.
Category is a unique identifier to allow overwriting old callbacks with
newer callbacks.
"""
self._finalizecallback[category] = callback
@active
def addpostclose(self, category, callback):
"""add or replace a callback to be called after the transactio... | for line in lines[1:]:
if line:
# Shave off the trailing newline
line = line[:-1]
line = decodeutf8(line)
try:
l, f, b, c = line.split("\0")
except Valu... | conditional_block | |
transaction.py | self.entries = []
self.map = {}
self.journal = journalname
self.undoname = undoname
self._queue = []
# A callback to validate transaction content before closing it.
# should raise exception is anything is wrong.
# target user is repository hooks.
i... |
@active
def registertmp(self, tmpfile, location=""):
"""register a temporary transaction file
Such files will be deleted when the transaction exits (on both
failure and success).
"""
self._addbackupentry((location, "", tmpfile, False))
@active
def addfilegener... | """register a new backup entry and write it to disk"""
self._backupentries.append(entry)
self._backupmap[entry[1]] = len(self._backupentries) - 1
self._backupsfile.write(encodeutf8("%s\0%s\0%s\0%d\n" % entry))
self._backupsfile.flush() | identifier_body |
costFunctionChecker.py | -05-01 20:31:43Z behrisch $
Run duarouter repeatedly and simulate weight changes via a cost function.
SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
Copyright (C) 2009-2013 DLR (http://www.dlr.de/) and contributors
All rights reserved
"""
import os, sys, subprocess, types
from datetime import da... | (self, edge):
return self._edgeWeights.get(edge, 0)
def getMaxDepart(self):
return self._maxDepart
class NetReader(handler.ContentHandler):
def __init__(self):
self._edges = []
def startElement(self, name, attrs):
if name == 'edge':
if not attrs.has_key('funct... | getWeight | identifier_name |
costFunctionChecker.py | -05-01 20:31:43Z behrisch $
Run duarouter repeatedly and simulate weight changes via a cost function.
SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
Copyright (C) 2009-2013 DLR (http://www.dlr.de/) and contributors
All rights reserved
"""
import os, sys, subprocess, types
from datetime import da... |
output = tripFile[:tripFile.find(".")] + "_%s.rou.xml" % step
print ">> Running router with " + file
btime = datetime.now()
print ">>> Begin time: %s" % btime
writeRouteConf(step, options, file, output)
retCode = call([duaBinary, "-c", "iteration_%s.d | file = tripFile[:tripFile.find(".")] + "_%s.rou.alt.xml" % (step-1) | conditional_block |
costFunctionChecker.py | -05-01 20:31:43Z behrisch $
Run duarouter repeatedly and simulate weight changes via a cost function.
SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
Copyright (C) 2009-2013 DLR (http://www.dlr.de/) and contributors
All rights reserved
"""
import os, sys, subprocess, types
from datetime import da... |
def getWeight(self, edge):
return self._edgeWeights.get(edge, 0)
def getMaxDepart(self):
return self._maxDepart
class NetReader(handler.ContentHandler):
def __init__(self):
self._edges = []
def startElement(self, name, attrs):
if name == 'edge':
if not a... | if name == 'route':
for edge in attrs['edges'].split():
if not edge in self._edgeWeights:
self._edgeWeights[edge] = 0
self._edgeWeights[edge] += 1
elif name == 'vehicle':
if float(attrs['depart']) > self._maxDepart:
self... | identifier_body |
costFunctionChecker.py | -05-01 20:31:43Z behrisch $
Run duarouter repeatedly and simulate weight changes via a cost function.
SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
Copyright (C) 2009-2013 DLR (http://www.dlr.de/) and contributors
All rights reserved
"""
import os, sys, subprocess, types
from datetime import da... | def generateWeights(step, options, edges, weights, costFunction):
fd = open("dump_%s_%s.xml" % (step, options.aggregation), "w")
print >> fd, '<?xml version="1.0"?>\n<netstats>'
for time in range(0, int(reader.getMaxDepart()+1), options.aggregation):
print >> fd, ' <interval begin="%s" end="%s" i... | def identity(edge, weight):
return weight
| random_line_split |
lib.rs | ")]
#[macro_use]
extern crate log;
mod job;
mod logfwd;
mod macros;
pub mod whole;
use crate::job::{Job, JobDriver};
use std::cell::{RefCell, RefMut};
use std::error;
use std::fmt::{self, Display, Formatter};
use std::io::{self, BufRead, BufReader, Read, Seek};
use std::mem;
use std::ops::Deref;
use std::ptr;
use st... |
}
impl<'a, B: Read + Seek + 'a, D: Read> Patch<'a, B, BufReader<D>> {
/// Creates a new patch stream.
///
/// This constructor takes a `Read + Seek` stream for the basis file (`base` parameter), and a
/// `Read` stream for the delta file (`delta` parameter). It produces a stream from which read
//... | {
self.driver.read(buf)
} | identifier_body |
lib.rs | ")]
#[macro_use]
extern crate log;
mod job;
mod logfwd;
mod macros;
pub mod whole;
use crate::job::{Job, JobDriver};
use std::cell::{RefCell, RefMut};
use std::error;
use std::fmt::{self, Display, Formatter};
use std::io::{self, BufRead, BufReader, Read, Seek};
use std::mem;
use std::ops::Deref;
use std::ptr;
use st... | (*mut raw::rs_signature_t);
// workaround for E0225
trait ReadAndSeek: Read + Seek {}
impl<T: Read + Seek> ReadAndSeek for T {}
impl<R: Read> Signature<BufReader<R>> {
/// Creates a new signature stream with default parameters.
///
/// This constructor takes an input stream for the file from which compute... | Sumset | identifier_name |
lib.rs | log")]
#[macro_use]
extern crate log;
mod job;
mod logfwd;
mod macros;
pub mod whole;
use crate::job::{Job, JobDriver};
use std::cell::{RefCell, RefMut};
use std::error;
use std::fmt::{self, Display, Formatter};
use std::io::{self, BufRead, BufReader, Read, Seek};
use std::mem;
use std::ops::Deref;
use std::ptr;
use... | pub type Result<T> = std::result::Result<T, Error>;
/// A struct to generate a signature.
///
/// This type takes a `Read` stream for the input from which compute the signatures, and implements
/// another `Read` stream from which get the result.
pub struct Signature<R> {
driver: JobDriver<R>,
}
/// A struct to g... | Unknown(i32),
}
/// A `Result` type alias for this crate's `Error` type. | random_line_split |
webpack.dev.config.js | var webpack = require('webpack');
var path = require('path');
var APP_DIR = path.resolve(__dirname, 'react');
var BUILD_DIR = path.resolve(__dirname, 'project/static/js');
var config = {
entry: {
public: APP_DIR + '/public.main.jsx',
private: APP_DIR + '/private.main.jsx',
},
output: {
path: BUILD_D... | require.resolve('babel-preset-es2015'),
require.resolve('babel-preset-stage-0'),
],
},
},
],
},
};
module.exports = config; | random_line_split | |
game_state.rs | use engine::state::{StateData, State, EngineState};
use engine::state::StateData::*;
use engine::state::EngineState::*;
use engine::resource_loader::{ResourceLoader};
use engine::settings::Settings;
use engine::rendering::{RenderContext, RenderQueue};
use engine::event_queue::{EventQueue};
use game::colors;
use game:... |
}
}
| {
NoChange
} | conditional_block |
game_state.rs | use engine::state::{StateData, State, EngineState};
use engine::state::StateData::*;
use engine::state::EngineState::*;
use engine::resource_loader::{ResourceLoader};
use engine::settings::Settings;
use engine::rendering::{RenderContext, RenderQueue};
use engine::event_queue::{EventQueue};
use game::colors;
use game:... |
}
impl<'a> State for GameState<'a> {
fn startup(&mut self, data: StateData) {
let value = match data {
IntStateData(i) => i,
_ => panic!()
};
}
fn queue_event_handlers(&mut self, event_queue: &mut EventQueue){
event_queue.push(&mut self.event_layer);
}
fn queue_renderers(&mut self, render_queue:... | {
GameState {
active: true,
level: Level::new(),
event_layer: GameEventLayer::new(settings),
}
} | identifier_body |
game_state.rs | use engine::state::{StateData, State, EngineState};
use engine::state::StateData::*;
use engine::state::EngineState::*;
use engine::resource_loader::{ResourceLoader};
use engine::settings::Settings;
use engine::rendering::{RenderContext, RenderQueue};
use engine::event_queue::{EventQueue};
use game::colors;
use game:... | (loader: &ResourceLoader, _render_ctx: &RenderContext, settings: &Settings) -> GameState<'a> {
GameState {
active: true,
level: Level::new(),
event_layer: GameEventLayer::new(settings),
}
}
}
impl<'a> State for GameState<'a> {
fn startup(&mut self, data: StateData) {
let value = match data {
Int... | new | identifier_name |
game_state.rs | use engine::state::{StateData, State, EngineState};
use engine::state::StateData::*;
use engine::state::EngineState::*;
use engine::resource_loader::{ResourceLoader};
use engine::settings::Settings;
use engine::rendering::{RenderContext, RenderQueue};
use engine::event_queue::{EventQueue};
use game::colors;
use game:... |
impl<'a> GameState<'a> {
pub fn new(loader: &ResourceLoader, _render_ctx: &RenderContext, settings: &Settings) -> GameState<'a> {
GameState {
active: true,
level: Level::new(),
event_layer: GameEventLayer::new(settings),
}
}
}
impl<'a> State for GameState<'a> {
fn startup(&mut self, data: StateData)... | active: bool,
level: Level<'a>,
event_layer: GameEventLayer,
} | random_line_split |
filelock.rs | //! Lock files for editing.
use remacs_macros::lisp_fn;
use crate::{
lisp::LispObject,
remacs_sys::Qstringp,
remacs_sys::{lock_file, unlock_file},
threads::ThreadState,
};
/// Lock FILE, if current buffer is modified.
/// FILE defaults to current buffer's visited file,
/// or else nothing is done if ... | () {
let cur_buf = ThreadState::current_buffer_unchecked();
let truename = cur_buf.truename();
if cur_buf.modified_since_save() && truename.is_string() {
unsafe { unlock_file(truename) }
}
}
include!(concat!(env!("OUT_DIR"), "/filelock_exports.rs"));
| unlock_buffer_lisp | identifier_name |
filelock.rs | //! Lock files for editing.
use remacs_macros::lisp_fn;
use crate::{
lisp::LispObject,
remacs_sys::Qstringp,
remacs_sys::{lock_file, unlock_file},
threads::ThreadState,
};
/// Lock FILE, if current buffer is modified.
/// FILE defaults to current buffer's visited file,
/// or else nothing is done if ... |
include!(concat!(env!("OUT_DIR"), "/filelock_exports.rs"));
| {
let cur_buf = ThreadState::current_buffer_unchecked();
let truename = cur_buf.truename();
if cur_buf.modified_since_save() && truename.is_string() {
unsafe { unlock_file(truename) }
}
} | identifier_body |
filelock.rs | //! Lock files for editing.
use remacs_macros::lisp_fn;
use crate::{
lisp::LispObject,
remacs_sys::Qstringp,
remacs_sys::{lock_file, unlock_file},
threads::ThreadState,
};
/// Lock FILE, if current buffer is modified.
/// FILE defaults to current buffer's visited file,
/// or else nothing is done if ... | /// Unlock the file visited in the current buffer.
/// If the buffer is not modified, this does nothing because the file
/// should not be locked in that case.
#[lisp_fn(name = "unlock-buffer")]
pub fn unlock_buffer_lisp() {
let cur_buf = ThreadState::current_buffer_unchecked();
let truename = cur_buf.truename(... | }
| random_line_split |
filelock.rs | //! Lock files for editing.
use remacs_macros::lisp_fn;
use crate::{
lisp::LispObject,
remacs_sys::Qstringp,
remacs_sys::{lock_file, unlock_file},
threads::ThreadState,
};
/// Lock FILE, if current buffer is modified.
/// FILE defaults to current buffer's visited file,
/// or else nothing is done if ... | else if file.is_string() {
file
} else {
wrong_type!(Qstringp, file)
};
if cur_buf.modified_since_save() && !file.is_nil() {
unsafe { lock_file(file) }
}
}
/// Unlock the file visited in the current buffer.
/// If the buffer is not modified, this does nothing because the file
... | {
cur_buf.truename()
} | conditional_block |
useFragmentNode.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow strict-local
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
const useRelay... | isListeningForUpdatesRef.current = true;
const didMissUpdates = FragmentResource.checkMissedUpdates(
fragmentResult,
)[0];
if (didMissUpdates) {
handleDataUpdate();
}
}
function disableStoreUpdates() {
isListeningForUpdatesRef.current = false;
}
function handleDataUpdate() ... | const isListeningForUpdatesRef = useRef(true);
function enableStoreUpdates() { | random_line_split |
useFragmentNode.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow strict-local
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
const useRelay... |
function disableStoreUpdates() {
isListeningForUpdatesRef.current = false;
}
function handleDataUpdate() {
if (
isMountedRef.current === false ||
isListeningForUpdatesRef.current === false
) {
return;
}
// If we receive an update from the Relay store, we need to make sure... | {
isListeningForUpdatesRef.current = true;
const didMissUpdates = FragmentResource.checkMissedUpdates(
fragmentResult,
)[0];
if (didMissUpdates) {
handleDataUpdate();
}
} | identifier_body |
useFragmentNode.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow strict-local
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
const useRelay... | () {
isListeningForUpdatesRef.current = true;
const didMissUpdates = FragmentResource.checkMissedUpdates(
fragmentResult,
)[0];
if (didMissUpdates) {
handleDataUpdate();
}
}
function disableStoreUpdates() {
isListeningForUpdatesRef.current = false;
}
function handleDataUpda... | enableStoreUpdates | identifier_name |
useFragmentNode.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow strict-local
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
const useRelay... |
// If we receive an update from the Relay store, we need to make sure the
// consuming component updates.
shouldUpdateGenerationRef.current++;
// React bails out on noop state updates as an optimization.
// If we want to force an update via setState, we need to pass an value.
// The actual va... | {
return;
} | conditional_block |
base.js | var expect = require("chai").expect;
var sinon = require("sinon");
var chalk = require("chalk");
var ReadlineStub = require("../../helpers/readline");
var Base = require("../../../lib/prompts/base");
describe("`base` prompt (e.g. prompt helpers)", function() {
beforeEach(function() {
this.rl = new ReadlineStu... | expect(this.base.suffix("m ")).to.equal("m ");
expect(this.base.suffix("9")).to.equal("9: ");
expect(this.base.suffix("9~")).to.equal("9~ ");
expect(this.base.suffix()).to.equal(": ");
});
it("should not point by reference to the entry `question` object", function() {
var question = {
mes... | random_line_split | |
7.6.1-4-7.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this n... | (value){
test2 = value;
},
get function(){
return test2;
}
};
var arr = [
'while' ,
'debugger',
'function'
];
for(var p in tokenCodes) {
for(var p1 in arr... | function | identifier_name |
7.6.1-4-7.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this n... |
};
var arr = [
'while' ,
'debugger',
'function'
];
for(var p in tokenCodes) {
for(var p1 in arr) {
if(arr[p1] === p) {
if(!tokenCodes.hasOwnProperty(arr[p1])) {
... | {
return test2;
} | identifier_body |
7.6.1-4-7.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this n... | ;
}
}
}
return true;
}
runTestCase(testcase);
| {
return false;
} | conditional_block |
7.6.1-4-7.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this n... | set debugger(value){
test1 = value;
},
get debugger(){
return test1;
},
set function(value){
test2 = value;
},
get function(){
return test2;
}
};
... | }, | random_line_split |
plugin.js | editor contents.
editor.on( 'beforeModeUnload', function()
{
editor.mode == 'wysiwyg' && undoManager.save( true );
});
// Make the undo manager available only in wysiwyg mode.
editor.on( 'mode', function()
{
undoManager.enabled = editor.readOnly ? false : editor.mode == 'wysiwyg';
... | this.contents = contents;
this.bookmarks = selection && selection.createBookmarks2( true );
editor.fire( 'afterUndoImage' );
};
// Attributes that browser may changing them when setting via innerHTML.
var protectedAttrs = /\b(?:href|src|name)="[^"]*?"/gi;
Image.prototype =
{
equals : function( otherImag... | random_line_split | |
plugin.js | editor contents.
editor.on( 'beforeModeUnload', function()
{
editor.mode == 'wysiwyg' && undoManager.save( true );
});
// Make the undo manager available only in wysiwyg mode.
editor.on( 'mode', function()
{
undoManager.enabled = editor.readOnly ? false : editor.mode == 'wysiwyg';
... | editor )
{
this.editor = editor;
// Reset the undo stack.
this.reset();
}
var editingKeyCodes = { /*Backspace*/ 8:1, /*Delete*/ 46:1 },
modifierKeyCodes = { /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1 },
navigationKeyCodes = { 37:1, 38:1, 39:1, 40:1 }; // Arrows: L, T, R, B
UndoManager.prototype =
{... | doManager( | identifier_name |
plugin.js | editor contents.
editor.on( 'beforeModeUnload', function()
{
editor.mode == 'wysiwyg' && undoManager.save( true );
});
// Make the undo manager available only in wysiwyg mode.
editor.on( 'mode', function()
{
undoManager.enabled = editor.readOnly ? false : editor.mode == 'wysiwyg';
... |
var editingKeyCodes = { /*Backspace*/ 8:1, /*Delete*/ 46:1 },
modifierKeyCodes = { /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1 },
navigationKeyCodes = { 37:1, 38:1, 39:1, 40:1 }; // Arrows: L, T, R, B
UndoManager.prototype =
{
/**
* Process undo system regard keystrikes.
* @param {OMEDITOR.dom.event} ... | this.editor = editor;
// Reset the undo stack.
this.reset();
}
| identifier_body |
core.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# HnTool - A hardening tool for Linux/BSD
# Copyright (C) 2009-2010 Authors
# Authors:
# * Hugo Doria <mail at hugodoria dot org>
# * Aurelio A. Heckert <aurium at gmail dot com>
#
# This program is free software; you can redistribute it and/or modify
# it under ... | from optparse import OptionParser
from optparse import OptionGroup
import gettext
gettext.install('HnTool')
import HnTool.modules.util
import HnTool.modules
import HnTool.output
from HnTool import __version__
class HnToolCore:
def __init__(self):
self.rule_modules = {}
self.output_modules = {}
... | import sys
import string | random_line_split |
core.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# HnTool - A hardening tool for Linux/BSD
# Copyright (C) 2009-2010 Authors
# Authors:
# * Hugo Doria <mail at hugodoria dot org>
# * Aurelio A. Heckert <aurium at gmail dot com>
#
# This program is free software; you can redistribute it and/or modify
# it under ... |
if __name__ == "__main__":
hn = HnToolCore()
hn.run_tests()
| hn = HnToolCore()
hn.run_tests() | identifier_body |
core.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# HnTool - A hardening tool for Linux/BSD
# Copyright (C) 2009-2010 Authors
# Authors:
# * Hugo Doria <mail at hugodoria dot org>
# * Aurelio A. Heckert <aurium at gmail dot com>
#
# This program is free software; you can redistribute it and/or modify
# it under ... |
else:
print >> sys.stderr, _('Invalid module ') + m
sys.exit(2)
# Give the report to the user
self.output_modules[self.options.output_format].output(
self.report,
self.options
)
def main():
hn = HnToolCore()
hn.run_t... | self.report.append({'title': self.rule_modules[m].long_name, \
'results': self.rule_modules[m].analyze(self.options)}) | conditional_block |
core.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# HnTool - A hardening tool for Linux/BSD
# Copyright (C) 2009-2010 Authors
# Authors:
# * Hugo Doria <mail at hugodoria dot org>
# * Aurelio A. Heckert <aurium at gmail dot com>
#
# This program is free software; you can redistribute it and/or modify
# it under ... | (self):
'''Method to load all output modules'''
for module in HnTool.output.__formats__:
self.output_modules[module] = \
__import__('HnTool.output.' + module, globals(), \
locals(), [HnTool]).Format(self.output_options)
# Parsing all the configuration opti... | load_output_modules | identifier_name |
macro-backtrace-nested.rs | // Copyright 2015 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 ... | () {
1 + call_nested_expr!(); //~ ERROR unresolved name
call_nested_expr_sum!(); //~ NOTE expansion site
}
| main | identifier_name |
macro-backtrace-nested.rs | // Copyright 2015 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 ... | {
1 + call_nested_expr!(); //~ ERROR unresolved name
call_nested_expr_sum!(); //~ NOTE expansion site
} | identifier_body | |
macro-backtrace-nested.rs | // Copyright 2015 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 ... | call_nested_expr_sum!(); //~ NOTE expansion site
} | 1 + call_nested_expr!(); //~ ERROR unresolved name | random_line_split |
generate_gr_fir_sysconfig_generic.py | #!/bin/env python
# -*- python -*-
#
# Copyright 2003,2009 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (... |
def make_info (sig, out):
out.write ('''
void
gr_fir_sysconfig_generic::get_gr_fir_%s_info (std::vector<gr_fir_%s_info> *info)
{
info->resize (1);
(*info)[0].name = "generic";
(*info)[0].create = make_gr_fir_%s;
}
''' % (sig, sig, sig))
# ----------------------------------------------------------------
... | out.write ('''
gr_fir_%s *
gr_fir_sysconfig_generic::create_gr_fir_%s (const std::vector<%s> &taps)
{
return make_gr_fir_%s (taps);
}
''' % (sig, sig, tap_type (sig), sig)) | identifier_body |
generate_gr_fir_sysconfig_generic.py | #!/bin/env python
# -*- python -*-
#
# Copyright 2003,2009 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (... |
# ----------------------------------------------------------------
def make_constructor (sig, out):
out.write ('''
static gr_fir_%s *
make_gr_fir_%s (const std::vector<%s> &taps)
{
return new gr_fir_%s_generic (taps);
}
''' % (sig, sig, tap_type (sig), sig))
def make_creator (sig, out):
out.write ('''
gr_... | out.close ()
| random_line_split |
generate_gr_fir_sysconfig_generic.py | #!/bin/env python
# -*- python -*-
#
# Copyright 2003,2009 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (... | generate () | conditional_block | |
generate_gr_fir_sysconfig_generic.py | #!/bin/env python
# -*- python -*-
#
# Copyright 2003,2009 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (... | ():
out = open_and_log_name ('gr_fir_sysconfig_generic.cc', 'w')
if not out:
return
out.write (copyright)
out.write (
'''
/*
* WARNING: This file is automatically generated by
* generate_gr_fir_sysconfig_generic.py.
*
* Any changes made to this file will be overwritten.
*/
#ifdef HAVE_CO... | make_gr_fir_sysconfig_generic_cc | identifier_name |
pinterest.js | import React, { Component } from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { Translation } from "/imports/plugins/core/ui/client/components";
class PinterestSocialButton extends Component {
handleClick = (event) => {
event.preventDefault();
if (window) {
... |
return null;
}
render() {
const iconClassNames = classnames({
"fa": true,
"fa-pinterest": this.props.altIcon !== true,
"fa-pinterest-alt": this.props.altIcon,
[this.props.size]: this.props.size
});
return (
<a className="btn btn-flat pinterest-share" aria-label="Shar... | {
return (
<Translation defaultValue="Share on Pinterest" i18nKey="social.shareOnPinterest" />
);
} | conditional_block |
pinterest.js | import React, { Component } from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { Translation } from "/imports/plugins/core/ui/client/components";
class | extends Component {
handleClick = (event) => {
event.preventDefault();
if (window) {
window.open(this.url, "pinterest_window", "width=750, height=650");
}
}
get url() {
const props = this.props;
const preferredUrl = props.url || location.origin + location.pathname;
const url = enc... | PinterestSocialButton | identifier_name |
pinterest.js | import React, { Component } from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { Translation } from "/imports/plugins/core/ui/client/components";
class PinterestSocialButton extends Component {
handleClick = (event) => {
event.preventDefault();
if (window) {
... | }
render() {
const iconClassNames = classnames({
"fa": true,
"fa-pinterest": this.props.altIcon !== true,
"fa-pinterest-alt": this.props.altIcon,
[this.props.size]: this.props.size
});
return (
<a className="btn btn-flat pinterest-share" aria-label="Share to Pinterest" hr... | }
return null; | random_line_split |
pinterest.js | import React, { Component } from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { Translation } from "/imports/plugins/core/ui/client/components";
class PinterestSocialButton extends Component {
handleClick = (event) => {
event.preventDefault();
if (window) {
... |
render() {
const iconClassNames = classnames({
"fa": true,
"fa-pinterest": this.props.altIcon !== true,
"fa-pinterest-alt": this.props.altIcon,
[this.props.size]: this.props.size
});
return (
<a className="btn btn-flat pinterest-share" aria-label="Share to Pinterest" href=... | {
if (this.props.showText) {
return (
<Translation defaultValue="Share on Pinterest" i18nKey="social.shareOnPinterest" />
);
}
return null;
} | identifier_body |
sftp.py | return stat.S_ISDIR(self.ftp.stat(path).st_mode)
except IOError:
return False
def islink(self, path):
try:
return stat.S_ISLNK(self.ftp.lstat(path).st_mode)
except IOError:
return False
def exists(self, path):
try:
sel... | if local_is_path and os.path.exists(local_path):
msg = "Local file %s already exists and is being overwritten."
warn(msg % local_path)
# When using sudo, "bounce" the file through a guaranteed-unique file
# path in the default remote CWD (which, typically, the login user... | _format_local(local_path, local_is_path),
remote_path
))
# Warn about overwrites, but keep going | random_line_split |
sftp.py |
def isdir(self, path):
try:
return stat.S_ISDIR(self.ftp.stat(path).st_mode)
except IOError:
return False
def islink(self, path):
try:
return stat.S_ISLNK(self.ftp.lstat(path).st_mode)
except IOError:
return False
def exists... | return getattr(self.ftp, attr) | identifier_body | |
sftp.py | return stat.S_ISDIR(self.ftp.stat(path).st_mode)
except IOError:
return False
def islink(self, path):
try:
return stat.S_ISLNK(self.ftp.lstat(path).st_mode)
except IOError:
return False
def exists(self, path):
try:
self.ftp.lstat... |
if os.path.isdir(local_path):
local_path = os.path.join(local_path, path_vars['basename'])
if output.running:
print("[%s] download: %s <- %s" % (
env.host_string,
_format_local(local_path, local_is_path),
remote_path
... | os.makedirs(dirpath) | conditional_block |
sftp.py | return stat.S_ISDIR(self.ftp.stat(path).st_mode)
except IOError:
return False
def islink(self, path):
try:
return stat.S_ISLNK(self.ftp.lstat(path).st_mode)
except IOError:
return False
def | (self, path):
try:
self.ftp.lstat(path).st_mode
except IOError:
return False
return True
def glob(self, path):
from fabric.state import win32
dirpart, pattern = os.path.split(path)
rlist = self.ftp.listdir(dirpart)
names = fnfilter([f... | exists | identifier_name |
xbox_controller.py | from xboxdrv_parser import Controller
from time import sleep
import argparse
import os
import sys
sys.path.append(os.path.abspath("../../.."))
from util.communication.grapevine import Communicator
from robosub_settings import settings
def main (args):
com = Communicator (args.module_name)
controller = Controll... | ():
parser = argparse.ArgumentParser(description='Mock module.')
parser.add_argument('-e', '--epoch', type=float,
default=0.1,
help='Sleep time per cycle.')
parser.add_argument('-m', '--module_name', type=str,
default='movement/fuzzification',
help='Module nam... | commandline | identifier_name |
xbox_controller.py | from xboxdrv_parser import Controller
from time import sleep
import argparse
import os
import sys
sys.path.append(os.path.abspath("../../.."))
from util.communication.grapevine import Communicator
from robosub_settings import settings
def main (args):
com = Communicator (args.module_name)
controller = Controll... | args = commandline()
main(args) | conditional_block | |
xbox_controller.py | from xboxdrv_parser import Controller
from time import sleep
import argparse
import os
import sys
sys.path.append(os.path.abspath("../../.."))
from util.communication.grapevine import Communicator
from robosub_settings import settings
def main (args):
| outgoing_packet["up/down"] = control_packet["up"] + control_packet["down"]
outgoing_packet["yaw"] = control_packet["yaw"]
outgoing_packet["pitch"] = control_packet["pitch"]
#outgoing_packet["roll"] = control_packet["roll"]
outgoing_packet["roll"] = 0.0
... | com = Communicator (args.module_name)
controller = Controller (["X1", "Y1", "X2", "Y2", "R2", "L2"], ["right/left", "forward/backward", "yaw", "pitch", "up", "down"], (0, 255), (-1, 1))
while True:
control_packet = controller.get_values ()
try:
outgoing_packet = {"right/left": 0.0,... | identifier_body |
xbox_controller.py | from xboxdrv_parser import Controller
from time import sleep
import argparse
import os
import sys
sys.path.append(os.path.abspath("../../.."))
from util.communication.grapevine import Communicator
from robosub_settings import settings
def main (args):
com = Communicator (args.module_name)
controller = Controll... | default='movement/fuzzification',
help='Module name.')
return parser.parse_args()
if __name__ == '__main__':
args = commandline()
main(args) | random_line_split | |
overloaded-calls-nontuple.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 ... | (&mut self, z: int) -> int {
self.x + self.y + z
}
}
fn main() {
let mut s = S {
x: 1,
y: 2,
};
drop(s(3)) //~ ERROR cannot use call notation
}
| call_mut | identifier_name |
overloaded-calls-nontuple.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 ... | use std::ops::FnMut;
struct S {
x: int,
y: int,
}
impl FnMut<int,int> for S {
fn call_mut(&mut self, z: int) -> int {
self.x + self.y + z
}
}
fn main() {
let mut s = S {
x: 1,
y: 2,
};
drop(s(3)) //~ ERROR cannot use call notation
} | // except according to those terms.
#![feature(overloaded_calls)]
| random_line_split |
hpastecollectionwidget.py | Widget.__HPasteCollectionWidget, self).__init__(parent, metadataExposedKeys=('raw_url', 'nettype'))
for x in range(1, 5):
self.ui.mainView.horizontalHeader().hideSection(x)
self.__nepane = None
self.__netType = ''
self.__nettypeFilter = QSortFilterProxyM... |
# a callback for authoriser
def _authCallback(self, callbackinfo):
auth, public, action = callbackinfo
if self.__insideAuthCallback: return # prevent looping
self.__insideAuthCallback = True
try:
if action == 0 or (action == 2 and not ... | return QMessageBox.warning(self, 'sure?', 'confirm removing the item from collection. This operation can not be undone.', QMessageBox.Ok | QMessageBox.Cancel) == QMessageBox.Ok | identifier_body |
hpastecollectionwidget.py | Widget.__HPasteCollectionWidget, self).__init__(parent, metadataExposedKeys=('raw_url', 'nettype'))
for x in range(1, 5):
self.ui.mainView.horizontalHeader().hideSection(x)
self.__nepane = None
self.__netType = ''
self.__nettypeFilter = QSortFilterProxyM... |
## test
# todel = []
# for auth in auths:
# if not GithubAuthorizator.testAuthorization(auth):
# if not GithubAuthorizator.newAuthorization(auth):
# todel.append(auth)
# for d in todel:
# ... | auths = list(GithubAuthorizator.listAuthorizations()) | conditional_block |
hpastecollectionwidget.py | pasted nodes in it
self.__savedNetworkViewPos = pane.cursorPosition()
if pane is None:
nettype = '*'
self.__netType = '' # Used to create new snippet types
else:
nettype = hpaste.getChildContext(pane.pwd(), hou.applicationVersion())
... | _killInstance | identifier_name | |
hpastecollectionwidget.py | Widget.__HPasteCollectionWidget, self).__init__(parent, metadataExposedKeys=('raw_url', 'nettype'))
for x in range(1, 5):
self.ui.mainView.horizontalHeader().hideSection(x)
self.__nepane = None
self.__netType = ''
self.__nettypeFilter = QSortFilterProxyM... |
try:
# print(name)
# print(desc)
# print(hpaste.nodesToString(nodes))
self.model().addItemToCollection(collection, name, desc, hpaste.nodesToString(nodes), public, metadata={'nettype': self.__netType})
except CollectionSyncError as... | return
if len(name) > 0:
break; # validity check | random_line_split |
search.js |
(function ($) {
function doSearch() {
var url = '/v0.1/search/?q=' + document.getElementsByName('q')[0].value;
window.location.assign(url);
}
$(document).ready(function() {
$('#searchbox_demo').on('submit', function(e) {
e.preventDefault();
doSearch();
... | () {
function timeoutHandler() {
resizeTimeout = null;
actualResizeHandler();
}
// ignore resize events as long as an actualResizeHandler execution is in the queue
if ( !resizeTimeout ) {
resizeTimeout = setTimeout(timeoutH... | resizeThrottler | identifier_name |
search.js | (function ($) {
function doSearch() {
var url = '/v0.1/search/?q=' + document.getElementsByName('q')[0].value;
window.location.assign(url);
}
$(document).ready(function() { | $('#searchbox_demo').on('submit', function(e) {
e.preventDefault();
doSearch();
});
$('.btn-search').on('click', function(e) {
e.preventDefault();
doSearch();
});
function setSearchBoxSize() {
var width = screen.width ... | random_line_split | |
search.js |
(function ($) {
function doSearch() {
var url = '/v0.1/search/?q=' + document.getElementsByName('q')[0].value;
window.location.assign(url);
}
$(document).ready(function() {
$('#searchbox_demo').on('submit', function(e) {
e.preventDefault();
doSearch();
... |
$(window).on('resize', resizeThrottler);
setSearchBoxSize();
});
}(jQuery));
| {
setSearchBoxSize();
} | identifier_body |
search.js |
(function ($) {
function doSearch() {
var url = '/v0.1/search/?q=' + document.getElementsByName('q')[0].value;
window.location.assign(url);
}
$(document).ready(function() {
$('#searchbox_demo').on('submit', function(e) {
e.preventDefault();
doSearch();
... |
}
function actualResizeHandler() {
setSearchBoxSize();
}
$(window).on('resize', resizeThrottler);
setSearchBoxSize();
});
}(jQuery));
| {
resizeTimeout = setTimeout(timeoutHandler, 66);
} | conditional_block |
amr_corpus_reader.py | #!/usr/bin/env python2
from hgraph import Hgraph
import amr_graph_description_parser
#import tree
import re
import sys
import string
from collections import defaultdict as ddict
def format_tagged(s):
#return [tuple(p.split('/')) for p in s.split()]
|
def format_amr(l):
amr_s = ' '.join(l)
amr_g = Hgraph.from_string(amr_s)
return amr_g
def read_to_empty(f):
lines = []
while True:
l = f.readline().strip()
if not l: return lines
lines.append(l)
def format_constituents(l):
return nltk.tree.ParentedTree("\n".join(l))
def format_alignments(l,... | return [p.rsplit('-',1)[0] for p in s.split()] | identifier_body |
amr_corpus_reader.py | #!/usr/bin/env python2
from hgraph import Hgraph
import amr_graph_description_parser
#import tree
import re
import sys
import string
from collections import defaultdict as ddict
def format_tagged(s):
#return [tuple(p.split('/')) for p in s.split()]
return [p.rsplit('-',1)[0] for p in s.split()]
def format_amr(l)... |
else:
buff.append(l)
class SentenceWithHgraph():
"""
A data structure to hold Hgraph <-> sentence pairs with
PTB parses and token to Hgraph edge elignments.
"""
def __init__(self, sent_id, sent_no, amr, tagged, ptb = None, edge_alignments = None, metadata = None):
... | metadata.append(l)
match = idmatcher.match(l)
if match:
sent_id = match.group(1)
match = sentmatcher.match(l)
if match:
sentence = match.group(1) | conditional_block |
amr_corpus_reader.py | #!/usr/bin/env python2
from hgraph import Hgraph
import amr_graph_description_parser
#import tree
import re
import sys
import string
from collections import defaultdict as ddict
def format_tagged(s):
#return [tuple(p.split('/')) for p in s.split()]
return [p.rsplit('-',1)[0] for p in s.split()]
def format_amr(l)... | (l, amr):
"""
Parse alignment descriptions from file
"""
r = []
for a in l:
m = re.match(r'(\S+)\s+:(\S+)\s+(\S+)\s+(.+)\-(\d+)', a)
if m:
var = m.group(1)
role = m.group(2)
filler = m.group(3).replace('"','')
token = m.group(4)
token_id = int(m.group(5)) - 1 ... | format_alignments | identifier_name |
amr_corpus_reader.py | #!/usr/bin/env python2
from hgraph import Hgraph
import amr_graph_description_parser
#import tree
import re
import sys
import string
from collections import defaultdict as ddict
def format_tagged(s):
#return [tuple(p.split('/')) for p in s.split()]
return [p.rsplit('-',1)[0] for p in s.split()]
def format_amr(l)... | #in_f = open(sys.argv[1],'r')
#corpus = metadata_amr_corpus(in_f) | self.metadata = metadata
| random_line_split |
misc.ts | /**
* Copyright (c) 2018-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
export const halfPI = Math.PI / 2;
export const PiDiv180 = Math.PI / 180;
export function degToRad(deg: number) {
return deg * PiDiv180; // deg * Mat... | (radius: number) {
let x = 0;
let y = 0;
const delta = [0, -1];
const size = radius * 2 + 1;
const halfSize = size / 2;
const out: [number, number][] = [];
for (let i = Math.pow(size, 2); i > 0; --i) {
if ((-halfSize < x && x <= halfSize) && (-halfSize < y && y <= halfSize)) {
... | spiral2d | identifier_name |
misc.ts | /**
* Copyright (c) 2018-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
export const halfPI = Math.PI / 2;
export const PiDiv180 = Math.PI / 180;
export function degToRad(deg: number) {
return deg * PiDiv180; // deg * Mat... |
return out;
} | {
if ((-halfSize < x && x <= halfSize) && (-halfSize < y && y <= halfSize)) {
out.push([x, y]);
}
if (x === y || (x < 0 && x === -y) || (x > 0 && x === 1 - y)) {
[delta[0], delta[1]] = [-delta[1], delta[0]]; // change direction
}
x += delta[0];
y... | conditional_block |
misc.ts | /**
* Copyright (c) 2018-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
export const halfPI = Math.PI / 2;
export const PiDiv180 = Math.PI / 180;
export function degToRad(deg: number) |
export function radToDeg(rad: number) {
return rad / PiDiv180; // rad * 180 / Math.PI
}
export function isPowerOfTwo(x: number) {
return (x !== 0) && (x & (x - 1)) === 0;
}
/** return the value that has the largest absolute value */
export function absMax(...values: number[]) {
let max = 0;
let absM... | {
return deg * PiDiv180; // deg * Math.PI / 180
} | identifier_body |
misc.ts | /**
* Copyright (c) 2018-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
export const halfPI = Math.PI / 2;
export const PiDiv180 = Math.PI / 180;
export function degToRad(deg: number) {
return deg * PiDiv180; // deg * Mat... | }
if (x === y || (x < 0 && x === -y) || (x > 0 && x === 1 - y)) {
[delta[0], delta[1]] = [-delta[1], delta[0]]; // change direction
}
x += delta[0];
y += delta[1];
}
return out;
} | random_line_split | |
search-reducer.spec.ts | import { is } from 'immutable';
import { SearchActions } from '../search-actions';
import { searchReducer } from './search-reducer';
import { SearchStateRecord } from './search-state';
describe('search', () => {
describe('searchReducer', () => {
let actions: SearchActions;
let query: string;
beforeEach... | query = 'test';
});
describe('default case', () => {
it('should return initial state', () => {
let search = searchReducer(undefined, {type: 'UNDEFINED'});
expect(is(search, SearchStateRecord())).toBe(true);
});
});
describe('LOAD_SEARCH_RESULTS action', () => {
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.