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
index.ts
/** * @license * Copyright (c) 2019 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors ma...
{ main(); }
conditional_block
13.5.4.9.js
/* -*- Mode: javascript; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * 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/. */ gTestfile = '13.5.4.9.js'; ...
var gods = <gods> <god> <name>Kibo</name> </god> <god> <name>Xibo</name> </god> </gods>; var godList = gods.god; var expect; var actual; var node; var descendants = godList.descendants(); expect = 4; actual = descendants.length(); TEST(2, expect, actual) expect = 'nodeKind(): element, name(): name;\...
// From Martin Honnen
random_line_split
parseXML.js
/* * Copyright (c) 2015-2016 Fraunhofer FOKUS * * 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...
return xml; }; return jQuery.parseXML; });
{ jQuery.error( "Invalid XML: " + data ); }
conditional_block
parseXML.js
/* * Copyright (c) 2015-2016 Fraunhofer FOKUS * * 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...
jQuery.error( "Invalid XML: " + data ); } return xml; }; return jQuery.parseXML; });
} if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
random_line_split
CommandPage.ts
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { ActivatedRoute } from '@angular/router'; import { BehaviorSubject } from 'rxjs';
templateUrl: './CommandPage.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class CommandPage { command$ = new BehaviorSubject<Command | null>(null); constructor( route: ActivatedRoute, readonly yamcs: YamcsService, private title: Title, ) { // When clicking links pointing ...
import { Command } from '../../client'; import { YamcsService } from '../../core/services/YamcsService'; @Component({
random_line_split
CommandPage.ts
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { ActivatedRoute } from '@angular/router'; import { BehaviorSubject } from 'rxjs'; import { Command } from '../../client'; import { YamcsService } from '../../core/services/YamcsService'; @Comp...
}
{ this.yamcs.yamcsClient.getCommand(this.yamcs.instance!, qualifiedName).then(command => { this.command$.next(command); this.title.setTitle(command.name); }); }
identifier_body
CommandPage.ts
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { ActivatedRoute } from '@angular/router'; import { BehaviorSubject } from 'rxjs'; import { Command } from '../../client'; import { YamcsService } from '../../core/services/YamcsService'; @Comp...
{ command$ = new BehaviorSubject<Command | null>(null); constructor( route: ActivatedRoute, readonly yamcs: YamcsService, private title: Title, ) { // When clicking links pointing to this same component, Angular will not reinstantiate // the component. Therefore subscribe to routeParams ...
CommandPage
identifier_name
GSTTools.py
''' Various tools to interface with pyGSTi for running GST experiments. Created on May 16, 2018 Original Author: Guilhem Ribeill Copyright 2018 Raytheon BBN Technologies 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 ...
qgl_seqs = [] for seq in seqs: qgl_seqs.append([clifford_pulse[c] for c in seq]) qgl_seqs[-1].append(MEAS(qubit)) if num_cals != 0: qgl_seqs += create_cal_seqs((qubit, ), abs(num_cals)) metafile = compile_to_hardware(qgl_seqs, 'GST/GST') return metafile
seqs = pygsti_to_cliffords(pygsti_seq)
random_line_split
GSTTools.py
''' Various tools to interface with pyGSTi for running GST experiments. Created on May 16, 2018 Original Author: Guilhem Ribeill Copyright 2018 Raytheon BBN Technologies 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 ...
def pygsti_to_cliffords(gst_seq): #Map from GST convention to cliffords cliff_map = {"{}": 0, "Gi": 1, "Gx": 2, "Gy": 5} #convert to dictionary of lambdas for compatibility with gst_map_1Q lambda_map = {k: lambda x, v=v: v for k, v in cliff_map.items...
""" Returns list of QGL sequences from a pyGSTi GateString list. See gst_map_1Q. The return value is a list of sequences that can be complied by QGL. """ return list(gst_map_1Q(gst_list, qubit, qgl_map=gate_map, append_meas=True))
identifier_body
GSTTools.py
''' Various tools to interface with pyGSTi for running GST experiments. Created on May 16, 2018 Original Author: Guilhem Ribeill Copyright 2018 Raytheon BBN Technologies 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 ...
else: rand_pauli = choices(c_ps, k=len(seq)) inter = 0 bare = 0 rseq = [] for j in range(len(seq)): inter = clifford_multiply(clifford_multiply(inter, rand_pauli[j]), seq[j]) bare = clifford_multiply(bare, seq[j]) ...
r_seqs.append([])
conditional_block
GSTTools.py
''' Various tools to interface with pyGSTi for running GST experiments. Created on May 16, 2018 Original Author: Guilhem Ribeill Copyright 2018 Raytheon BBN Technologies 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 ...
(gst_list, qubit, qgl_map=gst_gate_map, append_meas=True): """ Helper function that takes an arbitrarily nested list of pygsti gatestrings and converts them into QGL sequences, keeping the same nesting of lists. Inputs: gst_list: GateString to convert, or possibly nested list of pyGSTi GateStri...
gst_map_1Q
identifier_name
database_setup.rs
use support::{database, project}; #[test] fn
() { let p = project("database_setup_creates_database") .folder("migrations") .build(); let db = database(&p.database_url()); // sanity check assert!(!db.exists()); let result = p.command("database") .arg("setup") .run(); assert!(result.is_success(), "Result w...
database_setup_creates_database
identifier_name
database_setup.rs
use support::{database, project}; #[test] fn database_setup_creates_database() { let p = project("database_setup_creates_database") .folder("migrations") .build(); let db = database(&p.database_url()); // sanity check assert!(!db.exists()); let result = p.command("database") ...
.arg("setup") .run(); assert!(result.is_success(), "Result was unsuccessful {:?}", result); assert!(result.stdout().contains("Running migration 12345"), "Unexpected stdout {}", result.stdout()); assert!(db.table_exists("users")); }
// sanity check assert!(!db.exists()); let result = p.command("database")
random_line_split
database_setup.rs
use support::{database, project}; #[test] fn database_setup_creates_database()
#[test] fn database_setup_creates_schema_table () { let p = project("database_setup_creates_schema_table") .folder("migrations") .build(); let db = database(&p.database_url()); // sanity check assert!(!db.exists()); let result = p.command("database") .arg("setup") ...
{ let p = project("database_setup_creates_database") .folder("migrations") .build(); let db = database(&p.database_url()); // sanity check assert!(!db.exists()); let result = p.command("database") .arg("setup") .run(); assert!(result.is_success(), "Result was ...
identifier_body
condvar.rs
use crate::cell::UnsafeCell; use crate::sys::mutex::{self, Mutex}; use crate::time::Duration; pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t>, } pub type MovableCondvar = Box<Condvar>; unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} const TIMESPEC_MAX: libc::timespec = libc::tim...
(value: u64) -> libc::time_t { if value > <libc::time_t>::MAX as u64 { <libc::time_t>::MAX } else { value as libc::time_t } } impl Condvar { pub const fn new() -> Condvar { // Might be moved and address is changing it is better to avoid // initialization of potentially opaque OS data before it ...
saturating_cast_to_time_t
identifier_name
condvar.rs
use crate::cell::UnsafeCell; use crate::sys::mutex::{self, Mutex}; use crate::time::Duration; pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t>, } pub type MovableCondvar = Box<Condvar>; unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} const TIMESPEC_MAX: libc::timespec = libc::tim...
sec.map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec as _ }).unwrap_or(TIMESPEC_MAX); let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout); assert!(r == libc::ETIMEDOUT || r == 0); r == 0 } // This implementation is modeled after libcxx's con...
random_line_split
condvar.rs
use crate::cell::UnsafeCell; use crate::sys::mutex::{self, Mutex}; use crate::time::Duration; pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t>, } pub type MovableCondvar = Box<Condvar>; unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} const TIMESPEC_MAX: libc::timespec = libc::tim...
#[cfg(any( target_os = "macos", target_os = "ios", target_os = "l4re", target_os = "android", target_os = "redox" ))] pub unsafe fn init(&mut self) {} // NOTE: ESP-IDF's PTHREAD_COND_INITIALIZER support is not released yet // So on that platform, init() sho...
{ // Might be moved and address is changing it is better to avoid // initialization of potentially opaque OS data before it landed Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) } }
identifier_body
condvar.rs
use crate::cell::UnsafeCell; use crate::sys::mutex::{self, Mutex}; use crate::time::Duration; pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t>, } pub type MovableCondvar = Box<Condvar>; unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} const TIMESPEC_MAX: libc::timespec = libc::tim...
// First, figure out what time it currently is, in both system and // stable time. pthread_cond_timedwait uses system time, but we want to // report timeout based on stable time. let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 }; let stable_now = Instant::now(); ...
{ // OSX implementation of `pthread_cond_timedwait` is buggy // with super long durations. When duration is greater than // 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait` // in macOS Sierra return error 316. // // This program demonstrates ...
conditional_block
matisse.py
#!/usr/bin/env python """ MaTiSSe.py, Markdown To Impressive Scientific Slides """ from __future__ import print_function import argparse import os import sys from matisse_config import MatisseConfig from presentation import Presentation __appname__ = "MaTiSSe.py" __description__ = "MaTiSSe.py, Markdown To Impressive S...
cliparser.add_argument('--print-highlight-styles', required=False, action='store_true', default=None, help='Print the available highlight.js style (default github.css)') cliparser.add_argument('--print-themes', required=False, action='store_true', default=None, help='Print the list of the builtin themes') clipars...
cliparser.add_argument('--toc-at-subsec-beginning', required=False, action='store', default=None, help='Insert Table of Contents at each subsection beginning (default no): to activate indicate the TOC depth', metavar='TOC-DEPTH') cliparser.add_argument('--print-preamble', required=False, action='store_true', defaul...
random_line_split
matisse.py
#!/usr/bin/env python """ MaTiSSe.py, Markdown To Impressive Scientific Slides """ from __future__ import print_function import argparse import os import sys from matisse_config import MatisseConfig from presentation import Presentation __appname__ = "MaTiSSe.py" __description__ = "MaTiSSe.py, Markdown To Impressive S...
(): """Main function.""" cliparser = argparse.ArgumentParser(prog=__appname__, description='MaTiSSe.py, Markdown To Impressive Scientific Slides') cliparser.add_argument('-v', '--version', action='version', help='Show version', version='%(prog)s ' + __version__) cliparser.add_argument('-i', '--input', required=...
main
identifier_name
matisse.py
#!/usr/bin/env python """ MaTiSSe.py, Markdown To Impressive Scientific Slides """ from __future__ import print_function import argparse import os import sys from matisse_config import MatisseConfig from presentation import Presentation __appname__ = "MaTiSSe.py" __description__ = "MaTiSSe.py, Markdown To Impressive S...
if __name__ == '__main__': main()
if not os.path.exists(cliargs.input): sys.stderr.write('Error: input file "' + cliargs.input + '" not found!') sys.exit(1) else: with open(cliargs.input, 'r') as mdf: source = mdf.read() presentation = Presentation() if config.verbose: print('Parsing source ' + cliargs....
conditional_block
matisse.py
#!/usr/bin/env python """ MaTiSSe.py, Markdown To Impressive Scientific Slides """ from __future__ import print_function import argparse import os import sys from matisse_config import MatisseConfig from presentation import Presentation __appname__ = "MaTiSSe.py" __description__ = "MaTiSSe.py, Markdown To Impressive S...
if cliargs.input: if not os.path.exists(cliargs.input): sys.stderr.write('Error: input file "' + cliargs.input + '" not found!') sys.exit(1) else: with open(cliargs.input, 'r') as mdf: source = mdf.read() presentation = Presentation() if config.verbose: print('Par...
"""Main function.""" cliparser = argparse.ArgumentParser(prog=__appname__, description='MaTiSSe.py, Markdown To Impressive Scientific Slides') cliparser.add_argument('-v', '--version', action='version', help='Show version', version='%(prog)s ' + __version__) cliparser.add_argument('-i', '--input', required=False,...
identifier_body
015-M-3Sum.py
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets # in the array which gives the sum of zero. # # Note: The solution set must not contain duplicate triplets. # # For example, given array S = [-1, 0, 1, 2, -1, -4], # # A solution set is: # [ # [-1, 0, 1...
while l < r: s = nums[i] + nums[l] + nums[r] if s < 0: l += 1 elif s > 0: r -= 1 else: res.append((nums[i], nums[l], nums[r])) while l < r and nums[l] == nums[l + 1...
l, r = i + 1, len(nums) - 1
random_line_split
015-M-3Sum.py
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets # in the array which gives the sum of zero. # # Note: The solution set must not contain duplicate triplets. # # For example, given array S = [-1, 0, 1, 2, -1, -4], # # A solution set is: # [ # [-1, 0, 1...
l += 1 r -= 1 return res # Note: # Iterating through the list with the pointer i and then we try to find two extra numbers to sum to 0. # Since the list is ordered, the right pointer will always be higher than the left pointer. # So if the sum is too large, you can move...
r -= 1
conditional_block
015-M-3Sum.py
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets # in the array which gives the sum of zero. # # Note: The solution set must not contain duplicate triplets. # # For example, given array S = [-1, 0, 1, 2, -1, -4], # # A solution set is: # [ # [-1, 0, 1...
while l < r and nums[r] == nums[r - 1]: r -= 1 l += 1 r -= 1 return res # Note: # Iterating through the list with the pointer i and then we try to find two extra numbers to sum to 0. # Since the list is ordered, the right poin...
""" :type nums: List[int] :rtype: List[List[int]] """ res = [] nums.sort() for i in xrange(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue l, r = i + 1, len(nums) - 1 while l < r: s = nums[i...
identifier_body
015-M-3Sum.py
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets # in the array which gives the sum of zero. # # Note: The solution set must not contain duplicate triplets. # # For example, given array S = [-1, 0, 1, 2, -1, -4], # # A solution set is: # [ # [-1, 0, 1...
(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] nums.sort() for i in xrange(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue l, r = i + 1, len(nums) - 1 while l < r: ...
threeSum
identifier_name
sqoop_properties.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
data = "" return dict([line.split('=', 1) for line in data.split('\n') if '=' in line and not line.startswith('#')])
LOG.error('Cannot read from "%s": %s' % (site_path, err)) return
conditional_block
sqoop_properties.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
def has_sqoop_has_security(): return get_props().get(_CONF_SQOOP_AUTHENTICATION_TYPE, 'SIMPLE').upper() == 'KERBEROS' def _parse_properties(): global _PROPERTIES_DICT properties_file = os.path.join(SQOOP_CONF_DIR.get(), 'sqoop.properties') _PROPERTIES_DICT = _parse_site(properties_file) def _parse_site...
if _PROPERTIES_DICT is None: _parse_properties() return _PROPERTIES_DICT
identifier_body
sqoop_properties.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
(): return get_props().get(_CONF_SQOOP_AUTHENTICATION_TYPE, 'SIMPLE').upper() == 'KERBEROS' def _parse_properties(): global _PROPERTIES_DICT properties_file = os.path.join(SQOOP_CONF_DIR.get(), 'sqoop.properties') _PROPERTIES_DICT = _parse_site(properties_file) def _parse_site(site_path): try: with ...
has_sqoop_has_security
identifier_name
sqoop_properties.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
def _parse_properties(): global _PROPERTIES_DICT properties_file = os.path.join(SQOOP_CONF_DIR.get(), 'sqoop.properties') _PROPERTIES_DICT = _parse_site(properties_file) def _parse_site(site_path): try: with open(site_path, 'r') as f: data = f.read() except IOError as err: if err.errno != ...
def has_sqoop_has_security(): return get_props().get(_CONF_SQOOP_AUTHENTICATION_TYPE, 'SIMPLE').upper() == 'KERBEROS'
random_line_split
twitter.py
from __future__ import division __author__ = 'saeedamen' # Saeed Amen # # Copyright 2016 Cuemacro # # 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 # ...
if picture is None: self.twitter.update_status(status=msg) else: photo = open(picture, 'rb') response = self.twitter.upload_media(media=photo) self.twitter.update_status(status=msg, media_ids=[response['media_id']])
if (len(msg) > chars_lim): return None
random_line_split
twitter.py
from __future__ import division __author__ = 'saeedamen' # Saeed Amen # # Copyright 2016 Cuemacro # # 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 # ...
if (len(msg) > chars_lim): return None if picture is None: self.twitter.update_status(status=msg) else: photo = open(picture, 'rb') response = self.twitter.upload_media(media=photo) self.twitter.update_status(status=msg, media_ids=[r...
chars_lim = chars_lim - 23
conditional_block
twitter.py
from __future__ import division __author__ = 'saeedamen' # Saeed Amen # # Copyright 2016 Cuemacro # # 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 # ...
chars_lim = 140 if link is not None: chars_lim = chars_lim - (22 * link) if picture is not None: chars_lim = chars_lim - 23 if (len(msg) > chars_lim): return None if picture is None: self.twitter.update_status(status=msg) else: photo = open(...
identifier_body
twitter.py
from __future__ import division __author__ = 'saeedamen' # Saeed Amen # # Copyright 2016 Cuemacro # # 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 # ...
: def __init__(self, *args, **kwargs): pass def set_key(self, TWITTER_APP_KEY, TWITTER_APP_SECRET, TWITTER_OAUTH_TOKEN, TWITTER_OAUTH_TOKEN_SECRET): self.twitter = Twython(TWITTER_APP_KEY, TWITTER_APP_SECRET, TWITTER_OAUTH_TOKEN, TWITTER_OAUTH_TOKEN_SECRET) def auto_set_key(self): ...
Twitter
identifier_name
serializers.py
"""Defines serializers used by the Team API.""" from copy import deepcopy from django.contrib.auth.models import User from django.db.models import Count from django.conf import settings from django_countries import countries from rest_framework import serializers from openedx.core.lib.api.serializers import Collapsed...
class MembershipSerializer(serializers.ModelSerializer): """Serializes CourseTeamMemberships with information about both teams and users.""" profile_configuration = deepcopy(settings.ACCOUNT_VISIBILITY_CONFIGURATION) profile_configuration['shareable_fields'].append('url') profile_configuration['publi...
super(CourseTeamSerializerWithoutMembership, self).__init__(*args, **kwargs) del self.fields['membership']
identifier_body
serializers.py
"""Defines serializers used by the Team API.""" from copy import deepcopy from django.contrib.auth.models import User from django.db.models import Count from django.conf import settings from django_countries import countries from rest_framework import serializers from openedx.core.lib.api.serializers import Collapsed...
(BaseTopicSerializer): # pylint: disable=abstract-method """ Serializes a set of topics, adding the team_count field to each topic as a bulk operation. Requires that `context` is provided with a valid course_id in order to filter teams within the course. """ class Meta(object): list_seriali...
BulkTeamCountTopicSerializer
identifier_name
serializers.py
"""Defines serializers used by the Team API.""" from copy import deepcopy from django.contrib.auth.models import User from django.db.models import Count from django.conf import settings from django_countries import countries from rest_framework import serializers from openedx.core.lib.api.serializers import Collapsed...
topic['team_count'] = topics_to_team_count.get(topic['id'], 0)
conditional_block
serializers.py
"""Defines serializers used by the Team API.""" from copy import deepcopy from django.contrib.auth.models import User from django.db.models import Count from django.conf import settings from django_countries import countries from rest_framework import serializers from openedx.core.lib.api.serializers import Collapsed...
collapsed_serializer=CollapsedReferenceSerializer( model_class=User, id_source='username', view_name='accounts_api', read_only=True, ), expanded_serializer=UserReadOnlySerializer(configuration=profile_configuration) ) team = ExpandableField...
profile_configuration = deepcopy(settings.ACCOUNT_VISIBILITY_CONFIGURATION) profile_configuration['shareable_fields'].append('url') profile_configuration['public_fields'].append('url') user = ExpandableField(
random_line_split
SVGLinearGradientElement-dom-x1-attr.js
// [Name] SVGLinearGradientElement-dom-x1-attr.js // [Expected rendering result] green ellipse, no red visible - and a series of PASS messages description("Tests dynamic updates of the 'x1' attribute of the SVGLinearGradientElement object") createSVGTestCase(); var ellipseElement = createSVGElement("ellipse"); ellips...
var successfullyParsed = true;
{ linearGradientElement.setAttribute("x1", "200%"); shouldBeEqualToString("linearGradientElement.getAttribute('x1')", "200%"); }
identifier_body
SVGLinearGradientElement-dom-x1-attr.js
// [Name] SVGLinearGradientElement-dom-x1-attr.js // [Expected rendering result] green ellipse, no red visible - and a series of PASS messages description("Tests dynamic updates of the 'x1' attribute of the SVGLinearGradientElement object") createSVGTestCase(); var ellipseElement = createSVGElement("ellipse"); ellips...
linearGradientElement.setAttribute("x1", "100%"); var firstStopElement = createSVGElement("stop"); firstStopElement.setAttribute("offset", "0"); firstStopElement.setAttribute("stop-color", "red"); linearGradientElement.appendChild(firstStopElement); var lastStopElement = createSVGElement("stop"); lastStopElement.setA...
var defsElement = createSVGElement("defs"); rootSVGElement.appendChild(defsElement); var linearGradientElement = createSVGElement("linearGradient"); linearGradientElement.setAttribute("id", "gradient");
random_line_split
SVGLinearGradientElement-dom-x1-attr.js
// [Name] SVGLinearGradientElement-dom-x1-attr.js // [Expected rendering result] green ellipse, no red visible - and a series of PASS messages description("Tests dynamic updates of the 'x1' attribute of the SVGLinearGradientElement object") createSVGTestCase(); var ellipseElement = createSVGElement("ellipse"); ellips...
() { linearGradientElement.setAttribute("x1", "200%"); shouldBeEqualToString("linearGradientElement.getAttribute('x1')", "200%"); } var successfullyParsed = true;
repaintTest
identifier_name
meteo.rs
use crate::dispatcher::Module; use crate::dispatcher::MsgSender; use rand::distributions::Normal; use rand::prelude::*; use std::collections::HashMap; #[derive(PartialEq, Eq, Debug, Copy, Clone, Hash)] enum MeasurementType { Temperature, Humidity, Pressure, LightLevel, } #[derive(Debug)] pub struct ...
( &mut self, msg_writer: &mut dyn MsgSender, transaction_id: u32, _node_id: u32, msg_str: &str, ) -> Result<(), ()> { debug!("Handling message: {} {}", transaction_id, msg_str); let mut values = msg_str.split(','); let msg_type = values.next().ok_or(...
handle_incoming_msg
identifier_name
meteo.rs
use crate::dispatcher::Module; use crate::dispatcher::MsgSender; use rand::distributions::Normal; use rand::prelude::*; use std::collections::HashMap; #[derive(PartialEq, Eq, Debug, Copy, Clone, Hash)] enum MeasurementType { Temperature, Humidity, Pressure, LightLevel, } #[derive(Debug)] pub struct ...
self.generate_new_value(MeasurementType::Humidity, ch_num) ), "GET_PRESSURE" => format!( "PRESSURE_REPLY,{},{}", ch_num, self.generate_new_value(MeasurementType::Pressure, ch_num) ), "GET_LIGHT_LEVEL" => form...
"GET_HUMIDITY" => format!( "HUMIDITY_REPLY,{},{}", ch_num,
random_line_split
udp.rs
use ffi::{AF_INET, AF_INET6, AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, AI_PASSIVE, AI_NUMERICSERV}; use core::Protocol; use handler::Handler; use dgram_socket::DgramSocket; use ip::{IpEndpoint, IpProtocol, Passive, Resolver, ResolverIter, ResolverQuery}; use std::io; use std::fmt; use std::mem; /// The User Datagram Protoc...
} impl<'a> ResolverQuery<Udp> for (Passive, &'a str) { fn iter(self) -> io::Result<ResolverIter<Udp>> { ResolverIter::new(&Udp { family: AF_UNSPEC }, "", self.1, AI_PASSIVE) } } impl<'a, 'b> ResolverQuery<Udp> for (&'a str, &'b str) { fn iter(self) -> io::Result<ResolverIter<Udp>> { Resol...
{ let port = self.1.to_string(); ResolverIter::new( &Udp { family: AF_UNSPEC }, "", &port, AI_PASSIVE | AI_NUMERICSERV, ) }
identifier_body
udp.rs
use ffi::{AF_INET, AF_INET6, AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, AI_PASSIVE, AI_NUMERICSERV}; use core::Protocol; use handler::Handler; use dgram_socket::DgramSocket; use ip::{IpEndpoint, IpProtocol, Passive, Resolver, ResolverIter, ResolverQuery}; use std::io; use std::fmt; use std::mem; /// The User Datagram Protoc...
&port, AI_PASSIVE | AI_NUMERICSERV, ) } } impl<'a> ResolverQuery<Udp> for (Passive, &'a str) { fn iter(self) -> io::Result<ResolverIter<Udp>> { ResolverIter::new(&Udp { family: AF_UNSPEC }, "", self.1, AI_PASSIVE) } } impl<'a, 'b> ResolverQuery<Udp> for (&'a str, &'...
ResolverIter::new( &Udp { family: AF_UNSPEC }, "",
random_line_split
udp.rs
use ffi::{AF_INET, AF_INET6, AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, AI_PASSIVE, AI_NUMERICSERV}; use core::Protocol; use handler::Handler; use dgram_socket::DgramSocket; use ip::{IpEndpoint, IpProtocol, Passive, Resolver, ResolverIter, ResolverQuery}; use std::io; use std::fmt; use std::mem; /// The User Datagram Protoc...
() { use core::IoContext; use ip::*; let ctx = &IoContext::new().unwrap(); let re = UdpResolver::new(ctx); for ep in re.resolve(("127.0.0.1", "80")).unwrap() { assert_eq!(ep, UdpEndpoint::new(IpAddrV4::loopback(), 80)); } for ep in re.resolve(("::1", "80")).unwrap() { assert...
test_udp_resolve
identifier_name
deprecated.js
/*eslint no-console: 0 */ "use strict"; // wrap returns a function that will invoke the supplied function and print a deprecation warning to the console each // time it is called. exports.wrap = function (func, msg) { var wrapped = function () { // Watch out for IE7 and below! :( if (typeof console...
return func.apply(this, arguments); }; if (func.prototype) { wrapped.prototype = func.prototype; } return wrapped; }; // defaultMsg returns a string which can be supplied to `wrap()` to notify the user that a particular part of the // sinon API has been deprecated. exports.defaultMsg =...
{ if (console.info) { console.info(msg); } else { console.log(msg); } }
conditional_block
deprecated.js
/*eslint no-console: 0 */ "use strict"; // wrap returns a function that will invoke the supplied function and print a deprecation warning to the console each // time it is called. exports.wrap = function (func, msg) { var wrapped = function () { // Watch out for IE7 and below! :( if (typeof console...
return "sinon." + funcName + " is deprecated and will be removed from the public API in a future version of sinon."; };
// sinon API has been deprecated. exports.defaultMsg = function (funcName) {
random_line_split
exportmeta.js
var express = require('express'); var router = express.Router(); var mkdirp = require('mkdirp'); var fs = require("fs"); var file = __dirname + "/../database/panoinfo.db"; var exists = fs.existsSync(file); var sqlite3 = require("sqlite3").verbose(); var db = new sqlite3.Database(file); /* GET users listing. */ router...
; }); res.send(''); }); module.exports = router;
{ var data = JSON.parse(rows[i].info); console.log(data.location.pano) var filePath = panoinfoPath + '/' + data.location.pano; fs.writeFile(filePath, rows[i].info) }
conditional_block
exportmeta.js
var express = require('express'); var router = express.Router(); var mkdirp = require('mkdirp'); var fs = require("fs"); var file = __dirname + "/../database/panoinfo.db"; var exists = fs.existsSync(file); var sqlite3 = require("sqlite3").verbose(); var db = new sqlite3.Database(file); /* GET users listing. */ router...
module.exports = router;
res.send(''); });
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate rand; use std::io::Write; use clap::{App, AppSettings, Arg}; use rand::Rng; const LOWERCASE: &'static [u8] = b"abcdefghijklmnopqrstuvwxyz"; const UPPERCASE: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const DIGITS: &'static [u8] = b"0123456789"; const SYMBOL: &'static [...
(args: &Args, count: usize) { let mut rng = rand::thread_rng(); for _ in 0.. args.num_pw { let mut mtl: Vec<char> = Vec::new(); mtl.extend_from_slice(&each_choose(args.lower_c, &LOWERCASE)); mtl.extend_from_slice(&each_choose(args.upper_c, &UPPERCASE)); mtl.extend_from_slice(&eac...
generate_pw
identifier_name
main.rs
#[macro_use] extern crate clap; extern crate rand; use std::io::Write; use clap::{App, AppSettings, Arg}; use rand::Rng; const LOWERCASE: &'static [u8] = b"abcdefghijklmnopqrstuvwxyz"; const UPPERCASE: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const DIGITS: &'static [u8] = b"0123456789"; const SYMBOL: &'static [...
.arg(Arg::from_usage("-U 'Don't include uppercase letters'")) .arg(Arg::from_usage("-D 'Don't include digits'")) .arg(Arg::from_usage("-S 'Don't include symbols'")) .arg(Arg::from_usage("-l --length [length] 'Length of the password'").default_value("8")) .arg(Arg::from_usage("-n ...
let matches = App::new("rpwg") .version(crate_version!()) .author(crate_authors!()) .about("Random password generator") .setting(AppSettings::DeriveDisplayOrder)
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate rand; use std::io::Write; use clap::{App, AppSettings, Arg}; use rand::Rng; const LOWERCASE: &'static [u8] = b"abcdefghijklmnopqrstuvwxyz"; const UPPERCASE: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const DIGITS: &'static [u8] = b"0123456789"; const SYMBOL: &'static [...
{ let mut vec: Vec<_> = Vec::new(); vec.write(LOWERCASE).unwrap(); if args.upper == false { vec.write(UPPERCASE).unwrap(); } if args.digits == false { vec.write(DIGITS).unwrap(); } if args.symbol == false { vec.write(SYMBOL).unwrap(); } return vec; }
identifier_body
app.ts
import {Router, RouterConfiguration} from 'aurelia-router'; import {autoinject} from 'aurelia-framework'; import {AuthService} from './lib/auth-service'; @autoinject export class
{ authService: AuthService; router: Router; constructor(authService: AuthService) { this.authService = authService; } configureRouter(config: RouterConfiguration, router: Router) { config.title = 'PowerfulPerms-Web'; config.map([ { route: '', moduleId: 'views/no-category'}, ...
App
identifier_name
app.ts
import {Router, RouterConfiguration} from 'aurelia-router'; import {autoinject} from 'aurelia-framework'; import {AuthService} from './lib/auth-service'; @autoinject export class App { authService: AuthService; router: Router; constructor(authService: AuthService) { this.authService = authService; } co...
}); } }
{ console.log("Was not logged in, forwarding to login route"); $this.router.navigateToRoute("login"); }
conditional_block
app.ts
import {Router, RouterConfiguration} from 'aurelia-router'; import {autoinject} from 'aurelia-framework'; import {AuthService} from './lib/auth-service'; @autoinject export class App { authService: AuthService; router: Router; constructor(authService: AuthService) { this.authService = authService; } co...
$this.router.navigateToRoute("login"); } }); } }
attached() { let $this = this; this.authService.isLoggedIn().then(loggedIn => { if (!loggedIn) { console.log("Was not logged in, forwarding to login route");
random_line_split
htmlmetaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindin...
} } #[allow(unrooted_must_root)] fn apply_viewport(&self) { if !pref!(layout.viewport.enabled) { return; } let element = self.upcast::<Element>(); if let Some(ref content) = element.get_attribute(&ns!(), &local_name!("content")) { let content...
{ self.apply_referrer(); }
conditional_block
htmlmetaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::HTMLMetaElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLMetaElementBinding::HTMLMetaElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRo...
use crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell;
random_line_split
htmlmetaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindin...
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { if let Some(s) = self.super_type() { s.attribute_mutated(attr, mutation); } self.process_referrer_attribute(); } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = ...
{ if let Some(ref s) = self.super_type() { s.bind_to_tree(context); } if context.tree_connected { self.process_attributes(); } }
identifier_body
htmlmetaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindin...
( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLMetaElement> { Node::reflect_node( Box::new(HTMLMetaElement::new_inherited(local_name, prefix, document)), document, HTMLMetaElementBinding::Wrap, ) ...
new
identifier_name
base.py
import ns.point_to_point import ns.csma import ns.wifi import ns.bridge import ns.internet import ns.mesh import ns.wimax import ns.wimax import ns.lte import gobject import os.path import sys PIXELS_PER_METER = 3.0 # pixels-per-meter, at 100% zoom level class PyVizObject(gobject.GObject): __gtype_name__ = "PyVi...
netdevice_traits = { ns.point_to_point.PointToPointNetDevice: NetDeviceTraits(is_wireless=False), ns.csma.CsmaNetDevice: NetDeviceTraits(is_wireless=False), ns.wifi.WifiNetDevice: NetDeviceTraits(is_wireless=True), ns.bridge.BridgeNetDevice: NetDeviceTraits(is_virtual=True), ns.internet.LoopbackNe...
assert is_virtual or is_wireless is not None self.is_wireless = is_wireless self.is_virtual = is_virtual
identifier_body
base.py
import ns.point_to_point import ns.csma import ns.wifi import ns.bridge import ns.internet import ns.mesh import ns.wimax import ns.wimax import ns.lte import gobject import os.path import sys PIXELS_PER_METER = 3.0 # pixels-per-meter, at 100% zoom level class PyVizObject(gobject.GObject): __gtype_name__ = "PyVi...
ns.lte.UeNetDevice: NetDeviceTraits(is_wireless=True), ns.lte.EnbNetDevice: NetDeviceTraits(is_wireless=True), } def lookup_netdevice_traits(class_type): try: return netdevice_traits[class_type] except KeyError: sys.stderr.write("WARNING: no NetDeviceTraits registered for device type %r...
ns.wimax.BaseStationNetDevice: NetDeviceTraits(is_wireless=True),
random_line_split
base.py
import ns.point_to_point import ns.csma import ns.wifi import ns.bridge import ns.internet import ns.mesh import ns.wimax import ns.wimax import ns.lte import gobject import os.path import sys PIXELS_PER_METER = 3.0 # pixels-per-meter, at 100% zoom level class PyVizObject(gobject.GObject): __gtype_name__ = "PyVi...
(self, is_wireless=None, is_virtual=False): assert is_virtual or is_wireless is not None self.is_wireless = is_wireless self.is_virtual = is_virtual netdevice_traits = { ns.point_to_point.PointToPointNetDevice: NetDeviceTraits(is_wireless=False), ns.csma.CsmaNetDevice: NetDeviceTraits(i...
__init__
identifier_name
base.py
import ns.point_to_point import ns.csma import ns.wifi import ns.bridge import ns.internet import ns.mesh import ns.wimax import ns.wimax import ns.lte import gobject import os.path import sys PIXELS_PER_METER = 3.0 # pixels-per-meter, at 100% zoom level class PyVizObject(gobject.GObject): __gtype_name__ = "PyVi...
plugins_loaded = False def load_plugins(): global plugins_loaded if plugins_loaded: return plugins_loaded = True plugins_dir = os.path.join(os.path.dirname(__file__), 'plugins') old_path = list(sys.path) sys.path.insert(0, plugins_dir) for filename in os.listdir(plugins_dir): ...
plugin_modules[plugin_name] = plugin_module
conditional_block
wmove.rs
#[macro_use] extern crate cli_util; extern crate wlib; use std::env; use wlib::window; #[derive(Copy, Clone)] enum Mode { Relative, Absolute } fn main()
fn run(mode: Mode, x: i32, y: i32, wid: window::ID) -> Result<(), &'static str> { let disp = try!(wlib::Display::open()); let mut win = try!( disp.window(wid).map_err(|_| "window does not exist") ); match mode { Mode::Relative => try!(win.reposition_relative(x, y)), Mode::Absol...
{ let name = cli_util::name(&mut env::args()); parse_args!{ description: "move window", flag mode: Mode = Mode::Relative, (&["-r", "--relative"], Mode::Relative, "move relatively (default)"), (&["-a", "--absolute"], Mode::Absolute, "move absolutely"), arg x: i32,...
identifier_body
wmove.rs
#[macro_use] extern crate cli_util; extern crate wlib;
use std::env; use wlib::window; #[derive(Copy, Clone)] enum Mode { Relative, Absolute } fn main() { let name = cli_util::name(&mut env::args()); parse_args!{ description: "move window", flag mode: Mode = Mode::Relative, (&["-r", "--relative"], Mode::Relative, "move relativ...
random_line_split
wmove.rs
#[macro_use] extern crate cli_util; extern crate wlib; use std::env; use wlib::window; #[derive(Copy, Clone)] enum Mode { Relative, Absolute } fn
() { let name = cli_util::name(&mut env::args()); parse_args!{ description: "move window", flag mode: Mode = Mode::Relative, (&["-r", "--relative"], Mode::Relative, "move relatively (default)"), (&["-a", "--absolute"], Mode::Absolute, "move absolutely"), arg x: i...
main
identifier_name
console.py
#!/usr/bin/env python # -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; coding: utf-8 -*- # vim: tabstop=4 softtabstop=4 expandtab shiftwidth=4 fileencoding=utf-8 # # Shell command # Copyright 2010, Jeremy Grosser <synack@digg.com> import argparse import os import sys import clusto from clusto import scr...
(self, subparsers): parser = self._setup_subparser(subparsers) self._add_arguments(parser) def run(self, args): try: server = clusto.get(args.server[0]) if not server: raise LookupError('Object "%s" does not exist' % args.server) except Except...
add_subparser
identifier_name
console.py
#!/usr/bin/env python # -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; coding: utf-8 -*- # vim: tabstop=4 softtabstop=4 expandtab shiftwidth=4 fileencoding=utf-8 # # Shell command # Copyright 2010, Jeremy Grosser <synack@digg.com> import argparse import os import sys import clusto from clusto import scr...
except Exception as e: self.debug(e) self.error('No object like "%s" was found' % args.server) return 1 server = server[0] if not hasattr(server, 'console'): self.error('The object %s lacks a console method' % server.name) return 2 ...
raise LookupError('Object "%s" does not exist' % args.server)
conditional_block
console.py
#!/usr/bin/env python # -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; coding: utf-8 -*- # vim: tabstop=4 softtabstop=4 expandtab shiftwidth=4 fileencoding=utf-8 # # Shell command # Copyright 2010, Jeremy Grosser <synack@digg.com> import argparse import os import sys import clusto from clusto import scr...
except Exception as e: self.debug(e) self.error('No object like "%s" was found' % args.server) return 1 server = server[0] if not hasattr(server, 'console'): self.error('The object %s lacks a console method' % server.name) return 2 ...
try: server = clusto.get(args.server[0]) if not server: raise LookupError('Object "%s" does not exist' % args.server)
random_line_split
console.py
#!/usr/bin/env python # -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; coding: utf-8 -*- # vim: tabstop=4 softtabstop=4 expandtab shiftwidth=4 fileencoding=utf-8 # # Shell command # Copyright 2010, Jeremy Grosser <synack@digg.com> import argparse import os import sys import clusto from clusto import scr...
def run(self, args): try: server = clusto.get(args.server[0]) if not server: raise LookupError('Object "%s" does not exist' % args.server) except Exception as e: self.debug(e) self.error('No object like "%s" was found' % args.server) ...
parser = self._setup_subparser(subparsers) self._add_arguments(parser)
identifier_body
mlperf_test.py
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 applicable law or agree...
bench_cnn = benchmark_cnn.BenchmarkCNN(params, model=_MlPerfTestModel()) bench_cnn.run() logs = string_io.getvalue().splitlines() log_regexes = Counter() for log in logs: for regex in self.EXPECTED_LOG_REGEXES: if regex.search(log): log_regexes[regex] += 1...
string_io = six.StringIO() handler = logging.StreamHandler(string_io) data_dir = test_util.create_black_and_white_images() try: mlperf_log.LOGGER.addHandler(handler) params = benchmark_cnn.make_params(data_dir=data_dir, data_name='imagenet', ...
identifier_body
mlperf_test.py
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 writing, software # distributed under the License is distributed on an "AS IS" BASIS,...
tf.test.main()
random_line_split
mlperf_test.py
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 applicable law or agree...
(self, cnn): assert cnn.top_layer.shape[1:] == (3, 224, 224) cnn.conv(1, 1, 1, 1, 1, use_batch_norm=True) cnn.mpool(1, 1, 1, 1, num_channels_in=1) cnn.reshape([-1, 224 * 224]) cnn.affine(1, activation=None) # Assert that the batch norm variables are filtered out for L2 loss. variables = tf....
add_inference
identifier_name
mlperf_test.py
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 applicable law or agree...
finally: mlperf_log.LOGGER.removeHandler(handler) if
diff_counter = Counter(log_regexes) diff_counter.subtract(self.EXPECTED_LOG_REGEXES) differences = [] for regex in (k for k in diff_counter.keys() if diff_counter[k]): found_count = log_regexes[regex] expected_count = self.EXPECTED_LOG_REGEXES[regex] differences.app...
conditional_block
Bomb.ts
import { Actor } from './Actor'; import { ZeldaGame } from './ZeldaGame'; import { Link } from './Link'; import Rectangle from 'gtp/lib/gtp/Rectangle'; import Image from 'gtp/lib/gtp/Image'; declare let game: ZeldaGame; /** * A bomb Link has dropped, waiting to explode. */ export class Bomb extends Actor { priva...
() { const link: Link = game.link; this.frame--; // This "16" magic number matches how long Link is frozen swinging his sword. // Not sure if that matches the game or not... if (this.frame === Bomb.MAX_FRAME - 16) { link.frozen = false; link.step = Link.F...
update
identifier_name
Bomb.ts
import { Actor } from './Actor'; import { ZeldaGame } from './ZeldaGame'; import { Link } from './Link'; import Rectangle from 'gtp/lib/gtp/Rectangle'; import Image from 'gtp/lib/gtp/Image'; declare let game: ZeldaGame; /** * A bomb Link has dropped, waiting to explode. */ export class Bomb extends Actor { priva...
this.dir = link.dir; this.frame = Bomb.MAX_FRAME; switch (this.dir) { case 'DOWN': this.x = link.x + 4; this.y = link.y + 16 + 6; break; case 'LEFT': this.x = link.x - 16 + 4; this.y = link....
const link: Link = game.link;
random_line_split
Bomb.ts
import { Actor } from './Actor'; import { ZeldaGame } from './ZeldaGame'; import { Link } from './Link'; import Rectangle from 'gtp/lib/gtp/Rectangle'; import Image from 'gtp/lib/gtp/Image'; declare let game: ZeldaGame; /** * A bomb Link has dropped, waiting to explode. */ export class Bomb extends Actor { priva...
paint(ctx: CanvasRenderingContext2D) { this.possiblyPaintHitBox(ctx); if (this.frame < Bomb.MAX_FRAME - 2) { // First two frames, we aren't painted const image: Image = game.assets.get('treasures.bomb'); image.draw(ctx, this.x, this.y); } } update() { ...
{ // Do nothing return false; }
identifier_body
animation.js
// This uses GreenSocks TweenMax and TimeLine Classes for all the animated parts // Rather than using CANVAS that will break earlier browsers, instead we animate // DOM elements in realtime using JavaScript. // As the script is loaded AFTER the content, we can use onLoad :) /* Motion Sequence --------------- */ // ...
{ // hide loader! // remove loading class from #content UTIL.removeClass( elements.content , 'loading' ); timeline.play(); }; return Animations; })(); var anim = new Animations(); anim.assign(); // begin animating... // defer animation // anim.begin();
// Animations.prototype.begin = function()
random_line_split
animation.js
// This uses GreenSocks TweenMax and TimeLine Classes for all the animated parts // Rather than using CANVAS that will break earlier browsers, instead we animate // DOM elements in realtime using JavaScript. // As the script is loaded AFTER the content, we can use onLoad :) /* Motion Sequence --------------- */ // ...
() { } // This creates all of our animation elements Animations.prototype.assign = function() { variant = getElementById('variant').className || 'unknown'; elements.content = getElementById('content'); elements.first = getElementById('first'); elements.second = getElementById('...
Animations
identifier_name
animation.js
// This uses GreenSocks TweenMax and TimeLine Classes for all the animated parts // Rather than using CANVAS that will break earlier browsers, instead we animate // DOM elements in realtime using JavaScript. // As the script is loaded AFTER the content, we can use onLoad :) /* Motion Sequence --------------- */ // ...
// This creates all of our animation elements Animations.prototype.assign = function() { variant = getElementById('variant').className || 'unknown'; elements.content = getElementById('content'); elements.first = getElementById('first'); elements.second = getElementById('second'); ele...
{ }
identifier_body
ipythonchartanimation.py
from IPython.display import display from matplotlib import animation, rc import abc class IPythonChartAnimation(object): __metaclass__ = abc.ABCMeta VIDEO_TAG = """<video controls> <source src="data:video/x-m4v;base64,{0}" type="video/mp4"> Your browser does not support the...
@property def interval(self): return self.__interval @interval.setter def interval(self, inter): self.__interval = inter
self.__number_of_frames = value
identifier_body
ipythonchartanimation.py
from IPython.display import display from matplotlib import animation, rc import abc class IPythonChartAnimation(object): __metaclass__ = abc.ABCMeta VIDEO_TAG = """<video controls> <source src="data:video/x-m4v;base64,{0}" type="video/mp4"> Your browser does not support the...
def interval(self): return self.__interval @interval.setter def interval(self, inter): self.__interval = inter
@number_of_frames.setter def number_of_frames(self, value): self.__number_of_frames = value @property
random_line_split
ipythonchartanimation.py
from IPython.display import display from matplotlib import animation, rc import abc class IPythonChartAnimation(object): __metaclass__ = abc.ABCMeta VIDEO_TAG = """<video controls> <source src="data:video/x-m4v;base64,{0}" type="video/mp4"> Your browser does not support the...
(self): return self.__target_canvas @target_canvas.setter def target_canvas(self, canvas): self.__target_canvas = canvas @property def number_of_frames(self): return self.__number_of_frames @number_of_frames.setter def number_of_frames(self, value): self.__numb...
target_canvas
identifier_name
helper.py
## pythonFlu - Python wrapping for OpenFOAM C++ API ## Copyright (C) 2010- Alexey Petrov ## Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR) ## ## 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 F...
#--------------------------------------------------------------------------------------
def __call__( self, theExpr, theDeps ): result = theExpr.holder( theDeps ) theExpr.this.disown() return result pass pass
identifier_body
helper.py
## pythonFlu - Python wrapping for OpenFOAM C++ API ## Copyright (C) 2010- Alexey Petrov ## Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR) ## ## 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 F...
( self, the_attr ): if not self._dict.has_key( the_attr ): raise AttributeError( "There is no \"%s\" attribute " %the_attr) pass a_result = self._dict[ the_attr ] if type( a_result ) == str: an_interface =a_result.split('.')[ -1 ] #print ...
__getattr__
identifier_name
helper.py
## pythonFlu - Python wrapping for OpenFOAM C++ API ## Copyright (C) 2010- Alexey Petrov ## Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR) ## ## 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 F...
exec "self.%s = a_result" %the_attr return a_result pass #-------------------------------------------------------------------------------------- class TManLoadHelper( TLoadHelper ): def __call__( self, theExpr, theDeps ): result = theExpr.holder( theDeps ) theE...
an_interface =a_result.split('.')[ -1 ] #print an_interface an_interface_path = ".".join( a_result.split( "." )[ :-1 ] ) #print an_interface_path exec "from %s import %s as a_result" %( an_interface_path, an_interface ) pass
conditional_block
helper.py
## pythonFlu - Python wrapping for OpenFOAM C++ API ## Copyright (C) 2010- Alexey Petrov ## Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR) ## ## 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 F...
## #-------------------------------------------------------------------------------------- class TLoadHelper( object ): def __init__( self, the_dict ): self._dict = the_dict pass def __getattr__( self, the_attr ): if not self._dict.has_key( the_attr ): raise AttributeE...
## See http://sourceforge.net/projects/pythonflu ## ## Author : Alexey PETROV, Andrey SIMURZIN
random_line_split
config.py
from yaml import load from os import environ from os.path import join, isfile from ..module_ultra_repo import ModuleUltraRepo from ..module_ultra_config import ModuleUltraConfig class RepoDaemonConfig: """Represent a MU repo to the MU daemon.""" def __init__(self, **kwargs): self.repo_name = kwargs...
def get_pipeline_endpts(self, pipe_name): """Return a list of endpts or None.""" return None def get_pipeline_excluded_endpts(self, pipe_name): """Return a list of excluded endpts or None.""" return None class DaemonConfig: """Store config information for the MU daemon."...
"""Return tolerance for the pipeline.""" for pipe in self.pipelines: if pipe['name'] == pipe_name: return pipe.get('tolerance', 0)
identifier_body
config.py
from yaml import load from os import environ from os.path import join, isfile from ..module_ultra_repo import ModuleUltraRepo from ..module_ultra_config import ModuleUltraConfig class RepoDaemonConfig: """Represent a MU repo to the MU daemon.""" def __init__(self, **kwargs): self.repo_name = kwargs[...
def get_repo(self): """Return the MU repo that this represents.""" return ModuleUltraRepo(self.repo_path) def get_pipeline_list(self): """Return a list of (pipe_name, version).""" return [(pipe['name'], pipe['version']) for pipe in self.pipelines] def get_pipeline_tolerance...
self.pipelines = kwargs['pipelines']
random_line_split
config.py
from yaml import load from os import environ from os.path import join, isfile from ..module_ultra_repo import ModuleUltraRepo from ..module_ultra_config import ModuleUltraConfig class RepoDaemonConfig: """Represent a MU repo to the MU daemon.""" def __init__(self, **kwargs): self.repo_name = kwargs...
(self, pipe_name, pipe_version): """Return a filepath for the config to be used or None.""" return None @classmethod def get_daemon_config_filename(ctype): try: return environ['MODULE_ULTRA_DAEMON_CONFIG'] except KeyError: config_dir = ModuleUltraConfig.g...
get_pipeline_run_config
identifier_name
config.py
from yaml import load from os import environ from os.path import join, isfile from ..module_ultra_repo import ModuleUltraRepo from ..module_ultra_config import ModuleUltraConfig class RepoDaemonConfig: """Represent a MU repo to the MU daemon.""" def __init__(self, **kwargs): self.repo_name = kwargs...
def get_pipeline_endpts(self, pipe_name): """Return a list of endpts or None.""" return None def get_pipeline_excluded_endpts(self, pipe_name): """Return a list of excluded endpts or None.""" return None class DaemonConfig: """Store config information for the MU daemon."...
return pipe.get('tolerance', 0)
conditional_block
http.rs
use hyper::{Client, Url}; use hyper::status::StatusCode; use hyper::header::{ContentType, Headers, Authorization, Basic}; use std::io::Read; use errors::Error; fn get_headers(url: Url) -> Headers { let mut headers = Headers::new(); headers.set(ContentType::json()); headers.set(Authorization(Basic { ...
headers } #[doc(hidden)] pub fn post(url: &Url, body: &str) -> Result<String, Error> { let headers = get_headers(url.clone()); let client = Client::new(); let mut res = try!(client.post(url.clone()) .headers(headers) .body(body) .send()); let mut resp = String::new(); ...
None => None, Some(password) => Some(password.to_string()), }, }));
random_line_split
http.rs
use hyper::{Client, Url}; use hyper::status::StatusCode; use hyper::header::{ContentType, Headers, Authorization, Basic}; use std::io::Read; use errors::Error; fn get_headers(url: Url) -> Headers
#[doc(hidden)] pub fn post(url: &Url, body: &str) -> Result<String, Error> { let headers = get_headers(url.clone()); let client = Client::new(); let mut res = try!(client.post(url.clone()) .headers(headers) .body(body) .send()); let mut resp = String::new(); res.read_to_st...
{ let mut headers = Headers::new(); headers.set(ContentType::json()); headers.set(Authorization(Basic { username: url.username().to_string(), password: match url.password() { None => None, Some(password) => Some(password.to_string()), }, })); headers...
identifier_body
http.rs
use hyper::{Client, Url}; use hyper::status::StatusCode; use hyper::header::{ContentType, Headers, Authorization, Basic}; use std::io::Read; use errors::Error; fn get_headers(url: Url) -> Headers { let mut headers = Headers::new(); headers.set(ContentType::json()); headers.set(Authorization(Basic { ...
(url: &Url) -> Result<String, Error> { let headers = get_headers(url.clone()); let client = Client::new(); let mut res = try!(client.get(url.clone()) .headers(headers) .send()); let mut resp = String::new(); try!(res.read_to_string(&mut resp)); println!("GET {}", resp); pri...
get
identifier_name
http.rs
use hyper::{Client, Url}; use hyper::status::StatusCode; use hyper::header::{ContentType, Headers, Authorization, Basic}; use std::io::Read; use errors::Error; fn get_headers(url: Url) -> Headers { let mut headers = Headers::new(); headers.set(ContentType::json()); headers.set(Authorization(Basic { ...
}
{ Err(Error::from_couch(&resp)) }
conditional_block
stylesheets.rs
Set's invalid_scopes or invalid_elements table. #[derive(Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] enum Invalidation { /// An element with a given id. ID(Atom), /// An element with a given class name. Class(Atom), /// An element with a given local name. Lo...
( component: &Component<SelectorImpl>, invalidation: &mut Option<Invalidation>) { match *component { Component::LocalName(LocalName { ref name, ref lower_name }) => { if invalidation.as_ref().map_or(true, |s| !s.is_id_or_class()) { *invalidatio...
scan_component
identifier_name
stylesheets.rs
) => element_id == *id, None => false, } } Invalidation::LocalName { ref name, ref lower_name } => { // This could look at the quirks mode of the document, instead // of testing against both names, but it's probably not worth ...
random_line_split
stylesheets.rs
's invalid_scopes or invalid_elements table. #[derive(Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] enum Invalidation { /// An element with a given id. ID(Atom), /// An element with a given class name. Class(Atom), /// An element with a given local name. Local...
/// Mark the DOM tree styles' as fully invalid. pub fn invalidate_fully(&mut self) { debug!("StylesheetInvalidationSet::invalidate_fully"); self.invalid_scopes.clear(); self.invalid_elements.clear(); self.fully_invalid = true; } /// Analyze the given stylesheet, and co...
{ Self { invalid_scopes: FnvHashSet::default(), invalid_elements: FnvHashSet::default(), fully_invalid: false, } }
identifier_body
repository.js
import Mirage from 'ember-cli-mirage'; export default Mirage.Factory.extend({
email_subscribed: true, migration_status: null, owner_name: 'travis-ci', owner: Object.freeze({ login: 'travis-ci', }), permissions: Object.freeze({ read: false, activate: false, deactivate: false, star: false, unstar: false, create_request: false, create_cron: false, c...
name: 'travis-web', vcs_name: 'travis-web', github_language: 'ruby', active: true, active_on_org: false,
random_line_split