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 |
|---|---|---|---|---|
AgentManager.py | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
from blueman.Functions import dprint
from blueman.bluez.obex.Base import Base
class AgentManager(Base):
def __init__(self):
super(AgentManager, self).__init... |
def on_register_failed(error):
dprint(agent_path, error)
self._interface.RegisterAgent(agent_path, reply_handler=on_registered, error_handler=on_register_failed)
def unregister_agent(self, agent_path):
def on_unregistered():
dprint(agent_path)
def on_unre... | dprint(agent_path) | identifier_body |
AgentManager.py | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import |
from blueman.Functions import dprint
from blueman.bluez.obex.Base import Base
class AgentManager(Base):
def __init__(self):
super(AgentManager, self).__init__('org.bluez.obex.AgentManager1', '/org/bluez/obex')
def register_agent(self, agent_path):
def on_registered():
dprint(agen... | from __future__ import unicode_literals | random_line_split |
AgentManager.py | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
from blueman.Functions import dprint
from blueman.bluez.obex.Base import Base
class | (Base):
def __init__(self):
super(AgentManager, self).__init__('org.bluez.obex.AgentManager1', '/org/bluez/obex')
def register_agent(self, agent_path):
def on_registered():
dprint(agent_path)
def on_register_failed(error):
dprint(agent_path, error)
self... | AgentManager | identifier_name |
main.rs | #![allow(unused_variables)]
extern crate rustc_serialize;
#[macro_use] extern crate serde_derive;
extern crate docopt;
extern crate sdl2;
extern crate num;
extern crate rand;
#[macro_use] extern crate enum_primitive as ep;
mod chip8;
mod screen;
mod instruction;
use docopt::Docopt;
use sdl2::keyboard::Keycode;
use s... | Keycode::Q => chip8.press(0x4),
Keycode::W => chip8.press(0x5),
Keycode::E => chip8.press(0x6),
Keycode::R => chip8.press(0xd),
Keycode::A => chip8.press(0x7),
K... | random_line_split | |
main.rs | #![allow(unused_variables)]
extern crate rustc_serialize;
#[macro_use] extern crate serde_derive;
extern crate docopt;
extern crate sdl2;
extern crate num;
extern crate rand;
#[macro_use] extern crate enum_primitive as ep;
mod chip8;
mod screen;
mod instruction;
use docopt::Docopt;
use sdl2::keyboard::Keycode;
use s... | () {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
let ctx = sdl2::init().unwrap();
let mut chip8 = Chip8::new(&ctx);
let mut events = ctx.event_pump().unwrap();
chip8.load_rom(&args.arg_file);
'main: loop {
for even... | main | identifier_name |
vmware_host_firewall_manager.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... |
def ensure(self):
"""
Function to ensure rule set configuration
"""
fw_change_list = []
results = dict(changed=False, rule_set_state=dict())
for host in self.hosts:
firewall_system = host.configManager.firewallSystem
if firewall_system is No... | temp_rule_dict = dict()
temp_rule_dict['enabled'] = rule_set_obj.enabled
self.firewall_facts[host.name][rule_set_obj.key] = temp_rule_dict | conditional_block |
vmware_host_firewall_manager.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... | ():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
rules=dict(type='list', default=list(), required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,... | main | identifier_name |
vmware_host_firewall_manager.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... | Function to ensure rule set configuration
"""
fw_change_list = []
results = dict(changed=False, rule_set_state=dict())
for host in self.hosts:
firewall_system = host.configManager.firewallSystem
if firewall_system is None:
continue
... | temp_rule_dict['enabled'] = rule_set_obj.enabled
self.firewall_facts[host.name][rule_set_obj.key] = temp_rule_dict
def ensure(self):
""" | random_line_split |
vmware_host_firewall_manager.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... | def ensure(self):
"""
Function to ensure rule set configuration
"""
fw_change_list = []
results = dict(changed=False, rule_set_state=dict())
for host in self.hosts:
firewall_system = host.configManager.firewallSystem
if firewall_system is None... | def __init__(self, module):
super(VmwareFirewallManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.options = self.params.get('options', dict())
self.hosts = self.get_all_host_objs(clust... | identifier_body |
room.service.ts | import { Injectable } from '@angular/core';
import { Http, Response, Headers, Request, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Room } from "app/room/Room.model";
import { DynamicUrl } from "app/DynamicUrl.model";
@Injectable()
export class RoomService {
construc... |
getRoomByIdMap(id : number) : Observable<any>{
let ret = this.http.get(DynamicUrl.socket + `api/Room/Read/${id}`).map(r => r.json());
return ret;
}
getRoomsByIdMap(Id : number) : Observable<any>{
let ret = this.http.get(DynamicUrl.socket + `api/Room/ReadAll?$filter=AccommodationId eq ${Id}`).map(... | {
return this.http.get(DynamicUrl.socket + `api/Room/Read/${id}`);
} | identifier_body |
room.service.ts | import { Injectable } from '@angular/core';
import { Http, Response, Headers, Request, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Room } from "app/room/Room.model";
import { DynamicUrl } from "app/DynamicUrl.model";
@Injectable()
export class RoomService {
construc... | return ret;
}
getRoomsByIdMap(Id : number) : Observable<any>{
let ret = this.http.get(DynamicUrl.socket + `api/Room/ReadAll?$filter=AccommodationId eq ${Id}`).map(res => res.json());
return ret;
}
deleteRoom(id : number) : Observable<any> {
let opts = DynamicUrl.PutHeader();
return th... | random_line_split | |
room.service.ts | import { Injectable } from '@angular/core';
import { Http, Response, Headers, Request, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Room } from "app/room/Room.model";
import { DynamicUrl } from "app/DynamicUrl.model";
@Injectable()
export class RoomService {
construc... | (id : number) : Observable<any> {
let opts = DynamicUrl.PutHeader();
return this.http.delete(DynamicUrl.socket + `api/Room/Delete/${id}`, opts);
}
editRoom(room: Room) : Observable<any> {
let opts = DynamicUrl.PutHeader();
return this.http.put(DynamicUrl.socket + `api/Room/Change`, ... | deleteRoom | identifier_name |
test_models.py | # coding: utf-8
from django.test import TestCase
from django.db import IntegrityError
from datetime import datetime
from eventex.subscriptions.models import Subscription
class SubscriptionTest(TestCase):
def setUp(self):
self.obj = Subscription(
name='Henrique Bastos',
cpf='1234567... | s = Subscription.objects.create(name='Henrique Bastos', cpf='00000000011',
email='henrique@bastos.net')
self.assertEqual(2, s.pk) | random_line_split | |
test_models.py | # coding: utf-8
from django.test import TestCase
from django.db import IntegrityError
from datetime import datetime
from eventex.subscriptions.models import Subscription
class SubscriptionTest(TestCase):
def setUp(self):
self.obj = Subscription(
name='Henrique Bastos',
cpf='1234567... | def setUp(self):
# Create a first entry to force collision.
Subscription.objects.create(name='Henrique Bastos', cpf='12345678901',
email='henrique@bastos.net', phone='21-96186180')
def test_cpf_unique(self):
"""
CPF must be unique
"""
... | identifier_body | |
test_models.py | # coding: utf-8
from django.test import TestCase
from django.db import IntegrityError
from datetime import datetime
from eventex.subscriptions.models import Subscription
class SubscriptionTest(TestCase):
def setUp(self):
self.obj = Subscription(
name='Henrique Bastos',
cpf='1234567... | (self):
"""
Subscription must have name, cpf, email, phone
"""
self.obj.save()
self.assertEqual(1, self.obj.pk)
def test_has_created_at(self):
"""
Subscription must have automatica created_at.
"""
self.obj.save()
self.assertIsInstance(... | test_create | identifier_name |
build_orca.py | #!/usr/bin/python2
import argparse
import os
import subprocess
import sys
BASE_DIR = os.getcwd()
def build_install_orca(prefix, path):
# by default conan will install the files under /usr/local
return subprocess.call(["./configure --prefix={0} && make && make install_local".format(prefix)],
... |
if __name__ == "__main__":
sys.exit(main())
| return status | conditional_block |
build_orca.py | #!/usr/bin/python2
import argparse
import os
import subprocess
import sys
BASE_DIR = os.getcwd()
def build_install_orca(prefix, path):
# by default conan will install the files under /usr/local
return subprocess.call(["./configure --prefix={0} && make && make install_local".format(prefix)],
... |
if __name__ == "__main__":
sys.exit(main())
| parser = argparse.ArgumentParser(description='Main driver to build and install ORCA using conan')
parser.add_argument('--prefix', help='Configure prefix path', type=str, default='/tmp/')
required_arguments = parser.add_argument_group('required arguments')
required_arguments.add_argument('--cmakepath', help=... | identifier_body |
build_orca.py | #!/usr/bin/python2
import argparse
import os
import subprocess
import sys
BASE_DIR = os.getcwd()
def build_install_orca(prefix, path):
# by default conan will install the files under /usr/local
return subprocess.call(["./configure --prefix={0} && make && make install_local".format(prefix)],
... | (orca_install_dir_prefix):
return subprocess.call(["tar -czf {0}/bin_orca/bin_orca_conan.tar.gz ./include ./lib".format(BASE_DIR)],
shell=True, cwd=orca_install_dir_prefix)
def main():
parser = argparse.ArgumentParser(description='Main driver to build and install ORCA using conan')
... | package_orca | identifier_name |
build_orca.py | #!/usr/bin/python2
import argparse
import os
import subprocess | import sys
BASE_DIR = os.getcwd()
def build_install_orca(prefix, path):
# by default conan will install the files under /usr/local
return subprocess.call(["./configure --prefix={0} && make && make install_local".format(prefix)],
shell=True,
cwd="gpdb_src/de... | random_line_split | |
google-drive-picker.js | /** !
* Google Drive File Picker Example
* By Daniel Lo Nigro (http://dan.cx/)
*/
(function () {
/**
* Initialise a Google Driver file picker
*/
var FilePicker = window.FilePicker = function (options) {
// Config
this.apiKey = options.apiKey
this.clientId = options.clientId
// Elements
... | immediate: immediate
}, callback || function () {})
}
}
}()) | scope: 'https://www.googleapis.com/auth/drive.readonly', | random_line_split |
google-drive-picker.js | /** !
* Google Drive File Picker Example
* By Daniel Lo Nigro (http://dan.cx/)
*/
(function () {
/**
* Initialise a Google Driver file picker
*/
var FilePicker = window.FilePicker = function (options) {
// Config
this.apiKey = options.apiKey
this.clientId = options.clientId
// Elements
... |
},
/**
* Show the file picker once authentication has been done.
* @private
*/
_showPicker: function () {
var accessToken = window.gapi.auth.getToken().access_token
var view = new window.google.picker.DocsView()
view.setMimeTypes('text/markdown,text/html')
view.setIn... | {
// The user has not yet authenticated with Google
// We need to do the authentication before displaying the Drive picker.
this._doAuth(false, function () { this._showPicker() }.bind(this))
} | conditional_block |
mock-usb-producer.py | # -*- Mode:python; coding: utf-8; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
#
# Copyright (C) 2016 Endless Mobile, Inc.
# Author: Niv Sardi <xaiki@endlessm.com>
#
# 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
# ... | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("dir")
args = parser.parse_args()
store = simple_store.Producer(
prefix=SUBSCRIPTIONS_SOMA, base=path.realpath(args.dir))
logger.info('creating store: %s', args.__dict__)
store.start()
GLib.MainLoop().run() | conditional_block | |
mock-usb-producer.py | # -*- Mode:python; coding: utf-8; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
#
# Copyright (C) 2016 Endless Mobile, Inc.
# Author: Niv Sardi <xaiki@endlessm.com>
#
# 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
# ... |
import gi
gi.require_version('GLib', '2.0')
from gi.repository import GLib
from eos_data_distribution.names import SUBSCRIPTIONS_SOMA
from eos_data_distribution.store import simple_store
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
if __name__ == '__main__':
import... | from os import path | random_line_split |
alerts.ts | 'use strict';
import {Injectable, Inject} from '@angular/core';
import { Platform, Events} from 'ionic-angular';
import {GeofenceProvider} from './geofence';
import { Storage } from '@ionic/storage';
@Injectable()
export class AlertsProvider {
private geofenceProvider: GeofenceProvider;
private ALERTS_DATA: stri... | }
getAlertsData() {
return this.storage.get(this.ALERTS_DATA).then((value) => {
return value;
});
}
} | {
/*var alerts = [
{sensorName: 'Sensor 1', temperature: '100', pressure: '80'},
{sensorName: 'Sensor 2', temperature: '101', pressure: '82'},
{sensorName: 'Sensor 3', temperature: '102', pressure: '83'}
];
*/
/*
if (alerts.length > 0) {
if(this.ALERTS_DATA == '' || this.A... | identifier_body |
alerts.ts | 'use strict';
import {Injectable, Inject} from '@angular/core';
import { Platform, Events} from 'ionic-angular';
import {GeofenceProvider} from './geofence';
import { Storage } from '@ionic/storage';
@Injectable()
export class AlertsProvider {
private geofenceProvider: GeofenceProvider;
private ALERTS_DATA: stri... | () {
this.events.subscribe('geofence:vehicleout', () => {
this.geofenceProvider.getGeofenceData().then((geofence) => {
geofence = JSON.parse(geofence);
if (geofence.length > 0) {
this.setAlertsData(geofence);
}
});
});
}
setAlertsData(data) {
/*var aler... | listenToGeofenceEvents | identifier_name |
alerts.ts | 'use strict';
import {Injectable, Inject} from '@angular/core';
import { Platform, Events} from 'ionic-angular';
import {GeofenceProvider} from './geofence';
import { Storage } from '@ionic/storage';
@Injectable()
export class AlertsProvider {
private geofenceProvider: GeofenceProvider;
private ALERTS_DATA: stri... |
});
});
}
setAlertsData(data) {
/*var alerts = [
{sensorName: 'Sensor 1', temperature: '100', pressure: '80'},
{sensorName: 'Sensor 2', temperature: '101', pressure: '82'},
{sensorName: 'Sensor 3', temperature: '102', pressure: '83'}
];
*/
/*
if (alerts.length >... | {
this.setAlertsData(geofence);
} | conditional_block |
alerts.ts | 'use strict';
import {Injectable, Inject} from '@angular/core';
import { Platform, Events} from 'ionic-angular';
import {GeofenceProvider} from './geofence';
import { Storage } from '@ionic/storage';
@Injectable()
export class AlertsProvider {
private geofenceProvider: GeofenceProvider;
private ALERTS_DATA: stri... | setAlertsData(data) {
/*var alerts = [
{sensorName: 'Sensor 1', temperature: '100', pressure: '80'},
{sensorName: 'Sensor 2', temperature: '101', pressure: '82'},
{sensorName: 'Sensor 3', temperature: '102', pressure: '83'}
];
*/
/*
if (alerts.length > 0) {
if(this.ALERT... | });
});
}
| random_line_split |
image.py | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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.apac... |
def run(self):
if os.path.exists(self.image.path):
self.image.state = image_states['failed']
self.image.save(update_fields=['state'])
log.error(self.image.user.id, "Destination image %d for user %d exists! Aborting creation" % (
self.image.id, self.image.use... | threading.Thread.__init__(self)
self.image = image
self.filesystem = filesystem | identifier_body |
image.py | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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.apac... |
self.dest_image.state = image_states['ok']
self.dest_image.size = self.src_image.size
self.dest_image.save(update_fields=['progress', 'state', 'size'])
src.close()
dst.close()
except Exception, e:
log.exception(self.dest_image.user.id, "... | buff = src.read(1024 * 1024) # Should be less than MTU?
if len(buff) > 0 and copied <= size:
dst.write(buff)
copied = copied + len(buff)
else:
break
# Update image information:
progress = 100 * c... | conditional_block |
image.py | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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.apac... |
log.info(self.image.user.id, 'md5 hash of image %d is %s' % (self.image.id, md5sum.hexdigest()))
self.image.state = image_states['ok']
self.image.size = downloaded_size / (1024 * 1024)
self.image.save(update_fields=['progress', 'state', 'size'])
message.info(... | self.image.progress = progress
self.image.save(update_fields=['progress'])
dest_image.close() | random_line_split |
image.py | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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.apac... | (threading.Thread):
def __init__(self, src_image, dest_image):
threading.Thread.__init__(self)
self.src_image = src_image
self.dest_image = dest_image
def run(self):
copied = 0
prev_progress = 0
try:
size = os.path.getsize(self.src_image.path)
... | CopyImage | identifier_name |
index.d.ts | // Type definitions for sequelize-cursor-pagination 1.2
// Project: https://github.com/Kaltsoon/sequelize-cursor-pagination
// Definitions by: pilagod <https://github.com/pilagod>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/
// TypeScript Version: 3.2
import Sequelize = require('sequelize');
de... | function withPagination<MethodName extends string = 'paginate'>(options?: WithPaginationOptions<MethodName>): (
<Model extends Sequelize.Model<ModelInst, ModelAttrs>, ModelInst, ModelAttrs>(model: Model) => WithPaginationModel<MethodName, Model, ModelInst, ModelAttrs>
);
}
export = SequelizeCursorPagin... | random_line_split | |
lean.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import * as CodeMirror from "codemirror";
/*
This is just a first tiny quick step. To finish this:
- Look at https://codemirror.net/demo/simplemode.html for how this works.
... | { regex: /begin/, indent: true },
{ regex: /end/, dedent: true },
{ regex: /[a-z$][\w$]*/, token: "variable" },
{ regex: /b?"/, token: "string", next: "string" },
],
string: [
{ regex: /"/, token: "string", next: "start" },
{ regex: /(?:[^\\"]|\\(?:.|$))*/, token: "string" },
],
blockcom... | {
regex: /0x[a-f\d]+|[-+]?(?:\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/i,
token: "number",
},
{ regex: /\/-.*?-\//, token: "comment" }, | random_line_split |
old_serialize.py | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Modifications made by Cloudera are:
# Copyright (c) 2016 Cloudera, Inc. 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. A cop... | # need to add a new child dict as the value of the passed in dict.
# Below we will add all the structure members to the new serialized
# dictionary we just created.
serialized[key] = OrderedDict()
serialized = serialized[key]
for member_key, member_va... | random_line_split | |
old_serialize.py | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Modifications made by Cloudera are:
# Copyright (c) 2016 Cloudera, Inc. 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. A cop... | if key:
serialized[key] = value
else:
for member_key, member_value in value.items():
serialized[member_key] = member_value | identifier_body | |
old_serialize.py | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Modifications made by Cloudera are:
# Copyright (c) 2016 Cloudera, Inc. 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. A cop... | (object):
DEFAULT_ENCODING = 'utf-8'
def serialize_to_request(self, parameters, operation_model):
# Don't serialize any parameter with a None value.
filtered_parameters = OrderedDict(
(k, v) for k, v in parameters.items() if v is not None)
serialized = {}
# serializ... | Serializer | identifier_name |
old_serialize.py | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Modifications made by Cloudera are:
# Copyright (c) 2016 Cloudera, Inc. 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. A cop... |
serialized['body'] = json.dumps(serialized_body).encode(self.DEFAULT_ENCODING)
return serialized
def _serialize(self, serialized, value, shape, key=None):
# serialize_method_name = '_serialize_type_%s' % shape.type_name
# method = getattr(self, serialize_method_name, self._defaul... | self._serialize(serialized_body, filtered_parameters, None) | conditional_block |
trace.rs | use profile_traits::time::ProfilerChan as TimeProfilerChan;
use script_task::ScriptChan;
use script_traits::{LayoutMsg, ScriptMsg, TimerEventId, TimerSource, UntrustedNodeAddress};
use selectors::parser::PseudoElement;
use selectors::states::*;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::boxed... |
}
impl<T: JSTraceable + Copy> JSTraceable for Cell<T> {
fn trace(&self, trc: *mut JSTracer) {
self.get().trace(trc)
}
}
impl<T: JSTraceable> JSTraceable for UnsafeCell<T> {
fn trace(&self, trc: *mut JSTracer) {
unsafe { (*self.get()).trace(trc) }
}
}
impl JSTraceable for Heap<*mut J... | {
(**self).trace(trc)
} | identifier_body |
trace.rs | (*tracer).debugPrintIndex_ = !0;
(*tracer).debugPrintArg_ = name.as_ptr() as *const libc::c_void;
debug!("tracing {}", description);
JS_CallObjectTracer(tracer,
obj.ptr.get() as *mut _,
GCTraceKindToAscii(JSGCTraceKind::JSTRACE_OBJECT));
... | move<T | identifier_name | |
trace.rs | // if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type)
impl<T: JSTraceable + 'static> JSTraceable for SmallVec<[T; 1]> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.trace(trc);
}
}
}
impl<T: JSTraceable> JSTraceable for Option<T> {
#[... | random_line_split | ||
0009_simple_multiplication_with_stdin.rs | // Compute product of two numbers while accepting value from standard input.
use std::io; // imports io library from standard library
fn main() {
let mut a = String::new(); //creates new, empty String
let mut b = String::new();
let c: u32;
println!("Enter value a:");
io::stdin().read_line(&mut a... |
//Shadowing lets us to re-use the old name.
// parse() method on String converts the String into number
let a: u32 = a.trim().parse()
.ok()
.expect("Please type a number");
let b: u32 = b.trim().parse()
.ok()
.expect("Please type a number");
... | .expect("Failed to read value"); | random_line_split |
0009_simple_multiplication_with_stdin.rs | // Compute product of two numbers while accepting value from standard input.
use std::io; // imports io library from standard library
fn | () {
let mut a = String::new(); //creates new, empty String
let mut b = String::new();
let c: u32;
println!("Enter value a:");
io::stdin().read_line(&mut a)
.ok()
.expect("Failed to read value");
println!("Enter value b:");
io::stdin().read_line(&mut b)
... | main | identifier_name |
0009_simple_multiplication_with_stdin.rs | // Compute product of two numbers while accepting value from standard input.
use std::io; // imports io library from standard library
fn main() |
let b: u32 = b.trim().parse()
.ok()
.expect("Please type a number");
c = a * b;
println!("Product of {} * {} is {} ", a, b, c);
}
| {
let mut a = String::new(); //creates new, empty String
let mut b = String::new();
let c: u32;
println!("Enter value a:");
io::stdin().read_line(&mut a)
.ok()
.expect("Failed to read value");
println!("Enter value b:");
io::stdin().read_line(&mut b)
... | identifier_body |
create-group.ts | import { getEmailTransport, initializeAdminApp } from './_internal';
import * as functions from 'firebase-functions';
import { District, GroupCreateInput, RepresentativeCreateInput } from '@civ/city-council';
import { createRandomString } from './utils';
const app = initializeAdminApp();
const db = app.database();
co... | (repId: string, group: { id: string, name: string }, district?: { id: string, name: string }) {
let obj: any = {
[group.id]: {
name: group.name,
role: 'representative',
district
}
};
if (district) {
obj.district = { id: district.id, name: district.name }
}
return await db.ref(`... | updateRepresentativeGroups | identifier_name |
create-group.ts | import { getEmailTransport, initializeAdminApp } from './_internal';
import * as functions from 'firebase-functions';
import { District, GroupCreateInput, RepresentativeCreateInput } from '@civ/city-council';
import { createRandomString } from './utils';
const app = initializeAdminApp();
const db = app.database();
co... | <p>Look forward to seeing you online! </p>
<p>-Team Civinomics</p>
</div>
`
};
return new Promise((resolve, reject) => {
const transport = getEmailTransport();
transport.sendMail(msg, (err, info) => {
if (err) {
reject(err);
return;
}
... | </div>
<div>
<p>
If you have any questions, don't hesitate to contact us at <a href="mailto:info@civinomics.com">info@civinomics.com</a>
</p> | random_line_split |
create-group.ts | import { getEmailTransport, initializeAdminApp } from './_internal';
import * as functions from 'firebase-functions';
import { District, GroupCreateInput, RepresentativeCreateInput } from '@civ/city-council';
import { createRandomString } from './utils';
const app = initializeAdminApp();
const db = app.database();
co... |
return await db.ref(`/user/${repId}/groups`).update(obj);
}
| {
obj.district = { id: district.id, name: district.name }
} | conditional_block |
create-group.ts | import { getEmailTransport, initializeAdminApp } from './_internal';
import * as functions from 'firebase-functions';
import { District, GroupCreateInput, RepresentativeCreateInput } from '@civ/city-council';
import { createRandomString } from './utils';
const app = initializeAdminApp();
const db = app.database();
co... |
async function pushBasicInfo(name: string, icon: string, owner: string): Promise<string> {
console.info(`pushing basic info: {name: ${name}, icon: ${icon}, owner: ${owner}`);
const result = await db.ref(`/group`).push({ name, icon, owner });
return result.key;
}
async function createUserAccountForRepresent... | {
return await db.ref(`/group/${groupId}/representatives`).update({
[repId]: {
firstName: repData.firstName,
lastName: repData.lastName,
icon: repData.icon,
email: repData.email,
title: repData.title
}
})
} | identifier_body |
gestalt-tests.tsx | import {
Avatar,
Badge,
Box,
Button,
Card,
Checkbox,
Collage,
Column,
Container,
Divider,
Flyout,
GroupAvatar,
Heading,
Icon,
IconButton,
Image,
Label,
Layer,
Letterbox,
Link,
Mask,
Masonry,
Modal,
Pog,
Pulsar,
Radio... | Tabs,
Text,
TextArea,
TextField,
Toast,
Tooltip,
Touchable,
Video,
} from 'gestalt';
import * as React from 'react';
const MasonryComponent = ({}) => {
return <div>Masonry</div>;
};
<Avatar name="Nicolas" />;
<Badge text="Nicolas" />;
<Box />;
<Button text={'Click me'} />;
<Card />... | Switch, | random_line_split |
hexcanvas.py | from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty, ObjectProperty, BoundedNumericProperty, ListProperty
from .node import Node
from math import sqrt
class HexCanvas(FloatLayout):
last_node = ObjectProperty(None, allownone=True)
grid = ObjectProperty([])
row_count = ... |
def clean(self):
# TODO remove vhelixes and other stuff !!!
self.last_node = None
# for row in self.grid:
# for node in row:
# del node
self.grid = []
self.vvhelix_id = 0
self.scaffold_path = []
self.__construct()
| row = []
if j % 2 != 0:
offset = x_offset
else:
offset = 0
x = x_start + offset
for i in range(self.column_count):
node = Node(pos=(x, y), grid_id=(j, i))
row.append(node)
self.add_widget(node... | conditional_block |
hexcanvas.py | from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty, ObjectProperty, BoundedNumericProperty, ListProperty
from .node import Node
from math import sqrt
class | (FloatLayout):
last_node = ObjectProperty(None, allownone=True)
grid = ObjectProperty([])
row_count = BoundedNumericProperty(11, min=0, max=11)
column_count = BoundedNumericProperty(22, min=0, max=22)
vvhelix_id = NumericProperty(0)
scaffold_path = ListProperty([])
"""docstring for NanoCa... | HexCanvas | identifier_name |
hexcanvas.py | from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty, ObjectProperty, BoundedNumericProperty, ListProperty
from .node import Node
from math import sqrt
class HexCanvas(FloatLayout):
last_node = ObjectProperty(None, allownone=True)
grid = ObjectProperty([])
row_count = ... |
def __construct(self):
x_start, y_start = 30, 30
a = 60
x_offset = a / 2
y_offset = a * sqrt(3) / 2
y = y_start
for j in range(self.row_count):
row = []
if j % 2 != 0:
offset = x_offset
else:
offset ... | def __init__(self, **kwargs):
#super(HexCanvas, self).__init__(**kwargs)
super().__init__(**kwargs)
self.__construct() | random_line_split |
hexcanvas.py | from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty, ObjectProperty, BoundedNumericProperty, ListProperty
from .node import Node
from math import sqrt
class HexCanvas(FloatLayout):
last_node = ObjectProperty(None, allownone=True)
grid = ObjectProperty([])
row_count = ... |
def __construct(self):
x_start, y_start = 30, 30
a = 60
x_offset = a / 2
y_offset = a * sqrt(3) / 2
y = y_start
for j in range(self.row_count):
row = []
if j % 2 != 0:
offset = x_offset
else:
offset... | super().__init__(**kwargs)
self.__construct() | identifier_body |
CenteredText.js | import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Typography from '@material-ui/core/Typography'
export default ({ text, icon }) => {
const cx = useStyles()
return (
<div className={cx.root}>
<div className={cx.container}>
{icon}
<div className={cx.tex... | alignItems: 'flex-start',
justifyContent: 'center'
},
title: {
fontSize: '2em',
fontWeight: 400
}
})) | container: {
color: '#00052b',
display: 'flex', | random_line_split |
frontend.js | /* Copyright 2018 Onestein
* License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). */
odoo.define('website_lazy_load_image.lazy_image_loader', function (require) {
'use strict';
var Class = require('web.Class');
var mixins = require('web.mixins');
/**
* Handles lazy loading of images.
... | };
},
/**
* Triggered by the beforeLoad event of the lazy loading plugin.
*
* @param {DOMElement} el
* @private
*/
_beforeLoad: function (el) {
this.trigger('beforeLoad', el);
},
/**
* Triggered by th... | onFinishedAll: this._onFinishedAll.bind(this),
chainable: false, | random_line_split |
participants.py | """
How to Use this File.
participants is a dictionary where a key is the name of the participant and the value is
a set of all the invalid selections for that participant.
participants = {'Bob': {'Sue', 'Jim'},
'Jim': {'Bob', 'Betty'},
} # And so on.
history is a dictionary where a key is the name of ... |
def main():
return sorted([Participant(p) for p in participants.keys()],
key=lambda p: len(p.restricted_set), reverse=True)
if __name__ == '__main__':
main() | """The class for individual participants that contains their attributes."""
def __init__(self, name, restricted_set=None, giving_to=None):
self.name = name
self.restricted_set = restricted_set
self.restricted_set = participants.get(self.name)|set([y[1] for y in history.get(self.name)])
... | identifier_body |
participants.py | """
How to Use this File.
participants is a dictionary where a key is the name of the participant and the value is
a set of all the invalid selections for that participant.
participants = {'Bob': {'Sue', 'Jim'},
'Jim': {'Bob', 'Betty'},
} # And so on.
history is a dictionary where a key is the name of ... | 'Shaina': [(2017, 'Amanda')],
'Stefan': [(2015, 'George'), (2016, 'Renee'), (2017, 'Joe'), (2018, 'Francesca')],
}
class Participant:
"""The class for individual participants that contains their attributes."""
def __init__(self, name, restricted_set=None, giving_to=None):
... | 'Jeff': [(2015, 'Nanna'), (2016, 'Justin'), (2017, 'Shaina'), (2018, 'Amanda')],
'Joe': [(2015, 'Renee'), (2016, 'George'), (2017, 'Justin'), (2018, 'Angela')],
'Justin': [(2015, 'Francesca'), (2016, 'Adam'), (2017, 'George'), (2018, 'Renee')],
'Nanna': [(2015, 'David')],
... | random_line_split |
participants.py | """
How to Use this File.
participants is a dictionary where a key is the name of the participant and the value is
a set of all the invalid selections for that participant.
participants = {'Bob': {'Sue', 'Jim'},
'Jim': {'Bob', 'Betty'},
} # And so on.
history is a dictionary where a key is the name of ... | :
"""The class for individual participants that contains their attributes."""
def __init__(self, name, restricted_set=None, giving_to=None):
self.name = name
self.restricted_set = restricted_set
self.restricted_set = participants.get(self.name)|set([y[1] for y in history.get(self.name)]... | Participant | identifier_name |
participants.py | """
How to Use this File.
participants is a dictionary where a key is the name of the participant and the value is
a set of all the invalid selections for that participant.
participants = {'Bob': {'Sue', 'Jim'},
'Jim': {'Bob', 'Betty'},
} # And so on.
history is a dictionary where a key is the name of ... | main() | conditional_block | |
SimpleForm.js | import React from 'react';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import compose from 'recompose/compose';
import getDefaultValues from './getDefaultValues';
import FormField from './FormField';
import Toolbar from './Toolbar';
const noop = ()... | handleSubmit: PropTypes.func,
invalid: PropTypes.bool,
record: PropTypes.object,
resource: PropTypes.string,
basePath: PropTypes.string,
validate: PropTypes.func,
submitOnEnter: PropTypes.bool,
};
SimpleForm.defaultProps = {
submitOnEnter: true,
};
const enhance = compose(
connect(... | ]), | random_line_split |
inline-comment-spacing.js | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | * @fileoverview This option controls spacing before a inline comment.
* @author Joe Schafer
*/
goog.module('eslintClosure.rules.inlineCommentSpacing');
const utils = goog.require('eslintClosure.utils');
/** @const {number} */
const DEFAULT_PRECEDING_SPACES = 1;
/** @const {!ESLint.RuleDefinition} */
const INLINE... | /** | random_line_split |
inline-comment-spacing.js | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | (commentNode) {
const sourceCode = context.getSourceCode();
// Need to call getComments to attach comments to the AST.
sourceCode.getComments(commentNode);
// TODO: I'm not sure why I can't just call getTokenBefore. The tests
// fail if either of the two calls is missing.
const pre... | checkLineCommentForPrecedingSpace | identifier_name |
inline-comment-spacing.js | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | sourceCode.getTokenOrCommentBefore(commentNode);
// Return early if there's no tokens before commentNode or there's only
// whitespace.
if (previousToken == null ||
!utils.nodesShareOneLine(commentNode, previousToken)) {
return;
}
const whiteSpaceGap = comme... | {
// Check for null explicitily because 0 is a falsey value.
/** @const {number} */
const minPrecedingSpaces = context.options[0] == null ?
DEFAULT_PRECEDING_SPACES :
/** @type {number} */ (context.options[0]);
/**
* Reports a given comment if it's invalid..
* @param {!AST... | identifier_body |
inline-comment-spacing.js | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
const whiteSpaceGap = commentNode.start - previousToken.end;
if (whiteSpaceGap < minPrecedingSpaces) {
const spacesNoun = minPrecedingSpaces === 1 ? 'space' : 'spaces';
context.report({
node: commentNode,
message: `Expected at least ${minPrecedingSpaces} ${spacesNoun} ... | {
return;
} | conditional_block |
init-res-into-things.rs | // run-pass
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![feature(box_syntax)]
use std::cell::Cell;
// Resources can't be copied, but storing into data structures counts
// as a move unless the stored thing is used afterwards.
struct r<'a> {
i: &'a Cell<isize>,
}
struct BoxR<'a> { x: r<'a> }
impl<'a... | <'a> {
t0(r<'a>),
}
let i = &Cell::new(0);
{
let _a = t::t0(r(i));
}
assert_eq!(i.get(), 1);
}
fn test_tup() {
let i = &Cell::new(0);
{
let _a = (r(i), 0);
}
assert_eq!(i.get(), 1);
}
fn test_unique() {
let i = &Cell::new(0);
{
let _a: Box<_... | t | identifier_name |
init-res-into-things.rs | // run-pass
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![feature(box_syntax)]
use std::cell::Cell;
// Resources can't be copied, but storing into data structures counts
// as a move unless the stored thing is used afterwards.
struct r<'a> {
i: &'a Cell<isize>,
}
struct BoxR<'a> { x: r<'a> }
impl<'a... | }
let i = &Cell::new(0);
{
let _a = t::t0(r(i));
}
assert_eq!(i.get(), 1);
}
fn test_tup() {
let i = &Cell::new(0);
{
let _a = (r(i), 0);
}
assert_eq!(i.get(), 1);
}
fn test_unique() {
let i = &Cell::new(0);
{
let _a: Box<_> = box r(i);
}
as... |
fn test_tag() {
enum t<'a> {
t0(r<'a>), | random_line_split |
stock_change_quant_lot.py | # -*- coding: utf8 -*-
#
# Copyright (C) 2017 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# Licen... | "the lot %s of article %s: this is not possible") %
(product.display_name, self.lot_id.name,
self.lot_id.product_id.display_name))
else:
self.qu... | raise exceptions.except_orm(_("Error!"), _("You are trying to set a quant of product %s to " | random_line_split |
stock_change_quant_lot.py | # -*- coding: utf8 -*-
#
# Copyright (C) 2017 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# Licen... | products = set([quant.product_id for quant in self])
if len(products) > 1:
raise exceptions.except_orm(_("Error!"), _("You have quants of different products: %s. "
"Please change lots product by product") %
... | aise exceptions.except_orm(_("Error!"), _("You are not allowed to execute this action."))
| conditional_block |
stock_change_quant_lot.py | # -*- coding: utf8 -*-
#
# Copyright (C) 2017 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# Licen... | models.Model):
_inherit = 'stock.quant'
@api.multi
def change_quants_lots(self):
group_stock_manager = self.env.ref('stock.group_stock_manager')
if group_stock_manager not in self.env.user.groups_id:
raise exceptions.except_orm(_("Error!"), _("You are not allowed to execute this... | tockChangeQuantLotStockQuant( | identifier_name |
stock_change_quant_lot.py | # -*- coding: utf8 -*-
#
# Copyright (C) 2017 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# Licen... | self.quant_ids.sudo().write({'lot_id': self.lot_id.id})
| name = 'stock.change.quant.lot'
quant_ids = fields.Many2many('stock.quant', string=u"Quants", readonly=True)
product_id = fields.Many2one('product.product', related='quant_ids.product_id', readonly=True,
string=u"Product of the lot")
lot_id = fields.Many2one('stock.producti... | identifier_body |
xmlpoke.d.ts | // Type definitions for xmlpoke 0.1.12
// Project: https://github.com/mikeobrien/node-xmlpoke
// Definitions by: Garth Kidd <https://github.com/garthk/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../xpath/xpath.d.ts" />
declare module XmlPoke { // ghost module
interface T... | set(map: PathToValueMap): API;
setOrAdd(xpath: string, value: Value): API;
setOrAdd(map: PathToValueMap): API;
remove(xpath: string): API;
clear(xpath: string): API;
withBasePath(xpath: string): API;
addNamespace(prefix: string, uri: string): API;
errorOnNoMatches(): API;
}
interface CDataValue {
va... | add(map: PathToValueMap): API;
set(xpath: string, value: Value): API; | random_line_split |
adiabatic_flame.py | #
# ADIABATIC_FLAME - A freely-propagating, premixed methane/air flat
# flame with multicomponent transport properties
#
from Cantera import *
from Cantera.OneD import *
from Cantera.OneD.FreeFlame import FreeFlame
################################################################
#
# parameter values
#
p ... |
fcsv.close()
print 'solution saved to adiabatic_flame.csv'
print 'multicomponent flamespeed = ',u[0]
f.showStats()
| f.setGasState(n)
writeCSV(fcsv, [z[n], u[n], V[n], T[n], gas.density()]
+list(gas.moleFractions())) | conditional_block |
adiabatic_flame.py | #
# ADIABATIC_FLAME - A freely-propagating, premixed methane/air flat
# flame with multicomponent transport properties
#
from Cantera import *
from Cantera.OneD import *
from Cantera.OneD.FreeFlame import FreeFlame
################################################################
#
# parameter values
#
p ... | T = f.T()
u = f.u()
V = f.V()
fcsv = open('adiabatic_flame.csv','w')
writeCSV(fcsv, ['z (m)', 'u (m/s)', 'V (1/s)', 'T (K)', 'rho (kg/m3)']
+ list(gas.speciesNames()))
for n in range(f.flame.nPoints()):
f.setGasState(n)
writeCSV(fcsv, [z[n], u[n], V[n], T[n], gas.density()]
+list(gas.moleF... | 'solution with the energy equation enabled and multicomponent transport')
# write the velocity, temperature, density, and mole fractions to a CSV file
z = f.flame.grid() | random_line_split |
operations.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... |
db.session.flush()
if changes:
signals.event.contribution_updated.send(contrib, changes=changes)
logger.info('Contribution %s updated by %s', contrib, session.user)
contrib.event.log(EventLogRealm.management, EventLogKind.change, 'Contributions',
'Contribution ... | rv['unscheduled'] = True
rv['undo_unschedule'] = {'start_dt': timetable_entry.start_dt.isoformat(),
'contribution_id': contrib.id,
'session_block_id': current_session_block.id if current_session_block else None,
... | conditional_block |
operations.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... |
@no_autoflush
def create_contribution_from_abstract(abstract, contrib_session=None):
event = abstract.event
contrib_person_links = set()
person_link_attrs = {'_title', 'address', 'affiliation', 'first_name', 'last_name', 'phone', 'author_type',
'is_speaker', 'display_order'}
... | subcontrib.is_deleted = True
db.session.flush()
signals.event.subcontribution_deleted.send(subcontrib)
logger.info('Subcontribution %s deleted by %s', subcontrib, session.user)
subcontrib.event.log(EventLogRealm.management, EventLogKind.negative, 'Subcontributions',
'Subcontribu... | identifier_body |
operations.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | (subcontrib):
subcontrib.is_deleted = True
db.session.flush()
signals.event.subcontribution_deleted.send(subcontrib)
logger.info('Subcontribution %s deleted by %s', subcontrib, session.user)
subcontrib.event.log(EventLogRealm.management, EventLogKind.negative, 'Subcontributions',
... | delete_subcontribution | identifier_name |
operations.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | be unscheduled)
"""
rv = {'unscheduled': False, 'undo_unschedule': None}
current_session_block = contrib.session_block
start_dt = contrib_data.pop('start_dt', None)
if start_dt is not None:
update_timetable_entry(contrib.timetable_entry, {'start_dt': start_dt})
changes = con... | case `undo_unschedule` contains the necessary data to
re-schedule it (undoing the session change causing it to | random_line_split |
dump.rs | extern crate wasmparser;
use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::str;
use wasmparser::Parser;
use wasmparser::ParserState;
use wasmparser::WasmDecoder;
fn main() {
let args = env::args().collect::<Vec<_>>();
if args.len() != 2 {
println!("Usage: {} in.wasm", arg... | loop {
print!("0x{:08x}\t", parser.current_position());
let state = parser.read();
match *state {
ParserState::ExportSectionEntry {
field,
ref kind,
index,
} => {
println!(
"ExportSect... | return;
}
let buf: Vec<u8> = read_wasm(&args[1]).unwrap();
let mut parser = Parser::new(&buf); | random_line_split |
dump.rs | extern crate wasmparser;
use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::str;
use wasmparser::Parser;
use wasmparser::ParserState;
use wasmparser::WasmDecoder;
fn | () {
let args = env::args().collect::<Vec<_>>();
if args.len() != 2 {
println!("Usage: {} in.wasm", args[0]);
return;
}
let buf: Vec<u8> = read_wasm(&args[1]).unwrap();
let mut parser = Parser::new(&buf);
loop {
print!("0x{:08x}\t", parser.current_position());
le... | main | identifier_name |
dump.rs | extern crate wasmparser;
use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::str;
use wasmparser::Parser;
use wasmparser::ParserState;
use wasmparser::WasmDecoder;
fn main() {
let args = env::args().collect::<Vec<_>>();
if args.len() != 2 {
println!("Usage: {} in.wasm", arg... | {
let mut data = Vec::new();
let mut f = File::open(file)?;
f.read_to_end(&mut data)?;
Ok(data)
} | identifier_body | |
condvar.rs | use crate::ffi::c_void;
use crate::ptr;
use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use crate::sys::hermit::abi;
use crate::sys::mutex::Mutex;
use crate::time::Duration;
// The implementation is inspired by Andrew D. Birrell's paper
// "Implementing Condition Variables with Semaphores"
pub struct Condva... | (&self) {
let _ = abi::sem_destroy(self.sem1);
let _ = abi::sem_destroy(self.sem2);
}
}
| destroy | identifier_name |
condvar.rs | use crate::ffi::c_void;
use crate::ptr;
use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use crate::sys::hermit::abi;
use crate::sys::mutex::Mutex;
use crate::time::Duration;
// The implementation is inspired by Andrew D. Birrell's paper
// "Implementing Condition Variables with Semaphores"
pub struct Condva... |
}
pub unsafe fn notify_all(&self) {
let counter = self.counter.swap(0, SeqCst);
for _ in 0..counter {
abi::sem_post(self.sem1);
}
for _ in 0..counter {
abi::sem_timedwait(self.sem2, 0);
}
}
pub unsafe fn wait(&self, mutex: &Mutex) {
... | {
self.counter.fetch_sub(1, SeqCst);
abi::sem_post(self.sem1);
abi::sem_timedwait(self.sem2, 0);
} | conditional_block |
condvar.rs | use crate::ffi::c_void;
use crate::ptr;
use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use crate::sys::hermit::abi;
use crate::sys::mutex::Mutex;
use crate::time::Duration;
// The implementation is inspired by Andrew D. Birrell's paper
// "Implementing Condition Variables with Semaphores"
pub struct Condva... | mutex.unlock();
let millis = dur.as_millis().min(u32::MAX as u128) as u32;
let res = if millis > 0 {
abi::sem_timedwait(self.sem1, millis)
} else {
abi::sem_trywait(self.sem1)
};
abi::sem_post(self.sem2);
mutex.lock();
res == 0
... | self.counter.fetch_add(1, SeqCst); | random_line_split |
condvar.rs | use crate::ffi::c_void;
use crate::ptr;
use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use crate::sys::hermit::abi;
use crate::sys::mutex::Mutex;
use crate::time::Duration;
// The implementation is inspired by Andrew D. Birrell's paper
// "Implementing Condition Variables with Semaphores"
pub struct Condva... |
pub unsafe fn init(&mut self) {
let _ = abi::sem_init(&mut self.sem1 as *mut *const c_void, 0);
let _ = abi::sem_init(&mut self.sem2 as *mut *const c_void, 0);
}
pub unsafe fn notify_one(&self) {
if self.counter.load(SeqCst) > 0 {
self.counter.fetch_sub(1, SeqCst);
... | {
Condvar { counter: AtomicUsize::new(0), sem1: ptr::null(), sem2: ptr::null() }
} | identifier_body |
gallery-tipsy.js | var Lang = Y.Lang,
getCN = Y.ClassNameManager.getClassName,
//HTML5 Data Attributes
DATA_CONTENT = 'data-content',
DATA_PLACEMENT = 'data-placement',
//Classes
TIPSY = 'tipsy',
FADE = 'fade',
IN = 'in',
CLASSES = {
fade: getCN(TIPSY, FADE),
fadeIn: getCN(TIPSY, IN)... | else {
Y.log('The hideOn attribute should contain an array of events, or an object with keys "selector" (string), and "events" (array of events)');
}
if (delay) {
this._timer = Y.later(delay*1000, this, 'showTooltip', node);
} else {
this.show... | //hideOn = { node: '#selector', events: ['event1', 'event2'] }
else if (Lang.isObject(hideOn) && hideOn.selector && hideOn.events) {
this._handles.push(Y.one(hideOn.selector).on(hideOn.events, this._handleDelegateEnd, this));
} | random_line_split |
gallery-tipsy.js |
var Lang = Y.Lang,
getCN = Y.ClassNameManager.getClassName,
//HTML5 Data Attributes
DATA_CONTENT = 'data-content',
DATA_PLACEMENT = 'data-placement',
//Classes
TIPSY = 'tipsy',
FADE = 'fade',
IN = 'in',
CLASSES = {
fade: getCN(TIPSY, FADE),
fadeIn: getCN(TIPS... |
//showOn = { events: ['event1', 'event2'] }
else if (Lang.isObject(showOn) && !showOn.node) {
this._handles.push(del.delegate(showOn.events, this._handleDelegateStart, selector, this));
}
//showOn = { node: '#selector', events: ['event1', 'event2'] }
else if (Lang.... | {
this._handles.push(del.delegate(showOn, this._handleDelegateStart, selector, this));
} | conditional_block |
index.tsx | , QueryRevision } from "../queries";
import { Param, parseParams, stringifyParams } from "../parameters";
type option = {
label: string,
value: QueryRevision
}
const Input = (props: InputProps) => <components.Input {...props} isHidden={false} />;
const height = 43;
const MenuList = (props: any) => {
const { o... | (input: string): [string, string, number] {
let matches = input.match(queryTargetRegex) || [];
matches = matches.map(s => s.replace('/', ''));
return [matches[0] || "", matches[1] || "", parseInt(matches[2] || "") || 0];
}
const disableNoOptionsMessage = () => null;
type QueryControlsProps = {
params: Param[]... | parseQueryRevision | identifier_name |
index.tsx | value: QueryRevision
}
const Input = (props: InputProps) => <components.Input {...props} isHidden={false} />;
const height = 43;
const MenuList = (props: any) => {
const { options, children, maxHeight, getValue } = props;
const [value] = getValue();
const initialOffset = options.indexOf(value) * height;
re... | </ul> | random_line_split | |
index.tsx | QueryRevision } from "../queries";
import { Param, parseParams, stringifyParams } from "../parameters";
type option = {
label: string,
value: QueryRevision
}
const Input = (props: InputProps) => <components.Input {...props} isHidden={false} />;
const height = 43;
const MenuList = (props: any) => {
const { op... |
if (!Boolean(input) && Boolean(selectedNamespace) && Boolean(selectedQuery)) {
const namespacedQuery = `${selectedNamespace}/${selectedQuery}`
return candidate.label.includes(namespacedQuery);
}
const [namespace, queryName] = parseQueryRevision(input);
if (namespace && queryName) {
const namespac... | {
return false;
} | conditional_block |
index.tsx | QueryRevision } from "../queries";
import { Param, parseParams, stringifyParams } from "../parameters";
type option = {
label: string,
value: QueryRevision
}
const Input = (props: InputProps) => <components.Input {...props} isHidden={false} />;
const height = 43;
const MenuList = (props: any) => {
const { op... |
const disableNoOptionsMessage = () => null;
type QueryControlsProps = {
params: Param[],
disableActions: {run: boolean, save: boolean, archive: boolean},
onChange: (query: QueryRevision, params: Param[]) => void,
onRun: () => void,
onSave: () => void,
onMenuOpen: () => void,
onArchiveQuery: () => void,... | {
let matches = input.match(queryTargetRegex) || [];
matches = matches.map(s => s.replace('/', ''));
return [matches[0] || "", matches[1] || "", parseInt(matches[2] || "") || 0];
} | identifier_body |
date_pipe.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { PipeTransform } from '@angular/core';
/**
* @ngModule CommonModule
* @description
*
* Formats a date accordi... | * shown below or custom as shown in the table.
* - `'medium'`: equivalent to `'yMMMdjms'` (e.g. `Sep 3, 2010, 12:05:08 PM` for `en-US`)
* - `'short'`: equivalent to `'yMdjm'` (e.g. `9/3/2010, 12:05 PM` for `en-US`)
* - `'fullDate'`: equivalent to `'yMMMMEEEEd'` (e.g. `Friday, September 3, 2010` for `en-US`)... | *
* Where:
* - `expression` is a date object or a number (milliseconds since UTC epoch) or an ISO string
* (https://www.w3.org/TR/NOTE-datetime).
* - `format` indicates which date/time components to include. The format can be predefined as | random_line_split |
date_pipe.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { PipeTransform } from '@angular/core';
/**
* @ngModule CommonModule
* @description
*
* Formats a date accordi... | implements PipeTransform {
private _locale;
constructor(_locale: string);
transform(value: any, pattern?: string): string | null;
}
| DeprecatedDatePipe | identifier_name |
RecordAudio.py | import sys
import time
from naoqi import ALProxy
IP = "nao.local"
PORT = 9559
if (len(sys.argv) < 2):
|
fileName = "/home/nao/" + sys.argv[1] + ".wav"
aur = ALProxy("ALAudioRecorder", IP, PORT)
channels = [0,0,1,0]
aur.startMicrophonesRecording(fileName, "wav", 160000, channels)
c=raw_input("Sfarsit?")
aur.stopMicrophonesRecording()
c=raw_input("play?")
aup = ALProxy("ALAudioPlayer", IP, PORT)
#Launchs the playing o... | print "Usage: 'python RecordAudio.py nume'"
sys.exit(1) | conditional_block |
RecordAudio.py | import sys
import time
from naoqi import ALProxy
IP = "nao.local"
PORT = 9559
| fileName = "/home/nao/" + sys.argv[1] + ".wav"
aur = ALProxy("ALAudioRecorder", IP, PORT)
channels = [0,0,1,0]
aur.startMicrophonesRecording(fileName, "wav", 160000, channels)
c=raw_input("Sfarsit?")
aur.stopMicrophonesRecording()
c=raw_input("play?")
aup = ALProxy("ALAudioPlayer", IP, PORT)
#Launchs the playing of ... | if (len(sys.argv) < 2):
print "Usage: 'python RecordAudio.py nume'"
sys.exit(1)
| random_line_split |
md5.js | tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var output = "";
var len = input.length;
for(var i = 0; i < len; i += 3)
{
var triplet = (input.charCodeAt(i) << 16)
| (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)... | d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
... | random_line_split | |
md5.js | (s) { return rstr2hex(rstr_md5(str2rstr_utf8(s))); }
function b64_md5(s) { return rstr2b64(rstr_md5(str2rstr_utf8(s))); }
function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); }
function hex_hmac_md5(k, d)
{ return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_ut... | hex_md5 | identifier_name | |
md5.js | + 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 5... | {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
} | identifier_body | |
ast_clone.rs | use std::str::FromStr;
use {
proc_macro2::{Span, TokenStream},
syn::{
self, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed, FieldsUnnamed,
Generics, Ident, Variant,
},
};
use crate::{
attr,
shared::{map_lifetimes, map_type_params, split_for_impl},
};
pub fn de... |
fn create_ast_clone_bounds(generics: &Generics) -> Vec<TokenStream> {
map_type_params(generics, |ty| {
quote! {
#ty: gluon_base::ast::AstClone<'ast, Id>
}
})
}
fn create_lifetime_bounds(generics: &Generics) -> Vec<TokenStream> {
map_lifetimes(generics, |_lifetime| {
qu... | {
let fields = fields.into_iter().map(|field| {
let field_ty = &field.ty;
let field_ident = field
.ident
.as_ref()
.expect("Struct fields always have names");
quote! {
#field_ident: <#field_ty as gluon_base::ast::AstClone<_>>::ast_clone(#field_... | identifier_body |
ast_clone.rs | use std::str::FromStr;
use {
proc_macro2::{Span, TokenStream},
syn::{
self, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed, FieldsUnnamed,
Generics, Ident, Variant,
},
};
use crate::{
attr,
shared::{map_lifetimes, map_type_params, split_for_impl},
};
pub fn de... |
quote! {
#[allow(non_upper_case_globals)]
const #dummy_const: () = {
use crate as gluon_base;
#[automatically_derived]
#[allow(unused_attributes, unused_variables)]
impl #impl_generics gluon_base::ast::AstClone<'ast, Id> for #ident #ty_generics
... | quote! { #b, }
}); | random_line_split |
ast_clone.rs | use std::str::FromStr;
use {
proc_macro2::{Span, TokenStream},
syn::{
self, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed, FieldsUnnamed,
Generics, Ident, Variant,
},
};
use crate::{
attr,
shared::{map_lifetimes, map_type_params, split_for_impl},
};
pub fn de... | (ident: &Ident, _tag: usize, variant: &Variant) -> TokenStream {
let variant_ident = &variant.ident;
// depending on the type of the variant we need to generate different constructors
// for the enum
match &variant.fields {
Fields::Unit => quote! {
#ident::#variant_ident => #ident::... | gen_variant_match | identifier_name |
gulpfile.js | var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cac... | // Optimization Tasks
// ------------------
// Optimizing CSS and JavaScript
gulp.task('useref', function() {
return gulp.src('app/*.html')
.pipe(useref())
.pipe(gulpIf('app/js/*.js', uglify()))
.pipe(gulpIf('app/css/*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
// Optimizing I... | gulp.watch('app/css/*.+(scss|sass)', ['sass']);
gulp.watch('app/*.html', browserSync.reload);
gulp.watch('app/js/**/*.js', browserSync.reload);
}); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.