file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
marFileLockedStageFailurePartialSvc_win.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ /* File locked partial MAR file staged patch apply failure test */ const STATE_AFTER_STAGE = STATE_PENDING; function run_test() { if (!setupTestCommon()) { return; } gTestFiles = gTestFilesPartialSu...
() { runHelperLockFile(gTestFiles[2]); } /** * Called after the call to waitForHelperSleep finishes. */ function waitForHelperSleepFinished() { stageUpdate(); } /** * Called after the call to stageUpdate finishes. */ function stageUpdateFinished() { checkPostUpdateRunningFile(false); // Files aren't check...
setupUpdaterTestFinished
identifier_name
marFileLockedStageFailurePartialSvc_win.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ /* File locked partial MAR file staged patch apply failure test */ const STATE_AFTER_STAGE = STATE_PENDING; function run_test() { if (!setupTestCommon()) { return; } gTestFiles = gTestFilesPartialSu...
/** * Called after the call to waitForHelperSleep finishes. */ function waitForHelperSleepFinished() { stageUpdate(); } /** * Called after the call to stageUpdate finishes. */ function stageUpdateFinished() { checkPostUpdateRunningFile(false); // Files aren't checked after staging since this test locks a fil...
runHelperLockFile(gTestFiles[2]); }
random_line_split
marFileLockedStageFailurePartialSvc_win.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ /* File locked partial MAR file staged patch apply failure test */ const STATE_AFTER_STAGE = STATE_PENDING; function run_test() { if (!setupTestCommon())
gTestFiles = gTestFilesPartialSuccess; gTestDirs = gTestDirsPartialSuccess; setTestFilesAndDirsForFailure(); setupUpdaterTest(FILE_PARTIAL_MAR, false); } /** * Called after the call to setupUpdaterTest finishes. */ function setupUpdaterTestFinished() { runHelperLockFile(gTestFiles[2]); } /** * Called af...
{ return; }
conditional_block
deallocate.py
import angr import logging l = logging.getLogger(name=__name__) class deallocate(angr.SimProcedure): #pylint:disable=arguments-differ def run(self, addr, length): #pylint:disable=unused-argument # return code (see deallocate() docs) r = self.state.solver.ite_cases(( (addr % 0x...
addr = self.state.solver.max_int(addr) # into a page page_size = self.state.memory.page_size base_page_num = addr // page_size if self.state.solver.symbolic(length): l.warning("Concretizing symbolic length passed to deallocate to max_int") length = self.sta...
l.warning("Concretizing symbolic address passed to deallocate to max_int")
random_line_split
deallocate.py
import angr import logging l = logging.getLogger(name=__name__) class deallocate(angr.SimProcedure): #pylint:disable=arguments-differ def run(self, addr, length): #pylint:disable=unused-argument # return code (see deallocate() docs) r = self.state.solver.ite_cases(( (addr % 0x...
allowed_length = allowed_pages * page_size self.state.cgc.add_sinkhole(addr, allowed_length) l.debug("Deallocating [%#x, %#x]", addr, addr + allowed_length - 1) self.state.memory.unmap_region(addr, allowed_length) return r
return r
conditional_block
deallocate.py
import angr import logging l = logging.getLogger(name=__name__) class
(angr.SimProcedure): #pylint:disable=arguments-differ def run(self, addr, length): #pylint:disable=unused-argument # return code (see deallocate() docs) r = self.state.solver.ite_cases(( (addr % 0x1000 != 0, self.state.cgc.EINVAL), (length == 0, self.state.cgc.EI...
deallocate
identifier_name
deallocate.py
import angr import logging l = logging.getLogger(name=__name__) class deallocate(angr.SimProcedure): #pylint:disable=arguments-differ
def run(self, addr, length): #pylint:disable=unused-argument # return code (see deallocate() docs) r = self.state.solver.ite_cases(( (addr % 0x1000 != 0, self.state.cgc.EINVAL), (length == 0, self.state.cgc.EINVAL), (self.state.cgc.addr_invalid(addr), self...
identifier_body
BarChart.js
const React = require('react'); const { Bar } = require('react-chartjs'); export default class BarChart extends React.Component { constructor(props) { super(props); const colors = new Array(this.props.scores.length).fill('rgba(178,225,102,0.5)'); const teamIdx = this.props.names.findIndex(...
} BarChart.propTypes = { names: React.PropTypes.array, numSolved: React.PropTypes.array, scores: React.PropTypes.array, username: React.PropTypes.string.isRequired, };
{ const that = this; const options = { responsive: true, showTooltips: true, tooltipTemplate: (v) => { const teamIdx = that.props.names.findIndex((name) => name === v.label); const time = that.props.scores[teamIdx]; retu...
identifier_body
BarChart.js
const React = require('react'); const { Bar } = require('react-chartjs');
export default class BarChart extends React.Component { constructor(props) { super(props); const colors = new Array(this.props.scores.length).fill('rgba(178,225,102,0.5)'); const teamIdx = this.props.names.findIndex((name) => name === props.username); if (teamIdx !== -1) { ...
random_line_split
BarChart.js
const React = require('react'); const { Bar } = require('react-chartjs'); export default class BarChart extends React.Component { constructor(props) { super(props); const colors = new Array(this.props.scores.length).fill('rgba(178,225,102,0.5)'); const teamIdx = this.props.names.findIndex(...
this.state = { datasets: [ { label: 'Problems solved', fillColor: colors, data: this.props.numSolved, }, ], labels: this.props.names, }; } render() { const th...
{ colors[teamIdx] = 'rgba(54, 162, 235, 0.2)'; }
conditional_block
BarChart.js
const React = require('react'); const { Bar } = require('react-chartjs'); export default class
extends React.Component { constructor(props) { super(props); const colors = new Array(this.props.scores.length).fill('rgba(178,225,102,0.5)'); const teamIdx = this.props.names.findIndex((name) => name === props.username); if (teamIdx !== -1) { colors[teamIdx] = 'rgba(54...
BarChart
identifier_name
meinkino.py
# -*- coding: utf-8 -*- """ Flixnet Add-on Copyright (C) 2016 Viper2k4 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) an...
r = client.request(query) r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-items'}) r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item'}) r = dom_parser.parse_dom(r, 'a', attrs={'class': 'ml-name'}, req='href') r = [(i.attrs['href'], re.sub('<.+?>|</.+?>', '', i.content).s...
identifier_body
meinkino.py
# -*- coding: utf-8 -*- """ Flixnet Add-on Copyright (C) 2016 Viper2k4 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) an...
try: url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'localtvshowtitle': localtvshowtitle, 'year': year} return urllib.urlencode(url) except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): try: if ...
random_line_split
meinkino.py
# -*- coding: utf-8 -*- """ Flixnet Add-on Copyright (C) 2016 Viper2k4 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) an...
if not url and title != localtitle: url = self.__search(localtitle, 'filme', year) return url except: return def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, year): try: url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'local...
url = self.__search(title, 'filme', year)
conditional_block
meinkino.py
# -*- coding: utf-8 -*- """ Flixnet Add-on Copyright (C) 2016 Viper2k4 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) an...
(self, title, type, year, season=0, episode=False): try: years = [str(year), str(int(year) + 1), str(int(year) - 1)] years = ['&veroeffentlichung[]=%s' % i for i in years] query = self.search_link % (type, urllib.quote_plus(cleantitle.query(title))) query += ''.j...
__search
identifier_name
DisksInformation.tsx
import * as React from 'react'; import * as classNames from 'classnames'; import { IDisksInformationProps, IDisksInformationState } from './DisksInformation.Props';
import { ServerStatus, Partition } from '../../../models'; import { DirectionalHint } from '../../../utilities/DirectionalHint'; import { sortServersByStatusAndName } from '../../../utilities/server'; import { Popup } from '../../Popup/Popup'; import './DisksInformation.scss'; export class DisksInformation extends Re...
import { Icon } from '../../Icon/Icon'; import { Callout } from '../../Callout';
random_line_split
DisksInformation.tsx
import * as React from 'react'; import * as classNames from 'classnames'; import { IDisksInformationProps, IDisksInformationState } from './DisksInformation.Props'; import { Icon } from '../../Icon/Icon'; import { Callout } from '../../Callout'; import { ServerStatus, Partition } from '../../../models'; import { Direct...
(props) { super(props); this.state = { tooltipShow: false }; } private _calloutTargetElement: any; setCalloutTargetRef = (ref) => { this._calloutTargetElement = ref; }; public render(): JSX.Element { let diskIconColorClass = ''; if (this.props.diskInformation.filter((inf...
constructor
identifier_name
DisksInformation.tsx
import * as React from 'react'; import * as classNames from 'classnames'; import { IDisksInformationProps, IDisksInformationState } from './DisksInformation.Props'; import { Icon } from '../../Icon/Icon'; import { Callout } from '../../Callout'; import { ServerStatus, Partition } from '../../../models'; import { Direct...
private _calloutTargetElement: any; setCalloutTargetRef = (ref) => { this._calloutTargetElement = ref; }; public render(): JSX.Element { let diskIconColorClass = ''; if (this.props.diskInformation.filter((info) => { return info.status === ServerStatus.Critical; }).length > 0) { ...
{ super(props); this.state = { tooltipShow: false }; }
identifier_body
DisksInformation.tsx
import * as React from 'react'; import * as classNames from 'classnames'; import { IDisksInformationProps, IDisksInformationState } from './DisksInformation.Props'; import { Icon } from '../../Icon/Icon'; import { Callout } from '../../Callout'; import { ServerStatus, Partition } from '../../../models'; import { Direct...
else if (this.props.diskInformation.filter((info) => { return info.status === ServerStatus.Warning; }).length > 0) { diskIconColorClass = 'status-warning'; } let sortedDiskInfo = this.props.diskInformation.sort((disk1, disk2) => { return sortServersByStatusAndName( ...
{ diskIconColorClass = 'status-critical'; }
conditional_block
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/. */ //! Servo, the mighty web browser engine from the future. //! //! This is a very simple library that wires all of ...
(port: u16, constellation: Sender<ConstellationMsg>) { webdriver_server::start_server(port, constellation); } #[cfg(not(feature = "webdriver"))] fn webdriver(_port: u16, _constellation: Sender<ConstellationMsg>) { } use compositing::{CompositorProxy, IOCompositor}; use compositing::compositor_thread::InitialCompo...
webdriver
identifier_name
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/. */ //! Servo, the mighty web browser engine from the future. //! //! This is a very simple library that wires all of ...
pub fn request_title_for_main_frame(&self) { self.compositor.title_for_main_frame() } pub fn setup_logging(&self) { let constellation_chan = self.constellation_chan.clone(); log::set_logger(|max_log_level| { let env_logger = EnvLogger::new(); let con_logger...
{ self.compositor.pinch_zoom_level() }
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 http://mozilla.org/MPL/2.0/. */ //! Servo, the mighty web browser engine from the future. //! //! This is a very simple library that wires all of ...
use gaol::sandbox::{ChildSandbox, ChildSandboxMethods}; use gfx::font_cache_thread::FontCacheThread; use ipc_channel::ipc::{self, IpcSender}; use log::{Log, LogMetadata, LogRecord}; use net::bluetooth_thread::BluetoothThreadFactory; use net::image_cache_thread::new_image_cache_thread; use net::resource_thread::new_reso...
#[cfg(not(target_os = "windows"))] use constellation::content_process_sandbox_profile; use env_logger::Logger as EnvLogger; #[cfg(not(target_os = "windows"))]
random_line_split
types.rs
use crate::error::*; use std::fmt; use std::num::ParseFloatError; use std::str::FromStr; use std::string::ToString; #[derive(Debug, PartialEq, Clone)] pub struct Atom<T> { pub element: String, pub x: T, pub y: T, pub z: T, } impl<T> Atom<T> { pub fn new(element: &str, x: T, y: T, z: T) -> Self
} impl<T> FromStr for Atom<T> where T: FromStr<Err = ParseFloatError>, { type Err = Error; fn from_str(s: &str) -> Result<Self> { let splitted: Vec<&str> = s.split_whitespace().collect(); if splitted.len() != 4 { return Err(Error::IllegalState(String::from(""))); } ...
{ Atom { element: element.to_string(), x: x, y: y, z: z, } }
identifier_body
types.rs
use crate::error::*; use std::fmt; use std::num::ParseFloatError; use std::str::FromStr; use std::string::ToString; #[derive(Debug, PartialEq, Clone)] pub struct Atom<T> { pub element: String, pub x: T, pub y: T, pub z: T, } impl<T> Atom<T> { pub fn new(element: &str, x: T, y: T, z: T) -> Self { ...
Ok(Atom::new( splitted[0], splitted[1].parse()?, splitted[2].parse()?, splitted[3].parse()?, )) } } impl<T: fmt::Display> fmt::Display for Atom<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.elem...
{ return Err(Error::IllegalState(String::from(""))); }
conditional_block
types.rs
use crate::error::*; use std::fmt; use std::num::ParseFloatError; use std::str::FromStr; use std::string::ToString; #[derive(Debug, PartialEq, Clone)] pub struct Atom<T> { pub element: String, pub x: T, pub y: T, pub z: T, } impl<T> Atom<T> { pub fn new(element: &str, x: T, y: T, z: T) -> Self { ...
} }
C 10 11 12\n\ O 8.4 12.8 5\n\ H 23 9 11.8" );
random_line_split
types.rs
use crate::error::*; use std::fmt; use std::num::ParseFloatError; use std::str::FromStr; use std::string::ToString; #[derive(Debug, PartialEq, Clone)] pub struct Atom<T> { pub element: String, pub x: T, pub y: T, pub z: T, } impl<T> Atom<T> { pub fn new(element: &str, x: T, y: T, z: T) -> Self { ...
() { let snapshot = Snapshot { comment: "This is a comment".to_string(), atoms: vec![ Atom::new("C", 10.0, 11.0, 12.0), Atom::new("O", 8.4, 12.8, 5.0), Atom::new("H", 23.0, 9.0, 11.8), ], }; assert_eq!(3, snapsho...
test_snapshot
identifier_name
main.py
from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from keras.datasets import mnist, cifar10, cifar100 from sklearn.preprocessing import LabelBinarizer from nets import LeNet, LeNetVarDropout, VGG, VGGVarDropout sess = tf.Session() def main(): dataset ...
if dataset == 'mnist': (X_train, y_train), (X_test, y_test) = mnist.load_data() img_size = 28 num_classes = 10 num_channels = 1 elif dataset == 'cifar10': (X_train, y_train), (X_test, y_test) = cifar10.load_data() img_size = 32 num_classes = 10 num_channels = 3 elif dataset == 'cifar100': (X_train,...
# It will be downloaded first if necessary
random_line_split
main.py
from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from keras.datasets import mnist, cifar10, cifar100 from sklearn.preprocessing import LabelBinarizer from nets import LeNet, LeNetVarDropout, VGG, VGGVarDropout sess = tf.Session() def main():
if __name__ == "__main__": main()
dataset = 'cifar10' # mnist, cifar10, cifar100 # Load the data # It will be downloaded first if necessary if dataset == 'mnist': (X_train, y_train), (X_test, y_test) = mnist.load_data() img_size = 28 num_classes = 10 num_channels = 1 elif dataset == 'cifar10': (X_train, y_train), (X_test, y_test) = cifa...
identifier_body
main.py
from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from keras.datasets import mnist, cifar10, cifar100 from sklearn.preprocessing import LabelBinarizer from nets import LeNet, LeNetVarDropout, VGG, VGGVarDropout sess = tf.Session() def main(): dataset ...
main()
conditional_block
main.py
from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from keras.datasets import mnist, cifar10, cifar100 from sklearn.preprocessing import LabelBinarizer from nets import LeNet, LeNetVarDropout, VGG, VGGVarDropout sess = tf.Session() def
(): dataset = 'cifar10' # mnist, cifar10, cifar100 # Load the data # It will be downloaded first if necessary if dataset == 'mnist': (X_train, y_train), (X_test, y_test) = mnist.load_data() img_size = 28 num_classes = 10 num_channels = 1 elif dataset == 'cifar10': (X_train, y_train), (X_test, y_test) =...
main
identifier_name
schedule_topic_messages_and_cancellation.py
#!/usr/bin/env python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ---------------------------------------------...
if __name__ == "__main__": main()
servicebus_client = ServiceBusClient.from_connection_string( conn_str=CONNECTION_STR, logging_enable=True ) with servicebus_client: sender = servicebus_client.get_topic_sender(topic_name=TOPIC_NAME) with sender: sequence_number = schedule_single_message(sender) pr...
identifier_body
schedule_topic_messages_and_cancellation.py
#!/usr/bin/env python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ---------------------------------------------...
(sender): message = ServiceBusMessage("Message to be scheduled") scheduled_time_utc = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) sequence_number = sender.schedule_messages(message, scheduled_time_utc) return sequence_number def schedule_multiple_messages(sender): messages_to_sched...
schedule_single_message
identifier_name
schedule_topic_messages_and_cancellation.py
#!/usr/bin/env python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ---------------------------------------------...
main()
conditional_block
schedule_topic_messages_and_cancellation.py
#!/usr/bin/env python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ---------------------------------------------...
sender.cancel_scheduled_messages(sequence_number) sender.cancel_scheduled_messages(sequence_numbers) print("All scheduled messages are cancelled.") if __name__ == "__main__": main()
random_line_split
setup.py
from codecs import open from os import path from setuptools import setup, find_packages here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='serpy', version='0.3.1', description='ridiculously fast object ...
'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], keywords=('serialization', 'rest', 'json', 'api', 'marshal', ...
'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5',
random_line_split
conf.py
# -*- coding: utf-8 -*- # # libnacl documentation build configuration file, created by # sphinx-quickstart on Thu May 29 10:29:25 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
# If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If tru...
random_line_split
base-functions-proxies-node.ts
import { Site } from './../shared/models/arm/site'; import { ArmObj } from './../shared/models/arm/arm-obj'; import { BroadcastService } from './../shared/services/broadcast.service';
import { FunctionAppContext, FunctionsService } from './../shared/services/functions-service'; import { LogCategories } from './../shared/models/constants'; import { LogService } from './../shared/services/log.service'; import { DashboardType } from 'app/tree-view/models/dashboard-type'; import { EditModeHelper } from ...
random_line_split
base-functions-proxies-node.ts
import { Site } from './../shared/models/arm/site'; import { ArmObj } from './../shared/models/arm/arm-obj'; import { BroadcastService } from './../shared/services/broadcast.service'; import { FunctionAppContext, FunctionsService } from './../shared/services/functions-service'; import { LogCategories } from './../share...
(workingTitles: WorkingTitles, errorTitles: ErrorTitles): Observable<any> { return this.sideNav.cacheService.getArm(this._context.site.id) .map(i => i.json() as ArmObj<Site>) .concatMap(site => { if (site.properties.state === 'Running') { this.isLoadin...
baseLoadChildren
identifier_name
base-functions-proxies-node.ts
import { Site } from './../shared/models/arm/site'; import { ArmObj } from './../shared/models/arm/arm-obj'; import { BroadcastService } from './../shared/services/broadcast.service'; import { FunctionAppContext, FunctionsService } from './../shared/services/functions-service'; import { LogCategories } from './../share...
else if (!r.hasWritePermission) { this.disabledReason = this.sideNav.translateService.instant('You do not have write permissions to this app.') return this._updateTreeForNonUsableState(errorTitles.noAccessTitle); } else if (!r....
{ return this._updateTreeForStartedSite(workingTitles.readOnly.title, workingTitles.readOnly.newDashboard); }
conditional_block
base-functions-proxies-node.ts
import { Site } from './../shared/models/arm/site'; import { ArmObj } from './../shared/models/arm/arm-obj'; import { BroadcastService } from './../shared/services/broadcast.service'; import { FunctionAppContext, FunctionsService } from './../shared/services/functions-service'; import { LogCategories } from './../share...
public handleSelection(): Observable<any> { this.parent.inSelectedTree = true; return Observable.of({}); } }
{ return this.sideNav.cacheService.getArm(this._context.site.id) .map(i => i.json() as ArmObj<Site>) .concatMap(site => { if (site.properties.state === 'Running') { this.isLoading = true; return Observable.zip( ...
identifier_body
test_geopackage.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool by AusAid - **Clipper test suite.** Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation...
unittest.main()
conditional_block
test_geopackage.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool by AusAid - **Clipper test suite.** Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation...
# Create a geopackage from an empty file. path = QFileInfo(mktemp() + '.gpkg') self.assertFalse(path.exists()) data_store = GeoPackage(path) path.refresh() self.assertTrue(path.exists()) # Let's add a vector layer. layer_name = 'flood_test' layer ...
random_line_split
test_geopackage.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool by AusAid - **Clipper test suite.** Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation...
(self): pass def tearDown(self): pass @unittest.skipIf( int(gdal.VersionInfo('VERSION_NUM')) < 2000000, 'GDAL 2.0 is required for geopackage.') def test_create_geopackage(self): """Test if we can store geopackage.""" # Create a geopackage from an empty file...
setUp
identifier_name
test_geopackage.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool by AusAid - **Clipper test suite.** Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation...
@unittest.skipIf( int(gdal.VersionInfo('VERSION_NUM')) < 2000000, 'GDAL 2.0 is required for geopackage.') @expect_failure_in_windows(AssertionError) def test_read_existing_geopackage(self): """Test we can read an existing geopackage.""" path = standard_data_path('other', 'j...
"""Test if we can store geopackage.""" # Create a geopackage from an empty file. path = QFileInfo(mktemp() + '.gpkg') self.assertFalse(path.exists()) data_store = GeoPackage(path) path.refresh() self.assertTrue(path.exists()) # Let's add a vector layer. ...
identifier_body
test_util.py
# Copyright 2013-2014 MongoDB, Inc. # # 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 in writin...
(self): """Test bson_ts_to_long and long_to_bson_ts """ tstamp = timestamp.Timestamp(0x12345678, 0x90abcdef) self.assertEqual(0x1234567890abcdef, bson_ts_to_long(tstamp)) self.assertEqual(long_to_bson_ts(0x1234567890abcdef), tst...
test_bson_ts_to_long
identifier_name
test_util.py
# Copyright 2013-2014 MongoDB, Inc. # # 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 in writin...
self.assertEqual(long_to_bson_ts(0x1234567890abcdef), tstamp) def test_retry_until_ok(self): """Test retry_until_ok """ self.assertTrue(retry_until_ok(err_func)) self.assertEqual(err_func.counter, 3) if __name__ == '__main__': unittest.main()
tstamp = timestamp.Timestamp(0x12345678, 0x90abcdef) self.assertEqual(0x1234567890abcdef, bson_ts_to_long(tstamp))
random_line_split
test_util.py
# Copyright 2013-2014 MongoDB, Inc. # # 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 in writin...
def test_retry_until_ok(self): """Test retry_until_ok """ self.assertTrue(retry_until_ok(err_func)) self.assertEqual(err_func.counter, 3) if __name__ == '__main__': unittest.main()
"""Test bson_ts_to_long and long_to_bson_ts """ tstamp = timestamp.Timestamp(0x12345678, 0x90abcdef) self.assertEqual(0x1234567890abcdef, bson_ts_to_long(tstamp)) self.assertEqual(long_to_bson_ts(0x1234567890abcdef), tstamp)
identifier_body
test_util.py
# Copyright 2013-2014 MongoDB, Inc. # # 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 in writin...
err_func.counter = 0 class UtilTester(unittest.TestCase): """ Tests the utils """ def test_bson_ts_to_long(self): """Test bson_ts_to_long and long_to_bson_ts """ tstamp = timestamp.Timestamp(0x12345678, 0x90abcdef) self.assertEqual(0x1234567890abcdef, ...
raise TypeError
conditional_block
search-list.component.ts
import { Component } from '@angular/core'; import { ROUTER_DIRECTIVES,Route } from '@angular/router'; import { Song } from './song.model'; import { SearchPipe } from './search.pipe'; import { SongService } from './song-service.service'; @Component({ moduleId: module.id, selector: 'chord-search-list', templ...
}); }).catch(err => console.log(err)); } clearQuery() { this.query = ""; } }
{ this.songs.splice(index,1); }
conditional_block
search-list.component.ts
import { Component } from '@angular/core'; import { ROUTER_DIRECTIVES,Route } from '@angular/router'; import { Song } from './song.model'; import { SearchPipe } from './search.pipe'; import { SongService } from './song-service.service'; @Component({ moduleId: module.id, selector: 'chord-search-list', templ...
{ songs:Song[]; query:string; constructor(private songService:SongService) { this.songService.getAllSongs().then(result => this.songs = result).catch(err => console.log(err)); } onDelete(songId:string) { this.songService.deleteSong(songId).then(result => { ...
SearchListComponent
identifier_name
search-list.component.ts
import { Component } from '@angular/core'; import { ROUTER_DIRECTIVES,Route } from '@angular/router';
@Component({ moduleId: module.id, selector: 'chord-search-list', templateUrl: 'templates/search-list.component.html', styleUrls:['css/search-list.component.css'], providers:[SongService], directives:[ROUTER_DIRECTIVES], pipes:[SearchPipe] }) export class SearchListComponent { songs:Song[...
import { Song } from './song.model'; import { SearchPipe } from './search.pipe'; import { SongService } from './song-service.service';
random_line_split
dashboard.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../../services/auth.service'; import { Router } from '@angular/router'; import { UserActivity } from '../../model/user-activity'; import { Page } from '../../model/page'; @Component({ selector: 'app-dashboard', templateUrl: './dashboar...
(private authservice: AuthService, private router: Router, ) { this.page.pageNumber = 0; this.page.size = 5; /*console.log("p="+this.currentPage); this.getData(this.currentPage); this.authservice.getTotalActivities().subscribe(totalCount => { this.total = totalCount; this.maxSize ...
constructor
identifier_name
dashboard.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../../services/auth.service'; import { Router } from '@angular/router'; import { UserActivity } from '../../model/user-activity'; import { Page } from '../../model/page'; @Component({ selector: 'app-dashboard', templateUrl: './dashboar...
setPage(pageInfo) { this.page.pageNumber = pageInfo.offset; this.authservice.getTotalActivities().subscribe(totalCount => { this.page.totalElements = totalCount; this.page.totalPages = this.page.totalElements / this.page.size; //console.log('total=' + this.page.totalElements); //con...
{ this.setPage({ offset: 0 }); }
identifier_body
dashboard.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../../services/auth.service'; import { Router } from '@angular/router'; import { UserActivity } from '../../model/user-activity'; import { Page } from '../../model/page'; @Component({ selector: 'app-dashboard', templateUrl: './dashboar...
]; customClasses = this.page.customClasses; constructor(private authservice: AuthService, private router: Router, ) { this.page.pageNumber = 0; this.page.size = 5; /*console.log("p="+this.currentPage); this.getData(this.currentPage); this.authservice.getTotalActivities().subscribe(to...
{ name: 'Timestamp' }
random_line_split
dashboard.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../../services/auth.service'; import { Router } from '@angular/router'; import { UserActivity } from '../../model/user-activity'; import { Page } from '../../model/page'; @Component({ selector: 'app-dashboard', templateUrl: './dashboar...
this.rows = activities; //console.log(this.rows); }, err => { console.log(err); return false; }); } /*getData(page: Number) { this.activities = []; this.authservice.getActivitiesByPage(page, this.itemsPerPage).subscribe(activities => { console.log('acLen=' ...
{ this.activities.push(activities[i]); }
conditional_block
Search.test.js
import React from 'react'; import { shallow, mount } from 'enzyme'; import Search from '../lib/Components/Search'; describe('Search', () => { let wrapper; let mockFn; beforeEach(() => { mockFn = jest.fn(); wrapper = shallow(<Search getApi={mockFn} />); }); it('should exist', () => { expect(wra...
expect(wrapper.instance().trie).toEqual(expect.objectContaining({ root: expect.objectContaining({ letter: null, isWord: false, children: expect.objectContaining({}), }), })); }); });
expect(wrapper.instance().state.location).toEqual('a'); }); it('should create a new instance of Trie on mount', () => { wrapper.instance().componentDidMount();
random_line_split
age_calculator.py
from datetime import date def calculate_age(array): for i, val in enumerate(array): array[i] = int(val) born = date(array[2], array[1], array[0]) today = date.today() return today.year - born.year -\ ((today.month, today.day) < (born.month, born.day)) def find_splitter(text): for i, ...
age = calculate_age(inp) input('\n>>> Age = {0} years old'.format(age)) return age output = main()
inp[2] = int(this_cent[:len(this_cent) - len(inp[2])] + inp[2]) if inp[2] > int(this_year): inp[2] -= 100
conditional_block
age_calculator.py
from datetime import date def calculate_age(array): for i, val in enumerate(array): array[i] = int(val) born = date(array[2], array[1], array[0]) today = date.today() return today.year - born.year -\ ((today.month, today.day) < (born.month, born.day)) def find_splitter(text):
def main(): inp = input('Enter date/month/year: ') div = find_splitter(inp) inp = inp.split(div) this_year = date.today().strftime("%Y") this_cent = this_year[:2] + '00' init_year = inp[2] if len(inp[2]) < 4: inp[2] = int(this_cent[:len(this_cent) - len(inp[2])] + inp[2]) ...
for i, char in enumerate(text): try: int(char) except: return text[i] break
identifier_body
age_calculator.py
from datetime import date def calculate_age(array): for i, val in enumerate(array): array[i] = int(val) born = date(array[2], array[1], array[0]) today = date.today() return today.year - born.year -\ ((today.month, today.day) < (born.month, born.day)) def find_splitter(text):
for i, char in enumerate(text): try: int(char) except: return text[i] break def main(): inp = input('Enter date/month/year: ') div = find_splitter(inp) inp = inp.split(div) this_year = date.today().strftime("%Y") this_cent = this_year[:2] + '...
random_line_split
age_calculator.py
from datetime import date def calculate_age(array): for i, val in enumerate(array): array[i] = int(val) born = date(array[2], array[1], array[0]) today = date.today() return today.year - born.year -\ ((today.month, today.day) < (born.month, born.day)) def find_splitter(text): for i, ...
(): inp = input('Enter date/month/year: ') div = find_splitter(inp) inp = inp.split(div) this_year = date.today().strftime("%Y") this_cent = this_year[:2] + '00' init_year = inp[2] if len(inp[2]) < 4: inp[2] = int(this_cent[:len(this_cent) - len(inp[2])] + inp[2]) if inp[2] ...
main
identifier_name
sprite_sheet.py
""" A SpriteSheet is the overall collection of individual frames (which may be spread across files) that define one layer of the final sprite. """ from models.sprite_action import SpriteAction class
(): def __init__( self, data, group_name ): if "file_path" not in data: raise "file_path element missing in layer. Unable to load .spec file if we don't know which sheet you mean" self.file_path = data.get( "file_path" ) self.group_name = group_name self.name = data.get...
SpriteSheet
identifier_name
sprite_sheet.py
from models.sprite_action import SpriteAction class SpriteSheet(): def __init__( self, data, group_name ): if "file_path" not in data: raise "file_path element missing in layer. Unable to load .spec file if we don't know which sheet you mean" self.file_path = data.get( "file_path" ) ...
""" A SpriteSheet is the overall collection of individual frames (which may be spread across files) that define one layer of the final sprite. """
random_line_split
sprite_sheet.py
""" A SpriteSheet is the overall collection of individual frames (which may be spread across files) that define one layer of the final sprite. """ from models.sprite_action import SpriteAction class SpriteSheet(): def __init__( self, data, group_name ): if "file_path" not in data:
self.file_path = data.get( "file_path" ) self.group_name = group_name self.name = data.get( "name", "Unnamed Layer" ) self.layer = data.get( "layer", "Unspecified Layer" ) self.credit_name = data.get( "credit_name", "Unknown Artist" ) self.credit_url = data.get( "credit...
raise "file_path element missing in layer. Unable to load .spec file if we don't know which sheet you mean"
conditional_block
sprite_sheet.py
""" A SpriteSheet is the overall collection of individual frames (which may be spread across files) that define one layer of the final sprite. """ from models.sprite_action import SpriteAction class SpriteSheet():
def __init__( self, data, group_name ): if "file_path" not in data: raise "file_path element missing in layer. Unable to load .spec file if we don't know which sheet you mean" self.file_path = data.get( "file_path" ) self.group_name = group_name self.name = data.get( "name"...
identifier_body
public.js
import React from 'react'; import Rotate from './rotate'; import calcFill from './fill'; export default ({ fill = null,
light = false, disabled = false, direction = 'down', colors = {}, style = {}, ...rest }) => ( <Rotate direction={direction}> {({ style: rotateStyle }) => ( <svg viewBox="0 0 12 16" width="12" height="16" style={{ ...style, ...rotateStyle }} {...rest} ...
random_line_split
widget-preview.directive.js
/*! * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ /** * Usage: * <div piwik-widget-preview> */ (function () { angular.module('piwikApp').directive('piwikWidgetPreview', piwikWidgetPreview); piwikWidgetPreview.$...
(piwik, $window){ function getEmbedUrl(parameters, exportFormat) { var copyParameters = {}; for (var variableName in parameters) { copyParameters[variableName] = parameters[variableName]; } copyParameters['moduleToWidgetize'] = parameters['module'...
piwikWidgetPreview
identifier_name
widget-preview.directive.js
/*! * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ /** * Usage: * <div piwik-widget-preview> */ (function () { angular.module('piwikApp').directive('piwikWidgetPreview', piwikWidgetPreview); piwikWidgetPreview.$...
} })();
};
random_line_split
widget-preview.directive.js
/*! * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ /** * Usage: * <div piwik-widget-preview> */ (function () { angular.module('piwikApp').directive('piwikWidgetPreview', piwikWidgetPreview); piwikWidgetPreview.$...
})();
{ function getEmbedUrl(parameters, exportFormat) { var copyParameters = {}; for (var variableName in parameters) { copyParameters[variableName] = parameters[variableName]; } copyParameters['moduleToWidgetize'] = parameters['module']; c...
identifier_body
test.spec.js
'use strict'; var proxy = require('proxyquire'); var stubs = { googlemaps: jasmine.createSpyObj('googlemaps', ['staticMap']), request: jasmine.createSpy('request'), '@noCallThru': true }; describe('google-static-map', function() {
beforeEach(function() { uut = proxy('./index', stubs ); }); it('should not work without a api key', function() { expect( uut ).toThrow(new Error('You must provide a google api console key')); }); it('should provide a method to set a global api key', function() { expect( uut.set )...
var uut; describe('without auto-setting a key', function() {
random_line_split
jquery.tinysort.min.js
/** * jQuery plugin wrapper for TinySort * Does not use the first argument in tinysort.js since that is handled internally by the jQuery selector.
* @summary jQuery plugin wrapper for TinySort * @version 2.2.2 * @requires tinysort * @license MIT/GPL * @author Ron Valstar (http://www.sjeiti.com/) * @copyright Ron Valstar <ron@ronvalstar.nl> */ !function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery","tinysort"],a):jQuery&&!jQuery.fn....
* Sub-selections (option.selector) do not use the jQuery selector syntax but regular CSS3 selector syntax.
random_line_split
Tooltip.tsx
import { extend } from './Util' import * as React from 'react' import { ChartViewContext } from './ChartViewContext' import { observable, computed, runInAction } from 'mobx' import { observer } from 'mobx-react' import { Bounds } from './Bounds' export interface TooltipProps { x: number y: number, style?: ...
@computed get rendered() { const { bounds } = this const { chartView, chart } = this.context if (!chart.tooltip) return null const tooltip = chart.tooltip let x = tooltip.x as number let y = tooltip.y as number // Ensure tooltip remains inside chart ...
export class TooltipView extends React.Component { static contextType = ChartViewContext
random_line_split
mootools.more.js
// MooTools: the javascript framework. // Load this file's selection again by visiting: http://mootools.net/more/f0c28d76aff2f0ba12270c81dc5e8d18 // Or build this file again with packager using: packager build More/Assets More/Hash.Cookie /* --- script: More.js name: More description: MooTools More license: MIT-st...
filter: function(fn, bind){ return new Hash(Object.filter(this, fn, bind)); }, every: function(fn, bind){ return Object.every(this, fn, bind); }, some: function(fn, bind){ return Object.some(this, fn, bind); }, getKeys: function(){ return Object.keys(this); }, getValues: function(){ return Objec...
map: function(fn, bind){ return new Hash(Object.map(this, fn, bind)); },
random_line_split
15.2.3.6-3-195.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyrigh...
() { var obj = {}; Object.defineProperty(obj, "property", { writable: Math }); var beforeWrite = obj.hasOwnProperty("property"); obj.property = "isWritable"; var afterWrite = (obj.property === "isWritable"); return beforeWrite === true && afterWrite === tr...
testcase
identifier_name
15.2.3.6-3-195.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyrigh...
var beforeWrite = obj.hasOwnProperty("property"); obj.property = "isWritable"; var afterWrite = (obj.property === "isWritable"); return beforeWrite === true && afterWrite === true; } runTestCase(testcase);
function testcase() { var obj = {}; Object.defineProperty(obj, "property", { writable: Math });
random_line_split
15.2.3.6-3-195.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyrigh...
runTestCase(testcase);
{ var obj = {}; Object.defineProperty(obj, "property", { writable: Math }); var beforeWrite = obj.hasOwnProperty("property"); obj.property = "isWritable"; var afterWrite = (obj.property === "isWritable"); return beforeWrite === true && afterWrite === true;...
identifier_body
build_record_set_singleton.py
# coding: utf-8 """ Copyright 2015 SmartBear Software 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 `print` and `pprint` """ return self.to_str()
__repr__
identifier_name
build_record_set_singleton.py
# coding: utf-8 """ Copyright 2015 SmartBear Software 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...
return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str()
result[attr] = value
conditional_block
build_record_set_singleton.py
# coding: utf-8 """ Copyright 2015 SmartBear Software 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.attribute_map = { 'content': 'content' } self._content = None @property def content(self): """ Gets the content of this BuildRecordSetSingleton. :return: The content of this BuildRecordSetSingleton. :rtype: BuildRecordSetRest "...
""" self.swagger_types = { 'content': 'BuildRecordSetRest' }
random_line_split
build_record_set_singleton.py
# coding: utf-8 """ Copyright 2015 SmartBear Software 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...
""" For `print` and `pprint` """ return self.to_str()
identifier_body
gitRepository.py
#!/usr/bin/env python # This file should be compatible with both Python 2 and 3. # If it is not, please file a bug report. """ This is a Class which allows one to manipulate a git repository. """ #external imports import os import tempfile #internal imports import subuserlib.subprocessExtras as subprocessExtras from ...
if subfolder == "/": subfolder = "./" (returncode,output) = self.getRepository().runCollectOutput(["ls-tree"]+extraArgs+[self.getCommit(),subfolder]) if returncode != 0: return [] # This commenting out is intentional. It is simpler to just return [] here than to check if the repository is prope...
subfolder += "/"
conditional_block
gitRepository.py
#!/usr/bin/env python # This file should be compatible with both Python 2 and 3. # If it is not, please file a bug report. """ This is a Class which allows one to manipulate a git repository. """ #external imports import os import tempfile #internal imports import subuserlib.subprocessExtras as subprocessExtras from ...
>>> gitRepository = GitRepository("/home/travis/hashtest") >>> fileStructure = gitRepository.getFileStructureAtCommit("master") >>> print(",".join(fileStructure.ls("./"))) bar,blah """ items = self.lsTree(subfolder,extraArgs) paths = [] for item in items: paths.append(item[3]) ...
>>> from subuserlib.classes.gitRepository import GitRepository
random_line_split
gitRepository.py
#!/usr/bin/env python # This file should be compatible with both Python 2 and 3. # If it is not, please file a bug report. """ This is a Class which allows one to manipulate a git repository. """ #external imports import os import tempfile #internal imports import subuserlib.subprocessExtras as subprocessExtras from ...
class GitFileStructure(FileStructure): def __init__(self,gitRepository,commit): """ Initialize the file structure. Here we setup test stuff: >>> import subuserlib.subprocessExtras >>> subuserlib.subprocessExtras.call(["git","init"],cwd="/home/travis/hashtest") 0 >>> subuserlib.subproces...
def __init__(self,path): self.__path = path def getPath(self): return self.__path def run(self,args): """ Run git with the given command line arguments. """ return subprocessExtras.call(["git"]+args,cwd=self.getPath()) def runCollectOutput(self,args): """ Run git with the given ...
identifier_body
gitRepository.py
#!/usr/bin/env python # This file should be compatible with both Python 2 and 3. # If it is not, please file a bug report. """ This is a Class which allows one to manipulate a git repository. """ #external imports import os import tempfile #internal imports import subuserlib.subprocessExtras as subprocessExtras from ...
(self,gitRepository,commit): """ Initialize the file structure. Here we setup test stuff: >>> import subuserlib.subprocessExtras >>> subuserlib.subprocessExtras.call(["git","init"],cwd="/home/travis/hashtest") 0 >>> subuserlib.subprocessExtras.call(["git","add","."],cwd="/home/travis/hashte...
__init__
identifier_name
CookieNotice.tsx
import * as React from "react" import { useEffect, useState } from "react" import classnames from "classnames" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import { faCheck } from "@fortawesome/free-solid-svg-icons/faCheck" import { Action, getTodayDate } from "./CookiePreferencesManager" export co...
className="button accept" onClick={() => dispatch({ type: Action.Accept, payload: { date: getTodayDate() }, }) ...
<div className="owid-col owid-col--lg-0 actions"> <a href="/privacy-policy" className="button"> Manage preferences </a> <button
random_line_split
ResourcePickerPopover.tsx
import React, { createRef, useState } from 'react'; import { css } from '@emotion/css'; import { Button, ButtonGroup, useStyles2 } from '@grafana/ui'; import { GrafanaTheme2 } from '@grafana/data'; import { FocusScope } from '@react-aria/focus'; import { useDialog } from '@react-aria/dialog'; import { useOverlay } from...
<FocusScope contain autoFocus restoreFocus> <section ref={ref} {...overlayProps} {...dialogProps}> <div className={styles.resourcePickerPopover}> <div className={styles.resourcePickerPopoverTabs}> <button className={getTabClassName(PickerTabType.Folder)} ...
} }; return (
random_line_split
ResourcePickerPopover.tsx
import React, { createRef, useState } from 'react'; import { css } from '@emotion/css'; import { Button, ButtonGroup, useStyles2 } from '@grafana/ui'; import { GrafanaTheme2 } from '@grafana/data'; import { FocusScope } from '@react-aria/focus'; import { useDialog } from '@react-aria/dialog'; import { useOverlay } from...
(PickerTabType.URL)} onClick={() => setActivePicker(PickerTabType.URL)}> URL </button> </div> <div className={styles.resourcePickerPopoverContent}> {renderPicker()} <ButtonGroup className={styles.buttonGroup}> <Button className={styles....
getTabClassName
identifier_name
ResourcePickerPopover.tsx
import React, { createRef, useState } from 'react'; import { css } from '@emotion/css'; import { Button, ButtonGroup, useStyles2 } from '@grafana/ui'; import { GrafanaTheme2 } from '@grafana/data'; import { FocusScope } from '@react-aria/focus'; import { useDialog } from '@react-aria/dialog'; import { useOverlay } from...
> URL </button> </div> <div className={styles.resourcePickerPopoverContent}> {renderPicker()} <ButtonGroup className={styles.buttonGroup}> <Button className={styles.button} variant={'secondary'} onClick={() => onClose()}> ...
{() => setActivePicker(PickerTabType.URL)}
identifier_body
cargo_clean.rs
use std::default::Default; use std::fs; use std::io::prelude::*; use std::path::Path; use core::{Package, PackageSet, Profiles}; use core::source::{Source, SourceMap}; use core::registry::PackageRegistry; use util::{CargoResult, human, ChainError, Config}; use ops::{self, Layout, Context, BuildConfig, Kind, Unit}; pu...
<'a> { pub spec: &'a [String], pub target: Option<&'a str>, pub config: &'a Config, pub release: bool, } /// Cleans the project from build artifacts. pub fn clean(manifest_path: &Path, opts: &CleanOptions) -> CargoResult<()> { let root = try!(Package::for_path(manifest_path, opts.config)); let ...
CleanOptions
identifier_name
cargo_clean.rs
use std::default::Default; use std::fs; use std::io::prelude::*; use std::path::Path; use core::{Package, PackageSet, Profiles}; use core::source::{Source, SourceMap}; use core::registry::PackageRegistry; use util::{CargoResult, human, ChainError, Config}; use ops::{self, Layout, Context, BuildConfig, Kind, Unit}; pu...
{ let m = fs::metadata(path); if m.as_ref().map(|s| s.is_dir()).unwrap_or(false) { try!(fs::remove_dir_all(path).chain_error(|| { human("could not remove build directory") })); } else if m.is_ok() { try!(fs::remove_file(path).chain_error(|| { human("failed to ...
identifier_body
cargo_clean.rs
use std::default::Default; use std::fs; use std::io::prelude::*; use std::path::Path; use core::{Package, PackageSet, Profiles}; use core::source::{Source, SourceMap}; use core::registry::PackageRegistry; use util::{CargoResult, human, ChainError, Config}; use ops::{self, Layout, Context, BuildConfig, Kind, Unit}; pu...
human("failed to remove build artifact") })); } Ok(()) }
})); } else if m.is_ok() { try!(fs::remove_file(path).chain_error(|| {
random_line_split
http-parser.js
'use strict'; var cheerio = require( 'cheerio' ); function isJsonString( data ) { try { JSON.parse( data ); } catch (e) { return false; } return true; } function parseArticles( html ) { var el = cheerio.load( html || '' ); var articles = el( 'article.badge-entry-container' );...
return articleList; } module.exports = { /** * Method responsible for parse given data. This data should be a stringified JSON or HTML. * * @param {String} * @return {Object} */ parse: parse };
{ articleList = parseArticles( dataToParse ); }
conditional_block
http-parser.js
'use strict'; var cheerio = require( 'cheerio' ); function isJsonString( data ) { try { JSON.parse( data ); } catch (e) { return false; } return true; } function parseArticles( html ) { var el = cheerio.load( html || '' ); var articles = el( 'article.badge-entry-container' );...
function parse( dataToParse ) { var articleList = []; if ( typeof dataToParse === 'object' ) { articleList = getArticlesFromObject( dataToParse ); } else { articleList = parseArticles( dataToParse ); } return articleList; } module.exports = { /** * Method responsible fo...
{ data = data.items || {}; return Object.keys( data ).map( function getItemHtml( itemId ) { return data[itemId]; }) || []; }
identifier_body
http-parser.js
'use strict'; var cheerio = require( 'cheerio' ); function isJsonString( data ) { try { JSON.parse( data ); } catch (e) { return false; } return true; } function
( html ) { var el = cheerio.load( html || '' ); var articles = el( 'article.badge-entry-container' ); var result = []; result = ( Object.keys( articles ) ).map( function getItemHtml( key ) { return !isNaN( key ) ? el.html( articles[key] ) : null; } ) || []; return result.filter( functi...
parseArticles
identifier_name
http-parser.js
'use strict'; var cheerio = require( 'cheerio' ); function isJsonString( data ) { try { JSON.parse( data ); } catch (e) { return false; } return true; } function parseArticles( html ) { var el = cheerio.load( html || '' ); var articles = el( 'article.badge-entry-container' );...
return data[itemId]; }) || []; } function parse( dataToParse ) { var articleList = []; if ( typeof dataToParse === 'object' ) { articleList = getArticlesFromObject( dataToParse ); } else { articleList = parseArticles( dataToParse ); } return articleList; } module.expo...
data = data.items || {}; return Object.keys( data ).map( function getItemHtml( itemId ) {
random_line_split
dbc.py
import re import os import struct import sys import numbers from collections import namedtuple, defaultdict def int_or_float(s): # return number, trying to maintain int format if s.isdigit(): return int(s, 10) else: return float(s) DBCSignal = namedtuple( "DBCSignal", ["name", "start_bit", "size", "i...
(self, msg_id, dd): """Encode a CAN message using the dbc. Inputs: msg_id: The message ID. dd: A dictionary mapping signal name to signal data. """ msg_id = self.lookup_msg_id(msg_id) msg_def = self.msgs[msg_id] size = msg_def[0][1] result = 0 for s in msg_def[1]: ...
encode
identifier_name
dbc.py
import re import os import struct import sys import numbers from collections import namedtuple, defaultdict def int_or_float(s): # return number, trying to maintain int format if s.isdigit(): return int(s, 10) else: return float(s) DBCSignal = namedtuple( "DBCSignal", ["name", "start_bit", "size", "i...
result = struct.pack('>Q', result) return result[:size] def decode(self, x, arr=None, debug=False): """Decode a CAN message using the dbc. Inputs: x: A collection with elements (address, time, data), where address is the CAN address, time is the bus time, and data is the CAN ...
ival = (ival / s.factor) - s.offset ival = int(round(ival)) if s.is_signed and ival < 0: ival = (1 << s.size) + ival if s.is_little_endian: shift = s.start_bit else: b1 = (s.start_bit // 8) * 8 + (-s.start_bit - 1) % 8 shift = 64 - (b1 + s.size) ...
conditional_block
dbc.py
import re
import sys import numbers from collections import namedtuple, defaultdict def int_or_float(s): # return number, trying to maintain int format if s.isdigit(): return int(s, 10) else: return float(s) DBCSignal = namedtuple( "DBCSignal", ["name", "start_bit", "size", "is_little_endian", "is_signed", ...
import os import struct
random_line_split
dbc.py
import re import os import struct import sys import numbers from collections import namedtuple, defaultdict def int_or_float(s): # return number, trying to maintain int format if s.isdigit(): return int(s, 10) else: return float(s) DBCSignal = namedtuple( "DBCSignal", ["name", "start_bit", "size", "i...
if __name__ == "__main__": from opendbc import DBC_PATH dbc_test = dbc(os.path.join(DBC_PATH, 'toyota_prius_2017_pt_generated.dbc')) msg = ('STEER_ANGLE_SENSOR', {'STEER_ANGLE': -6.0, 'STEER_RATE': 4, 'STEER_FRACTION': -0.2}) encoded = dbc_test.encode(*msg) decoded = dbc_test.decode((0x25, 0, encoded...
msg = self.lookup_msg_id(msg) return [sgs.name for sgs in self.msgs[msg][1]]
identifier_body
types.rs
//! Exports Rust counterparts for all the common GLSL types, along with a few marker traits use rasen::prelude::{Dim, TypeName}; use std::ops::{Add, Div, Index, Mul, Rem, Sub}; use crate::{ context::{Container, Context}, value::{IntoValue, Value}, }; pub trait AsTypeName { const TYPE_NAME: &'static Type...
<V>(pub V); impl<V: Vector> AsTypeName for Sampler<V> where <V as Vector>::Scalar: AsTypeName, { const TYPE_NAME: &'static TypeName = &TypeName::Sampler(<<V as Vector>::Scalar as AsTypeName>::TYPE_NAME, Dim::Dim2D); }
Sampler
identifier_name
types.rs
//! Exports Rust counterparts for all the common GLSL types, along with a few marker traits use rasen::prelude::{Dim, TypeName}; use std::ops::{Add, Div, Index, Mul, Rem, Sub}; use crate::{ context::{Container, Context}, value::{IntoValue, Value}, }; pub trait AsTypeName { const TYPE_NAME: &'static Type...
} pub trait Vector3: Vector { fn cross(&self, rhs: &Self) -> Self; } pub trait Matrix { fn inverse(self) -> Self; } include!(concat!(env!("OUT_DIR"), "/types.rs")); #[derive(Copy, Clone, Debug)] pub struct Sampler<V>(pub V); impl<V: Vector> AsTypeName for Sampler<V> where <V as Vector>::Scalar: AsType...
{ self.length_squared().sqrt() }
identifier_body