file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
event.rs | //! Event handling (mouse, keyboard, controller, touch screen, etc.)
//!
//! See [`Event`](enum.Event.html) for more information.
//!
//! # Unstable
//!
//! There are still many unanswered questions about the design of the events API in the turtle
//! crate. This module may change or be completely removed in the future... | F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
Home,
Delete,
End,
/// The PageDown (PgDn) key
PageDown,
/// The PageUp (PgUp) key
PageUp,
/// The backspace key, right ... | F3,
F4,
F5, | random_line_split |
event.rs | //! Event handling (mouse, keyboard, controller, touch screen, etc.)
//!
//! See [`Event`](enum.Event.html) for more information.
//!
//! # Unstable
//!
//! There are still many unanswered questions about the design of the events API in the turtle
//! crate. This module may change or be completely removed in the future... | (state: glutin_event::ElementState) -> PressedState {
match state {
glutin_event::ElementState::Pressed => PressedState::Pressed,
glutin_event::ElementState::Released => PressedState::Released,
}
}
}
//TODO: Documentation
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Partia... | from_state | identifier_name |
event.rs | //! Event handling (mouse, keyboard, controller, touch screen, etc.)
//!
//! See [`Event`](enum.Event.html) for more information.
//!
//! # Unstable
//!
//! There are still many unanswered questions about the design of the events API in the turtle
//! crate. This module may change or be completely removed in the future... |
}
//TODO: Documentation
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Key {
/// The '1' key above the letters.
Num1,
/// The '2' key above the letters.
Num2,
/// The '3' key above the letters.
Num3,
/// The '4' key above the letters.
Num4,
... | {
match state {
glutin_event::ElementState::Pressed => PressedState::Pressed,
glutin_event::ElementState::Released => PressedState::Released,
}
} | identifier_body |
index.py | # 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/.
# Copyright (c) 2017 Mozilla Corporation
import os
from bottle import route, run, response, request, default_app
from b... |
return
@route('/_status')
@route('/_status/')
@route('/nxlog/', method=['POST','PUT'])
@route('/nxlog', method=['POST','PUT'])
@route('/events/',method=['POST','PUT'])
@route('/events', method=['POST','PUT'])
def eventsindex():
if request.body:
anevent=request.body.read()
# bottlelog('request... | bulkpost=request.body.read()
# bottlelog('request:{0}\n'.format(bulkpost))
request.body.close()
try: # Handles json array bulk format [{},{},...]
messages = json.loads(bulkpost)
for event in messages:
# don't post the items telling us where to post things... | conditional_block |
index.py | # 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/.
# Copyright (c) 2017 Mozilla Corporation
import os
from bottle import route, run, response, request, default_app
from b... |
def initConfig():
options.mqserver=getConfig('mqserver','localhost',options.configfile)
options.taskexchange=getConfig('taskexchange','eventtask',options.configfile)
options.mquser=getConfig('mquser','guest',options.configfile)
options.mqpassword=getConfig('mqpassword','guest',options.configfile)
... | '''
and endpoint designed for custom applications that want to post data
to elastic search through the mozdef event interface
post to /custom/vulnerabilities
for example to post vulnerability in a custom format
Posts must be in json and are best formatted using a plugin
t... | identifier_body |
index.py | # 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/.
# Copyright (c) 2017 Mozilla Corporation
import os
from bottle import route, run, response, request, default_app
from b... | ():
options.mqserver=getConfig('mqserver','localhost',options.configfile)
options.taskexchange=getConfig('taskexchange','eventtask',options.configfile)
options.mquser=getConfig('mquser','guest',options.configfile)
options.mqpassword=getConfig('mqpassword','guest',options.configfile)
options.mqport=g... | initConfig | identifier_name |
index.py | # 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/.
# Copyright (c) 2017 Mozilla Corporation
import os
from bottle import route, run, response, request, default_app
from b... | application = default_app() | else: | random_line_split |
jquery.markdownify.js | (function ($) {
$.fn.markdownify = function (options) {
if (options && options['cloudinary']) {
var cloudName = options['cloudinary']['cloudName'];
var unsignedUploadingKey = options['cloudinary']['unsignedUploadingKey']; | var current_element = this;
var editor = CodeMirror.fromTextArea(current_element, {
mode: 'markdown',
lineNumbers: true,
lineWrapping: true,
theme: "default",
extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"}
});
editor.on('change', function () ... | }
this.each(function () { | random_line_split |
borrowck-lend-flow-loop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
// In this instance, the borrow is carried through the loop.
let mut v = ~3;
let mut w = ~4;
let mut _x = &w;
for for_func {
borrow_mut(v); //~ ERROR cannot borrow
_x = &v;
}
}
fn loop_aliased_mut_break() {
// In this instance, the borrow is carried through the loop.
... | for_loop_aliased_mut | identifier_name |
borrowck-lend-flow-loop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
}
fn main() {}
| {
loop; // ...so it is not live as exit (and re-enter) the `while` loop here
} | conditional_block |
borrowck-lend-flow-loop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn cond() -> bool { fail!() }
fn for_func(_f: &fn() -> bool) -> bool { fail!() }
fn produce<T>() -> T { fail!(); }
fn inc(v: &mut ~int) {
*v = ~(**v + 1);
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v = ~3;
let mut x = &mut v;
**x += 1... | {} | identifier_body |
borrowck-lend-flow-loop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | break; // ...so it is not live as exit the `while` loop here
}
}
}
}
fn loop_loop_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
// Similar to `loop_break_pops_scopes` but for the `loop` keyword
while cond() {
while cond() {
// t... | let r: &'r mut uint = produce();
if !f(&mut *r) { | random_line_split |
wiki.py | # coding: utf-8
"""
MoinMoin wiki stats about updated pages
Config example::
[wiki]
type = wiki
wiki test = http://moinmo.in/
The optional key 'api' can be used to change the default
xmlrpc api endpoint::
[wiki]
type = wiki
api = ?action=xmlrpc2
wiki test = http://moinmo.in/
"""
import ... |
self.stats.sort()
def header(self):
""" Show summary header. """
# Different header for wiki: Updates on xxx: x changes of y pages
item(
"{0}: {1} change{2} of {3} page{4}".format(
self.name, self.changes, "" if self.changes == 1 else "s",
... | self.stats.append(url) | conditional_block |
wiki.py | # coding: utf-8
"""
MoinMoin wiki stats about updated pages
Config example::
[wiki]
type = wiki
wiki test = http://moinmo.in/
The optional key 'api' can be used to change the default
xmlrpc api endpoint::
[wiki]
type = wiki
api = ?action=xmlrpc2
wiki test = http://moinmo.in/
"""
import ... |
def header(self):
""" Show summary header. """
# Different header for wiki: Updates on xxx: x changes of y pages
item(
"{0}: {1} change{2} of {3} page{4}".format(
self.name, self.changes, "" if self.changes == 1 else "s",
len(self.stats), "" if l... | for change in self.proxy.getRecentChanges(
self.options.since.datetime):
if (change["author"] == self.user.login
and change["lastModified"] < self.options.until.date):
self.changes += 1
url = self.url + change["name"]
if url... | identifier_body |
wiki.py | # coding: utf-8
"""
MoinMoin wiki stats about updated pages
Config example::
[wiki]
type = wiki
wiki test = http://moinmo.in/
The optional key 'api' can be used to change the default
xmlrpc api endpoint::
[wiki]
type = wiki
api = ?action=xmlrpc2
wiki test = http://moinmo.in/ | from did.stats import Stats, StatsGroup
from did.utils import item
DEFAULT_API = '?action=xmlrpc2'
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Wiki Stats
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class WikiChanges(Stats):
""" Wiki chan... | """
import xmlrpc.client
from did.base import Config, ConfigError | random_line_split |
wiki.py | # coding: utf-8
"""
MoinMoin wiki stats about updated pages
Config example::
[wiki]
type = wiki
wiki test = http://moinmo.in/
The optional key 'api' can be used to change the default
xmlrpc api endpoint::
[wiki]
type = wiki
api = ?action=xmlrpc2
wiki test = http://moinmo.in/
"""
import ... | (self, option, name=None, parent=None, user=None):
StatsGroup.__init__(self, option, name, parent, user)
try:
api = Config().item(option, 'api')
except ConfigError:
api = None
for wiki, url in Config().section(option, skip=['type', 'api']):
self.stats.... | __init__ | identifier_name |
template.py | #!/usr/bin/env python -OO
# encoding: utf-8
###########
# ORP - Open Robotics Platform
#
# Copyright (c) 2010 John Harrison, William Woodall
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Softwa... | ():
pass
### IfMain ###
if __name__ == '__main__':
main()
| main | identifier_name |
template.py | #!/usr/bin/env python -OO
# encoding: utf-8
###########
# ORP - Open Robotics Platform
#
# Copyright (c) 2010 John Harrison, William Woodall
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Softwa... | main() | conditional_block | |
template.py | #!/usr/bin/env python -OO
# encoding: utf-8 |
###########
# ORP - Open Robotics Platform
#
# Copyright (c) 2010 John Harrison, William Woodall
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without li... | random_line_split | |
template.py | #!/usr/bin/env python -OO
# encoding: utf-8
###########
# ORP - Open Robotics Platform
#
# Copyright (c) 2010 John Harrison, William Woodall
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Softwa... |
### IfMain ###
if __name__ == '__main__':
main()
| pass | identifier_body |
calibrate.py | from cavicapture import CaviCapture
from process import CaviProcess
import sys, os, getopt
import time, datetime
import numpy as np
import matplotlib.pyplot as plt
def main():
config_path = './config.ini' # default
try:
opts, args = getopt.getopt(sys.argv[1:], "c", ["config="])
except getopt.GetoptError:
... |
def gen_file_path(self):
return self.output_dir + "/" + datetime.datetime.now().strftime('%Y%m%d-%H%M%S') + ".png"
def capture_image(self, file_path):
self.cavi_capture.camera.capture(file_path, 'png')
return file_path
if __name__ == '__main__':
main()
| average_pixel = np.average(img[img>0])
max_pixel = np.max(img[img>0])
min_pixel = np.min(img[img>0])
total_area = len(img[img>0])
self.cavi_process.log("Noise max: " + str(max_pixel))
self.cavi_process.log("Noise min: " + str(min_pixel))
self.cavi_process.log("Noise average: " + str(average_pix... | identifier_body |
calibrate.py | from cavicapture import CaviCapture
from process import CaviProcess
import sys, os, getopt
import time, datetime
import numpy as np
import matplotlib.pyplot as plt
def main():
config_path = './config.ini' # default
try:
opts, args = getopt.getopt(sys.argv[1:], "c", ["config="])
except getopt.GetoptError:
... |
self.cavi_capture = CaviCapture(config_path)
self.cavi_capture.log_file = self.output_dir + "/capture.log.txt"
self.cavi_capture.get_ini_config()
self.cavi_capture.setup_gpio()
self.cavi_capture.setup_camera()
self.cavi_process = CaviProcess(self.output_dir)
self.cavi_process.log_file... | os.makedirs(self.output_dir) | conditional_block |
calibrate.py | from cavicapture import CaviCapture
from process import CaviProcess
import sys, os, getopt
import time, datetime
import numpy as np
import matplotlib.pyplot as plt
def main():
config_path = './config.ini' # default
try:
opts, args = getopt.getopt(sys.argv[1:], "c", ["config="])
except getopt.GetoptError:
... | (self):
return self.output_dir + "/" + datetime.datetime.now().strftime('%Y%m%d-%H%M%S') + ".png"
def capture_image(self, file_path):
self.cavi_capture.camera.capture(file_path, 'png')
return file_path
if __name__ == '__main__':
main()
| gen_file_path | identifier_name |
calibrate.py | from cavicapture import CaviCapture
from process import CaviProcess
import sys, os, getopt
import time, datetime
import numpy as np
import matplotlib.pyplot as plt
def main():
config_path = './config.ini' # default
try:
opts, args = getopt.getopt(sys.argv[1:], "c", ["config="])
except getopt.GetoptError:
... | if __name__ == '__main__':
main() | random_line_split | |
source.rs | use crate::{Interest, Registry, Token};
use std::io;
/// An event source that may be registered with [`Registry`].
///
/// Types that implement `event::Source` can be registered with
/// `Registry`. Users of Mio **should not** use the `event::Source` trait
/// functions directly. Instead, the equivalent functions on ... | ///
/// [`Registry::reregister`]: ../struct.Registry.html#method.reregister
fn reregister(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()>;
/// Deregister `self` from the given `Registry` instance.
///
/// This function ... | /// re-registration by either delegating the call to another `Source` type. | random_line_split |
source.rs | use crate::{Interest, Registry, Token};
use std::io;
/// An event source that may be registered with [`Registry`].
///
/// Types that implement `event::Source` can be registered with
/// `Registry`. Users of Mio **should not** use the `event::Source` trait
/// functions directly. Instead, the equivalent functions on ... | (
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> io::Result<()> {
(&mut **self).register(registry, token, interests)
}
fn reregister(
&mut self,
registry: &Registry,
token: Token,
interests: Interest,
) -> ... | register | identifier_name |
source.rs | use crate::{Interest, Registry, Token};
use std::io;
/// An event source that may be registered with [`Registry`].
///
/// Types that implement `event::Source` can be registered with
/// `Registry`. Users of Mio **should not** use the `event::Source` trait
/// functions directly. Instead, the equivalent functions on ... |
}
| {
(&mut **self).deregister(registry)
} | identifier_body |
random.rs | use rand::{
distributions::Alphanumeric,
prelude::{Rng, SeedableRng, StdRng},
};
const OPERATORS: &[char] = &[
'+', '-', '<', '>', '(', ')', '*', '/', '&', '|', '!', ',', '.',
];
pub struct | (StdRng);
impl Rand {
pub fn new(seed: usize) -> Self {
Rand(StdRng::seed_from_u64(seed as u64))
}
pub fn unsigned(&mut self, max: usize) -> usize {
self.0.gen_range(0..max + 1)
}
pub fn words(&mut self, max_count: usize) -> Vec<u8> {
let mut result = Vec::new();
l... | Rand | identifier_name |
random.rs | use rand::{
distributions::Alphanumeric,
prelude::{Rng, SeedableRng, StdRng},
};
const OPERATORS: &[char] = &[
'+', '-', '<', '>', '(', ')', '*', '/', '&', '|', '!', ',', '.',
];
pub struct Rand(StdRng);
impl Rand {
pub fn new(seed: usize) -> Self {
Rand(StdRng::seed_from_u64(seed as u64))
... | for i in 0..word_count {
if i > 0 {
if self.unsigned(5) == 0 {
result.push('\n' as u8);
} else {
result.push(' ' as u8);
}
}
if self.unsigned(3) == 0 {
let index = self.uns... |
pub fn words(&mut self, max_count: usize) -> Vec<u8> {
let mut result = Vec::new();
let word_count = self.unsigned(max_count); | random_line_split |
random.rs | use rand::{
distributions::Alphanumeric,
prelude::{Rng, SeedableRng, StdRng},
};
const OPERATORS: &[char] = &[
'+', '-', '<', '>', '(', ')', '*', '/', '&', '|', '!', ',', '.',
];
pub struct Rand(StdRng);
impl Rand {
pub fn new(seed: usize) -> Self {
Rand(StdRng::seed_from_u64(seed as u64))
... |
}
result
}
}
| {
for _ in 0..self.unsigned(8) {
result.push(self.0.sample(Alphanumeric) as u8);
}
} | conditional_block |
generate_testdata.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def main(unused_argv=None):
target = FLAGS.target
if not target:
print("The --target flag is required.")
return -1
if os.path.exists(target):
if FLAGS.overwrite:
if os.path.isdir(target):
shutil.rmtree(target)
else:
os.remove(target)
else:
print("Refusing to ov... | """Generates the test data directory."""
run1_path = os.path.join(path, "run1")
os.makedirs(run1_path)
writer1 = tf.train.SummaryWriter(run1_path)
WriteScalarSeries(writer1, "foo/square", lambda x: x * x)
WriteScalarSeries(writer1, "bar/square", lambda x: x * x)
WriteScalarSeries(writer1, "foo/sin", math.si... | identifier_body |
generate_testdata.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
session.close()
def GenerateTestData(path):
"""Generates the test data directory."""
run1_path = os.path.join(path, "run1")
os.makedirs(run1_path)
writer1 = tf.train.SummaryWriter(run1_path)
WriteScalarSeries(writer1, "foo/square", lambda x: x * x)
WriteScalarSeries(writer1, "bar/square", lambda x: x *... | frequencies = np.random.random_integers(
min_frequency_hz, max_frequency_hz,
size=(frequencies_per_run, num_channels))
tiled_frequencies = np.tile(frequencies, (1, duration_frames))
tiled_increments = np.tile(
np.arange(0, duration_frames), (num_channels, 1)).T.reshape(
1, du... | conditional_block |
generate_testdata.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | import os
import os.path
import random
import shutil
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
tf.flags.DEFINE_string("target", None, """The directoy where serialized data
will be written""")
tf.flags.DEFINE_boolean("overwrite", False, """Whether to ... | from __future__ import print_function
import bisect
import math | random_line_split |
generate_testdata.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ():
v = 1E-12
buckets = []
neg_buckets = []
while v < 1E20:
buckets.append(v)
neg_buckets.append(-v)
v *= 1.1
# Should include DBL_MAX, but won't bother for test data.
return neg_buckets[::-1] + [0] + buckets
def _MakeHistogram(values):
"""Convert values into a histogram proto using logic fr... | _MakeHistogramBuckets | identifier_name |
version.rs | /*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use crate::sys;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Version {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
/// u... |
/// Get the version of SDL that is linked against your program.
#[doc(alias = "SDL_GetVersion")]
pub fn version() -> Version {
unsafe {
let mut cver = sys::SDL_version {
major: 0,
minor: 0,
patch: 0,
};
sys::SDL_GetVersion(&mut cver);
Version::fro... | }
} | random_line_split |
version.rs | /*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use crate::sys;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Version {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
/// u... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
}
/// Get the version of SDL that is linked against your program.
#[doc(alias = "SDL_GetVersion")]
pub fn version() -> Version {
unsafe {
let mut cver = sys::SDL_version {
ma... | fmt | identifier_name |
version.rs | /*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use crate::sys;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Version {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
/// u... |
}
/// Get the version of SDL that is linked against your program.
#[doc(alias = "SDL_GetVersion")]
pub fn version() -> Version {
unsafe {
let mut cver = sys::SDL_version {
major: 0,
minor: 0,
patch: 0,
};
sys::SDL_GetVersion(&mut cver);
Version::... | {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
} | identifier_body |
SHT21.py | from __future__ import print_function
from numpy import int16
import time
def connect(route,**args):
'''
route can either be I.I2C , or a radioLink instance
'''
return SHT21(route,**args)
class SHT21():
RESET = 0xFE
TEMP_ADDRESS = 0xF3
HUMIDITY_ADDRESS = 0xF5
selected=0xF3 | PLOTNAMES = ['Data']
ADDRESS = 0x40
name = 'Humidity/Temperature'
def __init__(self,I2C,**args):
self.I2C=I2C
self.ADDRESS = args.get('address',self.ADDRESS)
self.name = 'Humidity/Temperature'
'''
try:
print ('switching baud to 400k')
self.I2C.configI2C(400e3)
except:
print ('FAILED TO CHANGE B... | NUMPLOTS=1 | random_line_split |
SHT21.py | from __future__ import print_function
from numpy import int16
import time
def connect(route,**args):
'''
route can either be I.I2C , or a radioLink instance
'''
return SHT21(route,**args)
class SHT21():
| RESET = 0xFE
TEMP_ADDRESS = 0xF3
HUMIDITY_ADDRESS = 0xF5
selected=0xF3
NUMPLOTS=1
PLOTNAMES = ['Data']
ADDRESS = 0x40
name = 'Humidity/Temperature'
def __init__(self,I2C,**args):
self.I2C=I2C
self.ADDRESS = args.get('address',self.ADDRESS)
self.name = 'Humidity/Temperature'
'''
try:
print ('switch... | identifier_body | |
SHT21.py | from __future__ import print_function
from numpy import int16
import time
def connect(route,**args):
'''
route can either be I.I2C , or a radioLink instance
'''
return SHT21(route,**args)
class SHT21():
RESET = 0xFE
TEMP_ADDRESS = 0xF3
HUMIDITY_ADDRESS = 0xF5
selected=0xF3
NUMPLOTS=1
PLOTNAMES = ['Data']
... |
if self.selected==self.TEMP_ADDRESS:return self.rawToTemp(vals)
elif self.selected==self.HUMIDITY_ADDRESS:return self.rawToRH(vals)
| if self._calculate_checksum(vals,2)!=vals[2]:
return False
print (vals) | conditional_block |
SHT21.py | from __future__ import print_function
from numpy import int16
import time
def | (route,**args):
'''
route can either be I.I2C , or a radioLink instance
'''
return SHT21(route,**args)
class SHT21():
RESET = 0xFE
TEMP_ADDRESS = 0xF3
HUMIDITY_ADDRESS = 0xF5
selected=0xF3
NUMPLOTS=1
PLOTNAMES = ['Data']
ADDRESS = 0x40
name = 'Humidity/Temperature'
def __init__(self,I2C,**args):
self.... | connect | identifier_name |
forceGraph0-0-1.ts | module powerbi.visuals {
export class ForceGraph implements IVisual {
public static capabilities: VisualCapabilities = {
dataRoles: [
{
name: 'Values',
kind: VisualDataRoleKind.GroupingOrMeasure,
},
],
... | var data = {
"nodes": nodes, "links": links, "minFiles": minFiles, "maxFiles": maxFiles, "linkedByName": linkedByName
};
return data;
}
public init(options: VisualInitOptions): void {
this.root = d3.select(options.element.get(0));
... | random_line_split | |
forceGraph0-0-1.ts | module powerbi.visuals {
export class ForceGraph implements IVisual {
public static capabilities: VisualCapabilities = {
dataRoles: [
{
name: 'Values',
kind: VisualDataRoleKind.GroupingOrMeasure,
},
],
... |
// add the curvy lines
function tick() {
path.each(function () { this.parentNode.insertBefore(this, this); });
path.attr("d", function (d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
... | {
return data.linkedByName[a.name + "," + b.name] || data.linkedByName[b.name + "," + a.name] || a.name == b.name;
} | identifier_body |
forceGraph0-0-1.ts | module powerbi.visuals {
export class ForceGraph implements IVisual {
public static capabilities: VisualCapabilities = {
dataRoles: [
{
name: 'Values',
kind: VisualDataRoleKind.GroupingOrMeasure,
},
],
... | (opacity) {
return function (d) {
node.style("stroke-opacity", function (o) {
var thisOpacity = isConnected(d, o) ? 1 : opacity;
this.setAttribute('fill-opacity', thisOpacity);
return thisOpacity;
... | fadeNode | identifier_name |
events.spec.ts | /* tslint:disable:component-selector */
import {
Component, NgZone
} from '@angular/core';
import {
TestBed
} from '@angular/core/testing';
import {
DxDataGridModule
} from 'devextreme-angular';
import readyCallbacks from 'devextreme/core/utils/ready_callbacks';
import { on } from 'devextreme/events';
... | {
}
describe('global events', () => {
it('should be subscribed within Angular Zone', () => {
let readyCallbacksCalls = 0;
readyCallbacks.fire();
readyCallbacks.add(() => {
readyCallbacksCalls++;
NgZone.assertInAngularZone();
});
TestBed.configure... | TestContainerComponent | identifier_name |
events.spec.ts | /* tslint:disable:component-selector */
import {
Component, NgZone
} from '@angular/core';
import {
TestBed
} from '@angular/core/testing';
import {
DxDataGridModule
} from 'devextreme-angular';
import readyCallbacks from 'devextreme/core/utils/ready_callbacks';
import { on } from 'devextreme/events';
... | declarations: [TestContainerComponent],
imports: [DxDataGridModule]
});
TestBed.overrideComponent(TestContainerComponent, {
set: { template: `` }
});
TestBed.createComponent(TestContainerComponent);
expect(readyCallbacksCalls).toBe(1);
... |
TestBed.configureTestingModule({ | random_line_split |
parseUrl.js | export default (original) => {
const url = getHashUrl(original);
let [path, params] = url.split('?');
if (path.length >= 2) {
path = path.replace(/\/$/, '');
}
if (params) {
params = parseSearchParams(params);
} else {
params = {}
}
const actual = path + joinSearchParams(params);
ret... | }
const getHashUrl = (original) => {
let url = original.split('#');
if (url.length >= 2) {
url = url[1];
} else {
url = '/';
}
if (url === '') {
url = '/';
}
if (url[0] !== '/') {
url = '/' + url;
}
return url;
}
const parseSearchParams = (searchString) => {
let pairSplit;
re... | params,
original,
actual
}; | random_line_split |
parseUrl.js | export default (original) => {
const url = getHashUrl(original);
let [path, params] = url.split('?');
if (path.length >= 2) {
path = path.replace(/\/$/, '');
}
if (params) {
params = parseSearchParams(params);
} else {
params = {}
}
const actual = path + joinSearchParams(params);
ret... | else {
url = '/';
}
if (url === '') {
url = '/';
}
if (url[0] !== '/') {
url = '/' + url;
}
return url;
}
const parseSearchParams = (searchString) => {
let pairSplit;
return (searchString || '').replace(/^\?/, '').split('&').reduce((p, pair) => {
pairSplit = pair.split('=');
if ... | {
url = url[1];
} | conditional_block |
app.rs | use actix::prelude::*;
use actix_web::*;
use actors::{ForwardA2AMsg, GetEndpoint};
use actors::forward_agent::ForwardAgent;
use bytes::Bytes;
use domain::config::AppConfig;
use futures::*;
const MAX_PAYLOAD_SIZE: usize = 105_906_176;
pub struct AppState {
pub forward_agent: Addr<ForwardAgent>,
}
pub fn | (config: AppConfig, forward_agent: Addr<ForwardAgent>) -> App<AppState> {
App::with_state(AppState { forward_agent })
.prefix(config.prefix)
.middleware(middleware::Logger::default()) // enable logger
.resource("", |r| r.method(http::Method::GET).with(_get_endpoint_details))
.resourc... | new | identifier_name |
app.rs | use actix::prelude::*;
use actix_web::*;
use actors::{ForwardA2AMsg, GetEndpoint};
use actors::forward_agent::ForwardAgent;
use bytes::Bytes;
use domain::config::AppConfig;
use futures::*;
const MAX_PAYLOAD_SIZE: usize = 105_906_176;
pub struct AppState {
pub forward_agent: Addr<ForwardAgent>,
}
pub fn new(confi... |
fn _get_endpoint_details(state: State<AppState>) -> FutureResponse<HttpResponse> {
state.forward_agent
.send(GetEndpoint {})
.from_err()
.map(|res| match res {
Ok(endpoint) => HttpResponse::Ok().json(&endpoint),
Err(err) => HttpResponse::InternalServerError().body(f... | {
App::with_state(AppState { forward_agent })
.prefix(config.prefix)
.middleware(middleware::Logger::default()) // enable logger
.resource("", |r| r.method(http::Method::GET).with(_get_endpoint_details))
.resource("/msg", |r| r.method(http::Method::POST).with(_forward_message))
} | identifier_body |
app.rs | use actix::prelude::*;
use actix_web::*;
use actors::{ForwardA2AMsg, GetEndpoint};
use actors::forward_agent::ForwardAgent;
use bytes::Bytes;
use domain::config::AppConfig;
use futures::*;
const MAX_PAYLOAD_SIZE: usize = 105_906_176;
pub struct AppState {
pub forward_agent: Addr<ForwardAgent>,
}
pub fn new(confi... | })
.responder()
}
fn _forward_message((state, req): (State<AppState>, HttpRequest<AppState>)) -> FutureResponse<HttpResponse> {
req
.body()
.limit(MAX_PAYLOAD_SIZE)
.from_err()
.and_then(move |body| {
state.forward_agent
.send(ForwardA2AMs... | random_line_split | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(ascii)]
#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(cell_e... | else {
MAX_FILE_LIMIT
}
}
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
... | {
rlim.rlim_max
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(ascii)]
#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(cell_e... | // Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim: libc::rlimit = mem::uninitialized();
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_L... | const MAX_FILE_LIMIT: libc::rlim_t = 4096;
| random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(ascii)]
#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(cell_e... | () {
use std::mem;
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim: libc::rlimit = mem::uninitialized();
m... | perform_platform_specific_initialization | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(ascii)]
#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(cell_e... |
#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}
#[allow(unsafe_code)]
pub fn init() {
unsafe {
assert_eq!(js::jsapi::JS_Init(), true);
SetDOMProxyInformation(ptr::null(), 0, Some(script_task::shadow_check_callback));
}
// Create the global vtables used b... | {
use std::mem;
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim: libc::rlimit = mem::uninitialized();
matc... | identifier_body |
events.rs | use std::sync::mpsc::{Sender, Receiver, channel};
use std::iter::Iterator;
use std::error::Error;
use error;
use frame::events::{ServerEvent as FrameServerEvent, SimpleServerEvent as FrameSimpleServerEvent,
SchemaChange as FrameSchemaChange};
use frame::parser::parse_frame;
use compression::Compres... | else {
continue;
};
match self.tx.send(event) {
Err(err) => return Err(error::Error::General(err.description().to_string())),
_ => continue,
}
}
}
}
/// `EventStream` is an iterator which returns new events once they come.... | {
// unwrap is safe is we've checked that event_opt.is_some()
event_opt.unwrap().event as ServerEvent
} | conditional_block |
events.rs | use std::sync::mpsc::{Sender, Receiver, channel};
use std::iter::Iterator;
use std::error::Error;
use error;
use frame::events::{ServerEvent as FrameServerEvent, SimpleServerEvent as FrameSimpleServerEvent,
SchemaChange as FrameSchemaChange};
use frame::parser::parse_frame;
use compression::Compres... | /// It is similar to `Receiver::iter`.
pub fn new_listener<X>(transport: X) -> (Listener<X>, EventStream) {
let (tx, rx) = channel();
let listener = Listener {
transport: transport,
tx: tx,
};
let stream = EventStream { rx: rx };
(listener, stream)
}
/// `Listener` provides only one... | /// main thread.
///
/// `EventStream` is an iterator which returns new events once they come. | random_line_split |
events.rs | use std::sync::mpsc::{Sender, Receiver, channel};
use std::iter::Iterator;
use std::error::Error;
use error;
use frame::events::{ServerEvent as FrameServerEvent, SimpleServerEvent as FrameSimpleServerEvent,
SchemaChange as FrameSchemaChange};
use frame::parser::parse_frame;
use compression::Compres... |
}
/// `EventStream` is an iterator which returns new events once they come.
/// It is similar to `Receiver::iter`.
pub struct EventStream {
rx: Receiver<ServerEvent>,
}
impl Iterator for EventStream {
type Item = ServerEvent;
fn next(&mut self) -> Option<Self::Item> {
self.rx.recv().ok()
}
}... | {
loop {
let event_opt = try!(parse_frame(&mut self.transport, compressor))
.get_body()?
.into_server_event();
let event = if event_opt.is_some() {
// unwrap is safe is we've checked that event_opt.is_some()
event_opt.unwra... | identifier_body |
events.rs | use std::sync::mpsc::{Sender, Receiver, channel};
use std::iter::Iterator;
use std::error::Error;
use error;
use frame::events::{ServerEvent as FrameServerEvent, SimpleServerEvent as FrameSimpleServerEvent,
SchemaChange as FrameSchemaChange};
use frame::parser::parse_frame;
use compression::Compres... | <X> {
transport: X,
tx: Sender<ServerEvent>,
}
impl<X: CDRSTransport> Listener<X> {
/// It starts a process of listening to new events. Locks a frame.
pub fn start(&mut self, compressor: &Compression) -> error::Result<()> {
loop {
let event_opt = try!(parse_frame(&mut self.transport... | Listener | identifier_name |
checkout.py | # Copyright 2006 John Duda
# This file is part of Infoshopkeeper.
# Infoshopkeeper 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 any later version.
# Infoshopkeeper ... |
wxDialog.__init__(self, parent,-1,"Check out items")
self.mastersizer = wxBoxSizer(wxVERTICAL)
self.static1 = wxStaticText(self, -1, "Check out to :")
self.mastersizer.Add(self.static1)
self.notebook = wxNotebook(self, -1, style=wxNB_TOP)
self.new_member... | random_line_split | |
checkout.py | # Copyright 2006 John Duda
# This file is part of Infoshopkeeper.
# Infoshopkeeper 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 any later version.
# Infoshopkeeper ... |
def Borrow(self, id):
borrower = self.parent.membersList.get(id)
print borrower
for i in self.parent.orderbox.items:
# Check if this work on sqlobject 0.7... I got
# lots of problem on 0.6.1, and itemID __isn't__
# defined in emprunt, which is plain weir... | self.parent=parent
wxDialog.__init__(self, parent,-1,"Check out items")
self.mastersizer = wxBoxSizer(wxVERTICAL)
self.static1 = wxStaticText(self, -1, "Check out to :")
self.mastersizer.Add(self.static1)
self.notebook = wxNotebook(self, -1, style=wxNB_TOP)
... | identifier_body |
checkout.py | # Copyright 2006 John Duda
# This file is part of Infoshopkeeper.
# Infoshopkeeper 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 any later version.
# Infoshopkeeper ... | (self,event):
self.EndModal(1)
def Checkout(self,event):
borrower=self.borrower.GetValue()
if len(borrower)>0:
today="%s" % datetime.date.today()
self.parent.orderbox.change_status(today+"-"+borrower)
self.parent.orderbox.void()
self.Close... | OnCancel | identifier_name |
checkout.py | # Copyright 2006 John Duda
# This file is part of Infoshopkeeper.
# Infoshopkeeper 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 any later version.
# Infoshopkeeper ... |
self.parent.orderbox.setBorrowed()
self.parent.orderbox.void()
self.Close()
def OnCancel(self,event):
self.EndModal(1)
def Checkout(self,event):
borrower=self.borrower.GetValue()
if len(borrower)>0:
today="%s" % datetime.date.today()
... | e = Emprunt(borrower = id, itemID=i.database_id)
print i.database_id | conditional_block |
bitten.py | import codecs
unicode_string = "Hello Python 3 String"
bytes_object = b"Hello Python 3 Bytes"
print(unicode_string, type(unicode_string))
print(bytes_object, type(bytes_object))
#decode to unicode_string
ux = str(object=bytes_object, encoding="utf-8", errors="strict")
print(ux, type(ux))
ux = bytes_object.dec... |
if __name__ == "__main__":
print( encodes("walla") )
| pass | identifier_body |
bitten.py | import codecs
unicode_string = "Hello Python 3 String"
bytes_object = b"Hello Python 3 Bytes"
print(unicode_string, type(unicode_string))
print(bytes_object, type(bytes_object))
#decode to unicode_string
ux = str(object=bytes_object, encoding="utf-8", errors="strict")
print(ux, type(ux))
ux = bytes_object.dec... | ( btext ):
#btext = int('0b110100001100101011011000110110001101111', 2)
return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode()
def char_to_bytes(char):
return bin(ord(char))
def encodes(text):
bext = text.encode(encoding="utf-8")
enc_bext = codecs.encode(bext, "hex_codec")
retu... | bytes_to_string | identifier_name |
bitten.py | import codecs
unicode_string = "Hello Python 3 String"
bytes_object = b"Hello Python 3 Bytes"
print(unicode_string, type(unicode_string))
print(bytes_object, type(bytes_object))
#decode to unicode_string
ux = str(object=bytes_object, encoding="utf-8", errors="strict")
print(ux, type(ux))
ux = bytes_object.dec... | #btext = int('0b110100001100101011011000110110001101111', 2)
return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode()
def char_to_bytes(char):
return bin(ord(char))
def encodes(text):
bext = text.encode(encoding="utf-8")
enc_bext = codecs.encode(bext, "hex_codec")
return enc_bext... | def bytes_to_string( btext ): | random_line_split |
bitten.py | import codecs
unicode_string = "Hello Python 3 String"
bytes_object = b"Hello Python 3 Bytes"
print(unicode_string, type(unicode_string))
print(bytes_object, type(bytes_object))
#decode to unicode_string
ux = str(object=bytes_object, encoding="utf-8", errors="strict")
print(ux, type(ux))
ux = bytes_object.dec... | print( encodes("walla") ) | conditional_block | |
css-tag_test.ts | /**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import {css, CSSResult, unsafeCSS} from '../css-tag.js';
import {assert} from '@esm-bundle/chai';
suite('Styling', () => {
suite('css tag', () => {
test('CSSResults always produce the same stylesheet', () => {
// Ali... | // Example use case: apply cssModule as global page styles at
// document.body level.
const bodyStyles = `${cssModule}`;
assert.equal(bodyStyles.replace(/\s/g, ''), '.my-module{color:yellow;}');
});
});
}); | color: yellow;
}
`;
// Coercion allows for reusage of css-tag outcomes in regular strings. | random_line_split |
index.js | (function() {
'use strict';
let EE = require('./ee');
let ES6 = require('./es6');
let log = require('ee-log');
let iterations = 100;
let start;
let ee = 0;
let es6 = 0;
for (let k = 0; k < 1000; k++) {
start = process.hrtime();
for (let i = 0; i < iterations; i+... | log.success('ES6: '+(process.hrtime(start)[1]));
start = process.hrtime();
for (let i = 0; i < iterations; i++) {
new EE({
name: "fabian"
, age: 15
, isAlive: true
}).describe();
}
ee += process.hrtime(st... | , isAlive: true
}).describe();
}
es6 += process.hrtime(start)[1]; | random_line_split |
index.js | (function() {
'use strict';
let EE = require('./ee');
let ES6 = require('./es6');
let log = require('ee-log');
let iterations = 100;
let start;
let ee = 0;
let es6 = 0;
for (let k = 0; k < 1000; k++) {
start = process.hrtime();
for (let i = 0; i < iterations; i+... |
es6 += process.hrtime(start)[1];
log.success('ES6: '+(process.hrtime(start)[1]));
start = process.hrtime();
for (let i = 0; i < iterations; i++) {
new EE({
name: "fabian"
, age: 15
, isAlive: true
}).describe();... | {
new ES6({
name: "fabian"
, age: 15
, isAlive: true
}).describe();
} | conditional_block |
cache.py |
# Copyright (C) 2014 - Oscar Campos <oscar.campos@member.fsf.org>
# This program is Free Software see LICENSE file for details
import os
import json
import platform
from collections import defaultdict
from anaconda_go.lib import go
from anaconda_go.lib.plugin import typing
cachepath = {
'linux': os.path.join('~... |
for member in guru['package'].get('members', []):
if member.get('name') == node_name:
node = member
break
for method in member.get('methods', []):
if method['name'] == node_name:
node = metho... | node = guru
break | conditional_block |
cache.py |
# Copyright (C) 2014 - Oscar Campos <oscar.campos@member.fsf.org>
# This program is Free Software see LICENSE file for details
import os
import json
import platform
from collections import defaultdict
from anaconda_go.lib import go
from anaconda_go.lib.plugin import typing
cachepath = {
'linux': os.path.join('~... |
def persist_package_cache() -> None:
"""Write the contents of the package cache for this GOROOT into the disk
"""
gopath = go.GOPATH.replace(os.path.sep, '_')
cachefile = os.path.join(cache_directory, gopath, 'packages.cache')
if not os.path.exists(os.path.dirname(cachefile)):
os.makedir... | """Lookup the given node_name in the cache and return it back
"""
node = {}
if node_name == '':
node = PACKAGES_CACHE[go.GOROOT]
else:
for pkg in PACKAGES_CACHE[go.GOROOT]:
guru = pkg.get('Guru')
if guru is None:
continue
path = guru['... | identifier_body |
cache.py | # Copyright (C) 2014 - Oscar Campos <oscar.campos@member.fsf.org>
# This program is Free Software see LICENSE file for details
import os
import json
import platform
from collections import defaultdict
from anaconda_go.lib import go
from anaconda_go.lib.plugin import typing
cachepath = {
'linux': os.path.join('~'... | except FileNotFoundError:
pass | random_line_split | |
cache.py |
# Copyright (C) 2014 - Oscar Campos <oscar.campos@member.fsf.org>
# This program is Free Software see LICENSE file for details
import os
import json
import platform
from collections import defaultdict
from anaconda_go.lib import go
from anaconda_go.lib.plugin import typing
cachepath = {
'linux': os.path.join('~... | (package: typing.Dict) -> bool:
"""Look for the given package in the cache and return true if is there
"""
for pkg in PACKAGES_CACHE[go.GOROOT]:
if pkg['ImportPath'] == package['ImportPath']:
return True
return False
def lookup(node_name: str='') -> typing.Dict:
"""Lookup the... | package_in_cache | identifier_name |
pay.js | 'use strict';
let lib = {
"_id": "5e409c94c5a59210a815262c",
"name": "pay",
"description": "MS pay service for marketplace",
"type": "service",
"configuration": {
"subType": "ecommerce",
"port": 4102,
"group": "Marketplace",
"requestTimeout": 30,
"requestTimeoutRenewal": 5,
"maintenance": { | "readiness": "/heartbeat"
}
},
"versions": [
{
"version": "1",
"extKeyRequired": true,
"oauth": true,
"provision_ACL": false,
"tenant_Profile": false,
"urac": false,
"urac_ACL": false,
"urac_Config": false,
"urac_GroupConfig": false,
"urac_Profile": false,
"apis": [
{
... | "port": {
"type": "maintenance"
}, | random_line_split |
sample.rs | use std::collections::HashMap; | /// total number of events.
pub struct Sample<T> {
pub counts: HashMap<T,usize>,
pub total: usize,
}
impl<T: Eq + Hash> Sample<T> {
/// Creates a new Sample.
pub fn new() -> Sample<T> {
Sample {
counts: HashMap::new(),
total: 0,
}
}
/// Add an event to a... | use std::hash::Hash;
use std::iter::FromIterator;
/// A collection of events, with a running total of counts for each event and | random_line_split |
sample.rs | use std::collections::HashMap;
use std::hash::Hash;
use std::iter::FromIterator;
/// A collection of events, with a running total of counts for each event and
/// total number of events.
pub struct Sample<T> {
pub counts: HashMap<T,usize>,
pub total: usize,
}
impl<T: Eq + Hash> Sample<T> {
/// Creates a n... | (&self, event: &T) -> f64 {
let c = *self.counts.get(event).unwrap_or(&0);
(c as f64) / (self.total as f64)
}
}
// ---------------------------
impl<T: Eq + Hash> Extend<T> for Sample<T> {
fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
for k in iter { self.add(k); }
}
}
i... | p | identifier_name |
htmlhrelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods};
use... | (&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("align") => AttrValue::from_dimension(value.into()),
&local_name!("co... | super_type | identifier_name |
htmlhrelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods};
use... | impl HTMLHRElementMethods for HTMLHRElement {
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_getter!(Align, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-align
make_atomic_setter!(SetAlign, "align");
// https://html.spec.whatwg.org/multipage/#dom-hr-color
make_gette... | random_line_split | |
sig.rs | use std::collections::HashMap; |
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::sha1::Sha1;
use super::util;
fn transform_payload<K, V>(d: &HashMap<K, V>) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash
{
let mut kv_list: Vec<_> = d.iter().map(|(k, v)| (k.as_ref(), v.as_ref())).collect();
kv_li... | use std::hash::Hash; | random_line_split |
sig.rs | use std::collections::HashMap;
use std::hash::Hash;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::sha1::Sha1;
use super::util;
fn transform_payload<K, V>(d: &HashMap<K, V>) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash
{
let mut kv_list: Vec<_> = d.iter().map(|(k... | <K, V, S>(d: &HashMap<K, V>, secret: S) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash,
S: AsRef<str>
{
let payload = transform_payload(d);
let mut hmac = Hmac::new(Sha1::new(), secret.as_ref().as_bytes());
hmac.input(payload.as_bytes());
util::b64encode(h... | sign | identifier_name |
sig.rs | use std::collections::HashMap;
use std::hash::Hash;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::sha1::Sha1;
use super::util;
fn transform_payload<K, V>(d: &HashMap<K, V>) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash
{
let mut kv_list: Vec<_> = d.iter().map(|(k... |
result.push_str(k);
result.push('=');
result.push_str(v);
}
result
}
pub fn sign<K, V, S>(d: &HashMap<K, V>, secret: S) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash,
S: AsRef<str>
{
let payload = transform_payload(d);
let mut hm... | {
result.push('&');
} | conditional_block |
sig.rs | use std::collections::HashMap;
use std::hash::Hash;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::sha1::Sha1;
use super::util;
fn transform_payload<K, V>(d: &HashMap<K, V>) -> String
where K: AsRef<str> + Eq + Hash,
V: AsRef<str> + Eq + Hash
{
let mut kv_list: Vec<_> = d.iter().map(|(k... |
}
| {
let x = {
let mut tmp: HashMap<&str, String> = HashMap::new();
tmp.insert("k2", "v2".to_string());
tmp.insert("k3", "v3".to_string());
tmp.insert("k1", "v1".to_string());
tmp
};
assert_eq!(sign(&x, "012345"), "iAKpGb9i8EKY8q4HPfiMdfb2... | identifier_body |
closeDialog.js | // -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-
const Clutter = imports.gi.Clutter;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Lang = imports.lang;
const Meta = imports.gi.Meta;
const Shell = imports.gi.Shell;
const Dialog = imports.ui.dialog;
co... | this._addWindowEffect();
this._initDialog();
this._dialog.scale_y = 0;
this._dialog.set_pivot_point(0.5, 0.5);
Tweener.addTween(this._dialog,
{ scale_y: 1,
transition: 'linear',
time: DIALOG_TRANSITI... | random_line_split | |
closeDialog.js | // -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-
const Clutter = imports.gi.Clutter;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Lang = imports.lang;
const Meta = imports.gi.Meta;
const Shell = imports.gi.Shell;
const Dialog = imports.ui.dialog;
co... | ,
_createDialogContent() {
let tracker = Shell.WindowTracker.get_default();
let windowApp = tracker.get_window_app(this._window);
/* Translators: %s is an application name */
let title = _("“%s” is not responding.").format(windowApp.get_name());
let subtitle = _("You may ch... | {
this._window = window;
} | identifier_body |
closeDialog.js | // -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-
const Clutter = imports.gi.Clutter;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Lang = imports.lang;
const Meta = imports.gi.Meta;
const Shell = imports.gi.Shell;
const Dialog = imports.ui.dialog;
co... | (window) {
this._window = window;
},
_createDialogContent() {
let tracker = Shell.WindowTracker.get_default();
let windowApp = tracker.get_window_app(this._window);
/* Translators: %s is an application name */
let title = _("“%s” is not responding.").format(windowApp.ge... | window | identifier_name |
deprecated.js | if ( 'undefined' !== typeof(jQuery.fn.bxSlider) ) {
jQuery( '.bxslider' ).each( function () {
var $slider = jQuery( this );
$slider.bxSlider( $slider.data( 'settings' ) );
} );
}
if ( 'undefined' !== typeof(window.Swiper) ) {
jQuery( '.swiper-container' ).each( function () {
var $this = jQuery( this ),
my_... | }
jQuery( window ).resize( function () {
$this.find( '.swiper-slide' ).each( function () {
var height = jQuery( this ).outerHeight( true );
if ( height > max_slide_size ) {
max_slide_size = height;
}
} );
$this.height( max_slide_size );
} );
my_swiper = jQuery( this ).swiper( jQuery.ex... | $this.height( max_slide_size );
$this.css( 'overflow', 'hidden' ); | random_line_split |
BlurFilter.js | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | (blurX, blurY) {
_super.call(this);
this.blurX = blurX;
this.blurY = blurY;
this.type = "blur";
}
var __egretProto__ = BlurFilter.prototype;
return BlurFilter;
})(egret.Filter);
egret.BlurFilter = BlurFilter;
BlurFilter.prototype.__clas... | BlurFilter | identifier_name |
BlurFilter.js | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... |
var __egretProto__ = BlurFilter.prototype;
return BlurFilter;
})(egret.Filter);
egret.BlurFilter = BlurFilter;
BlurFilter.prototype.__class__ = "egret.BlurFilter";
})(egret || (egret = {}));
| {
_super.call(this);
this.blurX = blurX;
this.blurY = blurY;
this.type = "blur";
} | identifier_body |
BlurFilter.js | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved. | // modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, th... | // Redistribution and use in source and binary forms, with or without | random_line_split |
zdt1.rs | /// ZDT1 bi-objective test function
///
/// Evaluates solution parameters using the ZDT1 [1] synthetic test
/// test function to produce two objective values.
///
/// [1 ]E. Zitzler, K. Deb, and L. Thiele. Comparison of Multiobjective
/// Evolutionary Algorithms: Empirical Results. Evolutionary
/// Computation, 8(2):17... | (parameters: [f32; 30]) -> [f32; 2] {
// objective function 1
let f1 = parameters[0];
// objective function 2
let mut g = 1_f32;
// g(x)
for i in 1..parameters.len() {
g = g + ((9_f32 / (parameters.len() as f32 - 1_f32)) * parameters[i]);
}
// h(f1, x)
let h = 1_f32 - (f1 ... | zdt1 | identifier_name |
zdt1.rs | /// ZDT1 bi-objective test function
///
/// Evaluates solution parameters using the ZDT1 [1] synthetic test
/// test function to produce two objective values.
///
/// [1 ]E. Zitzler, K. Deb, and L. Thiele. Comparison of Multiobjective
/// Evolutionary Algorithms: Empirical Results. Evolutionary
/// Computation, 8(2):17... | {
// objective function 1
let f1 = parameters[0];
// objective function 2
let mut g = 1_f32;
// g(x)
for i in 1..parameters.len() {
g = g + ((9_f32 / (parameters.len() as f32 - 1_f32)) * parameters[i]);
}
// h(f1, x)
let h = 1_f32 - (f1 / g).sqrt();
// f2(x)
let f... | identifier_body | |
zdt1.rs | /// ZDT1 bi-objective test function
///
/// Evaluates solution parameters using the ZDT1 [1] synthetic test
/// test function to produce two objective values.
///
/// [1 ]E. Zitzler, K. Deb, and L. Thiele. Comparison of Multiobjective
/// Evolutionary Algorithms: Empirical Results. Evolutionary
/// Computation, 8(2):17... |
// objective function 1
let f1 = parameters[0];
// objective function 2
let mut g = 1_f32;
// g(x)
for i in 1..parameters.len() {
g = g + ((9_f32 / (parameters.len() as f32 - 1_f32)) * parameters[i]);
}
// h(f1, x)
let h = 1_f32 - (f1 / g).sqrt();
// f2(x)
let f2 ... | pub fn zdt1(parameters: [f32; 30]) -> [f32; 2] { | random_line_split |
470 Implement Rand10() Using Rand7().py | #!/usr/bin/python3
"""
Given a function rand7 which generates a uniform random integer in the range 1
to 7, write a function rand10 which generates a uniform random integer in the
range 1 to 10.
Do NOT use system's Math.random().
"""
# The rand7() API is already defined for you.
def rand7():
return 0
class Sol... | (self):
"""
generate 7 twice, (rv1, rv2), 49 combination
assign 40 combinations for the 1 to 10 respectively
7-ary system
:rtype: int
"""
while True:
rv1 = rand7()
rv2 = rand7()
s = (rv1 - 1) * 7 + (rv2 - 1) # make it start fr... | rand10 | identifier_name |
470 Implement Rand10() Using Rand7().py | #!/usr/bin/python3
"""
Given a function rand7 which generates a uniform random integer in the range 1
to 7, write a function rand10 which generates a uniform random integer in the
range 1 to 10.
Do NOT use system's Math.random().
"""
| return 0
class Solution:
def rand10(self):
"""
generate 7 twice, (rv1, rv2), 49 combination
assign 40 combinations for the 1 to 10 respectively
7-ary system
:rtype: int
"""
while True:
rv1 = rand7()
rv2 = rand7()
s = ... | # The rand7() API is already defined for you.
def rand7(): | random_line_split |
470 Implement Rand10() Using Rand7().py | #!/usr/bin/python3
"""
Given a function rand7 which generates a uniform random integer in the range 1
to 7, write a function rand10 which generates a uniform random integer in the
range 1 to 10.
Do NOT use system's Math.random().
"""
# The rand7() API is already defined for you.
def rand7():
return 0
class Sol... | """
generate 7 twice, (rv1, rv2), 49 combination
assign 40 combinations for the 1 to 10 respectively
7-ary system
:rtype: int
"""
while True:
rv1 = rand7()
rv2 = rand7()
s = (rv1 - 1) * 7 + (rv2 - 1) # make it start from 0
... | identifier_body | |
470 Implement Rand10() Using Rand7().py | #!/usr/bin/python3
"""
Given a function rand7 which generates a uniform random integer in the range 1
to 7, write a function rand10 which generates a uniform random integer in the
range 1 to 10.
Do NOT use system's Math.random().
"""
# The rand7() API is already defined for you.
def rand7():
return 0
class Sol... | return s % 10 + 1 # since I make it start from 0 | conditional_block | |
search.py | # Copyright 2013 Google 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | (cls):
return True
@classmethod
def is_enabled_for_course(cls, app_context):
course_settings = app_context.get_environ().get('course')
return course_settings and course_settings.get(AUTO_INDEX_SETTING)
def cron_action(self, app_context, unused_global_state):
try:
... | is_globally_enabled | identifier_name |
search.py | # Copyright 2013 Google 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
return {'num_indexed_docs': len(timestamps),
'doc_types': indexed_doc_types,
'indexing_time_secs': time.time() - start_time}
def clear_index(namespace, locale):
"""Delete all docs in the index for a given models.Course object."""
if not custom_module.enabled:
raise Module... | indexed_doc_types[type_name] += 1 | conditional_block |
search.py | # Copyright 2013 Google 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | number_found_accuracy=100,
snippeted_fields=snippeted_fields)
query = search.Query(query_string=query_string, options=options)
results = index.search(query)
except search.Error:
logging.info('Failed searching for: %s', query_string)
return {'results': None, 't... | offset=offset,
returned_fields=returned_fields, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.