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 |
|---|---|---|---|---|
tree.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use at... | } | } | random_line_split |
tree.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use at... | (&self) -> bool {
false
}
/// Return true if we want to stop lookup ancestor of the current
/// element while matching complex selectors with descendant/child
/// combinator.
fn blocks_ancestor_combinators(&self) -> bool {
false
}
}
| ignores_nth_child_selectors | identifier_name |
pygoogle.py | #!/usr/bin/python
"""
Google AJAX Search Module
http://code.google.com/apis/ajaxsearch/documentation/reference.html
Needs Python 2.6 or later
"""
try:
import json
except ImportError as e:
import simplejson as json
except ImportError as e:
print(e)
exit()
import sys
import urllib.request, urllib.parse, ... |
def __setup_logging(self, level):
logger = logging.getLogger('pygoogle')
logger.setLevel(level)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('%(module)s %(levelname)s %(funcName)s| %(message)s'))
logger.addHandler(handler)
... | self.pages = pages #Number of pages. default 10
self.query = query
self.filter = FILTER_ON #Controls turning on or off the duplicate content filter. On = 1.
self.rsz = RSZ_LARGE #Results per page. small = 4 /large = 8
self.safe = SAFE_OFF #SafeBrowsing - activ... | identifier_body |
pygoogle.py | #!/usr/bin/python
"""
Google AJAX Search Module
http://code.google.com/apis/ajaxsearch/documentation/reference.html
Needs Python 2.6 or later
"""
try:
import json
except ImportError as e:
import simplejson as json
except ImportError as e:
print(e)
exit()
import sys
import urllib.request, urllib.parse, ... | main() | conditional_block | |
pygoogle.py | #!/usr/bin/python
"""
Google AJAX Search Module
http://code.google.com/apis/ajaxsearch/documentation/reference.html
Needs Python 2.6 or later
"""
try:
import json
except ImportError as e:
import simplejson as json
except ImportError as e:
print(e)
exit()
import sys
import urllib.request, urllib.parse, ... | * safe=moderate - enables moderate safe search filtering (default)
* safe=off - disables safe search filtering
"""
SAFE_ACTIVE = "active"
SAFE_MODERATE = "moderate"
SAFE_OFF = "off"
"""
FILTER
This optional argument controls turning on or off the duplicate content filter:
* filter=0 - Turns o... | * safe=active - enables the highest level of safe search filtering | random_line_split |
pygoogle.py | #!/usr/bin/python
"""
Google AJAX Search Module
http://code.google.com/apis/ajaxsearch/documentation/reference.html
Needs Python 2.6 or later
"""
try:
import json
except ImportError as e:
import simplejson as json
except ImportError as e:
print(e)
exit()
import sys
import urllib.request, urllib.parse, ... | (self):
"""Returns the number of results"""
temp = self.pages
self.pages = 1
result_count = 0
search_results = self.__search__()
if not search_results:
return 0
try:
result_count = search_results[0]
if not isinstance(result_coun... | get_result_count | identifier_name |
types.component.ts | Document, Relations, SyncService, SyncStatus, Resource } from 'idai-field-core';
import { curry, filter, flatten, flow, is, Map, map, remove, set, take } from 'tsfun';
import { makeLookup } from '../../../../../../core/src/tools/transformers';
import { ProjectCategories } from '../../../core/configuration/project-categ... | (event: KeyboardEvent) {
if (event.key === 'Escape' && this.menuService.getContext() === MenuContext.DEFAULT) {
await this.tabManager.openActiveTab();
}
}
public async open(document: FieldDocument) {
await this.viewFacade.moveInto(document, false, true);
}
publi... | onKeyDown | identifier_name |
types.component.ts | Document, Relations, SyncService, SyncStatus, Resource } from 'idai-field-core';
import { curry, filter, flatten, flow, is, Map, map, remove, set, take } from 'tsfun';
import { makeLookup } from '../../../../../../core/src/tools/transformers';
import { ProjectCategories } from '../../../core/configuration/project-categ... | if (editedDocument) {
await this.updateLinkedDocuments();
this.loadImages([editedDocument], true);
}
}
public async jumpToResource(document: FieldDocument) {
await this.routingService.jumpToResource(document);
}
public async performContextMenuAction(a... |
public async edit(document: FieldDocument) {
const editedDocument: FieldDocument|undefined = await this.resourcesComponent.editDocument(document); | random_line_split |
types.component.ts | Document, Relations, SyncService, SyncStatus, Resource } from 'idai-field-core';
import { curry, filter, flatten, flow, is, Map, map, remove, set, take } from 'tsfun';
import { makeLookup } from '../../../../../../core/src/tools/transformers';
import { ProjectCategories } from '../../../core/configuration/project-categ... |
}
public async jumpToResource(document: FieldDocument) {
await this.routingService.jumpToResource(document);
}
public async performContextMenuAction(action: ContextMenuAction) {
if (this.contextMenu.documents.length !== 1) return;
const document: FieldDocument = this.conte... | {
await this.updateLinkedDocuments();
this.loadImages([editedDocument], true);
} | conditional_block |
types.component.ts | Document, Relations, SyncService, SyncStatus, Resource } from 'idai-field-core';
import { curry, filter, flatten, flow, is, Map, map, remove, set, take } from 'tsfun';
import { makeLookup } from '../../../../../../core/src/tools/transformers';
import { ProjectCategories } from '../../../core/configuration/project-categ... |
public handleClick(event: any, rightClick: boolean = false) {
if (!this.contextMenu.position) return;
let target = event.target;
let inside: boolean = false;
do {
if (target.id === 'context-menu'
|| (rightClick && target.id && target.id.startsWith('t... | {
if (!Document.hasRelations(document, Relations.Type.INSTANCEOF)) return undefined;
for (const typeId of document.resource.relations.isInstanceOf) {
const type = this.subtypes[typeId];
if (type) return type;
}
return undefined;
} | identifier_body |
db_migrate.py | #!hyphen-venv/bin/python | from config import SQLALCHEMY_MIGRATE_REPO
migration = SQLALCHEMY_MIGRATE_REPO + \
'/versions/%03d_migration.py' % \
(api.db_version(
SQLALCHEMY_DATABASE_URI,
SQLALCHEMY_MIGRATE_REPO) + 1)
tmp_module = imp.new_module('old_model')... | import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI | random_line_split |
demo-zwave-react.py | # Copyright (c) 2015-2016 Contributors as noted in the AUTHORS file
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import signal
import sys
from functools import par... |
elif value == 0x17: # Close
self.action_value.value = False
def sigterm_handler(self):
self.node.shutdown()
sys.exit(0)
if __name__ == '__main__':
demo = DemoNode()
try:
print 'serving'
demo.node.serve_forever()
except KeyboardInterrupt:
d... | self.action_value.value = True | conditional_block |
demo-zwave-react.py | # Copyright (c) 2015-2016 Contributors as noted in the AUTHORS file
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import signal
import sys
from functools import par... |
def value_update(self, iv, value, timestamp, tags):
print 'Received update: ', value
if value == 0x16: # Open
self.action_value.value = True
elif value == 0x17: # Close
self.action_value.value = False
def sigterm_handler(self):
self.node.shutdown()
... | self.node = IsacNode('demo-zwave-react')
green.signal(signal.SIGTERM, partial(self.sigterm_handler))
self.action_value = IsacValue(self.node, 'zwave://0xdefbc93b.power_strip001/switch_binary/1/switch', survey_last_value=False, survey_static_tags=False)
self.sensor_value = IsacValue(self.node, ... | identifier_body |
demo-zwave-react.py | # Copyright (c) 2015-2016 Contributors as noted in the AUTHORS file
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import signal
import sys
from functools import par... | (self):
self.node = IsacNode('demo-zwave-react')
green.signal(signal.SIGTERM, partial(self.sigterm_handler))
self.action_value = IsacValue(self.node, 'zwave://0xdefbc93b.power_strip001/switch_binary/1/switch', survey_last_value=False, survey_static_tags=False)
self.sensor_value = IsacV... | __init__ | identifier_name |
node-with-graph.js | 'use strict';
/**
* NodeWithGraph
* =============
*/
const path = require('path');
const inherit = require('inherit');
const Node = require('./node');
| __constructor(nodePath, makePlatform, cache, graph) {
this.__base(nodePath, makePlatform, cache);
/**
* Построитель графа сборки.
* @type {BuildGraph}
* @name NodeWithGraph.prototype._graph
* @private
*/
this._graph = graph;
},
_initTech... | module.exports = inherit(Node, { | random_line_split |
node-with-graph.js | 'use strict';
/**
* NodeWithGraph
* =============
*/
const path = require('path');
const inherit = require('inherit');
const Node = require('./node');
module.exports = inherit(Node, {
__constructor(nodePath, makePlatform, cache, graph) {
this.__base(nodePath, makePlatform, cache);
/**
... | _this = this;
const NodeAdapter = function () {};
NodeAdapter.prototype = _this;
const nodeAdapter = new NodeAdapter();
tech.init(nodeAdapter);
const targets = tech.getTargets();
targets.forEach(target => {
const targetPath = path.join(_this._path, target);... | const | identifier_name |
node-with-graph.js | 'use strict';
/**
* NodeWithGraph
* =============
*/
const path = require('path');
const inherit = require('inherit');
const Node = require('./node');
module.exports = inherit(Node, {
__constructor(nodePath, makePlatform, cache, graph) {
this.__base(nodePath, makePlatform, cache);
/**
... | (targets, sources, getDepFromPath) {
const _this = this;
targets = targets || [];
targets.forEach(target => {
const targetPath = path.join(_this._path, target);
sources.forEach(source => {
_this._graph.addDep(
targetPath,
... | sources).forEach(nodeName => {
const nodeSources = sources[nodeName];
this._addDepsToGraph(targets, nodeSources, (source) => {
return path.join(nodeName, this.unmaskNodeTargetName(nodeName, source));
});
});
return Node.prototype.requireNodeSources.a... | identifier_body |
update_machine.py | '^([^/]+)/(?:([^/]+)/)?([^/]+):([^/]+)/(?:([^/]+)/)?([^/]+)$')
def parse_remap_disk(old_vmholder, new_vmholder, remap_disk):
result = {}
if not remap_disk:
return result
maps = remap_disk.split(",")
for map in maps:
res = _disk_map_re.match(map)
if not res:
raise ... |
def update_disk_backing_stores(dbmachine, old_holder, new_holder, remap_disk):
if not old_holder:
old_holder = dbmachine.vm_container.holder.holder_object
if not new_holder:
new_holder = old_holder
disk_mapping = parse_remap_disk(old_holder, new_holder, remap_disk)
for dbdisk in dbm... | if hasattr(holder, "metacluster"):
return holder.metacluster
# vmhost
if hasattr(holder, "cluster") and holder.cluster:
return holder.cluster.metacluster
else:
# TODO vlocal still has clusters, so this case not tested yet.
return None | identifier_body |
update_machine.py | vmhost
if hasattr(holder, "cluster") and holder.cluster:
return holder.cluster.metacluster
else:
# TODO vlocal still has clusters, so this case not tested yet.
return None
def update_disk_backing_stores(dbmachine, old_holder, new_holder, remap_disk):
if not old_holder:
old... | if dbmachine.host:
for srv in dbmachine.host.services_provided:
si = srv.service_instance | random_line_split | |
update_machine.py | ([^/]+)/(?:([^/]+)/)?([^/]+):([^/]+)/(?:([^/]+)/)?([^/]+)$')
def parse_remap_disk(old_vmholder, new_vmholder, remap_disk):
result = {}
if not remap_disk:
return result
maps = remap_disk.split(",")
for map in maps:
res = _disk_map_re.match(map)
if not res:
raise Ar... | (session, logger, dbmachine, resholder, remap_disk,
allow_metacluster_change, autoip, plenaries):
old_holder = dbmachine.vm_container.holder.holder_object
if resholder:
new_holder = resholder.holder_object
else:
new_holder = old_holder
if new_holder != old_holder:
ol... | move_vm | identifier_name |
update_machine.py | _object
if resholder:
new_holder = resholder.holder_object
else:
new_holder = old_holder
if new_holder != old_holder:
old_mc = get_metacluster(old_holder)
new_mc = get_metacluster(new_holder)
if old_mc != new_mc and not allow_metacluster_change:
raise Arg... | raise ArgumentError("{0} slot {1} already has machine "
"{2}.".format(dbchassis, slot,
dbslot.machine.label)) | conditional_block | |
mod.rs | //! A Collection of Header implementations for common HTTP Headers.
//!
//! ## Mime
//!
//! Several header fields use MIME values for their contents. Keeping with the
//! strongly-typed theme, the [mime](http://seanmonstar.github.io/mime.rs) crate
//! is used, such as `ContentType(pub Mime)`.
pub use self::access_cont... | fn parse_header(raw: &[Vec<u8>]) -> Option<$from> {
$crate::header::parsing::from_one_raw_str(raw).map($from)
}
}
impl header::HeaderFormat for $from {
fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::std::... | fn header_name() -> &'static str {
$name
}
| random_line_split |
mul.rs | use std::ops::Mul;
use traits::{Flops, Matrix, UnsafeGet};
impl<A, B> Flops for ::Mul<A, B> where
A: Flops + UnsafeGet,
B: Flops + UnsafeGet,
A::Output: Mul<B::Output>,
{
#[inline(always)]
fn flops() -> usize {
A::flops() + B::flops() + 1
}
}
impl<A, B, C> Matrix for ::Mul<A, B> where... | } |
#[inline(always)]
unsafe fn unsafe_get(&self, i: (u32, u32)) -> C {
self.0.unsafe_get(i) * self.1.unsafe_get(i)
} | random_line_split |
mul.rs | use std::ops::Mul;
use traits::{Flops, Matrix, UnsafeGet};
impl<A, B> Flops for ::Mul<A, B> where
A: Flops + UnsafeGet,
B: Flops + UnsafeGet,
A::Output: Mul<B::Output>,
{
#[inline(always)]
fn flops() -> usize {
A::flops() + B::flops() + 1
}
}
impl<A, B, C> Matrix for ::Mul<A, B> where... | (&self) -> (u32, u32) {
B::size(&self.1)
}
}
impl<A, B, C> UnsafeGet for ::Mul<A, B> where
A: UnsafeGet,
B: UnsafeGet,
A::Output: Mul<B::Output, Output=C>,
{
type Output = C;
#[inline(always)]
unsafe fn unsafe_get(&self, i: (u32, u32)) -> C {
self.0.unsafe_get(i) * self.1.u... | size | identifier_name |
mul.rs | use std::ops::Mul;
use traits::{Flops, Matrix, UnsafeGet};
impl<A, B> Flops for ::Mul<A, B> where
A: Flops + UnsafeGet,
B: Flops + UnsafeGet,
A::Output: Mul<B::Output>,
{
#[inline(always)]
fn flops() -> usize |
}
impl<A, B, C> Matrix for ::Mul<A, B> where
A: UnsafeGet,
B: Matrix + UnsafeGet,
A::Output: Mul<B::Output, Output=C>,
{
#[inline(always)]
fn nrows(&self) -> u32 {
B::nrows(&self.1)
}
#[inline(always)]
fn ncols(&self) -> u32 {
B::ncols(&self.1)
}
#[inline(alwa... | {
A::flops() + B::flops() + 1
} | identifier_body |
platform.rs | /*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | -> u64 {
/*
This is kinda dicey, since *ideally* both this function and `file_last_modified` would be using the same underlying APIs. They are not, insofar as I know.
At least, not when targetting Windows.
That said, so long as everything is in the same units and uses the same epoch,... | rrent_time() | identifier_name |
platform.rs | /*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | }
fn SHGetKnownFolderPath(rfid: &winapi::KNOWNFOLDERID, dwFlags: winapi::DWORD, hToken: winapi::HANDLE) -> WinResult<OsString> {
use self::winapi::PWSTR;
let mut psz_path: PWSTR = unsafe { mem::uninitialized() };
let hresult = unsafe {
shell32::SHGetKnownFolderPath(
... | write!(fmt, "HRESULT({})", self.0)
}
| identifier_body |
platform.rs | /*
Copyright ⓒ 2015 cargo-script contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modifie... | + (now_1970_utc.nsec as u64 / 1_000_000);
now_ms_1970_utc
}
}
#[cfg(unix)]
mod inner {
pub use super::inner_unix_or_windows::current_time;
use std::path::{Path, PathBuf};
use std::{cmp, env, fs};
use std::os::unix::fs::MetadataExt;
use error::{MainError, Blame};
/**
... | return 0
}
let now_ms_1970_utc = (now_1970_utc.sec as u64 * 1000) | random_line_split |
assignmentToObjectAndFunction.js | //// [assignmentToObjectAndFunction.ts]
var errObj: Object = { toString: 0 }; // Error, incompatible toString
var goodObj: Object = {
toString(x?) {
return "";
}
}; // Ok, because toString is a subtype of Object's toString
var errFun: Function = {}; // Error for no call signature
function foo() { }
m... | () { }
(function (bar) {
function apply(thisArg, argArray) { }
bar.apply = apply;
})(bar || (bar = {}));
var goodFundule2 = bar; // ok
function bad() { }
(function (bad) {
bad.apply = 0;
})(bad || (bad = {}));
var badFundule = bad; // error
| bar | identifier_name |
assignmentToObjectAndFunction.js | //// [assignmentToObjectAndFunction.ts]
var errObj: Object = { toString: 0 }; // Error, incompatible toString
var goodObj: Object = {
toString(x?) {
return "";
}
}; // Ok, because toString is a subtype of Object's toString
var errFun: Function = {}; // Error for no call signature | function foo() { }
module foo {
export var boom = 0;
}
var goodFundule: Function = foo; // ok
function bar() { }
module bar {
export function apply(thisArg: string, argArray?: string) { }
}
var goodFundule2: Function = bar; // ok
function bad() { }
module bad {
export var apply = 0;
}
var badFundule: F... | random_line_split | |
assignmentToObjectAndFunction.js | //// [assignmentToObjectAndFunction.ts]
var errObj: Object = { toString: 0 }; // Error, incompatible toString
var goodObj: Object = {
toString(x?) {
return "";
}
}; // Ok, because toString is a subtype of Object's toString
var errFun: Function = {}; // Error for no call signature
function foo() { }
m... |
(function (foo) {
foo.boom = 0;
})(foo || (foo = {}));
var goodFundule = foo; // ok
function bar() { }
(function (bar) {
function apply(thisArg, argArray) { }
bar.apply = apply;
})(bar || (bar = {}));
var goodFundule2 = bar; // ok
function bad() { }
(function (bad) {
bad.apply = 0;
})(bad... | { } | identifier_body |
en.js | import I18n from "i18n-js"
I18n.translations || (I18n.translations = {});
I18n.translations["en"] = {
"days_in_office": "Days in office: %{nb_days}",
"mandate_terminated": "Mandate ended",
"entity_full_title": "%{name} lead by %{leader}", | "other": "Promises",
"status": {
"broken": "Broken",
"done": "Done",
"in_progress": "In progress",
"not_yet_started": "Not yet started"
}
},
"sources": "Sources",
"no_source": "No source have been given",
"others": "Others",
"presentation": "Presentation",
"see_all": "See... | "promise": {
"one": "Promise", | random_line_split |
explorer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
export const IExplorerViewsService = createDecorator<IExplorerViewsService>('explorerViewsService');
export interface IExplorerViewsService {
_serviceBrand: any;
readonly onViewCreated: Event<IExplorerView<any>... | import Event from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { TPromise } from 'vs/base/common/winjs.base';
import { IActionRunner } from 'vs/base/common/actions'; | random_line_split |
tag-align-u64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | fn is_8_byte_aligned(u: &Tag) -> bool {
let p: uint = unsafe { cast::transmute(u) };
return (p & 7u) == 0u;
}
pub fn main() {
let x = mk_rec();
assert!(is_8_byte_aligned(&x.t));
} | fn mk_rec() -> Rec {
return Rec { c8:0u8, t:Tag(0u64) };
}
| random_line_split |
tag-align-u64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
fn is_8_byte_aligned(u: &Tag) -> bool {
let p: uint = unsafe { cast::transmute(u) };
return (p & 7u) == 0u;
}
pub fn main() {
let x = mk_rec();
assert!(is_8_byte_aligned(&x.t));
}
| {
return Rec { c8:0u8, t:Tag(0u64) };
} | identifier_body |
tag-align-u64.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
c8: u8,
t: Tag
}
fn mk_rec() -> Rec {
return Rec { c8:0u8, t:Tag(0u64) };
}
fn is_8_byte_aligned(u: &Tag) -> bool {
let p: uint = unsafe { cast::transmute(u) };
return (p & 7u) == 0u;
}
pub fn main() {
let x = mk_rec();
assert!(is_8_byte_aligned(&x.t));
}
| Rec | identifier_name |
leaf_set.rs | // Copyright 2021 The Grin Developers
// 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 agreed t... | (
&self,
cutoff_pos: u64,
rewind_rm_pos: &Bitmap,
prune_list: &PruneList,
) -> Bitmap {
let mut bitmap = self.bitmap.clone();
// First remove pos from leaf_set that were
// added after the point we are rewinding to.
let to_remove = ((cutoff_pos + 1) as u32)..bitmap.maximum().unwrap_or(0);
bitmap.rem... | removed_pre_cutoff | identifier_name |
leaf_set.rs | // Copyright 2021 The Grin Developers
// 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 agreed t... | if !bitmap.is_empty() {
debug!(
"bitmap {} pos ({} bytes)",
bitmap.cardinality(),
bitmap.get_serialized_size_in_bytes(),
);
}
Ok(LeafSet {
path: file_path.to_path_buf(),
bitmap_bak: bitmap.clone(),
bitmap,
})
}
/// Copies a snapshot of the utxo file into the primary utxo file.
pu... | } else {
Bitmap::create()
};
| random_line_split |
leaf_set.rs | // Copyright 2021 The Grin Developers
// 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 agreed t... |
/// Remove the provided position from the leaf_set.
pub fn remove(&mut self, pos0: u64) {
self.bitmap.remove(1 + pos0 as u32);
}
/// Saves the utxo file tagged with block hash as filename suffix.
/// Needed during fast-sync as the receiving node cannot rewind
/// after receiving the txhashset zip file.
pub ... | {
self.bitmap.add(1 + pos0 as u32);
} | identifier_body |
leaf_set.rs | // Copyright 2021 The Grin Developers
// 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 agreed t... |
let bitmap = read_bitmap(&cp_file_path)?;
debug!(
"leaf_set: copying rewound file {} to {}",
cp_file_path.display(),
path.as_ref().display()
);
let mut leaf_set = LeafSet {
path: path.as_ref().to_path_buf(),
bitmap_bak: bitmap.clone(),
bitmap,
};
leaf_set.flush()?;
Ok(())
}
/// Ca... | {
debug!(
"leaf_set: rewound leaf file not found: {}",
cp_file_path.display()
);
return Ok(());
} | conditional_block |
EditorModalFooter.js | /**
* Copyright (C) 2016-2019 Mailvelope GmbH
* Licensed under the GNU Affero General Public License version 3
*/
import React from 'react';
import PropTypes from 'prop-types';
import * as l10n from '../../../lib/l10n';
import {Collapse} from 'reactstrap';
import './EditorModalFooter.scss';
l10n.register([
'edi... | () {
return (
<div className="d-flex flex-column w-100">
<Collapse id="sign-msg-option" isOpen={!this.state.collapse}>
<form className="mb-3">
<div className="row mb-2">
<label htmlFor="signingKey" className="col-sm-4 col-form-label">{l10n.map.sign_dialog_header}</l... | render | identifier_name |
EditorModalFooter.js | /**
* Copyright (C) 2016-2019 Mailvelope GmbH
* Licensed under the GNU Affero General Public License version 3
*/
import React from 'react';
import PropTypes from 'prop-types';
import * as l10n from '../../../lib/l10n';
import {Collapse} from 'reactstrap';
import './EditorModalFooter.scss';
l10n.register([
'edi... | integration: PropTypes.bool // integration active indicator
}; | onChangeSignKey: PropTypes.func, // user selects new key
onClickSignSetting: PropTypes.func, // click on navigation link | random_line_split |
readblock.py | #!/usr/bin/env python3
import subprocess as sp
def | (args):
with open(args.disk, 'rb') as f:
f.seek(args.block * args.block_size)
block = (f.read(args.block_size)
.ljust(args.block_size, b'\xff'))
# what did you expect?
print("%-8s %-s" % ('off', 'data'))
return sp.run(['xxd', '-g1', '-'], input=block).returncode
if __name_... | main | identifier_name |
readblock.py | #!/usr/bin/env python3
import subprocess as sp
def main(args):
with open(args.disk, 'rb') as f:
f.seek(args.block * args.block_size)
block = (f.read(args.block_size)
.ljust(args.block_size, b'\xff'))
# what did you expect?
print("%-8s %-s" % ('off', 'data'))
return sp.run... | import argparse
import sys
parser = argparse.ArgumentParser(
description="Hex dump a specific block in a disk.")
parser.add_argument('disk',
help="File representing the block device.")
parser.add_argument('block_size', type=lambda x: int(x, 0),
help="Size of a block in bytes.")
... | conditional_block | |
readblock.py | #!/usr/bin/env python3
import subprocess as sp
def main(args):
|
if __name__ == "__main__":
import argparse
import sys
parser = argparse.ArgumentParser(
description="Hex dump a specific block in a disk.")
parser.add_argument('disk',
help="File representing the block device.")
parser.add_argument('block_size', type=lambda x: int(x, 0),
he... | with open(args.disk, 'rb') as f:
f.seek(args.block * args.block_size)
block = (f.read(args.block_size)
.ljust(args.block_size, b'\xff'))
# what did you expect?
print("%-8s %-s" % ('off', 'data'))
return sp.run(['xxd', '-g1', '-'], input=block).returncode | identifier_body |
readblock.py | #!/usr/bin/env python3
import subprocess as sp
def main(args): |
# what did you expect?
print("%-8s %-s" % ('off', 'data'))
return sp.run(['xxd', '-g1', '-'], input=block).returncode
if __name__ == "__main__":
import argparse
import sys
parser = argparse.ArgumentParser(
description="Hex dump a specific block in a disk.")
parser.add_argument('di... | with open(args.disk, 'rb') as f:
f.seek(args.block * args.block_size)
block = (f.read(args.block_size)
.ljust(args.block_size, b'\xff')) | random_line_split |
index.js | "use strict";
const Base = require('yeoman-generator');
const generatorArguments = require('./arguments');
const generatorOptions = require('./options');
const generatorSteps = require('./steps');
module.exports = class ResponseGenerator extends Base {
constructor(args, options) {
super(args, options);
Obj... | () {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorS... | default | identifier_name |
index.js | "use strict";
const Base = require('yeoman-generator');
const generatorArguments = require('./arguments');
const generatorOptions = require('./options');
const generatorSteps = require('./steps');
module.exports = class ResponseGenerator extends Base {
constructor(args, options) {
super(args, options);
Obj... |
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorSteps.writing;
}
};
| {
return generatorSteps.end;
} | identifier_body |
index.js | "use strict";
const Base = require('yeoman-generator');
const generatorArguments = require('./arguments');
const generatorOptions = require('./options');
const generatorSteps = require('./steps');
module.exports = class ResponseGenerator extends Base {
constructor(args, options) {
super(args, options);
Obj... |
get default() {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
ret... | } | random_line_split |
0008_fix_name_indices.py | # Generated by Django 2.1.7 on 2019-05-12 16:08
from django.db import migrations, models
class | (migrations.Migration):
atomic = False
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',
name='title',
field=models.CharField(max_length=256),
),
migration... | Migration | identifier_name |
0008_fix_name_indices.py | # Generated by Django 2.1.7 on 2019-05-12 16:08
from django.db import migrations, models
class Migration(migrations.Migration):
| """,
reverse_sql="""
DROP INDEX CONCURRENTLY papers_journal_title_upper;
""",
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_publisher_name_upper ON public.papers_publisher USING btree (UPPER(name));
""",... | atomic = False
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',
name='title',
field=models.CharField(max_length=256),
),
migrations.AlterField(
mo... | identifier_body |
0008_fix_name_indices.py | # Generated by Django 2.1.7 on 2019-05-12 16:08
from django.db import migrations, models
class Migration(migrations.Migration):
atomic = False
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',... | reverse_sql="""
DROP INDEX CONCURRENTLY papers_journal_title_upper;
""",
),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_publisher_name_upper ON public.papers_publisher USING btree (UPPER(name));
""",
reve... | ),
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY papers_journal_title_upper ON public.papers_journal USING btree (UPPER(title));
""", | random_line_split |
it.js | // IT lang variables
tinyMCE.addToLang('',{
bold_desc : 'Grassetto (Ctrl+B)',
italic_desc : 'Corsivo (Ctrl+I)',
underline_desc : 'Sottolineato (Ctrl+U)',
striketrough_desc : 'Barrato',
justifyleft_desc : 'Allinea a sinistra',
justifycenter_desc : 'Allinea al centro',
justifyright_desc : 'Allinea a destra',
j... | popup_blocked : 'Un blocco popup sta impedendo l\'utilizzo di alcune funzionalità. Dovresti disabilitare il blocco per questo sito.',
insert_image_delta_width : 50,
insert_link_delta_width : 75
}); | italic_img : "italic.gif",
underline_img : "underline.gif",
clipboard_msg : 'Le operazioni di taglia, copia e incolla non sono disponibili in Firefox. Vuoi ricevere ulteriori informazioni al riguardo?',
| random_line_split |
surfaceGenerator.py | """
@summary: This script will generate a surface using cones and ellipsoids
@author: CJ Grady
"""
from math import sqrt
import numpy as np
from random import randint
# .............................................................................
class SurfaceGenerator(object):
"""
@summary: This class is used t... |
# ..................................
def addRandom(self, numCones=0, numEllipsoids=0, maxHeight=100, maxRad=100):
# TODO: Add mesas?
maxX, maxY = self.grid.shape
# Add cones
for i in range(numCones):
h = randint(1, maxHeight)
self.addCone(randint(0, maxX)... | try:
self.grid[y,x] = self.grid[y,x] + getZ(x, y)
except:
print "An exception occurred when setting the value of a cell" | conditional_block |
surfaceGenerator.py | """
@summary: This script will generate a surface using cones and ellipsoids
@author: CJ Grady
"""
from math import sqrt
import numpy as np
from random import randint
# .............................................................................
class SurfaceGenerator(object):
"""
@summary: This class is used t... | (self, fn):
np.savetxt(fn, self.grid, fmt="%i", header=self.headers, comments='')
# .............................................................................
if __name__ == "__main__":
#s = SurfaceGenerator(20, 20, 10, 10, 10, defVal=0)
#s = SurfaceGenerator(1000, 1000, 0, 0, 0.05, defVal=0)
s... | writeGrid | identifier_name |
surfaceGenerator.py | """
@summary: This script will generate a surface using cones and ellipsoids
@author: CJ Grady
"""
from math import sqrt
import numpy as np
from random import randint
# .............................................................................
class SurfaceGenerator(object):
"""
@summary: This class is used t... | t2 = height**2 * t
val = sqrt(t2)
if maxHeight is not None:
val = max(val, maxHeight)
return val
for x in range(max(0, (xCnt - xRad)), min(self.grid.shape[1], (xCnt + xRad))):
for y in range(max(0, (yCnt - yRad)), min(self.grid.sh... | yPart = (1.0*y - yCnt)**2 / yRad**2
t = 1 - xPart - yPart
| random_line_split |
surfaceGenerator.py | """
@summary: This script will generate a surface using cones and ellipsoids
@author: CJ Grady
"""
from math import sqrt
import numpy as np
from random import randint
# .............................................................................
class SurfaceGenerator(object):
"""
@summary: This class is used t... |
# .............................................................................
if __name__ == "__main__":
#s = SurfaceGenerator(20, 20, 10, 10, 10, defVal=0)
#s = SurfaceGenerator(1000, 1000, 0, 0, 0.05, defVal=0)
s = SurfaceGenerator(20, 20, 0, 0, 1.0, defVal=0)
#s.addEllipsoid(5, 5, 4, 3, 10)
... | np.savetxt(fn, self.grid, fmt="%i", header=self.headers, comments='') | identifier_body |
shell.ts | import { shell } from 'electron'
/**
* Wraps the inbuilt shell.openItem path to address a focus issue that affects macOS.
*
* When opening a folder in Finder, the window will appear behind the application
* window, which may confuse users. As a workaround, we will fallback to using
* shell.openExternal for macOS ... | {
// Add a trailing slash to the directory path.
//
// On Windows, if there's a file and a directory with the
// same name (e.g `C:\MyFolder\foo` and `C:\MyFolder\foo.exe`),
// when executing shell.openItem(`C:\MyFolder\foo`) then the EXE file
// will get opened.
// We can avoid this by adding a final bac... | identifier_body | |
shell.ts | import { shell } from 'electron'
/**
* Wraps the inbuilt shell.openItem path to address a focus issue that affects macOS.
*
* When opening a folder in Finder, the window will appear behind the application
* window, which may confuse users. As a workaround, we will fallback to using
* shell.openExternal for macOS ... |
})
}
| {
log.error(`Failed to open directory (${path}): ${err}`)
} | conditional_block |
shell.ts | import { shell } from 'electron'
/**
* Wraps the inbuilt shell.openItem path to address a focus issue that affects macOS.
*
* When opening a folder in Finder, the window will appear behind the application
* window, which may confuse users. As a workaround, we will fallback to using
* shell.openExternal for macOS ... | // will get opened.
// We can avoid this by adding a final backslash at the end of the path.
const pathname = __WIN32__ && !path.endsWith('\\') ? `${path}\\` : path
shell.openPath(pathname).then(err => {
if (err !== '') {
log.error(`Failed to open directory (${path}): ${err}`)
}
})
} | // when executing shell.openItem(`C:\MyFolder\foo`) then the EXE file | random_line_split |
shell.ts | import { shell } from 'electron'
/**
* Wraps the inbuilt shell.openItem path to address a focus issue that affects macOS.
*
* When opening a folder in Finder, the window will appear behind the application
* window, which may confuse users. As a workaround, we will fallback to using
* shell.openExternal for macOS ... | (path: string) {
// Add a trailing slash to the directory path.
//
// On Windows, if there's a file and a directory with the
// same name (e.g `C:\MyFolder\foo` and `C:\MyFolder\foo.exe`),
// when executing shell.openItem(`C:\MyFolder\foo`) then the EXE file
// will get opened.
// We can avoid this by add... | UNSAFE_openDirectory | identifier_name |
iterators.py | from scrapy.http import Response
from scrapy.selector import Selector
def xmliter_lxml(obj, nodename, namespace=None, prefix='x'):
from lxml import etree
reader = _StreamReader(obj)
tag = '{%s}%s' % (namespace, nodename) if namespace else nodename
iterable = etree.iterparse(reader, tag=tag, encoding=r... |
def _read_unicode(self, n=65535):
s, e = self._ptr, self._ptr + n
self._ptr = e
return self._text[s:e].encode('utf-8')
| s, e = self._ptr, self._ptr + n
self._ptr = e
return self._text[s:e] | identifier_body |
iterators.py | from scrapy.http import Response
from scrapy.selector import Selector
def xmliter_lxml(obj, nodename, namespace=None, prefix='x'):
from lxml import etree
reader = _StreamReader(obj)
tag = '{%s}%s' % (namespace, nodename) if namespace else nodename
iterable = etree.iterparse(reader, tag=tag, encoding=r... |
else:
self._text, self.encoding = obj, 'utf-8'
self._is_unicode = isinstance(self._text, unicode)
def read(self, n=65535):
self.read = self._read_unicode if self._is_unicode else self._read_string
return self.read(n).lstrip()
def _read_string(self, n=65535):
... | self._text, self.encoding = obj.body, obj.encoding | conditional_block |
iterators.py | from scrapy.http import Response
from scrapy.selector import Selector
def xmliter_lxml(obj, nodename, namespace=None, prefix='x'):
from lxml import etree
reader = _StreamReader(obj)
tag = '{%s}%s' % (namespace, nodename) if namespace else nodename
iterable = etree.iterparse(reader, tag=tag, encoding=r... | self._ptr = 0
if isinstance(obj, Response):
self._text, self.encoding = obj.body, obj.encoding
else:
self._text, self.encoding = obj, 'utf-8'
self._is_unicode = isinstance(self._text, unicode)
def read(self, n=65535):
self.read = self._read_unicode if... |
class _StreamReader(object):
def __init__(self, obj): | random_line_split |
iterators.py | from scrapy.http import Response
from scrapy.selector import Selector
def xmliter_lxml(obj, nodename, namespace=None, prefix='x'):
from lxml import etree
reader = _StreamReader(obj)
tag = '{%s}%s' % (namespace, nodename) if namespace else nodename
iterable = etree.iterparse(reader, tag=tag, encoding=r... | (self, n=65535):
s, e = self._ptr, self._ptr + n
self._ptr = e
return self._text[s:e]
def _read_unicode(self, n=65535):
s, e = self._ptr, self._ptr + n
self._ptr = e
return self._text[s:e].encode('utf-8')
| _read_string | identifier_name |
webdoc_webinterface.py | 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 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY... | redirect_to_url(req, url + ln_link)
else:
return display_webdoc_page(self.webdocname, categ=self.categ, ln=argd['ln'], req=req)
index = __call__
def display_webdoc_page(webdocname, categ="help", ln=CFG_SITE_LANG, req=None):
"""Display webdoc page WEBDOCNAME in language LN."""
... | url = CFG_SITE_URL + '/help/' + category + webdocname
ln_link = (ln != CFG_SITE_LANG and '?ln=' + ln) or '' | random_line_split |
webdoc_webinterface.py | 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 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY... |
ln_link = (ln != CFG_SITE_LANG and '?ln=' + ln) or ''
# get page parts in given language:
if webdocname != 'contents':
page_parts = get_webdoc_parts(webdocname, parts=['title', 'body',
'navtrail', 'lastupdated',
... | webdocname = 'help-central' | conditional_block |
webdoc_webinterface.py | 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 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY... | (WebInterfaceDirectory):
"""Defines the set of documentation pages, usually installed under /help."""
def __init__(self, webdocname='', categ='help'):
"""Constructor."""
self.webdocname = webdocname
self.categ = categ
self.legacy_urls_mappings = {'tips': 'search-tips',
... | WebInterfaceDocumentationPages | identifier_name |
webdoc_webinterface.py | 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 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY... |
def _lookup(self, component, path):
"""This handler parses dynamic URLs (/help/component)."""
if component in ['admin', 'hacking'] and len(path) == 1:
if path[0] != '':
webdocname = path[0] # /help/hacking/coding-style use
# codi... | """Constructor."""
self.webdocname = webdocname
self.categ = categ
self.legacy_urls_mappings = {'tips': 'search-tips',
'guide': 'search-guide',
'submit': 'submit-guide',
'index': '',
... | identifier_body |
entity.js | import _clone from 'lodash-es/clone';
import _keys from 'lodash-es/keys';
import _toPairs from 'lodash-es/toPairs';
import _union from 'lodash-es/union';
import _without from 'lodash-es/without';
import { debug } from '../index';
import { osmIsInterestingTag } from './tags';
import { dataDeprecated } from '../../data/... |
intersects: function(extent, resolver) {
return this.extent(resolver).intersects(extent);
},
isUsed: function(resolver) {
return _without(Object.keys(this.tags), 'area').length > 0 ||
resolver.parentRelations(this).length > 0;
},
hasInterestingTags: function() {
... | return changed ? this.update({tags: merged}) : this;
}, | random_line_split |
entity.js | import _clone from 'lodash-es/clone';
import _keys from 'lodash-es/keys';
import _toPairs from 'lodash-es/toPairs';
import _union from 'lodash-es/union';
import _without from 'lodash-es/without';
import { debug } from '../index';
import { osmIsInterestingTag } from './tags';
import { dataDeprecated } from '../../data/... |
osmEntity.id = function(type) {
return osmEntity.id.fromOSM(type, osmEntity.id.next[type]--);
};
osmEntity.id.next = {
changeset: -1, node: -1, way: -1, relation: -1
};
osmEntity.id.fromOSM = function(type, id) {
return type[0] + id;
};
osmEntity.id.toOSM = function(id) {
return id.slice(1);
};... | {
// For prototypal inheritance.
if (this instanceof osmEntity) return;
// Create the appropriate subtype.
if (attrs && attrs.type) {
return osmEntity[attrs.type].apply(this, arguments);
} else if (attrs && attrs.id) {
return osmEntity[osmEntity.id.type(attrs.id)].apply(this, argume... | identifier_body |
entity.js | import _clone from 'lodash-es/clone';
import _keys from 'lodash-es/keys';
import _toPairs from 'lodash-es/toPairs';
import _union from 'lodash-es/union';
import _without from 'lodash-es/without';
import { debug } from '../index';
import { osmIsInterestingTag } from './tags';
import { dataDeprecated } from '../../data/... | (attrs) {
// For prototypal inheritance.
if (this instanceof osmEntity) return;
// Create the appropriate subtype.
if (attrs && attrs.type) {
return osmEntity[attrs.type].apply(this, arguments);
} else if (attrs && attrs.id) {
return osmEntity[osmEntity.id.type(attrs.id)].apply(this... | osmEntity | identifier_name |
usage.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 ... | Install a package from a URL by Git or cURL (FTP, HTTP, etc.).
If target is provided, Git will checkout the branch or tag before
continuing. If the URL is a TAR file (with or without compression),
extract it before installing. If a URL isn't provided, the package will
be built and installed from the current directory (... |
pub fn install() {
io::println("rustpkg [options..] install [url] [target]
| random_line_split |
usage.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 ... | () {
io::println("rustpkg [options..] build
Build all targets described in the package script in the current
directory.
Options:
-c, --cfg Pass a cfg flag to the package script");
}
pub fn clean() {
io::println("rustpkg clean
Remove all build files in the work cache for the package in the current
d... | build | identifier_name |
usage.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 ... |
pub fn unprefer() {
io::println("rustpkg [options..] unprefer <id|name>[@version]
Remove all symlinks from the store to the binary directory for a package
name and optionally version. If version is not supplied, the latest version
of the package will be unpreferred. See `rustpkg prefer -h` for more
information."... | {
io::println("rustpkg [options..] prefer <id|name>[@version]
By default all binaries are given a unique name so that multiple versions can
coexist. The prefer command will symlink the uniquely named binary to
the binary directory under its bare name. If version is not supplied, the
latest version of the package w... | identifier_body |
topo_sort.py |
# Original topological sort code written by Ofer Faigon (www.bitformation.com) and used with permission
# Permission is hereby granted to copy, modify and use this source code for any purpose as long as the above comment line is included with it.
"""
Loop detection and depth calculation added by Zhenlei Cai (c) 2010... | graph[tonode][0] = graph[tonode][0] + 1
# step 1 - create a directed graph with an arc a->b for each input
# pair (a,b).
# The graph is represented by a dictionary. The dictionary contains
# a pair item:list for each node in the graph. /item/ is the value
# of the node. /list/'s 1st item is... | """Perform topological sort.
items is a list of items to be sorted.
partial_order is a list of pairs. If pair (a,b) is in it, it means
that item a should appear before item b.
Returns a list of the items in one of the possible orders, or
a tuple (True, [loop]) where loop ... | identifier_body |
topo_sort.py | # Original topological sort code written by Ofer Faigon (www.bitformation.com) and used with permission
# Permission is hereby granted to copy, modify and use this source code for any purpose as long as the above comment line is included with it.
"""
Loop detection and depth calculation added by Zhenlei Cai (c) 2010.... | next = start[1][1]
while next != loop[0]:
loop.append(next)
next = graph[next][1]
loop.append(loop[0])
return (True, loop)
return sorted | start = graph.popitem()
loop = [start[0]] | random_line_split |
topo_sort.py |
# Original topological sort code written by Ofer Faigon (www.bitformation.com) and used with permission
# Permission is hereby granted to copy, modify and use this source code for any purpose as long as the above comment line is included with it.
"""
Loop detection and depth calculation added by Zhenlei Cai (c) 2010... | (items, partial_order):
"""Perform topological sort.
items is a list of items to be sorted.
partial_order is a list of pairs. If pair (a,b) is in it, it means
that item a should appear before item b.
Returns a list of the items in one of the possible orders, or
a tupl... | topological_sort | identifier_name |
topo_sort.py |
# Original topological sort code written by Ofer Faigon (www.bitformation.com) and used with permission
# Permission is hereby granted to copy, modify and use this source code for any purpose as long as the above comment line is included with it.
"""
Loop detection and depth calculation added by Zhenlei Cai (c) 2010... |
del graph[root]
if len(graph.items()) != 0:
# There is a loop in the input.
start = graph.popitem()
loop = [start[0]]
next = start[1][1]
while next != loop[0]:
loop.append(next)
next = graph[next][1]
loop.append(loop[0])
return... | roots.append(child) | conditional_block |
hero.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
//Allows us to extend Observable with extra capabilities
import 'rxjs/add/operator/toPromise';
import { Hero } from '../classes/hero';
@Injectable()
export class HeroService {
private headers = new Headers({'Content-Type': ... |
/** ** ** ** ** ** ** ** ** ** ** ** **
GET an ARRAY of Heroes with an simulated delay
Get an array of Heroes
*/
getDataSlowly(): Promise<Hero[]> {
const ms = this.convertSecsToMillisecs(this.secsOfDelay);
return new Promise(resolve => {
setTimeout(() => resolve(this.getHeros()), ms);
});
}
convert... | //D. Catch any errors
.catch(this.onError);
} | random_line_split |
hero.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
//Allows us to extend Observable with extra capabilities
import 'rxjs/add/operator/toPromise';
import { Hero } from '../classes/hero';
@Injectable()
export class | {
private headers = new Headers({'Content-Type': 'application/json'});
private heroURL = 'http://localhost:8080/hero'
private heroesURL = 'http://localhost:8080/heroes'
private secsOfDelay = 0.2;
constructor(private http: Http) { }
/** ** ** ** ** ** ** ** ** ** ** ** **
GET a single Hero
*/
getHe... | HeroService | identifier_name |
hero.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
//Allows us to extend Observable with extra capabilities
import 'rxjs/add/operator/toPromise';
import { Hero } from '../classes/hero';
@Injectable()
export class HeroService {
private headers = new Headers({'Content-Type': ... |
/** ** ** ** ** ** ** ** ** ** ** ** **
Update a Hero
*/
update(hero:Hero): Promise<Hero> {
const url = `${this.heroURL}/${hero.id}`;
var data = JSON.stringify(hero)
//console.log(data);
return this.http
.put(url, data, { headers: this.headers })
.toPromise()
.then(() => hero)
.catch(this.onErro... | {
return this.http
.post(this.heroesURL, JSON.stringify({name: name}), { headers: this.headers })
.toPromise()
.then(res => res.json())
.catch(this.onError);
} | identifier_body |
shellscalingapi.rs | // except according to those terms.
ENUM!{enum PROCESS_DPI_AWARENESS {
Process_DPI_Unaware = 0,
Process_System_DPI_Aware = 1,
Process_Per_Monitor_DPI_Aware = 2,
}}
ENUM!{enum MONITOR_DPI_TYPE {
MDT_EFFECTIVE_DPI = 0,
MDT_ANGULAR_DPI = 1,
MDT_RAW_DPI = 2,
MDT_DEFAULT = MDT_EFFECTIVE_DPI,
}}
... | // Copyright © 2015-2017 winapi-rs developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied,... | random_line_split | |
__init__.py | """
The :mod:`sklearn.neighbors` module implements the k-nearest neighbors
algorithm.
"""
from .ball_tree import BallTree
from .kd_tree import KDTree
from .dist_metrics import DistanceMetric
from .graph import kneighbors_graph, radius_neighbors_graph
from .unsupervised import NearestNeighbors
from .classification impo... | 'VALID_METRICS',
'VALID_METRICS_SPARSE'] | 'NeighborhoodComponentsAnalysis', | random_line_split |
system_allocator.rs | , Result};
/// Manages allocating system resources such as address space and interrupt numbers.
/// MMIO address Type
/// Low: address allocated from low_address_space
/// High: address allocated from high_address_space
#[derive(Copy, Clone)]
pub enum MmioType {
Low,
High,
}
/// Region of memory.
pub s... |
/// Allocate PCI slot location.
pub fn allocate_pci(&mut self, bus: u8, tag: String) -> Option<Alloc> {
let id = self.get_anon_alloc();
let allocator = match self.get_pci_allocator_mut(bus) {
Some(v) => v,
None => return None,
};
allocator
.a... | {
if self.pci_allocator.get(&bus).is_none() {
true
} else {
false
}
} | identifier_body |
system_allocator.rs | , Result};
/// Manages allocating system resources such as address space and interrupt numbers.
/// MMIO address Type
/// Low: address allocated from low_address_space
/// High: address allocated from high_address_space
#[derive(Copy, Clone)]
pub enum MmioType {
Low,
High,
}
/// Region of memory.
pub s... | (&mut self, bus: u8) -> Option<&mut AddressAllocator> {
// pci root is 00:00.0, Bus 0 next device is 00:01.0 with mandatory function
// number zero.
if self.pci_allocator.get(&bus).is_none() {
let base = if bus == 0 { 8 } else { 0 };
// Each bus supports up to 32 (device... | get_pci_allocator_mut | identifier_name |
system_allocator.rs | Error, Result};
/// Manages allocating system resources such as address space and interrupt numbers.
/// MMIO address Type
/// Low: address allocated from low_address_space
/// High: address allocated from high_address_space
#[derive(Copy, Clone)]
pub enum MmioType {
Low,
High,
}
/// Region of memory.... | }
/// Reserves the next available system irq number.
pub fn reserve_irq(&mut self, irq: u32) -> bool {
let id = self.get_anon_alloc();
self.irq_allocator
.allocate_at(irq as u64, 1, id, "irq-fixed".to_string())
.is_ok()
}
fn get_pci_allocator_mut(&mut self, ... | random_line_split | |
ping.rs | // This file is generated by rust-protobuf 2.6.2. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![a... |
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self... | {
os.write_uint32(1, self.current_utc)?;
} | conditional_block |
ping.rs | // This file is generated by rust-protobuf 2.6.2. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![a... |
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn as_any_mut(&mut self) -> &mut ::std::any::Any {
self as &mut ::std::any::Any
}
fn into_any(self: Box... | {
&self.unknown_fields
} | identifier_body |
ping.rs | // This file is generated by rust-protobuf 2.6.2. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![a... | ::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields {
&mut self.unknow... | os.write_unknown_fields(self.get_unknown_fields())?; | random_line_split |
ping.rs | // This file is generated by rust-protobuf 2.6.2. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![a... | (&self) -> u32 {
self.current_utc
}
pub fn clear_current_utc(&mut self) {
self.current_utc = 0;
}
// Param is passed by value, moved
pub fn set_current_utc(&mut self, v: u32) {
self.current_utc = v;
}
}
impl ::protobuf::Message for PING_MESSAGE {
fn is_initialized(&... | get_current_utc | identifier_name |
os_c.py | import platform
class OSCollector(object):
def __init__(self, docker_client=None):
self.docker_client = docker_client
def key_name(self):
return "osInfo"
def _zip_fields_values(self, keys, values):
data = {}
for key, value in zip(keys, values):
if len(value) >... |
data['dockerVersion'] = version
return data
def _get_os(self):
data = {}
if platform.system() == 'Linux':
info = platform.linux_distribution()
keys = ["distribution", "version", "versionDescription"]
data = self._zip_fields_values(keys, inf... | ver_resp = self.docker_client.version()
version = "Docker version {0}, build {1}".format(
ver_resp.get("Version", "Unknown"),
ver_resp.get("GitCommit", "Unknown")) | conditional_block |
os_c.py | import platform
class OSCollector(object):
def __init__(self, docker_client=None):
self.docker_client = docker_client
def key_name(self):
return "osInfo"
def _zip_fields_values(self, keys, values):
data = {}
for key, value in zip(keys, values):
if len(value) >... |
def _get_os(self):
data = {}
if platform.system() == 'Linux':
info = platform.linux_distribution()
keys = ["distribution", "version", "versionDescription"]
data = self._zip_fields_values(keys, info)
data['kernelVersion'] = \
platform... | data = {}
if platform.system() == 'Linux':
version = "Unknown"
if self.docker_client:
ver_resp = self.docker_client.version()
version = "Docker version {0}, build {1}".format(
ver_resp.get("Version", "Unknown"),
ver... | identifier_body |
os_c.py | import platform
class OSCollector(object):
def __init__(self, docker_client=None):
self.docker_client = docker_client
def key_name(self):
return "osInfo"
def _zip_fields_values(self, keys, values):
data = {}
for key, value in zip(keys, values):
if len(value) >... |
return data
def get_data(self):
data = self._get_os()
data.update(self._get_docker_version())
return data | keys = ["distribution", "version", "versionDescription"]
data = self._zip_fields_values(keys, info)
data['kernelVersion'] = \
platform.release() if len(platform.release()) > 0 else None | random_line_split |
os_c.py | import platform
class OSCollector(object):
def | (self, docker_client=None):
self.docker_client = docker_client
def key_name(self):
return "osInfo"
def _zip_fields_values(self, keys, values):
data = {}
for key, value in zip(keys, values):
if len(value) > 0:
data[key] = value
else:
... | __init__ | identifier_name |
test_mysqldb.py | import sys
import pytest
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata... | ():
try:
import MySQLdb
with MySQLdb.connect(host='127.0.0.1', user='root'):
pass
return True
except:
return False
def assert_span(span, operation, parent=None):
assert span.operation_name == 'MySQLdb:' + operation
assert span.tags.get(tags.SPAN_KIND) == tag... | is_mysql_running | identifier_name |
test_mysqldb.py | import sys
import pytest
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata... | assert_span(rollback_span, 'rollback', root_span) | random_line_split | |
test_mysqldb.py | import sys
import pytest
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata... |
@pytest.mark.skipif(not is_mysql_running(), reason=SKIP_REASON_CONNECTION)
@pytest.mark.skipif(sys.version_info.major == 3, reason=SKIP_REASON_PYTHON_3)
def test_db(tracer, session):
root_span = tracer.start_span('root-span')
# span recording works for regular operations within a context only
with span_... | assert span.parent_id is None | conditional_block |
test_mysqldb.py | import sys
import pytest
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata... |
@pytest.mark.skipif(not is_mysql_running(), reason=SKIP_REASON_CONNECTION)
@pytest.mark.skipif(sys.version_info.major == 3, reason=SKIP_REASON_PYTHON_3)
def test_db(tracer, session):
root_span = tracer.start_span('root-span')
# span recording works for regular operations within a context only
with span_... | assert span.operation_name == 'MySQLdb:' + operation
assert span.tags.get(tags.SPAN_KIND) == tags.SPAN_KIND_RPC_CLIENT
if parent:
assert span.parent_id == parent.context.span_id
assert span.context.trace_id == parent.context.trace_id
else:
assert span.parent_id is None | identifier_body |
directory.rs | use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter};
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use hex::ToHex;
use serde_json;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use sources::PathSource;
use util::{Config, Sha256};
use util::... | {
package: String,
files: HashMap<String, String>,
}
impl<'cfg> DirectorySource<'cfg> {
pub fn new(path: &Path, id: &SourceId, config: &'cfg Config)
-> DirectorySource<'cfg> {
DirectorySource {
source_id: id.clone(),
root: path.to_path_buf(),
conf... | Checksum | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.