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
ics-convert.py
#!/usr/bin/env python """Converts the .ics/.ical file into a FullCalendar compatiable JSON file FullCalendar uses a specific JSON format similar to iCalendar format. This script creates a JSON file containing renamed event components. Only the title, description, start/end time, and url data are used. Does not support...
'start':component.decoded('dtstart').isoformat(), 'end':component.decoded('dtend').isoformat(), 'url':component.get('url') } # append to the result array result.append(event) ics_file.close() # saves the result using jsonify json_out = open(out_file, 'w') json_out.write(json.dumps(result, sort_keys = Fa...
event = { 'title':component.get('summary'), 'backgroundColor':component.get('location'), 'description':component.get('description'),
random_line_split
ics-convert.py
#!/usr/bin/env python """Converts the .ics/.ical file into a FullCalendar compatiable JSON file FullCalendar uses a specific JSON format similar to iCalendar format. This script creates a JSON file containing renamed event components. Only the title, description, start/end time, and url data are used. Does not support...
# default output filename (just adds .json extension on the given file) out_file = sys.argv[1] + '.json' if (len(sys.argv) == 3): # changes output filename to the 2nd arugment out_file = sys.argv[2] # opens the input .ics file and parses it as iCalendar Calendar object ics_file = open(sys.argv[1],'rb') ics_cal = ...
print sys.argv[0] + ': illegal operation' print 'usage: python ' + sys.argv[0] + ' file [output]' exit(1)
conditional_block
server.js
/* eslint-disable */ "use strict"; var express = require("express"), path = require("path"), webpack = require("webpack"), config = require("./examples.config"); config.module.loaders[0].query = {presets: ["react-hmre"]}; config.entry.unshift("webpack-hot-middleware/client"); config.plugins = [ new w...
console.log("Listening at http://localhost:3000"); });
{ console.log(err); return; }
conditional_block
server.js
/* eslint-disable */ "use strict"; var express = require("express"), path = require("path"), webpack = require("webpack"), config = require("./examples.config"); config.module.loaders[0].query = {presets: ["react-hmre"]}; config.entry.unshift("webpack-hot-middleware/client"); config.plugins = [ new w...
});
random_line_split
epubinfo.py
# Copyright (C) 2010, One Laptop Per Child # Copyright (C) 2010, Kushal Das # # 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 ver...
(self): try: subjectlist = [] for element in self._e_metadata.iterfind('.//{http://purl.org/dc/elements/1.1/}subject'): subjectlist.append(element.text) except AttributeError: return None return subjectlist def _get_cover_image(se...
_get_subject
identifier_name
epubinfo.py
# Copyright (C) 2010, One Laptop Per Child # Copyright (C) 2010, Kushal Das # # 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 ver...
return None return ret def _get_rights(self): try: ret = self._get_data('.//{http://purl.org/dc/elements/1.1/}rights') except AttributeError: return None return ret def _get_identifier(self): #TODO: iter elem...
ret = self._get_data('.//{http://purl.org/dc/elements/1.1/}source') except AttributeError:
random_line_split
epubinfo.py
# Copyright (C) 2010, One Laptop Per Child # Copyright (C) 2010, Kushal Das # # 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 ver...
def _get_description(self): try: ret = self._get_data('.//{http://purl.org/dc/elements/1.1/}description') except AttributeError: return None return ret def _get_title(self): try: ret = self._get_data('.//{http://purl.org/dc/elements/1.1/}ti...
element = self._e_metadata.find(tagname) return element.text
identifier_body
epubinfo.py
# Copyright (C) 2010, One Laptop Per Child # Copyright (C) 2010, Kushal Das # # 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 ver...
except AttributeError: return None return subjectlist def _get_cover_image(self): element = self._e_metadata.find('{http://www.idpf.org/2007/opf}meta') if element is not None and element.get('name') == 'cover': return element.get('content') ...
subjectlist.append(element.text)
conditional_block
callback_full_pipeline.py
# Copyright 2013-2015 DataStax, 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 writi...
for _ in range(min(concurrency, self.num_queries)): self.insert_next() self.event.wait() self.finish_profile() if __name__ == "__main__": benchmark(Runner)
concurrency = 100
conditional_block
callback_full_pipeline.py
# Copyright 2013-2015 DataStax, 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 writi...
if __name__ == "__main__": benchmark(Runner)
self.start_profile() if self.protocol_version >= 3: concurrency = 1000 else: concurrency = 100 for _ in range(min(concurrency, self.num_queries)): self.insert_next() self.event.wait() self.finish_profile()
identifier_body
callback_full_pipeline.py
# Copyright 2013-2015 DataStax, 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 writi...
benchmark(Runner)
self.finish_profile() if __name__ == "__main__":
random_line_split
callback_full_pipeline.py
# Copyright 2013-2015 DataStax, 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 writi...
(BenchmarkThread): def __init__(self, *args, **kwargs): BenchmarkThread.__init__(self, *args, **kwargs) self.num_started = count() self.num_finished = count() self.event = Event() def insert_next(self, previous_result=sentinel): if previous_result is not sentinel: ...
Runner
identifier_name
generator-base.js
"use strict"; var YL = Y.Lang, NAMESPACE, STRING, LENGTH, UPPER, LOWER, ALPHALEN, DIGIT, VALID_TYPES, TYPE, ATTRS, getNumber, random, randInt, randBoolean, randListItem; NAMESPACE = "Generator"; UPPER = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"...
return Math.round((Math.random() * (max - min) + min)); }; randBoolean = function () { return Math.round(Math.random()) === 1; }; randListItem = function (list) { return list[randInt(0, list.length - 1)]; }; Y.namespace(NAMESPACE).Base = Y.Base.create("Base", Y.Base, [], { initializer: function (me...
{ return min; }
conditional_block
generator-base.js
"use strict"; var YL = Y.Lang, NAMESPACE, STRING, LENGTH, UPPER, LOWER, ALPHALEN, DIGIT, VALID_TYPES, TYPE, ATTRS, getNumber, random, randInt, randBoolean, randListItem; NAMESPACE = "Generator"; UPPER = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"...
return list[randInt(0, list.length - 1)]; }; Y.namespace(NAMESPACE).Base = Y.Base.create("Base", Y.Base, [], { initializer: function (metadata) { this.setMetadata(metadata); }, setMetadata: function (metadata) { var property; for (property in metadata) { if (metada...
randListItem = function (list) {
random_line_split
filter_modules.py
""" Query modules mapping functions to their query strings structured: module_name { query_string: function_for_query } """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division # Standard imports from future import standar...
return get_trip_db().find(query) def getAlternativeTrips(trip_id): #TODO: clean up datetime, and queries here #d = datetime.datetime.now() - datetime.timedelta(days=6) #query = {'trip_id':trip_id, 'trip_start_datetime':{"$gt":d}} query = {'trip_id':trip_id} alternatives = get_alternatives_db()....
def getTrainingTrips_Date(uid, dys): d = datetime.datetime.now() - datetime.timedelta(days=dys) query = {'user_id':uid, 'type':'move','trip_start_datetime':{"$gt":d}, "pipelineFlags":{"$exists":True}} #query = {'user_id':uid, 'type':'move','trip_start_datetime':{"$gt":d}} #print get_trip_db().count_docu...
random_line_split
filter_modules.py
""" Query modules mapping functions to their query strings structured: module_name { query_string: function_for_query } """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division # Standard imports from future import standar...
cluster_json_list.append(json_dict) toRet = cluster_json_list return toRet.__iter__() #returns all trips to the user def getAllTrips(uid): #trips = list(get_trip_db().find({"user_id":uid, "type":"move"})) query = {'user_id':uid, 'type':'move'} return get_trip_db().find(query) def getAllTrip...
""" uid is a UUID object, not a string """ # canonical_trip_list = [] # x = 0 # if route clusters return nothing, then get common routes for user #clusters = get_routeCluster_db().find_one({'$and':[{'user':uid},{'method':'lcs'}]}) # c = get_routeCluster_db().find_one({'$and':[{'user':uid...
identifier_body
filter_modules.py
""" Query modules mapping functions to their query strings structured: module_name { query_string: function_for_query } """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division # Standard imports from future import standar...
(list,element,key): if element is not None and key in element: list.append(element[key]) else: logging.debug("not appending element %s with key %s" % (element, key)) class AlternativesNotFound(Exception): def __init__(self, value): self.value = value def __str__(self): r...
appendIfPresent
identifier_name
filter_modules.py
""" Query modules mapping functions to their query strings structured: module_name { query_string: function_for_query } """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division # Standard imports from future import standar...
return c_info def appendIfPresent(list,element,key): if element is not None and key in element: list.append(element[key]) else: logging.debug("not appending element %s with key %s" % (element, key)) class AlternativesNotFound(Exception): def __init__(self, value): self.val...
first = True logging.debug( "Number of sections in sectionList for user %s is %s" % (uid, len(sectionList))) if (len(sectionList) == 0): # There's no point in returning this cluster, let's move on continue distributionArrays = [[] for _ in range(5)] ...
conditional_block
interop_xz_encode.rs
#![no_main] #[macro_use] extern crate libfuzzer_sys;
use xz2::stream; fn encode_xz_lzmars(x: &[u8]) -> Result<Vec<u8>> { let mut compressed: Vec<u8> = Vec::new(); lzma_rs::xz_compress(&mut std::io::BufReader::new(x), &mut compressed)?; Ok(compressed) } fn decode_xz_xz2(compressed: &[u8]) -> Result<Vec<u8>> { let bf = std::io::Cursor::new(compressed); ...
use lzma_rs::error::Result; use std::io::Read;
random_line_split
interop_xz_encode.rs
#![no_main] #[macro_use] extern crate libfuzzer_sys; use lzma_rs::error::Result; use std::io::Read; use xz2::stream; fn encode_xz_lzmars(x: &[u8]) -> Result<Vec<u8>> { let mut compressed: Vec<u8> = Vec::new(); lzma_rs::xz_compress(&mut std::io::BufReader::new(x), &mut compressed)?; Ok(compressed) } fn
(compressed: &[u8]) -> Result<Vec<u8>> { let bf = std::io::Cursor::new(compressed); let mut decomp: Vec<u8> = Vec::new(); // create new XZ decompression stream with 8Gb memory limit and checksum verification disabled let xz_stream = stream::Stream::new_stream_decoder(8 * 1024 * 1024 * 1024, stre...
decode_xz_xz2
identifier_name
interop_xz_encode.rs
#![no_main] #[macro_use] extern crate libfuzzer_sys; use lzma_rs::error::Result; use std::io::Read; use xz2::stream; fn encode_xz_lzmars(x: &[u8]) -> Result<Vec<u8>>
fn decode_xz_xz2(compressed: &[u8]) -> Result<Vec<u8>> { let bf = std::io::Cursor::new(compressed); let mut decomp: Vec<u8> = Vec::new(); // create new XZ decompression stream with 8Gb memory limit and checksum verification disabled let xz_stream = stream::Stream::new_stream_decoder(8 * 1024 *...
{ let mut compressed: Vec<u8> = Vec::new(); lzma_rs::xz_compress(&mut std::io::BufReader::new(x), &mut compressed)?; Ok(compressed) }
identifier_body
server.py
#!/usr/bin/env python """Entry point to run app. Used to launch the REST and Cron servers. """ import logging import io import os import flask from flask_api import status from google.cloud import storage from typing import Text logging.getLogger().setLevel(logging.INFO) from metrics import base import env import m...
def _get_cloud_blob(filename: Text) -> storage.Blob: client = storage.Client() bucket = client.get_bucket(env.get('CLOUD_STORAGE_BUCKET')) return storage.Blob(filename, bucket) def _save_to_cloud(data: bytes, filename: Text, content_type: Text): """Saves data to a Google Cloud Storage blob. Args: dat...
'orange', 'yellow', 'green', 'forestgreen', ]
random_line_split
server.py
#!/usr/bin/env python """Entry point to run app. Used to launch the REST and Cron servers. """ import logging import io import os import flask from flask_api import status from google.cloud import storage from typing import Text logging.getLogger().setLevel(logging.INFO) from metrics import base import env import m...
scrapers.scrape(scrape_target) return 'Successfully scraped latest %s.' % scrape_target, status.HTTP_200_OK @app.route('/_cron/recompute/<metric_cls_name>') def recompute(metric_cls_name: Text): # This header is added to cron requests by GAE, and stripped from any external # requests. See # https://cloud.g...
return 'Attempted to access internal endpoint.', status.HTTP_403_FORBIDDEN
conditional_block
server.py
#!/usr/bin/env python """Entry point to run app. Used to launch the REST and Cron servers. """ import logging import io import os import flask from flask_api import status from google.cloud import storage from typing import Text logging.getLogger().setLevel(logging.INFO) from metrics import base import env import m...
@app.route( '/api/plot/<metric_cls_name>.png', defaults={'history_days': HISTORY_DAYS}) @app.route('/api/plot/<history_days>/<metric_cls_name>.png') def metric_history_plot(history_days: Text, metric_cls_name: Text): try: base.Metric.get_metric(metric_cls_name) except KeyError: logging.error('No acti...
try: results = base.Metric.get_latest().values() except Exception as error: return flask.jsonify({'error': error.message}), status.HTTP_500_SERVER_ERROR return flask.jsonify({'metrics': [metric.serializable for metric in results] }), status.HTTP_200_OK
identifier_body
server.py
#!/usr/bin/env python """Entry point to run app. Used to launch the REST and Cron servers. """ import logging import io import os import flask from flask_api import status from google.cloud import storage from typing import Text logging.getLogger().setLevel(logging.INFO) from metrics import base import env import m...
(history_days: Text, metric_cls_name: Text): try: base.Metric.get_metric(metric_cls_name) except KeyError: logging.error('No active metric found for %s.', metric_cls_name) return ('No active metric found for %s.' % metric_cls_name), status.HTTP_404_NOT_FOUND history_days = int(history_day...
metric_history_plot
identifier_name
framework_file_generator.py
#! /usr/bin/python # -*- coding: utf-8 -*- # Developped with python 2.7.3 import os import sys import tools import json print("The frame :") name = raw_input("-> name of the framework ?") kmin = float(raw_input("-> Minimum boundary ?")) kmax = float(raw_input("-> Maximum boundary ?")) precision = float(raw_input("-> ...
#print json.dumps(distribution); exit() o = open(name+".frmwrk",'w') o.write("# A framework is described as above : \n# in following order, we define min_boundary max_boundary precision frequences)\n") o.write(json.dumps([kmin, kmax, precision, distribution])) o.close()
distribution[i] = nb_agent_per_graduation i+= precision i = round(i, tools.get_round_precision(precision)) # fix : python >> 0.2 * 0.4
conditional_block
framework_file_generator.py
#! /usr/bin/python # -*- coding: utf-8 -*- # Developped with python 2.7.3 import os import sys import tools import json print("The frame :") name = raw_input("-> name of the framework ?") kmin = float(raw_input("-> Minimum boundary ?")) kmax = float(raw_input("-> Maximum boundary ?")) precision = float(raw_input("-> ...
o.close()
random_line_split
OrdersEdit.component.ts
/* ------------------------------------------------------------ * Created By : CodeBhagat v1.0 * Created Date : 12/13/2016 * Component : OrdersEditComponent * Purpose : This component retrieves data for the specified record id and allows to edit and save changes. * Dependency : OrdersService * Copyright : ...
opacity: 0, transform: 'translateX(-100%)' }), animate('0.2s ease-in') ]), transition(':leave', [ animate('0.5s ease-out', style({ opacity: 0, transform: 'translateY(100%)' })) ]) ]) ] }) export class OrdersE...
}) ), transition(':enter', [ style({
random_line_split
OrdersEdit.component.ts
/* ------------------------------------------------------------ * Created By : CodeBhagat v1.0 * Created Date : 12/13/2016 * Component : OrdersEditComponent * Purpose : This component retrieves data for the specified record id and allows to edit and save changes. * Dependency : OrdersService * Copyright : ...
} gotoOrders() { let Id = this.objOrders ? this.objOrders.OrderID : null; this.toastr.success('Back to Orders List...'); this.router.navigate(['/Orders']); } // Get Lookup List for Shippers getShippers() { this.ShippersService.getAll().subscribe(records => this.ShippersList=records); ...
{ this.OrdersService.deleteOrders(this.objOrders.OrderID.toString()) .subscribe(record => this.router.navigate(['/Orders']), error => this.errorMessage = 'There was an error while deleting record. Error: ' + <any>error, () => { console.log('Orders record deleted successfully...'); } ); }
conditional_block
OrdersEdit.component.ts
/* ------------------------------------------------------------ * Created By : CodeBhagat v1.0 * Created Date : 12/13/2016 * Component : OrdersEditComponent * Purpose : This component retrieves data for the specified record id and allows to edit and save changes. * Dependency : OrdersService * Copyright : ...
// @HostBinding('style.position') get position() { // return 'absolute'; // } objOrders: OrdersData; errorMessage: string; messages: string[]; // Lookup Arrays ShippersList: ShippersData[]; EmployeesList: EmployeesData[]; constructor(private route: ActivatedRoute, private router: R...
{ return 'block'; }
identifier_body
OrdersEdit.component.ts
/* ------------------------------------------------------------ * Created By : CodeBhagat v1.0 * Created Date : 12/13/2016 * Component : OrdersEditComponent * Purpose : This component retrieves data for the specified record id and allows to edit and save changes. * Dependency : OrdersService * Copyright : ...
(msg: string) { this.messages.splice(0, 0, msg); console.log(msg); } }
log
identifier_name
Simple.ts
</nav> * * <div id="foo">baz</div> * </div> */ validate(): boolean { if (!this.container.classList.contains("tabMenuContainer")) { return false; } const nav = DomTraverse.childByTag(this.container, "NAV"); if (nav === null) { return false; } // get children cons...
} return returnValue; } /** * Selects a tab. * * @param {?(string|int)} name tab name or sequence no * @param {Element=} tab tab element * @param {boolean=} disableEvent suppress event handling */ select(name: number | string | null, tab?: HTMLLIElement, disable...
this.container.appendChild(input); this.store = input; }
random_line_split
Simple.ts
nav> * * <div id="foo">baz</div> * </div> */ validate(): boolean { if (!this.container.classList.contains("tabMenuContainer")) { return false; } const nav = DomTraverse.childByTag(this.container, "NAV"); if (nav === null) { return false; } // get children const t...
if (this.tabs.has(name)) { throw new Error( "Tab names must be unique, li[data-name='" + name + "'] (tab menu id: '" + containerId + "') exists more than once.", ); } const container = this.containers.get(name); if (con...
{ return; }
conditional_block
Simple.ts
/** * Validates the properties and DOM structure of this container. * * Expected DOM: * <div class="tabMenuContainer"> * <nav> * <ul> * <li data-name="foo"><a>bar</a></li> * </ul> * </nav> * * <div id="foo">baz</div> * </div> */ validate(): boolean { if (!t...
{ this.container = container; }
identifier_body
Simple.ts
names must be unique, li[data-name='" + name + "'] (tab menu id: '" + containerId + "') exists more than once.", ); } const container = this.containers.get(name); if (container === undefined) { throw new Error( "Expected conte...
hasTab
identifier_name
select.rs
use iterator_type::IteratorType; use rmpv::Value; use utils::serialize; use request_type_key::RequestTypeKey; use code::Code; use action::Action; #[derive(Debug)] pub struct Select { pub space: u64, pub index: u64, pub limit: u64, pub offset: u64, pub iterator: IteratorType, pub keys: Vec<Value...
}
{ (RequestTypeKey::Select, serialize(Value::Map(vec![(Value::from(Code::SpaceId as u8), Value::from(self.space)), (Value::from(Code::IndexId as u8), Value::from(self.index)), (Value::from(Code::Limit as u8), Value::from(self.limit)),...
identifier_body
select.rs
use iterator_type::IteratorType; use rmpv::Value; use utils::serialize; use request_type_key::RequestTypeKey; use code::Code; use action::Action; #[derive(Debug)] pub struct Select { pub space: u64, pub index: u64, pub limit: u64, pub offset: u64, pub iterator: IteratorType, pub keys: Vec<Value...
(&self) -> (RequestTypeKey, Vec<u8>) { (RequestTypeKey::Select, serialize(Value::Map(vec![(Value::from(Code::SpaceId as u8), Value::from(self.space)), (Value::from(Code::IndexId as u8), Value::from(self.index)), (Value::from(Code::Li...
get
identifier_name
select.rs
use iterator_type::IteratorType; use rmpv::Value; use utils::serialize;
use code::Code; use action::Action; #[derive(Debug)] pub struct Select { pub space: u64, pub index: u64, pub limit: u64, pub offset: u64, pub iterator: IteratorType, pub keys: Vec<Value>, } impl Action for Select { fn get(&self) -> (RequestTypeKey, Vec<u8>) { (RequestTypeKey::Selec...
use request_type_key::RequestTypeKey;
random_line_split
print_reverse.py
from __future__ import annotations class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = [] temp = self while temp: ...
def main(): from doctest import testmod testmod() linked_list = make_linked_list([14, 52, 14, 12, 43]) print("Linked List:") print(linked_list) print("Elements in Reverse:") print_reverse(linked_list) if __name__ == "__main__": main()
print_reverse(head_node.next) print(head_node.data)
conditional_block
print_reverse.py
from __future__ import annotations class Node: def __init__(self, data=None):
def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = [] temp = self while temp: string_rep.append(f"{temp.data}") temp = temp.next return "->".join(string_rep) def make_linked_list(elements...
self.data = data self.next = None
identifier_body
print_reverse.py
from __future__ import annotations class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = [] temp = self while temp: ...
(): from doctest import testmod testmod() linked_list = make_linked_list([14, 52, 14, 12, 43]) print("Linked List:") print(linked_list) print("Elements in Reverse:") print_reverse(linked_list) if __name__ == "__main__": main()
main
identifier_name
print_reverse.py
from __future__ import annotations class Node: def __init__(self, data=None): self.data = data self.next = None
temp = self while temp: string_rep.append(f"{temp.data}") temp = temp.next return "->".join(string_rep) def make_linked_list(elements_list: list): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked Li...
def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = []
random_line_split
slog.rs
use slog::{self, info, o, warn, Drain}; fn main()
info!(root, "test info log {}", "key1"; "log-key" => true); warn!(root, "a warning, no color!"); }
{ let decorator = slog_term::TermDecorator::new().build(); let drain_full = slog_term::FullFormat::new(decorator) .use_file_location() .use_original_order() .build() .fuse(); let drain_full = slog_async::Async::new(drain_full).build().fuse(); let root = slog::Logger::root...
identifier_body
slog.rs
use slog::{self, info, o, warn, Drain}; fn
() { let decorator = slog_term::TermDecorator::new().build(); let drain_full = slog_term::FullFormat::new(decorator) .use_file_location() .use_original_order() .build() .fuse(); let drain_full = slog_async::Async::new(drain_full).build().fuse(); let root = slog::Logger::r...
main
identifier_name
slog.rs
use slog::{self, info, o, warn, Drain}; fn main() { let decorator = slog_term::TermDecorator::new().build(); let drain_full = slog_term::FullFormat::new(decorator) .use_file_location() .use_original_order()
let drain_full = slog_async::Async::new(drain_full).build().fuse(); let root = slog::Logger::root(drain_full, o!("key1" => "value1", "key2" => "value2")); info!(root, "test info log {}", "key1"; "log-key" => true); warn!(root, "a warning!"); std::thread::sleep(std::time::Duration::from_millis(10));...
.build() .fuse();
random_line_split
config.py
# -*- coding: utf8 -*- """ The ``config`` module ===================== Create a named logger and return it so users can log in different log files : one for each module. """ __author__ = 'Salas' __copyright__ = 'Copyright 2014 LTL' __credits__ = ['Salas'] __license__ = 'MIT' __version__ = '0.2.0' __main...
with open(config_file_path, 'a'): os.utime(config_file_path, None) try: with open(config_example_path, 'rb') as config_example_stream: config_dict_example = yaml.load(config_example_stream, Loader=Loader) # TODO : console based...
raise
conditional_block
config.py
# -*- coding: utf8 -*- """ The ``config`` module ===================== Create a named logger and return it so users can log in different log files : one for each module. """ __author__ = 'Salas' __copyright__ = 'Copyright 2014 LTL' __credits__ = ['Salas'] __license__ = 'MIT' __version__ = '0.2.0' __main...
else: raise with open(config_file_path, 'a'): os.utime(config_file_path, None) try: with open(config_example_path, 'rb') as config_example_stream: config_dict_example = yaml.load(config_example_stream, Loader...
""" Return the config from a yaml file as a dictionary. Create one file if not existing, using example file as template. :param config_file_path: :return: """ if config_file_path is None: config_dir_path = path.abspath(path.join(os.sep, path.dirname(__file__), path.pardir, 'config')) ...
identifier_body
config.py
# -*- coding: utf8 -*- """ The ``config`` module ===================== Create a named logger and return it so users can log in different log files : one for each module. """ __author__ = 'Salas' __copyright__ = 'Copyright 2014 LTL' __credits__ = ['Salas'] __license__ = 'MIT' __version__ = '0.2.0' __main...
(config_file_path=None, config_prefix='bot'): """ Return the config from a yaml file as a dictionary. Create one file if not existing, using example file as template. :param config_file_path: :return: """ if config_file_path is None: config_dir_path = path.abspath(path.join(os.sep, path...
get_config
identifier_name
config.py
# -*- coding: utf8 -*- """ The ``config`` module ===================== Create a named logger and return it so users can log in different log files : one for each module. """ __author__ = 'Salas' __copyright__ = 'Copyright 2014 LTL' __credits__ = ['Salas'] __license__ = 'MIT' __version__ = '0.2.0' __main...
os.makedirs(config_dir_path) except OSError as exc: if exc.errno == errno.EEXIST and path.isdir(config_dir_path): pass else: raise with open(config_file_path, 'a'): os.utime(config_file_path, ...
logger.info('') try:
random_line_split
TestLgamma.rs
/* * Copyright (C) 2016 The Android Open Source Project * * 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 app...
return lgamma(inV); } float2 __attribute__((kernel)) testLgammaFloat2Float2(float2 inV) { return lgamma(inV); } float3 __attribute__((kernel)) testLgammaFloat3Float3(float3 inV) { return lgamma(inV); } float4 __attribute__((kernel)) testLgammaFloat4Float4(float4 inV) { return lgamma(inV); } rs_alloca...
float __attribute__((kernel)) testLgammaFloatFloat(float inV) {
random_line_split
progress_bar.js
/*global FormplayerFrontend */ FormplayerFrontend.module("Layout.Views", function (Views, FormplayerFrontend, Backbone, Marionette) { Views.ProgressView = Marionette.ItemView.extend({ template: "#progress-view-template", initialize: function(options) { this.progressMessage = options.p...
}, }); });
{ $(this.el).find('.js-subtext small').text( gettext('Completed: ') + done + '/' + total ); }
conditional_block
progress_bar.js
/*global FormplayerFrontend */ FormplayerFrontend.module("Layout.Views", function (Views, FormplayerFrontend, Backbone, Marionette) { Views.ProgressView = Marionette.ItemView.extend({ template: "#progress-view-template",
}, templateHelpers: function() { return { progressMessage: this.progressMessage, }; }, setProgress: function(done, total, duration) { var progress = total === 0 ? 0 : done / total; // Due to jQuery bug, can't use .animate(...
initialize: function(options) { this.progressMessage = options.progressMessage;
random_line_split
GitTag.py
# Copyright 2012 Vincent Jacques # vincent@vincent-jacques.net # This file is part of PyGithub. http://vincent-jacques.net/PyGithub # PyGithub 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 Software Foundation, either vers...
if "tagger" in attributes: # pragma no branch assert attributes[ "tagger" ] is None or isinstance( attributes[ "tagger" ], dict ), attributes[ "tagger" ] self._tagger = None if attributes[ "tagger" ] is None else GitAuthor.GitAuthor( self._requester, attributes[ "tagger" ], completed = ...
assert attributes[ "tag" ] is None or isinstance( attributes[ "tag" ], ( str, unicode ) ), attributes[ "tag" ] self._tag = attributes[ "tag" ]
conditional_block
GitTag.py
# Copyright 2012 Vincent Jacques # vincent@vincent-jacques.net # This file is part of PyGithub. http://vincent-jacques.net/PyGithub # PyGithub 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 Software Foundation, either vers...
def _initAttributes( self ): self._message = GithubObject.NotSet self._object = GithubObject.NotSet self._sha = GithubObject.NotSet self._tag = GithubObject.NotSet self._tagger = GithubObject.NotSet self._url = GithubObject.NotSet def _useAttributes( self, attr...
self._completeIfNotSet( self._url ) return self._NoneIfNotSet( self._url )
identifier_body
GitTag.py
# Copyright 2012 Vincent Jacques # vincent@vincent-jacques.net # This file is part of PyGithub. http://vincent-jacques.net/PyGithub # PyGithub 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 Software Foundation, either vers...
( self ): self._completeIfNotSet( self._tagger ) return self._NoneIfNotSet( self._tagger ) @property def url( self ): self._completeIfNotSet( self._url ) return self._NoneIfNotSet( self._url ) def _initAttributes( self ): self._message = GithubObject.NotSet ...
tagger
identifier_name
GitTag.py
# Copyright 2012 Vincent Jacques # vincent@vincent-jacques.net # This file is part of PyGithub. http://vincent-jacques.net/PyGithub # PyGithub 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 Software Foundation, either vers...
def _useAttributes( self, attributes ): if "message" in attributes: # pragma no branch assert attributes[ "message" ] is None or isinstance( attributes[ "message" ], ( str, unicode ) ), attributes[ "message" ] self._message = attributes[ "message" ] if "object" in attributes:...
self._tagger = GithubObject.NotSet self._url = GithubObject.NotSet
random_line_split
popup.js
// start the popup specefic scripts // safe to use $ jQuery(document).ready(function($) { var vibes = { loadVals: function() { var shortcode = $('#_vibe_shortcode').text(), uShortcode = shortcode; // fill in the gaps eg {{param}} $('.vibe-input').each(function() ...
$this.html(shortcode_html); }); }); $( ".popup-slider" ).livequery( function() { var slide_val = $(this).next(); var $this = $(this); var std=parseInt(slide_val.attr('data-std')); var min=parseInt(slide_val.attr('data-min')); var max=parseI...
{ var matches = shortcode.match(regex); for(var match in matches) { var fthis=matches[match].replace('{{',''); fthis=fthis.replace('}}',''); fthis='#vibe_'+fthis; var repl =$(fthis).val();...
conditional_block
popup.js
// start the popup specefic scripts // safe to use $ jQuery(document).ready(function($) { var vibes = { loadVals: function() { var shortcode = $('#_vibe_shortcode').text(), uShortcode = shortcode; // fill in the gaps eg {{param}} $('.vibe-input').each(function() {...
}); // remove button $('.child-clone-row-remove').live('click', function() { var btn = $(this), row = btn.parent(); if( $('.child-clone-row').size() > 1 ) { row.remove(); } else { alert('You need a minimum of one row'); ...
allowDelete: false, focusFirst: false
random_line_split
union-smoke.rs
// min-lldb-version: 310 // ignore-gdb // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155
// === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print u // gdbg-check:$1 = {a = {__0 = 2 '\002', __1 = 2 '\002'}, b = 514} // gdbr-check:$1 = union_smoke::U {a: (2, 2), b: 514} // gdb-command:print union_smoke::SU // gdbg-check:$2 =...
// ignore-gdb-version: 7.11.90 - 7.12.9 // compile-flags:-g
random_line_split
union-smoke.rs
// min-lldb-version: 310 // ignore-gdb // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155 // ignore-gdb-version: 7.11.90 - 7.12.9 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:pr...
() {()}
zzz
identifier_name
union-smoke.rs
// min-lldb-version: 310 // ignore-gdb // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155 // ignore-gdb-version: 7.11.90 - 7.12.9 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:pr...
{()}
identifier_body
struct_with_anon_struct_pointer.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct foo { pub bar: *mut foo__bindgen_ty_1, } #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct foo__bindgen_ty_1 ...
() { assert_eq!( ::std::mem::size_of::<foo__bindgen_ty_1>(), 8usize, concat!("Size of: ", stringify!(foo__bindgen_ty_1)) ); assert_eq!( ::std::mem::align_of::<foo__bindgen_ty_1>(), 4usize, concat!("Alignment of ", stringify!(foo__bindgen_ty_1)) ); asse...
bindgen_test_layout_foo__bindgen_ty_1
identifier_name
struct_with_anon_struct_pointer.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct foo { pub bar: *mut foo__bindgen_ty_1, } #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct foo__bindgen_ty_1 ...
stringify!(a) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<foo__bindgen_ty_1>())).b as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(b)...
{ assert_eq!( ::std::mem::size_of::<foo__bindgen_ty_1>(), 8usize, concat!("Size of: ", stringify!(foo__bindgen_ty_1)) ); assert_eq!( ::std::mem::align_of::<foo__bindgen_ty_1>(), 4usize, concat!("Alignment of ", stringify!(foo__bindgen_ty_1)) ); assert_...
identifier_body
struct_with_anon_struct_pointer.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct foo { pub bar: *mut foo__bindgen_ty_1, } #[repr(C)] #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)] pub struct foo__bindgen_ty_1 ...
concat!( "Offset of field: ", stringify!(foo__bindgen_ty_1), "::", stringify!(a) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<foo__bindgen_ty_1>())).b as *const _ as usize }, 4usize, concat!( ...
random_line_split
manticore_protocol_cerberus_KeyExchange__req_to_wire.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // !! DO NOT EDIT !! // To regenerate this file, run `fuzz/generate_proto_tests.py`. #![no_main] #![allow(non_snake_case)] use libfuzzer_sys::fuzz_target; use mantico...
fuzz_target!(|data: AsStatic<'static, Req<'static>>| { let mut out = [0u8; 1024]; let _ = Req::borrow(&data).to_wire(&mut &mut out[..]); });
use manticore::protocol::cerberus::KeyExchange as C; type Req<'a> = <C as Command<'a>>::Req;
random_line_split
ReportRepository.ts
/** * Created by ka-yamao */ import ReportModel = require('./../model/ReportModel'); import IReportModel = require('./../model/interfaces/ReportModel'); import ReportSchema = require('./../dataAccess/schemas/ReportSchema'); import RepositoryBase = require('./BaseRepository'); class ReportRepository extends Reposito...
* コメント検索 * @param query * @param fields * @param options * @param callback */ searchReport(query: any, fields: any, options: any, callback: (error: any, result: any) => void) { let model = this._model model.find(query, fields, options).populate(['post', 'user', 'comment'])...
} }); }); } /**
conditional_block
ReportRepository.ts
/** * Created by ka-yamao */ import ReportModel = require('./../model/ReportModel'); import IReportModel = require('./../model/interfaces/ReportModel'); import ReportSchema = require('./../dataAccess/schemas/ReportSchema'); import RepositoryBase = require('./BaseRepository'); class ReportRepository extends Reposito...
}); }); } /** * コメント検索 * @param query * @param fields * @param options * @param callback */ searchReport(query: any, fields: any, options: any, callback: (error: any, result: any) => void) { let model = this._model model.find(query, fields,...
} else { resolve(result); }
random_line_split
ReportRepository.ts
/** * Created by ka-yamao */ import ReportModel = require('./../model/ReportModel'); import IReportModel = require('./../model/interfaces/ReportModel'); import ReportSchema = require('./../dataAccess/schemas/ReportSchema'); import RepositoryBase = require('./BaseRepository'); class ReportRepository extends Reposito...
mise((resolve, reject) => { this._model.count({ 'post': post_id }).count((error: any, result: any) => { if (error) { reject(error); } else { resolve(result); } }); }); } countReportSum(que...
fields, options).populate(['post', 'user', 'comment']).exec(function (err, docs) { let opt = { path: 'post.user', model: 'User' }; // postの中のユーザーを取得 model.populate(docs, opt, function (e: any, d: any) { callback(e, d) ...
identifier_body
ReportRepository.ts
/** * Created by ka-yamao */ import ReportModel = require('./../model/ReportModel'); import IReportModel = require('./../model/interfaces/ReportModel'); import ReportSchema = require('./../dataAccess/schemas/ReportSchema'); import RepositoryBase = require('./BaseRepository'); class ReportRepository extends Reposito...
() { super(ReportSchema); } /** * コメントを新規作成 * @param item */ createReport(item: IReportModel): Promise<any> { return new Promise((resolve, reject) => { this._model.create(item, (error: any, result: any) => { if (error) { reject...
constructor
identifier_name
rtcpeerconnectioniceevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindi...
(&self) -> Option<DOMString> { self.url.clone() } /// https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
GetUrl
identifier_name
rtcpeerconnectioniceevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindi...
/// https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ self.url.clone() }
identifier_body
rtcpeerconnectioniceevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindi...
use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; use crate::dom::globalscope::GlobalScope; use crate::dom::rtcicecandidate::RTCIceCandidate; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; #[dom_struct] pub struct RTCPeerConnectionIceEvent { event: Event, ...
use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::{Dom, DomRoot};
random_line_split
waf_config.py
for the specific language governing permissions and # # limitations under the License. # ############################################################################ import argparse import logging import os import stat import subprocess import sys import time import yaml...
haproxy_cp_ip = find_cp_ip(yaml_cfg['
for vnfr in vnfr_list: if vnfd_name in vnfr['name']: return vnfr raise ValueError("Could not find vnfd %s", vnfd_name)
identifier_body
waf_config.py
%H%M%S")) logger.debug("Creating script file %s", sh_file) with open(sh_file, "w") as f: f.write(r'''#!/usr/bin/expect -f set login "centos" set addr {mgmt_ip} set pw "centos" set retry 0 set max 20 while {{ $retry < $max }} {{ sleep 5 spawn ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile...
waf_mgmt_ip = find_mgmt_ip(yaml_cfg['vnfrs_in_group'], "waf_vnfd")
random_line_split
waf_config.py
for the specific language governing permissions and # # limitations under the License. # ############################################################################ import argparse import logging import os import stat import subprocess import sys import time import yaml...
raise ValueError("Could not find vnfd %s", vnfd_name) haproxy_cp_ip = find_cp_ip(yaml_cfg['vn
return vnfr
conditional_block
waf_config.py
for the specific language governing permissions and # # limitations under the License. # ############################################################################ import argparse import logging import os import stat import subprocess import sys import time import yaml...
(logger, run_dir, haproxy_mgmt_ip, waf_server_name): sh_file = "{}/haproxy_remove_httpd_config-{}.sh".format(run_dir, time.strftime("%Y%m%d%H%M%S")) logger.debug("Creating script file %s", sh_file) with open(sh_file, "w") as f: f.write(r'''#!/usr/bin/expect -f set login "centos" set addr {mgmt_ip} s...
configure_haproxy_remove_waf
identifier_name
required.spec.ts
import { FormControl } from '../../form-control'; import { RequiredValidator } from './required'; describe('Required validator', () => { let formControl: FormControl<any>; beforeEach(() => { formControl = new FormControl<any>( [RequiredValidator()] ); }); it('if value is u...
}); it('if value is set, it should be valid', () => { formControl.value = 'test'; formControl.validate(); expect(formControl.valid).toBe(true); }); });
random_line_split
cluster.js
/* jshint node: true */ 'use strict'; // cInfo: { cId, dir, attrList } function Cluster(endpoint, cInfo) { // this.epId = cInfo.epId; this.endpoint = endpoint; this.cId = cInfo.cId; this.name = 'xxx'; // find from zcl defs, if not found, give it 'manuSpecificCluster' this.dir = cInfo.dir; ...
Cluster.prototype.getEpId = function () { return this.endpoint; }; Cluster.prototype.dump = function () { return { cId: this.cId, dir: this.dir, attrs: _.cloneDeep(this.attrs) }; }; // Cluster.prototype.readAttrs = function (attrIds, callback) {}; // Cluster.prototype.addClusterCmd...
// push to ep.clusters (out clusters) }
random_line_split
cluster.js
/* jshint node: true */ 'use strict'; // cInfo: { cId, dir, attrList } function Cluster(endpoint, cInfo)
// cluster.addClusterCmd()? // cluster not there (msghub.emit('EPMGR:DEVICE_ANNCE_IND', { indType: 'CLUSTER_NEW', info: cInfo });) // new Cluster // isLocal // dir !== in // only put 'out' clusters to functional (it is client) // zclSupport:...
{ // this.epId = cInfo.epId; this.endpoint = endpoint; this.cId = cInfo.cId; this.name = 'xxx'; // find from zcl defs, if not found, give it 'manuSpecificCluster' this.dir = cInfo.dir; this.attrList = cInfo.attrList; // should discover all attibute ids first this.cmdList = []; // can r...
identifier_body
cluster.js
/* jshint node: true */ 'use strict'; // cInfo: { cId, dir, attrList } function
(endpoint, cInfo) { // this.epId = cInfo.epId; this.endpoint = endpoint; this.cId = cInfo.cId; this.name = 'xxx'; // find from zcl defs, if not found, give it 'manuSpecificCluster' this.dir = cInfo.dir; this.attrList = cInfo.attrList; // should discover all attibute ids first this.cmdLi...
Cluster
identifier_name
plugin.js
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT 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 the Free Software Foundation; either * version 3 of the License...
model.set({ _status: 'installing' }); } }); }, update: function () { return this._action({ url: baseUrl + '/api/plugins/update', success: function (model) { model.set({ _status: 'installing' }); } }); }, uninstall: function () { return this._action({ ...
install: function () { return this._action({ url: baseUrl + '/api/plugins/install', success: function (model) {
random_line_split
Base.py
high level Request object """ def
(self,*name,**args): self.donefunc=None self.async=None self.defaults = {} self.argparse(name,args) self.defaults = self.args self.tid = 0 def argparse(self,name,args): if not name and self.defaults.has_key('name'): args['name'] = self.defaults['name'] if type(name) is types.StringType: args['na...
__init__
identifier_name
Base.py
high level Request object """ def __init__(self,*name,**args): self.donefunc=None self.async=None self.defaults = {} self.argparse(name,args) self.defaults = self.args self.tid = 0 def argparse(self,name,args): if not name and self.defaults.has_key('name'): args['name'] = self.defaults['name'] if...
def showResult(self,*s): self.response.show() # # $Log: Base.py,v $ # Revision 1.12.2.10 2008/08/01 03:58:03 customdesigned # Don't try
pass
identifier_body
Base.py
else: return ParseResolvConf() class DnsRequest: """ high level Request object """ def __init__(self,*name,**args): self.donefunc=None self.async=None self.defaults = {} self.argparse(name,args) self.defaults = self.args self.tid = 0 def argparse(self,name,args): if not name and self.defaults.has...
import win32dns defaults['server']=win32dns.RegistryResolve()
conditional_block
Base.py
high level Request object """ def __init__(self,*name,**args): self.donefunc=None self.async=None self.defaults = {} self.argparse(name,args) self.defaults = self.args self.tid = 0 def argparse(self,name,args): if not name and self.defaults.has_key('name'): args['name'] = self.defaults['name'] if...
else: self.socketInit(socket.AF_INET, socket.SOCK_STREAM) try: # TODO. Handle timeouts &c correctly (RFC) self.time_start=time.time() self.conn() buf = Lib.pack16bit(len(self.request))+self.request # Keep server from making sendall hang self.s.setblocking(0) # FIXME: thro...
if self.ns.count(':'): if hasattr(socket,'has_ipv6') and socket.has_ipv6: self.socketInit(socket.AF_INET6, socket.SOCK_STREAM) else: continue
random_line_split
lockutils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 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/...
class _WindowsLock(_InterProcessLock): def trylock(self): msvcrt.locking(self.lockfile, msvcrt.LK_NBLCK, 1) def unlock(self): msvcrt.locking(self.lockfile, msvcrt.LK_UNLCK, 1) class _PosixLock(_InterProcessLock): def trylock(self): fcntl.lockf(self.lockfile, fcntl.LOCK_EX | fcn...
raise NotImplementedError()
identifier_body
lockutils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 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/...
(self): msvcrt.locking(self.lockfile, msvcrt.LK_NBLCK, 1) def unlock(self): msvcrt.locking(self.lockfile, msvcrt.LK_UNLCK, 1) class _PosixLock(_InterProcessLock): def trylock(self): fcntl.lockf(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) def unlock(self): fcntl.lockf(se...
trylock
identifier_name
lockutils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 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/...
safe_name = name.replace(os.sep, '_') lock_file_name = '%s%s' % (lock_file_prefix, safe_name) lock_file_path = os.path.join(local_lock_path, lock_file_name) try: loc...
LOG.debug(_('Attempting to grab file lock "%(lock)s" for ' 'method "%(method)s"...'), {'lock': name, 'method': f.__name__}) cleanup_dir = False # We need a copy of lock_path because it is non-local ...
conditional_block
lockutils.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 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/...
InterProcessLock = _PosixLock _semaphores = weakref.WeakValueDictionary() def synchronized(name, lock_file_prefix, external=False, lock_path=None): """Synchronization decorator. Decorating a method like so:: @synchronized('mylock') def foo(self, *args): ... ensures that ...
if os.name == 'nt': import msvcrt InterProcessLock = _WindowsLock else: import fcntl
random_line_split
sweep.py
#!/usr/bin/env python from utils import load_data, save_data def
(): # load in members, orient by bioguide ID print("Loading current legislators...") current = load_data("legislators-current.yaml") current_bioguide = { } for m in current: if "bioguide" in m["id"]: current_bioguide[m["id"]["bioguide"]] = m # remove out-of-office people from cur...
run
identifier_name
sweep.py
#!/usr/bin/env python from utils import load_data, save_data def run(): # load in members, orient by bioguide ID
socialmedia_current = load_data("legislators-social-media.yaml") for member in list(socialmedia_current): if member["id"]["bioguide"] not in current_bioguide: print("\t[%s] Ding ding ding! (%s)" % (member["id"]["bioguide"], member["social"])) socialmedia_current.remove(member) save_dat...
print("Loading current legislators...") current = load_data("legislators-current.yaml") current_bioguide = { } for m in current: if "bioguide" in m["id"]: current_bioguide[m["id"]["bioguide"]] = m # remove out-of-office people from current committee membership print("Sweeping committ...
identifier_body
sweep.py
#!/usr/bin/env python from utils import load_data, save_data def run(): # load in members, orient by bioguide ID
current_bioguide = { } for m in current: if "bioguide" in m["id"]: current_bioguide[m["id"]["bioguide"]] = m # remove out-of-office people from current committee membership print("Sweeping committee membership...") membership_current = load_data("committee-membership-current.yaml") ...
print("Loading current legislators...") current = load_data("legislators-current.yaml")
random_line_split
sweep.py
#!/usr/bin/env python from utils import load_data, save_data def run(): # load in members, orient by bioguide ID print("Loading current legislators...") current = load_data("legislators-current.yaml") current_bioguide = { } for m in current: if "bioguide" in m["id"]: current_bioguid...
save_data(socialmedia_current, "legislators-social-media.yaml") if __name__ == '__main__': run()
if member["id"]["bioguide"] not in current_bioguide: print("\t[%s] Ding ding ding! (%s)" % (member["id"]["bioguide"], member["social"])) socialmedia_current.remove(member)
conditional_block
error.rs
#[derive(thiserror::Error, Debug)] pub enum Error { #[error("Couldn't find or open file: {}", .0)] FileNotFound(String), #[error("Error while building path: {}", .0)] InvalidPath(String),
/// Any errors regarding the certificate setup. #[error("Invalid or malformed certificate: {}", .0)] CertificateFailure(String), #[error("{}", .0)] Connection(String), #[error("Got an empty payload")] EmptyPayload, #[error("Couldn't deserialize message:\n{}", .0)] MessageDeseriali...
random_line_split
error.rs
#[derive(thiserror::Error, Debug)] pub enum
{ #[error("Couldn't find or open file: {}", .0)] FileNotFound(String), #[error("Error while building path: {}", .0)] InvalidPath(String), /// Any errors regarding the certificate setup. #[error("Invalid or malformed certificate: {}", .0)] CertificateFailure(String), #[error("{}", .0)...
Error
identifier_name
issue-17662.rs
// // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:iss...
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
issue-17662.rs
// Copyright 2014 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) -> uint { 5_usize } } pub fn main() { assert_eq!(i::foo(&Bar { m: marker::PhantomData }), 5); }
foo
identifier_name
app.js
// Requred by theme templates window.jQuery = $ = require('jquery'); require('parsleyjs'); // Import Nav module import * as nav from './modules/nav.js'; import * as login from './modules/login.js'; import * as searchbar from './modules/searchbar.js'; import Tabs from './modules/tabs.js'; import Modal from './modu...
} $('.js-parsley-validate form').parsley({ successClass: 'is-valid', errorClass: 'is-error', trigger: 'change', classHandler: function(el) { return el.$element.parent(); }, errorsWrapper: '<ul class="form__errors-list"></ul>', errorTemplate: '<li class="form__error-item"></li>' });
});
random_line_split
app.js
// Requred by theme templates window.jQuery = $ = require('jquery'); require('parsleyjs'); // Import Nav module import * as nav from './modules/nav.js'; import * as login from './modules/login.js'; import * as searchbar from './modules/searchbar.js'; import Tabs from './modules/tabs.js'; import Modal from './modu...
if (document.querySelectorAll('#FeaturedImage').length && window.matchMedia('(min-width: 600px)').matches) { new Drift(document.querySelector('#FeaturedImage'), { paneContainer: document.querySelector('.gallery__fig'), namespace: 'gallery__drift', containInline: true }); } $('.js-parsley-validate form').pa...
{ var modals = document.querySelectorAll('.js-modal'); [].forEach.call(modals, function(item, i) { new Modal(modals[i]); }); }
conditional_block
robotremoteserver.py
"""Server port as an integer. If the initial given port is 0, also this property returns 0 until the server is activated. """ return self._server.server_address[1] def activate(self): """Bind port and activate the server but do not yet start serving. :retur...
def _announce_stop(self, log, port_file): self._log('stopped', log) if port_file and os.path.exists(port_file): os.remove(port_file) def _log(self, action, log=True, warn=False): if log: address = '%s:%s' % self.server_address if warn: ...
self._log('started', log) if port_file: with open(port_file, 'w') as pf: pf.write(str(self.server_port))
identifier_body