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
Button.js
/** * @file san-mui/Button * @author leon <ludafa@outlook.com> */ import {create} from '../common/util/cx'; import {TouchRipple} from '../Ripple'; import BaseButton from './Base'; import {DataTypes} from 'san'; const cx = create('button'); export default class Button extends BaseButton { static components = ...
} }
{ this.fire('click', e); }
conditional_block
Button.js
/** * @file san-mui/Button * @author leon <ludafa@outlook.com> */
import BaseButton from './Base'; import {DataTypes} from 'san'; const cx = create('button'); export default class Button extends BaseButton { static components = { 'san-touch-ripple': TouchRipple }; static template = ` <button on-click="click($event)" type="{{type...
import {create} from '../common/util/cx'; import {TouchRipple} from '../Ripple';
random_line_split
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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 *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // TypeScript Version: 2.0 /** * Interface describing `sfloor`. */ interface Routine { /** * Rounds each element in a single-precision ...
* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; /// An entity tag /// /// An Etag consists of a string enclosed by two literal double quotes. /// Preceding the first double quote is an optional weakness indicator, /// which always looks like this: W/ /// See also: https://tools.ietf.org/html/rfc7232#section-2.3 ...
// The etag is weak if its first char is not a DQUOTE. if slice.char_at(0) == '"' /* '"' */ { // No need to check if the last char is a DQUOTE, // we already did that above. if check_slice_validity(slice.slice_chars(1, length-1)) { return Ok(EntityTa...
{ return Err(()); }
conditional_block
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; /// An entity tag /// /// An Etag consists of a string enclosed by two literal double quotes. /// Preceding the first double quote is an optional weakness indicator, /// which always looks like this: W/ /// See also: https://tools.ietf.org/html/rfc7232#section-2.3 ...
() { // Expected successes let mut etag : EntityTag = "\"foobar\"".parse().unwrap(); assert_eq!(etag, (EntityTag { weak: false, tag: "foobar".to_string() })); etag = "\"\"".parse().unwrap(); assert_eq!(etag, EntityTag { weak: false, ...
test_etag_successes
identifier_name
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; /// An entity tag /// /// An Etag consists of a string enclosed by two literal double quotes. /// Preceding the first double quote is an optional weakness indicator, /// which always looks like this: W/ /// See also: https://tools.ietf.org/html/rfc7232#section-2.3 ...
impl FromStr for EntityTag { type Err = (); fn from_str(s: &str) -> Result<EntityTag, ()> { let length: usize = s.len(); let slice = &s[]; // Early exits: // 1. The string is empty, or, // 2. it doesn't terminate in a DQUOTE. if slice.is_empty() || !slice.ends_...
{ for c in slice.bytes() { match c { b'\x21' | b'\x23' ... b'\x7e' | b'\x80' ... b'\xff' => (), _ => { return false; } } } true }
identifier_body
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; /// An entity tag /// /// An Etag consists of a string enclosed by two literal double quotes. /// Preceding the first double quote is an optional weakness indicator, /// which always looks like this: W/ /// See also: https://tools.ietf.org/html/rfc7232#section-2.3 ...
return Ok(EntityTag { weak: false, tag: slice.slice_chars(1, length-1).to_string() }); } else { return Err(()); } } if slice.slice_chars(0, 3) == "W/\"" { if check_slice_validity(...
// The etag is weak if its first char is not a DQUOTE. if slice.char_at(0) == '"' /* '"' */ { // No need to check if the last char is a DQUOTE, // we already did that above. if check_slice_validity(slice.slice_chars(1, length-1)) {
random_line_split
specHelper.ts
import * as uuid from "uuid"; import { Worker } from "node-resque"; import { api, config, task, Task, Action, Connection } from "./../index"; import { WebServer } from "../servers/web"; import { AsyncReturnType } from "type-fest"; import { TaskInputs } from "../classes/task"; export type SpecHelperConnection = Connect...
(file: string): Promise<any> { const connection = await specHelper.buildConnection(); connection.params.file = file; const response = await new Promise((resolve) => { api.servers.servers.testServer.processFile(connection); connection.actionCallbacks[connection.messageId] = resolve; }); ...
getStaticFile
identifier_name
specHelper.ts
import * as uuid from "uuid"; import { Worker } from "node-resque"; import { api, config, task, Task, Action, Connection } from "./../index"; import { WebServer } from "../servers/web"; import { AsyncReturnType } from "type-fest"; import { TaskInputs } from "../classes/task"; export type SpecHelperConnection = Connect...
*/ export async function findEnqueuedTasks(taskName: string) { let found: TaskInputs[] = []; // normal queues const queues = await api.resque.queue.queues(); for (const i in queues) { const q = queues[i]; const length = await api.resque.queue.length(q); const batchFound = await t...
* Use the specHelper to find enqueued instances of a task * This will return an array of instances of the task which have been enqueued either in the normal queues or delayed queues * If a task is enqueued in a delayed queue, it will have a 'timestamp' property * i.e. [ { class: 'regularTask', queue: 'testQ...
random_line_split
specHelper.ts
import * as uuid from "uuid"; import { Worker } from "node-resque"; import { api, config, task, Task, Action, Connection } from "./../index"; import { WebServer } from "../servers/web"; import { AsyncReturnType } from "type-fest"; import { TaskInputs } from "../classes/task"; export type SpecHelperConnection = Connect...
else { connection = await specHelper.buildConnection(); connection.params = input; } connection.params.action = actionName; connection.messageId = connection.params.messageId || uuid.v4(); const response: (A extends Action ? AsyncReturnType<A["run"]> : { [key: string]: any }) ...
{ connection = input as SpecHelperConnection; }
conditional_block
specHelper.ts
import * as uuid from "uuid"; import { Worker } from "node-resque"; import { api, config, task, Task, Action, Connection } from "./../index"; import { WebServer } from "../servers/web"; import { AsyncReturnType } from "type-fest"; import { TaskInputs } from "../classes/task"; export type SpecHelperConnection = Connect...
}
{ const queues = await api.resque.queue.queues(); for (const i in queues) { const q = queues[i]; await api.resque.queue.del(q, taskName, [params]); await api.resque.queue.delDelayed(q, taskName, [params]); } }
identifier_body
youtube.server-tests.js
YUI.add('youtube-model-yql-tests', function (Y, NAME) { var suite = new YUITest.TestSuite(NAME), model = null, A = YUITest.Assert; suite.add(new YUITest.TestCase({ name: "youtube-model-yql user tests", setUp: function () { model = Y.mojito.models["youtube-model-yql...
/** model.getData({},function (data) { called = true; //A.isTrue(!err); //A.isObject(data); //A.areSame('data', data.some); }); A.isTrue(called); **/ } })); YUITest.TestRunner.add...
random_line_split
dst-index.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a>(&'a self, _: &uint) -> &'a str { "hello" } } struct T; impl Index<uint, Show + 'static> for T { fn index<'a>(&'a self, idx: &uint) -> &'a (Show + 'static) { static x: uint = 42; &x } } fn main() { S[0]; //~^ ERROR E0161 T[0]; //~^ ERROR cannot move out of dere...
index
identifier_name
dst-index.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
struct S; impl Index<uint, str> for S { fn index<'a>(&'a self, _: &uint) -> &'a str { "hello" } } struct T; impl Index<uint, Show + 'static> for T { fn index<'a>(&'a self, idx: &uint) -> &'a (Show + 'static) { static x: uint = 42; &x } } fn main() { S[0]; //~^ ERROR ...
use std::ops::Index; use std::fmt::Show;
random_line_split
player_unit.rs
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // 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 wi...
<S: Read>(stream: &mut S) -> Result<PlayerUnit> { let mut data: PlayerUnit = Default::default(); data.position_x = try!(stream.read_f32()); data.position_y = try!(stream.read_f32()); data.position_z = try!(stream.read_f32()); data.spawn_id = optional_id!(try!(stream.read_i32()));...
read_from_stream
identifier_name
player_unit.rs
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // 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 wi...
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SO...
// copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
random_line_split
trait-with-bounds-default.rs
// Copyright 2013 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 ...
() { assert_eq!(3.do_get2(), (3, 3)); assert_eq!(Some("hi".to_string()).do_get2(), ("hi".to_string(), "hi".to_string())); }
main
identifier_name
trait-with-bounds-default.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn main() { assert_eq!(3.do_get2(), (3, 3)); assert_eq!(Some("hi".to_string()).do_get2(), ("hi".to_string(), "hi".to_string())); }
{ self.as_ref().unwrap().clone() }
identifier_body
trait-with-bounds-default.rs
// Copyright 2013 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 do_get(&self) -> T; fn do_get2(&self) -> (T, T) { let x = self.do_get(); (x.clone(), x.clone()) } } impl Getter<isize> for isize { fn do_get(&self) -> isize { *self } } impl<T: Clone> Getter<T> for Option<T> { fn do_get(&self) -> T { self.as_ref().unwrap().clone() } } pub fn...
trait Getter<T: Clone> {
random_line_split
views.py
from django.shortcuts import render from rest_framework import viewsets from basin.models import Task from basin.serializers import TaskSerializer def index(request): context = {} return render(request, 'index.html', context) def display(request): state = 'active' if request.method == 'POST': ...
(viewsets.ModelViewSet): queryset = Task.objects.sleeping() serializer_class = TaskSerializer class BlockedViewSet(viewsets.ModelViewSet): queryset = Task.objects.blocked() serializer_class = TaskSerializer class DelegatedViewSet(viewsets.ModelViewSet): queryset = Task.objects.delegated() seri...
SleepingViewSet
identifier_name
views.py
from django.shortcuts import render from rest_framework import viewsets from basin.models import Task from basin.serializers import TaskSerializer def index(request): context = {} return render(request, 'index.html', context) def display(request): state = 'active' if request.method == 'POST': ...
model = Task serializer_class = TaskSerializer def get_queryset(self): if 'state' in self.request.QUERY_PARAMS: state = self.request.QUERY_PARAMS['state'] return Task.objects.state(state) return Task.objects.all()
identifier_body
views.py
from django.shortcuts import render from rest_framework import viewsets from basin.models import Task from basin.serializers import TaskSerializer def index(request): context = {} return render(request, 'index.html', context) def display(request): state = 'active' if request.method == 'POST': ...
context = { 'task_list': Task.objects.state(state), 'state': state, } return render(request, 'display.html', context) class ActiveViewSet(viewsets.ModelViewSet): queryset = Task.objects.active() serializer_class = TaskSerializer class SleepingViewSet(viewsets.ModelViewSet): qu...
state = request.GET['state']
conditional_block
views.py
from django.shortcuts import render from rest_framework import viewsets from basin.models import Task from basin.serializers import TaskSerializer def index(request): context = {} return render(request, 'index.html', context) def display(request): state = 'active' if request.method == 'POST': ...
elif request.method == 'GET': if 'state' in request.GET: state = request.GET['state'] context = { 'task_list': Task.objects.state(state), 'state': state, } return render(request, 'display.html', context) class ActiveViewSet(viewsets.ModelViewSet): queryset = Task...
if submit == 'check': task = Task.objects.get(id=tid) task.completed = not task.completed task.save()
random_line_split
app.js
/** * Module dependencies. */ var express = require('express'); var http = require('http'); var path = require('path'); var handlebars = require('express3-handlebars') var index = require('./routes/index'); // Example route // var user = require('./routes/user'); // below added by tommy var login = require('./rou...
// Add routes here app.get('/', index.view); // Example route // app.get('/users', user.list); //below added by tommy app.get('/login', login.view); app.get('/messages', messages.view); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }...
{ app.use(express.errorHandler()); }
conditional_block
app.js
/** * Module dependencies. */ var express = require('express'); var http = require('http'); var path = require('path'); var handlebars = require('express3-handlebars') var index = require('./routes/index'); // Example route // var user = require('./routes/user');
var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.engine('handlebars', handlebars()); app.set('view engine', 'handlebars'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlenc...
// below added by tommy var login = require('./routes/login'); var messages = require('./routes/messages');
random_line_split
ifdef.py
#! /usr/bin/env python # Selectively preprocess #ifdef / #ifndef statements. # Usage: # ifdef [-Dname] ... [-Uname] ... [file] ... # # This scans the file(s), looking for #ifdef and #ifndef preprocessor # commands that test for one of the names mentioned in the -D and -U # options. On standard output it write...
elif keyword == 'endif' and stack: s_ok, s_ko, s_word = stack[-1] if s_ko < 0: if ok: fpo.write(line) del stack[-1] ok = s_ok else: sys.stderr.write('Unknown keyword %s\n' % keyword) if stack: sys.stderr.w...
s_ok, s_ko, s_word = stack[-1] if s_ko < 0: if ok: fpo.write(line) else: s_ko = not s_ko ok = s_ok if not s_ko: ok = 0 stack[-1] = s_ok, s_ko, s_word
conditional_block
ifdef.py
#! /usr/bin/env python # Selectively preprocess #ifdef / #ifndef statements. # Usage: # ifdef [-Dname] ... [-Uname] ... [file] ... # # This scans the file(s), looking for #ifdef and #ifndef preprocessor # commands that test for one of the names mentioned in the -D and -U # options. On standard output it write...
if __name__ == '__main__': main()
keywords = ('if', 'ifdef', 'ifndef', 'else', 'endif') ok = 1 stack = [] while 1: line = fpi.readline() if not line: break while line[-2:] == '\\\n': nextline = fpi.readline() if not nextline: break line = line + nextline tmp = lin...
identifier_body
ifdef.py
#! /usr/bin/env python # Selectively preprocess #ifdef / #ifndef statements. # Usage: # ifdef [-Dname] ... [-Uname] ... [file] ... # # This scans the file(s), looking for #ifdef and #ifndef preprocessor # commands that test for one of the names mentioned in the -D and -U # options. On standard output it write...
(): opts, args = getopt.getopt(sys.argv[1:], 'D:U:') for o, a in opts: if o == '-D': defs.append(a) if o == '-U': undefs.append(a) if not args: args = ['-'] for filename in args: if filename == '-': process(sys.stdin, sys.std...
main
identifier_name
ifdef.py
#! /usr/bin/env python # Selectively preprocess #ifdef / #ifndef statements. # Usage: # ifdef [-Dname] ... [-Uname] ... [file] ... # # This scans the file(s), looking for #ifdef and #ifndef preprocessor # commands that test for one of the names mentioned in the -D and -U # options. On standard output it write...
words = tmp.split() keyword = words[0] if keyword not in keywords: if ok: fpo.write(line) continue if keyword in ('ifdef', 'ifndef') and len(words) == 2: if keyword == 'ifdef': ko = 1 else: ko = 0 ...
random_line_split
urls.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from PenBlog.admin import article,category,link,other __author__ = 'lihaoquan' from django.conf.urls import patterns, include, url urlpatterns = patterns('', # 文章 url(r'^$', article.show_articles), url(r'^new-article/$', article.new), url(r'^edit-article...
url(r'^show-categories/$', category.show_all), url(r'^new-category/$', category.new), url(r'^edit-category/([0-9a-f]+)/$', category.edit), url(r'^delete-category/([0-9a-f]+)/$', category.delete), # 连接 url( r'^show-links/$', link.show_all), url( r'^new-link/$', link.new), url( r'^edit-li...
url(r'^show-hidden-article/(\d+)/$', article.show_hidden_article), # 分类
random_line_split
appdirs.py
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2021 Philipp Wolfer # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the Licen...
def plugin_folder(): # FIXME: This really should be in QStandardPaths.AppDataLocation instead, # but this is a breaking change that requires data migration return os.path.normpath(os.environ.get('PICARD_PLUGIN_DIR', os.path.join(config_folder(), 'plugins')))
return os.path.normpath(os.environ.get('PICARD_CACHE_DIR', QStandardPaths.writableLocation(QStandardPaths.CacheLocation)))
identifier_body
appdirs.py
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2021 Philipp Wolfer # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the Licen...
QCoreApplication.setOrganizationName(PICARD_ORG_NAME) def config_folder(): return os.path.normpath(os.environ.get('PICARD_CONFIG_DIR', QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation))) def cache_folder(): return os.path.normpath(os.environ.get('PICARD_CACHE_DIR', QStandardPaths.writableLoc...
) # Ensure the application is properly configured for the paths to work QCoreApplication.setApplicationName(PICARD_APP_NAME)
random_line_split
appdirs.py
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2021 Philipp Wolfer # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the Licen...
(): return os.path.normpath(os.environ.get('PICARD_CONFIG_DIR', QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation))) def cache_folder(): return os.path.normpath(os.environ.get('PICARD_CACHE_DIR', QStandardPaths.writableLocation(QStandardPaths.CacheLocation))) def plugin_folder(): # FIXME:...
config_folder
identifier_name
position.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
/** * A function that compares positions, useful for sorting */ public static compare(a: IPosition, b: IPosition): number { const aLineNumber = a.lineNumber | 0; const bLineNumber = b.lineNumber | 0; if (aLineNumber === bLineNumber) { const aColumn = a.column | 0; const bColumn = b.column | 0; ret...
return false; } return a.column <= b.column; }
random_line_split
position.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
/** * Convert to a human-readable representation. */ public toString(): string { return '(' + this.lineNumber + ',' + this.column + ')'; } // --- /** * Create a `Position` from an `IPosition`. */ public static lift(pos: IPosition): Position { return new Position(pos.lineNumber, pos.column); } /...
{ return new Position(this.lineNumber, this.column); }
identifier_body
position.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(other: IPosition): boolean { return Position.isBeforeOrEqual(this, other); } /** * Test if position `a` is before position `b`. * If the two positions are equal, the result will be true. */ public static isBeforeOrEqual(a: IPosition, b: IPosition): boolean { if (a.lineNumber < b.lineNumber) { return t...
isBeforeOrEqual
identifier_name
position.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
if (b.lineNumber < a.lineNumber) { return false; } return a.column <= b.column; } /** * A function that compares positions, useful for sorting */ public static compare(a: IPosition, b: IPosition): number { const aLineNumber = a.lineNumber | 0; const bLineNumber = b.lineNumber | 0; if (aLineNumb...
{ return true; }
conditional_block
mod.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[test] fn test_int_from_str_overflow() { let mut i8_val: i8 = 127; assert_eq!("127".parse::<i8>().ok(), Some(i8_val)); assert_eq!("128".parse::<i8>().ok(), None); i8_val = i8_val.wrapping_add(1); assert_eq!("-128".parse::<i8>().ok(), Some(i8_val)); assert_eq!(...
{ let x1 : Option<f64> = f64::from_str_radix("-123.456", 10).ok(); assert_eq!(x1, Some(-123.456)); let x2 : Option<f32> = f32::from_str_radix("123.456", 10).ok(); assert_eq!(x2, Some(123.456)); let x3 : Option<f32> = f32::from_str_radix("-0.0", 10).ok(); assert_eq!(x3, So...
identifier_body
mod.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>(ten: T, two: T) where T: PartialEq + Add<Output=T> + Sub<Output=T> + Mul<Output=T> + Div<Output=T> + Rem<Output=T> + Debug + Copy { assert_eq!(ten.add(two), ten + two); assert_eq!(ten.sub(two), ten - two); assert_eq!(ten.mul(two), ten * two); assert_eq!(ten.div(two), ten ...
test_num
identifier_name
mod.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[test] fn test_int_from_str_overflow() { let mut i8_val: i8 = 127; assert_eq!("127".parse::<i8>().ok(), Some(i8_val)); assert_eq!("128".parse::<i8>().ok(), None); i8_val = i8_val.wrapping_add(1); assert_eq!("-128".parse::<i8>().ok(), Some(i8_val)); assert_eq!("-...
assert_eq!(x4, Some(1.0)); let x5 : Option<f32> = f32::from_str_radix("-1.0", 10).ok(); assert_eq!(x5, Some(-1.0)); }
random_line_split
issue-34798.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub struct ZeroSizeWithPhantomData<T>(::std::marker::PhantomData<T>); #[repr(C)] pub struct Bar { size: u8, baz: ZeroSizeWithPhantomData<i32>, } extern "C" { pub fn bar(_: *mut Foo, _: *mut Bar); } fn main() { }
#[repr(C)]
random_line_split
issue-34798.rs
// Copyright 2017 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 ...
{ size: u8, baz: ZeroSizeWithPhantomData<i32>, } extern "C" { pub fn bar(_: *mut Foo, _: *mut Bar); } fn main() { }
Bar
identifier_name
vec-res-add.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 ...
impl Drop for r { fn drop(&mut self) {} } fn main() { // This can't make sense as it would copy the classes let i = vec!(r(0)); let j = vec!(r(1)); let k = i + j; //~^ ERROR binary operation `+` cannot be applied to type println!("{}", j); }
fn r(i:int) -> r { r { i: i } }
random_line_split
vec-res-add.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 ...
(&mut self) {} } fn main() { // This can't make sense as it would copy the classes let i = vec!(r(0)); let j = vec!(r(1)); let k = i + j; //~^ ERROR binary operation `+` cannot be applied to type println!("{}", j); }
drop
identifier_name
vec-res-add.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 ...
impl Drop for r { fn drop(&mut self) {} } fn main() { // This can't make sense as it would copy the classes let i = vec!(r(0)); let j = vec!(r(1)); let k = i + j; //~^ ERROR binary operation `+` cannot be applied to type println!("{}", j); }
{ r { i: i } }
identifier_body
process.py
from .logging import debug, exception_log from .typing import Any, List, Dict, Callable, Optional, IO import os import shutil import subprocess import threading def add_extension_if_missing(server_binary_args: List[str]) -> List[str]: if len(server_binary_args) > 0: executable_arg = server_binary_args[0] ...
def attach_logger(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None: threading.Thread(target=log_stream, args=(process, stream, log_callback)).start() def log_stream(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None: """ Read...
si = None if os.name == "nt": server_binary_args = add_extension_if_missing(server_binary_args) si = subprocess.STARTUPINFO() # type: ignore si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW # type: ignore debug("starting " + str(server_binary_args)) stderr_desti...
identifier_body
process.py
from .logging import debug, exception_log from .typing import Any, List, Dict, Callable, Optional, IO import os import shutil import subprocess import threading def add_extension_if_missing(server_binary_args: List[str]) -> List[str]: if len(server_binary_args) > 0: executable_arg = server_binary_args[0] ...
log_callback(content.decode('UTF-8', 'replace').strip()) except IOError as err: exception_log("Failure reading stream", err) return debug("LSP stream logger stopped.")
break
conditional_block
process.py
from .logging import debug, exception_log from .typing import Any, List, Dict, Callable, Optional, IO import os import shutil import subprocess import threading def add_extension_if_missing(server_binary_args: List[str]) -> List[str]: if len(server_binary_args) > 0: executable_arg = server_binary_args[0] ...
def log_stream(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None: """ Read lines from a stream and invoke the log_callback on the result """ running = True while running: running = process.poll() is None try: content = stream.readli...
random_line_split
process.py
from .logging import debug, exception_log from .typing import Any, List, Dict, Callable, Optional, IO import os import shutil import subprocess import threading def add_extension_if_missing(server_binary_args: List[str]) -> List[str]: if len(server_binary_args) > 0: executable_arg = server_binary_args[0] ...
(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None: threading.Thread(target=log_stream, args=(process, stream, log_callback)).start() def log_stream(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None: """ Read lines from a stream...
attach_logger
identifier_name
FeedContent.d.ts
import * as React from 'react'; import { SemanticShorthandContent, SemanticShorthandItem } from '../..'; import { FeedDateProps } from './FeedDate'; import { FeedExtraProps } from './FeedExtra'; import { FeedMetaProps } from './FeedMeta'; import { FeedSummaryProps } from './FeedSummary'; export interface FeedContentP...
declare const FeedContent: React.StatelessComponent<FeedContentProps>; export default FeedContent;
random_line_split
uconf.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
self.column = 1 + len(skip_lines[-1]) else: self.column += len(skip_lines[0]) pos = m.end() continue for cls, type, regex in self.token_map: m = regex.match(string, pos=pos) if m: ...
skip_lines = m.group(0).split('\n') if len(skip_lines) > 1: self.row += len(skip_lines) - 1
random_line_split
uconf.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
(self, filename): self.filename = filename self.row = 1 self.column = 1 def tokenize(self, string): '''Yield tokens from the input string or throw ConfigParseError''' pos = 0 while pos < len(string): m = SKIP_RE.match(string, pos=pos) if m: ...
__init__
identifier_name
uconf.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
def load(f, filename=None, includedir=''): '''Load the contents of ``f`` (a file-like object) to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> with open('test/example.cfg') as f: ... config = libconf.l...
if not self.tokens.accept(start): return None result = nonterminal() self.tokens.expect(end) return result
identifier_body
uconf.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
tokens.extend(tokenizer.tokenize(''.join(lines))) return cls(tokens) def peek(self): '''Return (but do not consume) the next token At the end of input, ``None`` is returned. ''' if self.position >= len(self.tokens): return None return self.to...
lines.append(line)
conditional_block
utils.js
"use strict"; var assert = require('assert')
describe('Autocompleter widget', function () { var Autocompleter = require('../utils/autocomplete_widget') describe('instance', function () { var testAutocompleter = new Autocompleter(null, 'egp', 'topics'); it('should query the correct url', function () { assert.equal(testAutocompleter.url, '/api/p...
, _ = require('underscore')
random_line_split
generic_path.rs
use std::io::Write; use std::ops::Deref; use syn::ext::IdentExt; use crate::bindgen::config::{Config, Language}; use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver}; use crate::bindgen::ir::{Path, Type}; use crate::bindgen::utilities::IterHelpers; use crate::bindgen::writer::{Sourc...
(&self) -> &[Path] { &self.0 } } impl Source for GenericParams { fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) { self.write_internal(config, out, false); } } #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct GenericPath { path: Path, e...
deref
identifier_name
generic_path.rs
use std::io::Write; use std::ops::Deref; use syn::ext::IdentExt; use crate::bindgen::config::{Config, Language}; use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver}; use crate::bindgen::ir::{Path, Type}; use crate::bindgen::utilities::IterHelpers; use crate::bindgen::writer::{Sourc...
pub fn name(&self) -> &str { self.path.name() } pub fn export_name(&self) -> &str { &self.export_name } pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) { for generic in &mut self.generics { generic.rename_for_config(config,...
{ self.ctype.as_ref() }
identifier_body
generic_path.rs
use std::io::Write; use std::ops::Deref; use syn::ext::IdentExt; use crate::bindgen::config::{Config, Language}; use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver}; use crate::bindgen::ir::{Path, Type}; use crate::bindgen::utilities::IterHelpers; use crate::bindgen::writer::{Sourc...
} impl Deref for GenericParams { type Target = [Path]; fn deref(&self) -> &[Path] { &self.0 } } impl Source for GenericParams { fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) { self.write_internal(config, out, false); } } #[derive(Debug, Clone, PartialEq, E...
pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) { self.write_internal(config, out, true); }
random_line_split
generic_path.rs
use std::io::Write; use std::ops::Deref; use syn::ext::IdentExt; use crate::bindgen::config::{Config, Language}; use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver}; use crate::bindgen::ir::{Path, Type}; use crate::bindgen::utilities::IterHelpers; use crate::bindgen::writer::{Sourc...
write!(out, "typename {}", item); if with_default { write!(out, " = void"); } } out.write(">"); out.new_line(); } } pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter...
{ out.write(", "); }
conditional_block
getClientErrorObject_spec.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
return getClientErrorObject(new Response(jsonErrorString)).then( errorObj => { expect(errorObj.error).toEqual(jsonError.errors[0].message); expect(errorObj.link).toEqual(jsonError.errors[0].extra.link); }, ); }); it('Handles Response that can be parsed as text', () => { cons...
}, ], }; const jsonErrorString = JSON.stringify(jsonError);
random_line_split
class_ClientMessage.py
# _*_ coding:utf-8 _*_ # Filename:ClientUI.py # Python在线聊天客户端 from socket import * from ftplib import FTP import ftplib import socket import thread import time import sys import codecs import os reload(sys) sys.setdefaultencoding( "utf-8" ) class ClientMessage(): #设置用户名密码 def setUsrANDPwd(self,usr,pwd): ...
dpCliSock.sendto('2##'+self.usr+'##'+self.toUsr+'##'+message,self.ADDR); #清空用户在Text中输入的消息 self.inputText.delete(0.0,message.__len__()-1.0) #传文件 def sendFile(self): filename = self.inputText.get('1.0',Tkinter.END) theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ...
conditional_block
class_ClientMessage.py
# _*_ coding:utf-8 _*_ # Filename:ClientUI.py # Python在线聊天客户端 from socket import * from ftplib import FTP import ftplib import socket import thread import time import sys import codecs import os reload(sys) sys.setdefaultencoding( "utf-8" ) class ClientMessage(): #设置用户名密码 def setUsrANDPwd(self,usr,pwd): ...
return True elif s[0]== 'N': #self.chatText.insert(Tkinter.END,'客户端与服务器端建立连接失败......') return False elif s[0]=='CLOSE': i=5 while i>0: self.chatText.insert(Tkinter.END,'你的账号在另一端登录,该客户端'+str(i)+'秒后...
random_line_split
class_ClientMessage.py
# _*_ coding:utf-8 _*_ # Filename:ClientUI.py # Python在线聊天客户端 from socket import * from ftplib import FTP import ftplib import socket import thread import time import sys import codecs import os reload(sys) sys.setdefaultencoding( "utf-8" ) class ClientMessage(): #设置用户名密码 def setUsrANDPwd(self,usr,pwd): ...
lf.port = port def check_info(self): self.buffer = 1024 self.ADDR=(self.local,self.port) self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM) self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR) self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer) ...
ocal se
identifier_name
class_ClientMessage.py
# _*_ coding:utf-8 _*_ # Filename:ClientUI.py # Python在线聊天客户端 from socket import * from ftplib import FTP import ftplib import socket import thread import time import sys import codecs import os reload(sys) sys.setdefaultencoding( "utf-8" ) class ClientMessage(): #设置用户名密码 def setUsrANDPwd(self,usr,pwd): ...
ent.setUsrANDPwd('12073127', '12073127') client.setToUsr('12073128') client.startNewThread() if __name__=='__main__': main()
identifier_body
__init__.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2014, Nigel Small # # 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 # # Unle...
__all__ = ["LegacyResource", "LegacyNode", "Index", "LegacyReadBatch", "LegacyWriteBatch"]
from py2neo.legacy.batch import * from py2neo.legacy.core import * from py2neo.legacy.index import *
random_line_split
test-install.py
#!/usr/bin/python2.7 # # This file is part of drizzle-ci # # Copyright (c) 2013 Sharan Kumar M # # drizzle-ci is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or ...
for state in opt['state']: top_data = top_file.format(state) with open(path['state']+'/top.sls', 'w') as top_sls: top_sls.write(top_data) for minion in opt['minion']: output = subprocess.Popen(['sudo', 'salt', minion, 'state.highstate'], stdout=subprocess.PIPE) result, error = ...
log.info('\t\tstate minion status ') log.info('\t\t==================================================')
random_line_split
test-install.py
#!/usr/bin/python2.7 # # This file is part of drizzle-ci # # Copyright (c) 2013 Sharan Kumar M # # drizzle-ci is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or ...
(signal_type,handler): ''' This function handles the keyboard interrupt ''' log.info('\t\tPressed CTRL+C') log.info('\t\texiting...') exit(0) # processing the command line and kick start! opt = process_command_line() signal.signal(signal.SIGINT,keyboard_interrupt) log.info('\t\tsetting up the e...
keyboard_interrupt
identifier_name
test-install.py
#!/usr/bin/python2.7 # # This file is part of drizzle-ci # # Copyright (c) 2013 Sharan Kumar M # # drizzle-ci is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or ...
# processing the command line and kick start! opt = process_command_line() signal.signal(signal.SIGINT,keyboard_interrupt) log.info('\t\tsetting up the environment') # setting up the environment cmd = copy.format(path['state']+'/top.sls',path['state']+'/top.sls.bak') os.system(cmd) cmd = copy.format(path['root']+'/...
''' This function handles the keyboard interrupt ''' log.info('\t\tPressed CTRL+C') log.info('\t\texiting...') exit(0)
identifier_body
test-install.py
#!/usr/bin/python2.7 # # This file is part of drizzle-ci # # Copyright (c) 2013 Sharan Kumar M # # drizzle-ci is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or ...
else: status = 'OK' log.info('\t\t'+state.ljust(20)+minion.ljust(20)+status.ljust(10)) # restoring the original top.sls and cleaning up.. log.info('\t\t==================================================') log.info('\n\t\tcleaning up...') cmd = 'sudo mv {0} {1}'.format(path['state']+'/top....
status = 'FAILURE'
conditional_block
detect.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
} 0 }
{ let value = &s.name_string[i as usize]; *buffer = value.as_ptr(); *buffer_len = value.len() as u32; return 1; }
conditional_block
detect.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
-> u8 { if let Some(ref s) = tx.cname { if (i as usize) < s.name_string.len() { let value = &s.name_string[i as usize]; *buffer = value.as_ptr(); *buffer_len = value.len() as u32; return 1; } } 0 } ...
buffer_len: *mut u32)
random_line_split
detect.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
#[no_mangle] pub unsafe extern "C" fn rs_krb5_tx_get_sname(tx: &mut KRB5Transaction, i: u16, buffer: *mut *const u8, buffer_len: *mut u32) ...
{ if let Some(ref s) = tx.cname { if (i as usize) < s.name_string.len() { let value = &s.name_string[i as usize]; *buffer = value.as_ptr(); *buffer_len = value.len() as u32; return 1; } } 0 }
identifier_body
detect.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
(tx: &mut KRB5Transaction, ptr: *mut i32) -> u32 { match tx.error_code { Some(ref e) => { *ptr = e.0; 0 }, None => 1 } } #[no_mangle] pub unsafe extern "C" fn rs_krb5_tx_get_cname(tx: &mut KRB5Transaction, ...
rs_krb5_tx_get_errcode
identifier_name
misc.py
import time from os import system import bot as cleanBot def pp(message, mtype='INFO'): mtype = mtype.upper() print '[%s] [%s] %s' % (time.strftime('%H:%M:%S', time.gmtime()), mtype, message) def ppi(channel, message, username): print '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel,...
else: print '\n\n' print '\n'.join('CHAT ENABLED ACTIONS ARE OFF') print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer])
print '\n\n' print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer])
conditional_block
misc.py
import time from os import system import bot as cleanBot def pp(message, mtype='INFO'): mtype = mtype.upper() print '[%s] [%s] %s' % (time.strftime('%H:%M:%S', time.gmtime()), mtype, message) def ppi(channel, message, username): print '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel,...
print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer]) else: print '\n\n' print '\n'.join('CHAT ENABLED ACTIONS ARE OFF') print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), me...
print '\n\n'
random_line_split
misc.py
import time from os import system import bot as cleanBot def pp(message, mtype='INFO'): mtype = mtype.upper() print '[%s] [%s] %s' % (time.strftime('%H:%M:%S', time.gmtime()), mtype, message) def ppi(channel, message, username): print '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel,...
if cleanBot.Bot().botOn == True: print '\n\n' print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer]) else: print '\n\n' print '\n'.join('CHAT ENABLED ACTIONS ARE OFF') print '\n'.join([' {0:<12s...
identifier_body
misc.py
import time from os import system import bot as cleanBot def pp(message, mtype='INFO'): mtype = mtype.upper() print '[%s] [%s] %s' % (time.strftime('%H:%M:%S', time.gmtime()), mtype, message) def ppi(channel, message, username): print '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel,...
(message_buffer): #system('clear') if cleanBot.Bot().botOn == True: print '\n\n' print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer]) else: print '\n\n' print '\n'.join('CHAT ENABLED ACTIONS A...
pbutton
identifier_name
cryptographer.py
from base64 import b64decode, b64encode from hashlib import sha256 from Crypto import Random from Crypto.Cipher import AES from frontstage import app class
: """Manage the encryption and decryption of random byte strings""" def __init__(self): """ Set up the encryption key, this will come from an .ini file or from an environment variable. Change the block size to suit the data supplied or performance required. :param key: ...
Cryptographer
identifier_name
cryptographer.py
from base64 import b64decode, b64encode from hashlib import sha256 from Crypto import Random from Crypto.Cipher import AES from frontstage import app class Cryptographer: """Manage the encryption and decryption of random byte strings""" def __init__(self): """ Set up the encryption key, thi...
""" Un-pad the selected data. :param data: Our padded data :return: The data 'un'padded """ return data[0 : -data[-1]]
vector = AES.block_size - len(data) % AES.block_size return data + ((bytes([vector])) * vector) def unpad(self, data):
random_line_split
cryptographer.py
from base64 import b64decode, b64encode from hashlib import sha256 from Crypto import Random from Crypto.Cipher import AES from frontstage import app class Cryptographer: """Manage the encryption and decryption of random byte strings""" def __init__(self): """ Set up the encryption key, thi...
def unpad(self, data): """ Un-pad the selected data. :param data: Our padded data :return: The data 'un'padded """ return data[0 : -data[-1]]
""" Pad the data out to the selected block size. :param data: The data were trying to encrypt :return: The data padded out to our given block size """ vector = AES.block_size - len(data) % AES.block_size return data + ((bytes([vector])) * vector)
identifier_body
fp.rs
// Copyright 2021 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(idf: bool) -> &'static str { if idf { "Input denormal floating-point exception occurred." } else { "Input denormal floating-point exception did not occur." } } fn describe_ixf(ixf: bool) -> &'static str { if ixf { "Inexact floating-point exception occurred." } else { ...
describe_idf
identifier_name
fp.rs
// Copyright 2021 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} } fn describe_idf(idf: bool) -> &'static str { if idf { "Input denormal floating-point exception occurred." } else { "Input denormal floating-point exception did not occur." } } fn describe_ixf(ixf: bool) -> &'static str { if ixf { "Inexact floating-point exception occurr...
} else { "IDF, IXF, UFF, OFF, DZF and IOF do not hold valid information."
random_line_split
fp.rs
// Copyright 2021 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} fn describe_uff(uff: bool) -> &'static str { if uff { "Underflow floating-point exception occurred." } else { "Underflow floating-point exception did not occur." } } fn describe_off(off: bool) -> &'static str { if off { "Overflow floating-point exception occurred." } els...
{ "Inexact floating-point exception did not occur." }
conditional_block
fp.rs
// Copyright 2021 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
{ if iof { "Invalid Operation floating-point exception occurred." } else { "Invalid Operation floating-point exception did not occur." } }
identifier_body
app.component.spec.ts
import { TestBed, async } from '@angular/core/testing'; import { AppComponent } from './app.component'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { OnChangesDemoComponent } from './on-changes-demo/on-changes-demo.component'; import { DoCheckDemoComponent } from...
AfterContentInitChildComponent, AfterContentInitDemoComponent, OnDestroyDemoComponent, AfterViewInitDemoComponent ] }).compileComponents(); })); it('should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.deb...
OnChangesDemoComponent, DoCheckDemoComponent, OnInitDemoComponent,
random_line_split
dmc_colors.py
import csv import os import color def _GetDataDirPath(): return os.path.join(os.path.dirname(__file__), 'data') def _GetCsvPath(): return os.path.join(_GetDataDirPath(), 'dmccolors.csv') def _GetCsvString(): with open(_GetCsvPath()) as f: return f.read().strip() def _CreateDmcColorFromRow(row): number =...
def GetDMCColors(): global _dmc_colors if not _dmc_colors: _dmc_colors = frozenset(_CreateDMCColors()) return _dmc_colors def GetClosestDMCColorsPairs(rgb_color): pairs = list() for dcolor in GetDMCColors(): pairs.append((dcolor, color.RGBColor.distance(rgb_color, dcolor.color))) return s...
global _dmc_colors csv_data = _GetCsvString() lines = csv_data.splitlines() # Skip first line lines = lines[1:] reader = csv.reader(lines, delimiter='\t') dmc_colors = set() for row in reader: dmc_colors.add(_CreateDmcColorFromRow(row)) return dmc_colors
identifier_body
dmc_colors.py
import csv import os import color def _GetDataDirPath(): return os.path.join(os.path.dirname(__file__), 'data') def _GetCsvPath(): return os.path.join(_GetDataDirPath(), 'dmccolors.csv') def _GetCsvString(): with open(_GetCsvPath()) as f: return f.read().strip() def _CreateDmcColorFromRow(row): number =...
if __name__ == '__main__': main()
random_line_split
dmc_colors.py
import csv import os import color def _GetDataDirPath(): return os.path.join(os.path.dirname(__file__), 'data') def _GetCsvPath(): return os.path.join(_GetDataDirPath(), 'dmccolors.csv') def _GetCsvString(): with open(_GetCsvPath()) as f: return f.read().strip() def _CreateDmcColorFromRow(row): number =...
return dmc_colors def GetDMCColors(): global _dmc_colors if not _dmc_colors: _dmc_colors = frozenset(_CreateDMCColors()) return _dmc_colors def GetClosestDMCColorsPairs(rgb_color): pairs = list() for dcolor in GetDMCColors(): pairs.append((dcolor, color.RGBColor.distance(rgb_color, dcolor...
dmc_colors.add(_CreateDmcColorFromRow(row))
conditional_block
dmc_colors.py
import csv import os import color def _GetDataDirPath(): return os.path.join(os.path.dirname(__file__), 'data') def _GetCsvPath(): return os.path.join(_GetDataDirPath(), 'dmccolors.csv') def _GetCsvString(): with open(_GetCsvPath()) as f: return f.read().strip() def _CreateDmcColorFromRow(row): number =...
(self): return super(DMCColor, self).__str__() + str((self.number, self.name, self.color)) def GetStringForDMCColor(dmc_color): return "%s %s %s" % (dmc_color.number, dmc_color.name, dmc_color.color) # Simple executable functionality for debugging. def main(): for color in GetDMCColors(): print color i...
__str__
identifier_name
const-vec-of-fns.rs
// Copyright 2013 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 ...
() { } static bare_fns: &'static [fn()] = &[f, f]; struct S<F: FnOnce()>(F); static mut closures: &'static mut [S<fn()>] = &mut [S(f as fn()), S(f as fn())]; pub fn main() { unsafe { for &bare_fn in bare_fns { bare_fn() } for closure in &mut *closures { let S(ref mut closure) = *closure...
f
identifier_name
const-vec-of-fns.rs
// Copyright 2013 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Try to do...
random_line_split
output.py
# Copyright 1998-2004 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Id: output.py,v 1.1 2006/03/06 18:13:31 henrique Exp $ import os import sys import re havecolor = 1 dotitles = 1 spinpos = 0 spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|" esc_seq = "\x1b[" g_attr =...
(mystr): tmp = re.sub(esc_seq + "^m]+m", "", mystr) return len(tmp) def xtermTitle(mystr): if havecolor and dotitles and "TERM" in os.environ and sys.stderr.isatty(): myt = os.environ["TERM"] legal_terms = [ "xterm", "Eterm", "aterm", "rxvt", "screen", "kterm", "rxvt-unicode"] ...
nc_len
identifier_name
output.py
# Copyright 1998-2004 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Id: output.py,v 1.1 2006/03/06 18:13:31 henrique Exp $ import os import sys import re havecolor = 1 dotitles = 1 spinpos = 0 spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|" esc_seq = "\x1b[" g_attr =...
def resetColor(): return codes["reset"] def ctext(color, text): return codes[ctext] + text + codes["reset"] def bold(text): return codes["bold"] + text + codes["reset"] def faint(text): return codes["faint"] + text + codes["reset"] def white(text): return bold(text) def teal(text): ...
codes[x] = ""
conditional_block
output.py
# Copyright 1998-2004 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Id: output.py,v 1.1 2006/03/06 18:13:31 henrique Exp $ import os import sys import re havecolor = 1 dotitles = 1 spinpos = 0 spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|" esc_seq = "\x1b[" g_attr =...
def green(text): return codes["green"] + text + codes["reset"] def darkgreen(text): return codes["darkgreen"] + text + codes["reset"] def yellow(text): return codes["yellow"] + text + codes["reset"] def brown(text): return codes["brown"] + text + codes["reset"] def darkyellow(text): return...
def darkblue(text): return codes["darkblue"] + text + codes["reset"]
random_line_split
output.py
# Copyright 1998-2004 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Id: output.py,v 1.1 2006/03/06 18:13:31 henrique Exp $ import os import sys import re havecolor = 1 dotitles = 1 spinpos = 0 spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|" esc_seq = "\x1b[" g_attr =...
def ctext(color, text): return codes[ctext] + text + codes["reset"] def bold(text): return codes["bold"] + text + codes["reset"] def faint(text): return codes["faint"] + text + codes["reset"] def white(text): return bold(text) def teal(text): return codes["teal"] + text + codes["reset"] ...
return codes["reset"]
identifier_body
CustomizedTables.tsx
import * as React from 'react'; import { styled } from '@mui/material/styles'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell, { tableCellClasses } from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableContainer'; import TableHead from...
); }
random_line_split
CustomizedTables.tsx
import * as React from 'react'; import { styled } from '@mui/material/styles'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell, { tableCellClasses } from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableContainer'; import TableHead from...
( name: string, calories: number, fat: number, carbs: number, protein: number, ) { return { name, calories, fat, carbs, protein }; } const rows = [ createData('Frozen yoghurt', 159, 6.0, 24, 4.0), createData('Ice cream sandwich', 237, 9.0, 37, 4.3), createData('Eclair', 262, 16.0, 24, 6.0), createD...
createData
identifier_name
CustomizedTables.tsx
import * as React from 'react'; import { styled } from '@mui/material/styles'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell, { tableCellClasses } from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableContainer'; import TableHead from...
const rows = [ createData('Frozen yoghurt', 159, 6.0, 24, 4.0), createData('Ice cream sandwich', 237, 9.0, 37, 4.3), createData('Eclair', 262, 16.0, 24, 6.0), createData('Cupcake', 305, 3.7, 67, 4.3), createData('Gingerbread', 356, 16.0, 49, 3.9), ]; export default function CustomizedTables() { return ( ...
{ return { name, calories, fat, carbs, protein }; }
identifier_body
gulpfile.js
// ## Globals var argv = require('minimist')(process.argv.slice(2)); var autoprefixer = require('gulp-autoprefixer'); var browserSync = require('browser-sync').create(); var changed = require('gulp-changed'); var concat = require('gulp-concat'); var flatten = require('gulp-flatten'); var gulp ...
return gulp .src('templates/svg-icons.php') .pipe(inject(svgs, { transform: fileContents })) .pipe(gulp.dest('templates')); }); // ### Images // `gulp images` - Run lossless compression on all the images. gulp.task('images', function() { return gulp.src(globs.images) .pipe(imagemin({ ...
{ return file.contents.toString(); }
identifier_body
gulpfile.js
// ## Globals var argv = require('minimist')(process.argv.slice(2)); var autoprefixer = require('gulp-autoprefixer'); var browserSync = require('browser-sync').create(); var changed = require('gulp-changed'); var concat = require('gulp-concat'); var flatten = require('gulp-flatten'); var gulp ...
(filePath, file) { return file.contents.toString(); } return gulp .src('templates/svg-icons.php') .pipe(inject(svgs, { transform: fileContents })) .pipe(gulp.dest('templates')); }); // ### Images // `gulp images` - Run lossless compression on all the images. gulp.task('images', function()...
fileContents
identifier_name