file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
view_environment.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals
"""
Script to visualize the model coordination environments
"""
__author__ = "David Waroquiers"
__copyright__ = "Copyright 2012, The Materials Project"
__vers... |
myfactor = 3.0
if vis is None:
vis = visualize(cg=cg, zoom=1.0, myfactor=myfactor)
else:
vis = visualize(cg=cg, vis=vis, myfactor=myfactor)
cg_points = [myfactor*np.array(pp) for pp in cg.points]
cg_central_site = myfactor*np.array(cg.central_site)
... | try:
ialgo = int(test)
algo = cg.algorithms[ialgo]
sepplane = True
except:
print('Unable to determine the algorithm/separation_plane you want '
'to visualize for this geometry. Continues without ...... | conditional_block |
const-fields-and-indexing.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | struct K {a: isize, b: isize, c: D}
struct D { d: isize, e: isize }
const k : K = K {a: 10, b: 20, c: D {d: 30, e: 40}};
static m : isize = k.c.e;
pub fn main() {
println!("{}", p);
println!("{}", q);
println!("{}", t);
assert_eq!(p, 3);
assert_eq!(q, 3);
assert_eq!(t, 20);
} | static t : isize = s.b;
| random_line_split |
const-fields-and-indexing.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | { d: isize, e: isize }
const k : K = K {a: 10, b: 20, c: D {d: 30, e: 40}};
static m : isize = k.c.e;
pub fn main() {
println!("{}", p);
println!("{}", q);
println!("{}", t);
assert_eq!(p, 3);
assert_eq!(q, 3);
assert_eq!(t, 20);
}
| D | identifier_name |
9. if elif else.py | '''
What is going on everyone welcome to my if elif else tutorial video.
The idea of this is to add yet another layer of logic to the pre-existing if else statement.
See with our typical if else statment, the if will be checked for sure, and the
else will only run if the if fails... but then what if you want to chec... |
Instead, you can use what is called the "elif" here in python... which is short for "else if"
'''
x = 5
y = 10
z = 22
# first run the default like this, then
# change the x > y to x < y...
# then change both of these to an ==
if x > y:
print('x is greater than y')
elif x < z:
print('x is less than z')... | You could just write them all in, though this is somewhat improper. If you actually desire to check every single if statement, then this is fine.
There is nothing wrong with writing multiple ifs... if they are necessary to run, otherwise you shouldn't really do this. | random_line_split |
9. if elif else.py | '''
What is going on everyone welcome to my if elif else tutorial video.
The idea of this is to add yet another layer of logic to the pre-existing if else statement.
See with our typical if else statment, the if will be checked for sure, and the
else will only run if the if fails... but then what if you want to chec... |
else:
print('if and elif never ran...')
| print('x is less than z') | conditional_block |
forum.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) | } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdF... | { target[key] = source[key]; } | conditional_block |
forum.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } }... |
var MdForum = function MdForum(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm28.4 20q0 0.7-0.5 1.2... | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
forum.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } }... | (obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdForum = function MdForum(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_r... | _interopRequireDefault | identifier_name |
forum.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } }... | var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdForum = function MdForum(props) {
return _react2.defa... | random_line_split | |
routing.tsx | import * as myra from 'myra'
import * as router from 'myra-router'
import RouteComponent from './route-component'
/**
* State
*/
type State = {
routeCtx: router.RouteContext
}
const init = {} as State
/**
* Component
*/
export default myra.define(init, (evolve, events) => {
const onRoute = (ctx: router.... | 'test1/:param': (params: any) => <RouteComponent {...params} />
}, <nothing />)}
{state.routeCtx && state.routeCtx.match('test1/:param').isMatch ?
<p>Location '/test2/:param' matched.</p> : <nothing />}
<ul class="list-group">
<li cla... | <h1>Router examples</h1>
{state.routeCtx && state.routeCtx.matchAny({
'test1': <p>Route to '/test1'.</p>, | random_line_split |
flip.js | /* */
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');
var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixi... |
var ImageFlip = _react2.default.createClass({
displayName: 'ImageFlip',
mixins: [_reactAddonsPureRenderMixin2.default],
render: function render() {
return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 ... | {
return obj && obj.__esModule ? obj : {default: obj};
} | identifier_body |
flip.js | /* */
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');
var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixi... | });
exports.default = ImageFlip;
module.exports = exports['default']; | return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8 20h2V1h-2v22zm8-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z'}));
... | random_line_split |
flip.js | /* */
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');
var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixi... | (obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var ImageFlip = _react2.default.createClass({
displayName: 'ImageFlip',
mixins: [_reactAddonsPureRenderMixin2.default],
render: function render() {
return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement... | _interopRequireDefault | identifier_name |
HUnitDaughter2Woman_ConnectedLHS.py | from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS
"""
# Flag this instance as compiled now
self.is_... | super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[])
# Add the edges
self.add_edges([])
# Set the graph attributes
self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule']
self["MT_constraint__"] = """return True"""
self["name"] = """"... | random_line_split | |
HUnitDaughter2Woman_ConnectedLHS.py | from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS
"""
# Flag this instance as compiled now
self.is_... |
# define evaluation methods for each match association.
def eval_attr13(self, attr_value, this):
return attr_value == "daughters"
def constraint(self, PreNode, graph):
return True
| return True | identifier_body |
HUnitDaughter2Woman_ConnectedLHS.py | from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS
"""
# Flag this instance as compiled now
self.is_... | (self, attr_value, this):
return attr_value == "daughters"
def constraint(self, PreNode, graph):
return True
| eval_attr13 | identifier_name |
uniq-cc.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let v = empty_pointy();
{
let mut vb = v.borrow_mut();
vb.a = p(v);
}
} | identifier_body | |
uniq-cc.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
use std::cell::RefCell;
enum maybe_pointy {
none,
p(@RefCell<Pointy>),
}
struct Pointy {
a : maybe_pointy,
c : Box<int>,
d : proc():Send->(),
}
fn empty_pointy() -> @RefCell<Pointy> {
return @RefCell::new(Pointy {
a : none,
c : box 22,
d : proc() {},
})
}
pub fn ... | #![feature(managed_boxes)] | random_line_split |
uniq-cc.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> @RefCell<Pointy> {
return @RefCell::new(Pointy {
a : none,
c : box 22,
d : proc() {},
})
}
pub fn main() {
let v = empty_pointy();
{
let mut vb = v.borrow_mut();
vb.a = p(v);
}
}
| empty_pointy | identifier_name |
torrents.js | App.getTorrentsCollection = function (options) {
var start = +new Date(),
url = 'http://subapi.com/';
var supportedLanguages = ['english', 'french', 'dutch', 'portuguese', 'romanian', 'spanish', 'turkish', 'brazilian', 'italian'];
if (options.genre) {
url += options.genre.toLowerCase() + ... | url += 'search.json?query=' + options.keywords;
} else {
url += 'popular.json';
}
}
if (options.page && options.page.match(/\d+/)) {
var str = url.match(/\?/) ? '&' : '?';
url += str + 'page=' + options.page;
}
var MovieTorrentCollection = Backbo... | } else {
if (options.keywords) { | random_line_split |
torrents.js | App.getTorrentsCollection = function (options) {
var start = +new Date(),
url = 'http://subapi.com/';
var supportedLanguages = ['english', 'french', 'dutch', 'portuguese', 'romanian', 'spanish', 'turkish', 'brazilian', 'italian'];
if (options.genre) {
url += options.genre.toLowerCase() + ... |
}
if (options.page && options.page.match(/\d+/)) {
var str = url.match(/\?/) ? '&' : '?';
url += str + 'page=' + options.page;
}
var MovieTorrentCollection = Backbone.Collection.extend({
url: url,
model: App.Model.Movie,
parse: function (data) {
... | {
url += 'popular.json';
} | conditional_block |
BoxGeometry.d.ts | import { Geometry } from '../core/Geometry';
import { BufferGeometry } from '../core/BufferGeometry';
import { Float32BufferAttribute } from '../core/BufferAttribute';
import { Vector3 } from '../math/Vector3';
// Extras / Geometries /////////////////////////////////////////////////////////////////////
export class Bo... | widthSegments: number;
heightSegments: number;
depthSegments: number;
};
} | random_line_split | |
BoxGeometry.d.ts | import { Geometry } from '../core/Geometry';
import { BufferGeometry } from '../core/BufferGeometry';
import { Float32BufferAttribute } from '../core/BufferAttribute';
import { Vector3 } from '../math/Vector3';
// Extras / Geometries /////////////////////////////////////////////////////////////////////
export class | extends BufferGeometry {
constructor(
width?: number,
height?: number,
depth?: number,
widthSegments?: number,
heightSegments?: number,
depthSegments?: number
);
parameters: {
width: number;
height: number;
depth: number;
widthSegments: number;
heightSegments: number;... | BoxBufferGeometry | identifier_name |
show_hostlink_hostlink.py | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor
#
# 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... | (CommandShowHostlink):
required_parameters = ["hostlink"]
| CommandShowHostlinkHostlink | identifier_name |
show_hostlink_hostlink.py | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor
#
# 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... | from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611
from aquilon.worker.commands.show_hostlink import CommandShowHostlink
class CommandShowHostlinkHostlink(CommandShowHostlink):
required_parameters = ["hostlink"] | random_line_split | |
show_hostlink_hostlink.py | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor
#
# 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... | required_parameters = ["hostlink"] | identifier_body | |
ticket.js | 'use strict';
var mongoose = require('mongoose');
/**
* Schema defining the 'ticket' model.
*/
var TicketSchema = module.exports = new mongoose.Schema({
/**
* Describes on which board does this ticket belong.
*
* TODO Should we actually group the ticket's under the 'board' model as
* references, or k... | TicketSchema.options.toJSON.transform = function(doc, ret) {
ret.id = doc.id;
delete ret._id;
delete ret.__v;
}
/**
* BUG See 'config/schemas/board.js' for details.
*/
TicketSchema.options.toObject.transform = TicketSchema.options.toJSON.transform; |
if(!TicketSchema.options.toJSON) TicketSchema.options.toJSON = { }
if(!TicketSchema.options.toObject) TicketSchema.options.toObject = { }
| random_line_split |
catalog.js | function | (NumSection,GrosEntry){
var TabLink = ($('<li/>',{class: "subSection","data-toggle":"tab"})).append($('<a/>',{class:"LinktoAnchor", "href":"#Sect"+NumSection,"data-toggle":"tab",text:GrosEntry}))
// var SectionBody = $('<div/>',{id: 'One',class:'tab-pane',html:"<h2>@</h2>"})
$("#tabs").append(TabLink)
// ... | AddSection | identifier_name |
catalog.js | function AddSection(NumSection,GrosEntry){
var TabLink = ($('<li/>',{class: "subSection","data-toggle":"tab"})).append($('<a/>',{class:"LinktoAnchor", "href":"#Sect"+NumSection,"data-toggle":"tab",text:GrosEntry}))
// var SectionBody = $('<div/>',{id: 'One',class:'tab-pane',html:"<h2>@</h2>"})
$("#tabs").app... | }
$(document).ready(function () {
GetCatalog()
}) | random_line_split | |
catalog.js | function AddSection(NumSection,GrosEntry){
var TabLink = ($('<li/>',{class: "subSection","data-toggle":"tab"})).append($('<a/>',{class:"LinktoAnchor", "href":"#Sect"+NumSection,"data-toggle":"tab",text:GrosEntry}))
// var SectionBody = $('<div/>',{id: 'One',class:'tab-pane',html:"<h2>@</h2>"})
$("#tabs").app... | okie('ShopName',ShopName)
$('#PartnerShopHiden').val(ShopName)
function GetCatalog() {
var Section = "Sect"
var NumSection=0
$.getJSON("./catalog"+ShopName+".json", function(json){
Object.keys(json).forEach(function(GrosEntry) {
NumSection+=1
AddSection(NumSection,GrosEntry)
... | Name=$.cookie('ShopName')}
$.co | conditional_block |
catalog.js | function AddSection(NumSection,GrosEntry){
var TabLink = ($('<li/>',{class: "subSection","data-toggle":"tab"})).append($('<a/>',{class:"LinktoAnchor", "href":"#Sect"+NumSection,"data-toggle":"tab",text:GrosEntry}))
// var SectionBody = $('<div/>',{id: 'One',class:'tab-pane',html:"<h2>@</h2>"})
$("#tabs").app... | cument).ready(function () {
GetCatalog()
})
| var Section = "Sect"
var NumSection=0
$.getJSON("./catalog"+ShopName+".json", function(json){
Object.keys(json).forEach(function(GrosEntry) {
NumSection+=1
AddSection(NumSection,GrosEntry)
var SectionNum = Section+NumSection
$("#vitrina").append($("<div/>",{... | identifier_body |
lub.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a>(&'a self) -> Equate<'a, 'tcx> { Equate(self.fields.clone()) }
fn sub<'a>(&'a self) -> Sub<'a, 'tcx> { Sub(self.fields.clone()) }
fn lub<'a>(&'a self) -> Lub<'a, 'tcx> { Lub(self.fields.clone()) }
fn glb<'a>(&'a self) -> Glb<'a, 'tcx> { Glb(self.fields.clone()) }
fn mts(&self, a: &ty::mt<'tcx>, b: ... | equate | identifier_name |
lub.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | return Err(ty::terr_mutability)
}
let m = a.mutbl;
match m {
MutImmutable => {
let t = try!(self.tys(a.ty, b.ty));
Ok(ty::mt {ty: t, mutbl: m})
}
MutMutable => {
let t = try!(self.equate().tys(a.ty,... | random_line_split | |
CoarseFundamentalTop3Algorithm.py | ο»Ώ# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... | # we want 1/N allocation in each security in our universe
for security in self._changes.AddedSecurities:
self.SetHoldings(security.Symbol, 1 / self.__numberOfSymbols)
self._changes = None
# this event fires whenever we have changes to our universe
def OnSecuritiesChanged(s... | security.Invested:
self.Liquidate(security.Symbol)
| conditional_block |
CoarseFundamentalTop3Algorithm.py | ο»Ώ# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... | self.Log(f"OnOrderEvent({self.UtcTime}):: {fill}") | def OnOrderEvent(self, fill): | random_line_split |
CoarseFundamentalTop3Algorithm.py | ο»Ώ# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... |
def OnData(self, data):
self.Log(f"OnData({self.UtcTime}): Keys: {', '.join([key.Value for key in data.Keys])}")
# if we have no changes, do nothing
if self._changes is None: return
# liquidate removed securities
for security in self._changes.RemovedSecurities:
... | rtedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)
# return the symbol objects of the top entries from our sorted collection
return [ x.Symbol for x in sortedByDollarVolume[:self.__numberOfSymbols] ]
| identifier_body |
CoarseFundamentalTop3Algorithm.py | ο»Ώ# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... | CAlgorithm):
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.SetStartDate(2014,3,24) #Set Start Date
self.SetEndDate(2014,4,7) #Set End Date
self.SetCa... | arseFundamentalTop3Algorithm(Q | identifier_name |
import_ie_naptan_xml.py | """Import an Irish NaPTAN XML file, obtainable from
https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345
"""
import warnings
import zipfile
import xml.etree.cElementTree as ET
from django.contrib.gis.geos import Point
from django.core.management.base import Ba... |
stop_classification_element = element.find('naptan:StopClassification', self.ns)
stop_type = stop_classification_element.find('naptan:StopType', self.ns).text
if stop_type != 'class_undefined':
stop.stop_type = stop_type
bus_element = stop_classification_element.find(... | warnings.warn('Stop {} has an unexpected property: {}'.format(stop.atco_code, tag)) | conditional_block |
import_ie_naptan_xml.py | """Import an Irish NaPTAN XML file, obtainable from
https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345
"""
import warnings
import zipfile
import xml.etree.cElementTree as ET
from django.contrib.gis.geos import Point
from django.core.management.base import Ba... | locality_centre=element.find('naptan:Place/naptan:LocalityCentre', self.ns).text == 'true',
active=element.get('Status') == 'active',
)
for subelement in element.find('naptan:Descriptor', self.ns):
tag = subelement.tag[27:]
if tag == 'CommonName':
... | stop = StopPoint(
atco_code=element.find('naptan:AtcoCode', self.ns).text, | random_line_split |
import_ie_naptan_xml.py | """Import an Irish NaPTAN XML file, obtainable from
https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345
"""
import warnings
import zipfile
import xml.etree.cElementTree as ET
from django.contrib.gis.geos import Point
from django.core.management.base import Ba... |
def handle_file(self, archive, filename):
with archive.open(filename) as open_file:
iterator = ET.iterparse(open_file)
for _, element in iterator:
tag = element.tag[27:]
if tag == 'StopPoint':
self.handle_stop(element)
... | stop = StopPoint(
atco_code=element.find('naptan:AtcoCode', self.ns).text,
locality_centre=element.find('naptan:Place/naptan:LocalityCentre', self.ns).text == 'true',
active=element.get('Status') == 'active',
)
for subelement in element.find('naptan:Descriptor', self... | identifier_body |
import_ie_naptan_xml.py | """Import an Irish NaPTAN XML file, obtainable from
https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345
"""
import warnings
import zipfile
import xml.etree.cElementTree as ET
from django.contrib.gis.geos import Point
from django.core.management.base import Ba... | (parser):
parser.add_argument('filenames', nargs='+', type=str)
def handle_stop(self, element):
stop = StopPoint(
atco_code=element.find('naptan:AtcoCode', self.ns).text,
locality_centre=element.find('naptan:Place/naptan:LocalityCentre', self.ns).text == 'true',
... | add_arguments | identifier_name |
conftest.py | import socket
import subprocess
import sys
import time
import h11
import pytest
import requests
@pytest.fixture
def turq_instance():
return TurqInstance()
class TurqInstance:
"""Spins up and controls a live instance of Turq for testing."""
def __init__(self):
self.host = 'localhost'
#... | return
except OSError:
pass
raise RuntimeError('Turq failed to start')
def connect(self):
return socket.create_connection((self.host, self.mock_port), timeout=5)
def connect_editor(self):
return socket.create_connection((self.host, self.edito... | try:
self.connect().close()
self.connect_editor().close() | random_line_split |
conftest.py | import socket
import subprocess
import sys
import time
import h11
import pytest
import requests
@pytest.fixture
def turq_instance():
return TurqInstance()
class TurqInstance:
"""Spins up and controls a live instance of Turq for testing."""
def __init__(self):
self.host = 'localhost'
#... |
def request(self, method, url, **kwargs):
full_url = 'http://%s:%d%s' % (self.host, self.mock_port, url)
return requests.request(method, full_url, **kwargs)
def request_editor(self, method, url, **kwargs):
full_url = 'http://%s:%d%s' % (self.host, self.editor_port, url)
return... | yield event | conditional_block |
conftest.py | import socket
import subprocess
import sys
import time
import h11
import pytest
import requests
@pytest.fixture
def turq_instance():
return TurqInstance()
class TurqInstance:
"""Spins up and controls a live instance of Turq for testing."""
def __init__(self):
self.host = 'localhost'
#... |
def send(self, *events):
hconn = h11.Connection(our_role=h11.CLIENT)
with self.connect() as sock:
for event in events:
sock.sendall(hconn.send(event))
sock.shutdown(socket.SHUT_WR)
while hconn.their_state is not h11.CLOSED:
event ... | return socket.create_connection((self.host, self.editor_port),
timeout=5) | identifier_body |
conftest.py | import socket
import subprocess
import sys
import time
import h11
import pytest
import requests
@pytest.fixture
def turq_instance():
return TurqInstance()
class TurqInstance:
"""Spins up and controls a live instance of Turq for testing."""
def __init__(self):
self.host = 'localhost'
#... | (self, method, url, **kwargs):
full_url = 'http://%s:%d%s' % (self.host, self.mock_port, url)
return requests.request(method, full_url, **kwargs)
def request_editor(self, method, url, **kwargs):
full_url = 'http://%s:%d%s' % (self.host, self.editor_port, url)
return requests.request... | request | identifier_name |
aixc++.py | """SCons.Tool.aixc++
Tool-specific initialization for IBM xlC / Visual Age C++ compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is h... |
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| path, _cxx, version = get_xlc(env)
if path and _cxx:
xlc = os.path.join(path, _cxx)
if os.path.exists(xlc):
return xlc
return None | identifier_body |
aixc++.py | """SCons.Tool.aixc++
Tool-specific initialization for IBM xlC / Visual Age C++ compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is h... | xlc = os.path.join(path, _cxx)
if os.path.exists(xlc):
return xlc
return None
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4: | random_line_split | |
aixc++.py | """SCons.Tool.aixc++
Tool-specific initialization for IBM xlC / Visual Age C++ compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is h... |
if 'CXX' not in env:
env['CXX'] = _cxx
cplusplus.generate(env)
if version:
env['CXXVERSION'] = version
def exists(env):
path, _cxx, version = get_xlc(env)
if path and _cxx:
xlc = os.path.join(path, _cxx)
if os.path.exists(xlc):
return xlc
retu... | _cxx = os.path.join(path, _cxx) | conditional_block |
aixc++.py | """SCons.Tool.aixc++
Tool-specific initialization for IBM xlC / Visual Age C++ compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is h... | (env):
"""Add Builders and construction variables for xlC / Visual Age
suite to an Environment."""
path, _cxx, version = get_xlc(env)
if path and _cxx:
_cxx = os.path.join(path, _cxx)
if 'CXX' not in env:
env['CXX'] = _cxx
cplusplus.generate(env)
if version:
env['C... | generate | identifier_name |
count.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Enumerate;
struct | <T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} els... | A | identifier_name |
count.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Enumerate;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if ... | //
// #[inline]
// fn count(self) -> usize {
// self.iter.count()
// }
// }
#[test]
fn count_test1() {
let a: A<T> = A { begin: 10, end: 20 };
let enumerate: Enumerate<A<T>> = a.enumerate();
assert_eq!(enumerate.count(), 10);
}
#[test]
fn count_test2... | // let i = self.count + n;
// self.count = i + 1;
// (i, a)
// })
// } | random_line_split |
index.js | import { RequestHook, Selector } from 'testcafe';
import { resolve } from 'path';
const ReExecutablePromise = require(resolve('./lib/utils/re-executable-promise'));
export default class CustomHook extends RequestHook {
constructor (config) {
super(null, config);
this.pendingAjaxRequestIds = new S... |
get hasAjaxRequests () {
return ReExecutablePromise.fromFn(async () => this._hasAjaxRequests);
}
}
const hook1 = new CustomHook();
const hook2 = new CustomHook({});
const hook3 = new CustomHook({ includeHeaders: true });
fixture `GH-4516`
.page `http://localhost:3000/fixtures/regression/gh-4516/... | {
this.pendingAjaxRequestIds.delete(event.requestId);
} | identifier_body |
index.js | import { RequestHook, Selector } from 'testcafe';
import { resolve } from 'path';
const ReExecutablePromise = require(resolve('./lib/utils/re-executable-promise'));
export default class CustomHook extends RequestHook {
constructor (config) {
super(null, config);
this.pendingAjaxRequestIds = new S... |
}
onResponse (event) {
this.pendingAjaxRequestIds.delete(event.requestId);
}
get hasAjaxRequests () {
return ReExecutablePromise.fromFn(async () => this._hasAjaxRequests);
}
}
const hook1 = new CustomHook();
const hook2 = new CustomHook({});
const hook3 = new CustomHook({ include... | {
this.pendingAjaxRequestIds.add(event._requestInfo.requestId);
this._hasAjaxRequests = true;
} | conditional_block |
index.js | import { RequestHook, Selector } from 'testcafe';
import { resolve } from 'path';
const ReExecutablePromise = require(resolve('./lib/utils/re-executable-promise'));
export default class CustomHook extends RequestHook {
constructor (config) {
super(null, config);
this.pendingAjaxRequestIds = new S... | () {
return ReExecutablePromise.fromFn(async () => this._hasAjaxRequests);
}
}
const hook1 = new CustomHook();
const hook2 = new CustomHook({});
const hook3 = new CustomHook({ includeHeaders: true });
fixture `GH-4516`
.page `http://localhost:3000/fixtures/regression/gh-4516/pages/index.html`;
test.... | hasAjaxRequests | identifier_name |
index.js | import { RequestHook, Selector } from 'testcafe';
import { resolve } from 'path';
const ReExecutablePromise = require(resolve('./lib/utils/re-executable-promise'));
export default class CustomHook extends RequestHook {
constructor (config) {
super(null, config);
this.pendingAjaxRequestIds = new S... | .expect(Selector('#result').visible).ok()
.expect(hook2.hasAjaxRequests).ok()
.expect(hook2.pendingAjaxRequestIds.size).eql(0);
});
test.requestHooks(hook3)('With includeHeaders', async t => {
await t
.expect(Selector('#result').visible).ok()
.expect(hook3.hasAjaxRequests).o... |
test.requestHooks(hook2)('With empty config', async t => {
await t | random_line_split |
zenjmx.py | #! /usr/bin/env python
##############################################################################
#
# Copyright (C) Zenoss, Inc. 2008, 2009, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is installed.
#
#####... |
# If there was no result passed in, then this is the first attempt
# to start the client
else:
deferred = self._tryClientOnCurrentPort()
deferred.addCallback( self._startJavaProc )
return deferred
class ZenJMXTask(ObservableMixin):
"""
The scheduled ta... | if result[0] is True:
log.debug( 'Java jmx client started' )
self._jmxClient.restartEnabled = True
deferred = defer.succeed( True )
# If the result[0] is 10, there was a port conflict
elif result[0] == 10:
log.debug( 'Java client di... | conditional_block |
zenjmx.py | #! /usr/bin/env python
##############################################################################
#
# Copyright (C) Zenoss, Inc. 2008, 2009, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is installed.
#
#####... |
DEFAULT_JMX_JAVA_CLIENT_NAME = 'zenjmxjavaclient'
class ZenJMXJavaClientInitialization(object):
"""
Wrapper that continues to start the Java jmx client until
successful.
"""
def __init__(self,
registeredName=DEFAULT_JMX_JAVA_CLIENT_NAME):
"""
@param registeredNa... | """
Twisted function called when started
"""
if self.stopCalled:
return
self.log.info('run():starting zenjmxjava')
zenjmxjavacmd = os.path.join(ZenPacks.zenoss.ZenJMX.binDir,
'zenjmxjava')
if self.cycle:
args = ('runjmxenabled', )
... | identifier_body |
zenjmx.py | #! /usr/bin/env python
##############################################################################
#
# Copyright (C) Zenoss, Inc. 2008, 2009, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is installed.
#
#####... | (ObservableMixin):
"""
The scheduled task for all the jmx datasources on an individual device.
"""
zope.interface.implements(IScheduledTask)
def __init__(self,
deviceId,
taskName,
scheduleIntervalSeconds,
taskConfig,
... | ZenJMXTask | identifier_name |
zenjmx.py | #! /usr/bin/env python
##############################################################################
#
# Copyright (C) Zenoss, Inc. 2008, 2009, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is installed.
#
#####... | self._eventService.sendEvent(procEndEvent)
self.log.warn('processEnded():zenjmxjava process ended %s'
% reason)
if self.deferred:
msg = reason.getErrorMessage()
exitCode = reason.value.exitCode
if exitCode == ... | 'component': 'zenjmx',
'device': self._preferences.options.monitor,
} | random_line_split |
test.rs | text
/* this is a
/* nested
block */ comment.
And should stay a comment
even with "strings"
or 42 0x18 0b01011 // blah
or u32 as i16 if impl */
text
/** this is a
/*! nested
block */ doc comment */
text
/// test
/// *test*
/// **test**
/// ***test***
/// _test_
/// __test__
/// __***test***__
/// ___test___
/// # te... |
text
fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool {
announce!("There's no cake");
if !test_subject.under_control() {
text
let list: Vec<item> = some_iterator.map(|elem| elem.dosomething()).collect();
text
let boxed_lis... | {
assert!(1 != 2);
text
self.with_something(param, |arg1, arg2| {
text
}, other_param);
} | identifier_body |
test.rs | text
/* this is a
/* nested
block */ comment.
And should stay a comment
even with "strings"
or 42 0x18 0b01011 // blah
or u32 as i16 if impl */
text
/** this is a
/*! nested
block */ doc comment */
text
/// test
/// *test*
/// **test**
/// ***test***
/// _test_
/// __test__
/// __***test***__
/// ___test___
/// # te... |
// const function parameter (#52)
fn foo(bar: *const i32) {
let _ = 1234 as *const u32;
}
// Keywords and known types in wrapper structs (#56)
pub struct Foobar(pub Option<bool>);
pub struct Foobar(pub Test<W=bool>);
pub struct Foobar(pub Test<W==bool>);
pub struct Foobar(pub Test<W = bool>);
struct Test(i32);... | { } | conditional_block |
test.rs | text
/* this is a
/* nested
block */ comment.
And should stay a comment
even with "strings"
or 42 0x18 0b01011 // blah
or u32 as i16 if impl */
text
/** this is a
/*! nested
block */ doc comment */
text
/// test
/// *test*
/// **test**
/// ***test***
/// _test_
/// __test__
/// __***test***__
/// ___test___
/// # te... | (pub Test<W=bool>);
pub struct Foobar(pub Test<W==bool>);
pub struct Foobar(pub Test<W = bool>);
struct Test(i32);
struct Test(String);
struct Test(Vec<i32>);
struct Test(BTreeMap<String, i32>);
// Lifetimes in associated type definitions
trait Foo {
type B: A + 'static;
}
// where clause
impl Foo<A, B> where te... | Foobar | identifier_name |
test.rs | text
/* this is a
/* nested
block */ comment.
And should stay a comment
even with "strings"
or 42 0x18 0b01011 // blah
or u32 as i16 if impl */
text
/** this is a
/*! nested
block */ doc comment */
text
/// test
/// *test*
/// **test**
/// ***test***
/// _test_
/// __test__
/// __***test***__
/// ___test___
/// # te... | text r##"This is ##"# also valid."## text
text r#"This is #"## not valid."# text //"
text b"This is a bytestring" text
text br"And a raw byte string" text
text rb"Invalid raw byte string" text
text br##"This is ##"# also valid."## text
text r##"Raw strings can
span multiple lines"## text
text "double-quote string" te... |
text r"This is a raw string" text
text r"This raw string ends in \" text
text r#"This is also valid"# text | random_line_split |
sync.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Alexander Fomin <xander.fomin@ya.ru>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
/* Last synced with: sync (GNU coreutils) 8.13 */
extern crate libc;
... | #[allow(deprecated)]
let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized();
if winapi::um::fileapi::FindNextVolumeW(
next_volume_handle,
name.as_mut_ptr(),
name.len() as minwindef::DWORD,
) == 0
... |
unsafe fn find_all_volumes() -> Vec<String> {
let (first_volume, next_volume_handle) = find_first_volume();
let mut volumes = vec![first_volume];
loop { | random_line_split |
sync.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Alexander Fomin <xander.fomin@ya.ru>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
/* Last synced with: sync (GNU coreutils) 8.13 */
extern crate libc;
... |
pub unsafe fn do_syncfs(files: Vec<String>) -> isize {
for path in files {
flush_volume(
Path::new(&path)
.components()
.next()
.unwrap()
.as_os_str()
.to_str()
... | {
let volumes = find_all_volumes();
for vol in &volumes {
flush_volume(vol);
}
0
} | identifier_body |
sync.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Alexander Fomin <xander.fomin@ya.ru>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
/* Last synced with: sync (GNU coreutils) 8.13 */
extern crate libc;
... | (name: &str) {
let name_wide = name.to_wide_null();
if winapi::um::fileapi::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED {
let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash
match OpenOptions::new().write(true).open(sliced_name) {
... | flush_volume | identifier_name |
assignment2.py | '''
author Lama Hamadeh
'''
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import assignment2_helper as helper
# Look pretty...
matplotlib.style.use('ggplot')
# Do * NOT * alter this line, until instructed!
scaleFeatures = True #Features scaling (if it's false no scaling appears and that aff... | pca.fit(df)
decomposition.PCA(copy=True, n_components=2, whiten=False)
T= pca.transform(df)
# Plot the transformed data as a scatter plot. Recall that transforming
# the data will result in a NumPy NDArray. You can either use MatPlotLib
# to graph it directly, or you can convert it to DataFrame and have pandas
# do i... | from sklearn import decomposition
pca = decomposition.PCA(n_components=2) | random_line_split |
assignment2.py | '''
author Lama Hamadeh
'''
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import assignment2_helper as helper
# Look pretty...
matplotlib.style.use('ggplot')
# Do * NOT * alter this line, until instructed!
scaleFeatures = True #Features scaling (if it's false no scaling appears and that aff... |
# TODO: Run PCA on your dataset and reduce it to 2 components
# Ensure your PCA instance is saved in a variable called 'pca',
# and that the results of your transformation are saved in 'T'.
#
# .. your code here ..
from sklearn import decomposition
pca = decomposition.PCA(n_components=2)
pca.fit(df)
decomposition.P... | df = helper.scaleFeatures(df) | conditional_block |
docSearch.js | class DocSearchInterface extends ReactSingleAjax {
constructor(props) {
super(props);
let urlP = getURLParams();
this.state = {
termKind: urlP.termKind || "lemmas",
query: urlP.query || "",
operation: urlP.operation || "OR"
};
this.init();
... | () {
let resp = this.props.response;
if(resp == null) {
return <span />;
}
let results = _(resp.results).map(function(obj) {
return <li key={obj.id}><DocumentLink id={obj.id} name={obj.name} /></li>
}).value();
return <div>
<label>Que... | render | identifier_name |
docSearch.js | class DocSearchInterface extends ReactSingleAjax {
constructor(props) {
super(props);
let urlP = getURLParams();
this.state = {
termKind: urlP.termKind || "lemmas",
query: urlP.query || "",
operation: urlP.operation || "OR"
};
this.init();
... |
if(this.response()) {
results = <pre key="json">{JSON.stringify(this.response())}</pre>;
}
return <div>
<div>Document Search</div>
<textarea value={this.state.query} onChange={(x) => this.setState({query: x.target.value}) } />
<SelectWidget opts=... | {
results = this.errorMessage();
} | conditional_block |
docSearch.js | class DocSearchInterface extends ReactSingleAjax {
constructor(props) {
super(props);
let urlP = getURLParams();
this.state = {
termKind: urlP.termKind || "lemmas",
query: urlP.query || "",
operation: urlP.operation || "OR"
};
this.init();
... | let request = {};
request.termKind = this.state.termKind;
request.query = this.state.query;
request.operation = this.state.operation;
pushURLParams(request);
this.send("/api/MatchDocuments", request);
}
render() {
let results = "";
if(this.error()... | onFind(evt) {
// one request at a time...
if(this.waiting()) return;
| random_line_split |
custom_association_rules.py | import sys
sys.path.append("..")
|
LE = "leite"
PA = "pao"
SU = "suco"
OV = "ovos"
CA = "cafe"
BI = "biscoito"
AR = "arroz"
FE = "feijao"
CE = "cerveja"
MA = "manteiga"
data = [[CA, PA, MA], [LE, CE, PA, MA], [CA, PA, MA], [LE, CA, PA, MA],
[CE], [MA], [PA], [FE], [AR, FE], [AR]]
compare(data, 0.0000000001, 5.0, 0) | from data_mining.association_rule.base import rules, lift, support
from data_mining.association_rule.apriori import apriori
from data_mining.association_rule.liftmin import apriorilift
from pat_data_association_rules import compare | random_line_split |
utils.py | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import base64
from datetime import datetime, timedelta
import functools
import json
import os
import time
import yaml
import jinja2
import jmespath
from dateutil import parser
from dateutil.tz import gettz, tzutc
try:
from botocore.exc... |
elif resource_type == 'iam-role':
return " %s %s " % (
resource['RoleName'],
resource['CreateDate'])
elif resource_type == 'iam-policy':
return " %s " % (
resource['PolicyName'])
elif resource_type == 'iam-profile':
return " %s " % (
r... | return " %s " % (
resource['UserName']) | conditional_block |
utils.py | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import base64
from datetime import datetime, timedelta
import functools
import json
import os
import time
import yaml
import jinja2
import jmespath
from dateutil import parser
from dateutil.tz import gettz, tzutc
try:
from botocore.exc... | (sqs_message):
default_subject = 'Custodian notification - %s' % (sqs_message['policy']['name'])
subject = sqs_message['action'].get('subject', default_subject)
jinja_template = jinja2.Template(subject)
subject = jinja_template.render(
account=sqs_message.get('account', ''),
account_id=s... | get_message_subject | identifier_name |
utils.py | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import base64
from datetime import datetime, timedelta
import functools
import json
import os
import time
import yaml
import jinja2
import jmespath
from dateutil import parser
from dateutil.tz import gettz, tzutc
try:
from botocore.exc... | )
elif resource_type == "app-elb":
return "arn: %s zones: %s scheme: %s" % (
resource['LoadBalancerArn'],
len(resource['AvailabilityZones']),
resource['Scheme'])
elif resource_type == "nat-gateway":
return "id: %s state: %s vpc: %s" % (
... | resource['RouteTableId'],
resource['VpcId'] | random_line_split |
utils.py | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import base64
from datetime import datetime, timedelta
import functools
import json
import os
import time
import yaml
import jinja2
import jmespath
from dateutil import parser
from dateutil.tz import gettz, tzutc
try:
from botocore.exc... |
def get_provider(mailer_config):
if mailer_config.get('queue_url', '').startswith('asq://'):
return Providers.Azure
return Providers.AWS
def kms_decrypt(config, logger, session, encrypted_field):
if config.get(encrypted_field):
try:
kms = session.client('kms')
r... | if resource_type.startswith('aws.'):
resource_type = strip_prefix(resource_type, 'aws.')
if resource_type == 'ec2':
tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())}
return "%s %s %s %s %s %s" % (
resource['InstanceId'],
resource.get('VpcId', 'NO VPC!... | identifier_body |
QuickOpen.ts | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as i18n from '../../../../core/i18n/i18n.js';
import type * as UI from '../../legacy.js';
import type {Provider} from './FilteredListWidget.js';... | (_provider: Provider): void {
}
}
let showActionDelegateInstance: ShowActionDelegate;
export class ShowActionDelegate implements UI.ActionRegistration.ActionDelegate {
static instance(opts: {
forceNew: boolean|null,
} = {forceNew: null}): ShowActionDelegate {
const {forceNew} = opts;
if (!showAction... | providerLoadedForTest | identifier_name |
QuickOpen.ts | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as i18n from '../../../../core/i18n/i18n.js';
import type * as UI from '../../legacy.js';
import type {Provider} from './FilteredListWidget.js';... | this.filteredListWidget.setCommandPrefix(titlePrefixFunction ? titlePrefixFunction() : '');
const titleSuggestionFunction = (query === prefix) && this.providers.get(prefix)?.titleSuggestion;
this.filteredListWidget.setCommandSuggestion(titleSuggestionFunction ? titleSuggestionFunction() : '');
if (this... | if (!this.filteredListWidget) {
return;
}
this.filteredListWidget.setPrefix(prefix);
const titlePrefixFunction = this.providers.get(prefix)?.titlePrefix; | random_line_split |
QuickOpen.ts | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as i18n from '../../../../core/i18n/i18n.js';
import type * as UI from '../../legacy.js';
import type {Provider} from './FilteredListWidget.js';... |
return showActionDelegateInstance;
}
handleAction(context: UI.Context.Context, actionId: string): boolean {
switch (actionId) {
case 'quickOpen.show':
QuickOpenImpl.show('');
return true;
}
return false;
}
}
| {
showActionDelegateInstance = new ShowActionDelegate();
} | conditional_block |
HelloWorld.py | """Example macro."""
revision = "$Rev$"
url = "$URL$"
#
# The following shows the code for macro, old-style.
#
# The `execute` function serves no purpose other than to illustrate
# the example, it will not be used anymore.
#
# ---- (ignore in your own macro) ----
# --
from trac.util import escape
def execute(hdf, tx... | """
return 'Hello World, args = ' + unicode(args)
# Note that there's no need to HTML escape the returned data,
# as the template engine (Genshi) will do it for us.
# --
# ---- (reuse for your own macro) ---- | `args` is the text enclosed in parenthesis at the call of the macro.
Note that if there are ''no'' parenthesis (like in, e.g.
[[HelloWorld]]), then `args` is `None`. | random_line_split |
HelloWorld.py | """Example macro."""
revision = "$Rev$"
url = "$URL$"
#
# The following shows the code for macro, old-style.
#
# The `execute` function serves no purpose other than to illustrate
# the example, it will not be used anymore.
#
# ---- (ignore in your own macro) ----
# --
from trac.util import escape
def execute(hdf, tx... |
# Note that there's no need to HTML escape the returned data,
# as the template engine (Genshi) will do it for us.
# --
# ---- (reuse for your own macro) ----
| """Return some output that will be displayed in the Wiki content.
`name` is the actual name of the macro (no surprise, here it'll be
`'HelloWorld'`),
`args` is the text enclosed in parenthesis at the call of the macro.
Note that if there are ''no'' parenthesis (like in, e.g.
... | identifier_body |
HelloWorld.py | """Example macro."""
revision = "$Rev$"
url = "$URL$"
#
# The following shows the code for macro, old-style.
#
# The `execute` function serves no purpose other than to illustrate
# the example, it will not be used anymore.
#
# ---- (ignore in your own macro) ----
# --
from trac.util import escape
def execute(hdf, tx... |
# args will be `None` if the macro is called without parenthesis.
args = txt or 'No arguments'
# then, as `txt` comes from the user, it's important to guard against
# the possibility to inject malicious HTML/Javascript, by using `escape()`:
return 'Hello World, args = ' + escape(args)
# -... | hdf['wiki.macro.greeting'] = 'Hello World' | conditional_block |
HelloWorld.py | """Example macro."""
revision = "$Rev$"
url = "$URL$"
#
# The following shows the code for macro, old-style.
#
# The `execute` function serves no purpose other than to illustrate
# the example, it will not be used anymore.
#
# ---- (ignore in your own macro) ----
# --
from trac.util import escape
def | (hdf, txt, env):
# Currently hdf is set only when the macro is called
# From a wiki page
if hdf:
hdf['wiki.macro.greeting'] = 'Hello World'
# args will be `None` if the macro is called without parenthesis.
args = txt or 'No arguments'
# then, as `txt` comes from the user, it's ... | execute | identifier_name |
errorHandler.js | /**
* error handling middleware loosely based off of the connect/errorHandler code. This handler chooses
* to render errors using Jade / Express instead of the manual templating used by the connect middleware
* sample. This may or may not be a good idea :-)
* @param options {object} array of options
**/
exports =... | exports.NotFound = function(msg) {
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
} | };
};
| random_line_split |
errorHandler.js | /**
* error handling middleware loosely based off of the connect/errorHandler code. This handler chooses
* to render errors using Jade / Express instead of the manual templating used by the connect middleware
* sample. This may or may not be a good idea :-)
* @param options {object} array of options
**/
exports =... |
};
};
exports.NotFound = function(msg) {
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
| {
res.render('errors/500', { locals: {
title: 'The Server Encountered an Error'
, error: showStack ? err : undefined
}, status: 500
});
} | conditional_block |
base_scraper.py | import logging
import sys
import time
import traceback
from weakref import WeakValueDictionary
import bs4
from selenium import webdriver
from app.services import slack
from app.utils import db
class BaseScraper(object):
""" Abstract class for implementing a datasource. """
_instances = WeakValueDictionary... |
def _is_valid_offer(self, offer, r_offer):
"""
Let the datasource object checks if the offer to be parsed is a valid one.
If the validity check allows to prefill some fields, the offer model object can be used.
:return True if the offer is valid, False otherwise
"""
... | """
Returns a valid offer object for the offer to parse.
:return A BaseOffer object subclass instance
"""
NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) | identifier_body |
base_scraper.py | import logging
import sys
import time
import traceback
from weakref import WeakValueDictionary
import bs4
from selenium import webdriver
from app.services import slack
from app.utils import db
class BaseScraper(object):
""" Abstract class for implementing a datasource. """
_instances = WeakValueDictionary... |
return offers
def _get_offer_object(self, r_offer):
"""
Returns a valid offer object for the offer to parse.
:return A BaseOffer object subclass instance
"""
NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__))
def _is_v... | self.logger.warning("Invalid offer detected. Skipping...") | conditional_block |
base_scraper.py | import logging
import sys
import time
import traceback
from weakref import WeakValueDictionary
import bs4
from selenium import webdriver
from app.services import slack
from app.utils import db
class BaseScraper(object):
""" Abstract class for implementing a datasource. """
_instances = WeakValueDictionary... | (self, offer, r_offer):
"""
Let the datasource object checks if the offer to be parsed is a valid one.
If the validity check allows to prefill some fields, the offer model object can be used.
:return True if the offer is valid, False otherwise
"""
NotImplementedError("... | _is_valid_offer | identifier_name |
base_scraper.py | import logging
import sys
import time
import traceback
from weakref import WeakValueDictionary
import bs4
from selenium import webdriver
from app.services import slack
from app.utils import db
class BaseScraper(object):
""" Abstract class for implementing a datasource. """
_instances = WeakValueDictionary... | If the validity check allows to prefill some fields, the offer model object can be used.
:return True if the offer is valid, False otherwise
"""
NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__))
def _prepare_offer_filling(self, offer, r_of... | Let the datasource object checks if the offer to be parsed is a valid one. | random_line_split |
LayerFactory.js | import DynamicLayer from 'esri/layers/ArcGISDynamicMapServiceLayer';
import TiledLayer from 'esri/layers/ArcGISTiledMapServiceLayer';
import ImageLayer from 'esri/layers/ArcGISImageServiceLayer';
import ImageParameters from 'esri/layers/ImageParameters';
import WebTiledLayer from 'esri/layers/WebTiledLayer';
import Gra... |
break;
case 'graphic':
options.id = layer.id;
options.visible = layer.visible || false;
esriLayer = new GraphicsLayer(options);
break;
default:
throw new Error(errors.incorrectLayerConfig(layer.type));
}
return esriLayer;
};
| {
const pointSymbol = Symbols.getGrantsPointSymbol();
const renderer = new SimpleRenderer(pointSymbol);
esriLayer.renderer = renderer;
} | conditional_block |
LayerFactory.js | import DynamicLayer from 'esri/layers/ArcGISDynamicMapServiceLayer';
import TiledLayer from 'esri/layers/ArcGISTiledMapServiceLayer';
import ImageLayer from 'esri/layers/ArcGISImageServiceLayer';
import ImageParameters from 'esri/layers/ImageParameters';
import WebTiledLayer from 'esri/layers/WebTiledLayer';
import Gra... | options.outFields = layer.outFields || ['*'];
esriLayer = new FeatureLayer(layer.url, options);
if (layer.id === KEYS.smallGrants) {
const pointSymbol = Symbols.getGrantsPointSymbol();
const renderer = new SimpleRenderer(pointSymbol);
esriLayer.renderer = renderer;
}
... | break;
case 'feature':
options.id = layer.id;
options.visible = layer.visible || false; | random_line_split |
types.rs | extern crate serde_json;
extern crate rmp_serde;
use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use super::zmq;
use errors::common::CommonError;
use services::ledger::merkletree::merkletree::MerkleTree;
use utils::json::{JsonDecodable, JsonEncodable};
#[derive(Serialize, Deserialize,... | #[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Response {
pub req_id: u64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct PoolLedgerTxns {
pub txn: Response,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SimpleRequest {
... | #[derive(Serialize, Deserialize, Debug)]
pub struct Reply {
pub result: Response,
}
| random_line_split |
types.rs | extern crate serde_json;
extern crate rmp_serde;
use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use super::zmq;
use errors::common::CommonError;
use services::ledger::merkletree::merkletree::MerkleTree;
use utils::json::{JsonDecodable, JsonEncodable};
#[derive(Serialize, Deserialize,... | (str: &str) -> Result<Message, serde_json::Error> {
match str {
"po" => Ok(Message::Pong),
"pi" => Ok(Message::Ping),
_ => Message::from_json(str),
}
}
}
impl JsonEncodable for Message {}
impl<'a> JsonDecodable<'a> for Message {}
#[derive(Serialize, Deserialize... | from_raw_str | identifier_name |
test_parsers.py | import json
from io import BytesIO
import pytest
from rest_framework.exceptions import ParseError
from rest_framework_json_api.parsers import JSONParser
from rest_framework_json_api.utils import format_value
from tests.views import BasicModelViewSet
class TestJSONParser:
@pytest.fixture
def parser(self):
... |
@pytest.fixture
def parse(self, parser):
def parse_wrapper(data, parser_context):
stream = BytesIO(json.dumps(data).encode("utf-8"))
return parser.parse(stream, None, parser_context)
return parse_wrapper
@pytest.fixture
def parser_context(self, rf):
re... | return JSONParser() | identifier_body |
test_parsers.py | import json
from io import BytesIO
import pytest
from rest_framework.exceptions import ParseError
from rest_framework_json_api.parsers import JSONParser
from rest_framework_json_api.utils import format_value
from tests.views import BasicModelViewSet
class TestJSONParser:
@pytest.fixture
def parser(self):
... | "test_attribute": "test-value",
"test_relationship": {"id": "123", "type": "TestRelationship"},
}
def test_parse_extracts_meta(self, parse, parser_context):
data = {
"data": {
"type": "BasicModel",
},
"meta": {"random_key":... | assert result == {
"id": "123",
"type": "BasicModel", | random_line_split |
test_parsers.py | import json
from io import BytesIO
import pytest
from rest_framework.exceptions import ParseError
from rest_framework_json_api.parsers import JSONParser
from rest_framework_json_api.utils import format_value
from tests.views import BasicModelViewSet
class TestJSONParser:
@pytest.fixture
def parser(self):
... | (self, parser):
def parse_wrapper(data, parser_context):
stream = BytesIO(json.dumps(data).encode("utf-8"))
return parser.parse(stream, None, parser_context)
return parse_wrapper
@pytest.fixture
def parser_context(self, rf):
return {"request": rf.post("/"), "kwa... | parse | identifier_name |
addon.js | 'use strict';
var fs = require('fs');
var path = require('path');
var deprecate = require('../utilities/deprecate');
var assign = require('lodash-node/modern/objects/assign');
function Addon(project) |
Addon.__proto__ = require('./core-object');
Addon.prototype.constructor = Addon;
function unwatchedTree(dir) {
return {
read: function() { return dir; },
cleanup: function() { }
};
}
Addon.prototype.treePaths = {
app: 'app',
styles: 'app/styles',
templates: 'app/templates',
vendor: ... | {
this.project = project;
} | identifier_body |
addon.js | 'use strict';
var fs = require('fs');
var path = require('path');
var deprecate = require('../utilities/deprecate');
var assign = require('lodash-node/modern/objects/assign');
function Addon(project) {
this.project = project;
}
Addon.__proto__ = require('./core-object');
Addon.prototype.constructor ... | (dir) {
return {
read: function() { return dir; },
cleanup: function() { }
};
}
Addon.prototype.treePaths = {
app: 'app',
styles: 'app/styles',
templates: 'app/templates',
vendor: 'vendor'
};
Addon.prototype.treeFor = function treeFor(name) {
var treePath = path.join(this._root, t... | unwatchedTree | identifier_name |
addon.js | 'use strict';
var fs = require('fs');
var path = require('path');
var deprecate = require('../utilities/deprecate');
var assign = require('lodash-node/modern/objects/assign');
function Addon(project) {
this.project = project;
}
Addon.__proto__ = require('./core-object');
Addon.prototype.constructor ... | };
module.exports = Addon; | _root: moduleDir
});
}
return Constructor; | random_line_split |
addon.js | 'use strict';
var fs = require('fs');
var path = require('path');
var deprecate = require('../utilities/deprecate');
var assign = require('lodash-node/modern/objects/assign');
function Addon(project) {
this.project = project;
}
Addon.__proto__ = require('./core-object');
Addon.prototype.constructor ... |
return path.resolve(addon.path, addonMain);
};
Addon.lookup = function(addon) {
var Constructor, addonModule, modulePath, moduleDir;
modulePath = Addon.resolvePath(addon);
moduleDir = path.dirname(modulePath);
if (fs.existsSync(modulePath)) {
addonModule = require(modulePath);
if (typeof addonM... | {
addonMain += '.js';
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.