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
build.rs
extern crate serde_codegen; extern crate serde_json; extern crate glob; use std::env; use std::fs; use std::path::Path; /// generate an enum of Events fn
() { for entry in glob::glob("src/**/*.rs.in").expect("Failed to read glob pattern") { println!("cargo:rerun-if-changed={}", entry.unwrap().display()); } let out_dir = env::var_os("OUT_DIR").unwrap(); // Switch to our `src` directory so that we have the right base for our // globs, and so ...
main
identifier_name
index.js
/*! * ear-pipe * Pipe audio streams to your ears * Dan Motzenbecker <dan@oxism.com>
* MIT Licensed */ "use strict"; var spawn = require('child_process').spawn, util = require('util'), Duplex = require('stream').Duplex, apply = function(obj, method, args) { return obj[method].apply(obj, args); } var EarPipe = function(type, bits, transcode) { var params; if (!(this ...
random_line_split
index.js
/*! * ear-pipe * Pipe audio streams to your ears * Dan Motzenbecker <dan@oxism.com> * MIT Licensed */ "use strict"; var spawn = require('child_process').spawn, util = require('util'), Duplex = require('stream').Duplex, apply = function(obj, method, args) { return obj[method].apply(obj, args...
Duplex.apply(this); params = ['-q', '-b', bits || 16, '-t', type || 'mp3', '-']; if (transcode) { this.process = spawn('sox', params.concat(['-t', typeof transcode === 'string' ? transcode : 'wav', '-'])); } else { this.process = spawn('play', params); } } util.inherits(EarPipe, Duplex); E...
{ return new EarPipe(type, bits, transcode); }
conditional_block
woeidfromquery.py
import MySQLdb import urllib2, urllib, re, sys import xml from datetime import datetime ## gets woeid from query -helper function def getwoeid(searchstring): try: import xml.etree.ElementTree as ET namespaces = {'yweather': 'http://www.yahooapis.com/v1/base.rng'} # add more as needed #get records proxy = urll...
getwoeid(sys.argv[1])
conditional_block
woeidfromquery.py
import MySQLdb import urllib2, urllib, re, sys import xml from datetime import datetime ## gets woeid from query -helper function def getwoeid(searchstring):
except Exception as e: print '<>',e ## gets woeid from query -main program #takes searchstring as arg if __name__ == '__main__': getwoeid(sys.argv[1])
try: import xml.etree.ElementTree as ET namespaces = {'yweather': 'http://www.yahooapis.com/v1/base.rng'} # add more as needed #get records proxy = urllib2.ProxyHandler({'https': '10.10.78.62:3128','http': '10.10.78.62:3128'}) opener = urllib2.build_opener(proxy) urllib2.install_opener(opener) url = "http...
identifier_body
woeidfromquery.py
import MySQLdb import urllib2, urllib, re, sys import xml from datetime import datetime ## gets woeid from query -helper function def getwoeid(searchstring): try: import xml.etree.ElementTree as ET namespaces = {'yweather': 'http://www.yahooapis.com/v1/base.rng'} # add more as needed #get records proxy = urll...
cities = root.find('results').findall('Result') fcities = open('cities.txt', 'w') fwoeid = open('woeids.txt', 'w') for thiscity in cities: fcities.write(thiscity.find('city').text + ", " + thiscity.find('state').text + ", " + thiscity.find('country').text + "\n") fwoeid.write(thiscity.find('woeid').text +...
#root = ET.parse('data_city.xml').getroot()
random_line_split
woeidfromquery.py
import MySQLdb import urllib2, urllib, re, sys import xml from datetime import datetime ## gets woeid from query -helper function def
(searchstring): try: import xml.etree.ElementTree as ET namespaces = {'yweather': 'http://www.yahooapis.com/v1/base.rng'} # add more as needed #get records proxy = urllib2.ProxyHandler({'https': '10.10.78.62:3128','http': '10.10.78.62:3128'}) opener = urllib2.build_opener(proxy) urllib2.install_opener(open...
getwoeid
identifier_name
mod.rs
`down.sql`. //! `up.sql` will be used to run the migration, while `down.sql` will be used for reverting it. The //! folder itself should have the structure `{version}_{migration_name}`. It is recommended that //! you use the timestamp of creation for the version. //! //! ## Example //! //! ```text //! # Directory Stru...
fn previously_run_migration_versions<Conn>(conn: &Conn) -> QueryResult<HashSet<String>> where Conn: Connection, String: FromSql<VarChar, Conn::Backend>, { __diesel_schema_migrations.select(version) .load(conn) .map(|r| r.collect()) } fn latest_run_migration_version<Conn>(conn: &Conn) -> Q...
{ conn.silence_notices(|| { conn.execute("CREATE TABLE IF NOT EXISTS __diesel_schema_migrations ( version VARCHAR PRIMARY KEY NOT NULL, run_on TIMESTAMP NOT NULL DEFAULT 'now' )") }) }
identifier_body
mod.rs
and `down.sql`. //! `up.sql` will be used to run the migration, while `down.sql` will be used for reverting it. The //! folder itself should have the structure `{version}_{migration_name}`. It is recommended that //! you use the timestamp of creation for the version. //! //! ## Example //!
//! - 20160107082941_create_posts //! - up.sql //! - down.sql //! ``` //! //! ```sql //! -- 20151219180527_create_users/up.sql //! CREATE TABLE users ( //! id SERIAL PRIMARY KEY, //! name VARCHAR NOT NULL, //! hair_color VARCHAR //! ); //! ``` //! //! ```sql //! -- 20151219180527_create_users/down.sql //!...
//! ```text //! # Directory Structure //! - 20151219180527_create_users //! - up.sql //! - down.sql
random_line_split
mod.rs
`down.sql`. //! `up.sql` will be used to run the migration, while `down.sql` will be used for reverting it. The //! folder itself should have the structure `{version}_{migration_name}`. It is recommended that //! you use the timestamp of creation for the version. //! //! ## Example //! //! ```text //! # Directory Stru...
<Conn: Connection>(conn: &Conn, ver: &str, output: &mut Write) -> Result<(), RunMigrationsError> where for<'a> &'a NewMigration<'a>: Insertable<__diesel_schema_migrations, Conn::Backend>, { migration_with_version(ver) .map_err(|e| e.into()) .and_then(|m| run_migration(conn, m, output)) }...
run_migration_with_version
identifier_name
index.d.ts
// Type definitions for bootstrap-maxlength v1.7.0 // Project: https://github.com/mimo84/bootstrap-maxlength // Definitions by: Dan Manastireanu <https://github.com/danmana> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="jquery" /> declare namespace BootstrapMaxlength { ...
interface JQuery { /** Apply the maxlength plugin on the selected elemens */ maxlength(options?: BootstrapMaxlength.Options): JQuery; on(events: 'maxlength.shown', handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; on(events: 'maxlength.hidden', handler: (eventObject: JQueryEven...
}
random_line_split
page-manager-visualizator.js
2000, minWOuterScroll: 23, minHOuterScroll: 23, permanentVisible: true, minWDraggable: 15, minHDraggable: 15, minWIFrame: 320, minHIFrame: 480, $dimensions: undefined, responsiveToMovementOfTheCursorInAConfinedSpace: true, movementOfTheCursorInAConfinedSpaceSpred: 10, factor...
w_c = $outerWrap.width(); h_c = $outerWrap.height(); l = Math.round( (w_c - w) * l_factor ); t = Math.round( (h_c - h) * t_factor ); $fittingWrap.css({ top: t, left: l }); resizeIFrame._centerIFrameAndNoEmptySpace();//И так сработает пос...
var w, h, w_c, h_c, l, t; w = $fittingWrap.width(); h = $fittingWrap.height();
random_line_split
page-manager-visualizator.js
2000, minWOuterScroll: 23, minHOuterScroll: 23, permanentVisible: true, minWDraggable: 15, minHDraggable: 15, minWIFrame: 320, minHIFrame: 480, $dimensions: undefined, responsiveToMovementOfTheCursorInAConfinedSpace: true, movementOfTheCursorInAConfinedSpaceSpred: 10, factor...
} var w, h, w_c, h_c, l, t; w = $fittingWrap.width(); h = $fittingWrap.height(); w_c = $outerWrap.width(); h_c = $outerWrap.height(); l = Math.round( (w_c - w) * l_factor ); t = Math.round( (h_c - h) * t_factor ); $fittingWrap.css({ ...
} else { $fittingWrap = $container.find(" .pmv-fitting-wrap"); $outerWrap = $container.find(" .pmv-outer-wrap");
conditional_block
document_condition.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS C...
Err(()) } } #[cfg(feature = "gecko")] /// Evaluate a URL matching function. pub fn evaluate(&self, device: &Device) -> bool { let func = match *self { UrlMatchingFunction::Url(_) => GeckoUrlMatchingFunction::eURL, UrlMatchingFunction::UrlPrefix(_) => ...
Ok(UrlMatchingFunction::Url(url)) } else {
conditional_block
document_condition.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS C...
f, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { UrlMatchingFunction::Url(ref url) => { url.to_css(dest) }, UrlMatchingFunction::UrlPrefix(ref url_prefix) => { dest.write_str("url-prefix(")?; serialize...
>(&sel
identifier_name
document_condition.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS C...
cfg(not(feature = "gecko"))] /// Evaluate a URL matching function. pub fn evaluate(&self, _: &Device) -> bool { false } } impl ToCss for UrlMatchingFunction { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { UrlMatchingFunction::Ur...
let func = match *self { UrlMatchingFunction::Url(_) => GeckoUrlMatchingFunction::eURL, UrlMatchingFunction::UrlPrefix(_) => GeckoUrlMatchingFunction::eURLPrefix, UrlMatchingFunction::Domain(_) => GeckoUrlMatchingFunction::eDomain, UrlMatchingFunction::RegExp(_) => Geck...
identifier_body
document_condition.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS C...
}) } } impl UrlMatchingFunction { /// Parse a URL matching function for a`@document` rule's condition. pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<UrlMatchingFunction, ()> { if input.try(|input| input.expect_function_matching("url-prefix")).is_ok() { ...
while let Ok(_) = input.next() {} Ok($url_matching_function(input.slice_from(start).to_string())) })
random_line_split
api.ts
import { URLSearchParams } from 'url'; import Bugsnag from '@bugsnag/js'; import { sortArrayByObjectProperty } from '@ionaru/array-utils'; import { EVE, IMarketGroupData, IMarketHistoryData, IMarketOrdersData, IMarketOrdersDataUnit, IStatusData, IUniverseCategoryData, IUniverseGroupData...
return undefined; }; export const fetchCitadelData = async (): Promise<ICitadelData> => { const url = 'https://stop.hammerti.me.uk/api/citadel/all'; const citadelData = await fetchData<ICitadelData>(url); return citadelData || {}; }; export const fetchUniverseNames = async (ids: number[]): Promise<I...
{ if (type === 'sell') { const sellOrders = marketData.filter((entry) => !entry.is_buy_order); const sortedSellOrders: IMarketOrdersData = sortArrayByObjectProperty(sellOrders, (order) => order.price); return sortedSellOrders[0]; } else if (type === 'buy') { ...
conditional_block
api.ts
import { URLSearchParams } from 'url'; import Bugsnag from '@bugsnag/js'; import { sortArrayByObjectProperty } from '@ionaru/array-utils'; import { EVE, IMarketGroupData, IMarketHistoryData, IMarketOrdersData, IMarketOrdersDataUnit, IStatusData, IUniverseCategoryData, IUniverseGroupData...
return result?.data; }; export const fetchMarketData = async (itemId: number, regionId: number, orderType?: 'buy' | 'sell' | 'all'): Promise<IMarketOrdersData> => { const marketResponse = await fetchData<IMarketOrdersData>(EVE.getMarketOrdersUrl({ orderType, page: 1, regionId, t...
}, }) .catch((errorResponse) => captureRequestError(url, errorResponse));
random_line_split
hero-detail.component.ts
/** * Created by ivan on 17.09.16. */
import { ActivatedRoute, Params } from '@angular/router'; import { HeroService } from './hero.service'; import { Hero } from './hero'; @Component({ selector: 'my-hero-detail', templateUrl: 'app/hero-detail.component.html', styleUrls: ['app/hero-detail.component.css'] }) export class HeroDetailComponent...
import { Component, OnInit } from '@angular/core';
random_line_split
hero-detail.component.ts
/** * Created by ivan on 17.09.16. */ import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { HeroService } from './hero.service'; import { Hero } from './hero'; @Component({ selector: 'my-hero-detail', templateUrl: 'app/hero-detail.component.h...
implements OnInit { hero: Hero; constructor( private heroService: HeroService, private route: ActivatedRoute) { } ngOnInit(): void { this.route.params.forEach((params: Params) => { let id = +params['id']; this.heroService.getHero(id) .th...
HeroDetailComponent
identifier_name
nvic.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Harris <mail@bharr.is> // // 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 /...
(irqn: usize) { get_reg().iser[irqn / 32].clear_iser(irqn % 32); } /// Disable an interrupt pub fn disable_irq(irqn: usize) { get_reg().icer[irqn / 32].clear_icer(irqn % 32); } /// Return whether the given interrupt is enabled pub fn is_enabled(irqn: usize) -> bool { get_reg().iser[irqn / 32].iser(irqn % 32) } ...
enable_irq
identifier_name
nvic.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Harris <mail@bharr.is> // // 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 /...
/// Return whether the given interrupt is pending pub fn is_pending(irqn: usize) -> bool { get_reg().ispr[irqn / 32].ispr(irqn % 32) } /// Return whether the given interrupt is active pub fn is_active(irqn: usize) -> bool { get_reg().iabr[irqn / 32].iabr(irqn % 32) } /// Set the priority for the given interrupt...
{ get_reg().icpr[irqn / 32].clear_icpr(irqn % 32); }
identifier_body
nvic.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Harris <mail@bharr.is> // // 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 /...
0..8 => stir, } }); }
0x400 => reg32 ipr[8] { //! Interrupt priority register 0..31 => ipr[4], } 0xF00 => reg32 stir[8] { //! Software triggered interrupt register
random_line_split
lgt_spiders.py
-*- coding: UTF-8 -*- ##### ##### ===== 포함 파일 ===== # 개인적인 아이디, 비밀번호 파일. from personal.jconfig import LOGIN_ID, LOGIN_PW # scrapy item 파일. from joonggonara.items import JoonggonaraItem # 로그인을 위한 FormRequest. # 로그인 이후 크롤링을 위한 Request. from scrapy.http import FormRequest, Request # 게시판 페이지에서 각 게시글 url을 얻어온 후 url을 S...
e_num = re.split(r'[?=&]', response.url)[10] cur.execute('INSERT OR IGNORE INTO ' + DOWNLOADED_DB + ' (article_num) VALUES (' + str(article_num) + ')' ) conn.commit() # 수집한 게시글을 파일로 저장 with open(SAVE_LOCATION + article_num + '.html', 'wb') as f: f.write(response
global CRAWL_COUNT global MAX_PAGE global conn global cur # 수집한 게시글 다운로드 완료 리스트에 저장 articl
conditional_block
lgt_spiders.py
# -*- coding: UTF-8 -*- ##### ##### ===== 포함 파일 ===== # 개인적인 아이디, 비밀번호 파일. from personal.jconfig import LOGIN_ID, LOGIN_PW # scrapy item 파일. from joonggonara.items import JoonggonaraItem # 로그인을 위한 FormRequest. # 로그인 이후 크롤링을 위한 Request. from scrapy.http import FormRequest, Request # 게시판 페이지에서 각 게시글 url을 얻어온 후 url을 ...
채웠는지 체크 page_num = int(re.split(r'[=]', response.url)[8]) if ((CRAWL_COUNT >= CRAWL_TARGET) or (page_num >= MAX_PAGE)): return self.crawl_article() else: # 목표 개수 미달인 경우 다음 페이지 불러오기 next_url = BOARD_PAGE_URL + str(page_num+1) return Request(url=next_url, callback=self.parse_list) # 게시글 수집 def cra...
수 만큼 리스트를
identifier_name
lgt_spiders.py
-*- coding: UTF-8 -*- ##### ##### ===== 포함 파일 ===== # 개인적인 아이디, 비밀번호 파일. from personal.jconfig import LOGIN_ID, LOGIN_PW # scrapy item 파일. from joonggonara.items import JoonggonaraItem # 로그인을 위한 FormRequest. # 로그인 이후 크롤링을 위한 Request. from scrapy.http import FormRequest, Request # 게시판 페이지에서 각 게시글 url을 얻어온 후 url을 S...
# 참고: yield로 Request를 전송하기 때문에 cur가 동시에 사용될 가능성이 있다 # 따라서 fetchall()로 데이터를 모두 가져와야 한다 cur.execute('SELECT * FROM ' + LIST_DB) target_list = cur.fetchall() # Request 보내기 for data in target_list: # request_url 조립 article_num = data[0] request_url = ARTICLE_URL + str(article_num) # Request를 날리기 ...
)[8]) if ((CRAWL_COUNT >= CRAWL_TARGET) or (page_num >= MAX_PAGE)): return self.crawl_article() else: # 목표 개수 미달인 경우 다음 페이지 불러오기 next_url = BOARD_PAGE_URL + str(page_num+1) return Request(url=next_url, callback=self.parse_list) # 게시글 수집 def crawl_article(self): # 글로벌 변수를 불러옴 global CRAWL_TARGE...
identifier_body
lgt_spiders.py
# -*- coding: UTF-8 -*- ##### ##### ===== 포함 파일 ===== # 개인적인 아이디, 비밀번호 파일. from personal.jconfig import LOGIN_ID, LOGIN_PW # scrapy item 파일. from joonggonara.items import JoonggonaraItem # 로그인을 위한 FormRequest. # 로그인 이후 크롤링을 위한 Request. from scrapy.http import FormRequest, Request # 게시판 페이지에서 각 게시글 url을 얻어온 후 url을 ...
conn = None cur = None ##### ##### ===== 전역 변수 지역 끝 ===== ##### ##### ===== 프로젝트별 변수 ===== # 주요 변수 SPIDER_NAME = 'lgt' START_URL = 'http://nid.naver.com/nidlogin.login' BOARD_PAGE_URL = 'http://cafe.naver.com/ArticleList.nhn?search.boardtype=L&userDisplay=50&search.menuid=425&search.questionTab=A&search.clubid=100...
CRAWL_COUNT = 0 MAX_PAGE = 0 DOWNLOAD_DELAY = 2
random_line_split
interpolation-test.component.ts
import { Store } from '@ng-state/store'; import { ChangeDetectionStrategy, Component, ChangeDetectorRef } from '@angular/core'; import { ComponentState, HasStateActions } from '@ng-state/store'; import { ClearTodoMessage } from './../actions/todo.model'; import { Dispatcher } from '@ng-state/store'; import { Interpola...
} updateItem() { this.dispatcher.publish('update'); } clearHistory() { this.store.reset(); } updateSharedValue() { this.store.select(['shareTest']).update((state) => { state.set('testValue', Math.random()); }); } }
} updateDocList() { this.dispatcher.publish(new ClearTodoMessage());
random_line_split
interpolation-test.component.ts
import { Store } from '@ng-state/store'; import { ChangeDetectionStrategy, Component, ChangeDetectorRef } from '@angular/core'; import { ComponentState, HasStateActions } from '@ng-state/store'; import { ClearTodoMessage } from './../actions/todo.model'; import { Dispatcher } from '@ng-state/store'; import { Interpola...
() { this.store.reset(); } updateSharedValue() { this.store.select(['shareTest']).update((state) => { state.set('testValue', Math.random()); }); } }
clearHistory
identifier_name
interpolation-test.component.ts
import { Store } from '@ng-state/store'; import { ChangeDetectionStrategy, Component, ChangeDetectorRef } from '@angular/core'; import { ComponentState, HasStateActions } from '@ng-state/store'; import { ClearTodoMessage } from './../actions/todo.model'; import { Dispatcher } from '@ng-state/store'; import { Interpola...
updateSharedValue() { this.store.select(['shareTest']).update((state) => { state.set('testValue', Math.random()); }); } }
{ this.store.reset(); }
identifier_body
issue-662-part-2.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[derive(Clone, Copy, Debug)] pub struct RefPtr<T>(T); #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHolder<T> { pub a: T, pub _phantom_0: ::...
<U> { pub mPtr: RefPtr<nsMainThreadPtrHolder<U>>, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<U>>, } impl<U> Default for nsMainThreadPtrHandle<U> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } }
nsMainThreadPtrHandle
identifier_name
issue-662-part-2.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[derive(Clone, Copy, Debug)] pub struct RefPtr<T>(T); #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHolder<T> { pub a: T, pub _phantom_0: ::...
} #[repr(C)] pub struct nsMainThreadPtrHandle<U> { pub mPtr: RefPtr<nsMainThreadPtrHolder<U>>, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<U>>, } impl<U> Default for nsMainThreadPtrHandle<U> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } }
{ unsafe { ::std::mem::zeroed() } }
identifier_body
issue-662-part-2.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals
#[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHolder<T> { pub a: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>, } impl<T> Default for nsMainThreadPtrHolder<T> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] pub struct nsMa...
)] #[derive(Clone, Copy, Debug)] pub struct RefPtr<T>(T);
random_line_split
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import os import re import sys from setuptools import setup root_dir = os.path.abspath(os.path.dirname(__file__)) def get_version(package_name):
if sys.version_info[0:2] < (2, 7): # pragma: no cover test_loader = 'unittest2:TestLoader' else: test_loader = 'unittest:TestLoader' PACKAGE = 'factory' setup( name='factory_boy', version=get_version(PACKAGE), description="A versatile test fixtures replacement based on thoughtbot's factory_b...
version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$") package_components = package_name.split('.') init_path = os.path.join(root_dir, *(package_components + ['__init__.py'])) with codecs.open(init_path, 'r', 'utf-8') as f: for line in f: match = version_re.match(line[:-1]) ...
identifier_body
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import os import re import sys from setuptools import setup root_dir = os.path.abspath(os.path.dirname(__file__)) def get_version(package_name): version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$") package_components = package_name.spl...
return '0.1.0' if sys.version_info[0:2] < (2, 7): # pragma: no cover test_loader = 'unittest2:TestLoader' else: test_loader = 'unittest:TestLoader' PACKAGE = 'factory' setup( name='factory_boy', version=get_version(PACKAGE), description="A versatile test fixtures replacement based on tho...
return match.groups()[0]
conditional_block
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import os import re import sys from setuptools import setup root_dir = os.path.abspath(os.path.dirname(__file__)) def
(package_name): version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$") package_components = package_name.split('.') init_path = os.path.join(root_dir, *(package_components + ['__init__.py'])) with codecs.open(init_path, 'r', 'utf-8') as f: for line in f: match = version_re....
get_version
identifier_name
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import os import re import sys
def get_version(package_name): version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$") package_components = package_name.split('.') init_path = os.path.join(root_dir, *(package_components + ['__init__.py'])) with codecs.open(init_path, 'r', 'utf-8') as f: for line in f: ma...
from setuptools import setup root_dir = os.path.abspath(os.path.dirname(__file__))
random_line_split
overlay_nested2.py
#!/usr/bin/env python import warnings as _warnings _warnings.resetwarnings() _warnings.filterwarnings('error') from tdi import html template = html.from_string(""" <node tdi="item"> <znode tdi="nested" tdi:overlay="foo"> <ynode tdi="subnested"></ynode> </znode> <xnode tdi="a"></xnode> </node> """....
(object): def render_nested(self, node): node['been'] = u'here' def render_schnick(self, node): node.content = u"something" model = Model() template.render(model)
Model
identifier_name
overlay_nested2.py
#!/usr/bin/env python import warnings as _warnings _warnings.resetwarnings() _warnings.filterwarnings('error') from tdi import html template = html.from_string(""" <node tdi="item"> <znode tdi="nested" tdi:overlay="foo"> <ynode tdi="subnested"></ynode> </znode> <xnode tdi="a"></xnode> </node> """....
def render_schnick(self, node): node.content = u"something" model = Model() template.render(model)
node['been'] = u'here'
identifier_body
overlay_nested2.py
#!/usr/bin/env python import warnings as _warnings _warnings.resetwarnings() _warnings.filterwarnings('error') from tdi import html
<znode tdi="nested" tdi:overlay="foo"> <ynode tdi="subnested"></ynode> </znode> <xnode tdi="a"></xnode> </node> """.lstrip()).overlay(html.from_string(""" <anode tdi="grumpf" tdi:overlay="foo"> <bnode tdi:overlay="bar"></bnode> </anode> <anode tdi="zonk" tdi:overlay="bar"> <bnode tdi="schnic...
template = html.from_string(""" <node tdi="item">
random_line_split
test_hybrid_recommender.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ Test cases for the TAAR Hybrid recommender """ from taar.recommenders.hybrid_recommender import CuratedRecommender ...
def install_mock_curated_data(ctx): mock_data = [] for i in range(20): mock_data.append(str(i) * 16) ctx = ctx.child() conn = boto3.resource("s3", region_name="us-west-2") conn.create_bucket(Bucket=TAAR_WHITELIST_BUCKET) conn.Object(TAAR_WHITELIST_BUCKET, TAAR_WHITELIST_KEY).put( ...
ctx = ctx.child() conn = boto3.resource("s3", region_name="us-west-2") conn.create_bucket(Bucket=TAAR_WHITELIST_BUCKET) conn.Object(TAAR_WHITELIST_BUCKET, TAAR_WHITELIST_KEY).put(Body="") return ctx
identifier_body
test_hybrid_recommender.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ Test cases for the TAAR Hybrid recommender """ from taar.recommenders.hybrid_recommender import CuratedRecommender ...
@mock_s3 def test_hybrid_recommendations(test_ctx): # verify that the recommendations mix the curated and # ensemble results ctx = install_mock_curated_data(test_ctx) ctx = install_ensemble_fixtures(ctx) r = HybridRecommender(ctx) # Test that we can generate lists of results for LIMIT i...
guid_list = r.recommend({"client_id": "000000"}, limit=LIMIT) # The curated recommendations should always return with some kind # of recommendations assert len(guid_list) == LIMIT
conditional_block
test_hybrid_recommender.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ Test cases for the TAAR Hybrid recommender """ from taar.recommenders.hybrid_recommender import CuratedRecommender ...
(ctx): mock_data = [] for i in range(20): mock_data.append(str(i) * 16) ctx = ctx.child() conn = boto3.resource("s3", region_name="us-west-2") conn.create_bucket(Bucket=TAAR_WHITELIST_BUCKET) conn.Object(TAAR_WHITELIST_BUCKET, TAAR_WHITELIST_KEY).put( Body=json.dumps(mock_data)...
install_mock_curated_data
identifier_name
test_hybrid_recommender.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ Test cases for the TAAR Hybrid recommender """ from taar.recommenders.hybrid_recommender import CuratedRecommender ...
# ensemble results ctx = install_mock_curated_data(test_ctx) ctx = install_ensemble_fixtures(ctx) r = HybridRecommender(ctx) # Test that we can generate lists of results for LIMIT in range(4, 8): guid_list = r.recommend({"client_id": "000000"}, limit=LIMIT) # The curated recomm...
@mock_s3 def test_hybrid_recommendations(test_ctx): # verify that the recommendations mix the curated and
random_line_split
karma.conf.js
// Karma configuration // Generated on Wed Jul 15 2015 09:44:02 GMT+0200 (Romance Daylight Time) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.or...
// test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, /...
// preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { },
random_line_split
internet_protocol.py
# -*- test-case-name: twisted.test.test_factories,twisted.internet.test.test_protocol -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Standard implementations of Twisted protocol-related interfaces. Start here if you are looking to write a new protocol implementation for Twisted. The ...
(self, transport): """Make a connection to a transport and a server. This sets the 'transport' attribute of this Protocol, and calls the connectionMade() callback. """ self.connected = 1 self.transport = transport self.connectionMade() def connectionMade(sel...
makeConnection
identifier_name
internet_protocol.py
# -*- test-case-name: twisted.test.test_factories,twisted.internet.test.test_protocol -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Standard implementations of Twisted protocol-related interfaces. Start here if you are looking to write a new protocol implementation for Twisted. The ...
"""Called when a connection is made. This may be considered the initializer of the protocol, because it is called when the connection is completed. For clients, this is called once the connection to the server has been established; for servers, this is called after an accept() ...
self.transport = transport self.connectionMade() def connectionMade(self):
random_line_split
internet_protocol.py
# -*- test-case-name: twisted.test.test_factories,twisted.internet.test.test_protocol -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Standard implementations of Twisted protocol-related interfaces. Start here if you are looking to write a new protocol implementation for Twisted. The ...
self.numPorts = self.numPorts + 1 def doStop(self): """Make sure stopFactory is called. Users should not call this function themselves! """ if self.numPorts == 0: # this shouldn't happen, but does sometimes and this is better # than blowing up in as...
if self.noisy: log.msg("Starting factory %r" % self) self.startFactory()
conditional_block
internet_protocol.py
# -*- test-case-name: twisted.test.test_factories,twisted.internet.test.test_protocol -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Standard implementations of Twisted protocol-related interfaces. Start here if you are looking to write a new protocol implementation for Twisted. The ...
def stopFactory(self): """This will be called before I stop listening on all Ports/Connectors. This can be overridden to perform 'shutdown' tasks such as disconnecting database connections, closing files, etc. It will be called, for example, before an application shuts down, ...
"""This will be called before I begin listening on a Port or Connector. It will only be called once, even if the factory is connected to multiple ports. This can be used to perform 'unserialization' tasks that are best put off until things are actually running, such as connecti...
identifier_body
test_storage_engine.py
from unittest import TestCase from mock import patch from railgun.engines.storage_engine import DummyEngine class StorageEngineTestCase(TestCase): def setUp(self): self.config = { 'field1': 'value1', 'field2': 'value2' } def test_init(self): with patch('railg...
def test_config_from_dict_missing_field(self): engine = DummyEngine(self.config) new_config = { 'field1': 'value3' } self.assertRaises(ValueError, engine.config_from_dict, new_config) def test_extra_params_in_config_are_added_to_engine(self): self.config[...
self.assertEqual(engine.__getattribute__(key), value)
conditional_block
test_storage_engine.py
from unittest import TestCase from mock import patch from railgun.engines.storage_engine import DummyEngine class StorageEngineTestCase(TestCase): def setUp(self): self.config = { 'field1': 'value1', 'field2': 'value2' } def test_init(self): with patch('railg...
self.config['newfield'] = "test" engine = DummyEngine(self.config) self.assertEqual("test", engine.newfield)
identifier_body
test_storage_engine.py
from unittest import TestCase from mock import patch from railgun.engines.storage_engine import DummyEngine class StorageEngineTestCase(TestCase): def setUp(self): self.config = { 'field1': 'value1', 'field2': 'value2' } def test_init(self): with patch('railg...
def test_config_from_dict_missing_field(self): engine = DummyEngine(self.config) new_config = { 'field1': 'value3' } self.assertRaises(ValueError, engine.config_from_dict, new_config) def test_extra_params_in_config_are_added_to_engine(self): self.config['...
for key, value in new_config.iteritems(): self.assertEqual(engine.__getattribute__(key), value)
random_line_split
test_storage_engine.py
from unittest import TestCase from mock import patch from railgun.engines.storage_engine import DummyEngine class
(TestCase): def setUp(self): self.config = { 'field1': 'value1', 'field2': 'value2' } def test_init(self): with patch('railgun.engines.storage_engine.DummyEngine.config_from_dict') as mock_config_from_dict: DummyEngine(self.config) self.a...
StorageEngineTestCase
identifier_name
stats.py
def mean(vals): if vals: return sum(vals, 0.0) / len(vals) else: return 0.0 def trim(vals, trim=0.25): if trim > 0.0: trim = float(trim) size = len(vals) size_diff = int(size * trim) vals = vals[size_diff:-size_diff] return vals def median(vals): if ...
def variance(vals): return mean(pow_diff(vals, 2)) def std_dev(vals): return variance(vals) ** 0.5 def absolute_dev(vals, x): return [abs(x - v) for v in vals] def median_abs_dev(vals): x = median(vals) return median(absolute_dev(vals, x)) def rel_std_dev(vals): val_mean = mean(vals) ...
m = mean(vals) return [(v - m) ** power for v in vals]
identifier_body
stats.py
def
(vals): if vals: return sum(vals, 0.0) / len(vals) else: return 0.0 def trim(vals, trim=0.25): if trim > 0.0: trim = float(trim) size = len(vals) size_diff = int(size * trim) vals = vals[size_diff:-size_diff] return vals def median(vals): if not vals...
mean
identifier_name
stats.py
def mean(vals): if vals: return sum(vals, 0.0) / len(vals) else: return 0.0 def trim(vals, trim=0.25): if trim > 0.0:
return vals def median(vals): if not vals: return 0 copy = sorted(vals) size = len(copy) if size % 2 == 1: return copy[(size - 1) / 2] else: return (copy[size / 2 - 1] + copy[size / 2]) / 2.0 def pow_diff(vals, power): m = mean(vals) return [(v - m) ** power f...
trim = float(trim) size = len(vals) size_diff = int(size * trim) vals = vals[size_diff:-size_diff]
conditional_block
stats.py
def mean(vals): if vals: return sum(vals, 0.0) / len(vals) else: return 0.0 def trim(vals, trim=0.25): if trim > 0.0: trim = float(trim) size = len(vals) size_diff = int(size * trim) vals = vals[size_diff:-size_diff] return vals def median(vals): if ...
}
'kurtosis_trimmed': kurtosis(trimmed_vals), 'count': len(vals) # used to be called size; sample/population size
random_line_split
auth.js
import axios from 'axios'; import { SIGN_UP, SIGN_OUT, SIGN_IN, SET_MESSAGE } from './types'; // AUTH ACTIONS export function signUpUser(name, email, password)
export function signOutUser() { return { type: SIGN_OUT } } export function signInUser(email, password) { const signinRequest = axios({ method: 'post', url: '/signin', data: { email: email, password: password } }); return { type: SIGN_IN, payload: signinRequest };...
{ const signupRequest = axios({ method: 'post', url: '/signup', data: { dispName: name, email: email, password: password } }); return { type: SIGN_UP, payload: signupRequest }; }
identifier_body
auth.js
import axios from 'axios'; import { SIGN_UP, SIGN_OUT, SIGN_IN, SET_MESSAGE } from './types'; // AUTH ACTIONS export function signUpUser(name, email, password) { const signupRequest = axios({ method: 'post', url: '/signup', data: { dispName: name, email: email, password: passwo...
(message) { return { type: SET_MESSAGE, payload: message } }
setMessage
identifier_name
auth.js
import axios from 'axios'; import { SIGN_UP, SIGN_OUT, SIGN_IN, SET_MESSAGE } from './types';
method: 'post', url: '/signup', data: { dispName: name, email: email, password: password } }); return { type: SIGN_UP, payload: signupRequest }; } export function signOutUser() { return { type: SIGN_OUT } } export function signInUser(email, password) { const ...
// AUTH ACTIONS export function signUpUser(name, email, password) { const signupRequest = axios({
random_line_split
config.service.ts
// #docplaster // #docregion , proto import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; // #enddocregion proto import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; // #docregion rxjs-imports import { Observable, throwError } from 'rxjs'; import { catchErro...
} // #enddocregion getConfig getConfig_1() { // #docregion getConfig_1 return this.http.get<Config>(this.configUrl); } // #enddocregion getConfig_1 getConfig_2() { // #docregion getConfig_2 // now returns an Observable of Config return this.http.get<Config>(this.configUrl); } // #end...
retry(3), // retry a failed request up to 3 times catchError(this.handleError) // then handle the error );
random_line_split
config.service.ts
// #docplaster // #docregion , proto import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; // #enddocregion proto import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; // #docregion rxjs-imports import { Observable, throwError } from 'rxjs'; import { catchErro...
// #enddocregion getConfig_2 getConfig_3() { // #docregion getConfig_3 return this.http.get<Config>(this.configUrl) .pipe( catchError(this.handleError) ); } // #enddocregion getConfig_3 // #docregion getConfigResponse getConfigResponse(): Observable<HttpResponse<Config>> { ...
{ // #docregion getConfig_2 // now returns an Observable of Config return this.http.get<Config>(this.configUrl); }
identifier_body
config.service.ts
// #docplaster // #docregion , proto import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; // #enddocregion proto import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; // #docregion rxjs-imports import { Observable, throwError } from 'rxjs'; import { catchErro...
// Return an observable with a user-facing error message. return throwError( 'Something bad happened; please try again later.'); } // #enddocregion handleError makeIntentionalError() { return this.http.get('not/a/real/url') .pipe( catchError(this.handleError) ); } // #do...
{ // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong. console.error( `Backend returned code ${error.status}, body was: `, error.error); }
conditional_block
config.service.ts
// #docplaster // #docregion , proto import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; // #enddocregion proto import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; // #docregion rxjs-imports import { Observable, throwError } from 'rxjs'; import { catchErro...
(error: HttpErrorResponse) { if (error.status === 0) { // A client-side or network error occurred. Handle it accordingly. console.error('An error occurred:', error.error); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what we...
handleError
identifier_name
main.rs
// Mandelbrot set in rust // // This code shows how to calculate the set in serial and parallel. // More parallel versions will be added in the future. // // Written by Willi Kappler, grandor@gmx.de // // License: MIT // //#![feature(plugin)] // //#![plugin(clippy)] // External crates extern crate time; extern crate r...
() { // For example run with: // cargo run --release -- --re1=-2.0 --re2=1.0 --img1=-1.5 --img2=1.5 // --max_iter=2048 --img_size=1024 --num_threads=2 // // Or just using the default values: // cargo run --release -- --num_threads=2 // // Note that the image size must be a powe...
main
identifier_name
main.rs
// Mandelbrot set in rust // // This code shows how to calculate the set in serial and parallel. // More parallel versions will be added in the future. // // Written by Willi Kappler, grandor@gmx.de // // License: MIT // //#![feature(plugin)] // //#![plugin(clippy)] // External crates extern crate time; extern crate r...
, Err(e) => println!("Rayon error: set number of threads failed: {}", e) } do_run("rust_scoped_pool", &rust_scoped_pool, &mandel_config, &mut image, &time_now); do_run("job_steal", &job_steal, &mandel_config, &mut image, &time_now); do_run("job_steal_join", &job_steal_join, &mandel_config, &m...
{ do_run("rayon_join", &rayon_join, &mandel_config, &mut image, &time_now); do_run("rayon_par_iter", &rayon_par_iter, &mandel_config, &mut image, &time_now); }
conditional_block
main.rs
// Mandelbrot set in rust // // This code shows how to calculate the set in serial and parallel. // More parallel versions will be added in the future. // // Written by Willi Kappler, grandor@gmx.de // // License: MIT // //#![feature(plugin)] // //#![plugin(clippy)] // External crates extern crate time; extern crate r...
do_run("scoped_thread_pool", &scoped_thread_pool_, &mandel_config, &mut image, &time_now); // Make sure this is only called once match rayon::initialize(rayon::Configuration::new().set_num_threads(mandel_config.num_threads as usize)) { Ok(_) => { do_run("rayon_join", &rayon_join, &mand...
random_line_split
main.rs
// Mandelbrot set in rust // // This code shows how to calculate the set in serial and parallel. // More parallel versions will be added in the future. // // Written by Willi Kappler, grandor@gmx.de // // License: MIT // //#![feature(plugin)] // //#![plugin(clippy)] // External crates extern crate time; extern crate r...
let tm = tm.strftime("%Y_%m_%d__%H_%M_%S").unwrap(); let time_now = format!("{}", &tm); // vec! macro expects usize let mut image: Vec<u32> = vec![0; (mandel_config.img_size * mandel_config.img_size) as usize]; do_run("serial", &serial, &mandel_config, &mut image, &time_now); do_run("scoped_t...
{ // For example run with: // cargo run --release -- --re1=-2.0 --re2=1.0 --img1=-1.5 --img2=1.5 // --max_iter=2048 --img_size=1024 --num_threads=2 // // Or just using the default values: // cargo run --release -- --num_threads=2 // // Note that the image size must be a power o...
identifier_body
PostCard.tsx
import {Link} from 'gatsby'; import Img from 'gatsby-image'; import * as _ from 'lodash'; import {lighten} from 'polished'; import * as React from 'react'; import styled from '@emotion/styled'; import {css} from '@emotion/core'; import {colors} from '../styles/colors'; import {PageContext} from '../templates/post'; c...
`; const StaticAvatar = css ` display: block; overflow: hidden; margin: 0 -5px; width: 34px; height: 34px; border: #fff 2px solid; border-radius: 100%; `; const AuthorProfileImage = styled.img ` display: block; width: 100%; height: 100%; /* background: color(var(--lightgrey) l(+10%)); */ backg...
pointer-events: none; @media (max-width: 650px) { display: none; }
random_line_split
lib.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
extern crate native; extern crate phf; extern crate time; pub use tokenizer::Attribute; pub use driver::{one_input, ParseOpts, parse_to, parse}; #[cfg(not(for_c))] pub use serialize::serialize; mod macros; mod util { #![macro_escape] pub mod str; pub mod smallcharset; } pub mod tokenizer; pub mod tre...
#[cfg(test)]
random_line_split
productItem.js
import _ from "lodash"; import { Meteor } from "meteor/meteor"; import { Session } from "meteor/session"; import { Template } from "meteor/templating"; import { Tracker } from "meteor/tracker"; import { $ } from "meteor/jquery"; import { Reaction } from "/client/api"; import Logger from "/client/modules/logger"; import...
switch (weight) { case 1: return "product-medium"; case 2: return "product-large"; default: return "product-small"; } }, isSelected: function () { return _.includes(Session.get("productGrid/selectedProducts"), this._id) ? "active" : ""; }, isMediumWeight: fu...
const tag = ReactionProduct.getTag(); const positions = this.positions && this.positions[tag] || {}; const weight = positions.weight || 0;
random_line_split
productItem.js
import _ from "lodash"; import { Meteor } from "meteor/meteor"; import { Session } from "meteor/session"; import { Template } from "meteor/templating"; import { Tracker } from "meteor/tracker"; import { $ } from "meteor/jquery"; import { Reaction } from "/client/api"; import Logger from "/client/modules/logger"; import...
() { const data = instance.data.product; const $checkbox = instance.$(`input[type=checkbox][value=${data._id}]`); Session.set("productGrid/selectedProducts", []); $checkbox.prop("checked", true).trigger("change"); }, onPublishButtonClick() { ReactionProduct.publishPr...
onEditButtonClick
identifier_name
productItem.js
import _ from "lodash"; import { Meteor } from "meteor/meteor"; import { Session } from "meteor/session"; import { Template } from "meteor/templating"; import { Tracker } from "meteor/tracker"; import { $ } from "meteor/jquery"; import { Reaction } from "/client/api"; import Logger from "/client/modules/logger"; import...
}); /** * productGridItems events */ Template.productItem.events({ "click [data-event-action=productClick]": function (event, template) { const instance = Template.instance(); const view = instance.view; $(".js-search-modal").delay(400).fadeOut(400, () => { $("body").css("overflow-y", "inherit"...
{ const tag = ReactionProduct.getTag(); return this.positions && this.positions[tag] || {}; }
identifier_body
ConvokeSpirits.tsx
which. */ /** All convokable spells that 'hit' with a buff application */ const CONVOKE_BUFF_SPELLS = [ SPELLS.REJUVENATION, SPELLS.REJUVENATION_GERMINATION, SPELLS.REGROWTH, SPELLS.IRONFUR, SPELLS.TIGERS_FURY, SPELLS.FERAL_FRENZY_TALENT, SPELLS.WILD_GROWTH, SPELLS.FLOURISH_TALENT, SPELLS.STARFALL_...
onTravelTimeHit
identifier_name
ConvokeSpirits.tsx
enough to find out which. */ /** All convokable spells that 'hit' with a buff application */ const CONVOKE_BUFF_SPELLS = [ SPELLS.REJUVENATION, SPELLS.REJUVENATION_GERMINATION, SPELLS.REGROWTH, SPELLS.IRONFUR, SPELLS.TIGERS_FURY, SPELLS.FERAL_FRENZY_TALENT, SPELLS.WILD_GROWTH, SPELLS.FLOURISH_TALENT,...
{ this.lastTravelingSpellCast[event.ability.guid] = event; }
identifier_body
ConvokeSpirits.tsx
SPELLS.MOONFIRE_FERAL, SPELLS.RAKE_BLEED, SPELLS.THRASH_BEAR_DOT, ]; /** All convokable spells that 'hit' with direct healing */ const CONVOKE_HEAL_SPELLS = [SPELLS.SWIFTMEND]; /** All convokable spells that 'hit' with direct damage */ const CONVOKE_DAMAGE_SPELLS = [ SPELLS.WRATH, SPELLS.WRATH_MOONKIN, SPELL...
random_line_split
ConvokeSpirits.tsx
writing neither Abelito nor Sref * has cared enough to find out which. */ /** All convokable spells that 'hit' with a buff application */ const CONVOKE_BUFF_SPELLS = [ SPELLS.REJUVENATION, SPELLS.REJUVENATION_GERMINATION, SPELLS.REGROWTH, SPELLS.IRONFUR, SPELLS.TIGERS_FURY, SPELLS.FERAL_FRENZY_TALENT, ...
} /** * Tallies the given spellId as a convoked cast during the current convoke. */ registerConvokedSpell(spellId: number): void { const currentConvoke = this.convokeTracker[this.cast]; if (!currentConvoke.spellIdToCasts[spellId]) { currentConvoke.spellIdToCasts[spellId] = 0; } curre...
{ this.onTravelTimeHit(spellId); }
conditional_block
issue-13698.rs
// Copyright 2015 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 Bar for Foo {}
#[doc(hidden)] fn bar(&self) {} } // @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
random_line_split
issue-13698.rs
// Copyright 2015 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 ...
; // @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo' impl issue_13698::Foo for Foo {} pub trait Bar { #[doc(hidden)] fn bar(&self) {} } // @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar' impl Bar for Foo {}
Foo
identifier_name
EntityFactory.ts
import { ManagedFactory } from './ManagedFactory'; import type { Entity } from './Entity'; import { Json, JsonMap } from '../util'; import { Builder } from '../query'; import { EntityPartialUpdateBuilder } from '../partialupdate'; import { Metadata } from '../intersection'; export class EntityFactory<T extends Entity>...
} /** * Loads the instance for the given id, or null if the id does not exists. * @param id The id to query * @param [options] The load options * @param [options.depth=0] The object depth which will be loaded. Depth 0 loads only this object, * <code>true</code> loads the objects by reachability. ...
*/ newInstance(args?: any[] | IArguments) { const instance = super.newInstance(args); Metadata.get(instance).db = this.db; return instance;
random_line_split
EntityFactory.ts
import { ManagedFactory } from './ManagedFactory'; import type { Entity } from './Entity'; import { Json, JsonMap } from '../util'; import { Builder } from '../query'; import { EntityPartialUpdateBuilder } from '../partialupdate'; import { Metadata } from '../intersection'; export class EntityFactory<T extends Entity>...
return this.db.load(this.managedType.typeConstructor, id, options).then(doneCallback, failCallback); } /** * Gets an unloaded reference for the given id. * @param id The id of an object to get a reference for. * @return An unloaded reference to the object with the given id. */ ref(id: string): ...
{ return this.load(id, {}, options, doneCallback); }
conditional_block
EntityFactory.ts
import { ManagedFactory } from './ManagedFactory'; import type { Entity } from './Entity'; import { Json, JsonMap } from '../util'; import { Builder } from '../query'; import { EntityPartialUpdateBuilder } from '../partialupdate'; import { Metadata } from '../intersection'; export class EntityFactory<T extends Entity>...
}
{ return this.ref(id).partialUpdate(partialUpdate); }
identifier_body
EntityFactory.ts
import { ManagedFactory } from './ManagedFactory'; import type { Entity } from './Entity'; import { Json, JsonMap } from '../util'; import { Builder } from '../query'; import { EntityPartialUpdateBuilder } from '../partialupdate'; import { Metadata } from '../intersection'; export class EntityFactory<T extends Entity>...
(json: Json): T { const obj: T = this.db.getReference(this.managedType.ref, (json as JsonMap).id as string); return this.managedType.fromJsonValue(Metadata.get(obj), json, obj, { persisting: false })!; } /** * Creates a new query for this class * @return The query builder */ find(): Builder<T> {...
fromJSON
identifier_name
account_group.py
# Copyright 2021 Alfredo de la Fuente - AvanzOSC # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models, fields, api class AccountGroup(models.Model): _inherit = 'account.group' length_account = fields.Integer(
default=True) @api.depends('code_prefix_start') def _compute_length_account(self): for group in self: group.length_account = len(group.code_prefix_start) def _find_account_group_headquarter(self): found = False group = self while not found: i...
string='Length account', compute='_compute_length_account', store=True) without_headquarter = fields.Boolean( string='Without headquarter in invoices and accounting entries',
random_line_split
account_group.py
# Copyright 2021 Alfredo de la Fuente - AvanzOSC # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models, fields, api class AccountGroup(models.Model): _inherit = 'account.group' length_account = fields.Integer( string='Length account', compute='_compute_length_a...
def _find_account_group_headquarter(self): found = False group = self while not found: if not group.parent_id: found = True without_headquarter_control = group.without_headquarter else: cond = [('id', '=', group.parent...
group.length_account = len(group.code_prefix_start)
conditional_block
account_group.py
# Copyright 2021 Alfredo de la Fuente - AvanzOSC # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models, fields, api class AccountGroup(models.Model): _inherit = 'account.group' length_account = fields.Integer( string='Length account', compute='_compute_length_a...
def _find_account_group_headquarter(self): found = False group = self while not found: if not group.parent_id: found = True without_headquarter_control = group.without_headquarter else: cond = [('id', '=', group.parent...
for group in self: group.length_account = len(group.code_prefix_start)
identifier_body
account_group.py
# Copyright 2021 Alfredo de la Fuente - AvanzOSC # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models, fields, api class
(models.Model): _inherit = 'account.group' length_account = fields.Integer( string='Length account', compute='_compute_length_account', store=True) without_headquarter = fields.Boolean( string='Without headquarter in invoices and accounting entries', default=True) @api....
AccountGroup
identifier_name
UnitVertexBuffer.js
var UnitVertexBuffer = function(gl) { var self = {}; var ITEM_SIZE = 2; var VERT_COUNT = 4; var vertexBuffer; var ctor = function() { vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); var vertAr = [ -1.0, -1.0, 1.0, -1....
]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertAr), gl.STATIC_DRAW); }; self.draw = function(vertPosAttr) { gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.vertexAttribPointer(vertPosAttr, ITEM_SIZE, gl.FLOAT, false, 0, 0); gl.drawArrays(gl.TRIANGLE_STRIP, 0, VE...
random_line_split
production.py
# -*- coding: utf-8 -*- ''' Production Configurations - Use djangosecure - Use Amazon's S3 for storing static files and uploaded media - Use sendgrid to send emails - Use MEMCACHIER on Heroku ''' from configurations import values # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings...
SESSION_COOKIE_HTTPONLY = values.BooleanValue(True) SECURE_SSL_REDIRECT = values.BooleanValue(True) # end django-secure # SITE CONFIGURATION # Hosts/domain names that are valid for this site # See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts ALLOWED_HOSTS = ["*"] # ...
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # INSTALLED_APPS INSTALLED_APPS = Common.INSTALLED_APPS # END INSTALLED_APPS # SECRET KEY SECRET_KEY = values.SecretValue() # END SECRET KEY # django-secure INSTALLED_APPS += ("djangosecure", ) # set this to 60 seconds...
identifier_body
production.py
# -*- coding: utf-8 -*- ''' Production Configurations - Use djangosecure - Use Amazon's S3 for storing static files and uploaded media - Use sendgrid to send emails - Use MEMCACHIER on Heroku ''' from configurations import values # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings...
(Common): # This ensures that Django will be able to detect a secure connection # properly on Heroku. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # INSTALLED_APPS INSTALLED_APPS = Common.INSTALLED_APPS # END INSTALLED_APPS # SECRET KEY SECRET_KEY = values.SecretValue...
Production
identifier_name
production.py
# -*- coding: utf-8 -*- ''' Production Configurations - Use djangosecure - Use Amazon's S3 for storing static files and uploaded media - Use sendgrid to send emails - Use MEMCACHIER on Heroku ''' from configurations import values # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings...
EMAIL_SUBJECT_PREFIX = values.Value('[Blog API] ', environ_name="EMAIL_SUBJECT_PREFIX") EMAIL_USE_TLS = True SERVER_EMAIL = EMAIL_HOST_USER # END EMAIL # TEMPLATE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs TEMPLATE_LOADERS = ( ('django.tem...
EMAIL_HOST_USER = values.SecretValue(environ_prefix="", environ_name="SENDGRID_USERNAME") EMAIL_PORT = values.IntegerValue(587, environ_prefix="", environ_name="EMAIL_PORT")
random_line_split
lib.rs
//! Data types that represent playing cards. #![warn(bad_style, missing_docs, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(str_char)] use std::fmt; use std::str::FromStr; use Suit::{Spade, Heart, Dia, Club}; /// Playing card's suite. #[allow...
match *self { Card::BlackJoker => write!(f, "BJ"), Card::WhiteJoker => write!(f, "WJ"), Card::Suit(sc) => write!(f, "{}", sc), } } } impl FromStr for Card { type Err = (); fn from_str(s: &str) -> Result<Card, ()> { match s { "BJ" => O...
impl fmt::Display for Card { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
random_line_split
lib.rs
//! Data types that represent playing cards. #![warn(bad_style, missing_docs, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(str_char)] use std::fmt; use std::str::FromStr; use Suit::{Spade, Heart, Dia, Club}; /// Playing card's suite. #[allow...
check_pair("S".to_string(), Spade); check_pair("H".to_string(), Heart); check_pair("D".to_string(), Dia); check_pair("C".to_string(), Club); } #[test] fn show_card() { fn check_pair(s: String, card: Card) { assert_eq!(s, format!("{}", card)); ...
{ assert_eq!(s, format!("{}", suite)); assert_eq!(Ok(suite), s.parse()); }
identifier_body
lib.rs
//! Data types that represent playing cards. #![warn(bad_style, missing_docs, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(str_char)] use std::fmt; use std::str::FromStr; use Suit::{Spade, Heart, Dia, Club}; /// Playing card's suite. #[allow...
(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { &Spade => "S", &Heart => "H", &Dia => "D", &Club => "C" }; write!(f, "{}", s) } } impl FromStr for Suit { type Err = (); fn from_str(s: &str) -> Result<Suit, ()...
fmt
identifier_name
guess_video_rexps.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2012 Nicolas Wack <wackou@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free ...
def process(mtree): SingleNodeGuesser(guess_video_rexps, None, log).process(mtree)
string = '-' + string + '-' for rexp, confidence, span_adjust in video_rexps: match = re.search(sep + rexp + sep, string, re.IGNORECASE) if match: metadata = match.groupdict() # is this the better place to put it? (maybe, as it is at least # the soonest that we ca...
identifier_body
guess_video_rexps.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2012 Nicolas Wack <wackou@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free ...
def guess_video_rexps(string): string = '-' + string + '-' for rexp, confidence, span_adjust in video_rexps: match = re.search(sep + rexp + sep, string, re.IGNORECASE) if match: metadata = match.groupdict() # is this the better place to put it? (maybe, as it is at least ...
random_line_split
guess_video_rexps.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2012 Nicolas Wack <wackou@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free ...
(string): string = '-' + string + '-' for rexp, confidence, span_adjust in video_rexps: match = re.search(sep + rexp + sep, string, re.IGNORECASE) if match: metadata = match.groupdict() # is this the better place to put it? (maybe, as it is at least # the soon...
guess_video_rexps
identifier_name
guess_video_rexps.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2012 Nicolas Wack <wackou@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free ...
return None, None def process(mtree): SingleNodeGuesser(guess_video_rexps, None, log).process(mtree)
match = re.search(sep + rexp + sep, string, re.IGNORECASE) if match: metadata = match.groupdict() # is this the better place to put it? (maybe, as it is at least # the soonest that we can catch it) if metadata.get('cdNumberTotal', -1) is None: del ...
conditional_block
test_envcheckr.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_envcheckr ---------------------------------- Tests for `envcheckr` module. """ import pytest from envcheckr import envcheckr
assert len(lines_b) == 7 def test_parse_key(): lines = envcheckr.parse_lines('tests/env') assert(envcheckr.parse_key(lines[0])) == 'FRUIT' assert(envcheckr.parse_key(lines[1])) == 'DRINK' assert(envcheckr.parse_key(lines[2])) == 'ANIMAL' def test_get_missing_keys(): file_a = 'tests/env' ...
def test_parse_lines(): lines_a = envcheckr.parse_lines('tests/env') assert len(lines_a) == 3 lines_b = envcheckr.parse_lines('tests/env.example')
random_line_split