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 |
|---|---|---|---|---|
_steps.js | var locastyle = locastyle || {};
locastyle.steps = (function() {
'use strict';
var config = {
selectors: {
moduleActive: '.ls-actived [data-ls-module="steps"]',
nav: '.ls-steps-nav',
button: '.ls-steps-btn',
container: '.ls-steps-content',
steps: '.ls-steps',
moduleVisible:... |
}
// Displays the contents related to the active button
function addActivedNav() {
var index = $(config.selectors.nav).find(config.classes.active).index();
// Checks if there are any enabled button to load the page
if(index === -1) {
$(config.selectors.nav).each(function() {
var $el ... | {
var text = $($elem[i]).attr('title');
$($elem[i]).attr({ 'aria-label' : text });
} | conditional_block |
_steps.js | var locastyle = locastyle || {};
locastyle.steps = (function() {
'use strict';
var config = {
selectors: {
moduleActive: '.ls-actived [data-ls-module="steps"]',
nav: '.ls-steps-nav',
button: '.ls-steps-btn',
container: '.ls-steps-content',
steps: '.ls-steps',
moduleVisible:... | });
}
});
}
// Check what the order of the activated button
function addActiveContent(index) {
$(config.selectors.container).eq(index).addClass(config.status.active);
}
// Change the step
function changeStep($el) {
var $target = $($el.attr('href') || $el.data('target'));
activa... | $steps.stop().animate({
marginTop: 0 | random_line_split |
_steps.js | var locastyle = locastyle || {};
locastyle.steps = (function() {
'use strict';
var config = {
selectors: {
moduleActive: '.ls-actived [data-ls-module="steps"]',
nav: '.ls-steps-nav',
button: '.ls-steps-btn',
container: '.ls-steps-content',
steps: '.ls-steps',
moduleVisible:... |
// Always visible navigation when the page scrolls
function stepsAffix(elemVisible) {
var $steps = $(config.selectors.nav);
var offset = $steps.offset();
var $heightNav = $(config.selectors.nav).height();
$(window).scroll(function() {
if ($(window).width() < 768) {
return;
}
... | {
// TODO: when change the minor version we can remove this old event.
var evt = jQuery.Event('PrevStepEvent');
$(document).trigger(evt);
var beforeEvent = jQuery.Event('BeforePrevStep');
$(document).trigger(beforeEvent);
if(!evt.isDefaultPrevented() && !beforeEvent.isDefaultPrevented()) {
... | identifier_body |
fmt.rs | // Copyright 2012-2013 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... | {
ecx.span_err(sp, "`fmt!` is deprecated, use `format!` instead");
ecx.parse_sess.span_diagnostic.span_note(sp,
"see http://static.rust-lang.org/doc/master/std/fmt/index.html \
for documentation");
base::MRExpr(ecx.expr_uint(sp, 2))
} | identifier_body | |
fmt.rs | // Copyright 2012-2013 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... | } |
base::MRExpr(ecx.expr_uint(sp, 2)) | random_line_split |
fmt.rs | // Copyright 2012-2013 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... | (ecx: &mut base::ExtCtxt, sp: Span,
_tts: &[ast::TokenTree]) -> base::MacResult {
ecx.span_err(sp, "`fmt!` is deprecated, use `format!` instead");
ecx.parse_sess.span_diagnostic.span_note(sp,
"see http://static.rust-lang.org/doc/master/std/fmt/index.html \
for documenta... | expand_syntax_ext | identifier_name |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | () {
let content = r#"Hai
---
barbar
---
"#;
let file = mkfile(&content);
let res = entry_buffer_to_header_content(&file);
assert!(res.is_ok());
let (_, res_content) = res.unwrap();
assert_eq!(res_content, content)
}
#[test]
fn te... | test_entry_buffer_to_header_content_4 | identifier_name |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... |
#[test]
fn test_entry_buffer_to_header_content_3() {
let content = r#"Hai
barbar
"#;
let file = mkfile(&content);
let res = entry_buffer_to_header_content(&file);
assert!(res.is_ok());
let (_, res_content) = res.unwrap();
assert_eq!(res_content, content)
... | {
setup_logging();
let content = r#"Hai
"#;
let file = mkfile(&content);
debug!("FILE: <<<{}>>>", file);
let res = entry_buffer_to_header_content(&file);
assert!(res.is_ok());
let (_, res_content) = res.unwrap();
debug!("CONTENT: <<<{}>>>", res_content)... | identifier_body |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... |
fn setup_logging() {
let _ = env_logger::try_init();
}
fn mkfile(content: &str) -> String {
format!(r#"---
[imag]
version = '{version}'
---
{content}"#, version = env!("CARGO_PKG_VERSION"), content = content)
}
#[test]
fn test_entry_buffer_to_header_content_1() {
let c... | #[cfg(test)]
mod test {
extern crate env_logger;
use super::entry_buffer_to_header_content; | random_line_split |
utils.py | from __future__ import absolute_import
import hashlib
import jwt
from six.moves.urllib.parse import quote
from sentry.shared_integrations.exceptions import ApiError
def percent_encode(val):
# see https://en.wikipedia.org/wiki/Percent-encoding
return quote(val.encode("utf8", errors="replace")).replace("%7E"... |
sorted_query = []
for k, v in sorted(query_params.items()):
# don't include jwt query param
if k != "jwt":
if isinstance(v, list):
param_val = [percent_encode(val) for val in v].join(",")
else:
param_val = percent_encode(v)
so... | query_params = {} | conditional_block |
utils.py | from __future__ import absolute_import
import hashlib
import jwt
from six.moves.urllib.parse import quote
from sentry.shared_integrations.exceptions import ApiError
def percent_encode(val):
# see https://en.wikipedia.org/wiki/Percent-encoding
return quote(val.encode("utf8", errors="replace")).replace("%7E"... |
# TODO: probably shouldn't need to hardcode get... for post maybe
# the secret should just be a hidden field in the form ?
qsh = get_query_hash(request.path, "GET", request.GET)
# qsh = get_query_hash(request.path, request.method, request.GET)
if qsh != decoded_verified["qsh"]:
raise ApiErr... | token = request.GET.get("jwt")
if token is None:
raise ApiError("No token parameter")
# Decode the JWT token, without verification. This gives
# you a header JSON object, a claims JSON object, and a signature.
decoded = jwt.decode(token, verify=False)
# Extract the issuer ('iss') claim from ... | identifier_body |
utils.py | from __future__ import absolute_import
import hashlib
import jwt
from six.moves.urllib.parse import quote
from sentry.shared_integrations.exceptions import ApiError
def percent_encode(val):
# see https://en.wikipedia.org/wiki/Percent-encoding
return quote(val.encode("utf8", errors="replace")).replace("%7E"... | method = method.upper()
if query_params is None:
query_params = {}
sorted_query = []
for k, v in sorted(query_params.items()):
# don't include jwt query param
if k != "jwt":
if isinstance(v, list):
param_val = [percent_encode(val) for val in v].join("... | # https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html#qsh
uri = uri.rstrip("/") | random_line_split |
utils.py | from __future__ import absolute_import
import hashlib
import jwt
from six.moves.urllib.parse import quote
from sentry.shared_integrations.exceptions import ApiError
def percent_encode(val):
# see https://en.wikipedia.org/wiki/Percent-encoding
return quote(val.encode("utf8", errors="replace")).replace("%7E"... | (request):
# https://developer.atlassian.com/static/connect/docs/latest/concepts/authentication.html
# Extract the JWT token from the request's jwt query
# parameter or the authorization header.
token = request.GET.get("jwt")
if token is None:
raise ApiError("No token parameter")
# Decod... | get_jira_auth_from_request | identifier_name |
data_exporter.js | default: this.exporting_for === 'Insert New Records' ? 'blank_template' : 'all',
change: () => {
this.update_record_count_message();
}
},
{
fieldtype: 'HTML',
fieldname: 'filter_area',
depends_on: doc => doc.export_records === 'by_filter'
},
{
fieldtype: 'Select',
... | };
// parent
let doctype_fields = frappe.meta
.get_docfields(doctype) | random_line_split | |
data_exporter.js | ',
label: __('Export Type'),
options: [
{
label: __('All Records'),
value: 'all'
},
{
label: __('Filtered Records'),
value: 'by_filter'
},
{
label: __('5 Records'),
value: '5_records'
},
{
label: __('Blank Template'),
... | () {
this.dialog.$wrapper
.find(':checkbox')
.prop('checked', true)
.trigger('change');
}
select_mandatory() {
let mandatory_table_fields = frappe.meta
.get_table_fields(this.doctype)
.filter(df => df.reqd)
.map(df => df.fieldname);
mandatory_table_fields.push(this.doctype);
let multicheck... | select_all | identifier_name |
data_exporter.js | ',
label: __('Export Type'),
options: [
{
label: __('All Records'),
value: 'all'
},
{
label: __('Filtered Records'),
value: 'by_filter'
},
{
label: __('5 Records'),
value: '5_records'
},
{
label: __('Blank Template'),
... |
open_url_post(method, {
doctype: this.doctype,
file_type: values.file_type,
export_records: values.export_records,
export_fields: doctype_field_map,
export_filters: filters
});
}
make_filter_area() {
this.filter_group = new frappe.ui.FilterGroup({
parent: this.dialog.get_field('filter_area'... | {
filters = this.get_filters();
} | conditional_block |
data_exporter.js | ',
label: __('Export Type'),
options: [
{
label: __('All Records'),
value: 'all'
},
{
label: __('Filtered Records'),
value: 'by_filter'
},
{
label: __('5 Records'),
value: '5_records'
},
{
label: __('Blank Template'),
... |
select_mandatory() {
let mandatory_table_fields = frappe.meta
.get_table_fields(this.doctype)
.filter(df => df.reqd)
.map(df => df.fieldname);
mandatory_table_fields.push(this.doctype);
let multicheck_fields = this.dialog.fields
.filter(df => df.fieldtype === 'MultiCheck')
.map(df => df.fieldna... | {
this.dialog.$wrapper
.find(':checkbox')
.prop('checked', true)
.trigger('change');
} | identifier_body |
getCurrent.js | "use strict";
const getFirstIndex = require("./getFirstIndex");
const TimeUtils = require("./TimeUtils");
const dateToSeconds = TimeUtils.dateToSeconds;
const hoursToSeconds = TimeUtils.hoursToSeconds;
// get the current salat index from a list of times
const getCurrent = (times, date) => {
const now = date || n... | module.exports = getCurrent; |
// otherwise the current salat is the last item
return (first + total - 1) % total;
};
| random_line_split |
BatchJob.ts | import BatchReader from "./BatchReader";
import BatchProcessor from "./BatchProcessor";
import BatchWriter from "./BatchWriter";
import AbstractJob from "./AbstractJob";
export default class BatchJob extends AbstractJob {
constructor(
public jobName: string,
private reader: BatchReader<any>,
... |
protected async doRun(executionContext?): Promise<void> {
await this.reader.open(executionContext);
while(true) {
let item = await this.reader.read(executionContext);
if (item === null) break;
await this.processItem(item, executionContext);
}
awa... | {
super(jobName);
} | identifier_body |
BatchJob.ts | import BatchReader from "./BatchReader";
import BatchProcessor from "./BatchProcessor";
import BatchWriter from "./BatchWriter";
import AbstractJob from "./AbstractJob";
export default class BatchJob extends AbstractJob {
constructor(
public jobName: string,
private reader: BatchReader<any>,
... |
await this.reader.close(executionContext);
}
private async processItem(item, executionContext?): Promise<void> {
for (let processor of this.processors) {
item = await processor.process(item, executionContext);
}
await this.writer.write(item, executionContext);
}... | {
let item = await this.reader.read(executionContext);
if (item === null) break;
await this.processItem(item, executionContext);
} | conditional_block |
BatchJob.ts | import BatchReader from "./BatchReader";
import BatchProcessor from "./BatchProcessor";
import BatchWriter from "./BatchWriter";
import AbstractJob from "./AbstractJob";
export default class BatchJob extends AbstractJob {
constructor(
public jobName: string,
private reader: BatchReader<any>,
... | (item, executionContext?): Promise<void> {
for (let processor of this.processors) {
item = await processor.process(item, executionContext);
}
await this.writer.write(item, executionContext);
}
} | processItem | identifier_name |
BatchJob.ts | import BatchReader from "./BatchReader";
import BatchProcessor from "./BatchProcessor";
import BatchWriter from "./BatchWriter";
import AbstractJob from "./AbstractJob";
export default class BatchJob extends AbstractJob {
constructor(
public jobName: string,
private reader: BatchReader<any>,
... | protected async doRun(executionContext?): Promise<void> {
await this.reader.open(executionContext);
while(true) {
let item = await this.reader.read(executionContext);
if (item === null) break;
await this.processItem(item, executionContext);
}
await... | random_line_split | |
checkbox.ts | ValueAccessor} from '@angular/common';
/**
* Monotonically increasing integer used to auto-generate unique ids for checkbox components.
*/
let nextId = 0;
/**
* Provider Expression that allows md-checkbox to register as a ControlValueAccessor. This allows it
* to support [(ngModel)] and ngControl.
*/
const MD_CH... |
}
private _getAnimationClassForCheckStateTransition(
oldState: TransitionCheckState, newState: TransitionCheckState): string {
var animSuffix: string;
switch (oldState) {
case TransitionCheckState.Init:
// Handle edge case where user interacts with checkbox that does not have [(ngModel)] ... | {
this.toggle();
} | conditional_block |
checkbox.ts | ControlValueAccessor} from '@angular/common';
/**
* Monotonically increasing integer used to auto-generate unique ids for checkbox components.
*/
let nextId = 0;
/**
* Provider Expression that allows md-checkbox to register as a ControlValueAccessor. This allows it
* to support [(ngModel)] and ngControl.
*/
con... | () {
this.hasFocus = false;
this.onTouched();
}
/**
* Toggles the `checked` value between true and false
*/
toggle() {
this.checked = !this.checked;
}
/**
* Event handler for checkbox input element.
* Toggles checked state if element is not disabled.
* @param event
* @internal
... | onInputBlur | identifier_name |
checkbox.ts | ValueAccessor} from '@angular/common';
/**
* Monotonically increasing integer used to auto-generate unique ids for checkbox components.
*/
let nextId = 0;
/**
* Provider Expression that allows md-checkbox to register as a ControlValueAccessor. This allows it
* to support [(ngModel)] and ngControl.
*/
const MD_CH... |
set indeterminate(indeterminate: boolean) {
this._indeterminate = indeterminate;
if (this._indeterminate) {
this._transitionCheckState(TransitionCheckState.Indeterminate);
} else {
this._transitionCheckState(
this.checked ? TransitionCheckState.Checked : TransitionCheckState.Unchec... | {
return this._indeterminate;
} | identifier_body |
checkbox.ts | ControlValueAccessor} from '@angular/common';
/**
* Monotonically increasing integer used to auto-generate unique ids for checkbox components.
*/
let nextId = 0;
/**
* Provider Expression that allows md-checkbox to register as a ControlValueAccessor. This allows it
* to support [(ngModel)] and ngControl.
*/
con... |
/**
* Event handler for checkbox input element.
* Toggles checked state if element is not disabled.
* @param event
* @internal
*/
onInteractionEvent(event: Event) {
// We always have to stop propagation on the change event.
// Otherwise the change event, from the input element, will bubble u... | */
toggle() {
this.checked = !this.checked;
} | random_line_split |
util.rs | // This file is made up largely of utility methods which are invoked by the
// session in its interpret method. They are separate because they don't rely
// on the session (or take what they do need as arguments) and/or they are
// called by the session in multiple places.
use std::env::current_dir;
use std::fs;
use s... | (dir: &Path) -> String {
match current_dir() {
Err(_) => dir.display().to_string(),
Ok(absp) => {
let mut abs_path = absp.clone();
abs_path.push(dir);
abs_path.display().to_string()
}
}
}
pub fn perform_select(maildir: &str, select_args: &[&str], exam... | make_absolute | identifier_name |
util.rs | // This file is made up largely of utility methods which are invoked by the
// session in its interpret method. They are separate because they don't rely
// on the session (or take what they do need as arguments) and/or they are
// called by the session in multiple places.
use std::env::current_dir;
use std::fs;
use s... | {
let maildir_path = Path::new(maildir);
let mut responses = Vec::new();
if let Some(list_response) = list_dir(maildir_path, regex, maildir_path) {
responses.push(list_response);
}
for dir_res in WalkDir::new(&maildir_path) {
if let Ok(dir) = dir_res {
if let Some(list_re... | identifier_body | |
util.rs | // This file is made up largely of utility methods which are invoked by the
// session in its interpret method. They are separate because they don't rely
// on the session (or take what they do need as arguments) and/or they are
// called by the session in multiple places.
use std::env::current_dir;
use std::fs;
use s... |
}
responses
}
| {
if let Some(list_response) = list_dir(dir.path(), regex, maildir_path) {
responses.push(list_response);
}
} | conditional_block |
util.rs | // This file is made up largely of utility methods which are invoked by the
// session in its interpret method. They are separate because they don't rely
// on the session (or take what they do need as arguments) and/or they are
// called by the session in multiple places.
use std::env::current_dir;
use std::fs;
use s... | continue;
}
if fs::read_dir(&subdir.path().join("new")).is_err() {
continue;
}
children = true;
break;
... | let subdir_str = path_filename_to_str!(subdir_path);
if subdir_str != "cur" &&
subdir_str != "new" &&
subdir_str != "tmp" {
if fs::read_dir(&subdir.path().join("cur")).is_err() { | random_line_split |
liquid.rs |
use std::io::Write;
use std::sync::{Arc, RwLock};
use world::{self, block};
use shared::Direction;
use model::BlockVertex;
use render;
pub fn render_liquid<W: Write>(textures: Arc<RwLock<render::TextureManager>>,lava: bool, snapshot: &world::Snapshot, x: i32, y: i32, z: i32, buf: &mut W) -> usize {
let get_liquid... | (snapshot: &world::Snapshot, x: i32, y: i32, z: i32) -> Option<i32> {
match snapshot.get_block(x, y, z) {
block::Block::Water{level} | block::Block::FlowingWater{level} => Some(level as i32),
_ => None,
}
}
fn get_lava_level(snapshot: &world::Snapshot, x: i32, y: i32, z: i32) -> Option<i32> {
... | get_water_level | identifier_name |
liquid.rs |
use std::io::Write;
use std::sync::{Arc, RwLock};
use world::{self, block};
use shared::Direction;
use model::BlockVertex;
use render;
pub fn render_liquid<W: Write>(textures: Arc<RwLock<render::TextureManager>>,lava: bool, snapshot: &world::Snapshot, x: i32, y: i32, z: i32, buf: &mut W) -> usize {
let get_liquid... | (_, _) => ((16.0 / 8.0) * (br as f32)) as i32,
};
vert.y = (height as f32)/16.0 + (y as f32);
}
vert.x += x as f32;
vert.z += z as f32;
let (bl, sl) = super::calculate_light(
... | {
let verts = BlockVertex::face_by_direction(dir);
for vert in verts {
let mut vert = vert.clone();
vert.tx = tex.get_x() as u16;
vert.ty = tex.get_y() as u16;
vert.tw = tex.get_width() as u16;
vert.th = tex.get_heig... | conditional_block |
liquid.rs | use std::io::Write;
use std::sync::{Arc, RwLock};
use world::{self, block};
use shared::Direction;
use model::BlockVertex;
use render; | let get_liquid = if lava {
get_lava_level
} else {
get_water_level
};
let mut count = 0;
let (tl, tr, bl, br) = if get_liquid(snapshot, x, y + 1, z).is_some() {
(8, 8, 8, 8)
} else {
(
average_liquid_level(get_liquid, snapshot, x, y, z),
... |
pub fn render_liquid<W: Write>(textures: Arc<RwLock<render::TextureManager>>,lava: bool, snapshot: &world::Snapshot, x: i32, y: i32, z: i32, buf: &mut W) -> usize { | random_line_split |
liquid.rs |
use std::io::Write;
use std::sync::{Arc, RwLock};
use world::{self, block};
use shared::Direction;
use model::BlockVertex;
use render;
pub fn render_liquid<W: Write>(textures: Arc<RwLock<render::TextureManager>>,lava: bool, snapshot: &world::Snapshot, x: i32, y: i32, z: i32, buf: &mut W) -> usize {
let get_liquid... |
fn get_water_level(snapshot: &world::Snapshot, x: i32, y: i32, z: i32) -> Option<i32> {
match snapshot.get_block(x, y, z) {
block::Block::Water{level} | block::Block::FlowingWater{level} => Some(level as i32),
_ => None,
}
}
fn get_lava_level(snapshot: &world::Snapshot, x: i32, y: i32, z: i32... | {
let mut level = 0;
for xx in -1 .. 1 {
for zz in -1 .. 1 {
if get(snapshot, x+xx, y+1, z+zz).is_some() {
return 8;
}
if let Some(l) = get(snapshot, x+xx, y, z+zz) {
let nl = 7 - (l & 0x7);
if nl > level {
... | identifier_body |
tabhistory.py | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... | data = {
'originalURLString': item.original_url.toString(QUrl.FullyEncoded),
'scrollPosition': {'x': 0, 'y': 0},
'title': item.title,
'urlString': item.url.toString(QUrl.FullyEncoded),
}
try:
data['scrollPosition']['x'] = item.user_data['scroll-pos'].x()
data[... | random_line_split | |
tabhistory.py | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... | (items):
"""Serialize a list of WebHistoryItems to a data stream.
Args:
items: An iterable of WebHistoryItems.
Return:
A (stream, data, user_data) tuple.
stream: The reset QDataStream.
data: The QByteArray with the raw data.
user_data: A list with each i... | serialize | identifier_name |
tabhistory.py | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... |
def _serialize_item(item):
data = {
'originalURLString': item.original_url.toString(QUrl.FullyEncoded),
'scrollPosition': {'x': 0, 'y': 0},
'title': item.title,
'urlString': item.url.toString(QUrl.FullyEncoded),
}
try:
data['scrollPosition']['x'] = item.user_data['... | data = {'currentItemIndex': current_idx, 'history': []}
for item in items:
data['history'].append(_serialize_item(item))
stream.writeInt(3) # history stream version
stream.writeQVariantMap(data) | identifier_body |
tabhistory.py | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... |
stream.writeInt(3) # history stream version
stream.writeQVariantMap(data)
def _serialize_item(item):
data = {
'originalURLString': item.original_url.toString(QUrl.FullyEncoded),
'scrollPosition': {'x': 0, 'y': 0},
'title': item.title,
'urlString': item.url.toString(QUrl.... | data['history'].append(_serialize_item(item)) | conditional_block |
react-native-material-ui-tests.tsx | import * as React from 'react';
import { View, Text } from 'react-native';
import {
ActionButton,
Avatar,
ThemeProvider,
COLOR,
Badge,
Button,
Card,
Checkbox,
Dialog,
DialogDefaultActions,
BottomNavigation
} from 'react-native-material-ui';
const theme = {
palette: {
... |
render() {
return (
<BottomNavigation active={this.state.active} hidden={false} >
<BottomNavigation.Action
key="today"
icon="today"
label="Today"
active={this.state.active === 'today'}
... | {
super();
this.state = {
active: 'today'
};
} | identifier_body |
react-native-material-ui-tests.tsx | import * as React from 'react';
import { View, Text } from 'react-native';
import {
ActionButton,
Avatar,
ThemeProvider,
COLOR,
Badge,
Button,
Card,
Checkbox,
Dialog,
DialogDefaultActions,
BottomNavigation
} from 'react-native-material-ui';
const theme = {
palette: {
... | () {
super();
this.state = {
active: 'today'
};
}
render() {
return (
<BottomNavigation active={this.state.active} hidden={false} >
<BottomNavigation.Action
key="today"
icon="today"
... | constructor | identifier_name |
react-native-material-ui-tests.tsx | import * as React from 'react';
import { View, Text } from 'react-native';
import {
ActionButton,
Avatar,
ThemeProvider,
COLOR,
Badge,
Button,
Card,
Checkbox,
Dialog,
DialogDefaultActions,
BottomNavigation
} from 'react-native-material-ui';
const theme = {
palette: {
... | active={this.state.active === 'people'}
onPress={() => this.setState({ active: 'people' })}
/>
<BottomNavigation.Action
key="bookmark-border"
icon="bookmark-border"
label="Bookmark"
... | label="People" | random_line_split |
DateTimeConstants__zh_SG.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ma... | };
gadgets.i18n.DateTimeConstants.STANDALONENARROWMONTHS = gadgets.i18n.DateTimeConstants.NARROWMONTHS;
gadgets.i18n.DateTimeConstants.STANDALONEWEEKDAYS = gadgets.i18n.DateTimeConstants.WEEKDAYS;
gadgets.i18n.DateTimeConstants.STANDALONESHORTWEEKDAYS = gadgets.i18n.DateTimeConstants.SHORTWEEKDAYS;
gadgets.i18n.DateTim... | FIRSTDAYOFWEEK: 6,
WEEKENDRANGE: [5, 6],
FIRSTWEEKCUTOFFDAY: 2 | random_line_split |
sub.rs | -APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty::{BuiltinBounds};
use middle::ty;
use middle::ty::TyVar;
use ... | (&self, a: BuiltinBounds, b: BuiltinBounds) -> cres<BuiltinBounds> {
// More bounds is a subtype of fewer bounds.
//
// e.g., fn:Copy() <: fn(), because the former is a function
// that only closes over copyable things, but the latter is
// any function at all.
if a.conta... | bounds | identifier_name |
sub.rs | -APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty::{BuiltinBounds};
use middle::ty;
use middle::ty::TyVar;
use ... | if_ok!(self.get_ref().var_sub_t(a_id, b));
Ok(a)
}
(_, &ty::ty_infer(TyVar(b_id))) => {
if_ok!(self.get_ref().t_sub_var(a, b_id));
Ok(a)
}
(_, &ty::ty_bot) => {
Err(ty::terr_sorts(expected_fo... | (&ty::ty_infer(TyVar(a_id)), &ty::ty_infer(TyVar(b_id))) => {
if_ok!(self.get_ref().var_sub_var(a_id, b_id));
Ok(a)
}
(&ty::ty_infer(TyVar(a_id)), _) => { | random_line_split |
sub.rs | APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty::{BuiltinBounds};
use middle::ty;
use middle::ty::TyVar;
use m... |
fn tag(&self) -> ~str { ~"sub" }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace }
fn sub<'a>(&'a self) -> Sub<'a> { Sub(*self.get_ref()) }
fn lub<'a>(&'a self) -> Lub<'a> { Lub(*self.get_ref()) }
fn glb<'a>(&'a self) -> Glb<... | { self.get_ref().infcx } | identifier_body |
sub.rs | APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty::{BuiltinBounds};
use middle::ty;
use middle::ty::TyVar;
use m... |
(_, &ty::ty_infer(TyVar(b_id))) => {
if_ok!(self.get_ref().t_sub_var(a, b_id));
Ok(a)
}
(_, &ty::ty_bot) => {
Err(ty::terr_sorts(expected_found(self, a, b)))
}
_ => {
super_tys(self, a, b)
... | {
if_ok!(self.get_ref().var_sub_t(a_id, b));
Ok(a)
} | conditional_block |
jquery.easteregg.js | /*!
* Jquery EasterEgg v1.0.0 (https://github.com/gonpre/EasterEgg)
*
* Copyright 2015 Francisco Gonzalez
* Licensed under MIT (https://github.com/gonpre/EasterEgg/blob/master/LICENSE)
*/
(function($){
$.fn.easteregg = function(settings) {
var _settings = $.extend({}, $.fn.easteregg.default_settings... | (array1, array2) {
return array1.lenght == array2.lenght && array1.every(function(element, index) {
return element === array2[index];
});
}
var EasterEgg = function(settings){
this._settings = settings;
this._pressed_keys = [];
this._timer;
};
Ea... | is_same_array | identifier_name |
jquery.easteregg.js | /*!
* Jquery EasterEgg v1.0.0 (https://github.com/gonpre/EasterEgg)
*
* Copyright 2015 Francisco Gonzalez
* Licensed under MIT (https://github.com/gonpre/EasterEgg/blob/master/LICENSE)
*/
(function($){
$.fn.easteregg = function(settings) {
var _settings = $.extend({}, $.fn.easteregg.default_settings... |
}
});
});
_self._timer = _self.getTimer();
},
setKonami : function(callback) {
this._settings.eggsters[0].callback = callback;
},
addEgg : function(keys, callback) {
if (!($.type(keys) === 'array' || $.... | {
eggster.callback();
} | conditional_block |
jquery.easteregg.js | /*!
* Jquery EasterEgg v1.0.0 (https://github.com/gonpre/EasterEgg)
*
* Copyright 2015 Francisco Gonzalez
* Licensed under MIT (https://github.com/gonpre/EasterEgg/blob/master/LICENSE)
*/
(function($){
$.fn.easteregg = function(settings) {
var _settings = $.extend({}, $.fn.easteregg.default_settings... | eggsters : [
{
keys : [38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 66, 65],
callback : null
}
]
};
function is_same_array(array1, array2) {
return array1.lenght == array2.lenght && array1.every(function(element, index) {
... |
$.fn.easteregg.default_settings = {
delay_time : 1000, | random_line_split |
jquery.easteregg.js | /*!
* Jquery EasterEgg v1.0.0 (https://github.com/gonpre/EasterEgg)
*
* Copyright 2015 Francisco Gonzalez
* Licensed under MIT (https://github.com/gonpre/EasterEgg/blob/master/LICENSE)
*/
(function($){
$.fn.easteregg = function(settings) {
var _settings = $.extend({}, $.fn.easteregg.default_settings... |
var EasterEgg = function(settings){
this._settings = settings;
this._pressed_keys = [];
this._timer;
};
EasterEgg.VERSION = '1.0.0';
EasterEgg.prototype = {
init : function() {
var _self = this;
$(document).on('keydown', function(event){
... | {
return array1.lenght == array2.lenght && array1.every(function(element, index) {
return element === array2[index];
});
} | identifier_body |
paux.py | #!/usr/bin/env python
###############################################################################
# $Id: paux.py 32163 2015-12-13 17:44:50Z goatbar $
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read/write functionality for PAux driver.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
#####################... |
gdaltest_list = [
paux_1,
paux_2,
paux_3,
paux_cleanup ]
if __name__ == '__main__':
gdaltest.setup_run( 'paux' )
gdaltest.run_tests( gdaltest_list )
gdaltest.summarize() | return 'success' | random_line_split |
paux.py | #!/usr/bin/env python
###############################################################################
# $Id: paux.py 32163 2015-12-13 17:44:50Z goatbar $
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read/write functionality for PAux driver.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
#####################... |
gdaltest_list = [
paux_1,
paux_2,
paux_3,
paux_cleanup ]
if __name__ == '__main__':
gdaltest.setup_run( 'paux' )
gdaltest.run_tests( gdaltest_list )
gdaltest.summarize()
| gdaltest.clean_tmp()
return 'success' | identifier_body |
paux.py | #!/usr/bin/env python
###############################################################################
# $Id: paux.py 32163 2015-12-13 17:44:50Z goatbar $
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read/write functionality for PAux driver.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
#####################... | gdaltest.setup_run( 'paux' )
gdaltest.run_tests( gdaltest_list )
gdaltest.summarize() | conditional_block | |
paux.py | #!/usr/bin/env python
###############################################################################
# $Id: paux.py 32163 2015-12-13 17:44:50Z goatbar $
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read/write functionality for PAux driver.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
#####################... | ():
gdaltest.clean_tmp()
return 'success'
gdaltest_list = [
paux_1,
paux_2,
paux_3,
paux_cleanup ]
if __name__ == '__main__':
gdaltest.setup_run( 'paux' )
gdaltest.run_tests( gdaltest_list )
gdaltest.summarize()
| paux_cleanup | identifier_name |
helpers.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... |
}
pub fn init_server(hosts: Option<Vec<String>>, is_syncing: bool) -> (Server, Arc<FakeRegistrar>) {
init_logger();
let registrar = Arc::new(FakeRegistrar::new());
let mut dapps_path = env::temp_dir();
dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading");
let mut builder = ServerBuilder::new(dapp... | {
let mut builder = LogBuilder::new();
builder.parse(&log);
builder.init().expect("Logger is initialized only once.");
} | conditional_block |
helpers.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... |
pub fn assert_security_headers(headers: &[String]) {
http_client::assert_security_headers_present(headers, None)
}
pub fn assert_security_headers_for_embed(headers: &[String]) {
http_client::assert_security_headers_present(headers, Some(SIGNER_PORT))
}
| {
http_client::request(server.addr(), request)
} | identifier_body |
helpers.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... | }
}
pub fn init_server(hosts: Option<Vec<String>>, is_syncing: bool) -> (Server, Arc<FakeRegistrar>) {
init_logger();
let registrar = Arc::new(FakeRegistrar::new());
let mut dapps_path = env::temp_dir();
dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading");
let mut builder = ServerBuilder::new(da... | random_line_split | |
helpers.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... | (&self, address: Address, data: Bytes) -> Result<Bytes, String> {
self.calls.lock().push((address.to_hex(), data.to_hex()));
self.responses.lock().remove(0)
}
}
fn init_logger() {
// Initialize logger
if let Ok(log) = env::var("RUST_LOG") {
let mut builder = LogBuilder::new();
builder.parse(&log);
builder... | call | identifier_name |
app.component.ts | import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Component({
selector: 'my-app',
template: `
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<... | { name = 'Pannenkoek'; }
| AppComponent | identifier_name |
app.component.ts | import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Component({
selector: 'my-app',
template: `
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<... | <span class="icon-bar"></span>
</button>
<a class="navbar-brand" routerLink="/" >CountDown</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a routerLink="/new" >Nieuw <span class="s... | <span class="icon-bar"></span>
<span class="icon-bar"></span> | random_line_split |
core.py | ample_paths(gpaths):
# paths = copy.deepcopy(gpaths)
# for i in range(len(paths)):
# plen = paths[i]['action'].shape[0]
# rno = random.sample(range(plen), 2*plen/3)
# for j in paths[i].keys():
# paths[i][j] = np.delete(paths[i][j], rno, axis=0)
# return paths
def paralle... | def callback(result):
print("Length of paths: ", len(result), type(result))
paths.extend([path for paths_list in result for path in paths_list])
args_list = [(agent,
cfg['timestep_limit'],
cfg['timesteps_per_batch'] / num_proce... | num_processes = int(cfg["parallel"])
pool = Pool(processes=num_processes)
# very simple scheme, split work evenly among pool workers (queue would be better)
try: | random_line_split |
core.py | _paths(gpaths):
# paths = copy.deepcopy(gpaths)
# for i in range(len(paths)):
# plen = paths[i]['action'].shape[0]
# rno = random.sample(range(plen), 2*plen/3)
# for j in paths[i].keys():
# paths[i][j] = np.delete(paths[i][j], rno, axis=0)
# return paths
def parallel_rol... | (self, prob):
out = np.zeros_like(prob)
out[prob.argmax(axis=1)] = 1
class DiagGauss(ProbType):
def __init__(self, d):
self.d = d
def sampled_variable(self):
return T.matrix('a')
def prob | maxprob | identifier_name |
core.py | ample_paths(gpaths):
# paths = copy.deepcopy(gpaths)
# for i in range(len(paths)):
# plen = paths[i]['action'].shape[0]
# rno = random.sample(range(plen), 2*plen/3)
# for j in paths[i].keys():
# paths[i][j] = np.delete(paths[i][j], rno, axis=0)
# return paths
def paralle... |
@property
def variables(self):
return self._net.get_params()[0]
@property
def input(self):
return self._net.input
def get_output(self):
return self._net.output
def get_updates(self):
self._net.output #pylint: disable=W0104
return self._net.updates
def... | return self._net.trainable_weights | identifier_body |
core.py | ) + .5 * np.log(2 * np.pi * np.e) * self.d
def sample(self, prob):
mean_nd = prob[:, :self.d]
std_nd = prob[:, self.d:]
return np.random.randn(prob.shape[0], self.d).astype(floatX) * std_nd + mean_nd
def maxprob(self, prob):
return prob[:, :self.d]
def test_probtypes():
the... | self.all_losses.update(extra_losses) | conditional_block | |
chip-input-harness.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {HarnessPredicate, ComponentHarness, TestKey} from '@angular/cdk/testing';
import {ChipInputHarnessFilters} fr... |
}
/** Sends a chip separator key to the input element. */
async sendSeparatorKey(key: TestKey | string): Promise<void> {
const inputEl = await this.host();
return inputEl.sendKeys(key);
}
}
| {
await inputEl.sendKeys(newValue);
} | conditional_block |
chip-input-harness.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {HarnessPredicate, ComponentHarness, TestKey} from '@angular/cdk/testing';
import {ChipInputHarnessFilters} fr... |
/** Gets the value of the input. */
async getValue(): Promise<string> {
// The "value" property of the native input is never undefined.
return (await (await this.host()).getProperty('value'))!;
}
/** Gets the placeholder of the input. */
async getPlaceholder(): Promise<string> {
return (await (... | {
return (await this.host()).getProperty('required')!;
} | identifier_body |
chip-input-harness.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {HarnessPredicate, ComponentHarness, TestKey} from '@angular/cdk/testing';
import {ChipInputHarnessFilters} fr... |
/** Gets the value of the input. */
async getValue(): Promise<string> {
// The "value" property of the native input is never undefined.
return (await (await this.host()).getProperty('value'))!;
}
/** Gets the placeholder of the input. */
async getPlaceholder(): Promise<string> {
return (await (a... | return (await this.host()).getProperty('required')!;
} | random_line_split |
chip-input-harness.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {HarnessPredicate, ComponentHarness, TestKey} from '@angular/cdk/testing';
import {ChipInputHarnessFilters} fr... | (): Promise<boolean> {
return (await this.host()).getProperty('disabled')!;
}
/** Whether the input is required. */
async isRequired(): Promise<boolean> {
return (await this.host()).getProperty('required')!;
}
/** Gets the value of the input. */
async getValue(): Promise<string> {
// The "valu... | isDisabled | identifier_name |
feature_flags.rs | use fuse::{FileType, ReplyAttr, ReplyData, ReplyEntry, Request};
use fs::constants;
use fs::GoodDataFS;
use fs::helpers::create_inode_file_attributes;
use fs::item;
use fs::inode;
use helpers;
use object;
use std::path::Path;
use super::project_from_inode;
fn getattr(fs: &mut GoodDataFS, _req: &Request, ino: u64, r... | (fs: &mut GoodDataFS, inode: inode::Inode, reply: ReplyData, offset: u64, size: u32) {
debug!("read() - Reading {}",
constants::FEATURE_FLAGS_JSON_FILENAME);
let project: &object::Project = &project_from_inode(fs, inode);
let feature_flags = project.feature_flags(&mut fs.client.connector);
... | read | identifier_name |
feature_flags.rs | use fuse::{FileType, ReplyAttr, ReplyData, ReplyEntry, Request};
use fs::constants;
use fs::GoodDataFS;
use fs::helpers::create_inode_file_attributes;
use fs::item;
use fs::inode;
use helpers;
use object;
use std::path::Path;
use super::project_from_inode;
fn getattr(fs: &mut GoodDataFS, _req: &Request, ino: u64, r... |
fn lookup(fs: &mut GoodDataFS, _req: &Request, parent: u64, _name: &Path, reply: ReplyEntry) {
let inode_parent = inode::Inode::deserialize(parent);
let inode = inode::Inode::create(inode_parent.project,
constants::Category::Internal as u8,
... | {
let project: &object::Project = &project_from_inode(fs, ino);
let feature_flags = project.feature_flags(&mut fs.client.connector);
if feature_flags.is_some() {
let json: String = feature_flags.unwrap().into();
let attr =
create_inode_file_attributes(ino, json.len() as u64, co... | identifier_body |
feature_flags.rs | use fuse::{FileType, ReplyAttr, ReplyData, ReplyEntry, Request};
use fs::constants;
use fs::GoodDataFS;
use fs::helpers::create_inode_file_attributes;
use fs::item;
use fs::inode;
use helpers;
use object;
use std::path::Path;
use super::project_from_inode;
fn getattr(fs: &mut GoodDataFS, _req: &Request, ino: u64, r... |
}
fn read(fs: &mut GoodDataFS, inode: inode::Inode, reply: ReplyData, offset: u64, size: u32) {
debug!("read() - Reading {}",
constants::FEATURE_FLAGS_JSON_FILENAME);
let project: &object::Project = &project_from_inode(fs, inode);
let feature_flags = project.feature_flags(&mut fs.client.conne... | {
let json: String = feature_flags.unwrap().into();
let attr =
create_inode_file_attributes(inode, json.len() as u64, constants::DEFAULT_CREATE_TIME);
reply.entry(&constants::DEFAULT_TTL, &attr, 0);
} | conditional_block |
feature_flags.rs | use fuse::{FileType, ReplyAttr, ReplyData, ReplyEntry, Request};
use fs::constants;
use fs::GoodDataFS;
use fs::helpers::create_inode_file_attributes;
use fs::item;
use fs::inode;
use helpers;
use object;
use std::path::Path;
use super::project_from_inode;
fn getattr(fs: &mut GoodDataFS, _req: &Request, ino: u64, r... | pub const ITEM: item::ProjectItem = item::ProjectItem {
category: constants::Category::Internal as u8,
reserved: constants::ReservedFile::FeatureFlagsJson as u8,
item_type: FileType::RegularFile,
path: constants::FEATURE_FLAGS_JSON_FILENAME,
getattr: getattr,
lookup: lookup,
read: read,
}; | let json: String = feature_flags.unwrap().into();
reply.data(helpers::read_bytes(&json, offset, size));
}
}
| random_line_split |
mod.rs | // Copyright 2015-2017 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 lat... | _ => false,
}
}
/// Returns all algorithm types.
pub fn all_types() -> Vec<Algorithm> {
vec![Algorithm::Archive, Algorithm::EarlyMerge, Algorithm::OverlayRecent, Algorithm::RefCounted]
}
}
impl fmt::Display for Algorithm {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::R... |
/// Returns true if pruning strategy is stable
pub fn is_stable(&self) -> bool {
match *self {
Algorithm::Archive | Algorithm::OverlayRecent => true, | random_line_split |
mod.rs | // Copyright 2015-2017 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 lat... | (&self) -> &'static str {
match *self {
Algorithm::Archive => "archive",
Algorithm::EarlyMerge => "earlymerge",
Algorithm::OverlayRecent => "overlayrecent",
Algorithm::RefCounted => "refcounted",
}
}
/// Returns true if pruning strategy is stable
... | as_internal_name_str | identifier_name |
mod.rs | // Copyright 2015-2017 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 lat... |
#[test]
fn test_journal_algorithm_is_stable() {
assert!(Algorithm::Archive.is_stable());
assert!(Algorithm::OverlayRecent.is_stable());
assert!(!Algorithm::EarlyMerge.is_stable());
assert!(!Algorithm::RefCounted.is_stable());
}
#[test]
fn test_journal_algorithm_def... | {
assert_eq!(Algorithm::Archive.to_string(), "archive".to_owned());
assert_eq!(Algorithm::EarlyMerge.to_string(), "light".to_owned());
assert_eq!(Algorithm::OverlayRecent.to_string(), "fast".to_owned());
assert_eq!(Algorithm::RefCounted.to_string(), "basic".to_owned());
} | identifier_body |
test_support.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as ts from 'typescript';
... |
function createCompilerOptions(overrideOptions: ng.CompilerOptions = {}): ng.CompilerOptions {
return {
basePath,
'experimentalDecorators': true,
'skipLibCheck': true,
'strict': true,
'types': [],
'outDir': path.resolve(basePath, 'built'),
'rootDir': basePath,
'ba... | {
mockDirs.forEach(
(dir) => { Object.keys(dir).forEach((fileName) => { write(fileName, dir[fileName]); }); });
} | identifier_body |
test_support.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as ts from 'typescript';
... | (options: ng.CompilerOptions, diags: ng.Diagnostics) {
const errorDiags = diags.filter(d => d.category !== ts.DiagnosticCategory.Message);
if (errorDiags.length) {
throw new Error(`Expected no diagnostics: ${ng.formatDiagnostics(errorDiags)}`);
}
}
export function expectNoDiagnosticsInProgram(options: ng.Com... | expectNoDiagnostics | identifier_name |
test_support.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as ts from 'typescript';
... | } | ]); | random_line_split |
test_support.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as ts from 'typescript';
... |
}
function shouldNotExist(fileName: string) {
if (fs.existsSync(path.resolve(basePath, fileName))) {
throw new Error(`Did not expect ${fileName} to be emitted (basePath: ${basePath})`);
}
}
}
export function expectNoDiagnostics(options: ng.CompilerOptions, diags: ng.Diagnostics) {
const errorDi... | {
throw new Error(`Expected ${fileName} to be emitted (basePath: ${basePath})`);
} | conditional_block |
test.py | #! /usr/bin/env python
import os
import sys
import shutil
import logging
import argparse
import tempfile
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from webloader.phantomjs_loader import PhantomJSLoader
from webloader.curl_loader import CurlLoader
from webloader.pythonrequests_loader import Python... | (**kwargs):
loader = args.loader.lower()
if 'python' in loader or 'requests' in loader:
return PythonRequestsLoader(full_page=False, **kwargs)
elif 'curl' in loader:
return CurlLoader(full_page=False, **kwargs)
elif 'phantom' in loader or 'js' in loader:
return PhantomJSLoader(**... | get_loader | identifier_name |
test.py | #! /usr/bin/env python
import os
import sys |
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from webloader.phantomjs_loader import PhantomJSLoader
from webloader.curl_loader import CurlLoader
from webloader.pythonrequests_loader import PythonRequestsLoader
from webloader.chrome_loader import ChromeLoader
#from webloader.firefox_loader import Fire... | import shutil
import logging
import argparse
import tempfile | random_line_split |
test.py | #! /usr/bin/env python
import os
import sys
import shutil
import logging
import argparse
import tempfile
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from webloader.phantomjs_loader import PhantomJSLoader
from webloader.curl_loader import CurlLoader
from webloader.pythonrequests_loader import Python... |
def main():
outdir = os.path.join(tempfile.gettempdir(), 'loader-test')
loader = get_loader(outdir=outdir)
loader.load_pages([args.url])
print loader.page_results
print loader.load_results
try:
shutil.rmtree(outdir)
except:
pass
if __name__ == "__main__":
# set u... | loader = args.loader.lower()
if 'python' in loader or 'requests' in loader:
return PythonRequestsLoader(full_page=False, **kwargs)
elif 'curl' in loader:
return CurlLoader(full_page=False, **kwargs)
elif 'phantom' in loader or 'js' in loader:
return PhantomJSLoader(**kwargs)
elif... | identifier_body |
test.py | #! /usr/bin/env python
import os
import sys
import shutil
import logging
import argparse
import tempfile
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from webloader.phantomjs_loader import PhantomJSLoader
from webloader.curl_loader import CurlLoader
from webloader.pythonrequests_loader import Python... | logging.basicConfig(**config)
main()
| parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\
description='Test a loader by requesting a single URL.')
parser.add_argument('url', help='The URL to load.')
parser.add_argument('-l', '--loader', default="python-requests", help='The l... | conditional_block |
index.test.ts | import test from 'ava'
import { stripIndent } from 'common-tags'
import lissie from '../source' | const take = (array: any[], count: number): any[] => array.slice(0, count)
const head = (str: string): string => take(str.split('\n'), 3).join('\n')
test('returns license text', t => {
const expected = stripIndent`
The MIT License (MIT)
Copyright (c) {{year}} {{author}}
`
t.is(head(lissie()), expected)
t.... | random_line_split | |
utils.py | # -*- encoding: utf-8 -*-
__author__ = 'pp'
__date__ = '6/25/14'
"""
georest.view.utils
~~~~~~~~~~~~~~~~~
helper/mixin things for views
"""
import sys
from functools import wraps
from flask import request
from .exceptions import InvalidRequest
from ..geo import GeoException
def get_json_content():
... |
return etag
def catcher(f):
"""catching uncatched errors, and filling the traceback"""
@wraps(f)
def decorator(*args, **kwargs):
try:
return f(*args, **kwargs)
except GeoException as e:
if not e.traceback:
e.traceback = sys.exc_info()[2]
... | try:
etag, = request.if_match.as_set() # only 1 allowed
except ValueError:
raise InvalidRequest('Cannot process if_match %s' % \
request.if_match) | conditional_block |
utils.py | # -*- encoding: utf-8 -*-
__author__ = 'pp'
__date__ = '6/25/14'
"""
georest.view.utils
~~~~~~~~~~~~~~~~~
helper/mixin things for views
"""
import sys
from functools import wraps
from flask import request
from .exceptions import InvalidRequest
from ..geo import GeoException
def get_json_content():
... | (f):
"""catching uncatched errors, and filling the traceback"""
@wraps(f)
def decorator(*args, **kwargs):
try:
return f(*args, **kwargs)
except GeoException as e:
if not e.traceback:
e.traceback = sys.exc_info()[2]
raise
return decorat... | catcher | identifier_name |
utils.py | # -*- encoding: utf-8 -*-
__author__ = 'pp'
__date__ = '6/25/14'
"""
georest.view.utils
~~~~~~~~~~~~~~~~~
helper/mixin things for views
"""
import sys
from functools import wraps
from flask import request
from .exceptions import InvalidRequest
from ..geo import GeoException
def get_json_content():
... |
return decorator
| try:
return f(*args, **kwargs)
except GeoException as e:
if not e.traceback:
e.traceback = sys.exc_info()[2]
raise | identifier_body |
utils.py | # -*- encoding: utf-8 -*-
__author__ = 'pp'
__date__ = '6/25/14'
|
import sys
from functools import wraps
from flask import request
from .exceptions import InvalidRequest
from ..geo import GeoException
def get_json_content():
"""check content type and return raw text instrad of json data"""
if request.mimetype != 'application/json':
raise InvalidRequest('Only "app... | """
georest.view.utils
~~~~~~~~~~~~~~~~~
helper/mixin things for views
""" | random_line_split |
interpolators.py | # Rekall Memory Forensics
# Copyright 2016 Google Inc. All Rights Reserved.
#
# This program 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 2 of the License, or (at
# your option) any later ver... | (self, variable):
return []
class LinuxKnowledgeBase(KnowledgeBase):
@registry.memoize
def _get_users_homedir(self):
homedirs = []
for user in open("/etc/passwd"):
user = user.strip()
homedirs.append(user.split(":")[5])
return homedirs
def expand(... | expand | identifier_name |
interpolators.py | # Rekall Memory Forensics
# Copyright 2016 Google Inc. All Rights Reserved.
#
# This program 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 2 of the License, or (at
# your option) any later ver... | for hit_result in artifact_hit.get("result", []):
profile_path = hit_result.get("value")
if profile_path:
result.append(profile_path)
return result
def expand(self, variable):
if variable == "%%users.sid%%":
return self._g... | @registry.memoize
def _get_sids(self):
result = []
for hit in self.session.plugins.glob(
r"HKEY_USERS\*", filesystem="Reg", root="\\",
path_sep="\\").collect():
path = hit["path"]
m = re.search(
r"(S-(\d+-)+\d+)$", path.filename... | identifier_body |
interpolators.py | # Rekall Memory Forensics
# Copyright 2016 Google Inc. All Rights Reserved.
#
# This program 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 2 of the License, or (at
# your option) any later ver... | @registry.memoize
def _get_sids(self):
result = []
for hit in self.session.plugins.glob(
r"HKEY_USERS\*", filesystem="Reg", root="\\",
path_sep="\\").collect():
path = hit["path"]
m = re.search(
r"(S-(\d+-)+\d+)$", path.file... |
class WindowsKnowledgeBase(KnowledgeBase): | random_line_split |
interpolators.py | # Rekall Memory Forensics
# Copyright 2016 Google Inc. All Rights Reserved.
#
# This program 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 2 of the License, or (at
# your option) any later ver... |
if variable == "%%users.homedir%%":
return self._get_homedirs()
if variable == "%%environ_systemroot%%":
return [os.environ["systemroot"]]
return []
class KnowledgeBaseHook(kb.ParameterHook):
name = "knowledge_base"
def calculate(self):
if platform.... | return self._get_sids() | conditional_block |
rm_elems.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program 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 ... | use task::short::EId;
// TODO: to mod::utils
pub fn remove_element(doc: &mut Document, id: EId) {
doc.drain(|n| n.is_tag_name(id));
}
#[cfg(test)]
mod tests {
use super::*;
use svgdom::{Document, ToStringWithOptions, ElementId};
macro_rules! test {
($name:ident, $id:expr, $in_text:expr, $out_... | use svgdom::Document;
| random_line_split |
rm_elems.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program 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 ... |
#[cfg(test)]
mod tests {
use super::*;
use svgdom::{Document, ToStringWithOptions, ElementId};
macro_rules! test {
($name:ident, $id:expr, $in_text:expr, $out_text:expr) => (
#[test]
fn $name() {
let mut doc = Document::from_str($in_text).unwrap();
... | {
doc.drain(|n| n.is_tag_name(id));
} | identifier_body |
rm_elems.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program 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 ... | (doc: &mut Document, id: EId) {
doc.drain(|n| n.is_tag_name(id));
}
#[cfg(test)]
mod tests {
use super::*;
use svgdom::{Document, ToStringWithOptions, ElementId};
macro_rules! test {
($name:ident, $id:expr, $in_text:expr, $out_text:expr) => (
#[test]
fn $name() {
... | remove_element | identifier_name |
stream_parser.py | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# 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:... | It's designed to be used for data read from a transport which doesn't
preserve message boundaries. A typical example of such a transport
is TCP.
"""
class TooSmallException(Exception):
pass
def __init__(self):
self._q = bytearray()
def parse(self, data):
"""Tries ... | random_line_split | |
stream_parser.py | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# 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:... |
def parse(self, data):
"""Tries to extract messages from a raw byte stream.
The data argument would be python bytes newly read from the input
stream.
Returns an ordered list of extracted messages.
It can be an empty list.
The rest of data which doesn't produce a ... | self._q = bytearray() | identifier_body |
stream_parser.py | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# 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:... | (self, q):
"""Try to extract a message from the given bytes.
This is an override point for subclasses.
This method tries to extract a message from bytes given by the
argument.
Raises TooSmallException if the given data is not enough to
extract a complete message but th... | try_parse | identifier_name |
stream_parser.py | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# 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:... |
return msgs
@abstractmethod
def try_parse(self, q):
"""Try to extract a message from the given bytes.
This is an override point for subclasses.
This method tries to extract a message from bytes given by the
argument.
Raises TooSmallException if the given data... | try:
msg, self._q = self.try_parse(self._q)
except self.TooSmallException:
break
msgs.append(msg) | conditional_block |
gulpfile.js | /**
* Created by Pencroff on 04-Sep-16.
*/
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var dotify = require('gulp-dotify');
var watch = require('gulp-watch');
var transform = require(... | (options) {
gulp.task(options.name, function() {
var stream = gulp.src(options.files)
.pipe(plumber())
.pipe(concat(options.name + '.js'))
.pipe(gulp.dest(options.destination));
if (options.uglify) {
stream.pipe(rename(options.name + '.min.js'))
... | makeTask | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.