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
evaluateXPathToStrings.ts
import IDomFacade from './domFacade/IDomFacade'; import evaluateXPath, { EvaluableExpression } from './evaluateXPath'; import { Options } from './types/Options'; /** * Evaluates an XPath on the given contextNode. Returns the string result as if the XPath is wrapped in string(...). * * @public * * @param selector...
{ return evaluateXPath( selector, contextItem, domFacade, variables, evaluateXPath.STRINGS_TYPE, options ); }
identifier_body
evaluateXPathToStrings.ts
import IDomFacade from './domFacade/IDomFacade'; import evaluateXPath, { EvaluableExpression } from './evaluateXPath'; import { Options } from './types/Options'; /** * Evaluates an XPath on the given contextNode. Returns the string result as if the XPath is wrapped in string(...). * * @public * * @param selector...
( selector: EvaluableExpression, contextItem?: any | null, domFacade?: IDomFacade | null, variables?: { [s: string]: any } | null, options?: Options | null ): string[] { return evaluateXPath( selector, contextItem, domFacade, variables, evaluateXPath.STRINGS_TYPE, options ); }
evaluateXPathToStrings
identifier_name
CreateMapView.js
import React, { Component } from 'react'; import { GoogleMapLoader, GoogleMap, Marker, SearchBox } from 'react-google-maps'; class CreateMapView extends Component { constructor(props) { super(props); this.state = { coordinates: '', }; this.handlePlacesChanged = this.handlePlacesChanged...
} export default CreateMapView;
}
random_line_split
CreateMapView.js
import React, { Component } from 'react'; import { GoogleMapLoader, GoogleMap, Marker, SearchBox } from 'react-google-maps'; class CreateMapView extends Component { constructor(props) { super(props); this.state = { coordinates: '', }; this.handlePlacesChanged = this.handlePlacesChanged...
} export default CreateMapView;
{ return ( <div className="ui card"> <GoogleMapLoader options={{ mapTypeControl: false }} containerElement={ <div {...this.props} style={{ height: '250px', width: '500px', }} ...
identifier_body
CreateMapView.js
import React, { Component } from 'react'; import { GoogleMapLoader, GoogleMap, Marker, SearchBox } from 'react-google-maps'; class CreateMapView extends Component { constructor(props) { super(props); this.state = { coordinates: '', }; this.handlePlacesChanged = this.handlePlacesChanged...
() { const places = this.refs.searchBox.getPlaces(); const address = places[0].formatted_address; const lat = places[0].geometry.location.lat().toString(); const lng = places[0].geometry.location.lng().toString(); const coordinates = lat.concat(',').concat(lng); this.props.addMarker(coordi...
handlePlacesChanged
identifier_name
search.js
var search = (function () { var exports = {}; function narrow_or_search_for_term(search_string) { var search_query_box = $("#search_query"); ui_util.change_tab_to('#home'); var operators = Filter.parse(search_string); narrow.activate(operators, {trigger: 'search'}); // It's sort of annoying that ...
{ module.exports = search; }
conditional_block
search.js
var search = (function () { var exports = {}; function narrow_or_search_for_term(search_string)
function update_buttons_with_focus(focused) { var search_query = $('#search_query'); // Show buttons iff the search input is focused, or has non-empty contents, // or we are narrowed. if (focused || search_query.val() || narrow_state.active()) { $('.search_button').prop('disab...
{ var search_query_box = $("#search_query"); ui_util.change_tab_to('#home'); var operators = Filter.parse(search_string); narrow.activate(operators, {trigger: 'search'}); // It's sort of annoying that this is not in a position to // blur the search box, because it means that Esc won't // un...
identifier_body
search.js
var search = (function () { var exports = {}; function narrow_or_search_for_term(search_string) { var search_query_box = $("#search_query"); ui_util.change_tab_to('#home'); var operators = Filter.parse(search_string); narrow.activate(operators, {trigger: 'search'}); // It's sort of annoying that ...
$('#search_query').select(); }; exports.clear_search = function () { narrow.deactivate(); $('#search_query').blur(); exports.update_button_visibility(); }; return exports; }()); if (typeof module !== 'undefined') { module.exports = search; }
exports.initiate_search = function () {
random_line_split
search.js
var search = (function () { var exports = {}; function
(search_string) { var search_query_box = $("#search_query"); ui_util.change_tab_to('#home'); var operators = Filter.parse(search_string); narrow.activate(operators, {trigger: 'search'}); // It's sort of annoying that this is not in a position to // blur the search box, because it means that Esc...
narrow_or_search_for_term
identifier_name
setSecret.py
# Copyright (C) 2010-2012 Red Hat, Inc. # This work is licensed under the GNU GPLv2 or later. # Test secret series command, check the set secret value, get secret value import base64 from libvirttestapi.src import sharedmod from xml.dom import minidom from libvirt import libvirtError required_params = ('secretUUID',...
else: logger.info("Set secret value failed") return 1 def setSecret(params): """set a secret value """ logger = params['logger'] secretUUID = params['secretUUID'] value = params['value'] data = base64.encodestring(value.encode()).decode('ascii') try: conn = s...
logger.info("Set secret value successfully") return 0
conditional_block
setSecret.py
# Copyright (C) 2010-2012 Red Hat, Inc. # This work is licensed under the GNU GPLv2 or later. # Test secret series command, check the set secret value, get secret value import base64 from libvirttestapi.src import sharedmod from xml.dom import minidom from libvirt import libvirtError required_params = ('secretUUID',...
def setSecret(params): """set a secret value """ logger = params['logger'] secretUUID = params['secretUUID'] value = params['value'] data = base64.encodestring(value.encode()).decode('ascii') try: conn = sharedmod.libvirtobj['conn'] secretobj = conn.secretLookupByUUIDStr...
"""check whether the secret value is set correctly """ secretvalue = secretobj.value(0) original_data = base64.decodestring(secretvalue).decode() if original_data == value: logger.info("Set secret value successfully") return 0 else: logger.info("Set secret value failed") ...
identifier_body
setSecret.py
# Copyright (C) 2010-2012 Red Hat, Inc. # This work is licensed under the GNU GPLv2 or later. # Test secret series command, check the set secret value, get secret value import base64 from libvirttestapi.src import sharedmod from xml.dom import minidom from libvirt import libvirtError required_params = ('secretUUID',...
private = minidom.parseString(secretobj.XMLDesc(0)).\ getElementsByTagName('secret')[0].getAttribute('private') secretobj.setValue(data, 0) """if private is no, the value of secret can be get; if the private is yes, can't get the value of the secret. """ if...
random_line_split
setSecret.py
# Copyright (C) 2010-2012 Red Hat, Inc. # This work is licensed under the GNU GPLv2 or later. # Test secret series command, check the set secret value, get secret value import base64 from libvirttestapi.src import sharedmod from xml.dom import minidom from libvirt import libvirtError required_params = ('secretUUID',...
(params): """set a secret value """ logger = params['logger'] secretUUID = params['secretUUID'] value = params['value'] data = base64.encodestring(value.encode()).decode('ascii') try: conn = sharedmod.libvirtobj['conn'] secretobj = conn.secretLookupByUUIDString(secretUUID) ...
setSecret
identifier_name
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
} }
random_line_split
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
identifier_body
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) { error!("destructor runs"); } } fn main() { let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
finalize
identifier_name
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
{ }
conditional_block
views.py
from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from .models import Submission from .serializers import SubmissionSerializer from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView from django.utils.decorators import method_deco...
from problem.models import Problem from django.shortcuts import get_object_or_404 from .forms import SubmissionForm from django_tables2 import RequestConfig from .tables import SubmissionTable # from guardian.shortcuts import get_objects_for_user class SubmissionViewSet(viewsets.ModelViewSet): queryset = Submiss...
random_line_split
views.py
from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from .models import Submission from .serializers import SubmissionSerializer from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView from django.utils.decorators import method_deco...
model = Submission form_class = SubmissionForm template_name_suffix = '_create_form' @method_decorator(login_required) def dispatch(self, request, pid=None, *args, **kwargs): pid = self.kwargs['pid'] self.problem = get_object_or_404(Problem.objects.all(), pk=pid) return super(Su...
identifier_body
views.py
from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from .models import Submission from .serializers import SubmissionSerializer from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView from django.utils.decorators import method_deco...
(self, form): self.object = form.save(commit=False) self.object.problem = self.problem self.object.user = self.request.user return super(SubmissionCreateView, self).form_valid(form)
form_valid
identifier_name
index.tsx
import React, { Fragment, ReactElement, ReactNode } from 'react'; type Node = Element | Text; type Mark = | 'bold' | 'italic' | 'underline' | 'strikethrough' | 'code' | 'superscript' | 'subscript' | 'keyboard'; type Element = { children: Node[]; [key: string]: unknown; }; type Text = { text: s...
case 'code': { if ( node.children.length === 1 && node.children[0] && typeof node.children[0].text === 'string' ) { return <renderers.block.code>{node.children[0].text}</renderers.block.code>; } break; } case 'layout': { return <renderers.block.l...
random_line_split
index.tsx
import React, { Fragment, ReactElement, ReactNode } from 'react'; type Node = Element | Text; type Mark = | 'bold' | 'italic' | 'underline' | 'strikethrough' | 'code' | 'superscript' | 'subscript' | 'keyboard'; type Element = { children: Node[]; [key: string]: unknown; }; type Text = { text: s...
else { let firstElement = propPath.shift()!; set(obj[firstElement], propPath, value); } } function createComponentBlockProps(node: Element, children: ReactElement[]) { const formProps = JSON.parse(JSON.stringify(node.props)); node.children.forEach((child, i) => { if (child.propPath) { const pr...
{ obj[propPath[0]] = value; }
conditional_block
events_receiver.py
# -*- coding: utf-8 -*- # # Copyright (C) 2018-2019 Matthias Klumpp <matthias@tenstral.net> # # Licensed under the GNU Lesser General Public License Version 3 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free...
(self, socket, msg): data = str(msg[1], 'utf-8', 'replace') try: event = json.loads(data) except json.JSONDecodeError as e: # we ignore invalid requests log.info('Received invalid JSON message from sender: %s (%s)', data if len(data) > 1 else msg, str(e)) ...
_event_message_received
identifier_name
events_receiver.py
# -*- coding: utf-8 -*- # # Copyright (C) 2018-2019 Matthias Klumpp <matthias@tenstral.net> # # Licensed under the GNU Lesser General Public License Version 3 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free...
''' Lighthouse module handling event stream submissions, registering them and publishing them to the world. ''' def __init__(self, endpoint, pub_queue): from glob import glob from laniakea.localconfig import LocalConfig from laniakea.msgstream import keyfile_read_verify_key ...
identifier_body
events_receiver.py
# -*- coding: utf-8 -*- # # Copyright (C) 2018-2019 Matthias Klumpp <matthias@tenstral.net> # # Licensed under the GNU Lesser General Public License Version 3 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free...
# now publish the event to the world self._pub_queue.put([bytes(event['tag'], 'utf-8'), bytes(data, 'utf-8')]) def run(self): if self._socket: log.warning('Tried to run an already running event receiver again.') return self._so...
log.info('Unable to verify signature on event: {}'.format(str(event))) return
conditional_block
events_receiver.py
# -*- coding: utf-8 -*- # # Copyright (C) 2018-2019 Matthias Klumpp <matthias@tenstral.net> # # Licensed under the GNU Lesser General Public License Version 3 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free...
for keyfname in glob(os.path.join(LocalConfig().trusted_curve_keys_dir, '*')): signer_id, verify_key = keyfile_read_verify_key(keyfname) if signer_id and verify_key: self._trusted_keys[signer_id] = verify_key def _event_message_received(self, socket, msg): da...
# TODO: Implement auto-reloading of valid keys list if directory changes
random_line_split
TodoChart.js
var colors = ["#FF6384", "#4BC0C0", "#FFCE56", "#E7E9ED", "#36A2EB", "#F38630", "#E0E4CC", "#69D2E7", "#F7464A", "#E2EAE9", "#D4CCC5", "#949FB1", "#4D5360"]; function getChartColors(len) { if (len >= colors.length) {
return colors.slice(0, len); } function getChartColor(i) { if (i >= colors.length) { return colors[i % colors.length]; } return colors[i]; } function getChartColors2(len) { if (len >= colors.length) { var newColor = new Array(); for (var i = 0; i < len; i++) { ne...
return colors; }
conditional_block
TodoChart.js
var colors = ["#FF6384", "#4BC0C0", "#FFCE56", "#E7E9ED", "#36A2EB", "#F38630", "#E0E4CC", "#69D2E7", "#F7464A", "#E2EAE9", "#D4CCC5", "#949FB1", "#4D5360"]; function getChartColors(len) { if (len >= colors.length) { return colors; } return colors.slice(0, len); } function getChartColor(i) { ...
en) { if (len >= colors.length) { var newColor = new Array(); for (var i = 0; i < len; i++) { newColor[i] = getChartColor(i); } return newColor; } return colors; }
tChartColors2(l
identifier_name
TodoChart.js
var colors = ["#FF6384", "#4BC0C0", "#FFCE56", "#E7E9ED", "#36A2EB", "#F38630", "#E0E4CC", "#69D2E7", "#F7464A", "#E2EAE9", "#D4CCC5", "#949FB1", "#4D5360"]; function getChartColors(len) { if (len >= colors.length) { return colors; } return colors.slice(0, len); } function getChartColor(i) {
function getChartColors2(len) { if (len >= colors.length) { var newColor = new Array(); for (var i = 0; i < len; i++) { newColor[i] = getChartColor(i); } return newColor; } return colors; }
if (i >= colors.length) { return colors[i % colors.length]; } return colors[i]; }
identifier_body
TodoChart.js
var colors = ["#FF6384", "#4BC0C0", "#FFCE56", "#E7E9ED", "#36A2EB", "#F38630", "#E0E4CC", "#69D2E7", "#F7464A", "#E2EAE9", "#D4CCC5", "#949FB1", "#4D5360"]; function getChartColors(len) { if (len >= colors.length) { return colors; } return colors.slice(0, len); } function getChartColor(i) { ...
}
random_line_split
datepicker-zh-TW.js
/* Chinese initialisation for the jQuery UI date picker plugin. */ /* Written by Ressol (ressol@gmail.com). */ (function (factory) { // AMD. Register as an anonymous module. module.exports = factory(require('../datepicker'));; }(function (datepicker) { datepicker.regional['zh-TW'] = { closeTex...
'\u5341\u4E8C\u6708' ], monthNamesShort: [ '\u4E00\u6708', '\u4E8C\u6708', '\u4E09\u6708', '\u56DB\u6708', '\u4E94\u6708', '\u516D\u6708', '\u4E03\u6708', '\u516B\u6708', '\u4E5D\u6708...
'\u5341\u4E00\u6708',
random_line_split
ckan_search.py
import os import time import mechanize CKAN = os.environ.get('CKAN', 'http://data.england.nhs.uk/') class Transaction(object): def __init__(self): self.custom_timers = {} def run(self): # create a Browser instance br = mechanize.Browser() # don't bother with robots.txt ...
trans = Transaction() trans.run() for timer in trans.custom_timers: print '%s: %.5f secs' % (timer, trans.custom_timers[timer])
conditional_block
ckan_search.py
import os import time import mechanize CKAN = os.environ.get('CKAN', 'http://data.england.nhs.uk/') class Transaction(object): def
(self): self.custom_timers = {} def run(self): # create a Browser instance br = mechanize.Browser() # don't bother with robots.txt br.set_handle_robots(False) # add a custom header so CKAN allows our requests br.addheaders = [('User-agent', 'Mozilla/5.0 C...
__init__
identifier_name
ckan_search.py
import os import time import mechanize CKAN = os.environ.get('CKAN', 'http://data.england.nhs.uk/') class Transaction(object): def __init__(self): self.custom_timers = {} def run(self): # create a Browser instance br = mechanize.Browser() # don't bother with robots.txt ...
br.submit() assert 'datasets found for' in br.response().read(), 'Search not performed' # verify responses are valid assert (br.response().code == 200), 'Bad HTTP Response' latency = time.time() - start_timer # store the custom timer sel...
br.form['q'] = 'england' start_timer = time.time()
random_line_split
ckan_search.py
import os import time import mechanize CKAN = os.environ.get('CKAN', 'http://data.england.nhs.uk/') class Transaction(object): def __init__(self):
def run(self): # create a Browser instance br = mechanize.Browser() # don't bother with robots.txt br.set_handle_robots(False) # add a custom header so CKAN allows our requests br.addheaders = [('User-agent', 'Mozilla/5.0 Compatible')] # start t...
self.custom_timers = {}
identifier_body
filter_scheduler.py
# Copyright (c) 2011 Intel Corporation # Copyright (c) 2011 OpenStack, LLC. # 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/l...
(self, filter_properties, host): """Add a retry entry for the selected volume backend. In the event that the request gets re-scheduled, this entry will signal that the given backend has already been tried. """ retry = filter_properties.get('retry', None) if not retry: ...
_add_retry_host
identifier_name
filter_scheduler.py
# Copyright (c) 2011 Intel Corporation # Copyright (c) 2011 OpenStack, LLC. # 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/l...
def schedule_create_share(self, context, request_spec, filter_properties): weighed_host = self._schedule_share(context, request_spec, filter_properties) if not weighed_host: raise exception.NoValidH...
raise exception.InvalidParameterValue(err=msg) return max_attempts
random_line_split
filter_scheduler.py
# Copyright (c) 2011 Intel Corporation # Copyright (c) 2011 OpenStack, LLC. # 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/l...
def _add_retry_host(self, filter_properties, host): """Add a retry entry for the selected volume backend. In the event that the request gets re-scheduled, this entry will signal that the given backend has already been tried. """ retry = filter_properties.get('retry', None) ...
"""Add additional information to the filter properties after a host has been selected by the scheduling process. """ # Add a retry entry for the selected volume backend: self._add_retry_host(filter_properties, host_state.host)
identifier_body
filter_scheduler.py
# Copyright (c) 2011 Intel Corporation # Copyright (c) 2011 OpenStack, LLC. # 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/l...
filter_properties['retry'] = retry share_id = properties.get('share_id') self._log_share_error(share_id, retry) if retry['num_attempts'] > max_attempts: msg = _("Exceeded max scheduling attempts %(max_attempts)d for " "share %(share_id)s") % locals() ...
retry = { 'num_attempts': 1, 'hosts': [] # list of share service hosts tried }
conditional_block
aws.js
AwsApplicationModel = AwsDeploy.Model.extend({ idAttribute: "application_name" }); AwsApplicationCollection = AwsDeploy.Collection.extend({ model: AwsApplicationModel, url: "/aws/apps" }); AwsEnvironmentModel = AwsDeploy.Model.extend({ idAttribute: "environment_id" }); AwsEnvironmentCollection = AwsD...
}); AwsS3BucketCollection = AwsDeploy.Collection.extend({ model: AwsS3BucketModel, url: function () { return "/aws/s3/buckets"; } });
}); AwsS3BucketModel = AwsDeploy.Model.extend({ idAttribute: "bucket_name"
random_line_split
headphonemon.py
# Copyright 2015 Christoph Reiter # 2017 Nick Boultbee # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. impo...
for line in data.splitlines(): if line.strip() == b"Active Port: analog-output-headphones": return True else: return False class HeadphoneAction(object): DISCONNECTED = 0 CONNECTED = 1 class HeadphoneMonitor(GObject.Object): """Monitors the headphone connection state ...
random_line_split
headphonemon.py
# Copyright 2015 Christoph Reiter # 2017 Nick Boultbee # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. impo...
def start(self): """Start the monitoring process. Once this gets called the "changed" signal will be emitted. """ NULL = open(os.devnull, 'wb') try: self._process = subprocess.Popen( ["pactl", "subscribe"], stdout=subprocess.PIPE, stderr=NULL) ...
self._status = new_status self._emit() return
conditional_block
headphonemon.py
# Copyright 2015 Christoph Reiter # 2017 Nick Boultbee # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. impo...
(EventPlugin): PLUGIN_ID = "HeadphoneMonitor" PLUGIN_NAME = _("Pause on Headphone Unplug") PLUGIN_DESC = _("Pauses in case headphones get unplugged and unpauses in " "case they get plugged in again.") PLUGIN_ICON = Icons.MEDIA_PLAYBACK_PAUSE def enabled(self): self._was_...
HeadphoneMonitorPlugin
identifier_name
headphonemon.py
# Copyright 2015 Christoph Reiter # 2017 Nick Boultbee # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. impo...
PLUGIN_ID = "HeadphoneMonitor" PLUGIN_NAME = _("Pause on Headphone Unplug") PLUGIN_DESC = _("Pauses in case headphones get unplugged and unpauses in " "case they get plugged in again.") PLUGIN_ICON = Icons.MEDIA_PLAYBACK_PAUSE def enabled(self): self._was_paused = False ...
identifier_body
settings_menu.ts
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * 'settings-menu' shows a menu with a hardcoded set of pages and subpages. */ import 'chrome://resources/cr_elements/cr_button/cr_b...
this.setSelectedUrl_(anchors[i].href); return; } } this.setSelectedUrl_(''); // Nothing is selected. } focusFirstItem() { const firstFocusableItem = this.shadowRoot!.querySelector<HTMLElement>( '[role=menuitem]:not([hidden])'); if (firstFocusableItem) { firstFo...
if (anchorRoute && anchorRoute.contains(newRoute)) {
random_line_split
settings_menu.ts
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * 'settings-menu' shows a menu with a hardcoded set of pages and subpages. */ import 'chrome://resources/cr_elements/cr_button/cr_b...
this.setSelectedUrl_(''); // Nothing is selected. } focusFirstItem() { const firstFocusableItem = this.shadowRoot!.querySelector<HTMLElement>( '[role=menuitem]:not([hidden])'); if (firstFocusableItem) { firstFocusableItem.focus(); } } private onAdvancedButtonToggle_() { th...
{ const anchorRoute = Router.getInstance().getRouteForPath( anchors[i].getAttribute('href')!); if (anchorRoute && anchorRoute.contains(newRoute)) { this.setSelectedUrl_(anchors[i].href); return; } }
conditional_block
settings_menu.ts
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * 'settings-menu' shows a menu with a hardcoded set of pages and subpages. */ import 'chrome://resources/cr_elements/cr_button/cr_b...
} customElements.define(SettingsMenuElement.is, SettingsMenuElement);
{ return bool.toString(); }
identifier_body
settings_menu.ts
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * 'settings-menu' shows a menu with a hardcoded set of pages and subpages. */ import 'chrome://resources/cr_elements/cr_button/cr_b...
(event: Event) { if ((event.target as HTMLElement).matches('a:not(#extensionsLink)')) { event.preventDefault(); } } /** * Keeps both menus in sync. |url| needs to come from |element.href| because * |iron-list| uses the entire url. Using |getAttribute| will not work. */ private setSelectedU...
onLinkClick_
identifier_name
coverage.py
#!/usr/bin/env python3 import os, sys, glob, pickle, subprocess sys.path.insert(0, os.path.dirname(__file__)) from clang import cindex sys.path = sys.path[1:] def configure_libclang(): llvm_libdirs = ['/usr/lib/llvm-3.2/lib', '/usr/lib64/llvm'] try: libdir = subprocess.check_output(['llvm-config', '...
if filename in nperfile: n_nperfile = len(nperfile[filename]) else: n_nperfile = 0 perc = int(((n_perfile - n_nperfile) / n_perfile) * 100) print('\n File {0}, coverage {1}% ({2} out of {3}):'.format(b, perc, n_perfile - n_nperfile, n_perfile)) cp = list(f) cp.sort(key=lambd...
n_perfile = len(f)
random_line_split
coverage.py
#!/usr/bin/env python3 import os, sys, glob, pickle, subprocess sys.path.insert(0, os.path.dirname(__file__)) from clang import cindex sys.path = sys.path[1:] def configure_libclang(): llvm_libdirs = ['/usr/lib/llvm-3.2/lib', '/usr/lib64/llvm'] try: libdir = subprocess.check_output(['llvm-config', '...
: def __init__(self, cursor, decl): self.ident = cursor.displayname.decode('utf-8') self.filename = cursor.location.file.name.decode('utf-8') ex = cursor.extent self.start_line = ex.start.line self.start_column = ex.start.column self.end_line = ex.end.line ...
Call
identifier_name
coverage.py
#!/usr/bin/env python3 import os, sys, glob, pickle, subprocess sys.path.insert(0, os.path.dirname(__file__)) from clang import cindex sys.path = sys.path[1:] def configure_libclang(): llvm_libdirs = ['/usr/lib/llvm-3.2/lib', '/usr/lib64/llvm'] try: libdir = subprocess.check_output(['llvm-config', '...
configure_libclang() pos = sys.argv.index('--') cflags = sys.argv[1:pos] files = sys.argv[pos+1:] incdir = os.getenv('LIBGIT2_INCLUDE_DIR') defs = scan_libgit2(cflags, incdir) calls = scan_libgit2_glib(cflags, files, incdir) notused = {} perfile = {} nperfile = {} for d in defs: o = defs[d] if not d in...
tu = cindex.TranslationUnit.from_source(git2dir + '.h', cflags) process_diagnostics(tu) headers = glob.glob(os.path.join(git2dir, '*.h')) defs = {} objapi = ['lookup', 'lookup_prefix', 'free', 'id', 'owner'] objderiv = ['commit', 'tree', 'tag', 'blob'] ignore = set() for deriv in objderi...
identifier_body
coverage.py
#!/usr/bin/env python3 import os, sys, glob, pickle, subprocess sys.path.insert(0, os.path.dirname(__file__)) from clang import cindex sys.path = sys.path[1:] def configure_libclang(): llvm_libdirs = ['/usr/lib/llvm-3.2/lib', '/usr/lib64/llvm'] try: libdir = subprocess.check_output(['llvm-config', '...
def newer(a, b): try: return os.stat(a).st_mtime > os.stat(b).st_mtime except: return True def scan_libgit2_glib(cflags, files, git2dir): files = [os.path.abspath(f) for f in files] dname = os.path.dirname(__file__) allcalls = {} l = 0 if not os.getenv('SILENT'): ...
yield cursor proc += list(cursor.get_children())
conditional_block
transforms.js
import Ember from 'ember'; const { String: { htmlSafe } } = Ember; export function pageTransform(width) { let transform = `transform: translate3d(${width}%, 0px, 0px)`; return htmlSafe(`-webkit-${transform}; -ms-${transform}; ${transform}`); } export function pageTransformOffset(offset, columns) { let width ...
(width) { return htmlSafe(`transform: translate3d(${width}px, 0px, 0px); ${SLIDER_TRANSFORM_COMMON}`); } export function sliderTransformHover(width) { return htmlSafe(`transform: scale(2) translate3d(${width}px, 0px, 0px); z-index: 4; ${SLIDER_TRANSFORM_COMMON}`); }
sliderTransform
identifier_name
transforms.js
import Ember from 'ember'; const { String: { htmlSafe } } = Ember; export function pageTransform(width) { let transform = `transform: translate3d(${width}%, 0px, 0px)`; return htmlSafe(`-webkit-${transform}; -ms-${transform}; ${transform}`); } export function pageTransformOffset(offset, columns) { let width ...
export function sliderTransformHover(width) { return htmlSafe(`transform: scale(2) translate3d(${width}px, 0px, 0px); z-index: 4; ${SLIDER_TRANSFORM_COMMON}`); }
random_line_split
transforms.js
import Ember from 'ember'; const { String: { htmlSafe } } = Ember; export function pageTransform(width)
export function pageTransformOffset(offset, columns) { let width = 1.0 / columns * 100.0; let widthStr = -(width + offset).toFixed(14); return pageTransform(widthStr); } let SLIDER_TRANSFORM_COMMON = 'transition-duration: 400ms; transition-timing-function: cubic-bezier(0.5, 0, 0.1, 0); transition-delay: 0ms;';...
{ let transform = `transform: translate3d(${width}%, 0px, 0px)`; return htmlSafe(`-webkit-${transform}; -ms-${transform}; ${transform}`); }
identifier_body
policy_base.js
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import './strings.m.js'; import 'chrome://resources/js/action_link.js'; // <if expr="is_ios"> import 'chrome://resources/js/ios/web_ui.js'; // </if> ...
/** * Triggers the download of the policies as a JSON file. * @param {String} json The policies as a JSON string. */ downloadJson(json) { const blob = new Blob([json], {type: 'application/json'}); const blobUrl = URL.createObjectURL(blob); const link = document.createElement('a'); link.h...
{ /** @type {Array<!PolicyTableModel>} */ const policyGroups = policyValues.map(value => { const knownPolicyNames = policyNames[value.id] ? policyNames[value.id].policyNames : []; const knownPolicyNamesSet = new Set(knownPolicyNames); const receivedPolicyNames = Object.keys(value.pol...
identifier_body
policy_base.js
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import './strings.m.js'; import 'chrome://resources/js/action_link.js'; // <if expr="is_ios"> import 'chrome://resources/js/ios/web_ui.js'; // </if> ...
messagesDisplay.textContent = notice; if (policy.conflicts) { policy.conflicts.forEach(conflict => { const row = new PolicyConflict; row.initialize(conflict, 'conflictValue'); this.appendChild(row); }); } if (policy.superseded) { policy.sup...
{ // Include superseded notice regardless of other notices notice += `, ${supersededNotice}`; }
conditional_block
policy_base.js
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import './strings.m.js'; import 'chrome://resources/js/action_link.js'; // <if expr="is_ios"> import 'chrome://resources/js/ios/web_ui.js'; // </if> ...
() { const showUnset = $('show-unset').checked; const policies = this.querySelectorAll('.policy-data'); for (let i = 0; i < policies.length; i++) { const policyDisplay = policies[i]; policyDisplay.hidden = policyDisplay.policy.value === undefined && !showUnset || policyDispla...
filter
identifier_name
policy_base.js
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import './strings.m.js'; import 'chrome://resources/js/action_link.js'; // <if expr="is_ios"> import 'chrome://resources/js/ios/web_ui.js'; // </if> ...
// Clear policies const mainContent = this.querySelector('.main'); const policies = this.querySelectorAll('.policy-data'); this.querySelector('.header').textContent = dataModel.name; this.querySelector('.id').textContent = dataModel.id; this.querySelector('.id').hidden = !dataModel.id; polic...
this.filterPattern_ = ''; }, /** @param {PolicyTableModel} dataModel */ update(dataModel) {
random_line_split
lib.rs
//! Binding Rust with Python, both ways! //! //! This library will generate and handle type conversions between Python and //! Rust. To use Python from Rust refer to the //! [library wiki](https://github.com/iduartgomez/rustypy/wiki), more general examples //! and information on how to use Rust in Python can also be fo...
} else { // function w/o arguments fndef.push_str("::();"); } if add { match output { syn::ReturnType::Default => fndef.push_str("type(void)"), syn::ReturnType::Type(_, ty) => { ...
});
random_line_split
lib.rs
//! Binding Rust with Python, both ways! //! //! This library will generate and handle type conversions between Python and //! Rust. To use Python from Rust refer to the //! [library wiki](https://github.com/iduartgomez/rustypy/wiki), more general examples //! and information on how to use Rust in Python can also be fo...
#[cfg(test)] mod parsing_tests { use super::*; #[test] #[ignore] fn parse_lib() { let path = std::env::home_dir() .unwrap() .join("workspace/sources/rustypy_debug/rust_code/src/lib.rs"); // let path_ori: std::path::PathBuf = std::env::current_dir().unwrap(); ...
{ match krate.iter_krate(idx as usize) { Some(val) => PyString::from(val).into_raw(), None => PyString::from("NO_IDX_ERROR").into_raw(), } }
identifier_body
lib.rs
//! Binding Rust with Python, both ways! //! //! This library will generate and handle type conversions between Python and //! Rust. To use Python from Rust refer to the //! [library wiki](https://github.com/iduartgomez/rustypy/wiki), more general examples //! and information on how to use Rust in Python can also be fo...
(krate: &KrateData) -> size_t { krate.collected.len() } #[doc(hidden)] #[no_mangle] pub extern "C" fn krate_data_iter(krate: &KrateData, idx: size_t) -> *mut PyString { match krate.iter_krate(idx as usize) { Some(val) => PyString::from(val).into_raw(), None => PyString::from("NO_IDX_ERROR").int...
krate_data_len
identifier_name
tasks.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Task } from './task'; import { TaskService } from './task.service'; @Component({ selector: 'my-tasks', templateUrl: './tasks.component.html' }) export class
implements OnInit { tasks: Task[][]; selectedTask: Task; prevTasksInProgressLength: number; constructor(private router: Router, private taskService: TaskService) { } getTasks(): void { this.taskService.getTasksByStatus(1).then(tasks => { this.tasks[1] = tasks; }); this.taskService.getTasksByStatus...
TasksComponent
identifier_name
tasks.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Task } from './task'; import { TaskService } from './task.service'; @Component({ selector: 'my-tasks', templateUrl: './tasks.component.html' }) export class TasksComponent implements OnInit { tasks: Task[][]; ...
getTasks(): void { this.taskService.getTasksByStatus(1).then(tasks => { this.tasks[1] = tasks; }); this.taskService.getTasksByStatus(2).then(tasks => { this.tasks[2] = tasks; }); this.taskService.getTasksByStatus(3).then(tasks => this.tasks[3] = tasks); } add(title: string, description: string, pri...
{ }
identifier_body
tasks.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Task } from './task'; import { TaskService } from './task.service'; @Component({ selector: 'my-tasks', templateUrl: './tasks.component.html' }) export class TasksComponent implements OnInit { tasks: Task[][]; ...
}
this.tasks[zone].push(droppedTask); }); }
random_line_split
tasks.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Task } from './task'; import { TaskService } from './task.service'; @Component({ selector: 'my-tasks', templateUrl: './tasks.component.html' }) export class TasksComponent implements OnInit { tasks: Task[][]; ...
}); } ngOnInit(): void { this.tasks = new Array<Task[]>(); this.getTasks(); } onSelect(task: Task): void { this.selectedTask = task; } gotoDetail(): void { this.router.navigate(['/detail', this.selectedTask.id]); } addTo($event: any, zone:number): void { console.log(zone...
{ this.selectedTask = null; }
conditional_block
peerDependencies-type.test.ts
import {lint, ruleType} from '../../../src/rules/peerDependencies-type'; import {Severity} from '../../../src/types/severity'; describe('peerDependencies-type Unit Tests', () => { describe('a rule type value should be exported', () => { test('it should equal "standard"', () => { expect(ruleType).toStrictEq...
const packageJsonData = { peerDependencies: 'peerDependencies', }; const response = lint(packageJsonData, Severity.Error); expect(response.lintId).toStrictEqual('peerDependencies-type'); expect(response.severity).toStrictEqual('error'); expect(response.node).toStrictEqual('p...
random_line_split
upload-progress.component.ts
import { Component, OnInit, Input, ChangeDetectorRef } from '@angular/core'; import { UploadService } from '../../services/upload.service'; import { UsersService } from '../../services/users.service'; import { forkJoin } from '../../../../node_modules/rxjs'; import { User } from '../../model/user'; import { Select2Opti...
this.selectedUser = user; if (!this.ref['destroyed']) { this.ref.detectChanges(); } } initialiseUsersDropdown(): void { if (isDefined(this.users)) { this.users.forEach(user => { this.userOptionData.push({ id: user.Id.toString(), text: user.DisplayName }); }); } } ...
{ this.ref.detectChanges(); }
conditional_block
upload-progress.component.ts
import { Component, OnInit, Input, ChangeDetectorRef } from '@angular/core'; import { UploadService } from '../../services/upload.service'; import { UsersService } from '../../services/users.service'; import { forkJoin } from '../../../../node_modules/rxjs'; import { User } from '../../model/user'; import { Select2Opti...
(event: any): void { // The event input variable holds the user id // Find the user const user = this.users.find(x => x.Id === Number(event)); // Hide the user dropdown this.toggleUserDropdown(); // Refresh the job list this.selectedUser = user; this.ref.detectChanges(); } /** Met...
onUserChange
identifier_name
upload-progress.component.ts
import { Component, OnInit, Input, ChangeDetectorRef } from '@angular/core'; import { UploadService } from '../../services/upload.service'; import { UsersService } from '../../services/users.service'; import { forkJoin } from '../../../../node_modules/rxjs'; import { User } from '../../model/user'; import { Select2Opti...
private ref: ChangeDetectorRef) { } ngOnInit() { // Define the observable(s) const usersObservable = this.usersService.getUsers(); // API call(s) forkJoin([usersObservable]).subscribe(results => { // Initialise the list of users this.users = results[0]; // Initialise the curr...
public awaitingConfirmationCount = 0; constructor(private uploadService: UploadService, private usersService: UsersService,
random_line_split
quiz_group.py
from canvasapi.canvas_object import CanvasObject from canvasapi.exceptions import RequiredFieldMissing from canvasapi.util import combine_kwargs class QuizGroup(CanvasObject): def
(self): return "{} ({})".format(self.name, self.id) def delete(self, **kwargs): """ Get details of the quiz group with the given id. :calls: `DELETE /api/v1/courses/:course_id/quizzes/:quiz_id/groups/:id \ <https://canvas.instructure.com/doc/api/quiz_question_groups.html#me...
__str__
identifier_name
quiz_group.py
from canvasapi.canvas_object import CanvasObject from canvasapi.exceptions import RequiredFieldMissing from canvasapi.util import combine_kwargs class QuizGroup(CanvasObject): def __str__(self):
def delete(self, **kwargs): """ Get details of the quiz group with the given id. :calls: `DELETE /api/v1/courses/:course_id/quizzes/:quiz_id/groups/:id \ <https://canvas.instructure.com/doc/api/quiz_question_groups.html#method.quizzes/quiz_groups.destroy>`_ :returns: True...
return "{} ({})".format(self.name, self.id)
identifier_body
quiz_group.py
from canvasapi.canvas_object import CanvasObject from canvasapi.exceptions import RequiredFieldMissing from canvasapi.util import combine_kwargs class QuizGroup(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) def delete(self, **kwargs): """ Get details of...
super(QuizGroup, self).set_attributes(response.json().get("quiz_groups")[0]) return successful
random_line_split
quiz_group.py
from canvasapi.canvas_object import CanvasObject from canvasapi.exceptions import RequiredFieldMissing from canvasapi.util import combine_kwargs class QuizGroup(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) def delete(self, **kwargs): """ Get details of...
for question in order: if not isinstance(question, dict): raise ValueError( "`order` must consist only of dictionaries representing " "Question items." ) if "id" not in question: raise ValueError("D...
raise ValueError("Param `order` must be a non-empty list.")
conditional_block
actions.py
# Copyright 2017 AT&T Intellectual Property. All other 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...
class TaskShow(CliAction): # pylint: disable=too-few-public-methods """Action to show a task's detial.""" def __init__(self, api_client, task_id, block=False, poll_interval=15): """Object initializer. :param DrydockClient api_client: The api client used for invocation. :param strin...
return task
conditional_block
actions.py
# Copyright 2017 AT&T Intellectual Property. All other 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...
(self): """Invoke execution of this action.""" task = self.api_client.get_task(task_id=self.task_id) if not self.block: return task task_id = task.get('task_id') while True: time.sleep(self.poll_interval) task = self.api_client.get_task(task...
invoke
identifier_name
actions.py
# Copyright 2017 AT&T Intellectual Property. All other 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...
self.logger.debug("Node names = %s", node_names) self.logger.debug("Rack names = %s", rack_names) self.logger.debug("Node tags = %s", node_tags) self.block = block self.poll_interval = poll_interval if any([node_names, rack_names, node_tags]): filter_items =...
design_ref) self.logger.debug('Action is %s', action_name)
random_line_split
actions.py
# Copyright 2017 AT&T Intellectual Property. All other 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...
def invoke(self): """Invoke execution of this action.""" task = self.api_client.create_task( design_ref=self.design_ref, task_action=self.action_name, node_filter=self.node_filter) if not self.block: return task task_id = task.get('...
"""Object initializer. :param DrydockClient api_client: The api client used for invocation. :param string design_ref: The URI reference to design documents :param string action_name: The name of the action being performed for this task :param List node_names: The list of node names to r...
identifier_body
danmaku.py
#!/usr/bin/env python2 # -*- coding:utf-8 -*- import signal import json import argparse import threading import requests from settings import load_config from app import GDanmakuApp from server_selection import ServerSelectionWindow from danmaku_ui import Danmaku from gi.repository import Gtk, GLib, GObject class Ma...
if __name__ == '__main__': main() # vim: ts=4 sw=4 sts=4 expandtab
options = load_config() parser = argparse.ArgumentParser(prog="gdanmaku") parser.add_argument( "--server", type=str, default=options["http_stream_server"], help="danmaku stream server" ) parser.add_argument( '--config', action="store_true", help=...
identifier_body
danmaku.py
#!/usr/bin/env python2 # -*- coding:utf-8 -*- import signal import json import argparse import threading import requests from settings import load_config from app import GDanmakuApp
from gi.repository import Gtk, GLib, GObject class Main(object): def __init__(self, server=None): self.server = server server_selection = ServerSelectionWindow(self.server) server_selection.connect('server-selected', self.on_server_selected) self.app = GDanmakuApp(self) se...
from server_selection import ServerSelectionWindow from danmaku_ui import Danmaku
random_line_split
danmaku.py
#!/usr/bin/env python2 # -*- coding:utf-8 -*- import signal import json import argparse import threading import requests from settings import load_config from app import GDanmakuApp from server_selection import ServerSelectionWindow from danmaku_ui import Danmaku from gi.repository import Gtk, GLib, GObject class Ma...
def on_danmaku_delete(self, dm, event): self.live_danmakus.pop(id(dm)) def toggle_danmaku(self): self.enabled = not self.enabled if not self.enabled: for _, dm in self.live_danmakus.iteritems(): dm.hide() dm._clean_exit() def on_server_...
try: dm = Danmaku(**opt) dm.connect('delete-event', self.on_danmaku_delete) except Exception as e: print(e) continue self.live_danmakus[id(dm)] = dm
conditional_block
danmaku.py
#!/usr/bin/env python2 # -*- coding:utf-8 -*- import signal import json import argparse import threading import requests from settings import load_config from app import GDanmakuApp from server_selection import ServerSelectionWindow from danmaku_ui import Danmaku from gi.repository import Gtk, GLib, GObject class Ma...
(): options = load_config() parser = argparse.ArgumentParser(prog="gdanmaku") parser.add_argument( "--server", type=str, default=options["http_stream_server"], help="danmaku stream server" ) parser.add_argument( '--config', action="store_true", ...
main
identifier_name
statuses.js
define(['config', 'folders'], function (config, folders) { var wrikeStates = { 'active': 0, 'completed': 1, 'deferred': 2, 'cancelled': 3 }; var statusFolders = folders.getSubfolders(config.statusFolder) , statuses = {} , statusesById = {}; $.each(statusFolders, function (i, val) { var wrikeState = ...
val.powerWrike.wrikeState = wrikeState; statuses[val.powerWrike.uniquePath] = statusesById[val.id] = val; }); return { statuses: statuses, statusesById: statusesById, }; });
{ debug.warn('Status has the wrong format. Should be titled "123. Your Status Name (Active|Completed|Deferred|Cancelled)"\nYou provided "' + val.data.title + '"'); return; }
conditional_block
statuses.js
define(['config', 'folders'], function (config, folders) { var wrikeStates = { 'active': 0, 'completed': 1, 'deferred': 2, 'cancelled': 3 }; var statusFolders = folders.getSubfolders(config.statusFolder) , statuses = {} , statusesById = {}; $.each(statusFolders, function (i, val) { var wrikeState = ...
} val.powerWrike.wrikeState = wrikeState; statuses[val.powerWrike.uniquePath] = statusesById[val.id] = val; }); return { statuses: statuses, statusesById: statusesById, }; });
if (wrikeState === null || typeof (wrikeState = wrikeStates[wrikeState[1].toLowerCase()]) === 'undefined') { debug.warn('Status has the wrong format. Should be titled "123. Your Status Name (Active|Completed|Deferred|Cancelled)"\nYou provided "' + val.data.title + '"'); return;
random_line_split
xlang_kafkaio_it_test.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
logging.getLogger().setLevel(logging.INFO) unittest.main()
conditional_block
xlang_kafkaio_it_test.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
def run_xlang_kafkaio(self, pipeline): self.build_write_pipeline(pipeline) self.build_read_pipeline(pipeline) pipeline.run(False) @unittest.skipUnless( os.environ.get('LOCAL_KAFKA_JAR'), "LOCAL_KAFKA_JAR environment var is not provided.") class CrossLanguageKafkaIOTest(unittest.TestCase): de...
_ = ( pipeline | 'ReadFromKafka' >> ReadFromKafka( consumer_config={ 'bootstrap.servers': self.bootstrap_servers, 'auto.offset.reset': 'earliest' }, topics=[self.topic], expansion_service=self.expansion_service) | 'W...
identifier_body
xlang_kafkaio_it_test.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
(self): options = PipelineOptions([ '--runner', 'FlinkRunner', '--parallelism', '2', '--experiment', 'beam_fn_api' ]) return options def test_kafkaio_write(self): local_kafka_jar = os.environ.get('LOCAL_KAFKA_JAR') with self.local_kafka_service(loca...
get_options
identifier_name
xlang_kafkaio_it_test.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) unittest.main()
job.wait_until_finish()
random_line_split
project-cache-issue-31849.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { // More parens, more time. let it = ((((((((((),()),()),()),()),()),()),()),()),()); it.build(); }
main
identifier_name
project-cache-issue-31849.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub trait ToStatic { type Static: 'static; fn to_static(self) -> Self::Static where Self: Sized; } impl<T, U> ToStatic for (T, U) where T: ToStatic, U: ToStatic { type Static = (T::Static, U::Static); fn to_static(self) -> Self::Static { (self.0.to_static(), self.1.to_static()) } } i...
{ () }
identifier_body
project-cache-issue-31849.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn upcast(self) -> () { () } } pub trait ToStatic { type Static: 'static; fn to_static(self) -> Self::Static where Self: Sized; } impl<T, U> ToStatic for (T, U) where T: ToStatic, U: ToStatic { type Static = (T::Static, U::Static); fn to_static(self) -> Self::Static { (self.0.to_stat...
impl Upcast<()> for () {
random_line_split
tri10.rs
use russell_lab::{Matrix, Vector}; /// Defines a triangle with 10 nodes (cubic edges; interior node) /// /// # Local IDs of nodes /// /// ```text /// s /// | /// 2, (0,1) /// | ', /// | ', /// 5 7, /// | ', /// | ', /// 8 9 4, /// | ', /// | (0,0) ', (1,0) /// 0-----3---...
}
{ let (r, s) = (ksi[0], ksi[1]); let z = 1.0 - r - s; let q0 = 4.5 * (6.0 * z - 1.0); let q1 = 4.5 * s * (3.0 * s - 1.0); let q2 = 4.5 * z * (3.0 * z - 1.0); let q3 = 4.5 * r * (3.0 * r - 1.0); let q4 = 4.5 * (6.0 * s - 1.0); let q5 = 4.5 * (6.0 * r - 1....
identifier_body
tri10.rs
use russell_lab::{Matrix, Vector}; /// Defines a triangle with 10 nodes (cubic edges; interior node) /// /// # Local IDs of nodes /// /// ```text /// s /// | /// 2, (0,1) /// | ', /// | ', /// 5 7, /// | ', /// | ', /// 8 9 4, /// | ', /// | (0,0) ', (1,0) /// 0-----3---...
/// ``` /// /// # Local IDs of edges /// /// ```text /// |\ /// | \ /// | \ 1 /// 2| \ /// | \ /// |_____\ /// 0 /// ``` pub struct Tri10 {} impl Tri10 { pub const NDIM: usize = 2; pub const NNODE: usize = 10; pub const NEDGE: usize = 3; pub const NFACE: usize = 0; pub const EDGE_NNO...
random_line_split
tri10.rs
use russell_lab::{Matrix, Vector}; /// Defines a triangle with 10 nodes (cubic edges; interior node) /// /// # Local IDs of nodes /// /// ```text /// s /// | /// 2, (0,1) /// | ', /// | ', /// 5 7, /// | ', /// | ', /// 8 9 4, /// | ', /// | (0,0) ', (1,0) /// 0-----3---...
(deriv: &mut Matrix, ksi: &[f64]) { let (r, s) = (ksi[0], ksi[1]); let z = 1.0 - r - s; let q0 = 4.5 * (6.0 * z - 1.0); let q1 = 4.5 * s * (3.0 * s - 1.0); let q2 = 4.5 * z * (3.0 * z - 1.0); let q3 = 4.5 * r * (3.0 * r - 1.0); let q4 = 4.5 * (6.0 * s - 1.0); ...
calc_deriv
identifier_name
test_different_outputs.py
import unittest from polycircles import polycircles from nose.tools import assert_equal, assert_almost_equal class TestDifferentOutputs(unittest.TestCase): """Tests the various output methods: KML style, WKT, lat-lon and lon-lat.""" def setUp(self): self.latitude = 32.074322 self.longitude = ...
(self): """Asserts that the return value of to_kml() property is identical to the return value of to_lon_lat().""" assert_equal(self.polycircle.to_kml(), self.polycircle.to_lon_lat()) if __name__ == '__main__': unittest.main()
test_kml_equals_lon_lat
identifier_name
test_different_outputs.py
import unittest from polycircles import polycircles from nose.tools import assert_equal, assert_almost_equal class TestDifferentOutputs(unittest.TestCase): """Tests the various output methods: KML style, WKT, lat-lon and lon-lat.""" def setUp(self): self.latitude = 32.074322 self.longitude = ...
unittest.main()
conditional_block
test_different_outputs.py
import unittest from polycircles import polycircles from nose.tools import assert_equal, assert_almost_equal class TestDifferentOutputs(unittest.TestCase): """Tests the various output methods: KML style, WKT, lat-lon and lon-lat.""" def setUp(self): self.latitude = 32.074322 self.longitude = ...
assert_equal(self.polycircle.vertices, self.polycircle.to_lat_lon()) def test_kml_equals_lon_lat(self): """Asserts that the return value of to_kml() property is identical to the return value of to_lon_lat().""" assert_equal(self.polycircle.to_kml(), self.polycircle.to_lon_lat()) if...
assert_almost_equal(vertex[1], self.latitude, places=2) def test_vertices_equals_lat_lon(self): """Asserts that the "vertices" property is identical to the return value of to_lat_lon()."""
random_line_split
test_different_outputs.py
import unittest from polycircles import polycircles from nose.tools import assert_equal, assert_almost_equal class TestDifferentOutputs(unittest.TestCase): """Tests the various output methods: KML style, WKT, lat-lon and lon-lat.""" def setUp(self): self.latitude = 32.074322 self.longitude = ...
def test_vertices_equals_lat_lon(self): """Asserts that the "vertices" property is identical to the return value of to_lat_lon().""" assert_equal(self.polycircle.vertices, self.polycircle.to_lat_lon()) def test_kml_equals_lon_lat(self): """Asserts that the return value of to_k...
"""Asserts that the vertices in the lat-lon output are in the right order (lat before long).""" for vertex in self.polycircle.to_lon_lat(): assert_almost_equal(vertex[0], self.longitude, places=2) assert_almost_equal(vertex[1], self.latitude, places=2)
identifier_body
safeEval.py
#!/usr/bin/env python3 # Copyright 2016 - 2021 Bas van Meerten and Wouter Franssen # This file is part of ssNake. # # ssNake 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, o...
""" Creates a more restricted eval environment. Note that this method is still not acceptable to process strings from untrusted sources. Parameters ---------- inp : str String to evaluate. length : int or float, optional The variable length will be set to this value. By ...
identifier_body
safeEval.py
#!/usr/bin/env python3 # Copyright 2016 - 2021 Bas van Meerten and Wouter Franssen # This file is part of ssNake. # # ssNake 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, o...
(inp, length=None, Type='All', x=None): """ Creates a more restricted eval environment. Note that this method is still not acceptable to process strings from untrusted sources. Parameters ---------- inp : str String to evaluate. length : int or float, optional The variable l...
safeEval
identifier_name