file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
index.js | // External Dependencies
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
// Our Dependencies
import { track } from '../../util/analytics';
import * as BooksAPI from '../../BooksAPI';
import { getSuggetions } from '../../util/search';
// Our Components
import BookL... |
this.setState({ results, isSearching: false });
})
} else {
this.setState({ results: [] });
}
}
render() {
const { query, results, isSearching } = this.state;
const { onBackClick, onShelfChange, isFetching, onBookClick } = this.props;
const suggestions = getSuggetions();
... | {
const { books } = this.props;
// istanbul ignore next
books.forEach(b => {
resp.forEach((r, i, arr) => {
if (r.id === b.id) {
arr[i].shelf = b.shelf;
}
})
});
results = resp;
} | conditional_block |
index.js | // External Dependencies
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
// Our Dependencies
import { track } from '../../util/analytics';
import * as BooksAPI from '../../BooksAPI';
import { getSuggetions } from '../../util/search';
// Our Components
import BookL... | () {
const { lastQuery } = localStorage;
if (lastQuery) {
this.updateQuery(lastQuery);
}
track(window);
}
componentWillReceiveProps =({ books }) => {
const clonedResults = _.cloneDeep(this.state.results);
books.forEach(b => {
clonedResults.forEach((r, i, arr) => {
if (r.... | componentDidMount | identifier_name |
HandDetails.py | from triple_draw_poker.model.Pot import Pot
class HandDetails:
def __init__(self):
self.pot = Pot()
self.raised = 0
self.street = 0
self.number_of_streets = 4
self.in_draw = False
self.hands = []
self.dealt_cards_index = 0
def getDealtCardsIndex(self):
... | (self):
return self.street
def getStreetPremium(self):
if self.street < 3:
return 2
return 1
def getNumberOfStreets(self):
return self.number_of_streets
def getInDraw(self):
return self.in_draw
def setDealtCardsIndex(self, index):
self.deal... | getStreet | identifier_name |
HandDetails.py | from triple_draw_poker.model.Pot import Pot
class HandDetails:
def __init__(self):
self.pot = Pot()
self.raised = 0
self.street = 0
self.number_of_streets = 4
self.in_draw = False
self.hands = []
self.dealt_cards_index = 0
def getDealtCardsIndex(self):
... |
def getInDraw(self):
return self.in_draw
def setDealtCardsIndex(self, index):
self.dealt_cards_index = index
def addHand(self, hand):
self.hands.append(hand)
def incrementRaised(self):
self.raised += 1
def incrementStreet(self):
self.street += 1
def... | return self.number_of_streets | identifier_body |
HandDetails.py | from triple_draw_poker.model.Pot import Pot
class HandDetails:
def __init__(self):
self.pot = Pot()
self.raised = 0
self.street = 0
self.number_of_streets = 4
self.in_draw = False
self.hands = []
self.dealt_cards_index = 0
def getDealtCardsIndex(self):
... |
return 1
def getNumberOfStreets(self):
return self.number_of_streets
def getInDraw(self):
return self.in_draw
def setDealtCardsIndex(self, index):
self.dealt_cards_index = index
def addHand(self, hand):
self.hands.append(hand)
def incrementRaised(self):
... | return 2 | conditional_block |
HandDetails.py | from triple_draw_poker.model.Pot import Pot
class HandDetails:
def __init__(self):
self.pot = Pot()
self.raised = 0
self.street = 0
self.number_of_streets = 4
self.in_draw = False
self.hands = []
self.dealt_cards_index = 0
def getDealtCardsIndex(self):
... |
def getRaised(self):
return self.raised
def getStreet(self):
return self.street
def getStreetPremium(self):
if self.street < 3:
return 2
return 1
def getNumberOfStreets(self):
return self.number_of_streets
def getInDraw(self):
return s... | def getHands(self):
return self.hands
def getPot(self):
return self.pot | random_line_split |
code.py | back entries.
"""
Entry = TracebackEntry
def __init__(self, tb, excinfo=None):
""" initialize from given python traceback object and ExceptionInfo """
self._excinfo = excinfo
if hasattr(tb, "tb_next"):
|
else:
list.__init__(self, tb)
def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):
""" return a Traceback instance wrapping part of this Traceback
by provding any combination of path, lineno and firstlineno, the
first frame to start the to... | def f(cur):
while cur is not None:
yield self.Entry(cur, excinfo=excinfo)
cur = cur.tb_next
list.__init__(self, f(tb)) | conditional_block |
code.py | -> Traceback:
"""the traceback"""
if self._traceback is None:
self._traceback = Traceback(self.tb, excinfo=ref(self))
return self._traceback
@traceback.setter
def traceback(self, value: Traceback) -> None:
self._traceback = value
def __repr__(self) -> str:
... | _makepath | identifier_name | |
code.py | back entries.
"""
Entry = TracebackEntry
def __init__(self, tb, excinfo=None):
""" initialize from given python traceback object and ExceptionInfo """
self._excinfo = excinfo
if hasattr(tb, "tb_next"):
def f(cur):
while cur is not None:
... |
@property
def value(self) -> _E:
"""the exception value"""
assert (
self._excinfo is not None
), ".value can only be used after the context manager exits"
return self._excinfo[1]
@property
def tb(self) -> TracebackType:
"""the exception raw tracebac... | """the exception class"""
assert (
self._excinfo is not None
), ".type can only be used after the context manager exits"
return self._excinfo[0] | identifier_body |
code.py | Traceback entries.
"""
Entry = TracebackEntry
def __init__(self, tb, excinfo=None):
""" initialize from given python traceback object and ExceptionInfo """
self._excinfo = excinfo
if hasattr(tb, "tb_next"):
def f(cur):
while cur is not None:
... | showlocals: bool = False,
style: str = "long",
abspath: bool = False,
tbfilter: bool = True,
funcargs: bool = False,
truncate_locals: | def getrepr(
self, | random_line_split |
test_generate_course_overview.py | # pylint: disable=missing-docstring
from django.core.management.base import CommandError
from mock import patch
from nose.plugins.attrib import attr
from openedx.core.djangoapps.content.course_overviews.management.commands import generate_course_overview
from openedx.core.djangoapps.content.course_overviews.models impo... | (self):
"""
Test exception raised when no parameters are specified.
"""
with self.assertRaises(CommandError):
self.command.handle(all=False)
| test_no_params | identifier_name |
test_generate_course_overview.py | # pylint: disable=missing-docstring
from django.core.management.base import CommandError
from mock import patch
from nose.plugins.attrib import attr
from openedx.core.djangoapps.content.course_overviews.management.commands import generate_course_overview
from openedx.core.djangoapps.content.course_overviews.models impo... | """
self.command.handle('fake/course/id', all=False)
self.assertTrue(mock_log.exception.called)
def test_no_params(self):
"""
Test exception raised when no parameters are specified.
"""
with self.assertRaises(CommandError):
self.command.handle(all... | def test_not_found_key(self, mock_log):
"""
Test keys not found are logged. | random_line_split |
test_generate_course_overview.py | # pylint: disable=missing-docstring
from django.core.management.base import CommandError
from mock import patch
from nose.plugins.attrib import attr
from openedx.core.djangoapps.content.course_overviews.management.commands import generate_course_overview
from openedx.core.djangoapps.content.course_overviews.models impo... |
def test_generate_all(self):
"""
Test that all courses in the modulestore are loaded into course overviews.
"""
# ensure that the newly created courses aren't in course overviews
self._assert_courses_not_in_overview(self.course_key_1, self.course_key_2)
self.command... | self.assertIn(expected_course_key, course_keys) | conditional_block |
test_generate_course_overview.py | # pylint: disable=missing-docstring
from django.core.management.base import CommandError
from mock import patch
from nose.plugins.attrib import attr
from openedx.core.djangoapps.content.course_overviews.management.commands import generate_course_overview
from openedx.core.djangoapps.content.course_overviews.models impo... |
def test_generate_all(self):
"""
Test that all courses in the modulestore are loaded into course overviews.
"""
# ensure that the newly created courses aren't in course overviews
self._assert_courses_not_in_overview(self.course_key_1, self.course_key_2)
self.command... | """
Assert courses exists in course overviews.
"""
course_keys = CourseOverview.get_all_course_keys()
for expected_course_key in courses:
self.assertIn(expected_course_key, course_keys) | identifier_body |
randexp_vx.x.x.js | // flow-typed signature: e7c03a4ac695e4a014530cf5ab6c79da
// flow-typed version: <<STUB>>/randexp_v^0.4.3/flow_v0.37.0
/**
* This is an autogenerated libdef stub for:
*
* 'randexp'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* co... | declare module.exports: any;
}
declare module 'randexp/test/tests' {
declare module.exports: any;
}
// Filename aliases
declare module 'randexp/build/randexp.min.js' {
declare module.exports: $Exports<'randexp/build/randexp.min'>;
}
declare module 'randexp/gulpfile.js' {
declare module.exports: $Exports<'rand... | declare module 'randexp/test/sugar-test' { | random_line_split |
mod.ts | import {ModCollection, ModPrimary, ModPrimaryValue, ModSlot, TranslatedModName, Mod} from "../interface";
export const parseModCollection = ($: CheerioStatic): ModCollection => {
const m = $("body > div.container.p-t-md > div.content-container > div.content-container-primary.mod-list > ul > li.media.list-gro... |
return +m[1];
};
| {
return null;
} | conditional_block |
mod.ts | import {ModCollection, ModPrimary, ModPrimaryValue, ModSlot, TranslatedModName, Mod} from "../interface"; |
const m = $("body > div.container.p-t-md > div.content-container > div.content-container-primary.mod-list > ul > li.media.list-group-item.p-a.collection-mod-list > div > div > div")
.map(function (x) {
const _$ = $(this);
const tier = _$.find(".statmod-pip").length;
co... |
export const parseModCollection = ($: CheerioStatic): ModCollection => { | random_line_split |
index.ts | import { action, computed, observable } from 'mobx';
import { generateId } from 'utils/generate-id';
import { filterMethods } from 'utils/log-filter';
import { Connection, LineConnection } from './connection';
import { Point } from './point';
import { PointsByTick } from './points-by-tick';
import { TimelineVector } ... |
@action
addPoint(point: Point) {
this.addPointAtEnd(point);
}
@action
removePoint(point: Point) {
if (this.canRemovePoint(point)) {
this.removePoint_(point);
}
}
private removePoint_(point: Point) {
this.points.remove(point);
this.pointsByTick.remove(point);
this.pointInd... | {
this.points.forEach((p, index) => {
this.pointIndices.set(p, index);
});
} | identifier_body |
index.ts | import { action, computed, observable } from 'mobx';
import { generateId } from 'utils/generate-id';
import { filterMethods } from 'utils/log-filter';
import { Connection, LineConnection } from './connection';
import { Point } from './point';
import { PointsByTick } from './points-by-tick';
import { TimelineVector } ... | removePoint(point: Point) {
if (this.canRemovePoint(point)) {
this.removePoint_(point);
}
}
private removePoint_(point: Point) {
this.points.remove(point);
this.pointsByTick.remove(point);
this.pointIndices.delete(point);
this.updatePointIndices();
}
@action
setPointPosition(... |
@action | random_line_split |
index.ts | import { action, computed, observable } from 'mobx';
import { generateId } from 'utils/generate-id';
import { filterMethods } from 'utils/log-filter';
import { Connection, LineConnection } from './connection';
import { Point } from './point';
import { PointsByTick } from './points-by-tick';
import { TimelineVector } ... | (e: Envelope, ticks: number) {
const p = e.pointsByTick.get(ticks);
const output = p instanceof Array ? p : p instanceof Point ? [p] : [];
return output.sort((a, b) => e.getIndex(a) - e.getIndex(b));
}
}
const isSorted = (points: Point[]) => {
if (points.length === 0) return true;
const lastPosition ... | getPointsAtTicks | identifier_name |
uSqlExternalDataSourceList.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | () {
super();
}
/**
* Defines the metadata of USqlExternalDataSourceList
*
* @returns {object} metadata of USqlExternalDataSourceList
*
*/
mapper() {
return {
required: false,
serializedName: 'USqlExternalDataSourceList',
type: {
name: 'Composite',
classNa... | constructor | identifier_name |
uSqlExternalDataSourceList.js | * Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* @class
* Initializes a new instance of the... | /*
* Copyright (c) Microsoft Corporation. All rights reserved. | random_line_split | |
TypeDefinitions.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import { HTMLElement } from '@ephox/dom-globals';
// Localised Type ... | y: () => number;
}
// Sugar Position
export interface PositionCoordinates {
left: () => number;
top: () => number;
translate: (x: number, y: number) => PositionCoordinates;
} | raw: () => any;
stop: () => void;
target: () => SugarElement;
x: () => number; | random_line_split |
fromIterable.ts | import test from 'ava';
import { isImmutable } from '@collectable/core';
import { fromIterable, isEmpty, size } from '../src';
const pairs: [string, string][] = [['A', 'a'], ['B', 'b'], ['C', 'c'], ['D', 'd'], ['E', 'e']];
let it: IterableIterator<[string, string]>;
test.beforeEach(() => {
it = new Map(pairs).entri... | });
test('the returned set is frozen', t => {
t.true(isImmutable(fromIterable(it)));
}); | t.is(size(fromIterable(it)), pairs.length); | random_line_split |
plot_circos_plot.py | #!/usr/bin/env python
"""
Read the list of chimeric interactions and generate a file that can be read
by circos.
"""
import sys | import argparse
from collections import defaultdict
from math import log
import pro_clash
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
argv = sys.argv[1:]
# initi... | random_line_split | |
plot_circos_plot.py | #!/usr/bin/env python
"""
Read the list of chimeric interactions and generate a file that can be read
by circos.
"""
import sys
import argparse
from collections import defaultdict
from math import log
import pro_clash
def process_command_line(argv):
| help='Name of chromosome to plot.')
parser.add_argument(
'-p', '--print_chr', default='ecmain',
help='Name of chromosome in circos.')
parser.add_argument(
'-m', '--min_interactions', type=int, default=100,
help='Minimum number of interactions between two regions to plot.'... | """
Return a 2-tuple: (settings object, args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object, replace the description
parser = argparse.ArgumentParser(
description='Generate circos data... | identifier_body |
plot_circos_plot.py | #!/usr/bin/env python
"""
Read the list of chimeric interactions and generate a file that can be read
by circos.
"""
import sys
import argparse
from collections import defaultdict
from math import log
import pro_clash
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`a... | (argv=None):
settings = process_command_line(argv)
region_interactions, _, _, _=\
pro_clash.read_reads_table(open(settings.reads_in), settings.region)
both_strs = defaultdict(lambda: defaultdict(int))
for reg1 in region_interactions:
if reg1[2] != settings.chrn:
continue
... | main | identifier_name |
plot_circos_plot.py | #!/usr/bin/env python
"""
Read the list of chimeric interactions and generate a file that can be read
by circos.
"""
import sys
import argparse
from collections import defaultdict
from math import log
import pro_clash
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`a... |
# initialize the parser object, replace the description
parser = argparse.ArgumentParser(
description='Generate circos data file.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'reads_in',
help='An output file of map_chimeric_fragments.py wit... | argv = sys.argv[1:] | conditional_block |
fixtures.ts | import * as utxolib from '@bitgo/utxo-lib';
import * as fs from 'fs/promises';
export type Fixture = {
transaction: { hex: string };
inputs: { hex: string }[];
};
export async function getTransactionWithSpendType(
network: utxolib.Network,
t: utxolib.bitgo.outputScripts.ScriptType2Of3
): Promise<[utxolib.bitg... | );
function getPrevOut(i: utxolib.TxInput): utxolib.TxOutput {
for (const t of inputTxs) {
if (t.getHash().equals(i.hash) && i.index in t.outs) {
return t.outs[i.index];
}
}
throw new Error(`missing input ${utxolib.bitgo.formatOutputId(utxolib.bitgo.getOutputIdForInput(i))}`);
}
... | const f: Fixture = await JSON.parse(
await fs.readFile(
`../utxo-lib/test/integration_local_rpc/fixtures/${utxolib.getNetworkName(network)}/v1/spend_${t}.json`,
'utf8'
) | random_line_split |
fixtures.ts | import * as utxolib from '@bitgo/utxo-lib';
import * as fs from 'fs/promises';
export type Fixture = {
transaction: { hex: string };
inputs: { hex: string }[];
};
export async function getTransactionWithSpendType(
network: utxolib.Network,
t: utxolib.bitgo.outputScripts.ScriptType2Of3
): Promise<[utxolib.bitg... |
throw e;
}
}
| {
await fs.writeFile(path, defaultValue, 'utf8');
throw new Error(`wrote default value for ${path}`);
} | conditional_block |
fixtures.ts | import * as utxolib from '@bitgo/utxo-lib';
import * as fs from 'fs/promises';
export type Fixture = {
transaction: { hex: string };
inputs: { hex: string }[];
};
export async function getTransactionWithSpendType(
network: utxolib.Network,
t: utxolib.bitgo.outputScripts.ScriptType2Of3
): Promise<[utxolib.bitg... | (path: string, defaultValue: string): Promise<string> {
try {
return await fs.readFile(path, 'utf8');
} catch (e) {
if ((e as any).code === 'ENOENT') {
await fs.writeFile(path, defaultValue, 'utf8');
throw new Error(`wrote default value for ${path}`);
}
throw e;
}
}
| getFixtureString | identifier_name |
fixtures.ts | import * as utxolib from '@bitgo/utxo-lib';
import * as fs from 'fs/promises';
export type Fixture = {
transaction: { hex: string };
inputs: { hex: string }[];
};
export async function getTransactionWithSpendType(
network: utxolib.Network,
t: utxolib.bitgo.outputScripts.ScriptType2Of3
): Promise<[utxolib.bitg... | {
try {
return await fs.readFile(path, 'utf8');
} catch (e) {
if ((e as any).code === 'ENOENT') {
await fs.writeFile(path, defaultValue, 'utf8');
throw new Error(`wrote default value for ${path}`);
}
throw e;
}
} | identifier_body | |
lc993-cousins-in-binary-tree.py | # coding=utf-8
import unittest | https://leetcode.com/problems/cousins-in-binary-tree/description/
In a binary tree, the root node is at depth `0`, and children of each depth
`k` node are at depth `k+1`.
Two nodes of a binary tree are _cousins_ if they have the same depth, but have
**different parents**.
We are given the `root` of a binary tree wit... |
"""993. Cousins in Binary Tree | random_line_split |
lc993-cousins-in-binary-tree.py | # coding=utf-8
import unittest
"""993. Cousins in Binary Tree
https://leetcode.com/problems/cousins-in-binary-tree/description/
In a binary tree, the root node is at depth `0`, and children of each depth
`k` node are at depth `k+1`.
Two nodes of a binary tree are _cousins_ if they have the same depth, but have
**dif... |
if __name__ == "__main__":
unittest.main()
| pass | identifier_body |
lc993-cousins-in-binary-tree.py | # coding=utf-8
import unittest
"""993. Cousins in Binary Tree
https://leetcode.com/problems/cousins-in-binary-tree/description/
In a binary tree, the root node is at depth `0`, and children of each depth
`k` node are at depth `k+1`.
Two nodes of a binary tree are _cousins_ if they have the same depth, but have
**dif... | unittest.main() | conditional_block | |
lc993-cousins-in-binary-tree.py | # coding=utf-8
import unittest
"""993. Cousins in Binary Tree
https://leetcode.com/problems/cousins-in-binary-tree/description/
In a binary tree, the root node is at depth `0`, and children of each depth
`k` node are at depth `k+1`.
Two nodes of a binary tree are _cousins_ if they have the same depth, but have
**dif... | (object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
:rtype: bool
"""
def test(self):
pass
if __name__ == "__main__":
unittest.main()
| Solution | identifier_name |
main.rs | #![crate_name = "weather-client"]
/*!
* Weather update client
* Connects SUB socket to tcp://localhost:5556
* Collects weather updates and find avg temp in zipcode
*/
extern crate zmq;
fn atoi(s: &str) -> int {
from_str(s).unwrap()
}
fn main() {
println!("Collecting updates from weather server...");
... |
let mut total_temp = 0;
for _ in range(0i, 100i) {
let string = subscriber.recv_str(0).unwrap();
let chks: Vec<int> = string.as_slice().split(' ').map(|x| atoi(x)).collect();
let (_zipcode, temperature, _relhumidity) = (chks[0], chks[1], chks[2]);
total_temp += temperature;
... | assert!(subscriber.connect("tcp://localhost:5556").is_ok());
let args = std::os::args();
let filter = if args.len() > 1 { args[1].clone() } else { "10001".to_string() };
assert!(subscriber.set_subscribe(filter.as_bytes()).is_ok()); | random_line_split |
main.rs | #![crate_name = "weather-client"]
/*!
* Weather update client
* Connects SUB socket to tcp://localhost:5556
* Collects weather updates and find avg temp in zipcode
*/
extern crate zmq;
fn | (s: &str) -> int {
from_str(s).unwrap()
}
fn main() {
println!("Collecting updates from weather server...");
let mut context = zmq::Context::new();
let mut subscriber = context.socket(zmq::SUB).unwrap();
assert!(subscriber.connect("tcp://localhost:5556").is_ok());
let args = std::os::args();
... | atoi | identifier_name |
main.rs | #![crate_name = "weather-client"]
/*!
* Weather update client
* Connects SUB socket to tcp://localhost:5556
* Collects weather updates and find avg temp in zipcode
*/
extern crate zmq;
fn atoi(s: &str) -> int {
from_str(s).unwrap()
}
fn main() {
println!("Collecting updates from weather server...");
... | ;
assert!(subscriber.set_subscribe(filter.as_bytes()).is_ok());
let mut total_temp = 0;
for _ in range(0i, 100i) {
let string = subscriber.recv_str(0).unwrap();
let chks: Vec<int> = string.as_slice().split(' ').map(|x| atoi(x)).collect();
let (_zipcode, temperature, _relhumidity) =... | { "10001".to_string() } | conditional_block |
main.rs | #![crate_name = "weather-client"]
/*!
* Weather update client
* Connects SUB socket to tcp://localhost:5556
* Collects weather updates and find avg temp in zipcode
*/
extern crate zmq;
fn atoi(s: &str) -> int |
fn main() {
println!("Collecting updates from weather server...");
let mut context = zmq::Context::new();
let mut subscriber = context.socket(zmq::SUB).unwrap();
assert!(subscriber.connect("tcp://localhost:5556").is_ok());
let args = std::os::args();
let filter = if args.len() > 1 { args[1].... | {
from_str(s).unwrap()
} | identifier_body |
bench.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use lz4_pyframe::compress;
use lz4_pyframe::decompress;
use minibench::bench;
use minibench::elapsed;
use rand_core::RngCore;
use rand_core... | {
let mut rng = rand_chacha::ChaChaRng::seed_from_u64(0);
let mut buf = vec![0u8; 100_000000];
rng.fill_bytes(&mut buf);
let compressed = compress(&buf).unwrap();
bench("compress (100M)", || {
elapsed(|| {
compress(&buf).unwrap();
})
});
bench("decompress (~100M... | identifier_body | |
bench.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use lz4_pyframe::compress;
use lz4_pyframe::decompress;
use minibench::bench;
use minibench::elapsed;
use rand_core::RngCore;
use rand_core... |
bench("decompress (~100M)", || {
elapsed(|| {
decompress(&compressed).unwrap();
})
});
} | compress(&buf).unwrap();
})
}); | random_line_split |
bench.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use lz4_pyframe::compress;
use lz4_pyframe::decompress;
use minibench::bench;
use minibench::elapsed;
use rand_core::RngCore;
use rand_core... | () {
let mut rng = rand_chacha::ChaChaRng::seed_from_u64(0);
let mut buf = vec![0u8; 100_000000];
rng.fill_bytes(&mut buf);
let compressed = compress(&buf).unwrap();
bench("compress (100M)", || {
elapsed(|| {
compress(&buf).unwrap();
})
});
bench("decompress (~1... | main | identifier_name |
BrowserTests.js | import assert from 'assert'
import {PrivateKey, PublicKey} from 'shared/ecc'
import {encode, decode} from 'shared/chain/memo'
import {serverApiRecordEvent} from 'app/utils/ServerApiClient'
export const browserTests = {}
export default function runTests() | it('create private key', () => {
private_key = PrivateKey.fromSeed('1')
assert.equal(private_key.toWif(), wif)
})
it('supports WIF format', () => {
assert.deepEqual(PrivateKey.fromWif(wif), private_key)
})
it('finds public from private key', () => {
public_key = priv... | {
let rpt = ''
let pass = true
function it(name, fn) {
console.log('Testing', name)
rpt += 'Testing ' + name + '\n'
try {
fn()
} catch(error) {
console.error(error)
pass = false
rpt += error.stack + '\n\n'
serverApiR... | identifier_body |
BrowserTests.js | import assert from 'assert'
import {PrivateKey, PublicKey} from 'shared/ecc'
import {encode, decode} from 'shared/chain/memo'
import {serverApiRecordEvent} from 'app/utils/ServerApiClient'
export const browserTests = {}
export default function runTests() {
let rpt = ''
let pass = true
function | (name, fn) {
console.log('Testing', name)
rpt += 'Testing ' + name + '\n'
try {
fn()
} catch(error) {
console.error(error)
pass = false
rpt += error.stack + '\n\n'
serverApiRecordEvent('client_error', error)
}
}
... | it | identifier_name |
BrowserTests.js | import assert from 'assert'
import {PrivateKey, PublicKey} from 'shared/ecc'
import {encode, decode} from 'shared/chain/memo'
import {serverApiRecordEvent} from 'app/utils/ServerApiClient'
export const browserTests = {}
export default function runTests() {
let rpt = ''
let pass = true
function it(name, fn... |
// TODO: FIX! assert.equal(dec, _memo, 'decoded memo did not match original');
})
if(!pass) return rpt
}
| {
console.error('Decoded memo did not match (memo encryption is unavailable)')
browserTests.memo_encryption = false
} | conditional_block |
BrowserTests.js | import assert from 'assert'
import {PrivateKey, PublicKey} from 'shared/ecc'
import {encode, decode} from 'shared/chain/memo'
import {serverApiRecordEvent} from 'app/utils/ServerApiClient'
export const browserTests = {}
export default function runTests() {
let rpt = ''
let pass = true
function it(name, fn... | } catch(error) {
console.error(error)
pass = false
rpt += error.stack + '\n\n'
serverApiRecordEvent('client_error', error)
}
}
let private_key, public_key, encodedMemo
const wif = '5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw'
const... | try {
fn() | random_line_split |
index.js | module.exports = function bool_it_up (val) {
if (typeof val === 'boolean') {
return val
}
if (typeof val === 'string') {
if (/^(true|false)$/i.test(val)) {
return val.toLowerCase() === 'true'
}
if (/^(0|1)$/.test(val)) {
return val === '1'
}
if (/^(y|n)$/i.test(val)) {
re... | }
if (Object.prototype.toString.call(val) === '[object Date]') {
return !isNaN(val.valueOf())
}
return !!val
} | return val.length > 0
}
if (typeof val === 'object') {
return Object.keys(val).length > 0 | random_line_split |
index.js | module.exports = function bool_it_up (val) {
if (typeof val === 'boolean') {
return val
}
if (typeof val === 'string') {
if (/^(true|false)$/i.test(val)) {
return val.toLowerCase() === 'true'
}
if (/^(0|1)$/.test(val)) {
return val === '1'
}
if (/^(y|n)$/i.test(val)) {
re... |
if (typeof val === 'object') {
return Object.keys(val).length > 0
}
if (Object.prototype.toString.call(val) === '[object Date]') {
return !isNaN(val.valueOf())
}
return !!val
}
| {
return val.length > 0
} | conditional_block |
unmix.py | # ===============================================================================
# Copyright 2012 Jake Ross
#
# 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/licens... |
def si(ai, ei, ps, ts):
return sum([pk * fij(ai, ei, tk) for pk, tk in zip(ps, ts)])
def tj(ages, pj, to, ps, ts):
n = len(ages)
pj = 1 / n * sum([pj * fij(ai, ei, to) / si(ai, ei, ps, ts) for ai, ei in ages])
a = [pj * ai * fij(ai, ei, to) / (ei ** 2 * si(ai, ei, ps, ts)) for ai, ei in ages]
... | """
ages = list of 2-tuples (age, 1sigma )
:param ages:
:param ps:
:param ts:
:return:
"""
niterations = 20
for _ in range(niterations):
tis_n = []
pis_n = []
for pi, ti in zip(ps, ts):
pn, tn = tj(ages, pi, ti, ps, ts)
tis_n.append(tn)
... | identifier_body |
unmix.py | # ===============================================================================
# Copyright 2012 Jake Ross
#
# 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 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
import matplotlib.pyplot as plt
# ============= enthought ... | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
unmix.py | # ===============================================================================
# Copyright 2012 Jake Ross
#
# 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/licens... | (ages, ps, ts):
"""
ages = list of 2-tuples (age, 1sigma )
:param ages:
:param ps:
:param ts:
:return:
"""
niterations = 20
for _ in range(niterations):
tis_n = []
pis_n = []
for pi, ti in zip(ps, ts):
pn, tn = tj(ages, pi, ti, ps, ts)
... | unmix | identifier_name |
unmix.py | # ===============================================================================
# Copyright 2012 Jake Ross
#
# 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/licens... |
ps = pis_n
ts = tis_n
return ps, ts
def si(ai, ei, ps, ts):
return sum([pk * fij(ai, ei, tk) for pk, tk in zip(ps, ts)])
def tj(ages, pj, to, ps, ts):
n = len(ages)
pj = 1 / n * sum([pj * fij(ai, ei, to) / si(ai, ei, ps, ts) for ai, ei in ages])
a = [pj * ai * fij(ai, ei, to) ... | pn, tn = tj(ages, pi, ti, ps, ts)
tis_n.append(tn)
pis_n.append(pn) | conditional_block |
settings.py | """
Django settings for laborzugang project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...... |
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')] | }
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/ | random_line_split |
lib.rs | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file... | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT | random_line_split | |
packed-struct-transmute.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // transmute
// error-pattern: transmute called on types with different size
#[packed]
struct Foo {
bar: u8,
baz: uint
}
struct Oof {
rab: u8,
zab: uint
}
fn main() {
let foo = Foo { bar: 1, baz: 10 };
unsafe {
let oof: Oof = cast::transmute(foo);
debug!(oof);
}
} | random_line_split | |
packed-struct-transmute.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
bar: u8,
baz: uint
}
struct Oof {
rab: u8,
zab: uint
}
fn main() {
let foo = Foo { bar: 1, baz: 10 };
unsafe {
let oof: Oof = cast::transmute(foo);
debug!(oof);
}
}
| Foo | identifier_name |
update_product.py | import urllib, json, urllib2
import pprint
url = "https://data.ilri.org/portal/api/3/action/package_list"
# url = "http://127.0.0.1:5000/api/3/action/package_list"
response = urllib.urlopen(url)
data = json.loads(response.read())
for dataset in data["result"]:
print dataset
try:
url = "https://data.ilr... | # response = urllib2.urlopen(request, data_string)
# if response.code == 200:
# print "Done for " + dataset
except:
print "Error" | request.add_header("Authorization", authorization)
# Make the HTTP request.
# Uncomment the below lines to run the update | random_line_split |
update_product.py | import urllib, json, urllib2
import pprint
url = "https://data.ilri.org/portal/api/3/action/package_list"
# url = "http://127.0.0.1:5000/api/3/action/package_list"
response = urllib.urlopen(url)
data = json.loads(response.read())
for dataset in data["result"]:
| # Replace *** with your API key, from your user account on the CKAN site
# that you're creating the dataset on.
request.add_header("Authorization", authorization)
# Make the HTTP request.
# Uncomment the below lines to run the update
# response = urllib2.urlopen(request... | print dataset
try:
url = "https://data.ilri.org/portal/api/3/action/package_show?id=" + dataset
# url = "http://127.0.0.1:5000/api/3/action/package_show?id=" + dataset
response = urllib.urlopen(url)
content = json.loads(response.read())
currentData = content["result"]
... | conditional_block |
mod.rs | /*
* Copyright (C) 2017 AltOS-Rust Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distribute... | impl SCB {
fn scb() -> Self {
unsafe {
SCB(Volatile::new(SCB_ADDR as *const _))
}
}
}
impl Deref for SCB {
type Target = RawSCB;
fn deref(&self) -> &Self::Target {
&*(self.0)
}
}
impl DerefMut for SCB {
fn deref_mut(&mut self) -> &mut Self::Target {
... |
/// System Control Block
#[derive(Copy, Clone, Debug)]
pub struct SCB(Volatile<RawSCB>);
| random_line_split |
mod.rs | /*
* Copyright (C) 2017 AltOS-Rust Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distribute... | (&mut self) {
self.icsr.set_pend_sv();
}
/// Clear the pend_sv exception.
pub fn clear_pend_sv(&mut self) {
self.icsr.clear_pend_sv();
}
}
| set_pend_sv | identifier_name |
nonlinear_bellman.py | # Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# 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 ... | (build_targets, *value_argnums):
"""Decorator to convert targets to use transformed value function."""
@functools.wraps(build_targets)
def wrapped_build_targets(tx_pair, *args, **kwargs):
tx_args = list(args)
for index in value_argnums:
tx_args[index] = tx_pair.apply_inv(tx_args[index])
targets... | transform_values | identifier_name |
nonlinear_bellman.py | # Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# 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 ... |
transformed_lambda_returns = transform_values(multistep.lambda_returns, 2)
transformed_general_off_policy_returns_from_action_values = transform_values(
multistep.general_off_policy_returns_from_action_values, 0)
transformed_n_step_returns = transform_values(
multistep.n_step_bootstrapped_returns, 2)
def t... | """Decorator to convert targets to use transformed value function."""
@functools.wraps(build_targets)
def wrapped_build_targets(tx_pair, *args, **kwargs):
tx_args = list(args)
for index in value_argnums:
tx_args[index] = tx_pair.apply_inv(tx_args[index])
targets = build_targets(*tx_args, **kwargs... | identifier_body |
nonlinear_bellman.py | # Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# 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 ... |
targets = build_targets(*tx_args, **kwargs)
return tx_pair.apply(targets)
return wrapped_build_targets
transformed_lambda_returns = transform_values(multistep.lambda_returns, 2)
transformed_general_off_policy_returns_from_action_values = transform_values(
multistep.general_off_policy_returns_from_act... | tx_args[index] = tx_pair.apply_inv(tx_args[index]) | conditional_block |
nonlinear_bellman.py | # Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# 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 ... | that may be collected by an agent from any starting state. Value functions may
also be defined as the fixed points of certain linear recursive relations known
as Bellman equations. It is sometimes useful to consider transformed values that
are the solution to non-linear generalization of traditional Bellman equations.
... | # ==============================================================================
"""Transformed value functions.
Canonical value functions map states onto the expected discounted sum of rewards | random_line_split |
compile_rules.py | 2)) if m.group(2) else 0
if iGroup > nGroup:
echo("# Selected group > group number in regex at line " + sIdAction)
#### ACTION
sAction = sAction[m.end():].strip()
cAction = m.group(1)
if cAction == "-":
## error
iMsg = sAction.find(" # ")
sMsg = sAction[iMsg+3:].... | s += '"' + lRule[2] + '", '
s += json.dumps(lRule[3], ensure_ascii=False) + ", "
s += json.dumps(lRule[4], ensure_ascii=False) + ", " | random_line_split | |
compile_rules.py | sAction.find(" # ")
sMsg = sAction[iMsg+3:].strip()
sAction = sAction[:iMsg].strip()
sURL = ""
mURL = re.search("[|] *(https?://.*)", sMsg)
if mURL:
sURL = mURL.group(1).strip()
sMsg = sMsg[:mURL.start(0)].strip()
if sMsg[0:1] == "=":
... | [ int(sCode) if sCode.isdi | identifier_name | |
compile_rules.py | .startswith('"') and sAction.endswith('"'):
sAction = sAction[1:-1]
return [sCondition, cAction, sAction, iGroup, sMsg, sURL]
elif cAction == "~":
## text preprocessor
if sAction[0:1] == "=":
if sAction[1:2] == "@":
FUNCTIONS.append(("p"+sIdAction, sAc... | DstPy, \
o | conditional_block | |
compile_rules.py | "-":
## error detected
if sAction[0:1] == "=":
FUNCTIONS.append(("s"+sIdAction, sAction[1:]))
sAction = "=s"+sIdAction
elif sAction.startswith('"') and sAction.endswith('"'):
sAction = sAction[1:-1]
return [sCondition, cAction, sAction, iGroup, sMsg, ... | est = []
for i, sLine in enumerate(lRules):
if sLine.startswith('#END'):
break
elif sLine.startswith("#"):
lLine.append("")
elif sLine.startswith("DEF:"):
m = re.match("DEF: +([a-zA-Z_][a-zA-Z_0-9]*) +(.+)$", sLine.strip())
if m:
... | identifier_body | |
csssupportsrule.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 cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... |
/// <https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface>
pub fn set_condition_text(&self, text: DOMString) {
let mut input = ParserInput::new(&text);
let mut input = Parser::new(&mut input);
let cond = SupportsCondition::parse(&mut input);
if let Ok(cond)... | {
let guard = self.cssconditionrule.shared_lock().read();
let rule = self.supportsrule.read_with(&guard);
rule.condition.to_css_string().into()
} | identifier_body |
csssupportsrule.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 cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; | use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString;
use dom::cssconditionrule::CSSConditionRule;
use dom::cssrule::SpecificCSSRule;
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use dom_struct::dom_struct;
use servo_arc::A... | use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; | random_line_split |
csssupportsrule.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 cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... |
}
}
impl SpecificCSSRule for CSSSupportsRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::SUPPORTS_RULE
}
fn get_css(&self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
self.... | {
let global = self.global();
let win = global.as_window();
let url = win.Document().url();
let quirks_mode = win.Document().quirks_mode();
let context = ParserContext::new_for_cssom(
&url,
Some(CssRuleType::Supports),
... | conditional_block |
csssupportsrule.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 cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... | (window: &Window, parent_stylesheet: &CSSStyleSheet,
supportsrule: Arc<Locked<SupportsRule>>) -> DomRoot<CSSSupportsRule> {
reflect_dom_object(Box::new(CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule)),
window,
CSSSupportsRuleBi... | new | identifier_name |
coherence.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 ... | }
ty::ty_tup(ref ts) => {
ts.iter().any(|&t| ty_is_local(tcx, t))
}
ty::ty_enum(def_id, ref substs) |
ty::ty_struct(def_id, ref substs) => {
def_id.krate == ast::LOCAL_CRATE || {
let variances = ty::item_variances(tcx, def_id);
... | ty::ty_rptr(_, ty::mt { ty: t, .. }) => {
ty_is_local(tcx, t) | random_line_split |
coherence.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 ... | (infcx: &InferCtxt,
impl1_def_id: ast::DefId,
impl2_def_id: ast::DefId)
-> bool
{
debug!("impl_can_satisfy(\
impl1_def_id={}, \
impl2_def_id={})",
impl1_def_id.repr(infcx.tcx),
impl2_def_id.repr(infcx... | impl_can_satisfy | identifier_name |
coherence.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 ... |
// Otherwise, at least one of the input types must be local to the
// crate.
trait_ref.input_types().iter().any(|&t| ty_is_local(tcx, t))
}
pub fn ty_is_local(tcx: &ty::ctxt,
ty: ty::t)
-> bool
{
debug!("ty_is_local({})", ty.repr(tcx));
match ty::get(ty).sty... | {
debug!("trait {} is local to current crate",
trait_ref.def_id.repr(tcx));
return true;
} | conditional_block |
coherence.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 ... | selcx.evaluate_impl(impl2_def_id, &obligation)
}
pub fn impl_is_local(tcx: &ty::ctxt,
impl_def_id: ast::DefId)
-> bool
{
debug!("impl_is_local({})", impl_def_id.repr(tcx));
// We only except this routine to be invoked on implementations
// of a trait, not inh... | {
debug!("impl_can_satisfy(\
impl1_def_id={}, \
impl2_def_id={})",
impl1_def_id.repr(infcx.tcx),
impl2_def_id.repr(infcx.tcx));
// `impl1` provides an implementation of `Foo<X,Y> for Z`.
let impl1_substs =
util::fresh_substs_for_impl(infcx, DUMMY_SP, impl... | identifier_body |
Prob2_Part1.py | # Make sure you name your file with className.py
from hint.hint_class_helpers.find_matches import find_matches
class Prob2_Part1:
"""
Author: Shen Ting Ang
Date: 10/11/2016
"""
def check_attempt(self, params):
self.attempt = params['attempt'] #student's attempt
self.answer = params[... |
else:
return "",""
except Exception:
return '',''
def get_problems(self):
self.problem_list = ["Combinatorics/GrinsteadSnell3.2.18/part1"]
return self.problem_list
| hint='Missing choose function in the answer. '
return hint + 'How many possible ways are there to get 2 questions correct out of 5 questions? C(5,_)', '2' | conditional_block |
Prob2_Part1.py | # Make sure you name your file with className.py
from hint.hint_class_helpers.find_matches import find_matches
class Prob2_Part1:
"""
Author: Shen Ting Ang
Date: 10/11/2016
"""
def check_attempt(self, params):
| return "",""
except Exception:
return '',''
def get_problems(self):
self.problem_list = ["Combinatorics/GrinsteadSnell3.2.18/part1"]
return self.problem_list
| self.attempt = params['attempt'] #student's attempt
self.answer = params['answer'] #solution
self.att_tree = params['att_tree'] #attempt tree
self.ans_tree = params['ans_tree'] #solution tree
matches = find_matches(params)
matching_node = [m[0] for m in matches]
try:
... | identifier_body |
Prob2_Part1.py | # Make sure you name your file with className.py
from hint.hint_class_helpers.find_matches import find_matches
class Prob2_Part1:
"""
Author: Shen Ting Ang
Date: 10/11/2016
"""
def check_attempt(self, params):
self.attempt = params['attempt'] #student's attempt
self.answer = params[... | else:
return "",""
except Exception:
return '',''
def get_problems(self):
self.problem_list = ["Combinatorics/GrinsteadSnell3.2.18/part1"]
return self.problem_list | random_line_split | |
Prob2_Part1.py | # Make sure you name your file with className.py
from hint.hint_class_helpers.find_matches import find_matches
class Prob2_Part1:
"""
Author: Shen Ting Ang
Date: 10/11/2016
"""
def check_attempt(self, params):
self.attempt = params['attempt'] #student's attempt
self.answer = params[... | (self):
self.problem_list = ["Combinatorics/GrinsteadSnell3.2.18/part1"]
return self.problem_list
| get_problems | identifier_name |
base.py | from __future__ import absolute_import, unicode_literals
import os
import os.path
from freight.constants import PROJECT_ROOT
from freight.exceptions import CommandError
class UnknownRevision(CommandError):
pass
class Vcs(object):
ssh_connect_path = os.path.join(PROJECT_ROOT, 'bin', 'ssh-connect')
def... |
else:
handler = workspace.run
rv = handler(command, *args, **kwargs)
if isinstance(rv, basestring):
return rv.strip()
return rv
def exists(self, workspace=None):
if workspace is None:
workspace = self.workspace
return os.path.exi... | handler = workspace.capture | conditional_block |
base.py | from __future__ import absolute_import, unicode_literals
import os
import os.path
from freight.constants import PROJECT_ROOT
from freight.exceptions import CommandError
class UnknownRevision(CommandError):
pass
class Vcs(object):
ssh_connect_path = os.path.join(PROJECT_ROOT, 'bin', 'ssh-connect')
def... | (self):
raise NotImplementedError
| get_default_revision | identifier_name |
base.py | from __future__ import absolute_import, unicode_literals
import os
import os.path
from freight.constants import PROJECT_ROOT
from freight.exceptions import CommandError
class UnknownRevision(CommandError):
pass
class Vcs(object):
ssh_connect_path = os.path.join(PROJECT_ROOT, 'bin', 'ssh-connect')
def... |
def update(self):
raise NotImplementedError
def checkout(self, ref):
raise NotImplementedError
def describe(self, ref):
"""
Given a `ref` return the fully qualified version.
"""
raise NotImplementedError
def get_default_revision(self):
raise N... | raise NotImplementedError | identifier_body |
base.py | from __future__ import absolute_import, unicode_literals
import os
import os.path
from freight.constants import PROJECT_ROOT
from freight.exceptions import CommandError
class UnknownRevision(CommandError):
pass
class Vcs(object):
ssh_connect_path = os.path.join(PROJECT_ROOT, 'bin', 'ssh-connect')
def... | raise NotImplementedError | random_line_split | |
test3D_old.py | from rdkit import Chem
from rdkit import rdBase
from rdkit.Chem import rdMolDescriptors as rdMD
from rdkit.Chem import AllChem
from rdkit.Chem.EState import EStateIndices
from rdkit.Chem.EState import AtomTypes
import time
print rdBase.rdkitVersion
print rdBase.boostVersion
def getEState(mol):
return EStat... |
AllChem.MMFFOptimizeMolecule(mol, maxIters = steps)
return mol
def make3D(mol, steps = 50):
mol = Chem.AddHs(mol)
success = AllChem.EmbedMolecule(mol)
if success == -1: # Failed
success = AllChem.EmbedMolecule(mol, useRandomCoords = True)
if success == -1:
raise Error, ... | mol=make3D(mol) | conditional_block |
test3D_old.py | from rdkit import Chem
from rdkit import rdBase
from rdkit.Chem import rdMolDescriptors as rdMD
from rdkit.Chem import AllChem
from rdkit.Chem.EState import EStateIndices
from rdkit.Chem.EState import AtomTypes
import time
print rdBase.rdkitVersion
print rdBase.boostVersion
def getEState(mol):
return EStat... | (mol, steps = 50):
mol = Chem.AddHs(mol)
success = AllChem.EmbedMolecule(mol)
if success == -1: # Failed
success = AllChem.EmbedMolecule(mol, useRandomCoords = True)
if success == -1:
raise Error, "Embedding failed!"
mol = localopt(mol, steps)
return mol
def get3D(m,is3d... | make3D | identifier_name |
test3D_old.py | from rdkit import Chem
from rdkit import rdBase
from rdkit.Chem import rdMolDescriptors as rdMD
from rdkit.Chem import AllChem
from rdkit.Chem.EState import EStateIndices
from rdkit.Chem.EState import AtomTypes
import time
print rdBase.rdkitVersion
print rdBase.boostVersion
def getEState(mol):
return EStat... | return mol
def get3D(m,is3d):
if not is3d:
m = Chem.AddHs(m)
AllChem.EmbedMolecule(m)
AllChem.MMFFOptimizeMolecule(m)
r= rdMD.CalcAUTOCORR3D(m)+rdMD.CalcRDF(m)+rdMD.CalcMORSE(m)+rdMD.CalcWHIM(m)+rdMD.CalcGETAWAY(m)
return r
def generateALL():
m = Chem.MolFromSmiles('Cc1cccc... | mol = localopt(mol, steps) | random_line_split |
test3D_old.py | from rdkit import Chem
from rdkit import rdBase
from rdkit.Chem import rdMolDescriptors as rdMD
from rdkit.Chem import AllChem
from rdkit.Chem.EState import EStateIndices
from rdkit.Chem.EState import AtomTypes
import time
print rdBase.rdkitVersion
print rdBase.boostVersion
def getEState(mol):
return EStat... |
def generateALL():
m = Chem.MolFromSmiles('Cc1ccccc1')
thefile = open('testAC.txt', 'w')
filename="/Users/mbp/Github/rdkit_mine/Code/GraphMol/Descriptors/test_data/PBF_egfr.sdf"
suppl = Chem.SDMolSupplier(filename,removeHs=False)
mols = [x for x in suppl]
start = time.time()
for m in mols:... | if not is3d:
m = Chem.AddHs(m)
AllChem.EmbedMolecule(m)
AllChem.MMFFOptimizeMolecule(m)
r= rdMD.CalcAUTOCORR3D(m)+rdMD.CalcRDF(m)+rdMD.CalcMORSE(m)+rdMD.CalcWHIM(m)+rdMD.CalcGETAWAY(m)
return r | identifier_body |
hews-quiz-progress-threshold.py |
import argparse
import json
import datetime
import os
import sys
from codecs import open
def run(cohort_id, threshold, period, course_range):
from django.contrib.auth.models import User
from django.db.models import Sum, Max, Min, Avg
from django.utils.html import strip_tags
from oppia.mode... |
elif period == 'training':
START_DATE = datetime.datetime(2015,4,01,0,0,0)
END_DATE = datetime.datetime(2015,7,31,23,59,59)
elif period == 'cpd':
START_DATE = datetime.datetime(2015,8,01,0,0,0)
END_DATE = datetime.datetime(2016,10,31,23,59,59)
elif period == 'op3.4-mar16':
... | START_DATE = datetime.datetime(2015,4,01,0,0,0)
END_DATE = datetime.datetime(2016,10,31,23,59,59) | conditional_block |
hews-quiz-progress-threshold.py | import argparse
import json
import datetime
import os
import sys
from codecs import open
def run(cohort_id, threshold, period, course_range):
from django.contrib.auth.models import User
from django.db.models import Sum, Max, Min, Avg
from django.utils.html import strip_tags
from oppia.model... | students = User.objects.filter(participant__cohort_id=cohort_id, participant__role=Participant.STUDENT).order_by('username')
if course_range == 'ancpnc':
courses = Course.objects.filter(coursecohort__cohort_id = cohort_id, shortname__in=['anc1-et','anc2-et','pnc-et'])
elif course_range == 'anc':
... | else:
print "Invalid period supplied"
sys.exit()
| random_line_split |
hews-quiz-progress-threshold.py |
import argparse
import json
import datetime
import os
import sys
from codecs import open
def run(cohort_id, threshold, period, course_range):
from django.contrib.auth.models import User
from django.db.models import Sum, Max, Min, Avg
from django.utils.html import strip_tags
from oppia.mode... | (title,lang):
try:
titles = json.loads(title)
if lang in titles:
return titles[lang]
else:
for l in titles:
return titles[l]
except:
pass
return title
if __name__ == "__main__":
import django
django.setup()
parser = ... | title_lang | identifier_name |
hews-quiz-progress-threshold.py |
import argparse
import json
import datetime
import os
import sys
from codecs import open
def run(cohort_id, threshold, period, course_range):
from django.contrib.auth.models import User
from django.db.models import Sum, Max, Min, Avg
from django.utils.html import strip_tags
from oppia.mode... |
if __name__ == "__main__":
import django
django.setup()
parser = argparse.ArgumentParser()
parser.add_argument("--cohort_id", help="", type=int)
parser.add_argument("--threshold", help="", type=int)
parser.add_argument("--period", help="", choices=['project','training','cpd','op3.4-mar1... | try:
titles = json.loads(title)
if lang in titles:
return titles[lang]
else:
for l in titles:
return titles[l]
except:
pass
return title | identifier_body |
login.component.ts | import { Component, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { Store } from '@ngrx/store';
import { AuthService } from '../../core/services';
import { Login } from '../../core/entities';
import... | implements OnInit, OnDestroy {
private ngUnsubscribe: Subject<void> = new Subject<void>();
constructor(
private authService: AuthService,
private cd: ChangeDetectorRef,
private router: Router,
private store: Store<AppState>
) {}
ngOnInit(): void {
console.info('LoginComponent init... | LoginComponent | identifier_name |
login.component.ts | import { Component, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { Store } from '@ngrx/store';
import { AuthService } from '../../core/services';
import { Login } from '../../core/entities';
import... | }
ngOnDestroy(): void {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
onSubmit({ value }: { value: Login }): void {
this.authService.login(value);
}
} |
this.cd.markForCheck();
}); | random_line_split |
login.component.ts | import { Component, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { Store } from '@ngrx/store';
import { AuthService } from '../../core/services';
import { Login } from '../../core/entities';
import... |
this.cd.markForCheck();
});
}
ngOnDestroy(): void {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
onSubmit({ value }: { value: Login }): void {
this.authService.login(value);
}
}
| {
this.router.navigate(['courses']);
} | conditional_block |
app.js | // angular.module is a global place for creating, registering and retrieving Angular modules
// 'collaborate' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'collaborate.services' is found in services.js
// 'collaborate.control... | url: '/employee/:employeeId',
templateUrl: 'templates/employee-detail.html',
controller: 'EmployeeDetailCtrl'
})
.state('employee-reports', {
url: '/employee/:employeeId/reports',
templateUrl: 'templates/employee-re... | })
.state('employee-detail', { | random_line_split |
lib.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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | <T: 'static>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
| arc_ptr_eq | identifier_name |
lib.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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
} | identifier_body | |
lib.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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.