file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
index.ts
import { Application, Model, Property, QueryHandler, ActionHandler, Validator, SchemaTypeDefinition, IRequestContext, VALIDATORS } from 'vulcain-corejs'; // Define and register a new custom type (or validator) @SchemaTypeDefinition() class Age { type = "number"; // Define a sub type (optional) // Custom proper...
(val: number, context?: IRequestContext) { if (val < this.$min || val > 123) return "Age must be between {$min} and 123"; return null; } // Optional coerce method // used to convert the input value // coerce(val): number { return val;} } @Model() export class Hobby { @...
validate
identifier_name
index.ts
import { Application, Model, Property, QueryHandler, ActionHandler, Validator, SchemaTypeDefinition, IRequestContext, VALIDATORS } from 'vulcain-corejs'; // Define and register a new custom type (or validator) @SchemaTypeDefinition() class Age { type = "number"; // Define a sub type (optional) // Custom proper...
lastName: string; // Custom type @Property({ type: "Age", required: true, typeProperties: { min: 10 } }) age: number; @Property({ type: "uid", isKey: true }) // Create a new unique id if empty id: string; @Property({ type: "Hobby", cardinality: "many" }) hobbies: Hobby[]; } // Start ...
random_line_split
progress_bar.py
from lib.font import * import sys import fcntl import termios import struct class progress_bar(object): def __init__(self, tot=100, lenght=10): self.cp='/-\|' self.bar_lenght = lenght self.tot = tot def startprogress(self, title): """Creates a progress bar 40 chars long on the console and moves cursor ba...
sys.stdout.write(self.progress(current,total) + '\r') sys.stdout.flush()
identifier_body
progress_bar.py
from lib.font import * import sys import fcntl import termios import struct class progress_bar(object):
self.tot = tot def startprogress(self, title): """Creates a progress bar 40 chars long on the console and moves cursor back to beginning with BS character""" sys.stdout.write(title + ": [" + "-" * self.bar_lenght + "]" + chr(8) * (self.bar_lenght+1)) sys.stdout.flush() def progress(self, x): """Sets pro...
def __init__(self, tot=100, lenght=10): self.cp='/-\|' self.bar_lenght = lenght
random_line_split
progress_bar.py
from lib.font import * import sys import fcntl import termios import struct class progress_bar(object): def __init__(self, tot=100, lenght=10): self.cp='/-\|' self.bar_lenght = lenght self.tot = tot def
(self, title): """Creates a progress bar 40 chars long on the console and moves cursor back to beginning with BS character""" sys.stdout.write(title + ": [" + "-" * self.bar_lenght + "]" + chr(8) * (self.bar_lenght+1)) sys.stdout.flush() def progress(self, x): """Sets progress bar to a certain percentage x....
startprogress
identifier_name
util.py
# -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, division) import json import re import six import sys channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;]+\Z') app_id_re = re.compile('\A[0-9]+\Z') pusher_url_re = re.compile('\A(http|htt...
else: text = 'a string' def ensure_text(obj, name): if isinstance(obj, six.text_type): return obj if isinstance(obj, six.string_types): return six.text_type(obj) raise TypeError("%s should be %s" % (name, text)) def validate_channel(channel): channel = ensure_text(channel, "channel"...
random_line_split
util.py
# -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, division) import json import re import six import sys channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;]+\Z') app_id_re = re.compile('\A[0-9]+\Z') pusher_url_re = re.compile('\A(http|htt...
def validate_socket_id(socket_id): socket_id = ensure_text(socket_id, "socket_id") if not socket_id_re.match(socket_id): raise ValueError("Invalid socket ID: %s" % socket_id) return socket_id
channel = ensure_text(channel, "channel") if len(channel) > 200: raise ValueError("Channel too long: %s" % channel) if not channel_name_re.match(channel): raise ValueError("Invalid Channel: %s" % channel) return channel
identifier_body
util.py
# -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, division) import json import re import six import sys channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;]+\Z') app_id_re = re.compile('\A[0-9]+\Z') pusher_url_re = re.compile('\A(http|htt...
raise TypeError("%s should be %s" % (name, text)) def validate_channel(channel): channel = ensure_text(channel, "channel") if len(channel) > 200: raise ValueError("Channel too long: %s" % channel) if not channel_name_re.match(channel): raise ValueError("Invalid Channel: %s" % channel...
return six.text_type(obj)
conditional_block
util.py
# -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, division) import json import re import six import sys channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;]+\Z') app_id_re = re.compile('\A[0-9]+\Z') pusher_url_re = re.compile('\A(http|htt...
(socket_id): socket_id = ensure_text(socket_id, "socket_id") if not socket_id_re.match(socket_id): raise ValueError("Invalid socket ID: %s" % socket_id) return socket_id
validate_socket_id
identifier_name
graph-node.ts
import { Graph } from './graph'; import { Link } from './graph-links'; /** * Represents a node in a {@link Graph}. * * @hidden * @category Graph */ export abstract class GraphNode { private _disposed = false; constructor(protected readonly graph: Graph<GraphNode>) { this.graph = graph; } /** * Returns tr...
/** * Adds a Link to a managed {@link @GraphChildList}, and sets up a listener to * remove the link if it's disposed. This function is only for lists of links, * annotated with {@link @GraphChildList}. Properties are annotated and managed by * {@link @GraphChild} instead. * * @hidden */ protected addG...
{ this.graph.swapChild(this, old, replacement); return this; }
identifier_body
graph-node.ts
import { Graph } from './graph'; import { Link } from './graph-links'; /** * Represents a node in a {@link Graph}. * * @hidden * @category Graph */ export abstract class GraphNode { private _disposed = false; constructor(protected readonly graph: Graph<GraphNode>) { this.graph = graph; } /** * Returns tr...
(): boolean { return this._disposed; } /** * Removes both inbound references to and outbound references from this object. At the end * of the process the object holds no references, and nothing holds references to it. A * disposed object is not reusable. */ public dispose(): void { this.graph.disconnect...
isDisposed
identifier_name
graph-node.ts
import { Graph } from './graph'; import { Link } from './graph-links'; /** * Represents a node in a {@link Graph}. * * @hidden * @category Graph */ export abstract class GraphNode { private _disposed = false; constructor(protected readonly graph: Graph<GraphNode>) { this.graph = graph; } /** * Returns tr...
* {@link @GraphChild} instead. * * @hidden */ protected addGraphChild(links: Link<GraphNode, GraphNode>[], link: Link<GraphNode, GraphNode>): this { links.push(link); link.onDispose(() => { const remaining = links.filter((l) => l !== link); links.length = 0; for (const link of remaining) links.pus...
random_line_split
index.d.ts
// Type definitions for linkedin dustjs 1.2.1 // Project: https://github.com/linkedin/dustjs // Definitions by: Marcelo Dezem <https://github.com/mdezem> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // // Due to a lack of documentation it's not possible // to know which methods are intended to be...
/** * Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required. * @param source the template string. * @param context a plain object or an instance of dust.Context. * @param callback (optional). ...
* @param context a plain object or an instance of dust.Context. */ export declare function render(name: string, context: any, callback: (err: any, out: string) => any): void; export declare function render(name: string, context: Context, callback: (err: any, out: string) => any): void;
random_line_split
test-array_fill.js
// warning: This file is auto generated by `npm run build:tests` // Do not edit by hand! process.env.TZ = 'UTC' var expect = require('chai').expect var ini_set = require('../../../../src/php/info/ini_set') // eslint-disable-line no-unused-vars,camelcase var ini_get = require('../../../../src/php/info/ini_get') // eslin...
describe('src/php/array/array_fill.js (tested in test/languages/php/array/test-array_fill.js)', function () { it('should pass example 1', function (done) { var expected = { 5: 'banana', 6: 'banana', 7: 'banana', 8: 'banana', 9: 'banana', 10: 'banana' } var result = array_fill(5, 6, 'banana') expect(result...
random_line_split
clipboard_provider.rs
use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; use collections::borrow::ToOwned; use std::sync::mpsc::channel; pub trait ClipboardProvider { // blocking method to get the clipboard contents fn get_clipboard_contents(&mut self) -> String; // blocking met...
/* 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/. */
random_line_split
clipboard_provider.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 msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; use collectio...
(&mut self, _: &str) { panic!("not yet implemented"); } } pub struct DummyClipboardContext { content: String } impl DummyClipboardContext { pub fn new(s: &str) -> DummyClipboardContext { DummyClipboardContext { content: s.to_owned() } } } impl ClipboardProvider for...
set_clipboard_contents
identifier_name
clipboard_provider.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 msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; use collectio...
} pub struct DummyClipboardContext { content: String } impl DummyClipboardContext { pub fn new(s: &str) -> DummyClipboardContext { DummyClipboardContext { content: s.to_owned() } } } impl ClipboardProvider for DummyClipboardContext { fn get_clipboard_contents(&mut self) -...
{ panic!("not yet implemented"); }
identifier_body
DbvsFreq-Ampde0.1v-2huequitos.py
#!/usr/bin/env python2.7 import numpy as np
Freq=np.array([30,40,45,50,53,55,60,65,70,80,90,95,98,100,110,120]) Db=np.array([70.5,78.6,83.2,88.4,87.5,86.7,85.2,83.9,85.1,88,95.7,100.4,100.4,99.2,94.7,94.9]) plt.xlabel('Frecuencia') plt.ylabel('Decibel') plt.title('DecibelvsFreq a 0.1volts') #for i in range(len(Freq)): # plt.text(Freq[i],Db[i], r'$Freq=%f, \ Db...
import matplotlib.pyplot as plt
random_line_split
FieldChips.stories.tsx
/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. 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 limitation the rights to use, copy, modi...
/> </Grid> ) } FieldChipOptions.parameters = { storyshots: { disable: true }, } export const Controlled = () => { const [values, setValues] = useState<string[]>(['bananas']) const [inputValue, setInputValue] = useState('oranges') const handleChange = (vals: string[]) => setValues(vals) const han...
validationMessage={{ message: 'This is an error', type: 'error', }} values={values}
random_line_split
index.d.ts
// Type definitions for non-npm package amap-js-api-scale 1.4 // Project: https://lbs.amap.com/api/javascript-api/reference/map-control#AMap.Scale // Definitions by: breeze9527 <https://github.com/breeze9527> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// <reference t...
控件停靠位置 */ position: Scale.Position; /** * 相对于地图容器左上角的偏移量 */ offset: Pixel; /** * 是否可见 */ visible: boolean; /** * 显示比例尺 */ show(): void; /** * 隐藏比例尺 */ hide(): void; ...
*
identifier_name
index.d.ts
// Type definitions for non-npm package amap-js-api-scale 1.4 // Project: https://lbs.amap.com/api/javascript-api/reference/map-control#AMap.Scale // Definitions by: breeze9527 <https://github.com/breeze9527> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// <reference t...
/** * 比例尺插件 */ class Scale extends EventEmitter { constructor(options?: Scale.Options); /** * 控件停靠位置 */ position: Scale.Position; /** * 相对于地图容器左上角的偏移量 */ offset: Pixel; /** * 是否可见 */ visible: ...
random_line_split
__init__.py
"""The StarLine component.""" import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.core import Config, HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .account import StarlineAccount from .const import ( DOMAIN, PLATFORMS, SERVICE_UPDA...
"""Triggered by config entry options updates.""" account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] scan_interval = config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) account.set_update_interval(scan_interval)
identifier_body
__init__.py
"""The StarLine component.""" import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.core import Config, HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .account import StarlineAccount from .const import ( DOMAIN, PLATFORMS, SERVICE_UPDA...
async def async_set_scan_interval(call): """Service for set scan interval.""" options = dict(config_entry.options) options[CONF_SCAN_INTERVAL] = call.data[CONF_SCAN_INTERVAL] hass.config_entries.async_update_entry(entry=config_entry, options=options) hass.services.async_regist...
hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, domain) )
conditional_block
__init__.py
"""The StarLine component.""" import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.core import Config, HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .account import StarlineAccount from .const import ( DOMAIN, PLATFORMS, SERVICE_UPDA...
await hass.config_entries.async_forward_entry_unload(config_entry, domain) account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] account.unload() return True async def async_options_updated(hass: HomeAssistant, config_entry: ConfigEntry) -> None: """Triggered by config entry opt...
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Unload a config entry.""" for domain in PLATFORMS:
random_line_split
__init__.py
"""The StarLine component.""" import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.core import Config, HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .account import StarlineAccount from .const import ( DOMAIN, PLATFORMS, SERVICE_UPDA...
(hass: HomeAssistant, config_entry: ConfigEntry) -> None: """Triggered by config entry options updates.""" account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] scan_interval = config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) account.set_update_interval(scan_interval)
async_options_updated
identifier_name
lists.py
""" This file contains code for working on lists and dictionaries. """ def moreThanOne(dict, key): """ Checks if a key in a dictionary has a value more than one. Arguments: dict -- the dictionary key -- the key Returns: True if the key exists in the dictionary and the value is at least one, otherwise...
return u def alphabetical(lst): """ Sorts a list of tuples in reverse alphabetical order by the first key in the tuple. Arguments: lst -- the list to sort Returns: the sorted list """ return list(reversed(sorted(lst, key=lambda x: x[0])))
if not l in u: u.append(l)
conditional_block
lists.py
""" This file contains code for working on lists and dictionaries. """ def moreThanOne(dict, key): """ Checks if a key in a dictionary has a value more than one. Arguments: dict -- the dictionary key -- the key Returns: True if the key exists in the dictionary and the value is at least one, otherwise...
(lst): """ Sorts a list of tuples in reverse alphabetical order by the first key in the tuple. Arguments: lst -- the list to sort Returns: the sorted list """ return list(reversed(sorted(lst, key=lambda x: x[0])))
alphabetical
identifier_name
lists.py
""" This file contains code for working on lists and dictionaries. """ def moreThanOne(dict, key): """ Checks if a key in a dictionary has a value more than one. Arguments: dict -- the dictionary key -- the key Returns: True if the key exists in the dictionary and the value is at least one, otherwise...
for l in list: if not l in u: u.append(l) return u def alphabetical(lst): """ Sorts a list of tuples in reverse alphabetical order by the first key in the tuple. Arguments: lst -- the list to sort Returns: the sorted list """ return list(reversed(sorted(lst, key=lambda x: x[0])))
return False def makeUnique(list): """ Removes duplicates from a list. """ u = []
random_line_split
lists.py
""" This file contains code for working on lists and dictionaries. """ def moreThanOne(dict, key): """ Checks if a key in a dictionary has a value more than one. Arguments: dict -- the dictionary key -- the key Returns: True if the key exists in the dictionary and the value is at least one, otherwise...
def makeUnique(list): """ Removes duplicates from a list. """ u = [] for l in list: if not l in u: u.append(l) return u def alphabetical(lst): """ Sorts a list of tuples in reverse alphabetical order by the first key in the tuple. Arguments: lst -- the list to sort Returns: the sorted list ...
""" Checks if any of a list of keys in a dictionary has a value more than one. Arguments: dict -- the dictionary keys -- the keys Returns: True if any key exists in the dictionary and the value is at least one, otherwise false """ for key in keys: if key in dict and dict[key] > 0: return True r...
identifier_body
console.py
#!/usr/bin/python # Console import sys, os, time, subprocess def MCS(): return subprocess.Popen(['python', 'mcs.py']) def color(text, color): if color == 0: color = "\033[0m" if color == 1: color = "\033[94m" if color == 2: color = "\033[92m" if color == 3: color = "\033[91m" if color == 4: ...
if command == 'q': exit(0) if __name__ == "__main__": main()
if main.poll() == None: main.terminate() main.kill()
conditional_block
console.py
#!/usr/bin/python # Console import sys, os, time, subprocess def MCS(): return subprocess.Popen(['python', 'mcs.py']) def color(text, color): if color == 0: color = "\033[0m" if color == 1: color = "\033[94m" if color == 2: color = "\033[92m" if color == 3: color = "\033[91m" if color == 4: ...
(): return True while 1: showMenu() command = str(input("=> ")) if command == '4': if main.poll() == None: main.terminate() main.kill() main = MCS() if command == '5': if main.poll() == None: main....
poll
identifier_name
console.py
#!/usr/bin/python # Console import sys, os, time, subprocess def MCS(): return subprocess.Popen(['python', 'mcs.py'])
if color == 0: color = "\033[0m" if color == 1: color = "\033[94m" if color == 2: color = "\033[92m" if color == 3: color = "\033[91m" if color == 4: color = "\033[93m" return color+text+"\033[0m" def showMenu(): print("\033[H\033[J", end="") print("== Music Control System v0.1 ==") ...
def color(text, color):
random_line_split
console.py
#!/usr/bin/python # Console import sys, os, time, subprocess def MCS(): return subprocess.Popen(['python', 'mcs.py']) def color(text, color): if color == 0: color = "\033[0m" if color == 1: color = "\033[94m" if color == 2: color = "\033[92m" if color == 3: color = "\033[91m" if color == 4: ...
while 1: showMenu() command = str(input("=> ")) if command == '4': if main.poll() == None: main.terminate() main.kill() main = MCS() if command == '5': if main.poll() == None: main.terminate() ...
def poll(): return True
identifier_body
test_nis.py
from test import support import unittest import sys # Skip test if nis module does not exist. nis = support.import_module('nis') class NisTests(unittest.TestCase): def test_maps(self):
else: # just test the one key, otherwise this test could take a # very long time done = 1 break if done: break if __name__ == '__main__': unittest.main()
try: maps = nis.maps() except nis.error as msg: # NIS is probably not active, so this test isn't useful self.skipTest(str(msg)) try: # On some systems, this map is only accessible to the # super user maps.remove("passwd.adjunct.byna...
identifier_body
test_nis.py
from test import support import unittest import sys
nis = support.import_module('nis') class NisTests(unittest.TestCase): def test_maps(self): try: maps = nis.maps() except nis.error as msg: # NIS is probably not active, so this test isn't useful self.skipTest(str(msg)) try: # On some systems,...
# Skip test if nis module does not exist.
random_line_split
test_nis.py
from test import support import unittest import sys # Skip test if nis module does not exist. nis = support.import_module('nis') class NisTests(unittest.TestCase): def test_maps(self): try: maps = nis.maps() except nis.error as msg: # NIS is probably not active, so this te...
if __name__ == '__main__': unittest.main()
mapping = nis.cat(nismap) for k, v in mapping.items(): if not k: continue if nis.match(k, nismap) != v: self.fail("NIS match failed for key `%s' in map `%s'" % (k, nismap)) else: # just test the one k...
conditional_block
test_nis.py
from test import support import unittest import sys # Skip test if nis module does not exist. nis = support.import_module('nis') class NisTests(unittest.TestCase): def
(self): try: maps = nis.maps() except nis.error as msg: # NIS is probably not active, so this test isn't useful self.skipTest(str(msg)) try: # On some systems, this map is only accessible to the # super user maps.remove("pas...
test_maps
identifier_name
codec.rs
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
{ Uint8, Uint16, Float32, Float64, } impl PositionEncoding { pub fn new(bounding_cube: &Cube, resolution: f64) -> PositionEncoding { let min_bits = (bounding_cube.edge_length() / resolution).log2() as u32 + 1; match min_bits { 0..=8 => PositionEncoding::Uint8, ...
PositionEncoding
identifier_name
codec.rs
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
// Capping at 24 keeps the worst resolution at ~1 mm for an edge length of ~8389 km. 17..=24 => PositionEncoding::Float32, _ => PositionEncoding::Float64, } } // TODO(sirver): Returning a Result here makes this function more expensive than needed - since // we re...
random_line_split
lib.rs
#![cfg_attr(feature = "nightly", feature(test))] #![feature(nll, try_trait)] #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; #[macro_use] extern crate bitflags; extern crate syntax; #[macro_use] extern crate derive_more; extern crate rls_span; #[macro_use] mod testutils; #[macro_use] mod util; ...
complete_from_file, complete_fully_qualified_name, find_definition, is_use_stmt, to_coords, to_point, }; pub use core::{ BytePos, ByteRange, Coordinate, FileCache, FileLoader, Location, Match, MatchType, Session, }; pub use primitive::PrimKind; pub use project_model::ProjectModelProvider; pub use snippets::...
pub use ast_types::PathSearch; pub use core::{
random_line_split
class-impl-very-parameterized-trait.rs
// Copyright 2012-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-MI...
fn find(&self, k: &int) -> Option<&T> { if *k <= self.meows { Some(&self.name) } else { None } } fn insert(&mut self, k: int, _: T) -> bool { self.meows += k; true } fn find_mut(&mut self, _k: &int) -> Option<&mut T> { panic!() } ...
{ *k <= self.meows }
identifier_body
class-impl-very-parameterized-trait.rs
// Copyright 2012-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-MI...
<T> { // Yes, you can have negative meows meows : int, how_hungry : int, name : T, } impl<T> cat<T> { pub fn speak(&mut self) { self.meow(); } pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; ret...
cat
identifier_name
class-impl-very-parameterized-trait.rs
// Copyright 2012-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-MI...
pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> { cat{meows: in_x, how_hungry: in_y, name: in_name } } } impl<T> cat<T> { fn meow(&mut self) { self.meows += 1; println!("Meow {}", self.meows); if self.meows % 5 == 0 { self.how_hungry += 1; } } ...
}
random_line_split
MiaoZuanScripts.py
#!/usr/bin/python #encoding=utf-8 import urllib, urllib2 import cookielib import re import time from random import random from json import dumps as json_dumps, loads as json_loads import sys reload(sys) sys.setdefaultencoding('utf-8') import os project_root_path = os.path.abspath(os.path.join(os.path....
(object): """docstring for MiaoZuan""" def __init__(self, account_file): super(MiaoZuan, self).__init__() self.headers = headers = { 'User-Agent':'IOS_8.1_IPHONE5C', 'm-lng':'113.331639', 'm-ct':'2', 'm-lat':'23.158624', 'm-cw'...
MiaoZuan
identifier_name
MiaoZuanScripts.py
#!/usr/bin/python #encoding=utf-8 import urllib, urllib2 import cookielib import re import time from random import random from json import dumps as json_dumps, loads as json_loads import sys reload(sys) sys.setdefaultencoding('utf-8') import os project_root_path = os.path.abspath(os.path.join(os.path....
cookie_support = urllib2.HTTPCookieProcessor(cookielib.CookieJar()) opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler) urllib2.install_opener(opener) try: content = urllib2.urlopen(req).read() resp_dict = json_loads(content) ret...
headers=self.headers )
random_line_split
MiaoZuanScripts.py
#!/usr/bin/python #encoding=utf-8 import urllib, urllib2 import cookielib import re import time from random import random from json import dumps as json_dumps, loads as json_loads import sys reload(sys) sys.setdefaultencoding('utf-8') import os project_root_path = os.path.abspath(os.path.join(os.path....
if resp_dict["IsSuccess"]: total_data_by_categoryId += resp_dict["Data"] logger.debug("get %s more points", resp_dict["Data"]) elif resp_dict["Code"] == 31303: logger.debug("view advert id = %s, Response from the server:...
selectNum -= silverAdsList_Count
conditional_block
MiaoZuanScripts.py
#!/usr/bin/python #encoding=utf-8 import urllib, urllib2 import cookielib import re import time from random import random from json import dumps as json_dumps, loads as json_loads import sys reload(sys) sys.setdefaultencoding('utf-8') import os project_root_path = os.path.abspath(os.path.join(os.path....
except Exception as e: logger.exception(e) return {"IsSuccess": False, "Desc": ""} def pull_SilverAdvert_List(self, categoryId): postdata = urllib.urlencode({ 'CategoryIds':categoryId }) req = urllib2.Request( url='http://ser...
postdata = urllib.urlencode({ 'UserName':userName, 'Password':passWord, 'Imei':imei }) req = urllib2.Request( url='http://service.inkey.com/api/Auth/Login', data=postdata, headers=self.headers ) ...
identifier_body
async_cmd_desc_map.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use crate::virtio::queue::DescriptorChain; use crate::virtio::video::command::QueueType; use crate::virtio::video::dev...
_ => { // Keep commands for other streams. } } } responses } }
{ // TODO(b/1518105): Use more appropriate error code if a new protocol supports // one. responses.push(AsyncCmdResponse::from_error( *tag, VideoError::InvalidOperation, )); }
conditional_block
async_cmd_desc_map.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use crate::virtio::queue::DescriptorChain; use crate::virtio::video::command::QueueType; use crate::virtio::video::dev...
impl AsyncCmdDescMap { pub fn insert(&mut self, tag: AsyncCmdTag, descriptor_chain: DescriptorChain) { self.0.insert(tag, descriptor_chain); } pub fn remove(&mut self, tag: &AsyncCmdTag) -> Option<DescriptorChain> { self.0.remove(tag) } /// Returns a list of `AsyncCmdResponse`s to ...
random_line_split
async_cmd_desc_map.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use crate::virtio::queue::DescriptorChain; use crate::virtio::video::command::QueueType; use crate::virtio::video::dev...
AsyncCmdTag::Drain { stream_id } if stream_id == target_stream_id => { // TODO(b/1518105): Use more appropriate error code if a new protocol supports // one. responses.push(AsyncCmdResponse::from_error( *tag, ...
{ let mut responses = vec![]; for tag in self.0.keys().filter(|&&k| Some(k) != processing_tag) { match tag { AsyncCmdTag::Queue { stream_id, queue_type, .. } if stream_id == target_stream_id ...
identifier_body
async_cmd_desc_map.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use crate::virtio::queue::DescriptorChain; use crate::virtio::video::command::QueueType; use crate::virtio::video::dev...
(BTreeMap<AsyncCmdTag, DescriptorChain>); impl AsyncCmdDescMap { pub fn insert(&mut self, tag: AsyncCmdTag, descriptor_chain: DescriptorChain) { self.0.insert(tag, descriptor_chain); } pub fn remove(&mut self, tag: &AsyncCmdTag) -> Option<DescriptorChain> { self.0.remove(tag) } //...
AsyncCmdDescMap
identifier_name
zephyr.py
apjoin(callback=self.lvap_join_callback) # Register an lvap leave event self.lvapleave(callback=self.lvap_leave_callback) def lvap_leave_callback(self, lvap): """Called when an LVAP disassociates from a tennant.""" self.log.info("LVAP %s left %s" % (lvap.addr, lvap.ssid)) def...
# Filter Resource Blocks by RSSI valid = [block for block in matches if block.ucqm[lvap.addr]['mov_rssi'] >= max_rssi] if not valid: self.log.info("not valid") ...
max_rssi=block.ucqm[lvap.addr]['mov_rssi']
conditional_block
zephyr.py
apjoin(callback=self.lvap_join_callback) # Register an lvap leave event self.lvapleave(callback=self.lvap_leave_callback) def lvap_leave_callback(self, lvap): """Called when an LVAP disassociates from a tennant.""" self.log.info("LVAP %s left %s" % (lvap.addr, lvap.ssid)) def...
(self, lvap): """Called when an joins the network.""" self.rssi(lvap=lvap.addr, value=self.limit, relation='LT', callback=self.low_rssi) def handover(self, lvap): """ Handover the LVAP to a WTP with an RSSI higher that -65dB. """ self.log.info("Running han...
lvap_join_callback
identifier_name
zephyr.py
apjoin(callback=self.lvap_join_callback) # Register an lvap leave event self.lvapleave(callback=self.lvap_leave_callback) def lvap_leave_callback(self, lvap): """Called when an LVAP disassociates from a tennant.""" self.log.info("LVAP %s left %s" % (lvap.addr, lvap.ssid)) def...
def lvap_join_callback(self, lvap): """Called when an joins the network.""" self.rssi(lvap=lvap.addr, value=self.limit, relation='LT', callback=self.low_rssi) def handover(self, lvap): """ Handover the LVAP to a WTP with an RSSI higher that -65dB. """ ...
"""Called when a new WTP connects to the controller.""" for block in wtp.supports: self.ucqm(block=block, every=self.every)
identifier_body
zephyr.py
apjoin(callback=self.lvap_join_callback) # Register an lvap leave event self.lvapleave(callback=self.lvap_leave_callback) def lvap_leave_callback(self, lvap): """Called when an LVAP disassociates from a tennant.""" self.log.info("LVAP %s left %s" % (lvap.addr, lvap.ssid)) def...
def lvap_join_callback(self, lvap): """Called when an joins the network.""" self.rssi(lvap=lvap.addr, value=self.limit, relation='LT', callback=self.low_rssi) def handover(self, lvap): """ Handover the LVAP to a WTP with an RSSI higher that -65dB. """ ...
for block in wtp.supports: self.ucqm(block=block, every=self.every)
random_line_split
readers.py
""" DataReader code lives here. All DataReader classes should extend DataReader and implement the following methods: - help() - get_data() """ from datetime import datetime import requests class DataReader(object): """ Class-level constants that can be defined in code until we get around to putt...
(self, uri): """ Hit Wunderground API and retrieve JSON object. Return GaugeData object. :param uri : this is the gauge being queried :returns: <GaugeData>: updated values in the form of a GaugeData object """
get_data
identifier_name
readers.py
""" DataReader code lives here. All DataReader classes should extend DataReader and implement the following methods: - help() - get_data() """ from datetime import datetime import requests class DataReader(object): """ Class-level constants that can be defined in code until we get around to putt...
package = {"gauge_id": uri, "timestamp": datetime.strptime( output["00065"]["dateTime"][:18], "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"), "level": level, "flow_cfs": flow} return package cla...
level = output["00065"]["value"]
conditional_block
readers.py
""" DataReader code lives here. All DataReader classes should extend DataReader and implement the following methods: - help() - get_data() """ from datetime import datetime import requests class DataReader(object): """ Class-level constants that can be defined in code until we get around to putt...
def help(self): return self.RETURN_FORMAT class USGSDataReader(DataReader): TARGET_URL = "http://waterservices.usgs.gov/nwis/iv/?format={}&sites={}&parameterCd={}" DATA_TYPE = "json" USGS_CODE_FLOW = '00060' USGS_CODE_LEVEL = '00065' def __init__(self): super(USGSDataReader...
pass
identifier_body
readers.py
""" DataReader code lives here. All DataReader classes should extend DataReader and implement the following methods: - help() - get_data() """ from datetime import datetime import requests class DataReader(object): """ Class-level constants that can be defined in code until we get around to putt...
output["00065"]["dateTime"][:18], "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"), "level": level, "flow_cfs": flow} return package class WundergroundReader(DataReader): TARGET_URL = "http://api.wunderground.com/api/{}...
package = {"gauge_id": uri, "timestamp": datetime.strptime(
random_line_split
test.py
from nose.tools import with_setup import os import hk_glazer as js2deg import subprocess import json class TestClass: @classmethod def setup_class(cls): cls.here = os.path.dirname(__file__) cls.data = cls.here + '/data' def test_1(self): '''Test 1: Check that json_to_degree works when imported'...
finally: os.remove("test3.txt")
assert(False)
conditional_block
test.py
from nose.tools import with_setup import os import hk_glazer as js2deg import subprocess import json
cls.here = os.path.dirname(__file__) cls.data = cls.here + '/data' def test_1(self): '''Test 1: Check that json_to_degree works when imported''' with open(self.data + "/json_test_in.json") as config_file: config_dict = json.load(config_file) gen_str = js2deg.dict_to_dat(config_dic...
class TestClass: @classmethod def setup_class(cls):
random_line_split
test.py
from nose.tools import with_setup import os import hk_glazer as js2deg import subprocess import json class TestClass: @classmethod def setup_class(cls): cls.here = os.path.dirname(__file__) cls.data = cls.here + '/data' def test_1(self): '''Test 1: Check that json_to_degree works when imported'...
(self): '''Test 2: Check command line execution when saving to file''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') print(cmd) subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"]) with open("test2.txt") as file: gen_str = ...
test_2
identifier_name
test.py
from nose.tools import with_setup import os import hk_glazer as js2deg import subprocess import json class TestClass: @classmethod def setup_class(cls): cls.here = os.path.dirname(__file__) cls.data = cls.here + '/data' def test_1(self): '''Test 1: Check that json_to_degree works when imported'...
def test_3(self): '''Test 3: Command line execution when outfile already exists''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"]) try: subprocess.check_call([cmd,"js2degree", self.data ...
'''Test 2: Check command line execution when saving to file''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') print(cmd) subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"]) with open("test2.txt") as file: gen_str = file.read() ...
identifier_body
environment.prod.ts
/** * Copyright 2022 Google LLC * * 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 writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT W...
random_line_split
shardcounter_sync.py
import random from google.appengine.api import memcache from google.appengine.ext import ndb SHARD_KEY_TEMPLATE = 'shard-{}-{:d}' class GeneralCounterShardConfig(ndb.Model): num_shards = ndb.IntegerProperty(default=20) @classmethod def all_keys(cls, name): config = cls.get_or_insert(name) ...
parent_key = ndb.Key('ShardCounterParent', name) shard_query = GeneralCounterShard.query(ancestor=parent_key) shard_counters = shard_query.fetch(limit=None) for counter in shard_counters: if counter is not None: total += counter.count memcach...
if total is None: total = 0
random_line_split
shardcounter_sync.py
import random from google.appengine.api import memcache from google.appengine.ext import ndb SHARD_KEY_TEMPLATE = 'shard-{}-{:d}' class GeneralCounterShardConfig(ndb.Model): num_shards = ndb.IntegerProperty(default=20) @classmethod def all_keys(cls, name): config = cls.get_or_insert(name) ...
@ndb.transactional def _increment(name, num_shards): index = random.randint(0, num_shards - 1) shard_key_string = SHARD_KEY_TEMPLATE.format(name, index) parent_key = ndb.Key('ShardCounterParent', name) counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key) if counter is ...
config = GeneralCounterShardConfig.get_or_insert(name) return _increment(name, config.num_shards)
identifier_body
shardcounter_sync.py
import random from google.appengine.api import memcache from google.appengine.ext import ndb SHARD_KEY_TEMPLATE = 'shard-{}-{:d}' class GeneralCounterShardConfig(ndb.Model): num_shards = ndb.IntegerProperty(default=20) @classmethod def all_keys(cls, name): config = cls.get_or_insert(name) ...
return rval @ndb.transactional def increase_shards(name, num_shards): config = GeneralCounterShardConfig.get_or_insert(name) if config.num_shards < num_shards: config.num_shards = num_shards config.put()
return get_count(name)
conditional_block
shardcounter_sync.py
import random from google.appengine.api import memcache from google.appengine.ext import ndb SHARD_KEY_TEMPLATE = 'shard-{}-{:d}' class GeneralCounterShardConfig(ndb.Model): num_shards = ndb.IntegerProperty(default=20) @classmethod def all_keys(cls, name): config = cls.get_or_insert(name) ...
(name): total = memcache.get(name) if total is None: total = 0 parent_key = ndb.Key('ShardCounterParent', name) shard_query = GeneralCounterShard.query(ancestor=parent_key) shard_counters = shard_query.fetch(limit=None) for counter in shard_counters: if co...
get_count
identifier_name
testrunprogram.py
import unittest import sys import os sys.path.append('bin') from umdinst import wrap class TestRunProgram(unittest.TestCase): def setUp(self): self.tempfilename = 'emptyfile' # This is in createfile.sh self.failIf(os.path.exists(self.tempfilename)) # Find the "touch" program if os.path.exists('...
def testRunWithArgs(self): prog = self.touchprog # Make sure the file doesn't exist self.failIf(os.path.exists(self.tempfilename)) # Create a temporary file args = [self.tempfilename] wrap.run(prog,args) self.failUnless(os.path.exists(self.tempfilename)) def testRunNoArgs(self): # Run a program w...
if os.path.exists(self.tempfilename): os.unlink(self.tempfilename)
identifier_body
testrunprogram.py
import unittest import sys import os sys.path.append('bin') from umdinst import wrap class TestRunProgram(unittest.TestCase): def setUp(self): self.tempfilename = 'emptyfile' # This is in createfile.sh self.failIf(os.path.exists(self.tempfilename)) # Find the "touch" program if os.path.exists('...
self.failIf(status!=0) self.successprog = './success' def tearDown(self): if os.path.exists(self.tempfilename): os.unlink(self.tempfilename) def testRunWithArgs(self): prog = self.touchprog # Make sure the file doesn't exist self.failIf(os.path.exists(self.tempfilename))...
# Build a "succeeding" program, that returns zero status status = os.system("gcc -o success test/testsource/success.c")
random_line_split
testrunprogram.py
import unittest import sys import os sys.path.append('bin') from umdinst import wrap class TestRunProgram(unittest.TestCase): def setUp(self): self.tempfilename = 'emptyfile' # This is in createfile.sh self.failIf(os.path.exists(self.tempfilename)) # Find the "touch" program if os.path.exists('...
# Build a "failing" program, that just returns non-zero status status = os.system("gcc -o fail test/testsource/fail.c") self.failIf(status!=0) self.failprog = './fail' # Build a "succeeding" program, that returns zero status status = os.system("gcc -o success test/tes...
raise ValueError, "Cannot locate the 'touch' program, which is needed for testing"
conditional_block
testrunprogram.py
import unittest import sys import os sys.path.append('bin') from umdinst import wrap class TestRunProgram(unittest.TestCase): def setUp(self): self.tempfilename = 'emptyfile' # This is in createfile.sh self.failIf(os.path.exists(self.tempfilename)) # Find the "touch" program if os.path.exists('...
(self): # Run a program that succeeds s = wrap.run(self.successprog,[self.successprog]) self.failUnless(s) def testRunFailure(self): # Runa program that fails and test for failure s = wrap.run(self.failprog,[self.failprog]) self.failIf(s) if __na...
testRunSuccess
identifier_name
transaction.ts
import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types'; /** Add node transaction to the event */ export class Transaction implements Integration { /** * @inheritDoc */ public name: string = Transaction.id; /** * @inheritDoc */ public static id: string = 'Transaction'; ...
return event; }); } /** * @inheritDoc */ public process(event: Event): Event { const frames = this._getFramesFromEvent(event); // use for loop so we don't have to reverse whole frames array for (let i = frames.length - 1; i >= 0; i--) { const frame = frames[i]; if (fram...
{ return self.process(event); }
conditional_block
transaction.ts
import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types'; /** Add node transaction to the event */ export class Transaction implements Integration { /** * @inheritDoc */ public name: string = Transaction.id; /** * @inheritDoc */ public static id: string = 'Transaction'; ...
(frame: StackFrame): string { return frame.module || frame.function ? `${frame.module || '?'}/${frame.function || '?'}` : '<unknown>'; } }
_getTransaction
identifier_name
transaction.ts
import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types'; /** Add node transaction to the event */ export class Transaction implements Integration { /** * @inheritDoc */ public name: string = Transaction.id; /** * @inheritDoc */ public static id: string = 'Transaction'; ...
} return event; } /** JSDoc */ private _getFramesFromEvent(event: Event): StackFrame[] { const exception = event.exception && event.exception.values && event.exception.values[0]; return (exception && exception.stacktrace && exception.stacktrace.frames) || []; } /** JSDoc */ private _getTr...
if (frame.in_app === true) { event.transaction = this._getTransaction(frame); break; }
random_line_split
transaction.ts
import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types'; /** Add node transaction to the event */ export class Transaction implements Integration { /** * @inheritDoc */ public name: string = Transaction.id; /** * @inheritDoc */ public static id: string = 'Transaction'; ...
/** * @inheritDoc */ public process(event: Event): Event { const frames = this._getFramesFromEvent(event); // use for loop so we don't have to reverse whole frames array for (let i = frames.length - 1; i >= 0; i--) { const frame = frames[i]; if (frame.in_app === true) { eve...
{ addGlobalEventProcessor(event => { const self = getCurrentHub().getIntegration(Transaction); if (self) { return self.process(event); } return event; }); }
identifier_body
views.py
from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from .models import Question, Choice def index(request): latest_question_list = Question.object...
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
random_line_split
views.py
from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from .models import Question, Choice def index(request): latest_question_list = Question.object...
(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) # choice = get_object_or_404(Choice, pk=choice_id) # return r...
detail
identifier_name
views.py
from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from .models import Question, Choice def index(request): latest_question_list = Question.object...
selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
conditional_block
views.py
from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from .models import Question, Choice def index(request): latest_question_list = Question.object...
p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_mes...
identifier_body
factory.py
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def mss(**kwargs): # type: (Any) ->...
if os_ == "windows": from . import windows return windows.MSS(**kwargs) raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
from . import linux return linux.MSS(**kwargs)
conditional_block
factory.py
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def
(**kwargs): # type: (Any) -> MSSBase """ Factory returning a proper MSS class instance. It detects the platform we are running on and chooses the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ # pyli...
mss
identifier_name
factory.py
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def mss(**kwargs): # type: (Any) ->...
return linux.MSS(**kwargs) if os_ == "windows": from . import windows return windows.MSS(**kwargs) raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
""" Factory returning a proper MSS class instance. It detects the platform we are running on and chooses the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ # pylint: disable=import-outside-toplevel os_ ...
identifier_body
factory.py
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def mss(**kwargs): # type: (Any) ->...
return linux.MSS(**kwargs) if os_ == "windows": from . import windows return windows.MSS(**kwargs) raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
if os_ == "linux": from . import linux
random_line_split
hu.js
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image', 'hu', { alertUrl: 'Töltse ki a kép webcímét', alt: 'Buborék szöveg', border: 'Keret', btnUpload: 'Küldés a szerverre', button2Img: 'A ...
vSpace: 'Függ. táv', validateBorder: 'A keret méretének egész számot kell beírni!', validateHSpace: 'Vízszintes távolságnak egész számot kell beírni!', validateVSpace: 'Függőleges távolságnak egész számot kell beírni!' });
upload: 'Feltöltés', urlMissing: 'Hiányzik a kép URL-je',
random_line_split
diagnostic.rs
-bug-report"; pub trait Emitter { fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level); } // a span-handler is like a handler but also // accepts span information for source-location // reporting. pub struct SpanHandler { handler: @Handler, cm:...
} fn highlight_lines(cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: &codemap::FileLines) { let fm = lines.file; let mut err = io::stderr(); let err = &mut err as &mut io::Writer; // arbitrarily only print up to six lines of the error l...
{ match cmsp { Some((cm, sp)) => { let sp = cm.adjust_span(sp); let ss = cm.span_to_str(sp); let lines = cm.span_to_lines(sp); print_diagnostic(ss, lvl, msg); highlight_lines(cm, sp, lvl, lines); print_ma...
identifier_body
diagnostic.rs
-bug-report"; pub trait Emitter { fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level); } // a span-handler is like a handler but also // accepts span information for source-location // reporting. pub struct SpanHandler { handler: @Handler, cm:...
(&self) -> ~str { match *self { Fatal | Error => ~"error", Warning => ~"warning", Note => ~"note" } } } impl Level { fn color(self) -> term::color::Color { match self { Fatal | Error => term::color::BRIGHT_RED, Warning => term:...
to_str
identifier_name
diagnostic.rs
-bug-report"; pub trait Emitter { fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level); } // a span-handler is like a handler but also // accepts span information for source-location // reporting. pub struct SpanHandler { handler: @Handler, cm:...
// arbitrarily only print up to six lines of the error let max_lines = 6u; let mut elided = false; let mut display_lines = lines.lines.as_slice(); if display_lines.len() > max_lines { display_lines = display_lines.slice(0u, max_lines); elided = true; } // Print the offending...
lines: &codemap::FileLines) { let fm = lines.file; let mut err = io::stderr(); let err = &mut err as &mut io::Writer;
random_line_split
plshadow.rs
use winapi::*; use create_device; use dxsafe::*; use dxsafe::structwrappers::*; use dxsems::VertexFormat; use std::marker::PhantomData; // Point Light Shadow // The name isn't quite correct. This module just fills depth cubemap. pub struct PLShadow<T: VertexFormat> { pub pso: D3D12PipelineState, pub root_sig: ...
Ok(_) => {}, }; trace!("Done"); trace!("Root signature creation"); let root_sig = try!(dev.create_root_signature(0, &rsig_bc[..])); try!(root_sig.set_name("plshadow RSD")); let input_elts_desc = T::generate(0); // pso_desc contains pointers to local...
], D3DCOMPILE_OPTIMIZATION_LEVEL3) { Err(err) => { error!("Error compiling 'plshadow.hlsl': {}", err); return Err(E_FAIL); },
random_line_split
plshadow.rs
use winapi::*; use create_device; use dxsafe::*; use dxsafe::structwrappers::*; use dxsems::VertexFormat; use std::marker::PhantomData; // Point Light Shadow // The name isn't quite correct. This module just fills depth cubemap. pub struct PLShadow<T: VertexFormat> { pub pso: D3D12PipelineState, pub root_sig: ...
(dev: &D3D12Device) -> HResult<PLShadow<T>> { let mut vshader_bc = vec![]; let mut gshader_bc = vec![]; let mut pshader_bc = vec![]; let mut rsig_bc = vec![]; trace!("Compiling 'plshadow.hlsl'..."); match create_device::compile_shaders("plshadow.hlsl",&mut[ ...
new
identifier_name
plshadow.rs
use winapi::*; use create_device; use dxsafe::*; use dxsafe::structwrappers::*; use dxsems::VertexFormat; use std::marker::PhantomData; // Point Light Shadow // The name isn't quite correct. This module just fills depth cubemap. pub struct PLShadow<T: VertexFormat> { pub pso: D3D12PipelineState, pub root_sig: ...
trace!("Root signature creation"); let root_sig = try!(dev.create_root_signature(0, &rsig_bc[..])); try!(root_sig.set_name("plshadow RSD")); let input_elts_desc = T::generate(0); // pso_desc contains pointers to local data, so I mustn't pass it around, but I can. Unsafe. ...
{ let mut vshader_bc = vec![]; let mut gshader_bc = vec![]; let mut pshader_bc = vec![]; let mut rsig_bc = vec![]; trace!("Compiling 'plshadow.hlsl'..."); match create_device::compile_shaders("plshadow.hlsl",&mut[ ("VSMain", "vs_5_0", &mut vshader_bc),...
identifier_body
lib.rs
pub mod nodes; pub mod parser; pub mod tokenizer; mod tests; use tokenizer::*; use parser::*; use nodes::*; pub struct Document { root: Element, } impl Document { pub fn new() -> Document { Document { root: Element::new("root"), } } pub fn from_element(e: Element) -> Doc...
(&self) -> &Element { match self.root.get_first_child() { Some(c) => c, None => panic!("Document has no root element!"), } } pub fn print(&self) { self.root.print(0); } }
get_root
identifier_name
lib.rs
pub mod nodes; pub mod parser; pub mod tokenizer;
mod tests; use tokenizer::*; use parser::*; use nodes::*; pub struct Document { root: Element, } impl Document { pub fn new() -> Document { Document { root: Element::new("root"), } } pub fn from_element(e: Element) -> Document { Document { root: e, ...
random_line_split
lib.rs
pub mod nodes; pub mod parser; pub mod tokenizer; mod tests; use tokenizer::*; use parser::*; use nodes::*; pub struct Document { root: Element, } impl Document { pub fn new() -> Document { Document { root: Element::new("root"), } } pub fn from_element(e: Element) -> Doc...
pub fn from_string(s: &str) -> Result<Document, String> { let tokens = match tokenize(&s) { Ok(tokens) => tokens, Err(e) => return Err(e), }; let element = match parse(tokens) { Ok(element) => element, Err(e) => return Err(e), }; ...
{ Document { root: e, } }
identifier_body
file.rs
//! Provides File Management functions use std::ffi; use std::os::windows::ffi::{ OsStrExt, OsStringExt }; use std::default; use std::ptr; use std::mem; use std::convert; use std::io; use crate::inner_raw as raw; use self::raw::winapi::*; use crate::utils; const NO_MORE_FILES: i32 = ERROR_NO_MORE_FILES as i3...
///Returns whether Entry is read-only pub fn is_read_only(&self) -> bool { (self.0.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0 } ///Returns name of Entry. pub fn name(&self) -> ffi::OsString { ffi::OsString::from_wide(match self.0.cFileName.iter().position(|c| *c == 0) { ...
{ ((self.0.nFileSizeHigh as u64) << 32) | (self.0.nFileSizeLow as u64) }
identifier_body
file.rs
//! Provides File Management functions use std::ffi; use std::os::windows::ffi::{ OsStrExt, OsStringExt }; use std::default; use std::ptr; use std::mem; use std::convert; use std::io; use crate::inner_raw as raw; use self::raw::winapi::*; use crate::utils; const NO_MORE_FILES: i32 = ERROR_NO_MORE_FILES as i3...
(&self) -> u64 { ((self.0.nFileSizeHigh as u64) << 32) | (self.0.nFileSizeLow as u64) } ///Returns whether Entry is read-only pub fn is_read_only(&self) -> bool { (self.0.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0 } ///Returns name of Entry. pub fn name(&self) -> ffi::OsS...
size
identifier_name
file.rs
//! Provides File Management functions use std::ffi; use std::os::windows::ffi::{ OsStrExt, OsStringExt }; use std::default; use std::ptr; use std::mem; use std::convert; use std::io; use crate::inner_raw as raw; use self::raw::winapi::*; use crate::utils; const NO_MORE_FILES: i32 = ERROR_NO_MORE_FILES as i3...
!self.is_dir() } ///Returns size of entry pub fn size(&self) -> u64 { ((self.0.nFileSizeHigh as u64) << 32) | (self.0.nFileSizeLow as u64) } ///Returns whether Entry is read-only pub fn is_read_only(&self) -> bool { (self.0.dwFileAttributes & FILE_ATTRIBUTE_READONLY) !=...
random_line_split
mut_dns_packet.rs
use buf::*; #[derive(Debug)] pub struct MutDnsPacket<'a> { buf: &'a mut [u8], pos: usize, } impl<'a> MutDnsPacket<'a> { pub fn new(buf: &mut [u8]) -> MutDnsPacket { MutDnsPacket::new_at(buf, 0) } pub fn new_at(buf: &mut [u8], pos: usize) -> MutDnsPacket { debug!("New MutDn...
#[test] fn write_u16_bounds() { let mut vec = vec![0, 0, 0, 0]; let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); assert_eq!(true, packet.write_u16(1)); assert_eq!(true, packet.write_u16(1)); assert_eq!(false, packet.write_u16(1)); //no ...
{ let mut vec = test_buf(); let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); packet.write_u16(2161); packet.write_u16(1); packet.seek(0); println!("{:?}", packet); assert_eq!(2161, packet.next_u16().unwrap()); assert_eq!(1...
identifier_body
mut_dns_packet.rs
use buf::*; #[derive(Debug)] pub struct MutDnsPacket<'a> { buf: &'a mut [u8], pos: usize, } impl<'a> MutDnsPacket<'a> { pub fn new(buf: &mut [u8]) -> MutDnsPacket { MutDnsPacket::new_at(buf, 0) } pub fn new_at(buf: &mut [u8], pos: usize) -> MutDnsPacket { debug!("New MutDn...
#[test] fn write_u16() { let mut vec = test_buf(); let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); packet.write_u16(2161); packet.write_u16(1); packet.seek(0); println!("{:?}", packet); assert_eq!(2161, packet.next_u16()...
assert_eq!(8, packet.next_u8().unwrap()); assert_eq!(9, packet.next_u8().unwrap()); }
random_line_split
mut_dns_packet.rs
use buf::*; #[derive(Debug)] pub struct MutDnsPacket<'a> { buf: &'a mut [u8], pos: usize, } impl<'a> MutDnsPacket<'a> { pub fn new(buf: &mut [u8]) -> MutDnsPacket { MutDnsPacket::new_at(buf, 0) } pub fn new_at(buf: &mut [u8], pos: usize) -> MutDnsPacket { debug!("New MutDn...
(&mut self) -> &mut [u8] { self.buf } } impl<'a> BufRead for MutDnsPacket<'a> { fn buf(&self) -> &[u8] { self.buf } } impl<'a> DirectAccessBuf for MutDnsPacket<'a> { fn pos(&self) -> usize { self.pos } fn set_pos(&mut self, pos: usize) { self.pos = pos; } ...
buf
identifier_name