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 |
|---|---|---|---|---|
xhr_backend.js | /**
* @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 { Injectable } from '@angular/core';
import { __platform_browser_private__ } from '@angular/platform-browser';... | // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
var status = _xhr.status === 1223 ? 204 : _xhr.status;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
... | var url = getResponseURL(_xhr); | random_line_split |
xhr_backend.js | /**
* @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 { Injectable } from '@angular/core';
import { __platform_browser_private__ } from '@angular/platform-browser';... |
// load event handler
var onLoad = function () {
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in ResourceLoader Level2 spec (supported
// by IE10)
... | {
_xhr.withCredentials = req.withCredentials;
} | conditional_block |
xhr_backend.js | /**
* @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 { Injectable } from '@angular/core';
import { __platform_browser_private__ } from '@angular/platform-browser';... | // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
var status = _xhr.status === 1223 ? 204 : _xhr.status;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
... | {
var _this = this;
this.request = req;
this.response = new Observable(function (responseObserver) {
var _xhr = browserXHR.build();
_xhr.open(RequestMethod[req.method].toUpperCase(), req.url);
if (isPresent(req.withCredentials)) {
_xhr.withCred... | identifier_body |
model.py | pipeline is based upon: https://github.com/tensorflow/tfx/blob/master/tfx/examples.
"""
import functools
import absl
import os
from typing import List, Text
import tensorflow as tf
import tensorflow_model_analysis as tfma
import tensorflow_transform as tft
from tensorflow_transform.tf_metadata import schema_utils
i... | # Defines wide feature columns and input layers.
categorical_columns = [
tf.feature_column.categorical_column_with_identity(
key=features.transformed_name(key),
num_buckets=tf_transform_output.num_buckets_for_transformed_feature(features.transformed_name(key)),
default_value=0)... | """Creates a Keras WideDeep Classifier model.
Args:
hparams: Holds HyperParameters for tuning.
tf_transform_output: A TFTransformOutput.
Returns:
A keras Model.
"""
# Defines deep feature columns and input layers.
deep_columns = [
tf.feature_column.numeric_column(
key=features.tran... | identifier_body |
model.py | pipeline is based upon: https://github.com/tensorflow/tfx/blob/master/tfx/examples.
"""
import functools
import absl
import os
from typing import List, Text
import tensorflow as tf
import tensorflow_model_analysis as tfma
import tensorflow_transform as tft
from tensorflow_transform.tf_metadata import schema_utils
i... |
wide = tf.keras.layers.DenseFeatures(wide_columns)(input_layers)
output = tf.keras.layers.Dense(features.NUM_CLASSES, activation='softmax')(
tf.keras.layers.concatenate([deep, wide]))
model = tf.keras.Model(input_layers, output)
model.compile(
loss='sparse_categorical_crossentropy',
... | deep = tf.keras.layers.Dense(units=hparams.get('n_units_' + str(n + 1)))(deep) | conditional_block |
model.py | this pipeline is based upon: https://github.com/tensorflow/tfx/blob/master/tfx/examples.
"""
import functools
import absl
import os
from typing import List, Text
import tensorflow as tf
import tensorflow_model_analysis as tfma
import tensorflow_transform as tft
from tensorflow_transform.tf_metadata import schema_ut... | from models.keras.constants import (
EPOCHS,
TRAIN_BATCH_SIZE,
EVAL_BATCH_SIZE,
LOCAL_LOG_DIR,
)
def _gzip_reader_fn(filenames):
"""Small utility returning a record reader that can read gzip'ed files."""
return tf.data.TFRecordDataset(filenames, compression_type='GZIP')
def _get_serve_tf_examples_fn(mo... | from tfx.components.trainer.fn_args_utils import DataAccessor
from tfx.components.tuner.component import TunerFnResult
from tfx_bsl.tfxio import dataset_options
from models import features | random_line_split |
model.py | pipeline is based upon: https://github.com/tensorflow/tfx/blob/master/tfx/examples.
"""
import functools
import absl
import os
from typing import List, Text
import tensorflow as tf
import tensorflow_model_analysis as tfma
import tensorflow_transform as tft
from tensorflow_transform.tf_metadata import schema_utils
i... | (hparams: kerastuner.HyperParameters,
tf_transform_output: tft.TFTransformOutput) -> tf.keras.Model:
"""Creates a Keras WideDeep Classifier model.
Args:
hparams: Holds HyperParameters for tuning.
tf_transform_output: A TFTransformOutput.
Returns:
A keras Model.
"""
# Define... | _build_keras_model | identifier_name |
activated-route-stub.ts | /**
* Copyright 2019 Google LLC
*
* 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 | * distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { convertToParamMap, ParamMap, Params } from '@angular/rou... | *
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software | random_line_split |
activated-route-stub.ts | /**
* Copyright 2019 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | (initialParams?: Params, initialFragment?: string) {
this.setParamMap(initialParams);
this.setFragment(initialFragment);
}
/** Set the paramMap observables's next value */
setParamMap(params?: Params) {
this.paramMap$.next(convertToParamMap(params || {}));
}
/** Set the fragment observables's ne... | constructor | identifier_name |
test.js | var Jsonix = require('jsonix').Jsonix;
var ietf_params_xml_ns_lost1 = require('./mapping/ietf_params_xml_ns_lost1');
var net_opengis_gml = require('./mapping/net_opengis_gml'); | var findServiceXml = "<?xml version='1.0' encoding='UTF-8'?><findService xmlns='urn:ietf:params:xml:ns:lost1' xmlns:p2='http://www.opengis.net/gml' serviceBoundary='value' recursive='true'><location id='6020688f1ce1896d' profile='geodetic-2d'><p2:Point id='point1' srsName='urn:ogc:def:crs:EPSG::4326'><p2:pos>37.775 -12... | random_line_split | |
config.ts | /**
* Created by rt3 on 2/15/17.
*/
// import { IPeers, IPeer, IUser, ICredentials } from './config.interfaces';
class SeedConfig {
/**
* Projet name for chaincode project, under ./src
* @type {string}
*/
CC_PROJECT_NAME = 'build-chaincode';
/**
* Hyperledger Network Name |
}
export const seedConfig = new SeedConfig();
// Get config from bluemix or local
const credentials = require('./ServiceCredentials.json');
const adminUser = credentials.users.filter(
(user: any) => user.enrollId === 'WebAppAdmin')[0];
// bluemix config
export const bluemix = {
network: {
peers: credent... | * @type {string}
*/
NETWORK_NAME = 'Example Network'; | random_line_split |
config.ts | /**
* Created by rt3 on 2/15/17.
*/
// import { IPeers, IPeer, IUser, ICredentials } from './config.interfaces';
class | {
/**
* Projet name for chaincode project, under ./src
* @type {string}
*/
CC_PROJECT_NAME = 'build-chaincode';
/**
* Hyperledger Network Name
* @type {string}
*/
NETWORK_NAME = 'Example Network';
}
export const seedConfig = new SeedConfig();
// Get config from bluemix or local
con... | SeedConfig | identifier_name |
test-util.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
*/
/*
* Usage:
*
* function supportsOnClick() {
* const div = document.createElement('div');
* const clickP... | export function supportPatchXHROnProperty() {
let desc = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'onload');
if (!desc && (window as any)['XMLHttpRequestEventTarget']) {
desc = Object.getOwnPropertyDescriptor(global['XMLHttpRequestEventTarget'].prototype, 'onload');
}
if (!desc || !desc.con... | done && done();
}
}
| random_line_split |
test-util.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
*/
/*
* Usage:
*
* function supportsOnClick() {
* const div = document.createElement('div');
* const clickP... |
return null;
}
export function isFirefox() {
const userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf('firefox') != -1) {
return true;
}
return false;
}
export function isSafari() {
const userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf('safari') != -1) {
r... | {
return parseInt(userAgent.split('msie')[1]);
} | conditional_block |
test-util.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
*/
/*
* Usage:
*
* function supportsOnClick() {
* const div = document.createElement('div');
* const clickP... |
function _ifEnvSupports(test: any, block: Function, withDone = false) {
if (withDone) {
return function(done?: Function) {
_runTest(test, block, done);
};
} else {
return function() {
_runTest(test, block, undefined);
};
}
}
function _runTest(test: any, block: Function, done?: Funct... | {
return _ifEnvSupports(test, block, true);
} | identifier_body |
test-util.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
*/
/*
* Usage:
*
* function supportsOnClick() {
* const div = document.createElement('div');
* const clickP... | () {
const userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf('firefox') != -1) {
return true;
}
return false;
}
export function isSafari() {
const userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf('safari') != -1) {
return true;
}
return false;
}
export fu... | isFirefox | identifier_name |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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 ap... | */
declare var reExtendedLengthPath: ReExtendedLengthPath;
// EXPORTS //
export = reExtendedLengthPath; | *
* @example
* var bool = reExtendedLengthPath.REGEXP.test( 'C:\\foo\\bar' );
* // returns false | random_line_split |
add-farm.ts | import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, NavParams, ViewController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { AuthService } from '../../providers/auth-service';
import { AlertController } from 'ionic-angular';
declare var... |
// Accommodates the given latitudes and longitudes to the ones available at
// the Hyroclimate Data Center
accommodateGPS(GPS) {
var latIndex, lonIndex, diff1, diff2;
//Latitude Operation
for (latIndex = 0; GPS.latitude > this.latitudes[latIndex].latcoordinate;latIndex++);
if (GPS.latitude === ... | {
this.geolocation.getCurrentPosition().then((position) => {
var GPS = { latitude: position.coords.latitude,
longitude: position.coords.longitude};
if (this.auth.isDebug()) console.log(GPS);
//GPS = this.accommodateGPS(GPS);
if (this.auth.isDebug()) console.log(GPS);
... | identifier_body |
add-farm.ts | import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, NavParams, ViewController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { AuthService } from '../../providers/auth-service';
import { AlertController } from 'ionic-angular';
declare var... | soilTypes: any = [];
latitudes: any = [];
longitudes: any = [];
latitude: number = 0;
longitude:number = 0;
public farm = {uid: 0, farmname : '', soiltype: '', latindex: 0, lonindex: 0};
// Initializes soils, latitudes and longitudes, and loads map
constructor(public navCtrl: NavController, public navParams: NavP... | @ViewChild('map') mapElement: ElementRef;
map: any;
user: any = []; | random_line_split |
add-farm.ts | import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, NavParams, ViewController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { AuthService } from '../../providers/auth-service';
import { AlertController } from 'ionic-angular';
declare var... | {
@ViewChild('map') mapElement: ElementRef;
map: any;
user: any = [];
soilTypes: any = [];
latitudes: any = [];
longitudes: any = [];
latitude: number = 0;
longitude:number = 0;
public farm = {uid: 0, farmname : '', soiltype: '', latindex: 0, lonindex: 0};
// Initializes soils, latitudes and longitudes, and loads... | AddFarmPage | identifier_name |
ng_probe.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 {APP_INITIALIZER, ApplicationRef, DebugNode, NgProbeToken, NgZone, Optional, Provider, getDebugNode} from '@a... | (element: any): DebugNode|null {
return getDebugNode(element);
}
export function _createNgProbe(coreTokens: NgProbeToken[]): any {
exportNgVar(INSPECT_GLOBAL_NAME, inspectNativeElement);
exportNgVar(CORE_TOKENS_GLOBAL_NAME, {...CORE_TOKENS, ..._ngProbeTokensToMap(coreTokens || [])});
return () => inspectNative... | inspectNativeElement | identifier_name |
ng_probe.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
* | * found in the LICENSE file at https://angular.io/license
*/
import {APP_INITIALIZER, ApplicationRef, DebugNode, NgProbeToken, NgZone, Optional, Provider, getDebugNode} from '@angular/core';
import {exportNgVar} from '../util';
const CORE_TOKENS = (() => ({
'ApplicationRef': ApplicationRef,
... | * Use of this source code is governed by an MIT-style license that can be | random_line_split |
ng_probe.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 {APP_INITIALIZER, ApplicationRef, DebugNode, NgProbeToken, NgZone, Optional, Provider, getDebugNode} from '@a... |
export function _createNgProbe(coreTokens: NgProbeToken[]): any {
exportNgVar(INSPECT_GLOBAL_NAME, inspectNativeElement);
exportNgVar(CORE_TOKENS_GLOBAL_NAME, {...CORE_TOKENS, ..._ngProbeTokensToMap(coreTokens || [])});
return () => inspectNativeElement;
}
function _ngProbeTokensToMap(tokens: NgProbeToken[]): ... | {
return getDebugNode(element);
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#![deny(unsafe_code)]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern ... | mod storage_thread;
pub mod subresource_integrity;
mod websocket_loader;
/// An implementation of the [Fetch specification](https://fetch.spec.whatwg.org/)
pub mod fetch {
pub mod cors_cache;
pub mod methods;
}
/// A module for re-exports of items used in unit tests.
pub mod test {
pub use crate::hosts::{p... | pub mod http_cache;
pub mod http_loader;
pub mod image_cache;
pub mod mime_classifier;
pub mod resource_thread; | random_line_split |
debug.rs | ,
TempId,
};
use internal_types::{
TermWithTempIds,
};
use schema::{
SchemaBuilding,
};
use types::*;
use tx::{
transact,
transact_terms,
};
use watcher::NullWatcher;
/// Represents a *datom* (assertion) in the store.
#[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)]
pub struct Datom {
//... | <S: Borrow<Schema>>(conn: &rusqlite::Connection, schema: &S) -> Result<Datoms> {
datoms_after(conn, schema, bootstrap::TX0 - 1)
}
/// Return the set of datoms in the store with transaction ID strictly greater than the given `tx`,
/// ordered by (e, a, v, tx).
///
/// The datom set returned does not include any dat... | datoms | identifier_name |
debug.rs | ,
TempId,
};
use internal_types::{
TermWithTempIds,
};
use schema::{
SchemaBuilding,
};
use types::*;
use tx::{
transact,
transact_terms,
};
use watcher::NullWatcher;
/// Represents a *datom* (assertion) in the store.
#[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)]
pub struct Datom {
//... |
}
}
/// Convert a numeric entid to an ident `Entid` if possible, otherwise a numeric `Entid`.
pub fn to_entid(schema: &Schema, entid: i64) -> EntidOrIdent {
schema.get_ident(entid).map_or(EntidOrIdent::Entid(entid), |ident| EntidOrIdent::Ident(ident.clone()))
}
// /// Convert a symbolic ident to an ident `En... | {
self
} | conditional_block |
debug.rs | ,
TempId,
};
use internal_types::{
TermWithTempIds,
};
use schema::{
SchemaBuilding,
};
use types::*;
use tx::{
transact,
transact_terms,
};
use watcher::NullWatcher;
/// Represents a *datom* (assertion) in the store.
#[derive(Clone,Debug,Eq,Hash,Ord,PartialOrd,PartialEq)] | pub a: EntidOrIdent,
pub v: edn::Value,
pub tx: i64,
pub added: Option<bool>,
}
/// Represents a set of datoms (assertions) in the store.
///
/// To make comparision easier, we deterministically order. The ordering is the ascending tuple
/// ordering determined by `(e, a, (value_type_tag, v), tx)`, wh... | pub struct Datom {
// TODO: generalize this.
pub e: EntidOrIdent, | random_line_split |
traits.rs | // Copyright (c) 2017 Jason White | // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//... | // | random_line_split |
traits.rs | // Copyright (c) 2017 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, d... |
/// Outputs the task knows about *a priori*. It must calculate these by
/// *only* looking at the task parameters. It cannot do anything fancy like
/// running an external process to determine these.
fn known_outputs(&self, _resources: &mut res::Set) {}
}
| {} | identifier_body |
traits.rs | // Copyright (c) 2017 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, d... | (&self, _resources: &mut res::Set) {}
/// Outputs the task knows about *a priori*. It must calculate these by
/// *only* looking at the task parameters. It cannot do anything fancy like
/// running an external process to determine these.
fn known_outputs(&self, _resources: &mut res::Set) {}
}
| known_inputs | identifier_name |
ms.js | /* flatpickr v4.4.2, @license MIT */ | (factory((global.ms = {})));
}(this, (function (exports) { 'use strict';
var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : {
l10ns: {}
};
var Malaysian = {
weekdays: {
shorthand: ["Min", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab"],
l... | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) : | random_line_split |
SunshineNewPostsList.tsx | import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useMulti } from '../../lib/crud/withMulti';
import React from 'react';
import { userCanDo } from '../../lib/vulcan-users/permissions';
import { useCurrentUser } from '../common/withUser';
const styles = (theme: ThemeType): JssStyles => ({
... | });
const currentUser = useCurrentUser();
const { SunshineListCount, SunshineListTitle, SunshineNewPostsItem } = Components
if (results && results.length && userCanDo(currentUser, "posts.moderate.all")) {
return (
<div className={classes.root}>
<SunshineListTitle>
Unreviewed Posts... | random_line_split | |
lib.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/. */
#![comment = "The Servo Parallel Browser Project"]
#![license = "MPL"]
#![feature(globs, macro_rules)]
#![deny(u... | pub use properties::{CSSFloat, DeclaredValue, PropertyDeclarationParseResult};
pub use properties::{longhands, Angle, AngleOrCorner, AngleAoc, CornerAoc};
pub use properties::{Left, Right, Bottom, Top};
pub use node::{TElement, TElementAttributes, TNode};
pub use selectors::{PseudoElement, Before, After, SelectorList, ... | pub use selector_matching::{matches, matches_simple_selector, common_style_affecting_attributes};
pub use selector_matching::{RECOMMENDED_SELECTOR_BLOOM_FILTER_SIZE,SELECTOR_WHITESPACE};
pub use properties::{cascade, cascade_anonymous, computed};
pub use properties::{PropertyDeclaration, ComputedValues, computed_values... | random_line_split |
memory.rs | extern crate byteorder;
use std::io::Cursor;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
#[derive(Debug)]
pub enum MemoryError {
PPUAccessViolation(String),
APUAccessViolation(String),
}
pub struct Memory {
pub mem: Vec<u8>,
}
impl Memory {
pub fn new() -> Memory {
let mut m = M... | if addr <= 0x3FFF { return Ok( (addr & 0x7FF & 0x08) as usize); }
if addr <= 0x401F { return Err(MemoryError::APUAccessViolation("Memory access is currently not implemented".to_string())); }
Ok(addr as usize)
}
} | if addr <= 0x1FFF { return Ok( (addr & 0x7FF) as usize); }
if addr <= 0x2007 { return Err(MemoryError::PPUAccessViolation("PPU Memory access is currently not implemented".to_string())); } | random_line_split |
memory.rs | extern crate byteorder;
use std::io::Cursor;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
#[derive(Debug)]
pub enum MemoryError {
PPUAccessViolation(String),
APUAccessViolation(String),
}
pub struct | {
pub mem: Vec<u8>,
}
impl Memory {
pub fn new() -> Memory {
let mut m = Memory {
mem: Vec::with_capacity(::std::u16::MAX as usize +1)
};
unsafe { &m.mem.set_len(::std::u16::MAX as usize +1); }
return m;
}
// meant for a 'raw' write interface, not meant t... | Memory | identifier_name |
memory.rs | extern crate byteorder;
use std::io::Cursor;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
#[derive(Debug)]
pub enum MemoryError {
PPUAccessViolation(String),
APUAccessViolation(String),
}
pub struct Memory {
pub mem: Vec<u8>,
}
impl Memory {
pub fn new() -> Memory {
let mut m = M... |
&self.mem[idx..(idx+inp.len())].clone_from_slice(inp);
}
pub fn read8(self:&Memory,addr: u16) -> Result<u8,MemoryError> {
match self.resolve_address(addr) {
Ok(raddr) => Ok(self.mem[raddr]),
Err(err) => Err(err)
}
}
pub fn read16(self:&Memory,addr: u16) ... | {
panic!("memory vec length is {}, input array goes from {} to {}",self.mem.len(),index,inp.len()+idx)
} | conditional_block |
memory.rs | extern crate byteorder;
use std::io::Cursor;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
#[derive(Debug)]
pub enum MemoryError {
PPUAccessViolation(String),
APUAccessViolation(String),
}
pub struct Memory {
pub mem: Vec<u8>,
}
impl Memory {
pub fn new() -> Memory |
// meant for a 'raw' write interface, not meant to be used by the 6502 processor itself, more
// tests and other tools to be able to read blocks of memory quickly and easily
//
pub fn write(self:&mut Memory, index:u16, inp: &[u8]) {
let idx = index as usize;
if inp.len() + idx > self.m... | {
let mut m = Memory {
mem: Vec::with_capacity(::std::u16::MAX as usize +1)
};
unsafe { &m.mem.set_len(::std::u16::MAX as usize +1); }
return m;
} | identifier_body |
test_rl_accel.py | __doc__='''basic tests.'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, printLocation
setOutDir(__name__)
import unittest
def getrc(defns,depth=1):
from sys import getrefcount, _getframe
f = _getframe(depth)
G0 = f.f_globals
L = f.f_locals
if L is not G0:
LL = [L]
... |
G0 = G0.copy()
return ' '.join([str(getrefcount(eval(x,L,G0))-1) for x in defns.split()])
def checkrc(defns,rcv0):
rcv1 = getrc(defns,2)
return ' '.join(["%s %s-->%s" % (x,v,w) for x,v,w in zip(defns.split(),rcv0.split(),rcv1.split()) if v!=w])
class RlAccelTestCase(unittest.TestCase):
def testF... | L = L.copy() | conditional_block |
test_rl_accel.py | __doc__='''basic tests.'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, printLocation
setOutDir(__name__)
import unittest
def getrc(defns,depth=1):
from sys import getrefcount, _getframe
f = _getframe(depth)
G0 = f.f_globals
L = f.f_locals
if L is not G0: | f = f.f_back
G = f.f_globals
L = f.f_locals
if G is not G0 or G is L: break
LL.append(L)
L = {}
LL.reverse()
for l in LL:
L.update(l)
else:
L = L.copy()
G0 = G0.copy()
return ' '.join([str(getrefcount(eva... | LL = [L]
while 1: | random_line_split |
test_rl_accel.py | __doc__='''basic tests.'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, printLocation
setOutDir(__name__)
import unittest
def getrc(defns,depth=1):
from sys import getrefcount, _getframe
f = _getframe(depth)
G0 = f.f_globals
L = f.f_locals
if L is not G0:
LL = [L]
... | (self):
from _rl_accel import _AsciiBase85Decode
assert _AsciiBase85Decode('6ul^K@;[2RDIdd%@f~>')=='Dragan Andric'
def testEscapePDF(self):
from _rl_accel import escapePDF
assert escapePDF('(test)')=='\\(test\\)'
def test_instanceEscapePDF(self):
from _rl_accel import _... | test_AsciiBase85Decode | identifier_name |
test_rl_accel.py | __doc__='''basic tests.'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, printLocation
setOutDir(__name__)
import unittest
def getrc(defns,depth=1):
|
def checkrc(defns,rcv0):
rcv1 = getrc(defns,2)
return ' '.join(["%s %s-->%s" % (x,v,w) for x,v,w in zip(defns.split(),rcv0.split(),rcv1.split()) if v!=w])
class RlAccelTestCase(unittest.TestCase):
def testFpStr(self):
# should give siz decimal places if less than 1.
# if more, give up to... | from sys import getrefcount, _getframe
f = _getframe(depth)
G0 = f.f_globals
L = f.f_locals
if L is not G0:
LL = [L]
while 1:
f = f.f_back
G = f.f_globals
L = f.f_locals
if G is not G0 or G is L: break
LL.append(L)
L = {... | identifier_body |
models.py | from django.db import models
from machina.models.fields import ExtendedImageField, MarkupTextField
RESIZED_IMAGE_WIDTH = 100
RESIZED_IMAGE_HEIGHT = 100
VALIDATED_IMAGE_MIN_WIDTH = 100
VALIDATED_IMAGE_MAX_WIDTH = 120
VALIDATED_IMAGE_MIN_HEIGHT = 100
VALIDATED_IMAGE_MAX_HEIGHT = 120
VALIDATED_IMAGE_MAX_SIZE = 12000
... | validated_image = ExtendedImageField(
upload_to='machina/test_images', min_width=VALIDATED_IMAGE_MIN_WIDTH,
max_width=VALIDATED_IMAGE_MAX_WIDTH, min_height=VALIDATED_IMAGE_MIN_HEIGHT,
max_height=VALIDATED_IMAGE_MAX_HEIGHT, max_upload_size=VALIDATED_IMAGE_MAX_SIZE, null=True,
blank=Tr... | """
content = MarkupTextField(null=True, blank=True)
resized_image = ExtendedImageField(
upload_to='machina/test_images', width=RESIZED_IMAGE_WIDTH, height=RESIZED_IMAGE_HEIGHT,
null=True, blank=True) | random_line_split |
models.py | from django.db import models
from machina.models.fields import ExtendedImageField, MarkupTextField
RESIZED_IMAGE_WIDTH = 100
RESIZED_IMAGE_HEIGHT = 100
VALIDATED_IMAGE_MIN_WIDTH = 100
VALIDATED_IMAGE_MAX_WIDTH = 120
VALIDATED_IMAGE_MIN_HEIGHT = 100
VALIDATED_IMAGE_MAX_HEIGHT = 120
VALIDATED_IMAGE_MAX_SIZE = 12000
... | (models.Model):
"""
This model will be used for testing purposes only.
"""
content = MarkupTextField(null=True, blank=True)
resized_image = ExtendedImageField(
upload_to='machina/test_images', width=RESIZED_IMAGE_WIDTH, height=RESIZED_IMAGE_HEIGHT,
null=True, blank=True)
validate... | DummyModel | identifier_name |
models.py | from django.db import models
from machina.models.fields import ExtendedImageField, MarkupTextField
RESIZED_IMAGE_WIDTH = 100
RESIZED_IMAGE_HEIGHT = 100
VALIDATED_IMAGE_MIN_WIDTH = 100
VALIDATED_IMAGE_MAX_WIDTH = 120
VALIDATED_IMAGE_MIN_HEIGHT = 100
VALIDATED_IMAGE_MAX_HEIGHT = 120
VALIDATED_IMAGE_MAX_SIZE = 12000
... | """
This model will be used for testing purposes only.
"""
content = MarkupTextField(null=True, blank=True)
resized_image = ExtendedImageField(
upload_to='machina/test_images', width=RESIZED_IMAGE_WIDTH, height=RESIZED_IMAGE_HEIGHT,
null=True, blank=True)
validated_image = ExtendedIm... | identifier_body | |
retrieve_stats.py | import sys, csv, string
def generate_R_input(report_path, output_path):
| output_file.write(str(confid) + '\n')
first_val = False
output_file.close()
if __name__ =="__main__":
_report_path = sys.argv[1]
_output_path = sys.argv[2]
generate_R_input(_report_path, _output_path)
| confidence_values = []
report_file = open(report_path, 'r')
first_line = True
for line in report_file:
if first_line:
first_line = False
continue
line = line.strip().split(',')
if line[5] == 'Yes':
confidence_values.append(line[6])
elif line[5] == 'No':
confid =... | identifier_body |
retrieve_stats.py | import sys, csv, string
def | (report_path, output_path):
confidence_values = []
report_file = open(report_path, 'r')
first_line = True
for line in report_file:
if first_line:
first_line = False
continue
line = line.strip().split(',')
if line[5] == 'Yes':
confidence_values.append(line[6])
eli... | generate_R_input | identifier_name |
retrieve_stats.py | import sys, csv, string
def generate_R_input(report_path, output_path):
confidence_values = []
report_file = open(report_path, 'r')
first_line = True
for line in report_file:
if first_line:
first_line = False
continue
line = line.strip().split(',')
if line[5] == 'Yes'... | _report_path = sys.argv[1]
_output_path = sys.argv[2]
generate_R_input(_report_path, _output_path) | conditional_block | |
retrieve_stats.py | import sys, csv, string
def generate_R_input(report_path, output_path):
confidence_values = []
report_file = open(report_path, 'r')
first_line = True
for line in report_file:
if first_line:
first_line = False
continue
line = line.strip().split(',')
if line[5] == 'Yes'... | first_val = False
output_file.close()
if __name__ =="__main__":
_report_path = sys.argv[1]
_output_path = sys.argv[2]
generate_R_input(_report_path, _output_path) | random_line_split | |
sharedStrings.js | var Code = require('code');
var Lab = require('lab');
var partial = require('lodash.partial');
var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var before = lab.before;
var after = lab.after;
var expect = Code.expect;
var bdd = {it: it, expect: expect};
var utilities = require('../... |
describe('SharedStrings', function () {
var sharedStrings = new SharedStrings();
var readOnlyTest = partial(utilities.readOnlyTest, bdd, sharedStrings);
var constantTest = partial(utilities.constantTest, bdd, sharedStrings);
var writeOnceTest = partial(utilities.writeOnceTest, bdd, sharedStrings);
... | {
it('has a read-only property: ' + name, function (done) {
if (test) test();
expect(function () { obj[name] = 'foo'; }).to.throw(Error, new RegExp("Cannot set " + name + " directly\."));
done()
});
} | identifier_body |
sharedStrings.js | var Code = require('code');
var Lab = require('lab');
var partial = require('lodash.partial');
var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var before = lab.before;
var after = lab.after;
var expect = Code.expect;
var bdd = {it: it, expect: expect};
var utilities = require('../... | (obj, name, test) {
it('has a read-only property: ' + name, function (done) {
if (test) test();
expect(function () { obj[name] = 'foo'; }).to.throw(Error, new RegExp("Cannot set " + name + " directly\."));
done()
});
}
describe('SharedStrings', function () {
var sharedStrings = new ... | readOnlyTest | identifier_name |
sharedStrings.js | var Code = require('code');
var Lab = require('lab');
var partial = require('lodash.partial');
var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var before = lab.before;
var after = lab.after;
var expect = Code.expect;
var bdd = {it: it, expect: expect};
var utilities = require('../... |
function readOnlyTest(obj, name, test) {
it('has a read-only property: ' + name, function (done) {
if (test) test();
expect(function () { obj[name] = 'foo'; }).to.throw(Error, new RegExp("Cannot set " + name + " directly\."));
done()
});
}
describe('SharedStrings', function () {
va... | var SharedStrings = require('../lib/parts/sharedStrings');
var Rels = require('../lib/parts/rels'); | random_line_split |
scrutinizer-base.js | import { BaseJsonService, NotFound, InvalidResponse } from '../index.js'
export default class ScrutinizerBase extends BaseJsonService {
// https://scrutinizer-ci.com/docs/api/#repository-details
async | ({ schema, vcs, slug }) {
return this._requestJson({
schema,
url: `https://scrutinizer-ci.com/api/repositories/${vcs}/${slug}`,
errorMessages: {
401: 'not authorized to access project',
404: 'project not found',
},
})
}
transformBranchInfo({ json, wantedBranch }) {
... | fetch | identifier_name |
scrutinizer-base.js | import { BaseJsonService, NotFound, InvalidResponse } from '../index.js'
export default class ScrutinizerBase extends BaseJsonService {
// https://scrutinizer-ci.com/docs/api/#repository-details
async fetch({ schema, vcs, slug }) {
return this._requestJson({
schema,
url: `https://scrutinizer-ci.com... |
return branchInfo
}
transformBranchInfoMetricValue({ json, branch, metric }) {
const branchInfo = this.transformBranchInfo({ json, wantedBranch: branch })
if (!branchInfo.index) {
throw new InvalidResponse({ prettyMessage: 'metrics missing for branch' })
}
const {
index: {
... | {
throw new NotFound({ prettyMessage: noBranchInfoMessage })
} | conditional_block |
scrutinizer-base.js | import { BaseJsonService, NotFound, InvalidResponse } from '../index.js'
export default class ScrutinizerBase extends BaseJsonService {
// https://scrutinizer-ci.com/docs/api/#repository-details
async fetch({ schema, vcs, slug }) {
return this._requestJson({
schema,
url: `https://scrutinizer-ci.com... | throw new InvalidResponse({ prettyMessage: 'metrics missing for branch' })
}
const {
index: {
_embedded: {
project: { metric_values: metricValues },
},
},
} = branchInfo
return { value: metricValues[metric] }
}
} | random_line_split | |
scrutinizer-base.js | import { BaseJsonService, NotFound, InvalidResponse } from '../index.js'
export default class ScrutinizerBase extends BaseJsonService {
// https://scrutinizer-ci.com/docs/api/#repository-details
async fetch({ schema, vcs, slug }) {
return this._requestJson({
schema,
url: `https://scrutinizer-ci.com... |
}
| {
const branchInfo = this.transformBranchInfo({ json, wantedBranch: branch })
if (!branchInfo.index) {
throw new InvalidResponse({ prettyMessage: 'metrics missing for branch' })
}
const {
index: {
_embedded: {
project: { metric_values: metricValues },
},
},
... | identifier_body |
test_pool_upgrade_no_loop_reinstall.py | from copy import deepcopy
import pytest
from sovrin_node.test import waits
from stp_core.loop.eventually import eventually
from plenum.common.constants import VERSION
from sovrin_common.constants import REINSTALL
from sovrin_node.test.upgrade.helper import bumpedVersion, checkUpgradeScheduled, \
ensureUpgradeSen... | trustee,
trusteeWallet,
monkeypatch):
new_version = bumpedVersion()
upgr1 = deepcopy(validUpgrade)
upgr1[VERSION] = new_version
upgr1[REINSTALL] = True
# An upgrade scheduled, it should pass
ensureUpgradeSent(looper, trustee, trusteeWallet, upgr1)
looper.run(
... | looper,
tconf,
nodeSet,
validUpgrade, | random_line_split |
test_pool_upgrade_no_loop_reinstall.py | from copy import deepcopy
import pytest
from sovrin_node.test import waits
from stp_core.loop.eventually import eventually
from plenum.common.constants import VERSION
from sovrin_common.constants import REINSTALL
from sovrin_node.test.upgrade.helper import bumpedVersion, checkUpgradeScheduled, \
ensureUpgradeSen... | new_version = bumpedVersion()
upgr1 = deepcopy(validUpgrade)
upgr1[VERSION] = new_version
upgr1[REINSTALL] = True
# An upgrade scheduled, it should pass
ensureUpgradeSent(looper, trustee, trusteeWallet, upgr1)
looper.run(
eventually(
checkUpgradeScheduled,
nodeSe... | identifier_body | |
test_pool_upgrade_no_loop_reinstall.py | from copy import deepcopy
import pytest
from sovrin_node.test import waits
from stp_core.loop.eventually import eventually
from plenum.common.constants import VERSION
from sovrin_common.constants import REINSTALL
from sovrin_node.test.upgrade.helper import bumpedVersion, checkUpgradeScheduled, \
ensureUpgradeSen... | (
looper,
tconf,
nodeSet,
validUpgrade,
trustee,
trusteeWallet,
monkeypatch):
new_version = bumpedVersion()
upgr1 = deepcopy(validUpgrade)
upgr1[VERSION] = new_version
upgr1[REINSTALL] = True
# An upgrade scheduled, it should pass
ensureUp... | test_upgrade_does_not_get_into_loop_if_reinstall | identifier_name |
newlines.py | from SCons.Script import *
def exists(env):
return (env["PLATFORM"]=="win32")
def ConvertNewlines(target,source,env):
for t,s in zip(target,source):
f_in=open(str(s),"rb")
f_out=open(str(t),"wb")
f_out.write(f_in.read().replace("\n","\r\n"))
f_out.close()
f_in.close()
... | env["BUILDERS"]["ConvertNewlinesB"]=Builder(action=ConvertNewlinesB,suffix=".txt") | random_line_split | |
newlines.py | from SCons.Script import *
def exists(env):
return (env["PLATFORM"]=="win32")
def ConvertNewlines(target,source,env):
|
def ConvertNewlinesB(target,source,env):
for t,s in zip(target,source):
f_in=open(str(s),"rb")
f_out=open(str(t),"wb")
f_out.write("\xef\xbb\xbf")
f_out.write(f_in.read().replace("\n","\r\n"))
f_out.close()
f_in.close()
return None
def generate(env):
env["B... | for t,s in zip(target,source):
f_in=open(str(s),"rb")
f_out=open(str(t),"wb")
f_out.write(f_in.read().replace("\n","\r\n"))
f_out.close()
f_in.close()
return None | identifier_body |
newlines.py | from SCons.Script import *
def exists(env):
return (env["PLATFORM"]=="win32")
def ConvertNewlines(target,source,env):
for t,s in zip(target,source):
f_in=open(str(s),"rb")
f_out=open(str(t),"wb")
f_out.write(f_in.read().replace("\n","\r\n"))
f_out.close()
f_in.close()
... |
return None
def generate(env):
env["BUILDERS"]["ConvertNewlines"]=Builder(action=ConvertNewlines,suffix=".txt")
env["BUILDERS"]["ConvertNewlinesB"]=Builder(action=ConvertNewlinesB,suffix=".txt")
| f_in=open(str(s),"rb")
f_out=open(str(t),"wb")
f_out.write("\xef\xbb\xbf")
f_out.write(f_in.read().replace("\n","\r\n"))
f_out.close()
f_in.close() | conditional_block |
newlines.py | from SCons.Script import *
def | (env):
return (env["PLATFORM"]=="win32")
def ConvertNewlines(target,source,env):
for t,s in zip(target,source):
f_in=open(str(s),"rb")
f_out=open(str(t),"wb")
f_out.write(f_in.read().replace("\n","\r\n"))
f_out.close()
f_in.close()
return None
def ConvertNewlinesB(t... | exists | identifier_name |
index.js | import React from "react";
import { observer } from "mobx-react";
import AutoMeter from "components/StatusBar/AutoMeter";
import Notification from "components/StatusBar/Notification";
import TrafficLightIndicator from "components/StatusBar/TrafficLightIndicator";
import DrivingMode from "components/StatusBar/DrivingMo... | </div>
</div>
);
}
}
| {
const { meters, trafficSignal, showNotification,
showPlanningRSSInfo, monitor } = this.props;
return (
<div className="status-bar">
{showNotification &&
<Notification monitor={monitor}
showPlanningRSSInfo={showPla... | identifier_body |
index.js | import React from "react";
import { observer } from "mobx-react";
import AutoMeter from "components/StatusBar/AutoMeter";
import Notification from "components/StatusBar/Notification";
import TrafficLightIndicator from "components/StatusBar/TrafficLightIndicator";
import DrivingMode from "components/StatusBar/DrivingMo... | </div>
);
}
} | <TrafficLightIndicator colorName={trafficSignal.color} />
<DrivingMode drivingMode={meters.drivingMode}
isAutoMode={meters.isAutoMode} />
</div> | random_line_split |
index.js | import React from "react";
import { observer } from "mobx-react";
import AutoMeter from "components/StatusBar/AutoMeter";
import Notification from "components/StatusBar/Notification";
import TrafficLightIndicator from "components/StatusBar/TrafficLightIndicator";
import DrivingMode from "components/StatusBar/DrivingMo... | () {
const { meters, trafficSignal, showNotification,
showPlanningRSSInfo, monitor } = this.props;
return (
<div className="status-bar">
{showNotification &&
<Notification monitor={monitor}
showPlanningRSSInfo={show... | render | identifier_name |
ml_mlp.py | from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD, Adam, RMSprop
from keras.utils import np_utils
from elephas.ml... | model.add(Dense(784, 128))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(128, 128))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(128, 10))
model.add(Activation('softmax'))
# Compile model
rms = RMSprop()
model.compile(loss='categorical_crossentropy', optimizer=rms)
# C... | Y_test = np_utils.to_categorical(y_test, nb_classes)
model = Sequential() | random_line_split |
margin.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import ALL_SIDES, maybe_moz_logical_alias %>
<%... | allowed_in_page_rule=True,
servo_restyle_damage="reflow"
)}
% endfor | logical=side[1],
spec=spec,
flags="APPLIES_TO_FIRST_LETTER GETCS_NEEDS_LAYOUT_FLUSH", | random_line_split |
types.rs | //! Representation of an email address
use idna::domain_to_ascii;
use once_cell::sync::Lazy;
use regex::Regex;
use std::{
convert::{TryFrom, TryInto},
error::Error,
ffi::OsStr,
fmt::{Display, Formatter, Result as FmtResult},
net::IpAddr,
str::FromStr,
};
/// Represents an email address with a ... | (user: &str) -> Result<(), AddressError> {
if USER_RE.is_match(user) {
Ok(())
} else {
Err(AddressError::InvalidUser)
}
}
pub(super) fn check_domain(domain: &str) -> Result<(), AddressError> {
Address::check_domain_ascii(domain).or_else(|_| {
... | check_user | identifier_name |
types.rs | //! Representation of an email address
use idna::domain_to_ascii;
use once_cell::sync::Lazy;
use regex::Regex;
use std::{
convert::{TryFrom, TryInto},
error::Error,
ffi::OsStr,
fmt::{Display, Formatter, Result as FmtResult},
net::IpAddr,
str::FromStr,
};
/// Represents an email address with a ... |
if let Some(caps) = LITERAL_RE.captures(domain) {
if let Some(cap) = caps.get(1) {
if cap.as_str().parse::<IpAddr>().is_ok() {
return Ok(());
}
}
}
Err(AddressError::InvalidDomain)
}
#[cfg(feature = "smtp-tra... | {
return Ok(());
} | conditional_block |
types.rs | //! Representation of an email address
use idna::domain_to_ascii;
use once_cell::sync::Lazy;
use regex::Regex;
use std::{
convert::{TryFrom, TryInto},
error::Error,
ffi::OsStr,
fmt::{Display, Formatter, Result as FmtResult},
net::IpAddr,
str::FromStr,
};
/// Represents an email address with a ... | Address::check_domain(domain)?;
Ok(user.len())
}
#[derive(Debug, PartialEq, Clone, Copy)]
/// Errors in email addresses parsing
pub enum AddressError {
/// Missing domain or user
MissingParts,
/// Unbalanced angle bracket
Unbalanced,
/// Invalid email user
InvalidUser,
/// Invalid e... |
Address::check_user(user)?; | random_line_split |
types.rs | //! Representation of an email address
use idna::domain_to_ascii;
use once_cell::sync::Lazy;
use regex::Regex;
use std::{
convert::{TryFrom, TryInto},
error::Error,
ffi::OsStr,
fmt::{Display, Formatter, Result as FmtResult},
net::IpAddr,
str::FromStr,
};
/// Represents an email address with a ... |
}
impl<U, D> TryFrom<(U, D)> for Address
where
U: AsRef<str>,
D: AsRef<str>,
{
type Error = AddressError;
fn try_from((user, domain): (U, D)) -> Result<Self, Self::Error> {
let user = user.as_ref();
Address::check_user(user)?;
let domain = domain.as_ref();
Address::ch... | {
let at_start = check_address(val)?;
Ok(Address {
serialized: val.into(),
at_start,
})
} | identifier_body |
step6.py | import json
f = open('text-stripped-3.json')
out = open('text-lines.json', 'w')
start_obj = json.load(f)
end_obj = {'data': []}
characters_on_stage = []
currently_speaking = None
last_scene = '1.1'
for i in range(len(start_obj['data'])):
obj = start_obj['data'][i]
if obj['type'] == 'entrance':
if obj['characte... | characters_on_stage = []
elif obj['type'] == 'exit':
characters_on_stage = [char for char in characters_on_stage if char not in obj['characters']]
elif obj['type'] == 'speaker tag':
if obj['speaker'] not in characters_on_stage:
raise Exception('Character tried to speak when not on stage at object ' + str(i)... | random_line_split | |
step6.py | import json
f = open('text-stripped-3.json')
out = open('text-lines.json', 'w')
start_obj = json.load(f)
end_obj = {'data': []}
characters_on_stage = []
currently_speaking = None
last_scene = '1.1'
for i in range(len(start_obj['data'])):
obj = start_obj['data'][i]
if obj['type'] == 'entrance':
if obj['characte... |
elif obj['type'] == 'line':
if currently_speaking == None:
raise Exception('A line did not have an associated speaker at object ' + str(i))
identifier_info = obj['identifier'].split('.')
scene = identifier_info[0] + '.' + identifier_info[1]
#if scene != last_scene:
# if len(characters_on_stage) != 0:
... | if obj['speaker'] not in characters_on_stage:
raise Exception('Character tried to speak when not on stage at object ' + str(i), start_obj['data'][i + 1])
currently_speaking = obj['speaker'] | conditional_block |
example.js | /**
* Example
* @version 0.0.1
*/
var MetaReponse = require('./MetaResponse');
var MetaData = require('./MetaData'); |
data1.setId(3);
data1.setType('recipe');
data1.addAttribute('title', 'Risotto al funghi');
data1.addAttribute('time', '45mins');
data1.addLink('self', 'http://www.monsite.com/recipe/3');
data1.addLink('next', 'http://www.monsite.com/recipe/4');
data1.addLink('prev', 'http://www.monsite.com/recipe/2');
mr.addLink('sel... | var MetaError = require('./MetaError');
var data1 = new MetaData();
var mr = new MetaReponse(); | random_line_split |
id-or-object.ts | export type ID = string | number;
/**
* Marks a parameter that accepts either the object's ID or the object itself.
*/
export type IdOrObject<T extends { id: ID }> = Pick<T, 'id'> | T['id'] | ID;
/**
* Converts an object to its ID, or if an ID was passed instead, returns that ID.
* Always returns a string.
*/
exp... | <T extends { id: ID }>(idOrObject: T | ID): string {
if (typeof idOrObject === 'string' || typeof idOrObject === 'number') {
return `${idOrObject}`;
}
if (idOrObject.id === null || idOrObject.id === undefined) {
throw new Error('ID cannot be extracted from parameter');
}
return `${idOrObject.id}`;
}
... | extractId | identifier_name |
id-or-object.ts | export type ID = string | number;
/**
* Marks a parameter that accepts either the object's ID or the object itself.
*/
export type IdOrObject<T extends { id: ID }> = Pick<T, 'id'> | T['id'] | ID;
/**
* Converts an object to its ID, or if an ID was passed instead, returns that ID.
* Always returns a string.
*/
exp... | }
if (idOrObject.id === null || idOrObject.id === undefined) {
throw new Error('ID cannot be extracted from parameter');
}
return `${idOrObject.id}`;
}
/**
* Converts an object to its ID, or if an ID was passed instead, returns that ID.
* Always returns a number.
*/
export function extractIdToNumber<T e... | return `${idOrObject}`; | random_line_split |
id-or-object.ts | export type ID = string | number;
/**
* Marks a parameter that accepts either the object's ID or the object itself.
*/
export type IdOrObject<T extends { id: ID }> = Pick<T, 'id'> | T['id'] | ID;
/**
* Converts an object to its ID, or if an ID was passed instead, returns that ID.
* Always returns a string.
*/
exp... | {
if (typeof idOrObject === 'number') {
return idOrObject;
}
if (typeof idOrObject === 'string') {
return parseInt(idOrObject, 10);
}
return extractIdToNumber(idOrObject.id);
} | identifier_body | |
id-or-object.ts | export type ID = string | number;
/**
* Marks a parameter that accepts either the object's ID or the object itself.
*/
export type IdOrObject<T extends { id: ID }> = Pick<T, 'id'> | T['id'] | ID;
/**
* Converts an object to its ID, or if an ID was passed instead, returns that ID.
* Always returns a string.
*/
exp... |
return `${idOrObject.id}`;
}
/**
* Converts an object to its ID, or if an ID was passed instead, returns that ID.
* Always returns a number.
*/
export function extractIdToNumber<T extends { id: ID }>(
idOrObject: T | ID,
): number {
if (typeof idOrObject === 'number') {
return idOrObject;
}
if (typeo... | {
throw new Error('ID cannot be extracted from parameter');
} | conditional_block |
image_cache_thread.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/. */
use image::base::ImageMetadata;
use ipc_channel::ipc::{self, IpcSender};
use msg::constellation_msg::Image;
use st... | {
No,
Yes,
}
/// The client side of the image cache thread. This can be safely cloned
/// and passed to different threads.
#[derive(Clone, Deserialize, Serialize)]
pub struct ImageCacheThread {
chan: IpcSender<ImageCacheCommand>,
}
/// The public API for the image cache thread.
impl ImageCacheThread {
... | UsePlaceholder | identifier_name |
image_cache_thread.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/. */
use image::base::ImageMetadata;
use ipc_channel::ipc::{self, IpcSender};
use msg::constellation_msg::Image;
use st... | /// TODO(gw): Profile this on some real world sites and see
/// if it's worth caching the results of this locally in each
/// layout / paint thread.
GetImageIfAvailable(Url, UsePlaceholder, IpcSender<Result<Arc<Image>, ImageState>>),
/// Synchronously check the state of an image in the cache. If th... | /// loaded. Supply a channel to receive the results, and optionally an image responder
/// that is passed to the result channel.
RequestImageAndMetadata(Url, ImageCacheChan, Option<ImageResponder>),
/// Synchronously check the state of an image in the cache. | random_line_split |
traversal.js | /**
* Copyright 2015 The Incremental DOM Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless ... |
/**
* Enters an Element, setting the current namespace for nested elements.
* @param {Node} node
*/
var enterNode = function(node) {
var data = getData(node);
enterTag(data.nodeName);
};
/**
* Exits an Element, unwinding the current namespace to the previous value.
* @param {Node} node
*/
var exitNode = f... |
// For https://github.com/esperantojs/esperanto/issues/187
var dummy; | random_line_split |
addBorder_BACKUP_4896.py | #!/usr/bin/env/python
# -*-coding : utf-8 -*-
<<<<<<< HEAD
'''
Given a rectangular matrix of characters, add a border of asterisks(*) to it.
For
picture = ["abc",
"ded"]
the output should be | addBorder(picture) = ["*****",
"*abc*",
"*ded*",
"*****"]
'''
=======
"""
Given a rectangular matrix of characters, add a border of asterisks(*) to it.
"""
>>>>>>> 21f9d6ac126a25331fed7b68271620f143e23a1d
def addBorder(picture):
picture = [''... | random_line_split | |
addBorder_BACKUP_4896.py | #!/usr/bin/env/python
# -*-coding : utf-8 -*-
<<<<<<< HEAD
'''
Given a rectangular matrix of characters, add a border of asterisks(*) to it.
For
picture = ["abc",
"ded"]
the output should be
addBorder(picture) = ["*****",
"*abc*",
"*ded*",
"**... |
if __name__ == '__main__':
picture = ["a"]
print addBorder(picture)
<<<<<<< HEAD
=======
>>>>>>> 21f9d6ac126a25331fed7b68271620f143e23a1d
| picture = [''.join(('*',i,'*')) for i in picture]
for item in picture:
border = '*'*len(item)
indx = [0,(len(picture)+1)]
for item in indx:
picture.insert(item,border)
return picture | identifier_body |
addBorder_BACKUP_4896.py | #!/usr/bin/env/python
# -*-coding : utf-8 -*-
<<<<<<< HEAD
'''
Given a rectangular matrix of characters, add a border of asterisks(*) to it.
For
picture = ["abc",
"ded"]
the output should be
addBorder(picture) = ["*****",
"*abc*",
"*ded*",
"**... | (picture):
picture = [''.join(('*',i,'*')) for i in picture]
for item in picture:
border = '*'*len(item)
indx = [0,(len(picture)+1)]
for item in indx:
picture.insert(item,border)
return picture
if __name__ == '__main__':
picture = ["a"]
print addBorder(picture)
<<<<<<<... | addBorder | identifier_name |
addBorder_BACKUP_4896.py | #!/usr/bin/env/python
# -*-coding : utf-8 -*-
<<<<<<< HEAD
'''
Given a rectangular matrix of characters, add a border of asterisks(*) to it.
For
picture = ["abc",
"ded"]
the output should be
addBorder(picture) = ["*****",
"*abc*",
"*ded*",
"**... |
indx = [0,(len(picture)+1)]
for item in indx:
picture.insert(item,border)
return picture
if __name__ == '__main__':
picture = ["a"]
print addBorder(picture)
<<<<<<< HEAD
=======
>>>>>>> 21f9d6ac126a25331fed7b68271620f143e23a1d
| border = '*'*len(item) | conditional_block |
provider_command.py | # 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 may not u... | if args.full:
provider_info["description"] = _remove_rst_syntax(provider_info["description"])
AirflowConsole().print_as(
data=[provider_info],
output=args.output,
)
else:
print(f"Provider: {args.provider_name}")
... | random_line_split | |
provider_command.py | # 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 may not u... |
@suppress_logs_and_warning
def provider_get(args):
"""Get a provider info."""
providers = ProvidersManager().providers
if args.provider_name in providers:
provider_version = providers[args.provider_name].version
provider_info = providers[args.provider_name].provider_info
if args.f... | return re.sub("[`_<>]", "", value.strip(" \n.")) | identifier_body |
provider_command.py | # 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 may not u... | (args):
"""Lists all custom connection form fields at the command line"""
AirflowConsole().print_as(
data=list(ProvidersManager().connection_form_widgets.items()),
output=args.output,
mapper=lambda x: {
"connection_parameter_name": x[0],
"class": x[1].connection_c... | connection_form_widget_list | identifier_name |
provider_command.py | # 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 may not u... |
@suppress_logs_and_warning
def providers_list(args):
"""Lists all providers at the command line"""
AirflowConsole().print_as(
data=list(ProvidersManager().providers.values()),
output=args.output,
mapper=lambda x: {
"package_name": x[1]["package-name"],
"descrip... | raise SystemExit(f"No such provider installed: {args.provider_name}") | conditional_block |
setup.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# SoundConverter - GNOME application for converting between audio formats.
# Copyright 2004 Lars Wirzenius
# Copyright 2005-2020 Gautier Portet
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as ... | # - Copy the rest to /usr/share/soundconverter, like the .glade file
# Thanks to DistUtilsExtra (https://salsa.debian.org/python-team/modules/python-distutils-extra/-/tree/master/doc) # noqa
class Install(DistUtilsExtra.auto.install_auto):
def run(self):
DistUtilsExtra.auto.install_auto.run(self)
... | random_line_split | |
setup.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# SoundConverter - GNOME application for converting between audio formats.
# Copyright 2004 Lars Wirzenius
# Copyright 2005-2020 Gautier Portet
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as ... | (DistUtilsExtra.auto.install_auto):
def run(self):
DistUtilsExtra.auto.install_auto.run(self)
# after DistUtilsExtra automatically copied data/org.soundconverter.gschema.xml
# to /usr/share/glib-2.0/schemas/ it doesn't seem to compile them.
glib_schema_path = os.path.join(self.instal... | Install | identifier_name |
setup.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# SoundConverter - GNOME application for converting between audio formats.
# Copyright 2004 Lars Wirzenius
# Copyright 2005-2020 Gautier Portet
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as ... |
DistUtilsExtra.auto.setup(
name='soundconverter',
version='4.0.2',
description=(
'A simple sound converter application for the GNOME environment. '
'It writes WAV, FLAC, MP3, and Ogg Vorbis files.'
),
license='GPL-3.0',
data_files=[
('share/metainfo/', ['data/soundconv... | DistUtilsExtra.auto.install_auto.run(self)
# after DistUtilsExtra automatically copied data/org.soundconverter.gschema.xml
# to /usr/share/glib-2.0/schemas/ it doesn't seem to compile them.
glib_schema_path = os.path.join(self.install_data, 'share/glib-2.0/schemas/')
cmd = 'glib-compile-... | identifier_body |
process.rs | : true,
start_time_without_boot_time,
start_time: start_time_without_boot_time + info.boot_time,
run_time: 0,
uid: 0,
gid: 0,
status: ProcessStatus::Unknown(0),
tasks: if pid.0 == 0 {
HashMap::with_capacity(1000)
... | {
PathBuf::from(cmd)
} | conditional_block | |
process.rs | old_written_bytes: u64,
read_bytes: u64,
written_bytes: u64,
}
impl Process {
pub(crate) fn new(
pid: Pid,
parent: Option<Pid>,
start_time_without_boot_time: u64,
info: &SystemInfo,
) -> Process {
Process {
name: String::with_capacity(20),
... | }
fn start_time(&self) -> u64 {
self.start_time
}
fn run_time(&self) -> u64 {
self.run_time
}
fn cpu_usage(&self) -> f32 {
self.cpu_usage
}
fn disk_usage(&self) -> DiskUsage {
DiskUsage {
written_bytes: self.written_bytes.saturating_sub(sel... | }
fn status(&self) -> ProcessStatus {
self.status | random_line_split |
process.rs |
}
#[doc(hidden)]
impl From<char> for ProcessStatus {
fn from(status: char) -> ProcessStatus {
match status {
'R' => ProcessStatus::Run,
'S' => ProcessStatus::Sleep,
'D' => ProcessStatus::Idle,
'Z' => ProcessStatus::Zombie,
'T' => ProcessStatus::S... | {
match status {
1 => ProcessStatus::Idle,
2 => ProcessStatus::Run,
3 => ProcessStatus::Sleep,
4 => ProcessStatus::Stop,
5 => ProcessStatus::Zombie,
x => ProcessStatus::Unknown(x),
}
} | identifier_body | |
process.rs | _written_bytes: u64,
read_bytes: u64,
written_bytes: u64,
}
impl Process {
pub(crate) fn new(
pid: Pid,
parent: Option<Pid>,
start_time_without_boot_time: u64,
info: &SystemInfo,
) -> Process {
Process {
name: String::with_capacity(20),
pi... | (&self) -> ProcessStatus {
self.status
}
fn start_time(&self) -> u64 {
self.start_time
}
fn run_time(&self) -> u64 {
self.run_time
}
fn cpu_usage(&self) -> f32 {
self.cpu_usage
}
fn disk_usage(&self) -> DiskUsage {
DiskUsage {
writt... | status | identifier_name |
core.py | indent, allow_unicode=True, default_flow_style=False, **kw)
return to_text(transformed)
def to_json(a, *args, **kw):
''' Convert the value to JSON '''
return json.dumps(a, cls=AnsibleJSONEncoder, *args, **kw)
def to_nice_json(a, indent=4, *args, **kw):
'''Make verbose, human readable JSON'''
# pyt... | (a):
from jinja2.runtime import Undefined
''' Make a variable mandatory '''
if isinstance(a, Undefined):
raise errors.AnsibleFilterError('Mandatory variable not defined.')
return a
def combine(*terms, **kwargs):
recursive = kwargs.get('recursive', False)
if len(kwargs) > 1 or (len(kwar... | mandatory | identifier_name |
core.py | indent, allow_unicode=True, default_flow_style=False, **kw)
return to_text(transformed)
def to_json(a, *args, **kw):
''' Convert the value to JSON '''
return json.dumps(a, cls=AnsibleJSONEncoder, *args, **kw)
def to_nice_json(a, indent=4, *args, **kw):
'''Make verbose, human readable JSON'''
# pyt... |
else:
shuffle(mylist)
except:
pass
return mylist
def get_hash(data, hashtype='sha1'):
try: # see if hash is supported
h = hashlib.new(hashtype)
except:
return None
h.update(to_bytes(data, errors='surrogate_then_strict'))
return h.hexdigest()
def g... | r = Random(seed)
r.shuffle(mylist) | conditional_block |
core.py |
def to_nice_yaml(a, indent=4, *args, **kw):
'''Make verbose, human readable yaml'''
transformed = yaml.dump(a, Dumper=AnsibleDumper, indent=indent, allow_unicode=True, default_flow_style=False, **kw)
return to_text(transformed)
def to_json(a, *args, **kw):
''' Convert the value to JSON '''
return... | '''Make verbose, human readable yaml'''
transformed = yaml.dump(a, Dumper=AnsibleDumper, allow_unicode=True, **kw)
return to_text(transformed) | identifier_body | |
core.py | return None
def to_uuid(string):
return str(uuid.uuid5(UUID_NAMESPACE_ANSIBLE, str(string)))
def mandatory(a):
from jinja2.runtime import Undefined
''' Make a variable mandatory '''
if isinstance(a, Undefined):
raise errors.AnsibleFilterError('Mandatory variable not defined.')
return a
... | 'failure' : failed,
'success' : success,
'succeeded' : success,
# changed testing | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.