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
string_list.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 libc::{c_int}; use std::slice; use string::cef_string_utf16_set; use types::{cef_string_list_t,cef_string_t}; ...
let ref string = (*lt)[index as usize]; let utf16_chars: Vec<u16> = Utf16Encoder::new(string.chars()).collect(); cef_string_utf16_set(utf16_chars.as_ptr(), utf16_chars.len() as u64, value, 1) } } #[no_mangle] pub extern "C" fn cef_string_list_clear(lt: *mut cef_string_list_t) { unsafe ...
{ return 0; }
conditional_block
string_list.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 libc::{c_int}; use std::slice; use string::cef_string_utf16_set; use types::{cef_string_list_t,cef_string_t}; ...
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int { unsafe { if lt.is_null() { return 0; } (*lt).len() as c_int } } #[no_mangle] pub extern "C" fn cef_string_list_append(lt: *mut cef_string_list_t, value: *const cef_string_t) { unsafe { if lt.is_null() { re...
#[no_mangle]
random_line_split
com.sun.management.VMOption$Origin.d.ts
declare namespace com { namespace sun { namespace management { class
extends java.lang.Enum<com.sun.management.VMOption$Origin> { public static readonly DEFAULT: com.sun.management.VMOption$Origin public static readonly VM_CREATION: com.sun.management.VMOption$Origin public static readonly ENVIRON_VAR: com.sun.management.VMOption$Origin public static rea...
VMOption$Origin
identifier_name
com.sun.management.VMOption$Origin.d.ts
declare namespace com { namespace sun { namespace management { class VMOption$Origin extends java.lang.Enum<com.sun.management.VMOption$Origin> { public static readonly DEFAULT: com.sun.management.VMOption$Origin public static readonly VM_CREATION: com.sun.management.VMOption$Origin ...
public static readonly OTHER: com.sun.management.VMOption$Origin public static values(): com.sun.management.VMOption$Origin[] public static valueOf(arg0: java.lang.String | string): com.sun.management.VMOption$Origin } } } }
public static readonly ERGONOMIC: com.sun.management.VMOption$Origin public static readonly ATTACH_ON_DEMAND: com.sun.management.VMOption$Origin
random_line_split
coord_units.rs
//! `userSpaceOnUse` or `objectBoundingBox` values. use cssparser::Parser; use crate::error::*; use crate::parsers::Parse; /// Defines the units to be used for things that can consider a /// coordinate system in terms of the current transformation, or in /// terms of the current object's bounding box. #[derive(Debug...
#[test] fn converts_to_coord_units() { assert_eq!( CoordUnits::from(MyUnits(CoordUnits::ObjectBoundingBox)), CoordUnits::ObjectBoundingBox ); } }
random_line_split
coord_units.rs
//! `userSpaceOnUse` or `objectBoundingBox` values. use cssparser::Parser; use crate::error::*; use crate::parsers::Parse; /// Defines the units to be used for things that can consider a /// coordinate system in terms of the current transformation, or in /// terms of the current object's bounding box. #[derive(Debug...
() { assert!(MyUnits::parse_str("").is_err()); assert!(MyUnits::parse_str("foo").is_err()); } #[test] fn parses_paint_server_units() { assert_eq!( MyUnits::parse_str("userSpaceOnUse").unwrap(), MyUnits(CoordUnits::UserSpaceOnUse) ); assert_eq!...
parsing_invalid_strings_yields_error
identifier_name
coord_units.rs
//! `userSpaceOnUse` or `objectBoundingBox` values. use cssparser::Parser; use crate::error::*; use crate::parsers::Parse; /// Defines the units to be used for things that can consider a /// coordinate system in terms of the current transformation, or in /// terms of the current object's bounding box. #[derive(Debug...
#[test] fn has_correct_default() { assert_eq!(MyUnits::default(), MyUnits(CoordUnits::ObjectBoundingBox)); } #[test] fn converts_to_coord_units() { assert_eq!( CoordUnits::from(MyUnits(CoordUnits::ObjectBoundingBox)), CoordUnits::ObjectBoundingBox )...
{ assert_eq!( MyUnits::parse_str("userSpaceOnUse").unwrap(), MyUnits(CoordUnits::UserSpaceOnUse) ); assert_eq!( MyUnits::parse_str("objectBoundingBox").unwrap(), MyUnits(CoordUnits::ObjectBoundingBox) ); }
identifier_body
DirectClient.ts
import { IOpenable } from 'pip-services-commons-node'; import { IConfigurable } from 'pip-services-commons-node'; import { IReferenceable } from 'pip-services-commons-node'; import { IReferences } from 'pip-services-commons-node'; import { Descriptor } from 'pip-services-commons-node'; import { DependencyResolver ...
(correlationId: string, callback?: (err: any) => void): void { if (this._opened) { callback(null); return; } if (this._controller == null) { let err = new ConnectionException(correlationId, 'NO_CONTROLLER', 'Controller reference is missing'); ...
open
identifier_name
DirectClient.ts
import { IOpenable } from 'pip-services-commons-node'; import { IConfigurable } from 'pip-services-commons-node'; import { IReferenceable } from 'pip-services-commons-node'; import { IReferences } from 'pip-services-commons-node'; import { Descriptor } from 'pip-services-commons-node'; import { DependencyResolver ...
this._opened = true; this._logger.info(correlationId, "Opened direct client"); callback(null); } public close(correlationId: string, callback?: (err: any) => void): void { if (this._opened) this._logger.info(correlationId, "Closed direct client"); ...
{ let err = new ConnectionException(correlationId, 'NO_CONTROLLER', 'Controller reference is missing'); if (callback) { callback(err); return; } else { throw err; } }
conditional_block
DirectClient.ts
import { IOpenable } from 'pip-services-commons-node'; import { IConfigurable } from 'pip-services-commons-node'; import { IReferenceable } from 'pip-services-commons-node'; import { IReferences } from 'pip-services-commons-node'; import { Descriptor } from 'pip-services-commons-node'; import { DependencyResolver ...
this._controller = this._dependencyResolver.getOneRequired<T>('controller'); } protected instrument(correlationId: string, name: string): Timing { this._logger.trace(correlationId, "Executing %s method", name); return this._counters.beginTiming(name + ".call_time"); } public isOpened(): bool...
this._dependencyResolver.setReferences(references);
random_line_split
DirectClient.ts
import { IOpenable } from 'pip-services-commons-node'; import { IConfigurable } from 'pip-services-commons-node'; import { IReferenceable } from 'pip-services-commons-node'; import { IReferences } from 'pip-services-commons-node'; import { Descriptor } from 'pip-services-commons-node'; import { DependencyResolver ...
}
{ if (this._opened) this._logger.info(correlationId, "Closed direct client"); this._opened = false; callback(null); }
identifier_body
app_settings.py
""" :create: 2018 by Jens Diemer :copyleft: 2018 by the django-cms-tools team, see AUTHORS for more details. :license: GNU GPL v3 or above, see LICENSE for more details. """ from django.conf import settings from django.utils.translation import ugettext_lazy as _
LANDING_PAGE_HIDE_INDEX_VIEW = getattr(settings, "LANDING_PAGE_HIDE_INDEX_VIEW", True) # Always expand toolbar or all links only if current page is the landing page app? LANDING_PAGE_ALWAYS_ADD_TOOLBAR = getattr(settings, "LANDING_PAGE_ALWAYS_ADD_TOOLBAR", True) # Menu Text in cms toolbar: LANDING_PAGE_TOOLBAR_VERB...
# Template used to render one landing page: LANDING_PAGE_TEMPLATE = getattr(settings, "LANDING_PAGE_TEMPLATE", "landing_page/landing_page.html") # redirect user, e.g.: /en/langing_page/ -> /
random_line_split
generate.py
#!/usr/bin/env python3 """Download GTFS file and generate JSON file. Author: Panu Ranta, panu.ranta@iki.fi, https://14142.net/kartalla/about.html """ import argparse import datetime import hashlib import json import logging import os import resource import shutil import sys import tempfile import time import zipfile...
def _get_now_timestamp(): return datetime.datetime.now().strftime('%Y%m%d_%H%M%S') if __name__ == "__main__": _main()
os.rename(filename, new_filename) _progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename, new_filename))
random_line_split
generate.py
#!/usr/bin/env python3 """Download GTFS file and generate JSON file. Author: Panu Ranta, panu.ranta@iki.fi, https://14142.net/kartalla/about.html """ import argparse import datetime import hashlib import json import logging import os import resource import shutil import sys import tempfile import time import zipfile...
_rename_existing_file(new_filename) os.rename(old_filename, new_filename) _progress('renamed: {} -> {}'.format(old_filename, new_filename)) return new_filename def _create_dir(new_dir): if not os.path.isdir(new_dir): os.makedirs(new_dir) def _compare_files(filename_a, filename_b): r...
_progress('downloaded gtfs file is identical to: {}'.format(new_filename)) os.remove(old_filename) return None
conditional_block
generate.py
#!/usr/bin/env python3 """Download GTFS file and generate JSON file. Author: Panu Ranta, panu.ranta@iki.fi, https://14142.net/kartalla/about.html """ import argparse import datetime import hashlib import json import logging import os import resource import shutil import sys import tempfile import time import zipfile...
(gtfs_dir, old_filename, gtfs_name, modify_date): _create_dir(gtfs_dir) new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date)) if os.path.isfile(new_filename): if _compare_files(old_filename, new_filename): _progress('downloaded gtfs file is identical to: {}'.f...
_rename_gtfs_zip
identifier_name
generate.py
#!/usr/bin/env python3 """Download GTFS file and generate JSON file. Author: Panu Ranta, panu.ranta@iki.fi, https://14142.net/kartalla/about.html """ import argparse import datetime import hashlib import json import logging import os import resource import shutil import sys import tempfile import time import zipfile...
if __name__ == "__main__": _main()
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
identifier_body
fileapi.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! ApiSet Contract for api-ms-win-core-file-l1 pub const CREATE_NEW: ::DWORD = 1; pub const CREATE_ALWAYS: ::DWORD = 2; pub const OPEN_EXISTING: ::DWORD = 3; pub const OPEN_ALWAYS: ::DWORD = 4; pub const TRUNCATE_EXISTING: ::DWORD = 5; ...
{ pub dwFileAttributes: ::DWORD, pub ftCreationTime: ::FILETIME, pub ftLastAccessTime: ::FILETIME, pub ftLastWriteTime: ::FILETIME, pub nFileSizeHigh: ::DWORD, pub nFileSizeLow: ::DWORD, } pub type LPWIN32_FILE_ATTRIBUTE_DATA = *mut WIN32_FILE_ATTRIBUTE_DATA; #[repr(C)] #[derive(Clone, Copy, Deb...
IN32_FILE_ATTRIBUTE_DATA
identifier_name
fileapi.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! ApiSet Contract for api-ms-win-core-file-l1 pub const CREATE_NEW: ::DWORD = 1; pub const CREATE_ALWAYS: ::DWORD = 2; pub const OPEN_EXISTING: ::DWORD = 3; pub const OPEN_ALWAYS: ::DWORD = 4; pub const TRUNCATE_EXISTING: ::DWORD = 5; ...
pub struct CREATEFILE2_EXTENDED_PARAMETERS { pub dwSize: ::DWORD, pub dwFileAttributes: ::DWORD, pub dwFileFlags: ::DWORD, pub dwSecurityQosFlags: ::DWORD, pub lpSecurityAttributes: ::LPSECURITY_ATTRIBUTES, pub hTemplateFile: ::HANDLE, } pub type PCREATEFILE2_EXTENDED_PARAMETERS = *mut CREATEFIL...
pub type PBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION; pub type LPBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION; #[repr(C)] #[derive(Clone, Copy, Debug)]
random_line_split
datasets.py
# Copyright 2017 The TensorFlow 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 required by applica...
def __next__(self): # For Python 3 compatibility return self.next() def next(self): """Return the next tf.Tensor from the dataset.""" try: # TODO(ashankar): Consider removing this ops.device() contextmanager # and instead mimic ops placement in graphs: Operations on resource # hand...
return self
identifier_body
datasets.py
# Copyright 2017 The TensorFlow 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 required by applica...
(self): # For Python 3 compatibility return self.next() def next(self): """Return the next tf.Tensor from the dataset.""" try: # TODO(ashankar): Consider removing this ops.device() contextmanager # and instead mimic ops placement in graphs: Operations on resource # handles execute on t...
__next__
identifier_name
datasets.py
# Copyright 2017 The TensorFlow 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 required by applica...
gen_dataset_ops.make_iterator(ds_variant, self._resource) def __del__(self): if self._resource is not None: with ops.device("/device:CPU:0"): resource_variable_ops.destroy_resource_op(self._resource) self._resource = None def __iter__(self): return self def __next__(self): # Fo...
self._resource = gen_dataset_ops.iterator( container="", shared_name=_iterator_shared_name(), output_types=self._flat_output_types, output_shapes=self._flat_output_shapes)
random_line_split
datasets.py
# Copyright 2017 The TensorFlow 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 required by applica...
with ops.device("/device:CPU:0"): ds_variant = dataset._as_variant_tensor() # pylint: disable=protected-access self._output_types = dataset.output_types self._flat_output_types = nest.flatten(dataset.output_types) self._flat_output_shapes = nest.flatten(dataset.output_shapes) self._r...
raise RuntimeError( "{} objects only make sense when eager execution is enabled".format( type(self)))
conditional_block
bufferTime.ts
import { Subscription } from '../Subscription'; import { OperatorFunction, SchedulerLike } from '../types'; import { operate } from '../util/lift'; import { OperatorSubscriber } from './OperatorSubscriber'; import { arrRemove } from '../util/arrRemove'; import { asyncScheduler } from '../scheduler/async'; import { popS...
}; bufferCreationInterval !== null && bufferCreationInterval >= 0 ? // The user passed both a bufferTimeSpan (required), and a creation interval // That means we need to start new buffers on the interval, and those buffers need // to wait the required time span before emitting. s...
{ const subs = new Subscription(); subscriber.add(subs); const buffer: T[] = []; const record = { buffer, subs, }; bufferRecords.push(record); subs.add(scheduler.schedule(() => emit(record), bufferTimeSpan)); }
conditional_block
bufferTime.ts
import { Subscription } from '../Subscription'; import { OperatorFunction, SchedulerLike } from '../types'; import { operate } from '../util/lift'; import { OperatorSubscriber } from './OperatorSubscriber'; import { arrRemove } from '../util/arrRemove'; import { asyncScheduler } from '../scheduler/async'; import { popS...
subs.unsubscribe(); arrRemove(bufferRecords, record); subscriber.next(buffer); restartOnEmit && startBuffer(); }; /** * Called every time we start a new buffer. This does * the work of scheduling a job at the requested bufferTimeSpan * that will emit the buffer (if it's n...
{ const scheduler = popScheduler(otherArgs) ?? asyncScheduler; const bufferCreationInterval = (otherArgs[0] as number) ?? null; const maxBufferSize = (otherArgs[1] as number) || Infinity; return operate((source, subscriber) => { // The active buffers, their related subscriptions, and removal functions. ...
identifier_body
bufferTime.ts
import { Subscription } from '../Subscription'; import { OperatorFunction, SchedulerLike } from '../types'; import { operate } from '../util/lift'; import { OperatorSubscriber } from './OperatorSubscriber'; import { arrRemove } from '../util/arrRemove'; import { asyncScheduler } from '../scheduler/async'; import { popS...
<T>(bufferTimeSpan: number, ...otherArgs: any[]): OperatorFunction<T, T[]> { const scheduler = popScheduler(otherArgs) ?? asyncScheduler; const bufferCreationInterval = (otherArgs[0] as number) ?? null; const maxBufferSize = (otherArgs[1] as number) || Infinity; return operate((source, subscriber) => { // ...
bufferTime
identifier_name
bufferTime.ts
import { Subscription } from '../Subscription'; import { OperatorFunction, SchedulerLike } from '../types'; import { operate } from '../util/lift'; import { OperatorSubscriber } from './OperatorSubscriber'; import { arrRemove } from '../util/arrRemove'; import { asyncScheduler } from '../scheduler/async'; import { popS...
* * <span class="informal">Collects values from the past as an array, and emits * those arrays periodically in time.</span> * * ![](bufferTime.png) * * Buffers values from the source for a specific time duration `bufferTimeSpan`. * Unless the optional argument `bufferCreationInterval` is given, it emits and * ...
/** * Buffers the source Observable values for a specific time period.
random_line_split
Class_LabExperimBased.py
# -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General P...
def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig...
""" calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.d...
identifier_body
Class_LabExperimBased.py
# -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General P...
inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_co...
---------- columns : array of strings """
random_line_split
Class_LabExperimBased.py
# -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General P...
(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided ...
LabExperimBased
identifier_name
Class_LabExperimBased.py
# -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General P...
self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='...
new_name = column_name + ' ' + 'mg/L'
conditional_block
query.tablehelpers.js
DataExplorer.TableHelpers = (function () { var tables, infoTemplate = document.create('i', { className: 'icon-info button table-data', title: 'show the contents of this table' }), closeTemplate = document.create('i', { className: 'icon-remove butto...
}); var table = panel.getElementsByTagName('table')[0], tableBody = table.children[1], header = table.children[0].children[0], record = tableBody.children[0]; tableBody.removeChild(record); ...
var schema = document.getElementById('schema'); tables = tableData; $('ul .schema-table', schema).each(function () { var tableName = this[_textContent], data = tables[tableName.toCamelCase()]; if (data) { var infoIcon = infoTempl...
identifier_body
query.tablehelpers.js
DataExplorer.TableHelpers = (function () { var tables, infoTemplate = document.create('i', { className: 'icon-info button table-data', title: 'show the contents of this table' }), closeTemplate = document.create('i', { className: 'icon-remove butto...
ableData) { var schema = document.getElementById('schema'); tables = tableData; $('ul .schema-table', schema).each(function () { var tableName = this[_textContent], data = tables[tableName.toCamelCase()]; if (data) { var infoIcon...
it(t
identifier_name
query.tablehelpers.js
DataExplorer.TableHelpers = (function () { var tables, infoTemplate = document.create('i', { className: 'icon-info button table-data', title: 'show the contents of this table' }), closeTemplate = document.create('i', { className: 'icon-remove butto...
})();
random_line_split
query.tablehelpers.js
DataExplorer.TableHelpers = (function () { var tables, infoTemplate = document.create('i', { className: 'icon-info button table-data', title: 'show the contents of this table' }), closeTemplate = document.create('i', { className: 'icon-remove butto...
schema.insertBefore(panel, schema.children[0]); $(infoIcon).click(function () { $panel.show(); return false; }); } }); } // This is terrible, because it requires the outside code to // ...
var row = record.cloneNode(true); for (var c = 0; c < data.columns.length; ++c) { row.children[c][_textContent] = data.rows[i][c]; } tableBody.appendChild(row); }
conditional_block
controller.js
import AbstractEditController from 'hospitalrun/controllers/abstract-edit-controller'; import Ember from 'ember'; export default AbstractEditController.extend({ needs: ['procedures/edit'], cancelAction: 'closeModal', newPricingItem: false, requestingController: Ember.computed.alias('controllers.procedu...
} } });
afterUpdate: function(record) { if (this.get('newCharge')) { this.get('requestingController').send('addCharge', record); } else { this.send('closeModal');
random_line_split
controller.js
import AbstractEditController from 'hospitalrun/controllers/abstract-edit-controller'; import Ember from 'ember'; export default AbstractEditController.extend({ needs: ['procedures/edit'], cancelAction: 'closeModal', newPricingItem: false, requestingController: Ember.computed.alias('controllers.procedu...
if (this.get('newPricingItem')) { return new Ember.RSVP.Promise(function(resolve, reject) { var newPricing = this.store.createRecord('pricing', { name: this.get('itemName'), category: this.get('pricingCategory') ...
{ this.set('newCharge', true); }
conditional_block
main.rs
use std::io::BufReader; use std::io::BufRead; use std::path::Path; use std::fs::OpenOptions; use std::io::BufWriter; use std::io::Write; fn
() { let mut read_options = OpenOptions::new(); read_options.read(true); let mut write_options = OpenOptions::new(); write_options.write(true).create(true); /* We may use Path to read/write existing file or create new files. Hence, no error handling for Path. Erros happen during 'ope...
main
identifier_name
main.rs
use std::io::BufReader; use std::io::BufRead; use std::path::Path; use std::fs::OpenOptions; use std::io::BufWriter; use std::io::Write; fn main() { let mut read_options = OpenOptions::new(); read_options.read(true); let mut write_options = OpenOptions::new(); write_options.write(true).create(true); ...
let num = line.parse::<i32>().unwrap(); match (num % 5, num % 3){ (0, 0) => writeln!(& mut writer, "Num = {}", "FizzBuzz"), (0, _) => writeln!(& mut writer, "Num = {}", "Fizz"), (_, 0) => writeln!(& mut writer, "Num = {}", "Buzz"), _ => writeln!(& mu...
let line = line.unwrap();
random_line_split
main.rs
use std::io::BufReader; use std::io::BufRead; use std::path::Path; use std::fs::OpenOptions; use std::io::BufWriter; use std::io::Write; fn main()
match (num % 5, num % 3){ (0, 0) => writeln!(& mut writer, "Num = {}", "FizzBuzz"), (0, _) => writeln!(& mut writer, "Num = {}", "Fizz"), (_, 0) => writeln!(& mut writer, "Num = {}", "Buzz"), _ => writeln!(& mut writer, "Num = {}", num) }; } }
{ let mut read_options = OpenOptions::new(); read_options.read(true); let mut write_options = OpenOptions::new(); write_options.write(true).create(true); /* We may use Path to read/write existing file or create new files. Hence, no error handling for Path. Erros happen during 'open' ...
identifier_body
constant_offsets.rs
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors use core::hash::{Hash, Hasher}; use pyo3::class::basic::CompareOp; use pyo3::prelude::*; use pyo3::PyObjectProtocol; use std::collections::hash_map::DefaultHasher; /// Contains the offsets of the displacement and immediate....
(&self) -> u32 { self.offsets.immediate_offset2() as u32 } /// int: (``u32``) Size in bytes of the second immediate, or 0 if there's no second immediate #[getter] fn immediate_size2(&self) -> u32 { self.offsets.immediate_size2() as u32 } /// bool: ``True`` if :class:`ConstantOffsets.displacement_offset` and...
immediate_offset2
identifier_name
constant_offsets.rs
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors use core::hash::{Hash, Hasher}; use pyo3::class::basic::CompareOp; use pyo3::prelude::*; use pyo3::PyObjectProtocol; use std::collections::hash_map::DefaultHasher; /// Contains the offsets of the displacement and immediate....
/// int: (``u32``) Size in bytes of the displacement, or 0 if there's no displacement #[getter] fn displacement_size(&self) -> u32 { self.offsets.displacement_size() as u32 } /// int: (``u32``) The offset of the first immediate, if any. /// /// This field can be invalid even if the operand has an immediate ...
{ self.offsets.displacement_offset() as u32 }
identifier_body
constant_offsets.rs
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors use core::hash::{Hash, Hasher}; use pyo3::class::basic::CompareOp; use pyo3::prelude::*; use pyo3::PyObjectProtocol; use std::collections::hash_map::DefaultHasher; /// Contains the offsets of the displacement and immediate....
/// bool: ``True`` if :class:`ConstantOffsets.immediate_offset2` and :class:`ConstantOffsets.immediate_size2` are valid #[getter] fn has_immediate2(&self) -> bool { self.offsets.has_immediate2() } /// Returns a copy of this instance. /// /// Returns: /// ConstantOffsets: A copy of this instance /// ///...
#[getter] fn has_immediate(&self) -> bool { self.offsets.has_immediate() }
random_line_split
ssh_client2.py
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' 使用paramiko模块远程管理服务器 通过key登录 ''' import paramiko private_key_path = 'D:\workspace\Python-oldboy\day07\zhangyage_pass'
ssh = paramiko.SSHClient() #实例化一个客户端 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #自动恢复yes,在我们使用ssh客户端链接的时候第一次的时候都会让我们输入一个yes确定的 ssh.connect('192.168.75.133', 22, username='root', pkey=key) stdin,stdout,stderr = ssh.exec_command('ifconfig') #定义三个变量进行输出,默认输出是个元组会赋值给三个变量 print stdout.read() ssh.cl...
#key = paramiko.RSAKey.from_private_key_file(filename, password) key = paramiko.RSAKey.from_private_key_file(private_key_path,'12345678') #private_key_path是秘钥文件的位置,'12345678'是秘钥的口令
random_line_split
json-decoder.ts
import { ResultTreeHandler } from '../result-tree/result-tree-handler' import { QueryTreeNode } from '../query-tree/query-tree-node' import { JSONDecoderHandler } from './json-decoder-handler' import { Query } from '../query-tree/query' import { RunningQuery } from '../client/query' // JSONDecoder is a result handler ...
private dirty = false // qnode_id -> array_idx => parent[qnode_field_name] = [] // qnode_id -> array_idx -> primitive => parent[qnode_field_name][array_idx-1] = primitive // qnode_id -> primitive => parent[qnode_field_name] = primitive // qnode_id -> array_idx -> qnode_id = parent[qnode_field_name][array_i...
// dirty indicates the value is dirty
random_line_split
json-decoder.ts
import { ResultTreeHandler } from '../result-tree/result-tree-handler' import { QueryTreeNode } from '../query-tree/query-tree-node' import { JSONDecoderHandler } from './json-decoder-handler' import { Query } from '../query-tree/query' import { RunningQuery } from '../client/query' // JSONDecoder is a result handler ...
// getResult returns the active result value. public getResult(): any { return this.result } // flush flushes any pending change callbacks public flush() { /* if (!this.dirty) { return } */ this.dirty = false if (this.resultCb) { this.resultCb(this.result) } }...
{}
identifier_body
json-decoder.ts
import { ResultTreeHandler } from '../result-tree/result-tree-handler' import { QueryTreeNode } from '../query-tree/query-tree-node' import { JSONDecoderHandler } from './json-decoder-handler' import { Query } from '../query-tree/query' import { RunningQuery } from '../client/query' // JSONDecoder is a result handler ...
() { /* if (!this.dirty) { return } */ this.dirty = false if (this.resultCb) { this.resultCb(this.result) } } // getResultHandler returns the result tree handler function. public getResultHandler(): ResultTreeHandler { let qmap = this.query.getQueryMap() || undefined ...
flush
identifier_name
json-decoder.ts
import { ResultTreeHandler } from '../result-tree/result-tree-handler' import { QueryTreeNode } from '../query-tree/query-tree-node' import { JSONDecoderHandler } from './json-decoder-handler' import { Query } from '../query-tree/query' import { RunningQuery } from '../client/query' // JSONDecoder is a result handler ...
} // getResultHandler returns the result tree handler function. public getResultHandler(): ResultTreeHandler { let qmap = this.query.getQueryMap() || undefined let handler = new JSONDecoderHandler(qmap, () => { this.dirty = true }) handler.qnode = this.qnode handler.value = this.result...
{ this.resultCb(this.result) }
conditional_block
feature_abortnode.py
#!/usr/bin/env python3 # Copyright (c) 2019-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoind aborts if can't disconnect a block. - Start a single node and generate 3 blocks. - Delet...
def setup_network(self): self.setup_nodes() # We'll connect the nodes later def run_test(self): self.nodes[0].generate(3) datadir = get_datadir_path(self.options.tmpdir, 0) # Deleting the undo file will result in reorg failure os.unlink(os.path.join(datadir, s...
self.setup_clean_chain = True self.num_nodes = 2 self.rpc_timeout = 240
identifier_body
feature_abortnode.py
#!/usr/bin/env python3 # Copyright (c) 2019-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoind aborts if can't disconnect a block. - Start a single node and generate 3 blocks. - Delet...
AbortNodeTest().main()
conditional_block
feature_abortnode.py
#!/usr/bin/env python3 # Copyright (c) 2019-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoind aborts if can't disconnect a block. - Start a single node and generate 3 blocks. - Delet...
(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 2 self.rpc_timeout = 240 def setup_network(self): self.setup_nodes() # We'll connect the nodes later def run_test(self): self.nodes[0].generate(3) datad...
AbortNodeTest
identifier_name
feature_abortnode.py
#!/usr/bin/env python3 # Copyright (c) 2019-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoind aborts if can't disconnect a block. - Start a single node and generate 3 blocks. - Delet...
# Deleting the undo file will result in reorg failure os.unlink(os.path.join(datadir, self.chain, 'blocks', 'rev00000.dat')) # Connecting to a node with a more work chain will trigger a reorg # attempt. self.nodes[1].generate(3) with self.nodes[0].assert_debug_log(["Fail...
def run_test(self): self.nodes[0].generate(3) datadir = get_datadir_path(self.options.tmpdir, 0)
random_line_split
__main__.py
''' Usage: manager puzzle_load (--file <filename>) [--url <url>] manager puzzle_del (--name <name>) [--url <url>] manager puzzles [--url <url>] manager puzzleboards_clear [--url <url>] manager puzzleboard_consume [--async-url <url>] (--name <name>) [--size <size>] manager puzzleboard_pop (--name...
opts = docopt(__doc__, version='0.1') command = [v for k, v in verbs.items() if opts[k]][0] command(**opts)
conditional_block
__main__.py
''' Usage: manager puzzle_load (--file <filename>) [--url <url>] manager puzzle_del (--name <name>) [--url <url>] manager puzzles [--url <url>] manager puzzleboards_clear [--url <url>] manager puzzleboard_consume [--async-url <url>] (--name <name>) [--size <size>] manager puzzleboard_pop (--name...
'puzzle_load': command_puzzle_load, 'puzzles': command_puzzles, 'puzzleboards_clear': command_puzzleboards_clear, 'puzzleboard_consume': command_puzzleboard_consume, 'puzzleboard_pop': command_puzzleboard_pop } if __name__ == '__main__': opts = docopt(__doc__, version='0.1') command = [v f...
# Command pattern verbs = {
random_line_split
visitor.rs
// Copyright 2016 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to...
fn visit_external_non_terminal_symbol(&mut self, _this: usize, _rule: &syn::Path) -> R { R::default() } fn visit_atom(&mut self, _this: usize) -> R { R::default() } fn visit_any_single_char(&mut self, this: usize) -> R { self.visit_atom(this) } fn visit_character_class(&mut self, this: usize, _char_cla...
{ R::default() }
identifier_body
visitor.rs
// Copyright 2016 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to...
ZeroOrOne(child) => { visitor.visit_optional(this, child) } NotPredicate(child) => { visitor.visit_not_predicate(this, child) } AndPredicate(child) => { visitor.visit_and_predicate(this, child) } CharacterClass(char_class) => { visitor.visit_character_class(this, cha...
{ visitor.visit_one_or_more(this, child) }
conditional_block
visitor.rs
// Copyright 2016 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to...
(&mut self, this: usize, child: usize) -> R { self.visit_repeat(this, child) } fn visit_one_or_more(&mut self, this: usize, child: usize) -> R { self.visit_repeat(this, child) } fn visit_optional(&mut self, _this: usize, child: usize) -> R { self.visit_expr(child) } fn visit_syntactic_predica...
visit_zero_or_more
identifier_name
visitor.rs
// Copyright 2016 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to...
fn visit_expr(&mut self, this: usize) -> R { walk_expr(self, this) } fn visit_str_literal(&mut self, _this: usize, _lit: String) -> R { R::default() } fn visit_non_terminal_symbol(&mut self, _this: usize, _rule: &Ident) -> R { R::default() } fn visit_external_non_terminal_symbol(&mut self, _this: usize, ...
random_line_split
naivebayes.py
""" Simple implementation of mutinomial Naive Bayes for text classfification. TODO: Apply to 20 Newsgroups, Reuters-21578 datasets """ __author__ = 'Duong Nguyen' __version__ = '0.0' import math import sys from collections import defaultdict class NaiveBayes(object): """ Multinomial Naive Bayes""" def...
(self): self.categories = set() self.vocabularies = set() self.wordcount = {} self.catcount = {} self.denom = {} def train(self, data): for d in data: cat = d[0] self.categories.add(cat) for cat in self.categories: ...
__init__
identifier_name
naivebayes.py
""" Simple implementation of mutinomial Naive Bayes for text classfification. TODO: Apply to 20 Newsgroups, Reuters-21578 datasets """ __author__ = 'Duong Nguyen' __version__ = '0.0' import math
class NaiveBayes(object): """ Multinomial Naive Bayes""" def __init__(self): self.categories = set() self.vocabularies = set() self.wordcount = {} self.catcount = {} self.denom = {} def train(self, data): for d in data: cat = d[0] ...
import sys from collections import defaultdict
random_line_split
naivebayes.py
""" Simple implementation of mutinomial Naive Bayes for text classfification. TODO: Apply to 20 Newsgroups, Reuters-21578 datasets """ __author__ = 'Duong Nguyen' __version__ = '0.0' import math import sys from collections import defaultdict class NaiveBayes(object): """ Multinomial Naive Bayes""" def...
def train(self, data): for d in data: cat = d[0] self.categories.add(cat) for cat in self.categories: self.wordcount[cat] = defaultdict(int) self.catcount[cat] = 0 for d in data: cat, doc = d[0], d[1:...
self.categories = set() self.vocabularies = set() self.wordcount = {} self.catcount = {} self.denom = {}
identifier_body
naivebayes.py
""" Simple implementation of mutinomial Naive Bayes for text classfification. TODO: Apply to 20 Newsgroups, Reuters-21578 datasets """ __author__ = 'Duong Nguyen' __version__ = '0.0' import math import sys from collections import defaultdict class NaiveBayes(object): """ Multinomial Naive Bayes""" def...
return best if __name__ == '__main__': pass
maxP = p best = cat
conditional_block
virtual_nic_send_buffer.py
import logging from autotest.client import utils from autotest.client.shared import error from virttest import remote from virttest import utils_misc from virttest import utils_test from virttest import utils_net @error.context_aware def run(test, params, env): """ Test Steps: 1. boot up guest with snd...
ping_timeout = int(params.get("ping_timeout", 60)) host_ip = utils_net.get_host_ip_address(params) txt = "Ping %s from %s during netperf testing" % (host_ip, dsthost) error.context(txt, logging.info) status, output = utils_test.ping(host_ip, session=dst_ses, ...
err = "Fail to start netperf test between guest and host" raise error.TestError(err)
conditional_block
virtual_nic_send_buffer.py
import logging from autotest.client import utils from autotest.client.shared import error from virttest import remote from virttest import utils_misc from virttest import utils_test from virttest import utils_net @error.context_aware def run(test, params, env):
dsthost = params.get("dsthost") login_timeout = int(params.get("login_timeout", 360)) if dsthost: params_host = params.object_params("dsthost") dst_ses = remote.wait_for_login(params_host.get("shell_client"), dsthost, ...
""" Test Steps: 1. boot up guest with sndbuf=1048576 or other value. 2. Transfer file between host and guest. 3. Run netperf between host and guest. 4. During netperf testing, from an external host ping the host whitch booting the guest. Params: :param test: QEMU test object. ...
identifier_body
virtual_nic_send_buffer.py
import logging from autotest.client import utils from autotest.client.shared import error from virttest import remote from virttest import utils_misc from virttest import utils_test from virttest import utils_net @error.context_aware def run(test, params, env): """ Test Steps: 1. boot up guest with snd...
finally: try: stress_thread.join(60) except Exception: pass if dst_ses: dst_ses.close()
if package_lost > package_lost_ratio: raise error.TestFail(txt) logging.info(txt)
random_line_split
virtual_nic_send_buffer.py
import logging from autotest.client import utils from autotest.client.shared import error from virttest import remote from virttest import utils_misc from virttest import utils_test from virttest import utils_net @error.context_aware def
(test, params, env): """ Test Steps: 1. boot up guest with sndbuf=1048576 or other value. 2. Transfer file between host and guest. 3. Run netperf between host and guest. 4. During netperf testing, from an external host ping the host whitch booting the guest. Params: :param t...
run
identifier_name
database.py
#!/usr/bin/python from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy #flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy_utils import ScalarListType db = SQLAlchemy() login_manager = LoginManager() # User # email, password, authenticated (once user logins) class User(db.Model): ...
# given user, return user object @login_manager.user_loader def load_user(user_id): try: return User.query.get(user_id) except: return None # Team # Team with its own number and a list of members and admins class Team(db.Model): __tablename__ = "team" number = db.Column(db.Integer, ...
random_line_split
database.py
#!/usr/bin/python from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy #flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy_utils import ScalarListType db = SQLAlchemy() login_manager = LoginManager() # User # email, password, authenticated (once user logins) class User(db.Model): ...
(self): return self.authenticated # Required by flask logout_user() def is_anonymous(self): return False # given user, return user object @login_manager.user_loader def load_user(user_id): try: return User.query.get(user_id) except: return None # Team # Team with its...
is_authenticated
identifier_name
database.py
#!/usr/bin/python from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy #flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy_utils import ScalarListType db = SQLAlchemy() login_manager = LoginManager() # User # email, password, authenticated (once user logins) class User(db.Model): ...
def is_active(self): return True def get_id(self): return self.email def is_authenticated(self): return self.authenticated # Required by flask logout_user() def is_anonymous(self): return False # given user, return user object @login_manager.user_loader def...
self.email = email self.password = password self.name = name self.teamNumber = teamNumber
identifier_body
application.js
import Ember from 'ember'; import DS from 'ember-data'; import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin'; export default DS.RESTAdapter.extend(DataAdapterMixin, { authorizer: 'authorizer:dspace', initENVProperties: Ember.on('init', function() { let ENV = this.container.lookupFactory(...
(url, type, hash) { if (Ember.isEmpty(hash)) { hash = {}; } if (Ember.isEmpty(hash.data)) { hash.data = {}; } if (type === "GET") { hash.data.expand = 'all'; //add ?expand=all to all GET calls } return this._super(url, type, hash); } });
ajax
identifier_name
application.js
import Ember from 'ember'; import DS from 'ember-data'; import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin'; export default DS.RESTAdapter.extend(DataAdapterMixin, { authorizer: 'authorizer:dspace', initENVProperties: Ember.on('init', function() { let ENV = this.container.lookupFactory(...
});
{ if (Ember.isEmpty(hash)) { hash = {}; } if (Ember.isEmpty(hash.data)) { hash.data = {}; } if (type === "GET") { hash.data.expand = 'all'; //add ?expand=all to all GET calls } return this._super(url, type, hash); }
identifier_body
application.js
import Ember from 'ember'; import DS from 'ember-data'; import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin'; export default DS.RESTAdapter.extend(DataAdapterMixin, { authorizer: 'authorizer:dspace', initENVProperties: Ember.on('init', function() { let ENV = this.container.lookupFactory(...
}), //coalesceFindRequests: true, -> commented out, because it only works for some endpoints (e.g. items) and not others (e.g. communities) ajax(url, type, hash) { if (Ember.isEmpty(hash)) { hash = {}; } if (Ember.isEmpty(hash.data)) { hash.data = {}; } if (type === "GET") { ...
}
random_line_split
application.js
import Ember from 'ember'; import DS from 'ember-data'; import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin'; export default DS.RESTAdapter.extend(DataAdapterMixin, { authorizer: 'authorizer:dspace', initENVProperties: Ember.on('init', function() { let ENV = this.container.lookupFactory(...
if (type === "GET") { hash.data.expand = 'all'; //add ?expand=all to all GET calls } return this._super(url, type, hash); } });
{ hash.data = {}; }
conditional_block
eulers_sum_of_powers_conjecture.rs
// http://rosettacode.org/wiki/Euler's_sum_of_powers_conjecture const MAX_N: u64 = 250; fn
() -> (usize, usize, usize, usize, usize) { let pow5: Vec<u64> = (0..MAX_N).map(|i| i.pow(5)).collect(); let pow5_to_n = |pow| pow5.binary_search(&pow); for x0 in 1..MAX_N as usize { for x1 in 1..x0 { for x2 in 1..x1 { for x3 in 1..x2 { let pow_sum = ...
eulers_sum_of_powers
identifier_name
eulers_sum_of_powers_conjecture.rs
// http://rosettacode.org/wiki/Euler's_sum_of_powers_conjecture const MAX_N: u64 = 250; fn eulers_sum_of_powers() -> (usize, usize, usize, usize, usize)
fn main() { let (x0, x1, x2, x3, y) = eulers_sum_of_powers(); println!("{}^5 + {}^5 + {}^5 + {}^5 == {}^5", x0, x1, x2, x3, y) }
{ let pow5: Vec<u64> = (0..MAX_N).map(|i| i.pow(5)).collect(); let pow5_to_n = |pow| pow5.binary_search(&pow); for x0 in 1..MAX_N as usize { for x1 in 1..x0 { for x2 in 1..x1 { for x3 in 1..x2 { let pow_sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3];...
identifier_body
eulers_sum_of_powers_conjecture.rs
// http://rosettacode.org/wiki/Euler's_sum_of_powers_conjecture const MAX_N: u64 = 250; fn eulers_sum_of_powers() -> (usize, usize, usize, usize, usize) { let pow5: Vec<u64> = (0..MAX_N).map(|i| i.pow(5)).collect(); let pow5_to_n = |pow| pow5.binary_search(&pow); for x0 in 1..MAX_N as usize { for ...
}
println!("{}^5 + {}^5 + {}^5 + {}^5 == {}^5", x0, x1, x2, x3, y)
random_line_split
eulers_sum_of_powers_conjecture.rs
// http://rosettacode.org/wiki/Euler's_sum_of_powers_conjecture const MAX_N: u64 = 250; fn eulers_sum_of_powers() -> (usize, usize, usize, usize, usize) { let pow5: Vec<u64> = (0..MAX_N).map(|i| i.pow(5)).collect(); let pow5_to_n = |pow| pow5.binary_search(&pow); for x0 in 1..MAX_N as usize { for ...
} } } } panic!(); } fn main() { let (x0, x1, x2, x3, y) = eulers_sum_of_powers(); println!("{}^5 + {}^5 + {}^5 + {}^5 == {}^5", x0, x1, x2, x3, y) }
{ return (x0, x1, x2, x3, n) }
conditional_block
stylesheet.rs
UrlExtraData>, /// The namespaces that apply to this stylesheet. pub namespaces: RwLock<Namespaces>, /// The quirks mode of this stylesheet. pub quirks_mode: QuirksMode, /// This stylesheet's source map URL. pub source_map_url: RwLock<Option<String>>, /// This stylesheet's source URL. pu...
update_from_str
identifier_name
stylesheet.rs
origin: Origin, /// The url data this stylesheet should use. pub url_data: RwLock<UrlExtraData>, /// The namespaces that apply to this stylesheet. pub namespaces: RwLock<Namespaces>, /// The quirks mode of this stylesheet. pub quirks_mode: QuirksMode, /// This stylesheet's source map URL. ...
} } )+ } } /// A trait to represent a given stylesheet in a document. pub trait StylesheetInDocument { /// Get the stylesheet origin. fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin; /// Get the stylesheet quirks mode. fn quirks_mode(&self, guard: &Sha...
random_line_split
stylesheet.rs
origin: Origin, /// The url data this stylesheet should use. pub url_data: RwLock<UrlExtraData>, /// The namespaces that apply to this stylesheet. pub namespaces: RwLock<Namespaces>, /// The quirks mode of this stylesheet. pub quirks_mode: QuirksMode, /// This stylesheet's source map URL. ...
} /// The structure servo uses to represent a stylesheet. #[derive(Debug)] pub struct Stylesheet { /// The contents of this stylesheet. pub contents: StylesheetContents, /// The lock used for objects inside this stylesheet pub shared_lock: SharedRwLock, /// List of media associated with the Styles...
{ // Make a deep clone of the rules, using the new lock. let rules = self.rules .read_with(guard) .deep_clone_with_lock(lock, guard, params); Self { rules: Arc::new(lock.wrap(rules)), quirks_mode: self.quirks_mode, origin: self.origin,...
identifier_body
List.js
import React from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import { trimString } from '../../utils/index'; const BestNewList = (props) => ( <ReactCSSTransitionGroup className="top10-item" component="section" transitionName="top10-item" transitionEnterTimeout={100...
export default BestNewList;
);
random_line_split
main.rs
_empty() { break; } digest.update(data); data.len() }; reader.consume(count); } let output = digest.finalize(); let result = output.to_hex().to_ascii_lowercase(); Ok(result) } fn hash_file<P>(length: usize, path: P) -> eyre::Result...
{ let expected = "7ea59e7a000ec003846b6607dfd5f9217b681dc1a81b0789b464c3995105d93083f7f0a86fca01a1bed27e9f9303ae58d01746e3b20443480bea56198e65bfc5"; assert_eq!(expected, hash_reader(64, "hi\n".as_bytes()).unwrap()); }
identifier_body
main.rs
blake2 algorithm and must be a multiple of 8 [default: 512] --tag create a BSD-style checksum The following five options are useful only when verifying checksums: --ignore-missing don't fail or report status for missing files --quiet don't print OK for ...
Ok(errors) } fn check_args(args: Args) -> eyre::Result<i32> { let filename = args.arg_filename[0].as_str(); let errors = if filename == "-" { let stdin = io::stdin(); check_input(&args, filename, stdin.lock())? } else { let file = File::open(filename)?; let reader = BufR...
println!("FAILED"); } } }
random_line_split
main.rs
blake2 algorithm and must be a multiple of 8 [default: 512] --tag create a BSD-style checksum The following five options are useful only when verifying checksums: --ignore-missing don't fail or report status for missing files --quiet don't print OK for ...
(args: Args) -> eyre::Result<i32> { let filename = args.arg_filename[0].as_str(); let errors = if filename == "-" { let stdin = io::stdin(); check_input(&args, filename, stdin.lock())? } else { let file = File::open(filename)?; let reader = BufReader::new(file); check...
check_args
identifier_name
main.rs
blake2 algorithm and must be a multiple of 8 [default: 512] --tag create a BSD-style checksum The following five options are useful only when verifying checksums: --ignore-missing don't fail or report status for missing files --quiet don't print OK for ...
; process::exit(result) } #[cfg(test)] mod tests { use super::*; #[test] fn split_check_line_with_valid_line() { let line = "c0ae24f806df19d850565b234bc37afd5035e7536388290db9413c98578394313f38b093143ecfbc208425d54b9bfef0d9917a9e93910f7914a97e73fea23534 test"; let (hash, filename) = s...
{ hash_args(args)? }
conditional_block
compile.ts
import * as fs from "fs" import * as path from "path" import * as ts from "typescript" const coffee = require("coffeescript") const less = require("less") import {argv} from "yargs" import {collect_deps} from "./dependencies" const mkCoffeescriptError = (error: any, file?: string) => { const message = error.message...
(name: string): boolean { return inputs[name] != null || ts.sys.fileExists(name) }, readFile(name: string): string | undefined { return inputs[name] != null ? inputs[name] : ts.sys.readFile(name) }, writeFile(name, content): void { ts.sys.writeFile(name, content) }, getSourceFi...
fileExists
identifier_name
compile.ts
import * as fs from "fs" import * as path from "path" import * as ts from "typescript" const coffee = require("coffeescript") const less = require("less") import {argv} from "yargs" import {collect_deps} from "./dependencies" const mkCoffeescriptError = (error: any, file?: string) => { const message = error.message...
let data = "" stdin.on("data", (chunk: string) => data += chunk) stdin.on("end", () => compile_and_resolve_deps(JSON.parse(data))) }
const stdin = process.stdin stdin.resume() stdin.setEncoding("utf-8")
random_line_split
compile.ts
import * as fs from "fs" import * as path from "path" import * as ts from "typescript" const coffee = require("coffeescript") const less = require("less") import {argv} from "yargs" import {collect_deps} from "./dependencies" const mkCoffeescriptError = (error: any, file?: string) => { const message = error.message...
, readFile(name: string): string | undefined { return inputs[name] != null ? inputs[name] : ts.sys.readFile(name) }, writeFile(name, content): void { ts.sys.writeFile(name, content) }, getSourceFile(name: string, target: ts.ScriptTarget, _onError?: (message: string) => void) { cons...
{ return inputs[name] != null || ts.sys.fileExists(name) }
identifier_body
Attractor.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Attractor = void 0; const Utils_1 = require("../../../../Utils"); class Attractor { constructor(container) { this.container = container; } interact(p1, _delta) { var _a; const container = this.contai...
reset(particle) { } } exports.Attractor = Attractor;
isEnabled(particle) { return particle.particlesOptions.move.attract.enable; }
random_line_split
Attractor.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Attractor = void 0; const Utils_1 = require("../../../../Utils"); class Attractor { constructor(container) { this.container = container; } interact(p1, _delta)
} } isEnabled(particle) { return particle.particlesOptions.move.attract.enable; } reset(particle) { } } exports.Attractor = Attractor;
{ var _a; const container = this.container; const options = container.options; const distance = (_a = p1.linksDistance) !== null && _a !== void 0 ? _a : container.retina.linksDistance; const pos1 = p1.getPosition(); const query = container.particles.quadTree.query(new Uti...
identifier_body
Attractor.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Attractor = void 0; const Utils_1 = require("../../../../Utils"); class Attractor { constructor(container) { this.container = container; }
(p1, _delta) { var _a; const container = this.container; const options = container.options; const distance = (_a = p1.linksDistance) !== null && _a !== void 0 ? _a : container.retina.linksDistance; const pos1 = p1.getPosition(); const query = container.particles.quadTree....
interact
identifier_name
Attractor.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Attractor = void 0; const Utils_1 = require("../../../../Utils"); class Attractor { constructor(container) { this.container = container; } interact(p1, _delta) { var _a; const container = this.contai...
const pos2 = p2.getPosition(); const { dx, dy } = Utils_1.Utils.getDistances(pos1, pos2); const rotate = options.particles.move.attract.rotate; const ax = dx / (rotate.x * 1000); const ay = dy / (rotate.y * 1000); p1.velocity.horizontal -= ax; ...
{ continue; }
conditional_block
setup.py
from __future__ import division, absolute_import, print_function,\ unicode_literals import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup, Extension from distutils.core import Extension from distutils.errors import DistutilsError from distutils.command.bui...
print("WARNING : CPython API extension could not be built.") print() print("Exception was : %r" % (e,)) print() print( "If you need the extensions (they may be faster than " "alternative on some" ) print(...
try: build_ext.run(self) except Exception as e: print() print("=" * 79)
random_line_split
setup.py
from __future__ import division, absolute_import, print_function,\ unicode_literals import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup, Extension from distutils.core import Extension from distutils.errors import DistutilsError from distutils.command.bui...
(self): try: build_ext.run(self) except Exception as e: print() print("=" * 79) print("WARNING : CPython API extension could not be built.") print() print("Exception was : %r" % (e,)) print() print( ...
run
identifier_name
setup.py
from __future__ import division, absolute_import, print_function,\ unicode_literals import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup, Extension from distutils.core import Extension from distutils.errors import DistutilsError from distutils.command.bui...
else: _lib = ctypes.cdll.LoadLibrary('libnanoconfig.so') except OSError: # Building without nanoconfig cpy_extension = Extension(str('_nanomsg_cpy'), sources=[str('_nanomsg_cpy/wrapper.c')], libraries=[str('nanomsg')], ) else: ...
_lib = ctypes.windll.nanoconfig
conditional_block
setup.py
from __future__ import division, absolute_import, print_function,\ unicode_literals import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup, Extension from distutils.core import Extension from distutils.errors import DistutilsError from distutils.command.bui...
try: import ctypes if sys.platform in ('win32', 'cygwin'): _lib = ctypes.windll.nanoconfig else: _lib = ctypes.cdll.LoadLibrary('libnanoconfig.so') except OSError: # Building without nanoconfig cpy_extension = Extension(str('_nanomsg_cpy'), sources=[str('_na...
def run(self): try: build_ext.run(self) except Exception as e: print() print("=" * 79) print("WARNING : CPython API extension could not be built.") print() print("Exception was : %r" % (e,)) print() print( ...
identifier_body
jsLists.js
/* * JSLists v0.4.5 * © 2016 George Duff * * Release date: 01/06/2016 * The MIT License (MIT) * Copyright (c) 2016 George Duff * 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 witho...
) { var JSLists = {}; var JSLists_Error = function(error, alertType) { console.log(error); } var getUl = function(){ return document.getElementsByTagName("UL"); }; var getOl = function(){ return document.getElementsByTagName("OL"); }; var getAllLists = function(){ var olLis...
efine_JSLists(
identifier_name
jsLists.js
/* * JSLists v0.4.5 * © 2016 George Duff * * Release date: 01/06/2016 * The MIT License (MIT) * Copyright (c) 2016 George Duff * 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 witho...
for(i=1; i<listItems.length; i++) { // console.log(listItems[i].childNodes.length); if(listItems[i].classList = "jslist-li" && listItems[i].childNodes.length < 2) { listItems[i].innerHTML = blackCircle + listItems[i].innerHTML } } this.padUnorderedLists(listId); this.padOrderedLists...
if(listItems[i].childNodes[0].className != "jsl-collapsed-arrow") { listItems[i].classList.add('jslist-li'); } }
conditional_block
jsLists.js
/* * JSLists v0.4.5 * © 2016 George Duff * * Release date: 01/06/2016 * The MIT License (MIT) * Copyright (c) 2016 George Duff * 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 witho...
JSLists.searchList = function(listId, searchTerm) { var i, j, lilNodes, liItems = document.getElementsByTagName("LI"); for(i=0; i<liItems.length; i++) { if(liItems[i].hasChildNodes()) { for(j=0; j<liItems[i].childNodes.length; j++) { if(liItems[...
var JSLists = {}; var JSLists_Error = function(error, alertType) { console.log(error); } var getUl = function(){ return document.getElementsByTagName("UL"); }; var getOl = function(){ return document.getElementsByTagName("OL"); }; var getAllLists = function(){ var olLists ...
identifier_body
jsLists.js
/* * JSLists v0.4.5 * © 2016 George Duff * * Release date: 01/06/2016 * The MIT License (MIT) * Copyright (c) 2016 George Duff * 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 witho...
this.padUnorderedLists(listId); this.padOrderedLists(listId); }; JSLists.createTree = function(listId, bulletPoint) { document.getElementById(listId).style.display = "none;" var i, j, curElem, ulCount, olCount, listItems = document.getElementById(listId).getElementsByTagName('LI'); //this s...
listItems[i].innerHTML = blackCircle + listItems[i].innerHTML } }
random_line_split
get_landmines.py
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This file emits the list of reasons why a particular build needs to be clobbered (or a list of 'landmines'). """ import sys de...
(): """ ALL LANDMINES ARE EMITTED FROM HERE. """ print 'Need to clobber after ICU52 roll.' print 'Landmines test.' print 'Activating MSVS 2013.' print 'Revert activation of MSVS 2013.' print 'Activating MSVS 2013 again.' print 'Clobber after ICU roll.' print 'Moar clobbering...' print 'Remove buil...
main
identifier_name