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
reddit_db_scraper.py
from pymongo import MongoClient import json import requests import time from datetime import datetime def subredditInfo(sr, limit=100, sorting="top", period="day", user_agent="ChicagoSchool's scraper", **kwargs): """retrieves X (max 100) amount of stories in a subreddit 'sorting' is whether ...
(db_n, col_n, sub_l): """scrapes all the threads for a subreddit and stores them in a mongodb db""" m_ind = 0 t_f = datetime.now() sub_ln = len(sub_l) client = MongoClient() db = client[db_n] col = db[col_n] while True: t_1 = datetime.now() for i, s in enumerate(su...
dbScraper
identifier_name
reddit_db_scraper.py
from pymongo import MongoClient import json import requests import time from datetime import datetime def subredditInfo(sr, limit=100, sorting="top", period="day", user_agent="ChicagoSchool's scraper", **kwargs): """retrieves X (max 100) amount of stories in a subreddit 'sorting' is whether ...
print e time.sleep(300) print i * 100. / sub_ln, j * 100. / sub_info_ln, m_ind, i, j, datetime.now() - t_1, datetime.now() - t_f time.sleep(2) # now we wait until a full day has passed since we started our search t_diff = ...
try: sub_info = subredditInfo(s) except Exception as e: print e time.sleep(300) sub_info = subredditInfo(s) time.sleep(2) sub_info_ln = len(sub_info) for j, l in enumerate(sub_info): link = l[...
conditional_block
reddit_db_scraper.py
from pymongo import MongoClient import json import requests import time from datetime import datetime
'sorting' is whether or not the sorting of the reddit should be customized or not, if it is: Allowed passing params/queries such as t=hour, week, month, year or all""" #query to send parameters = {"limit": limit,} parameters.update(kwargs) url = "http://www.reddit.com/r/%s/%s.json?limit=%d&t...
def subredditInfo(sr, limit=100, sorting="top", period="day", user_agent="ChicagoSchool's scraper", **kwargs): """retrieves X (max 100) amount of stories in a subreddit
random_line_split
reddit_db_scraper.py
from pymongo import MongoClient import json import requests import time from datetime import datetime def subredditInfo(sr, limit=100, sorting="top", period="day", user_agent="ChicagoSchool's scraper", **kwargs): """retrieves X (max 100) amount of stories in a subreddit 'sorting' is whether ...
def dbScraper(db_n, col_n, sub_l): """scrapes all the threads for a subreddit and stores them in a mongodb db""" m_ind = 0 t_f = datetime.now() sub_ln = len(sub_l) client = MongoClient() db = client[db_n] col = db[col_n] while True: t_1 = datetime.now() for i, s...
url = "http://www.reddit.com/%s.json?sort=%s&limit=%d" % (link, sorting, limit) r = requests.get(url, headers={"user-agent": user_agent}) j = json.loads(r.text) date = datetime.fromtimestamp(j[0]["data"]["children"][0]["data"]["created"]) db_data = {"date": date, "link": link, "subreddit": sub, "content...
identifier_body
classImplementsClass6.js
//// [classImplementsClass6.ts] class A { static bar(): string { return ""; } foo(): number { return 1; } } class C implements A { foo() { return 1; } } class C2 extends A {} var c: C; var c2: C2; c = c2; c2 = c; c.bar(); // error c2.bar(); // should error //// [classImplemen...
__.prototype = b.prototype; d.prototype = new __(); }; var A = (function () { function A() { } A.bar = function () { return ""; }; A.prototype.foo = function () { return 1; }; return A; })(); var C = (function () { function C() { } C.prototype.foo = function () { ...
{ this.constructor = d; }
identifier_body
classImplementsClass6.js
//// [classImplementsClass6.ts] class A { static bar(): string { return ""; } foo(): number { return 1; } } class C implements A { foo() { return 1; } } class C2 extends A {} var c: C; var c2: C2; c = c2;
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var A = (function () { function A() { } A.bar = function () { return "";...
c2 = c; c.bar(); // error c2.bar(); // should error //// [classImplementsClass6.js]
random_line_split
classImplementsClass6.js
//// [classImplementsClass6.ts] class A { static bar(): string { return ""; } foo(): number { return 1; } } class C implements A { foo() { return 1; } } class C2 extends A {} var c: C; var c2: C2; c = c2; c2 = c; c.bar(); // error c2.bar(); // should error //// [classImplemen...
() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var A = (function () { function A() { } A.bar = function () { return ""; }; A.prototype.foo = function () { return 1; }; return A; })(); var C = (function () { function C() { } C.proto...
__
identifier_name
logging.py
# standard imports import os import logging import traceback # Qt imports from PyQt5.QtCore import pyqtSignal, pyqtSlot from PyQt5.QtWidgets import QPlainTextEdit # toolbox imports from dltb.util.debug import edit
# logging LOG = logging.getLogger(__name__) class QLogHandler(QPlainTextEdit, logging.Handler): """A log handler that displays log messages in a QWidget. A :py:class:`QLogHandler` can be used """ _message_signal = pyqtSignal(str) def __init__(self, parent=None): # FIXME[question]: can...
# GUI imports from ..utils import protect
random_line_split
logging.py
# standard imports import os import logging import traceback # Qt imports from PyQt5.QtCore import pyqtSignal, pyqtSlot from PyQt5.QtWidgets import QPlainTextEdit # toolbox imports from dltb.util.debug import edit # GUI imports from ..utils import protect # logging LOG = logging.getLogger(__name__) class QLogHa...
""" return self._counter def clear(self): """Clear this :py:class:QLogHandler. """ super().clear() self._records.clear() self._counter = 1 self._message_signal.emit("Log view cleared") @pyqtSlot(str) def appendMessage(self, message: str): ...
"""A log handler that displays log messages in a QWidget. A :py:class:`QLogHandler` can be used """ _message_signal = pyqtSignal(str) def __init__(self, parent=None): # FIXME[question]: can we use real python multiple inheritance here? # (that is just super().__init__(*args, **kwargs...
identifier_body
logging.py
# standard imports import os import logging import traceback # Qt imports from PyQt5.QtCore import pyqtSignal, pyqtSlot from PyQt5.QtWidgets import QPlainTextEdit # toolbox imports from dltb.util.debug import edit # GUI imports from ..utils import protect # logging LOG = logging.getLogger(__name__) class QLogHa...
else: LOG.info(f"Edit command returned: {retcode}" f"({'error' if retcode else 'success'})") except OSError as error: LOG.error(f"Edit command failed: {error}")
LOG.error("Edit command was terminated by signal " f"{-retcode}")
conditional_block
logging.py
# standard imports import os import logging import traceback # Qt imports from PyQt5.QtCore import pyqtSignal, pyqtSlot from PyQt5.QtWidgets import QPlainTextEdit # toolbox imports from dltb.util.debug import edit # GUI imports from ..utils import protect # logging LOG = logging.getLogger(__name__) class QLogHa...
(self): """The number of lines in this QLogHandler. """ return self._counter def clear(self): """Clear this :py:class:QLogHandler. """ super().clear() self._records.clear() self._counter = 1 self._message_signal.emit("Log view cleared") @...
__len__
identifier_name
GitHubReleasePreview.tsx
import { FunctionComponent } from "react" import TagsList from "./TagsList" import FormattedDate from "./FormattedDate" import HorizontalRule from "./HorizontalRule" import { GitHubRelease } from "../models/GitHubRelease" interface Props { release: GitHubRelease } const GitHubReleasePreview: FunctionComponent<Props...
} export default GitHubReleasePreview
]} </article> )
random_line_split
config-panel.component.ts
import {fromEvent as observableFromEvent, Subscription , Observable } from 'rxjs'; import {filter} from 'rxjs/operators'; import { UIPopoverContent, UIPopoverRef } from 'deneb-ui'; import { Component, ElementRef, OnDestroy, Self } from '@angular/core'; import { UserActionPanelComponent } from '../../../../home/user-...
} get directDownload(): boolean { return this._directDownload; } set autoPlayNext(v: boolean) { this._autoPlayNext = v; this._persistStorage.setItem(PlayList.AUTO_PLAY_NEXT, v + ''); } get autoPlayNext(): boolean { return this._autoPlayNext; } set auto...
private _autoFloatPlayWhenLeave: boolean; set directDownload(v: boolean) { this._directDownload = v; this._persistStorage.setItem(Capture.DIRECT_DOWNLOAD, v + '');
random_line_split
config-panel.component.ts
import {fromEvent as observableFromEvent, Subscription , Observable } from 'rxjs'; import {filter} from 'rxjs/operators'; import { UIPopoverContent, UIPopoverRef } from 'deneb-ui'; import { Component, ElementRef, OnDestroy, Self } from '@angular/core'; import { UserActionPanelComponent } from '../../../../home/user...
set autoFloatPlayWhenLeave(v: boolean) { this._autoFloatPlayWhenLeave = v; this._persistStorage.setItem(FloatPlayer.AUTO_FLOAT_WHEN_LEAVE, v + ''); } get autoFloatPlayWhenLeave(): boolean { return this._autoFloatPlayWhenLeave; } constructor(@Self() private _selfElementRef...
{ return this._autoFloatPlayWhenScroll; }
identifier_body
config-panel.component.ts
import {fromEvent as observableFromEvent, Subscription , Observable } from 'rxjs'; import {filter} from 'rxjs/operators'; import { UIPopoverContent, UIPopoverRef } from 'deneb-ui'; import { Component, ElementRef, OnDestroy, Self } from '@angular/core'; import { UserActionPanelComponent } from '../../../../home/user...
() { super.ngAfterViewInit(); this._subscription.add( observableFromEvent(document.body, 'click').pipe( filter((event: MouseEvent) => { const selfElement = this._selfElementRef.nativeElement as HTMLElement; const rect = selfElement.getB...
ngAfterViewInit
identifier_name
sidebar.ts
import { ClientFunction, t, Selector } from 'testcafe'; import { waitForReact, ReactSelector } from 'testcafe-react-selectors'; const getWindowLocation = ClientFunction(() => window.location.href); fixture`Sidebar`.page`http://localhost:3000`.beforeEach(async () => { await waitForReact(15000); }); // tslint:disabl...
); await t .expect(locationSetMessage.innerText) .eql('Your location: Littleton'); } }); // tslint:disable-next-line:no-shadowed-variable test('Sidebar body contains a list of issues and a footer to more issues', async t => { const Sidebar = await ReactSelector('Sidebar'); await t.expect(Sid...
{ const locationButton = await Location.findReact('button'); await t.expect(locationButton.innerText).eql('CHANGE LOCATION'); await t.click(locationButton); const addressField = Selector('#address'); await t .expect(addressField.getAttribute('placeholder')) .eql('Enter an address or zip...
conditional_block
sidebar.ts
import { ClientFunction, t, Selector } from 'testcafe'; import { waitForReact, ReactSelector } from 'testcafe-react-selectors'; const getWindowLocation = ClientFunction(() => window.location.href); fixture`Sidebar`.page`http://localhost:3000`.beforeEach(async () => { await waitForReact(15000); }); // tslint:disabl...
await t .expect(setLocationMessage.exists) .ok('Set location message is not displayed'); let locationSetMessage = await Selector('#locationMessage').withText( 'Set your location' ); if (await locationSetMessage.exists) { const locationButton = await Location.findReact('button'); await t.ex...
const Location = await ReactSelector('Location'); await t.expect(Location).ok('Location component is not displayed'); const setLocationMessage = await Selector('#setLocationMessage');
random_line_split
mac_tool.py
def _DetectInputEncoding(self, file_name): """Reads the first few bytes from file_name and tries to guess the text encoding. Returns None as a guess if it can't detect it.""" fp = open(file_name, 'rb') try: header = fp.read(3) except e: fp.close() return None fp.close() ...
"""Copies a .strings file using iconv to reconvert the input into UTF-16.""" input_code = self._DetectInputEncoding(source) or "UTF-8" # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints # CFPropertyListCreateFro...
identifier_body
mac_tool.py
(self, dest): subprocess.check_call([ 'xcrun', 'plutil', '-convert', 'binary1', '-o', dest, dest]) def _CopyStringsFile(self, source, dest): """Copies a .strings file using iconv to reconvert the input into UTF-16.""" input_code = self._DetectInputEncoding(source) or "UTF-8" # Xcode's CpyCop...
_ConvertToBinary
identifier_name
mac_tool.py
convert_to_binary, *keys): """Copies the |source| Info.plist to the destination directory |dest|.""" # Read the source Info.plist into memory. fd = open(source, 'r') lines = fd.read() fd.close() # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild). plist = plistlib.readPlistFrom...
evar = '${%s}' % key evalue = os.environ[key] lines = string.replace(lines, evar, evalue) # Xcode supports various suffices on environment variables, which are # all undocumented. :rfc1034identifier is used in the standard project # template these days, and :identifier was used ear...
continue
conditional_block
mac_tool.py
_list): """Calls libtool and filters out '/path/to/libtool: file: foo.o has no symbols'.""" libtool_re = re.compile(r'^.*libtool: (?:for architecture: \S* )?' r'file: .* has no symbols$') libtool_re5 = re.compile( r'^.*libtool: warning for library: ' + r'.* th...
specific that correspond to the bundle identifier. Args:
random_line_split
smtpd.py
% domain) return False # Our task now is to get a connection to the most preferable # Mail Exchanger (MX) we can reach. # Make a list of all the addresses to try, in order of preference. # We prefer IPv6 for the first attempt, but interleave IPv6 and # IPv4 addresses in case one tr...
data_mode
identifier_name
smtpd.py
user = parts[0] domain = parts[1] return [user, domain] def find_wildcard(self, subdomain, domains): splode = subdomain.split(".") for i in range(0, len(splode)): wildsub = "*." + ".".join(splode[i:]) if wildsub in domains: return wildsub return None def...
# more's the pity. # XXX does this work with unicode? parts = address.lower().split("@") if len(parts) != 2: return None
random_line_split
smtpd.py
(x) print("connection.mail_from borked:", str(x)) return False return True @asyncio.coroutine def connect_to_addresses(self, addresses, interval): tasks = [] client_futs = [] greet_futs = [] connection = None @asyncio.coroutine def process_completions(timeout): connec...
if chunk.endswith(eom[0:i]): eom_offset = i break
conditional_block
smtpd.py
just check that it's a valid local address if not self.validate_mailbox(addr): print("not a local address: ", repr(addr)) return False # Now check to see if the address delivers to the # specified mailbox, which should be the mailbox # of the authenticated user. slot = self.userdb....
tasks = [] client_futs = [] greet_futs = [] connection = None @asyncio.coroutine def process_completions(timeout): connection = None while connection == None and (len(tasks) > 0 or len(client_futs) > 0 or len(greet_...
identifier_body
task.rs
/// Provides detailed control over the properties and behavior of new tasks. // NB: Builders are designed to be single-use because they do stateful // things that get weird when reusing - e.g. if you create a result future // it only applies to a single task, so then you have to maintain Some // potentially tricky sta...
#[test
{ let (tx, rx) = channel(); TaskBuilder::new().spawn(proc() { tx.send(()); }); rx.recv(); }
identifier_body
task.rs
/// Provides detailed control over the properties and behavior of new tasks. // NB: Builders are designed to be single-use because they do stateful // things that get weird when reusing - e.g. if you create a result future // it only applies to a single task, so then you have to maintain Some // potentially tricky sta...
(mut self, stderr: Box<Writer + Send>) -> TaskBuilder { self.stderr = Some(stderr); self } // Where spawning actually happens (whether yielding a future or not) fn spawn_internal(self, f: proc():Send, on_exit: Option<proc(Result<(), Box<Any + Send>>):Send>) { l...
stderr
identifier_name
task.rs
/// Provides detailed control over the properties and behavior of new tasks. // NB: Builders are designed to be single-use because they do stateful // things that get weird when reusing - e.g. if you create a result future // it only applies to a single task, so then you have to maintain Some // potentially tricky sta...
#[test] fn test_run_basic() { let (tx, rx) = channel(); TaskBuilder::new().spawn(proc() { tx.send(()); }); rx.recv(); } #[test]
fn test_send_named_task() { TaskBuilder::new().named("ada lovelace".into_cow()).try(proc() { assert!(name().unwrap() == "ada lovelace"); }).map_err(|_| ()).unwrap(); }
random_line_split
helpers.js
const pg = require('pg') const fs = require('fs') const path = require('path') const connect = connectionConfig => { const poolConfig = { idleTimeoutMillis: 30000, max: 10 } const config = Object.assign({}, poolConfig, connectionConfig) const pool = new pg.Pool(config) /* istanbul ignore next */ ...
const noEscape = path.basename(queryName) const queryPath = path.join(__dirname, 'queries', noEscape) + '.sql' fs.readFile(queryPath, { encoding: 'utf8' }, (error, queryText) => { if (error) { console.error('Failed to find schema in fs') return cb(error) } query(queryText, queryArgs, cb) ...
const runSqlFromFs = (query, queryName, queryArgs = [], cb) => { // so we have control of where we look in fs
random_line_split
urlhint.rs
} /// Hash-Addressed Content #[derive(Debug, PartialEq)] pub struct Content { /// URL of the content pub url: String, /// MIME type of the content pub mime: Mime, /// Content owner address pub owner: Address, } /// Result of resolving id to URL #[derive(Debug, PartialEq)] pub enum URLHintResult { /// Dapp Dap...
() -> Self { FakeRegistrar { calls: Arc::new(Mutex::new(Vec::new())), responses: Mutex::new( vec![ Ok(format!("000000000000000000000000{}", URLHINT).from_hex().unwrap()), Ok(Vec::new()) ] ), } } } impl ContractClient for FakeRegistrar { fn registrar(&self) -> Result<Addres...
new
identifier_name
urlhint.rs
} /// Hash-Addressed Content #[derive(Debug, PartialEq)] pub struct Content { /// URL of the content pub url: String, /// MIME type of the content pub mime: Mime, /// Content owner address pub owner: Address, } /// Result of resolving id to URL #[derive(Debug, PartialEq)] pub enum URLHintResult { /// Dapp Dap...
impl URLHint for URLHintContract { fn resolve(&self, id: Bytes) -> BoxFuture<Option<URLHintResult>, String> { use futures::future::Either; let do_call = |_, data| { let addr = match self.client.registrar() { Ok(addr) => addr, Err(e) => return Box::new(future::err(e)) as BoxFuture<Vec<u8>, _>, ...
repo: repo, commit: commit, owner: owner, })) }
random_line_split
urlhint.rs
} /// Hash-Addressed Content #[derive(Debug, PartialEq)] pub struct Content { /// URL of the content pub url: String, /// MIME type of the content pub mime: Mime, /// Content owner address pub owner: Address, } /// Result of resolving id to URL #[derive(Debug, PartialEq)] pub enum URLHintResult { /// Dapp Da...
{ if bytes.len() < COMMIT_LEN { return None; } let mut commit = [0; COMMIT_LEN]; for i in 0..COMMIT_LEN { commit[i] = bytes[i]; } Some(commit) }
identifier_body
JsQuanLyNgayPhep.js
var getColor = function (value, p, record) { return "<span style='color:blue;'>" + value + "</span>"; } var getDayNumber = function (value, p, record) { if (value == "" || value == 0) { return "<span style='float:right;'>0</span>"; } return "<b style='float:right;color:blue;'>" + value...
} return "<b style='float:right;color:red;'>" + value + "</b>"; } //Lấy số ngày phép được hưởng mỗi năm var getUsedDayPerYear = function (value, p, record) { if (value == "" || value == 0) { return "<span style='float:right;'>0</span>"; } return "<b style='float:right;color:red;'>"...
if (value == "" || value == 0) { return "";
random_line_split
JsQuanLyNgayPhep.js
var getColor = function (value, p, record) { return "<span style='color:blue;'>" + value + "</span>"; } var getDayNumber = function (value, p, record) { if (value == "" || value == 0) { return "<span style='float:right;'>0</span>"; } return "<b style='float:right;color:blue;'>" + value...
else { rs = month + " tháng "; if (remainDay > 0) { rs += remainDay + " ngày"; } } return rs; }
f (remainMonth > 0) { rs += remainMonth + " tháng"; } }
conditional_block
generic-extern-mangle.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 ...
() { assert_eq!(99u8, foo(255u8, 100u8)); assert_eq!(99u16, foo(65535u16, 100u16)); }
main
identifier_name
generic-extern-mangle.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() { assert_eq!(99u8, foo(255u8, 100u8)); assert_eq!(99u16, foo(65535u16, 100u16)); }
random_line_split
generic-extern-mangle.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() { assert_eq!(99u8, foo(255u8, 100u8)); assert_eq!(99u16, foo(65535u16, 100u16)); }
{ a.wrapping_add(b) }
identifier_body
pointing.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/. */ //! Specified values for Pointing properties. //! //! https://drafts.csswg.org/css-ui/#pointing-keyboard use styl...
/// https://drafts.csswg.org/css-ui/#cursor #[cfg(feature = "servo")] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub struct Cursor(pub CursorKind); /// The specified value for the `cursor` property. /// /// https://drafts.csswg.org/css-ui/#cursor #[cfg(feature = "gecko")] #[derive(C...
///
random_line_split
pointing.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/. */ //! Specified values for Pointing properties. //! //! https://drafts.csswg.org/css-ui/#pointing-keyboard use styl...
(pub CursorKind); /// The specified value for the `cursor` property. /// /// https://drafts.csswg.org/css-ui/#cursor #[cfg(feature = "gecko")] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Cursor { /// The parsed images for the cursor. pub images: Box<[CursorImage]>, /// The ...
Cursor
identifier_name
ImgMediaCard.js
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActionArea from '@material-ui/core/CardActionArea'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import CardMedia f...
() { const classes = useStyles(); return ( <Card className={classes.card}> <CardActionArea> <CardMedia component="img" alt="Contemplative Reptile" height="140" image="/static/images/cards/contemplative-reptile.jpg" title="Contemplative Reptile" ...
ImgMediaCard
identifier_name
ImgMediaCard.js
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActionArea from '@material-ui/core/CardActionArea'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import CardMedia f...
</Typography> </CardContent> </CardActionArea> <CardActions> <Button size="small" color="primary"> Share </Button> <Button size="small" color="primary"> Learn More </Button> </CardActions> </Card> ); } export default ImgMedi...
{ const classes = useStyles(); return ( <Card className={classes.card}> <CardActionArea> <CardMedia component="img" alt="Contemplative Reptile" height="140" image="/static/images/cards/contemplative-reptile.jpg" title="Contemplative Reptile" ...
identifier_body
ImgMediaCard.js
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActionArea from '@material-ui/core/CardActionArea'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import CardMedia f...
<Typography gutterBottom variant="h5" component="h2"> Lizard </Typography> <Typography variant="body2" color="textSecondary" component="p"> Lizards are a widespread group of squamate reptiles, with over 6,000 species, ranging across all continents except...
title="Contemplative Reptile" /> <CardContent>
random_line_split
ns.spec.ts
import { mask_config } from '@core/api/config'; import { renderer_renderAsync } from '@core/renderer/exports'; import { Module } from '@core/feature/modules/exports';
UTest({ $teardown () { mask_config('getFile', null); mask_config('getScript', null); }, async 'should load mask' () { mask_config('getFile', assert.await(async path => { has_(path, 'controls/Foo.mask'); var template = 'define Foo { h3 > "FooTest" }'; return template; })); let dom = await renderer...
random_line_split
ns.spec.ts
import { mask_config } from '@core/api/config'; import { renderer_renderAsync } from '@core/renderer/exports'; import { Module } from '@core/feature/modules/exports'; UTest({ $teardown () { mask_config('getFile', null); mask_config('getScript', null); }, async 'should load mask' () { mask_config('getFile', a...
() { return 'FooServiceTest' } }; return service; })); let dom = await renderer_renderAsync(` import Foo from services; h5 > '~[Foo.getName()]'; `); return UTest.domtest(dom, ` find('h5') > text FooServiceTest; `); } });
getName
identifier_name
ns.spec.ts
import { mask_config } from '@core/api/config'; import { renderer_renderAsync } from '@core/renderer/exports'; import { Module } from '@core/feature/modules/exports'; UTest({ $teardown () { mask_config('getFile', null); mask_config('getScript', null); }, async 'should load mask' () { mask_config('getFile', a...
}; return service; })); let dom = await renderer_renderAsync(` import Foo from services; h5 > '~[Foo.getName()]'; `); return UTest.domtest(dom, ` find('h5') > text FooServiceTest; `); } });
{ return 'FooServiceTest' }
identifier_body
index.js
import React from 'react'; import { connect } from 'react-redux' import Snackbar from 'material-ui/Snackbar'; import RaisedButton from 'material-ui/RaisedButton'; class Errors extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } ...
} handleActionClick = () => { this.setState({ open: false, }); }; handleRequestClose = () => { this.setState({ open: false, }); }; render() { const { error } = this.props if (!error || !error.message) { retu...
{ console.error("An error occurred", this.props.error) this.setState({ open: true }) }
conditional_block
index.js
import React from 'react'; import { connect } from 'react-redux' import Snackbar from 'material-ui/Snackbar'; import RaisedButton from 'material-ui/RaisedButton'; class Errors extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } ...
() { const { error } = this.props if (!error || !error.message) { return null } return ( <div> <Snackbar open={this.state.open} message={error && error.message} action="close" ...
render
identifier_name
index.js
import React from 'react'; import { connect } from 'react-redux' import Snackbar from 'material-ui/Snackbar'; import RaisedButton from 'material-ui/RaisedButton'; class Errors extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } ...
export default connect(mapStateToProps, {})(Errors)
{ const errors = state.errors.errors const error = state.errors.lastError return { error, } }
identifier_body
index.js
import React from 'react'; import { connect } from 'react-redux' import Snackbar from 'material-ui/Snackbar'; import RaisedButton from 'material-ui/RaisedButton'; class Errors extends React.Component { constructor(props) { super(props); this.state = { open: false, }; }
this.setState({ open: true }) } } handleActionClick = () => { this.setState({ open: false, }); }; handleRequestClose = () => { this.setState({ open: false, }); }; render() { const { error } = this.props ...
componentWillReceiveProps = () => { if (this.props.error) { console.error("An error occurred", this.props.error)
random_line_split
plot-link-actu-pred.py
#!/usr/bin/python3 -B # coding=utf8 # ------------------------------------------------------------------------------ import os import sys import math import random import matplotlib.pyplot as plt import matplotlib.ticker as pltckr import matplotlib.lines as pltlns import numpy as np from statistics import mean from co...
# ------------------------------------------------------------------------------ def do_plot(options): data = {} error = 0.0 for p in options.input_path: stats = DictObject.loadJson(p) for run in stats: for tgt in run.targets: try: data[tgt.n...
return ArgParser(prog=os.path.basename(__file__))
identifier_body
plot-link-actu-pred.py
#!/usr/bin/python3 -B # coding=utf8 # ------------------------------------------------------------------------------ import os import sys import math import random import matplotlib.pyplot as plt import matplotlib.ticker as pltckr import matplotlib.lines as pltlns import numpy as np from statistics import mean from co...
avp.plot(x, e, color="red") avp.plot(x, z, color="black") act.plot(x, a, color="black") act.scatter(x, a, color="black") options.finalize(plt) # ------------------------------------------------------------------------------ def main(): do_plot(make_argparser().make_options()) return 0 # --...
avp.plot(x, y, color="black") avp.scatter(x, y, color="black")
random_line_split
plot-link-actu-pred.py
#!/usr/bin/python3 -B # coding=utf8 # ------------------------------------------------------------------------------ import os import sys import math import random import matplotlib.pyplot as plt import matplotlib.ticker as pltckr import matplotlib.lines as pltlns import numpy as np from statistics import mean from co...
(): return ArgParser(prog=os.path.basename(__file__)) # ------------------------------------------------------------------------------ def do_plot(options): data = {} error = 0.0 for p in options.input_path: stats = DictObject.loadJson(p) for run in stats: for tgt in run.tar...
make_argparser
identifier_name
plot-link-actu-pred.py
#!/usr/bin/python3 -B # coding=utf8 # ------------------------------------------------------------------------------ import os import sys import math import random import matplotlib.pyplot as plt import matplotlib.ticker as pltckr import matplotlib.lines as pltlns import numpy as np from statistics import mean from co...
# ------------------------------------------------------------------------------
exit(main())
conditional_block
stock_maximize.rs
use std::io; use std::io::BufRead; fn stock_maximize(stock_values: &Vec<i64>) -> i64 { let mut money = 0i64; let mut current_max = *stock_values.last().unwrap(); for stock_values in stock_values.iter().rev() { if *stock_values <= current_max { money += current_max - stock_values; ...
#[test] fn sample2() { assert_eq!(197, super::stock_maximize(&vec![1, 2, 100])); } #[test] fn sample3() { assert_eq!(3, super::stock_maximize(&vec![1, 3, 1, 2])); } //&(1..250).collect() #[test] fn big() { super::stock_maximize(&(1..40000).collect()); ...
{ assert_eq!(0, super::stock_maximize(&vec![5, 3, 2])); }
identifier_body
stock_maximize.rs
use std::io; use std::io::BufRead; fn stock_maximize(stock_values: &Vec<i64>) -> i64 { let mut money = 0i64; let mut current_max = *stock_values.last().unwrap(); for stock_values in stock_values.iter().rev() { if *stock_values <= current_max { money += current_max - stock_values; ...
() { super::stock_maximize(&(1..40000).collect()); } }
big
identifier_name
stock_maximize.rs
use std::io; use std::io::BufRead; fn stock_maximize(stock_values: &Vec<i64>) -> i64 { let mut money = 0i64; let mut current_max = *stock_values.last().unwrap(); for stock_values in stock_values.iter().rev() { if *stock_values <= current_max { money += current_max - stock_values; ...
.map(|value| value.parse::<i64>().unwrap()) .take(count) .collect(); results.push(stock_maximize(&values)); } for result in results.iter() { println!("{}", result); } } #[cfg(test)] mod tests { #[test] fn sample1() { assert_eq!(0, super::...
while let Some(line_count) = lines_enum.next() { let count = line_count.unwrap().trim().parse::<usize>().unwrap(); let line_values = lines_enum.next().unwrap().unwrap(); let values: Vec<i64> = line_values.trim().split(' ')
random_line_split
stock_maximize.rs
use std::io; use std::io::BufRead; fn stock_maximize(stock_values: &Vec<i64>) -> i64 { let mut money = 0i64; let mut current_max = *stock_values.last().unwrap(); for stock_values in stock_values.iter().rev() { if *stock_values <= current_max
else { current_max = *stock_values; } } money } #[allow(dead_code)] fn main() { let stdin = io::stdin(); let mut lines = stdin.lock().lines(); let first_line = lines.next().unwrap().unwrap(); let t = first_line.trim().parse::<usize>().unwrap(); let mut lines_enum = line...
{ money += current_max - stock_values; }
conditional_block
problem_9.py
# -*- coding: utf-8 -*- # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a² + b² = c² # For example, 3² + 4² = 9 + 16 = 25 = 52. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc.
for a in range(1, n / 2 - 2): for b in range(a, n / 2 - 1): c = n - a - b if not c > b: continue if a ** 2 + b ** 2 == c ** 2: return a, b, c return None if __name__ == '__main__': ret = resolve(1000) print ret, reduce(lambda x...
def resolve(n):
random_line_split
problem_9.py
# -*- coding: utf-8 -*- # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a² + b² = c² # For example, 3² + 4² = 9 + 16 = 25 = 52. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. def resolve(n): for a in range(1, n / 2 - 2): ...
return None if __name__ == '__main__': ret = resolve(1000) print ret, reduce(lambda x, y: x * y, ret)
in range(a, n / 2 - 1): c = n - a - b if not c > b: continue if a ** 2 + b ** 2 == c ** 2: return a, b, c
conditional_block
problem_9.py
# -*- coding: utf-8 -*- # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a² + b² = c² # For example, 3² + 4² = 9 + 16 = 25 = 52. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. def resolve(n): for a
__name__ == '__main__': ret = resolve(1000) print ret, reduce(lambda x, y: x * y, ret)
in range(1, n / 2 - 2): for b in range(a, n / 2 - 1): c = n - a - b if not c > b: continue if a ** 2 + b ** 2 == c ** 2: return a, b, c return None if
identifier_body
problem_9.py
# -*- coding: utf-8 -*- # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a² + b² = c² # For example, 3² + 4² = 9 + 16 = 25 = 52. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. def resol
for a in range(1, n / 2 - 2): for b in range(a, n / 2 - 1): c = n - a - b if not c > b: continue if a ** 2 + b ** 2 == c ** 2: return a, b, c return None if __name__ == '__main__': ret = resolve(1000) print ret, reduce(lambda x...
ve(n):
identifier_name
htmldlistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDListElementBinding; use dom::bindings::js::Root; use dom::bindings::str...
HTMLDListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDListElement> { ...
htmlelement: HTMLElement } impl HTMLDListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDListElement {
random_line_split
htmldlistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDListElementBinding; use dom::bindings::js::Root; use dom::bindings::str...
#[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDListElement> { let element = HTMLDListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDListElem...
{ HTMLDListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
identifier_body
htmldlistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDListElementBinding; use dom::bindings::js::Root; use dom::bindings::str...
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDListElement { HTMLDListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Opt...
new_inherited
identifier_name
volsay.py
# Copyright 2011 Hakan Kjellerstrand hakank@gmail.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
Volsay problem in Google or-tools. From the OPL model volsay.mod This model was created by Hakan Kjellerstrand (hakank@gmail.com) Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ """ from ortools.linear_solver import pywraplp def main(unused_argv): # Create the solver....
# limitations under the License. """
random_line_split
volsay.py
# Copyright 2011 Hakan Kjellerstrand hakank@gmail.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
main('Volsay')
conditional_block
volsay.py
# Copyright 2011 Hakan Kjellerstrand hakank@gmail.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
(unused_argv): # Create the solver. # using GLPK #solver = pywraplp.Solver('CoinsGridGLPK', # pywraplp.Solver.GLPK_LINEAR_PROGRAMMING) # Using CLP solver = pywraplp.Solver('CoinsGridCLP', pywraplp.Solver.CLP_LINEAR_PROGRAMMING) # data # declare var...
main
identifier_name
volsay.py
# Copyright 2011 Hakan Kjellerstrand hakank@gmail.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
# # solution and search # solver.Solve() print() print('objective = ', solver.Objective().Value()) print('Gas = ', Gas.SolutionValue(), 'ReducedCost =', Gas.ReducedCost()) print('Chloride:', Chloride.SolutionValue(), 'ReducedCost =', Chloride.ReducedCost()) if __name__ == '__main__': main(...
solver = pywraplp.Solver('CoinsGridCLP', pywraplp.Solver.CLP_LINEAR_PROGRAMMING) # data # declare variables Gas = solver.NumVar(0, 100000, 'Gas') Chloride = solver.NumVar(0, 100000, 'Cloride') # # constraints # solver.Add(Gas + Chloride <= 50) solver.Add(3 * Gas + 4 * Chl...
identifier_body
Fixtures.js
(function() { function Fixtures()
artist: 'Guglielmo Marconi', label: 'EM', year: '1909', albumArtUrl: '/assets/images/album_covers/20.png', songs: [ { name: 'Hello, Operator?', length: '1:01' }, { name: 'Ring, ring, ring', length: '5:01' }, { name: 'Fits in your pocket', length: '3:21'}, { ...
{ var Fixtures = {}; var albumPicasso = { name: 'The Colors', artist: 'Pablo Picasso', label: 'Cubism', year: '1881', albumArtUrl: '/assets/images/album_covers/01.png', songs: [ { name: 'Blue', length: 161.71, audioUrl: 'assets/music/blue'}, { name: 'Green', ...
identifier_body
Fixtures.js
(function() { function Fixtures() { var Fixtures = {}; var albumPicasso = { name: 'The Colors', artist: 'Pablo Picasso', label: 'Cubism', year: '1881', albumArtUrl: '/assets/images/album_covers/01.png', songs: [ { name: 'Blue', length: 161.71, audioUrl: 'assets/mus...
return this.albums; }; return Fixtures; } angular .module('blocJams') .factory('Fixtures', Fixtures); })();
};
random_line_split
Fixtures.js
(function() { function Fixtures() { var Fixtures = {}; var albumPicasso = { name: 'The Colors', artist: 'Pablo Picasso', label: 'Cubism', year: '1881', albumArtUrl: '/assets/images/album_covers/01.png', songs: [ { name: 'Blue', length: 161.71, audioUrl: 'assets/mus...
; return this.albums; }; return Fixtures; } angular .module('blocJams') .factory('Fixtures', Fixtures); })();
{ this.albums.push(angular.copy(albumPicasso)); }
conditional_block
Fixtures.js
(function() { function
() { var Fixtures = {}; var albumPicasso = { name: 'The Colors', artist: 'Pablo Picasso', label: 'Cubism', year: '1881', albumArtUrl: '/assets/images/album_covers/01.png', songs: [ { name: 'Blue', length: 161.71, audioUrl: 'assets/music/blue'}, { name: 'Green...
Fixtures
identifier_name
launch_reduction.py
import os import traceback from mantidqt.utils.asynchronous import AsyncTask from addie.processing.mantid.master_table.master_table_exporter import TableFileExporter as MantidTableExporter # Mantid Total Scattering integration # (https://github.com/marshallmcdonnell/mantid_total_scattering) try: import total_scat...
(self, task_result): # TODO should emit a signal self.task_output = task_result.output print('SUCCESS!!! {}'.format(self.task_output)) def on_error(self, task_result): # TODO should emit a signal print('ERROR!!!') self.task_exc_type = task_result.exc_type sel...
on_success
identifier_name
launch_reduction.py
import os import traceback from mantidqt.utils.asynchronous import AsyncTask from addie.processing.mantid.master_table.master_table_exporter import TableFileExporter as MantidTableExporter # Mantid Total Scattering integration # (https://github.com/marshallmcdonnell/mantid_total_scattering) try: import total_scat...
def run_mantid(parent): num_rows = parent.processing_ui.h3_table.rowCount() if num_rows <= 0: raise RuntimeError('Cannot export empty table') exporter = MantidTableExporter(parent=parent) # write out the full table to disk # TODO make a class level name so it can be reused full_redu...
'''Both success and failure call this method afterwards''' # TODO should emit a signal self._start_next() # kick off the next one in the pool
identifier_body
launch_reduction.py
import os import traceback from mantidqt.utils.asynchronous import AsyncTask from addie.processing.mantid.master_table.master_table_exporter import TableFileExporter as MantidTableExporter # Mantid Total Scattering integration # (https://github.com/marshallmcdonnell/mantid_total_scattering) try: import total_scat...
if MANTID_TS_ENABLED: pool = JobPool(reduction_inputs) pool.start() else: # TODO should be on the status bar print('total_scattering module not found. Functionality disabled')
# locate total scattering script
random_line_split
launch_reduction.py
import os import traceback from mantidqt.utils.asynchronous import AsyncTask from addie.processing.mantid.master_table.master_table_exporter import TableFileExporter as MantidTableExporter # Mantid Total Scattering integration # (https://github.com/marshallmcdonnell/mantid_total_scattering) try: import total_scat...
else: # TODO should be on the status bar print('total_scattering module not found. Functionality disabled')
pool = JobPool(reduction_inputs) pool.start()
conditional_block
mod.rs
//! Collision detection algorithms and structure for the Narrow Phase. #[doc(inline)] pub use self::collision_detector::{CollisionDetector, CollisionDispatcher, CollisionAlgorithm}; pub use self::ball_ball::BallBall; pub use self::plane_support_map::{PlaneSupportMap, SupportMapPlane}; pub use self::support_map_support_...
mod plane_support_map; mod support_map_support_map; mod incremental_contact_manifold_generator; mod one_shot_contact_manifold_generator; mod composite_shape_repr; mod basic_collision_dispatcher;
pub mod collision_detector; #[doc(hidden)] pub mod contact_signal; mod ball_ball;
random_line_split
Gruntfile.ts
/* * Build scripts for persisto */ module.exports = (grunt: any) => { grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), exec: { build: { stdin: true, // Allow interactive console cmd: "yarn build",
qunit: { // options: { // timeout: 20000, // "--cookies-file": "misc/cookies.txt", // }, build: ["test/unit/test-core-build.html"], develop: ["test/unit/test-core.html"], }, yabs: { release: { common: { // defaults for all tools manif...
}, },
random_line_split
Gruntfile.ts
/* * Build scripts for persisto */ module.exports = (grunt: any) => { grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), exec: { build: { stdin: true, // Allow interactive console cmd: "yarn build", }, }, qunit: { // options: { // timeout: 20000, ...
} // Register tasks grunt.registerTask("test", ["qunit:develop"]); grunt.registerTask("ci", ["test"]); // Called by 'npm test' grunt.registerTask("default", ["test"]); if (parseInt(process.env.TRAVIS_PULL_REQUEST!, 10) > 0) { // saucelab keys do not work on forks // http://support.saucelabs.com/en...
{ grunt.loadNpmTasks(key); }
conditional_block
index.js
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import { GridList, GridListTile, GridListTileBar } from 'material-ui/GridList'; import Subheader from 'material-ui/List/ListSubheader'; import IconButton from 'material-ui/IconButton'; import InfoIcon from 'm...
(props) { const { classes, users, city, onSelectCity } = props; const gridListStyle = { width: city ? '80%' : 0, maxWidth: 1450, height: city ? 750 : 0 } return ( <div className={`${classes.container} fade`}> <GridList cellHeight={180} style={gridListStyle}> <GridListTile key="Su...
Grid
identifier_name
index.js
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import { GridList, GridListTile, GridListTileBar } from 'material-ui/GridList'; import Subheader from 'material-ui/List/ListSubheader'; import IconButton from 'material-ui/IconButton'; import InfoIcon from 'm...
</GridList> </div> ); } Grid.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(Grid);
{ const { classes, users, city, onSelectCity } = props; const gridListStyle = { width: city ? '80%' : 0, maxWidth: 1450, height: city ? 750 : 0 } return ( <div className={`${classes.container} fade`}> <GridList cellHeight={180} style={gridListStyle}> <GridListTile key="Subheader"...
identifier_body
index.js
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import { GridList, GridListTile, GridListTileBar } from 'material-ui/GridList'; import Subheader from 'material-ui/List/ListSubheader'; import IconButton from 'material-ui/IconButton'; import InfoIcon from 'm...
function Grid(props) { const { classes, users, city, onSelectCity } = props; const gridListStyle = { width: city ? '80%' : 0, maxWidth: 1450, height: city ? 750 : 0 } return ( <div className={`${classes.container} fade`}> <GridList cellHeight={180} style={gridListStyle}> <GridLis...
height: 600 }, });
random_line_split
headline.spec.tsx
import {shallow} from 'enzyme';
import Headline, {defaultProps, HeadlineProps} from './headline'; describe('<Headline/>', () => { const props: HeadlineProps = { ...defaultProps, children: 'Foo children', theme: { 'heading': 'headingClassName', } }; it('should render correctly.', () => { ...
import toJson from 'enzyme-to-json'; import React from 'react';
random_line_split
datastore.js
module.exports = { name: "datastore", ns: "nedb", description: "Nedb Datastore", phrases: { active: "Creating datastore" }, dependencies: { npm: { nedb: require('nedb') } }, ports: { input: { options: { title: "Options", type: "object", required: false...
} else { output({ db: $.create(db) }); } }); }.call(this); return { output: output, state: state, on: on, return: r }; } }
random_line_split
datastore.js
module.exports = { name: "datastore", ns: "nedb", description: "Nedb Datastore", phrases: { active: "Creating datastore" }, dependencies: { npm: { nedb: require('nedb') } }, ports: { input: { options: { title: "Options", type: "object", required: false...
else { output({ db: $.create(db) }); } }); }.call(this); return { output: output, state: state, on: on, return: r }; } }
{ output({ error: $.create(err) }); }
conditional_block
audioProcessor.js
var __decorate = this.__decorate || function (decorators, target, key, value) { var kind = typeof (arguments.length == 2 ? value = target : value); for (var i = decorators.length - 1; i >= 0; --i) { var decorator = decorators[i]; switch (kind) { case "function": value = decorator(val...
this.sourceBuffer = this.audioContext.createBufferSource(); //create the analyser node this.analyser = this.audioContext.createAnalyser(); this.analyser.smoothingTimeConstant = 0.3; this.analyser.fftSize = 512; //connect source to analyser this.sourceBuffer.connec...
{ var _this = this; this.onProcessing = function () { var array = new Uint8Array(_this.analyser.frequencyBinCount); _this.analyser.getByteFrequencyData(array); _this.renderer.render(array); _this.timeline.headStep(_this.audioContext.currentTime); }...
identifier_body
audioProcessor.js
var __decorate = this.__decorate || function (decorators, target, key, value) { var kind = typeof (arguments.length == 2 ? value = target : value); for (var i = decorators.length - 1; i >= 0; --i) { var decorator = decorators[i]; switch (kind) { case "function": value = decorator(val...
(renderer, timeline) { var _this = this; this.onProcessing = function () { var array = new Uint8Array(_this.analyser.frequencyBinCount); _this.analyser.getByteFrequencyData(array); _this.renderer.render(array); _this.timeline.headStep(_this.audioContext.cu...
AudioProcessor
identifier_name
audioProcessor.js
var __decorate = this.__decorate || function (decorators, target, key, value) { var kind = typeof (arguments.length == 2 ? value = target : value); for (var i = decorators.length - 1; i >= 0; --i)
return value; }; var AudioProcessor = (function () { function AudioProcessor(renderer, timeline) { var _this = this; this.onProcessing = function () { var array = new Uint8Array(_this.analyser.frequencyBinCount); _this.analyser.getByteFrequencyData(array); _t...
{ var decorator = decorators[i]; switch (kind) { case "function": value = decorator(value) || value; break; case "number": decorator(target, key, value); break; case "undefined": decorator(target, key); break; case "object": value = decorator(target, key, ...
conditional_block
audioProcessor.js
var decorator = decorators[i]; switch (kind) { case "function": value = decorator(value) || value; break; case "number": decorator(target, key, value); break; case "undefined": decorator(target, key); break; case "object": value = decorator(target, key, va...
var __decorate = this.__decorate || function (decorators, target, key, value) { var kind = typeof (arguments.length == 2 ? value = target : value); for (var i = decorators.length - 1; i >= 0; --i) {
random_line_split
unexpand.rs
#![crate_name = "unexpand"] /* * This file is part of the uutils coreutils package. * * (c) Virgile Andreani <virgile.andreani@anbuco.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #![feature(macro_rules)] extern crate geto...
(s: String) -> Vec<uint> { let words = s.as_slice().split(',').collect::<Vec<&str>>(); let nums = words.into_iter() .map(|sn| from_str::<uint>(sn) .unwrap_or_else( || crash!(1, "{}\n", "tab size contains invalid character(s)")) ) .collect::<Vec<uint>>(); ...
tabstops_parse
identifier_name
unexpand.rs
#![crate_name = "unexpand"] /* * This file is part of the uutils coreutils package. * * (c) Virgile Andreani <virgile.andreani@anbuco.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #![feature(macro_rules)] extern crate geto...
file_buf = match io::File::open(&Path::new(path.as_slice())) { Ok(a) => a, _ => crash!(1, "{}: {}\n", path, "No such file or directory") }; io::BufferedReader::new(box file_buf as Box<Reader>) } } fn is_tabstop(tabstops: &[uint], col: uint) -> bool { match tabsto...
random_line_split
unexpand.rs
#![crate_name = "unexpand"] /* * This file is part of the uutils coreutils package. * * (c) Virgile Andreani <virgile.andreani@anbuco.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #![feature(macro_rules)] extern crate geto...
if is_tabstop(ts, col) { nspaces = 0; col += 1; safe_write!(&mut output, "{}", '\t'); } match to_next_stop(ts, col) { Some(to_next) => { ...
{ let mut output = io::stdout(); let ts = options.tabstops.as_slice(); for file in options.files.into_iter() { let mut col = 0; let mut nspaces = 0; let mut init = true; for c in open(file).chars() { match c { Ok(' ') => { if i...
identifier_body
app.module.ts
import { NgModule } from '@angular/core'; import { IonicApp, IonicModule } from 'ionic-angular'; import { CloudSettings, CloudModule } from '@ionic/cloud-angular'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { ResultPage } from '../pages/result/result'; import { ChuckN...
{ }
AppModule
identifier_name
app.module.ts
import { NgModule } from '@angular/core'; import { IonicApp, IonicModule } from 'ionic-angular'; import { CloudSettings, CloudModule } from '@ionic/cloud-angular'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { ResultPage } from '../pages/result/result'; import { ChuckN...
], providers: [ChuckNorrisJokesService] }) export class AppModule { }
bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage, ResultPage
random_line_split
angular-locale_nl-sr.js
/* * This file is part of huborcid. * * huborcid 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. * * huborcid is distrib...
"za" ], "SHORTMONTH": [ "jan.", "feb.", "mrt.", "apr.", "mei", "jun.", "jul.", "aug.", "sep.", "okt.", "nov.", "dec." ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", ...
"vr",
random_line_split
angular-locale_nl-sr.js
/* * This file is part of huborcid. * * huborcid 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. * * huborcid is distrib...
(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide....
getDecimals
identifier_name
angular-locale_nl-sr.js
/* * This file is part of huborcid. * * huborcid 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. * * huborcid is distrib...
function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "a.m.", "p.m." ]...
{ n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; }
identifier_body
angular-locale_nl-sr.js
/* * This file is part of huborcid. * * huborcid 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. * * huborcid is distrib...
var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "a.m.", "p.m." ], "DAY": [ "zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "za...
{ v = Math.min(getDecimals(n), 3); }
conditional_block
ScriptExt.js
Clazz.declarePackage ("JS"); Clazz.load (null, "JS.ScriptExt", ["JU.AU"], function () { c$ = Clazz.decorateAsClass (function () { this.vwr = null; this.e = null; this.chk = false; this.st = null; this.slen = 0; Clazz.instantialize (this, arguments); }, JS, "ScriptExt"); Clazz.defineMethod (c$, "init", funct...
} if (points == null) { if (bs == null) bs = this.vwr.getAllAtoms (); points = new Array (bs.cardinality ()); for (var i = bs.nextSetBit (0), pt = 0; i >= 0; i = bs.nextSetBit (i + 1)) points[pt++] = this.vwr.ms.at[i]; }} catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } if (points...
case 1073742325: bs = this.atomExpressionAt (index); break;
random_line_split
220 Contains Duplicate III.py
class
(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i ...
Solution
identifier_name