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
graphs.rs
extern crate rand; extern crate timely; extern crate differential_dataflow; use std::rc::Rc; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use differential_dataflow::input::Input; use differential_dataflow::Collection; use differential_dataflow::operators::*; use differential_dataflow::trace::Trace...
<G: Scope<Timestamp = ()>> ( graph: &mut TraceHandle, roots: Collection<G, Node> ) -> Collection<G, Node> { let graph = graph.import(&roots.scope()); roots.iterate(|inner| { let graph = graph.enter(&inner.scope()); let roots = roots.enter(&inner.scope()); // let reach = inner...
reach
identifier_name
graphs.rs
extern crate rand; extern crate timely; extern crate differential_dataflow; use std::rc::Rc; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use differential_dataflow::input::Input; use differential_dataflow::Collection; use differential_dataflow::operators::*; use differential_dataflow::trace::Trace...
roots.close(); while worker.step() { } if index == 0 { println!("{:?}\tbfs complete", timer.elapsed()); } }).unwrap(); } // use differential_dataflow::trace::implementations::ord::OrdValSpine; use differential_dataflow::operators::arrange::TraceAgent; type TraceHandle = TraceAgent<Node,...
{ roots.insert(0); }
conditional_block
sha256.rs
} // Copy any input data into the buffer. At this point in the method, the amount of // data left in the input vector will be less than the buffer size and the buffer will // be empty. let input_remaining = input.len() - i; copy_memory( self.buffer.slice_to_m...
fn sigma1(x: u32) -> u32 { ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10) } let mut a = self.h0; let mut b = self.h1; let mut c = self.h2; let mut d = self.h3; let mut e = self.h4; let mut f = self.h5; let mut g = self....
random_line_split
sha256.rs
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifie...
{ let (new_high_bits, new_low_bits) = bytes.to_bits(); if new_high_bits > Int::zero() { panic!("numeric overflow occurred.") } match bits.checked_add(new_low_bits) { Some(x) => return x, None => panic!("numeric overflow occurred.") } }
identifier_body
sha256.rs
, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; // A structure that keeps track of the state of the Sha-256 operation and contains the logic //...
test_1million_random_sha256
identifier_name
__init__.py
from os.path import abspath import wptools from mycroft.messagebus.message import Message from mycroft.skills.LILACS_knowledge.services import KnowledgeBackend from mycroft.util.log import getLogger __author__ = 'jarbas' logger = getLogger(abspath(__file__).split('/')[-2]) class WikidataService(KnowledgeBackend):...
else: dict = {} node_data = {} # get knowledge about # TODO exception handling for erros try: page = wptools.page(subject, silent=True, verbose=False).get_wikidata() # parse for distant child of node_dat...
logger.error("No subject to adquire knowledge about") return
conditional_block
__init__.py
from os.path import abspath import wptools from mycroft.messagebus.message import Message from mycroft.skills.LILACS_knowledge.services import KnowledgeBackend from mycroft.util.log import getLogger __author__ = 'jarbas' logger = getLogger(abspath(__file__).split('/')[-2]) class WikidataService(KnowledgeBackend):...
def load_service(base_config, emitter): backends = base_config.get('backends', []) services = [(b, backends[b]) for b in backends if backends[b]['type'] == 'wikidata'] instances = [WikidataService(s[1], emitter, s[0]) for s in services] return instances
random_line_split
__init__.py
from os.path import abspath import wptools from mycroft.messagebus.message import Message from mycroft.skills.LILACS_knowledge.services import KnowledgeBackend from mycroft.util.log import getLogger __author__ = 'jarbas' logger = getLogger(abspath(__file__).split('/')[-2]) class WikidataService(KnowledgeBackend):...
(self, subject): logger.info('Call WikidataKnowledgeAdquire') self.emitter.emit(Message('WikidataKnowledgeAdquire', {"subject": subject})) def send_result(self, result = {}): self.emitter.emit(Message("LILACS_result", {"data": result})) def stop(self): logger.info('WikidataKnow...
adquire
identifier_name
__init__.py
from os.path import abspath import wptools from mycroft.messagebus.message import Message from mycroft.skills.LILACS_knowledge.services import KnowledgeBackend from mycroft.util.log import getLogger __author__ = 'jarbas' logger = getLogger(abspath(__file__).split('/')[-2]) class WikidataService(KnowledgeBackend):...
node_data["properties"] = page.props # id info source dict["wikidata"] = node_data except: logger.error("Could not parse wikidata for " + str(subject)) self.send_result(dict) def adquire(self, subject): logger.info('Ca...
logger.info('WikidataKnowledge_Adquire') subject = message.data["subject"] if subject is None: logger.error("No subject to adquire knowledge about") return else: dict = {} node_data = {} # get knowledge about # TODO exceptio...
identifier_body
test_apt.rs
extern crate woko; // use std::io::prelude::*; #[cfg(test)] mod tests { use std::fs::File; use std::io::Read; use std::path::Path; //use std::collections::HashMap; use woko::apt; fn
() -> String { let mut f = File::open(Path::new("tests/apt.out")).unwrap(); let mut s = String::new(); f.read_to_string(&mut s).ok(); return s; } #[test] fn test_woko_apt() { let apts = apt::parse_from_string(&read()).unwrap(); let l122 = apts.get(121).unwrap...
read
identifier_name
test_apt.rs
extern crate woko;
#[cfg(test)] mod tests { use std::fs::File; use std::io::Read; use std::path::Path; //use std::collections::HashMap; use woko::apt; fn read() -> String { let mut f = File::open(Path::new("tests/apt.out")).unwrap(); let mut s = String::new(); f.read_to_string(&mut s).ok()...
// use std::io::prelude::*;
random_line_split
test_apt.rs
extern crate woko; // use std::io::prelude::*; #[cfg(test)] mod tests { use std::fs::File; use std::io::Read; use std::path::Path; //use std::collections::HashMap; use woko::apt; fn read() -> String { let mut f = File::open(Path::new("tests/apt.out")).unwrap(); let mut s = ...
}
{ let apts = apt::parse_from_string(&read()).unwrap(); let l122 = apts.get(121).unwrap(); assert_eq!(132, apts.len()); assert_eq!("http://archive.ubuntu.com/ubuntu/pool/main/r/rename/rename_0.20-4_all.deb", l122.url); assert_eq!("rename_0.20-4_all.deb", l122.name); assert...
identifier_body
Ellipsis.tsx
import * as classNames from 'classnames'; import * as React from 'react'; import { Bulma, getActiveModifiers, getFocusedModifiers, removeActiveModifiers, removeFocusedModifiers, withHelpersModifiers, } from './../../bulma'; import { combineModifiers, getHTMLProps } from './../../helpers'; export inter...
const className = classNames( 'pagination-ellipsis', { ...combineModifiers(props, getActiveModifiers, getFocusedModifiers), }, props.className, ); const { children, ...HTMLProps } = getHTMLProps(props, removeActiveModifiers, removeFocusedModifiers); return R...
export function Ellipsis({ tag = 'span', ...props }: Ellipsis<HTMLElement>) {
random_line_split
Ellipsis.tsx
import * as classNames from 'classnames'; import * as React from 'react'; import { Bulma, getActiveModifiers, getFocusedModifiers, removeActiveModifiers, removeFocusedModifiers, withHelpersModifiers, } from './../../bulma'; import { combineModifiers, getHTMLProps } from './../../helpers'; export inter...
const HOC = /*@__PURE__*/withHelpersModifiers(Ellipsis); export default HOC;
{ const className = classNames( 'pagination-ellipsis', { ...combineModifiers(props, getActiveModifiers, getFocusedModifiers), }, props.className, ); const { children, ...HTMLProps } = getHTMLProps(props, removeActiveModifiers, removeFocusedModifiers); return...
identifier_body
Ellipsis.tsx
import * as classNames from 'classnames'; import * as React from 'react'; import { Bulma, getActiveModifiers, getFocusedModifiers, removeActiveModifiers, removeFocusedModifiers, withHelpersModifiers, } from './../../bulma'; import { combineModifiers, getHTMLProps } from './../../helpers'; export inter...
({ tag = 'span', ...props }: Ellipsis<HTMLElement>) { const className = classNames( 'pagination-ellipsis', { ...combineModifiers(props, getActiveModifiers, getFocusedModifiers), }, props.className, ); const { children, ...HTMLProps } = getHTMLProps(props, removeA...
Ellipsis
identifier_name
pelicanconf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals import os AUTHOR = u'Eric Carmichael' SITENAME = u"Eric Carmichael's Nerdery" SITEURL = os.environ.get("PELICAN_SITE_URL", "") TIMEZONE = 'Europe/Paris' DEFAULT_LANG = u'en'
FEED_ALL_ATOM = 'feeds/all.atom.xml' CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None DEFAULT_PAGINATION = 2 # WITH_FUTURE_DATES = True GITHUB_URL = 'http://github.com/ckcollab/' THEME = "themes/mintheme" PATH = "content" PLUGINS = ["plugins.assets", "plugins.sitemap"] MARKUP = (('rst', 'md', 'html')) WEBASSETS...
# Feed generation is usually not desired when developing
random_line_split
to_toml.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // 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 r...
(&self, h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> RenderResult<()> { let param = h.param(0) .ok_or_else(|| RenderError::new("Expected 1 parameter for \"toToml\""))? .value(); let bytes = toml::ser::to_vec(&param) .map_err(|e| RenderError::new(format!("Can...
call
identifier_name
to_toml.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // 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 r...
.value(); let bytes = toml::ser::to_vec(&param) .map_err(|e| RenderError::new(format!("Can't serialize parameter to TOML: {}", e)))?; rc.writer.write_all(bytes.as_ref())?; Ok(()) } } pub static TO_TOML: ToTomlHelper = ToTomlHelper;
impl HelperDef for ToTomlHelper { fn call(&self, h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> RenderResult<()> { let param = h.param(0) .ok_or_else(|| RenderError::new("Expected 1 parameter for \"toToml\""))?
random_line_split
plugin.py
# -*- coding: utf-8 -*- """ pygments.plugin ~~~~~~~~~~~~~~~ Pygments setuptools plugin interface. The methods defined here also work if setuptools isn't installed but they just return nothing. lexer plugins:: [pygments.lexers] yourlexer = yourmodule:YourLexer
formatter plugins:: [pygments.formatters] yourformatter = yourformatter:YourFormatter /.ext = yourformatter:YourFormatter As you can see, you can define extensions for the formatter with a leading slash. syntax plugins:: [pygments.styles] yourstyle = yourstyle...
random_line_split
plugin.py
# -*- coding: utf-8 -*- """ pygments.plugin ~~~~~~~~~~~~~~~ Pygments setuptools plugin interface. The methods defined here also work if setuptools isn't installed but they just return nothing. lexer plugins:: [pygments.lexers] yourlexer = yourmodule:YourLexer formatter pl...
(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(STYLE_ENTRY_POINT): yield entrypoint.name, entrypoint.load() def find_plugin_filters(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(FILTER_ENTRY_POINT):...
find_plugin_styles
identifier_name
plugin.py
# -*- coding: utf-8 -*- """ pygments.plugin ~~~~~~~~~~~~~~~ Pygments setuptools plugin interface. The methods defined here also work if setuptools isn't installed but they just return nothing. lexer plugins:: [pygments.lexers] yourlexer = yourmodule:YourLexer formatter pl...
def find_plugin_filters(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(FILTER_ENTRY_POINT): yield entrypoint.name, entrypoint.load()
if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(STYLE_ENTRY_POINT): yield entrypoint.name, entrypoint.load()
identifier_body
plugin.py
# -*- coding: utf-8 -*- """ pygments.plugin ~~~~~~~~~~~~~~~ Pygments setuptools plugin interface. The methods defined here also work if setuptools isn't installed but they just return nothing. lexer plugins:: [pygments.lexers] yourlexer = yourmodule:YourLexer formatter pl...
for entrypoint in pkg_resources.iter_entry_points(LEXER_ENTRY_POINT): yield entrypoint.load() def find_plugin_formatters(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(FORMATTER_ENTRY_POINT): yield entrypoint.name, entrypoint.load() def fin...
return
conditional_block
examples.js
angular.module('examples', []) .factory('formPostData', ['$document', function($document) { return function(url, fields) { var form = angular.element('<form style="display: none;" method="post" action="' + url + '" target="_blank"></form>'); angular.forEach(fields, function(value, name) { var input = a...
return { name: filename, content: response.data }; })); }); return $q.all(filePromises); }) .then(function(files) { var postData = {}; angular.forEach(files, function(file) { postData['files[...
{ filename = "index.html" }
conditional_block
examples.js
angular.module('examples', []) .factory('formPostData', ['$document', function($document) { return function(url, fields) { var form = angular.element('<form style="display: none;" method="post" action="' + url + '" target="_blank"></form>'); angular.forEach(fields, function(value, name) { var input = a...
})); }); return $q.all(filePromises); }) .then(function(files) { var postData = {}; angular.forEach(files, function(file) { postData['files[' + file.name + ']'] = file.content; }); postData['tags[0]'] = "angularjs"; postData['ta...
random_line_split
timer.rs
use libc::{uint32_t, c_void}; use std::mem; use sys::timer as ll; pub fn get_ticks() -> u32 { unsafe { ll::SDL_GetTicks() } } pub fn get_performance_counter() -> u64 { unsafe { ll::SDL_GetPerformanceCounter() } } pub fn get_performance_frequency() -> u64 { unsafe { ll::SDL_GetPerformanceFrequency() } } ...
} } extern "C" fn c_timer_callback(_interval: u32, param: *const c_void) -> uint32_t { unsafe { let f: *const Box<Fn() -> u32> = mem::transmute(param); (*f)() as uint32_t } } #[cfg(test)] use std::sync::{StaticMutex, MUTEX_INIT}; #[cfg(test)] static TIMER_INIT_LOCK: StaticMutex = MUTEX_...
{ println!("error dropping timer {}, maybe already removed.", self.raw); }
conditional_block
timer.rs
use libc::{uint32_t, c_void}; use std::mem; use sys::timer as ll; pub fn get_ticks() -> u32 { unsafe { ll::SDL_GetTicks() } } pub fn get_performance_counter() -> u64 { unsafe { ll::SDL_GetPerformanceCounter() } } pub fn get_performance_frequency() -> u64 { unsafe { ll::SDL_GetPerformanceFrequency() } } ...
#[cfg(test)] use std::sync::{StaticMutex, MUTEX_INIT}; #[cfg(test)] static TIMER_INIT_LOCK: StaticMutex = MUTEX_INIT; #[test] fn test_timer_runs_multiple_times() { use std::sync::{Arc, Mutex}; let _running = TIMER_INIT_LOCK.lock().unwrap(); ::sdl::init(::sdl::INIT_TIMER).unwrap(); let local_num = A...
{ unsafe { let f: *const Box<Fn() -> u32> = mem::transmute(param); (*f)() as uint32_t } }
identifier_body
timer.rs
use libc::{uint32_t, c_void}; use std::mem; use sys::timer as ll; pub fn get_ticks() -> u32 { unsafe { ll::SDL_GetTicks() } } pub fn get_performance_counter() -> u64 { unsafe { ll::SDL_GetPerformanceCounter() } } pub fn get_performance_frequency() -> u64 { unsafe { ll::SDL_GetPerformanceFrequency() } } ...
(&mut self) { let ret = unsafe { ll::SDL_RemoveTimer(self.raw) }; if ret != 1 { println!("error dropping timer {}, maybe already removed.", self.raw); } } } extern "C" fn c_timer_callback(_interval: u32, param: *const c_void) -> uint32_t { unsafe { let f: *const Box...
drop
identifier_name
timer.rs
use libc::{uint32_t, c_void}; use std::mem; use sys::timer as ll; pub fn get_ticks() -> u32 { unsafe { ll::SDL_GetTicks() } } pub fn get_performance_counter() -> u64 { unsafe { ll::SDL_GetPerformanceCounter() } } pub fn get_performance_frequency() -> u64 { unsafe { ll::SDL_GetPerformanceFrequency() } } ...
impl<'a> Drop for Timer<'a> { fn drop(&mut self) { let ret = unsafe { ll::SDL_RemoveTimer(self.raw) }; if ret != 1 { println!("error dropping timer {}, maybe already removed.", self.raw); } } } extern "C" fn c_timer_callback(_interval: u32, param: *const c_void) -> uint32_t ...
#[unsafe_destructor]
random_line_split
copy-all-static-files.ts
import chalk from 'chalk'; import fs from 'fs-extra'; import path from 'path'; import { logger } from '@storybook/node-logger'; import { parseStaticDir } from './server-statics'; export async function
(staticDirs: any[] | undefined, outputDir: string) { if (staticDirs && staticDirs.length > 0) { await Promise.all( staticDirs.map(async (dir) => { try { const { staticDir, staticPath, targetDir } = await parseStaticDir(dir); const targetPath = path.join(outputDir, targetDir); ...
copyAllStaticFiles
identifier_name
copy-all-static-files.ts
import chalk from 'chalk'; import fs from 'fs-extra'; import path from 'path'; import { logger } from '@storybook/node-logger'; import { parseStaticDir } from './server-statics'; export async function copyAllStaticFiles(staticDirs: any[] | undefined, outputDir: string)
}) ); } }
{ if (staticDirs && staticDirs.length > 0) { await Promise.all( staticDirs.map(async (dir) => { try { const { staticDir, staticPath, targetDir } = await parseStaticDir(dir); const targetPath = path.join(outputDir, targetDir); logger.info(chalk`=> Copying static files: {...
identifier_body
copy-all-static-files.ts
import chalk from 'chalk'; import fs from 'fs-extra'; import path from 'path'; import { logger } from '@storybook/node-logger'; import { parseStaticDir } from './server-statics'; export async function copyAllStaticFiles(staticDirs: any[] | undefined, outputDir: string) { if (staticDirs && staticDirs.length > 0)
); } }
{ await Promise.all( staticDirs.map(async (dir) => { try { const { staticDir, staticPath, targetDir } = await parseStaticDir(dir); const targetPath = path.join(outputDir, targetDir); logger.info(chalk`=> Copying static files: {cyan ${staticDir}} => {cyan ${targetDir}}`); ...
conditional_block
copy-all-static-files.ts
import chalk from 'chalk'; import fs from 'fs-extra'; import path from 'path'; import { logger } from '@storybook/node-logger'; import { parseStaticDir } from './server-statics'; export async function copyAllStaticFiles(staticDirs: any[] | undefined, outputDir: string) { if (staticDirs && staticDirs.length > 0) { ...
} catch (e) { logger.error(e.message); process.exit(-1); } }) ); } }
filter: (_, dest) => !skipPaths.includes(dest), });
random_line_split
webserver.py
# -*- coding: utf-8 -*- from flask import Flask from flask import Flask,jsonify, request, Response, session,g,redirect, url_for,abort, render_template, flash from islem import * from bot import * import sys import time import datetime reload(sys) sys.setdefaultencoding("utf-8") app = Flask(__name__) toxbot = tox_fac...
@app.route('/toxfs', methods = ['GET','POST']) def toxfs(): # localhost:2061 #if request.method == 'GET': islem=Islem() islem.fno = request.args.get('fno') islem.tip = request.args.get('tip') islem.mesaj = request.args.get('mesaj') islem.komut="---" print "islem icerik:" islem.icerik() islem.dosyala(komut_d...
arkadaslar="" for num in toxbot.self_get_friend_list(): arkadaslar+="<tr><td><a href=/toxsys?fno="+str(num)+">"+str(num)+"</td><td>"+toxbot.friend_get_name(num)+"</td><td>"+str(toxbot.friend_get_status_message(num))+"</td><td>"+str(toxbot.friend_get_public_key(num))+"</td></tr>" return '''<html> <h2>Tox...
identifier_body
webserver.py
# -*- coding: utf-8 -*- from flask import Flask from flask import Flask,jsonify, request, Response, session,g,redirect, url_for,abort, render_template, flash from islem import * from bot import * import sys import time import datetime reload(sys) sys.setdefaultencoding("utf-8") app = Flask(__name__) toxbot = tox_fac...
dosyalar_html="" # localhost:2061 #if request.method == 'GET': islem=Islem() if 'fno' in request.args and 'dosya' not in request.args: islem.fno = request.args.get('fno') islem.tip = "komut" islem.mesaj = "x" islem.komut = "@100@dlist" print "islem icerik:" islem.icerik() islem.dosyala(komut_dosyasi...
sys():
identifier_name
webserver.py
# -*- coding: utf-8 -*- from flask import Flask from flask import Flask,jsonify, request, Response, session,g,redirect, url_for,abort, render_template, flash from islem import * from bot import * import sys import time import datetime reload(sys) sys.setdefaultencoding("utf-8") app = Flask(__name__) toxbot = tox_fac...
else: print "dlist sonucu bekleniyor.",krono.total_seconds() if 'fno' in request.args and 'dosya' in request.args: islem.fno = request.args.get('fno') dosya = request.args.get('dosya') islem.tip = "komut" islem.mesaj = "x" islem.komut = "@102@"+dosya islem.dosyala(komut_dosyasi) cevap_geldi=False...
ak
conditional_block
webserver.py
# -*- coding: utf-8 -*- from flask import Flask from flask import Flask,jsonify, request, Response, session,g,redirect, url_for,abort, render_template, flash from islem import * from bot import * import sys import time import datetime reload(sys) sys.setdefaultencoding("utf-8") app = Flask(__name__) toxbot = tox_fac...
for dosya in cevaplar: dosyalar_html+="<tr><td><a href=/toxsys?fno="+str(islem.fno)+"&dosya="+dosya+">"+dosya+"</td><td></tr>" os.remove(karsi_dosyalar) cevap_geldi=True return '''<html> <h3>dosyalar</h3> <table border=1> '''+dosyalar_html+''' </tr> <a href="./">anasayfa</a> ...
if os.path.exists(karsi_dosyalar): time.sleep(1) cevaplar=open(karsi_dosyalar,"r").read() cevaplar=cevaplar.split("\n")
random_line_split
knockoutExtenders.js
๏ปฟdefine(function () { return { registerExtenders: registerExtenders }; function registerExtenders() { registerDateBinding(); registerMoneyExtension(); } function re
) { ko.bindingHandlers.dateString = { //Credit to Ryan Rahlf http://stackoverflow.com/questions/17001303/date-formatting-issues-with-knockout-and-syncing-to-breeze-js-entityaspect-modif init: function (element, valueAccessor) { //attach an event handler to our dom element...
gisterDateBinding (
identifier_name
knockoutExtenders.js
๏ปฟdefine(function () { return { registerExtenders: registerExtenders }; function registerExtenders() { registerDateBinding(); registerMoneyExtension(); } function registerDateBinding () { ko.bindingHandlers.dateString = { //Credit to Ryan Rahlf http://stackoverflow....
} }; } function registerMoneyExtension() { //Credit to Josh Bush http://freshbrewedcode.com/joshbush/2011/12/27/knockout-js-observable-extensions/ var format = function (value) { toks = value.toFixed(2).replace('-', '').split('.'); var display = '$'...
element.value = moment(valueUnwrapped).format('L'); }
conditional_block
knockoutExtenders.js
๏ปฟdefine(function () { return { registerExtenders: registerExtenders };
registerDateBinding(); registerMoneyExtension(); } function registerDateBinding () { ko.bindingHandlers.dateString = { //Credit to Ryan Rahlf http://stackoverflow.com/questions/17001303/date-formatting-issues-with-knockout-and-syncing-to-breeze-js-entityaspect-modif ...
function registerExtenders() {
random_line_split
knockoutExtenders.js
๏ปฟdefine(function () { return { registerExtenders: registerExtenders }; function registerExtenders() { registerDateBinding(); registerMoneyExtension(); } function registerDateBinding () { ko.bindingHandlers.dateString = { //Credit to Ryan Rahlf http://stackoverflow....
}, write: writeTarget }); result.formatted = ko.computed({ read: function () { return format(target()); }, write: writeTarget }); return result; }; } });...
//Credit to Josh Bush http://freshbrewedcode.com/joshbush/2011/12/27/knockout-js-observable-extensions/ var format = function (value) { toks = value.toFixed(2).replace('-', '').split('.'); var display = '$' + $.map(toks[0].split('').reverse(), function (elm, i) { ...
identifier_body
by-move-pattern-binding.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 ...
{ x: E } fn f(x: String) {} fn main() { let s = S { x: E::Bar("hello".to_string()) }; match &s.x { &E::Foo => {} &E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move }; match &s.x { &E::Foo => {} &E::Bar(ref identifier) => println!("{}", *identifier)...
S
identifier_name
by-move-pattern-binding.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 { x: E } fn f(x: String) {} fn main() { let s = S { x: E::Bar("hello".to_string()) }; match &s.x { &E::Foo => {} &E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move }; match &s.x { &E::Foo => {} &E::Bar(ref identifier) => println!("{}", *...
enum E { Foo, Bar(String)
random_line_split
by-move-pattern-binding.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 ...
fn main() { let s = S { x: E::Bar("hello".to_string()) }; match &s.x { &E::Foo => {} &E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move }; match &s.x { &E::Foo => {} &E::Bar(ref identifier) => println!("{}", *identifier) }; }
{}
identifier_body
karma.conf.js
// Karma configuration // Generated on Wed May 13 2015 17:38:34 GMT-0400 (EDT) module.exports = function(config) {
browsers: ['Firefox', 'PhantomJS'], frameworks: ['mocha', 'requirejs'], files: [ 'node_modules/mocha/mocha.js', 'node_modules/mocha/mocha.css', 'node_modules/chai/chai.js', {pattern: 'bower_components/**/*.js', included: false}, {pattern: 'bower_components/**/*.css', inclu...
config.set({ basePath: '',
random_line_split
question_cli.py
#!/usr/bin/env python # # License: MIT # from __future__ import absolute_import, division, print_function ############################################################################## # Imports ############################################################################## import os import sys import argparse import ...
logger = logging.getLogger("question") answer = ros1_pytemplate.Answer(6) logger.info(answer.retrieve())
print("ROS1 pytemplate version " + ros1_pytemplate.__version__ + "\n from " + ros1_pytemplate.__file__) sys.exit(0)
conditional_block
question_cli.py
#!/usr/bin/env python # # License: MIT # from __future__ import absolute_import, division, print_function ############################################################################## # Imports ############################################################################## import os import sys import argparse import ...
(cmd=None): cmd = os.path.relpath(sys.argv[0], os.getcwd()) if cmd is None else cmd return "{0} [-h|--help] [--version]".format(cmd) def show_epilog(): return "never enough testing" ############################################################################## # Main #####################################...
show_usage
identifier_name
question_cli.py
#!/usr/bin/env python # # License: MIT # from __future__ import absolute_import, division, print_function ############################################################################## # Imports ############################################################################## import os import sys import argparse import ...
usage=show_usage(), epilog=show_epilog(), formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--version", action='store_true', help="display the version number and exits.") p...
############################################################################## if __name__ == '__main__': # Ref : https://docs.python.org/2/library/argparse parser = argparse.ArgumentParser(description=show_description(),
random_line_split
question_cli.py
#!/usr/bin/env python # # License: MIT # from __future__ import absolute_import, division, print_function ############################################################################## # Imports ############################################################################## import os import sys import argparse import ...
############################################################################## # Main ############################################################################## if __name__ == '__main__': # Ref : https://docs.python.org/2/library/argparse parser = argparse.ArgumentParser(description=show_description(), ...
return "never enough testing"
identifier_body
evenly_discretized.py
# The Hazard Library # Copyright (C) 2012-2014, GEM Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. ...
:param occurrence_rates: The list of non-negative float values representing the actual annual occurrence rates. The resulting histogram has as many bins as this list length. """ MODIFICATIONS = set(('set_mfd',)) _slots_ = 'min_mag bin_width occurrence_rates'.split() def __in...
:param bin_width: A positive float value -- the width of a single histogram bin.
random_line_split
evenly_discretized.py
# The Hazard Library # Copyright (C) 2012-2014, GEM Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. ...
self.check_constraints() def check_constraints(self): """ Checks the following constraints: * Bin width is positive. * Occurrence rates list is not empty. * Each number in occurrence rates list is non-negative. * Minimum magnitude is positive. """ ...
""" Evenly discretized MFD is defined as a precalculated histogram. :param min_mag: Positive float value representing the middle point of the first bin in the histogram. :param bin_width: A positive float value -- the width of a single histogram bin. :param occurrence_rates: ...
identifier_body
evenly_discretized.py
# The Hazard Library # Copyright (C) 2012-2014, GEM Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. ...
if not any(value > 0 for value in self.occurrence_rates): raise ValueError('at least one occurrence rate must be positive') if not self.min_mag >= 0: raise ValueError('minimum magnitude must be non-negative') def get_annual_occurrence_rates(self): """ Retu...
raise ValueError('all occurrence rates must not be negative')
conditional_block
evenly_discretized.py
# The Hazard Library # Copyright (C) 2012-2014, GEM Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. ...
(self, min_mag, bin_width, occurrence_rates): self.min_mag = min_mag self.bin_width = bin_width self.occurrence_rates = occurrence_rates self.check_constraints() def check_constraints(self): """ Checks the following constraints: * Bin width is positive. ...
__init__
identifier_name
TotemTracker.tsx
import Analyzer, { Options, SELECTED_PLAYER, SELECTED_PLAYER_PET } from 'parser/core/Analyzer'; import Events, { CastEvent, DeathEvent, FightEndEvent, SummonEvent } from 'parser/core/Events'; import Combatants from 'parser/shared/modules/Combatants'; import * as SPELLS from '../../SPELLS'; import { AllTotemsFilter, ...
totemSummoned(event: SummonEvent) { const totemSpellId = event.ability.guid; const totemName = event.ability.name; const totemElement = GetTotemElement(totemSpellId); if (!totemElement) { return; } this.markTotemAsDismissed(totemElement, event.timestamp, event.type); this.totemEl...
{ super(options); this.addEventListener( Events.summon.by(SELECTED_PLAYER).spell(AllTotemsFilter()), this.totemSummoned, ); this.addEventListener(Events.death.to(SELECTED_PLAYER_PET), this.totemDeathEvent); this.addEventListener(Events.cast, this.totemCastEvent); this.addEventLis...
identifier_body
TotemTracker.tsx
import Analyzer, { Options, SELECTED_PLAYER, SELECTED_PLAYER_PET } from 'parser/core/Analyzer'; import Events, { CastEvent, DeathEvent, FightEndEvent, SummonEvent } from 'parser/core/Events'; import Combatants from 'parser/shared/modules/Combatants'; import * as SPELLS from '../../SPELLS'; import { AllTotemsFilter, ...
(totemIdOrElement: TotemElements | number) { if (Number.isInteger(totemIdOrElement)) { const totemId = totemIdOrElement as number; if (this.totemEvents(totemId).length === 0) { return 0; } return this.totemEvents(totemId) .map((event) => event.duration || 0) .reduce((...
totalTotemUptime
identifier_name
TotemTracker.tsx
import Analyzer, { Options, SELECTED_PLAYER, SELECTED_PLAYER_PET } from 'parser/core/Analyzer'; import Events, { CastEvent, DeathEvent, FightEndEvent, SummonEvent } from 'parser/core/Events'; import Combatants from 'parser/shared/modules/Combatants'; import * as SPELLS from '../../SPELLS'; import { AllTotemsFilter, ...
Events.summon.by(SELECTED_PLAYER).spell(AllTotemsFilter()), this.totemSummoned, ); this.addEventListener(Events.death.to(SELECTED_PLAYER_PET), this.totemDeathEvent); this.addEventListener(Events.cast, this.totemCastEvent); this.addEventListener( Events.cast.by(SELECTED_PLAYER).spell...
constructor(options: Options) { super(options); this.addEventListener(
random_line_split
TotemTracker.tsx
import Analyzer, { Options, SELECTED_PLAYER, SELECTED_PLAYER_PET } from 'parser/core/Analyzer'; import Events, { CastEvent, DeathEvent, FightEndEvent, SummonEvent } from 'parser/core/Events'; import Combatants from 'parser/shared/modules/Combatants'; import * as SPELLS from '../../SPELLS'; import { AllTotemsFilter, ...
const totemEvent: TotemEvent = this.totemElementEvents[element][ this.totemElementEvents[element].length - 1 ]; const possibleDuration: number = timestamp - totemEvent.summonedAt; const maxDuration: number = (TotemDurations as any)[totemEvent.totemSpellId] as number; const duration = Math.mi...
{ return; }
conditional_block
reducer_test.ts
import { fakeState } from "../../__test_support__/fake_state"; import { overwrite, refreshStart, refreshOK, refreshNO } from "../../api/crud"; import { SpecialStatus, TaggedSequence, TaggedDevice, ResourceName, TaggedResource, TaggedTool, } from "farmbot"; import { buildResourceIndex } from "../../__test_su...
const startingState = fakeState().resources; const uuid = Object.keys(startingState.index.byKind.Tool)[0]; const action = { type: Actions._RESOURCE_NO, payload: { uuid, err: "Whatever", statusBeforeError: SpecialStatus.DIRTY } }; const newState = resourceReducer(startingState, action); ...
it("handles resource failures", () => {
random_line_split
ConvexPolygon.d.ts
import { Color } from '../Drawing/Color'; import { BoundingBox } from './BoundingBox'; import { CollisionContact } from './CollisionContact'; import { CollisionShape } from './CollisionShape'; import { Vector, Line, Ray, Projection } from '../Algebra'; import { Collider } from './Collider'; export interface ConvexPolyg...
* Get the axis aligned bounding box for the polygon shape in local coordinates */ get localBounds(): BoundingBox; /** * Get the moment of inertia for an arbitrary polygon * https://en.wikipedia.org/wiki/List_of_moments_of_inertia */ get inertia(): number; /** * Casts a ray ...
random_line_split
ConvexPolygon.d.ts
import { Color } from '../Drawing/Color'; import { BoundingBox } from './BoundingBox'; import { CollisionContact } from './CollisionContact'; import { CollisionShape } from './CollisionShape'; import { Vector, Line, Ray, Projection } from '../Algebra'; import { Collider } from './Collider'; export interface ConvexPolyg...
implements CollisionShape { offset: Vector; points: Vector[]; /** * Collider associated with this shape */ collider?: Collider; private _transformedPoints; private _axes; private _sides; constructor(options: ConvexPolygonOptions); /** * Returns a clone of this ConvexP...
ConvexPolygon
identifier_name
hgid.rs
bytes")]` (current default) /// - `#[serde(with = "types::serde_with::hgid::hex")]` /// - `#[serde(with = "types::serde_with::hgid::tuple")]` /// /// Using them can change the size or the type of serialization result: /// /// | lib \ serde_with | hgid::tuple | hgid::bytes | hgid::hex | /// |------------------|...
() { HgId::from_slice(&[0u8; 25]).expect_err("bad slice length"); } #[test] fn test_serde_with_using_cbor() { // Note: this test is for CBOR.
test_incorrect_length
identifier_name
hgid.rs
")]` (current default) /// - `#[serde(with = "types::serde_with::hgid::hex")]` /// - `#[serde(with = "types::serde_with::hgid::tuple")]` /// /// Using them can change the size or the type of serialization result: /// /// | lib \ serde_with | hgid::tuple | hgid::bytes | hgid::hex | /// |------------------|-----...
#[cfg(any(test, feature = "for-tests"))] pub fn random(rng: &mut dyn RngCore) -> Self { let mut bytes = [0; HgId::len()]; rng.fill_bytes(&mut bytes); loop { let hgid = HgId::from(&bytes); if !hgid.is_null() { return hgid; } } ...
{ // Parents must be hashed in sorted order. let (p1, p2) = match parents.into_nodes() { (p1, p2) if p1 > p2 => (p2, p1), (p1, p2) => (p1, p2), }; let mut hasher = Sha1::new(); hasher.input(p1.as_ref()); hasher.input(p2.as_ref()); hasher.i...
identifier_body
hgid.rs
")]` (current default) /// - `#[serde(with = "types::serde_with::hgid::hex")]` /// - `#[serde(with = "types::serde_with::hgid::tuple")]` /// /// Using them can change the size or the type of serialization result: /// /// | lib \ serde_with | hgid::tuple | hgid::bytes | hgid::hex | /// |------------------|-----...
} nodes } } impl<'a> From<&'a [u8; HgId::len()]> for HgId { fn from(bytes: &[u8; HgId::len()]) -> HgId { HgId::from_byte_array(bytes.clone()) } } pub trait WriteHgIdExt { /// Write a ``HgId`` directly to a stream. /// /// # Examples /// /// ``` /// use type...
{ nodeset.insert(hgid.clone()); nodes.push(hgid); }
conditional_block
hgid.rs
bytes")]` (current default) /// - `#[serde(with = "types::serde_with::hgid::hex")]` /// - `#[serde(with = "types::serde_with::hgid::tuple")]` /// /// Using them can change the size or the type of serialization result: /// /// | lib \ serde_with | hgid::tuple | hgid::bytes | hgid::hex | /// |------------------|...
use super::*; #[test] fn test_incorrect_length() { HgId::from_slice(&[0u8; 25]).expect_err("bad slice length"); } #[test] fn test_serde_with_using_cbor() { // Note: this test is for CBOR.
mod tests { use quickcheck::quickcheck; use serde::Deserialize; use serde::Serialize;
random_line_split
plot_string_subst_bar.py
# Plotting performance of string_subst_.py scripts # bar chart of relative comparison with variances as error bars import numpy as np import matplotlib.pyplot as plt
scripts = ['string_subst_1.py', 'string_subst_2.py', 'string_subst_3.py'] x_pos = np.arange(len(scripts)) plt.bar(x_pos, performance, yerr=variance, align='center', alpha=0.5) plt.xticks(x_pos, scripts) plt.axhline(y=1, linestyle='--', color='black') plt.ylim([0,12]) plt.ylabel('rel. performance gain') plt.title('St...
performance = [10.3882388499416,1,10.3212281215746] variance = [0.790435196936213,0,0.827207394592818]
random_line_split
_tools.py
to a class:`pint.Unit`. It also handles converting data returns to be instances of class:`pint.Quantity` rather than bare (unit-less) arrays. """ def __init__(self, var): r"""Construct a new :class:`UnitLinker`. Parameters ---------- var : Variable The :class:...
(self, s): """Parse bytes and return a namedtuple.""" return self._create(super(NamedStruct, self).unpack(s)) def unpack_from(self, buff, offset=0): """Read bytes from a buffer and return as a namedtuple.""" return self._create(super(NamedStruct, self).unpack_from(buff, offset)) ...
unpack
identifier_name
_tools.py
to a class:`pint.Unit`. It also handles converting data returns to be instances of class:`pint.Quantity` rather than bare (unit-less) arrays. """ def __init__(self, var): r"""Construct a new :class:`UnitLinker`. Parameters ---------- var : Variable The :class:...
def read_struct(self, struct_class): """Parse and return a structure from the current buffer offset.""" struct = struct_class.unpack_from(bytearray_to_buff(self._data), self._offset) self.skip(struct_class.size) return struct def read_func(self, func, num_bytes=None): ...
"""Replace the data after the marked location with the specified data.""" self.jump_to(mark) self._data = self._data[:self._offset] + bytearray(newdata)
identifier_body
_tools.py
from collections import namedtuple import gzip import logging from struct import Struct import zlib from ..units import UndefinedUnitError, units log = logging.getLogger(__name__) # This works around problems on early Python 2.7 where Struct.unpack_from() can't handle # being given a bytearray; use memoryview on Py...
from __future__ import print_function import bz2
random_line_split
_tools.py
to a class:`pint.Unit`. It also handles converting data returns to be instances of class:`pint.Quantity` rather than bare (unit-less) arrays. """ def __init__(self, var): r"""Construct a new :class:`UnitLinker`. Parameters ---------- var : Variable The :class:...
else: self._unit = units(val) class NamedStruct(Struct): """Parse bytes using :class:`Struct` but provide named fields.""" def __init__(self, info, prefmt='', tuple_name=None): """Initialize the NamedStruct.""" if tuple_name is None: tuple_name = 'NamedStruct'...
self._unit = val
conditional_block
types.d.ts
/// <reference types="node" /> import { IRouter, Request, Response } from 'express'; import { Readable } from 'stream'; export declare type PathParams = string | RegExp | Array<string | RegExp>; export declare type CacheOptions = { private?: boolean; public?: boolean; noStore?: boolean; noCache?: boolea...
formatResults?: (context: SutroRequest, req: Request, resource: ResourceRoot, rawData: any) => void; trace?: Trace; }; export interface SutroRouter extends IRouter { swagger?: Swagger; meta?: Meta; base?: string; } export declare type ResponseStatusKeys = 'default' | '200' | '201' | '204' | '401' | ...
random_line_split
matcher.rs
#![feature(test)] extern crate rff; extern crate test; use test::Bencher; use rff::matcher::matches; #[bench] fn bench_matches(b: &mut Bencher) { b.iter(|| matches("amor", "app/models/order.rb")) } #[bench] fn bench_matches_utf8(b: &mut Bencher) { b.iter(|| matches("รŸ", "WEIแบž")) } #[bench] fn bench_matches...
&mut Bencher) { b.iter(|| matches("app/models", "app/models/order.rb")) } #[bench] fn bench_matches_mixed_case(b: &mut Bencher) { b.iter(|| matches("AMOr", "App/Models/Order.rb")) } #[bench] fn bench_matches_multiple(b: &mut Bencher) { b.iter(|| { matches("amor", "app/models/order.rb"); ma...
h_matches_more_specific(b:
identifier_name
matcher.rs
#![feature(test)] extern crate rff; extern crate test; use test::Bencher; use rff::matcher::matches; #[bench] fn bench_matches(b: &mut Bencher) { b.iter(|| matches("amor", "app/models/order.rb")) }
fn bench_matches_utf8(b: &mut Bencher) { b.iter(|| matches("รŸ", "WEIแบž")) } #[bench] fn bench_matches_mixed(b: &mut Bencher) { b.iter(|| matches("abc", "abร˜")) } #[bench] fn bench_matches_more_specific(b: &mut Bencher) { b.iter(|| matches("app/models", "app/models/order.rb")) } #[bench] fn bench_matches_m...
#[bench]
random_line_split
matcher.rs
#![feature(test)] extern crate rff; extern crate test; use test::Bencher; use rff::matcher::matches; #[bench] fn bench_matches(b: &mut Bencher) { b.iter(|| matches("amor", "app/models/order.rb")) } #[bench] fn bench_matches_utf8(b: &mut Bencher) { b.iter(|| matches("รŸ", "WEIแบž")) } #[bench] fn bench_matches...
bench] fn bench_matches_eq(b: &mut Bencher) { b.iter(|| { matches("Gemfile", "Gemfile"); matches("gemfile", "Gemfile") }) }
b.iter(|| { matches("amor", "app/models/order.rb"); matches("amor", "spec/models/order_spec.rb"); matches("amor", "other_garbage.rb"); matches("amor", "Gemfile"); matches("amor", "node_modules/test/a/thing.js"); matches("amor", "vendor/bundle/ruby/gem.rb") }) } #[
identifier_body
translate-provider.js
'use strict'; var storageKey = 'VN_TRANSLATE'; // ReSharper disable once InconsistentNaming function Translate($translate, $translatePartialLoader, storage, options, disableTranslations) { this.$translate = $translate; this.$translatePartialLoader = $translatePartialLoader; this.storage = storage; this.disableTra...
urlTemplate: '/translations/{part}/{lang}.json' }); if (lang === 'en') { $translateProvider.useMessageFormatInterpolation(); } $translateProvider.useMissingTranslationHandlerLog(); $translateProvider.useLocalStorage(); }; angular.module('Volusion.toolboxCommon') .provider('translate', ['$translateProvider', ...
random_line_split
translate-provider.js
'use strict'; var storageKey = 'VN_TRANSLATE'; // ReSharper disable once InconsistentNaming function
($translate, $translatePartialLoader, storage, options, disableTranslations) { this.$translate = $translate; this.$translatePartialLoader = $translatePartialLoader; this.storage = storage; this.disableTranslations = disableTranslations; this.configure(angular.extend(options, this.getConfig())); this.addPart = $tr...
Translate
identifier_name
translate-provider.js
'use strict'; var storageKey = 'VN_TRANSLATE'; // ReSharper disable once InconsistentNaming function Translate($translate, $translatePartialLoader, storage, options, disableTranslations) { this.$translate = $translate; this.$translatePartialLoader = $translatePartialLoader; this.storage = storage; this.disableTra...
var loader = this.$translatePartialLoader; angular.forEach(arguments, function(part) { loader.addPart(part); }); return this.$translate.refresh(); }; function TranslateProvider($translateProvider) { this.$translateProvider = $translateProvider; this.setPreferredLanguage = $translateProvider.preferredLangu...
{ return true; }
conditional_block
translate-provider.js
'use strict'; var storageKey = 'VN_TRANSLATE'; // ReSharper disable once InconsistentNaming function Translate($translate, $translatePartialLoader, storage, options, disableTranslations) { this.$translate = $translate; this.$translatePartialLoader = $translatePartialLoader; this.storage = storage; this.disableTra...
TranslateProvider.prototype.$get = [ '$translate', '$translatePartialLoader', 'storage', function($translate, $translatePartialLoader, storage) { var options = this.options; return new Translate($translate, $translatePartialLoader, storage, { region: options.region, lang: options.lang, country: option...
{ this.$translateProvider = $translateProvider; this.setPreferredLanguage = $translateProvider.preferredLanguage; }
identifier_body
Xml.js
'users.xml', reader: { type: 'xml', record: 'user' } } }); </code></pre> * * <p>The example above creates a 'User' model. Models are explained in the {@link Ext.data.Model Model} docs if you're * not already familiar with them.</p> * * <p>We created the simplest type of...
response: response, msg: 'XML data not found in the response' }); } //</debug> return xml; }, /** * Normalizes the data object * @param {Object} data The raw data object * @return {Object} Returns the documentElement property o...
random_line_split
Xml.js
users.xml', reader: { type: 'xml', record: 'user' } } }); </code></pre> * * <p>The example above creates a 'User' model. Models are explained in the {@link Ext.data.Model Model} docs if you're * not already familiar with them.</p> * * <p>We created the simplest type of X...
}, /** * @private * We're just preparing the data for the superclass by pulling out the record nodes we want * @param {XMLElement} root The XML root node * @return {Ext.data.Model[]} The records */ extractData: function(root) { var recordName = this.record; //<deb...
{ // This fix ensures we have XML data // Related to TreeStore calling getRoot with the root node, which isn't XML // Probably should be resolved in TreeStore at some point return Ext.DomQuery.selectNode(root, data); }
conditional_block
complaint.component.ts
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ import { environment } from '../../environments/environment' import { ComplaintService } from '../Services/complaint.service' import { UserService } from '../Services/user.service' import { Component, ElementRef, OnInit, ViewChild } fr...
implements OnInit { public customerControl: FormControl = new FormControl({ value: '', disabled: true }, []) public messageControl: FormControl = new FormControl('', [Validators.required, Validators.maxLength(160)]) @ViewChild('fileControl', { static: true }) fileControl!: ElementRef // For controlling the DOM E...
ComplaintComponent
identifier_name
complaint.component.ts
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ import { environment } from '../../environments/environment' import { ComplaintService } from '../Services/complaint.service' import { UserService } from '../Services/user.service' import { Component, ElementRef, OnInit, ViewChild } fr...
save () { if (this.uploader.queue[0]) { this.uploader.queue[0].upload() this.fileControl.nativeElement.value = null } else { this.saveComplaint() } } saveComplaint () { this.complaint.message = this.messageControl.value this.complaintService.save(this.complaint).subscribe((s...
console.log(err) }) }
random_line_split
complaint.component.ts
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ import { environment } from '../../environments/environment' import { ComplaintService } from '../Services/complaint.service' import { UserService } from '../Services/user.service' import { Component, ElementRef, OnInit, ViewChild } fr...
} saveComplaint () { this.complaint.message = this.messageControl.value this.complaintService.save(this.complaint).subscribe((savedComplaint: any) => { this.translate.get('CUSTOMER_SUPPORT_COMPLAINT_REPLY', { ref: savedComplaint.id }).subscribe((customerSupportReply) => { this.confirmation =...
{ this.saveComplaint() }
conditional_block
main.rs
/* Aurรฉlien DESBRIรˆRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” // Std Library Option โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ // An integer division that doesn't `panic!` fn checked_division(dividend: i32, divisor: i32) -> Option<i32> { if di
// Failure is represented as the `None` variant None } else { // Result is wrapped in a `Some` variant Some(dividend / divisor) } } // This function handles a division that may not succeed fn try_division(dividend: i32, divisor: i32) { // `Option` values can be pattern matched,...
visor == 0 {
identifier_name
main.rs
/* Aurรฉlien DESBRIรˆRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” // Std Library Option โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ // An integer division that doesn't `panic!` fn checked_division(dividend: i32, divisor: i32) -> Option<i32> { if divisor == 0 { // Failure is r...
// Binding `None` to a variable needs to be type annotated let none: Option<i32> = None; let _equivalent_none = None::<i32>; let optional_float = Some(0f32); // Unwrapping a `Some` variant will extract the value wrapped. println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap())...
}, } } fn main() { try_division(4, 2); try_division(1, 0);
conditional_block
main.rs
/* Aurรฉlien DESBRIรˆRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” // Std Library Option โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ // An integer division that doesn't `panic!` fn checked_division(dividend: i32, divisor: i32) -> Option<i32> { if divisor == 0 { // Failure is r...
} } // This function handles a division that may not succeed fn try_division(dividend: i32, divisor: i32) { // `Option` values can be pattern matched, just like other enums match checked_division(dividend, divisor) { None => println!("{} / {} failed!", dividend, divisor), Some(quotient) => ...
// Result is wrapped in a `Some` variant Some(dividend / divisor)
random_line_split
main.rs
/* Aurรฉlien DESBRIรˆRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” // Std Library Option โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ // An integer division that doesn't `panic!` fn checked_division(dividend: i32, divisor: i32) -> Option<i32> { if divisor == 0 { // Failure is r...
nding `None` to a variable needs to be type annotated let none: Option<i32> = None; let _equivalent_none = None::<i32>; let optional_float = Some(0f32); // Unwrapping a `Some` variant will extract the value wrapped. println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap()); //...
match checked_division(dividend, divisor) { None => println!("{} / {} failed!", dividend, divisor), Some(quotient) => { println!("{} / {} = {}", dividend, divisor, quotient) }, } } fn main() { try_division(4, 2); try_division(1, 0); // Bi
identifier_body
microphone-outline.js
import React from 'react' import Icon from 'react-icon-base' const TiMicrophoneOutline = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m20 26.7c-3.7 0-6.7-3-6.7-6.7v-10c0-3.7 3-6.7 6.7-6.7s6.7 3 6.7 6.7v10c0 3.7-3 6.7-6.7 6.7z m0-20c-1.8 0-3.3 1.5-3.3 3.3v10c0 1.8 1.5 3.3 3.3 3.3s3.3-1.5 3.3...
) export default TiMicrophoneOutline
random_line_split
regions-early-bound-used-in-bound-method.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 ...
} pub fn main() { let b1 = Box { t: &3 }; assert_eq!(b1.add(b1), 6); }
{ *self.t + *g2.get() }
identifier_body
regions-early-bound-used-in-bound-method.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// <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. // Tests that you can use a fn lifetime parameter as part of // the value for a type parameter in a bound. trait GetRef<'a> { fn get(&self) -> &'a in...
// 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
random_line_split
regions-early-bound-used-in-bound-method.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 ...
<'a> { t: &'a int } impl<'a> Copy for Box<'a> {} impl<'a> GetRef<'a> for Box<'a> { fn get(&self) -> &'a int { self.t } } impl<'a> Box<'a> { fn add<'b,G:GetRef<'b>>(&self, g2: G) -> int { *self.t + *g2.get() } } pub fn main() { let b1 = Box { t: &3 }; assert_eq!(b1.add(b1)...
Box
identifier_name
lib.rs
//! # r2d2-mysql //! MySQL support for the r2d2 connection pool (Rust) . see [`r2d2`](http://github.com/sfackler/r2d2.git) . //! //! #### Install //! Just include another `[dependencies.*]` section into your Cargo.toml: //! //! ```toml //! [dependencies.r2d2_mysql] //! git = "https://github.com/outersky/r2d2-mysql" //...
() { let url = env::var("DATABASE_URL").unwrap(); let opts = Opts::from_url(&url).unwrap(); let builder = OptsBuilder::from_opts(opts); let manager = MysqlConnectionManager::new(builder); let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap()); let...
query_pool
identifier_name
lib.rs
//! # r2d2-mysql //! MySQL support for the r2d2 connection pool (Rust) . see [`r2d2`](http://github.com/sfackler/r2d2.git) . //! //! #### Install //! Just include another `[dependencies.*]` section into your Cargo.toml: //! //! ```toml //! [dependencies.r2d2_mysql] //! git = "https://github.com/outersky/r2d2-mysql" //...
.unwrap(); let _ = conn.query("SELECT version()").map(|_: Vec<String>| ()).map_err(|err| { println!("execute query error in line:{} ! error: {:?}", line!(), err) }); }); tasks.push(th); } for th in tasks { ...
{ let url = env::var("DATABASE_URL").unwrap(); let opts = Opts::from_url(&url).unwrap(); let builder = OptsBuilder::from_opts(opts); let manager = MysqlConnectionManager::new(builder); let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap()); let mu...
identifier_body
lib.rs
//! # r2d2-mysql //! MySQL support for the r2d2 connection pool (Rust) . see [`r2d2`](http://github.com/sfackler/r2d2.git) . //! //! #### Install //! Just include another `[dependencies.*]` section into your Cargo.toml: //! //! ```toml //! [dependencies.r2d2_mysql] //! git = "https://github.com/outersky/r2d2-mysql" //...
//! ``` //! #![doc(html_root_url = "http://outersky.github.io/r2d2-mysql/doc/v0.2.0/r2d2_mysql/")] #![crate_name = "r2d2_mysql"] #![crate_type = "rlib"] #![crate_type = "dylib"] pub extern crate mysql; pub extern crate r2d2; pub mod pool; pub use pool::MysqlConnectionManager; #[cfg(test)] mod test { use mysql::...
random_line_split
fi.py
# -*- coding: utf-8 -*- # $Id: fi.py 7119 2011-09-02 13:00:23Z milde $ # Author: Asko Soukka <asko.soukka@iki.fi> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files ...
'alaindeksi': 'subscript', 'indeksi': 'subscript', 'yl\u00e4indeksi': 'superscript', 'title-reference (translation required)': 'title-reference', 'title (translation required)': 'title-reference', 'pep-reference (translation required)': 'pep-reference', 'rfc-reference (translation required)'...
'kirjainsana': 'acronym', 'code (translation required)': 'code', 'hakemisto': 'index', 'luettelo': 'index',
random_line_split
build.rs
#[cfg(feature = "with-syntex")] mod inner { extern crate syntex; extern crate syntex_syntax as syntax; use std::env; use std::path::Path; use self::syntax::codemap::Span; use self::syntax::ext::base::{self, ExtCtxt}; use self::syntax::tokenstream::TokenTree; pub fn main() { le...
($macro_name: ident, $name: ident) => { fn $name<'cx>( cx: &'cx mut ExtCtxt, sp: Span, tts: &[TokenTree], ) -> Box<base::MacResult + 'cx> { syntax::ext::quote::$name(cx, sp, tts) }...
macro_rules! register_quote_macro {
random_line_split
build.rs
#[cfg(feature = "with-syntex")] mod inner { extern crate syntex; extern crate syntex_syntax as syntax; use std::env; use std::path::Path; use self::syntax::codemap::Span; use self::syntax::ext::base::{self, ExtCtxt}; use self::syntax::tokenstream::TokenTree; pub fn main() { le...
} fn main() { inner::main(); }
{}
identifier_body
build.rs
#[cfg(feature = "with-syntex")] mod inner { extern crate syntex; extern crate syntex_syntax as syntax; use std::env; use std::path::Path; use self::syntax::codemap::Span; use self::syntax::ext::base::{self, ExtCtxt}; use self::syntax::tokenstream::TokenTree; pub fn
() { let out_dir = env::var_os("OUT_DIR").unwrap(); let mut registry = syntex::Registry::new(); macro_rules! register_quote_macro { ($macro_name: ident, $name: ident) => { fn $name<'cx>( cx: &'cx mut ExtCtxt, sp: Span, ...
main
identifier_name
AddForm.tsx
import { randomUUID } from 'node:crypto'; import { Fragment, useState, type ReactElement, type Dispatch as D, type SetStateAction as S, type MouseEvent } from 'react'; import { useDispatch } from 'react-redux'; import type { Dispatch } from '@reduxjs/toolkit'; import { Button, Form, Modal, Input } from 'antd'; import t...
let formValue: Store; try { formValue = await form.validateFields(); } catch (err) { return console.error(err); } dispatch(IDBSaveBilibiliLiveList({ data: { ...formValue, id: randomUUID() } })); setVisible(false); } // ๅ…ณ้—ญ็ช—ๅฃๅŽ้‡็ฝฎ่กจๅ• function handl...
const [visible, setVisible]: [boolean, D<S<boolean>>] = useState(false); // ๆทปๅŠ ไธ€ไธช็›ดๆ’ญ้—ด async function handleAddRoomIdClick(event: MouseEvent<HTMLButtonElement>): Promise<void> {
random_line_split
AddForm.tsx
import { randomUUID } from 'node:crypto'; import { Fragment, useState, type ReactElement, type Dispatch as D, type SetStateAction as S, type MouseEvent } from 'react'; import { useDispatch } from 'react-redux'; import type { Dispatch } from '@reduxjs/toolkit'; import { Button, Form, Modal, Input } from 'antd'; import t...
e); } return ( <Fragment> <Button type="primary" onClick={ handleOpenAddModalClick }>ๆทปๅŠ ็›ดๆ’ญ้—ดไฟกๆฏ</Button> <Modal title="ๆทปๅŠ B็ซ™็›ดๆ’ญ้—ดไฟกๆฏ" visible={ visible } width={ 500 } afterClose={ handleAddModalClose } onOk={ handleAddRoomIdClick } onCancel={ handleCloseAddModalCli...
id { setVisible(fals
identifier_name
AddForm.tsx
import { randomUUID } from 'node:crypto'; import { Fragment, useState, type ReactElement, type Dispatch as D, type SetStateAction as S, type MouseEvent } from 'react'; import { useDispatch } from 'react-redux'; import type { Dispatch } from '@reduxjs/toolkit'; import { Button, Form, Modal, Input } from 'antd'; import t...
k(event: MouseEvent<HTMLButtonElement>): void { setVisible(true); } // ๅ…ณ้—ญๅผนๅ‡บๅฑ‚ function handleCloseAddModalClick(event: MouseEvent<HTMLButtonElement>): void { setVisible(false); } return ( <Fragment> <Button type="primary" onClick={ handleOpenAddModalClick }>ๆทปๅŠ ็›ดๆ’ญ้—ดไฟกๆฏ</Button> <Modal tit...
nction handleOpenAddModalClic
identifier_body
jcarousel.responsive.js
(function($) { $(function() { var jcarousel = $('.jcarousel'); jcarousel .on('jcarousel:reload jcarousel:create', function () { var width = jcarousel.innerWidth(); if (width >= 600)
else if (width >= 350) { width = width / 2; } jcarousel.jcarousel('items').css('width', width + 'px'); }) .jcarousel({ wrap: 'circular' }); $('.jcarousel-control-prev') .jcarouselControl({ ...
{ width = width / 3; }
conditional_block