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 |
|---|---|---|---|---|
_version.py | "):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
if line.strip().startswith("git_date ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["date"] = mo.group(1)
f.... | rendered = "0.post.dev%d" % pieces["distance"] | conditional_block | |
_version.py |
# This file is released into the public domain. Generated by
# versioneer-0.18 (https://github.com/warner/python-versioneer)
"""Git implementation of _version.py."""
import errno
import os
import re
import subprocess
import sys
def get_keywords():
"""Get the keywords needed to look up the version information."... | # feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains the computed version number. | random_line_split | |
_version.py | mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
if line.strip().startswith("git_date ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["date"] = mo.group(1)
f.close()
except ... | """TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%d" % pieces["distance"]
else:
# exception #1
rendered = "0.post... | identifier_body | |
_version.py | stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
print("stdout was %s" % stdout)
return None, p.returncode
return stdout, p.returncode
def versions_from_parentdir(parentdir_prefix, root, verbose):
"""Try to determine the... | (versionfile_abs):
"""Extract version information from the given file."""
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is not used from
# _version.py.
... | git_get_keywords | identifier_name |
is_power_of_2.rs | use malachite_base::num::arithmetic::traits::IsPowerOf2;
use Rational;
impl IsPowerOf2 for Rational {
/// Determines whether a `Rational` is an integer power of 2.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(1)$
///
/// where $T$ is time, $M$ is additional memory... |
}
| {
self.sign
&& (self.denominator == 1u32 && self.numerator.is_power_of_2()
|| self.numerator == 1u32 && self.denominator.is_power_of_2())
} | identifier_body |
is_power_of_2.rs | use malachite_base::num::arithmetic::traits::IsPowerOf2;
use Rational;
impl IsPowerOf2 for Rational {
/// Determines whether a `Rational` is an integer power of 2.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(1)$
///
/// where $T$ is time, $M$ is additional memory... | && (self.denominator == 1u32 && self.numerator.is_power_of_2()
|| self.numerator == 1u32 && self.denominator.is_power_of_2())
}
} | random_line_split | |
is_power_of_2.rs | use malachite_base::num::arithmetic::traits::IsPowerOf2;
use Rational;
impl IsPowerOf2 for Rational {
/// Determines whether a `Rational` is an integer power of 2.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(1)$
///
/// where $T$ is time, $M$ is additional memory... | (&self) -> bool {
self.sign
&& (self.denominator == 1u32 && self.numerator.is_power_of_2()
|| self.numerator == 1u32 && self.denominator.is_power_of_2())
}
}
| is_power_of_2 | identifier_name |
plot_pattern_diagram_markers.py | import matplotlib.pyplot as plt
import matplotlib.colors as clr
import matplotlib
import warnings
from skill_metrics import add_legend
def plot_pattern_diagram_markers(X,Y,option):
| OUTPUTS:
None
Created on Nov 30, 2016
Revised on Jan 6, 2019
Author: Peter A. Rochford
Symplectic, LLC
www.thesymplectic.com
prochford@thesymplectic.com
'''
# Set face color transparency
alpha = option['alpha']
# Set font and marker size
fontSi... | '''
Plots color markers on a pattern diagram.
Plots color markers on a target diagram according their (X,Y)
locations. The symbols and colors are chosen automatically with a
limit of 70 symbol & color combinations.
The color bar is titled using the content of option['titleColorBar']
... | identifier_body |
plot_pattern_diagram_markers.py | import matplotlib.pyplot as plt
import matplotlib.colors as clr
import matplotlib
import warnings
from skill_metrics import add_legend
def plot_pattern_diagram_markers(X,Y,option):
'''
Plots color markers on a pattern diagram.
Plots color markers on a target diagram according their (X,Y)
location... | (text):
print(text)
| _disp | identifier_name |
plot_pattern_diagram_markers.py | import matplotlib.pyplot as plt
import matplotlib.colors as clr
import matplotlib
import warnings
from skill_metrics import add_legend
def plot_pattern_diagram_markers(X,Y,option):
'''
Plots color markers on a pattern diagram.
Plots color markers on a target diagram according their (X,Y)
location... |
else:
# Define markers and colors using predefined list
marker = []
markercolor = [] #Bug Fix: missing array initialization
for color in colorm:
for symbol in kind:
marker.append(symbol + color)
rgba = clr.t... | marker = []
markercolor = []
for color in colorm:
for symbol in kind:
marker.append(symbol + option['markercolor'])
rgba = clr.to_rgb(option['markercolor']) + (alpha,)
markercolor.append(rgba) | conditional_block |
plot_pattern_diagram_markers.py | import matplotlib.pyplot as plt
import matplotlib.colors as clr
import matplotlib
import warnings
from skill_metrics import add_legend
def plot_pattern_diagram_markers(X,Y,option):
'''
Plots color markers on a pattern diagram.
Plots color markers on a target diagram according their (X,Y)
location... | for i, xval in enumerate(X):
if abs(X[i]) <= limit and abs(Y[i]) <= limit:
h = plt.plot(X[i],Y[i],marker[i], markersize = markerSize,
markerfacecolor = markercolor[i],
markeredgecolor = marker[i][1],
markeredgewidth = 2)... |
# Plot markers at data points
limit = option['axismax']
hp = ()
markerlabel = [] | random_line_split |
TelegrafConfig.tsx | // Libraries
import React, {PureComponent} from 'react'
import {connect, ConnectedProps} from 'react-redux'
import {withRouter, RouteComponentProps, matchPath} from 'react-router-dom'
// Components
import {ErrorHandling} from 'src/shared/decorators/errors'
import Editor from 'src/shared/components/TomlMonacoEditor'
/... | const mstp = ({resources}: AppState) => ({
telegrafConfig: resources.telegrafs.currentConfig.item,
status: resources.telegrafs.currentConfig.status,
})
const mdtp = {
getTelegrafConfigToml,
}
const connector = connect(mstp, mdtp)
export default connector(withRouter(TelegrafConfig)) | random_line_split | |
TelegrafConfig.tsx | // Libraries
import React, {PureComponent} from 'react'
import {connect, ConnectedProps} from 'react-redux'
import {withRouter, RouteComponentProps, matchPath} from 'react-router-dom'
// Components
import {ErrorHandling} from 'src/shared/decorators/errors'
import Editor from 'src/shared/components/TomlMonacoEditor'
/... | (): JSX.Element {
const {telegrafConfig} = this.props
return <Editor script={telegrafConfig} readOnly />
}
}
const mstp = ({resources}: AppState) => ({
telegrafConfig: resources.telegrafs.currentConfig.item,
status: resources.telegrafs.currentConfig.status,
})
const mdtp = {
getTelegrafConfigToml,
}
... | overlayBody | identifier_name |
mimetype.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::MimeTypeBinding::MimeTypeMethods;
use dom::bindings::js::Root;
use dom::bind... |
// https://html.spec.whatwg.org/multipage/#dom-mimetype-description
fn Description(&self) -> DOMString {
unreachable!()
}
// https://html.spec.whatwg.org/multipage/#dom-mimetype-suffixes
fn Suffixes(&self) -> DOMString {
unreachable!()
}
// https://html.spec.whatwg.org/mu... | {
unreachable!()
} | identifier_body |
mimetype.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::MimeTypeBinding::MimeTypeMethods;
use dom::bindings::js::Root;
use dom::bind... | fn Suffixes(&self) -> DOMString {
unreachable!()
}
// https://html.spec.whatwg.org/multipage/#dom-mimetype-enabledplugin
fn EnabledPlugin(&self) -> Root<Plugin> {
unreachable!()
}
} | }
// https://html.spec.whatwg.org/multipage/#dom-mimetype-suffixes | random_line_split |
mimetype.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::MimeTypeBinding::MimeTypeMethods;
use dom::bindings::js::Root;
use dom::bind... | {
reflector_: Reflector,
}
impl MimeTypeMethods for MimeType {
// https://html.spec.whatwg.org/multipage/#dom-mimetype-type
fn Type(&self) -> DOMString {
unreachable!()
}
// https://html.spec.whatwg.org/multipage/#dom-mimetype-description
fn Description(&self) -> DOMString {
u... | MimeType | identifier_name |
dstr-let-obj-ptrn-prop-ary-trailing-comma.js | // This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-prop-ary-trailing-comma.case
// - src/dstr-binding/default/for-of-let.template
/*---
description: Trailing comma is allowed following BindingPropertyList (for-of statement)
esid: sec-for-in-and-for-of-statements-runtime-s... | assert.sameValue(iterCount, 1, 'Iteration occurred as expected'); | random_line_split | |
__init__.py | # Natural Language Toolkit: Semantic Interpretation
#
# Copyright (C) 2001-2017 NLTK Project
# Author: Ewan Klein <ewan@inf.ed.ac.uk>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
NLTK Semantic Interpretation Package
This package contains classes for representing semantic structure in
formu... | from nltk.sem.evaluate import (Valuation, Assignment, Model, Undefined,
is_rel, set2rel, arity, read_valuation)
from nltk.sem.logic import (boolean_ops, binding_ops, equality_preds,
read_logic, Variable, Expression,
ApplicationExpressi... |
from nltk.sem.util import (parse_sents, interpret_sents, evaluate_sents,
root_semrep) | random_line_split |
_outlook.py | import datetime
import sqlalchemy.orm.exc
from nylas.logging import get_logger
log = get_logger()
from inbox.auth.oauth import OAuthAuthHandler
from inbox.basicauth import OAuthError
from inbox.models import Namespace
from inbox.config import config
from inbox.models.backends.outlook import OutlookAccount
from inbox... | auth_code = raw_input('Enter authorization code: ').strip()
try:
auth_response = self._get_authenticated_user(auth_code)
return auth_response
except OAuthError:
print '\nInvalid authorization code, try again...\n'
auth_code = None | conditional_block | |
_outlook.py | import datetime
import sqlalchemy.orm.exc
from nylas.logging import get_logger
log = get_logger()
from inbox.auth.oauth import OAuthAuthHandler
from inbox.basicauth import OAuthError
from inbox.models import Namespace
from inbox.config import config
from inbox.models.backends.outlook import OutlookAccount
from inbox... | account.locale = response.get('locale')
# Unlike Gmail, Outlook doesn't return the client_id and secret here
account.client_id = OAUTH_CLIENT_ID
account.client_secret = OAUTH_CLIENT_SECRET
# Ensure account has sync enabled.
account.enable_sync()
return account
... | email_address = response.get('emails')['account']
try:
account = db_session.query(OutlookAccount).filter_by(
email_address=email_address).one()
except sqlalchemy.orm.exc.NoResultFound:
namespace = Namespace()
account = OutlookAccount(namespace=namespac... | identifier_body |
_outlook.py | import datetime
import sqlalchemy.orm.exc
from nylas.logging import get_logger
log = get_logger()
from inbox.auth.oauth import OAuthAuthHandler
from inbox.basicauth import OAuthError
from inbox.models import Namespace
from inbox.config import config
from inbox.models.backends.outlook import OutlookAccount
from inbox... | (self, access_token):
return self._get_user_info(access_token)
def interactive_auth(self, email_address=None):
url_args = {'redirect_uri': self.OAUTH_REDIRECT_URI,
'client_id': self.OAUTH_CLIENT_ID,
'response_type': 'code',
'scope': self.O... | validate_token | identifier_name |
_outlook.py | import datetime
import sqlalchemy.orm.exc
from nylas.logging import get_logger
log = get_logger()
from inbox.auth.oauth import OAuthAuthHandler
from inbox.basicauth import OAuthError
from inbox.models import Namespace
from inbox.config import config
from inbox.models.backends.outlook import OutlookAccount
from inbox... | except OAuthError:
print '\nInvalid authorization code, try again...\n'
auth_code = None | while True:
auth_code = raw_input('Enter authorization code: ').strip()
try:
auth_response = self._get_authenticated_user(auth_code)
return auth_response | random_line_split |
defined_structures.ts | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | (name: string) {
super(name);
}
static fromJSON(json: NamedJson) {
return new DefinedPipeline(json.name);
}
}
export class DefinedEnvironment extends NamedConcept {
readonly children: NamedTree[] = [];
constructor(name: string) {
super(name);
}
static fromJSON(json: NamedJson) {
return... | constructor | identifier_name |
defined_structures.ts | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | export class DefinedEnvironment extends NamedConcept {
readonly children: NamedTree[] = [];
constructor(name: string) {
super(name);
}
static fromJSON(json: NamedJson) {
return new DefinedEnvironment(json.name);
}
}
interface NamedJson {
name: string;
}
interface GroupJson extends NamedJson {
... | random_line_split | |
index.js | require('module-alias/register');
var generators = require('yeoman-generator');
var _ = require('lodash');
var mkdirp = require('mkdirp');
var ifNotDatabase = require('/utils/if-not-database');
var writeScript = require('/utils/write-script');
var sharedInput = require('/utils/shared-input');
var wipeableGenerator = ... |
}
});
| {
writeScript(this, {
databaseName: this.props.dbname,
entityCollection: 'sequences',
useSchema: this.props.useschema,
schemaName: this.props.schemaname,
entityName: this.props.sequencename,
scriptType: 'sql',
templateName: 'create_sequence'
});
} | conditional_block |
index.js | require('module-alias/register');
var generators = require('yeoman-generator');
var _ = require('lodash');
var mkdirp = require('mkdirp');
var ifNotDatabase = require('/utils/if-not-database');
var writeScript = require('/utils/write-script');
var sharedInput = require('/utils/shared-input');
var wipeableGenerator = ... | name: 'min',
message: 'Enter the sequence\'s minimum value or leave empty for no minimum:',
default: function(response) {
return response.increment;
}
},
{
type: 'input',
name: 'max',
message: 'Enter the sequence\'s maximu... | {
type: 'input', | random_line_split |
chrome-reader-mode.js | import React from 'react'; |
let ActionChromeReaderMode = (props) => (
<SvgIcon {...props}>
<path d="M13 12h7v1.5h-7zm0-2.5h7V11h-7zm0 5h7V16h-7zM21 4H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 15h-9V6h9v13z"/>
</SvgIcon>
);
ActionChromeReaderMode = pure(ActionChromeReaderMode);
ActionChromeReaderMode.display... | import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon'; | random_line_split |
util.rs | // This file is part of rss.
//
// Copyright © 2015-2017 The rust-syndication Developers
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the MIT License and/or Apache 2.0 License.
use std::collections::HashMap;
use std::io::BufRead;
use std::str;
use quick_xml::even... | }
let items = match extension.children.get_mut(name) {
Some(items) => items,
None => unreachable!(),
};
items.push(ext);
}
Event::CData(element) => {
extension.value = Some(r... |
let mut extension = Extension::default();
let mut buf = Vec::new();
for attr in atts.with_checks(false) {
if let Ok(attr) = attr {
let key = str::from_utf8(attr.key)?;
let value = attr.unescape_and_decode_value(reader)?;
extension.attrs.insert(key.to_string(), v... | identifier_body |
util.rs | // This file is part of rss.
//
// Copyright © 2015-2017 The rust-syndication Developers
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the MIT License and/or Apache 2.0 License.
use std::collections::HashMap;
use std::io::BufRead;
use std::str;
use quick_xml::even... |
map: &mut HashMap<String, Vec<Extension>>,
key: &str,
) -> Option<String> {
map.remove(key)
.map(|mut v| v.remove(0))
.and_then(|ext| ext.value)
}
| emove_extension_value( | identifier_name |
util.rs | // This file is part of rss.
//
// Copyright © 2015-2017 The rust-syndication Developers
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the MIT License and/or Apache 2.0 License.
use std::collections::HashMap;
use std::io::BufRead;
use std::str;
use quick_xml::even... | }
loop {
match reader.read_event(&mut buf)? {
Event::Start(element) => {
let ext = parse_extension_element(reader, element.attributes())?;
let name = str::from_utf8(element.local_name())?;
if !extension.children.contains_key(name) {
... |
let key = str::from_utf8(attr.key)?;
let value = attr.unescape_and_decode_value(reader)?;
extension.attrs.insert(key.to_string(), value);
}
| conditional_block |
util.rs | // This file is part of rss.
//
// Copyright © 2015-2017 The rust-syndication Developers
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the MIT License and/or Apache 2.0 License.
use std::collections::HashMap;
use std::io::BufRead;
use std::str;
use quick_xml::even... | fn parse_extension_element<R: BufRead>(
reader: &mut Reader<R>,
mut atts: Attributes,
) -> Result<Extension, Error> {
let mut extension = Extension::default();
let mut buf = Vec::new();
for attr in atts.with_checks(false) {
if let Ok(attr) = attr {
let key = str::from_utf8(attr.... | }
| random_line_split |
CreateGroupStore.js | import _ from 'lodash';
import { EventEmitter } from 'events';
import { ActionTypes } from '../constants/ActorAppConstants';
import Dispatcher from '../dispatcher/ActorAppDispatcher';
const CHANGE_EVENT = 'change';
let modalOpen = false;
const CreateGroupStore = _.assign(EventEmitter.prototype, {
emitChange: ()... | break;
case ActionTypes.CREATE_GROUP_MODAL_CLOSE:
modalOpen = false;
CreateGroupStore.emitChange();
}
});
export default CreateGroupStore; | random_line_split | |
all_67.js | var searchData=
[
['getanno',['getAnno',['../classFileMultimediale.html#a424b22f61f08f9c8397f254d6b756e42',1,'FileMultimediale.getAnno()'],['../classPannelloModifica.html#a944ba9f7a82cc5481e58dd27e55c5a48',1,'PannelloModifica.getAnno()']]],
['getautore',['getAutore',['../classFileMultimediale.html#a6eca23197261b42d... | ['gruppo',['gruppo',['../classPannelloAggiungi.html#aa91fdf6e09519f389209c27aaefd2a67',1,'PannelloAggiungi']]]
]; | ['getvalueat',['getValueAt',['../classLibreriaTableModel.html#ad73eef7944a2e4160ac091df5b97d1ad',1,'LibreriaTableModel']]], | random_line_split |
mainduplicate.js | (function () {
"use strict";
var PLUGIN_ID = require("./package.json").name,
MENU_ID = "Blendin generator",
MENU_LABEL = "$$$/JavaScripts/Generator/Blendin generator/Menu=Blendin generator";
var _generator = null,
_currentDocumentId = null,
_config = null;
var fs =... | console.log("got Pixmap: "+pixmap.width+" x "+pixmap.height);
console.log(stringify(pixmap));
savePixmap(pixmap);
},
function(err){
console.error("err pixmap:",err);
}
).done();
}
function updateMenuSta... | _generator.getPixmap(options.documentId,options.layerId,{}).then(
function(pixmap){ | random_line_split |
mainduplicate.js | (function () {
"use strict";
var PLUGIN_ID = require("./package.json").name,
MENU_ID = "Blendin generator",
MENU_LABEL = "$$$/JavaScripts/Generator/Blendin generator/Menu=Blendin generator";
var _generator = null,
_currentDocumentId = null,
_config = null;
var fs =... |
function setCurrentDocumentId(id) {
if (_currentDocumentId === id) {
return;
}
console.log("Current document ID:", id);
_currentDocumentId = id;
}
exports.init = init;
// Unit test function exports
exports._setConfig = function (config) { _config = con... | {
_generator.evaluateJSXString(str).then(
function(result){
console.log(result);
},
function(err){
console.log(err);
});
} | identifier_body |
mainduplicate.js | (function () {
"use strict";
var PLUGIN_ID = require("./package.json").name,
MENU_ID = "Blendin generator",
MENU_LABEL = "$$$/JavaScripts/Generator/Blendin generator/Menu=Blendin generator";
var _generator = null,
_currentDocumentId = null,
_config = null;
var fs =... | (generator, config) {
_generator = generator;
_config = config;
console.log("initializing generator getting started tutorial with config %j", _config);
_generator.addMenuItem(MENU_ID, MENU_LABEL, true, false).then(
function () {
console.log("Menu cre... | init | identifier_name |
app.component.spec.ts | import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppHeaderComponent } from './app-header/app-header.component';
import { TopicListComponent } from './topic-list/topic-list.component';
import { VennDiagramComponent } from './venn-diagram/venn-diagram.compo... | const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Venn Diagram Generator');
}));
}); |
it('should render title in h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges(); | random_line_split |
bittorrent-console.py | #!/usr/bin/env python
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/li... | (self, errormsg):
"""Called by DL if an error occurs"""
print strftime('[%H:%M:%S] ') + errormsg
self.send("failed", "outbox")
def display(self, statistics):
"""Called by DL to display status updates"""
# Forward on to next component
self.send(statistics, "outbox")
... | error | identifier_name |
bittorrent-console.py | #!/usr/bin/env python
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/li... | elif self.config['save_in']:
saveas = os.path.join(self.config['save_in'], torrent_name)
else:
saveas = torrent_name
self.d.set_torrent_values(metainfo.name, os.path.abspath(saveas),
metainfo.total_bytes, len(metainfo.h... | """This class accepts feedback from the multitorrent downloader class
which it can then pass back to the inboxes of TorrentClient"""
def __init__(self, metainfo, config, interface):
self.doneflag = threading.Event()
self.metainfo = metainfo
self.config = Preferences().initWithDict(config... | identifier_body |
bittorrent-console.py | #!/usr/bin/env python
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/li... | defaults.append(('twisted', 0,
_("Use Twisted network libraries for network connections. 1 means use twisted, 0 means do not use twisted, -1 means autodetect, and prefer twisted")))
metainfo = None
config, args = configfile.parse_configuration_and_args(defaults, uiname)
tr... | defaults = get_defaults(uiname) | random_line_split |
bittorrent-console.py | #!/usr/bin/env python
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/li... |
class TorrentClient(threadedcomponent):
"""Using threadedcomponent so we don't have to worry about blocking IO or making
mainline yield periodically"""
Inboxes = { "inbox" : "Commands, e.g. shutdown",
"control" : "NOT USED",
}
Outboxes = { "outbox" : "State chang... | yield 1
sleep(0.05) | conditional_block |
enum-doc-bitfield.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals | /// Document field with three slashes
pub const VAR_A: B = B(0);
}
impl B {
/// Document field with preceeding star
pub const VAR_B: B = B(1);
}
impl B {
/// Document field with preceeding exclamation
pub const VAR_C: B = B(2);
}
impl B {
///< Document field with following star
pub const... | )]
impl B { | random_line_split |
enum-doc-bitfield.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
impl B {
/// Document field with three slashes
pub const VAR_A: B = B(0);
}
impl B {
/// Document field with preceeding star
pub const VAR_B: B = B(1);
}
i... | (self, other: Self) -> Self {
B(self.0 & other.0)
}
}
impl ::std::ops::BitAndAssign for B {
#[inline]
fn bitand_assign(&mut self, rhs: B) {
self.0 &= rhs.0;
}
}
#[repr(transparent)]
/// Document enum
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct B(pub u32);
| bitand | identifier_name |
enum-doc-bitfield.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
impl B {
/// Document field with three slashes
pub const VAR_A: B = B(0);
}
impl B {
/// Document field with preceeding star
pub const VAR_B: B = B(1);
}
i... |
}
impl ::std::ops::BitOrAssign for B {
#[inline]
fn bitor_assign(&mut self, rhs: B) {
self.0 |= rhs.0;
}
}
impl ::std::ops::BitAnd<B> for B {
type Output = Self;
#[inline]
fn bitand(self, other: Self) -> Self {
B(self.0 & other.0)
}
}
impl ::std::ops::BitAndAssign for B {
... | {
B(self.0 | other.0)
} | identifier_body |
rest.py | import shutil
import json
from rest_framework import routers, serializers, viewsets, parsers, filters
from rest_framework.views import APIView
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from django.core.exceptions import ValidationError
from django.core.files.uploa... | def create(self, request):
# If a seeds file or a textseeds exists, then use those. Otherwise, look
# for a string in request.data["seeds"]
seeds_list = request.FILES.get("seeds", False)
textseeds = request.data.get("textseeds", False)
if seeds_list:
request.data[... | random_line_split | |
rest.py | import shutil
import json
from rest_framework import routers, serializers, viewsets, parsers, filters
from rest_framework.views import APIView
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from django.core.exceptions import ValidationError
from django.core.files.uploa... |
return trails
def get(self, request, format=None):
# TODO: catch all exception. At the very least, deal with 404 not found and
# connection refused exceptions.
# Temporarily remove exceptions for debugging.
try:
trail_ids = [x["key"] for x in self.es.search(inde... | url_search = self.es.search(index=self.index, q="trail_id:%d" % x,
fields="url", size=1000)["hits"]["hits"]
new_trail = {"trail_id": x, "urls": [], "domain_name":url_search[0]["_type"]}
for y in url_search:
new_trail["urls"].append(y["fields"]["url"][0])
... | conditional_block |
rest.py | import shutil
import json
from rest_framework import routers, serializers, viewsets, parsers, filters
from rest_framework.views import APIView
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from django.core.exceptions import ValidationError
from django.core.files.uploa... | (viewsets.ModelViewSet):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
filter_fields = ('id', 'slug', 'name',)
class CrawlViewSet(viewsets.ModelViewSet):
queryset = Crawl.objects.all()
serializer_class = CrawlSerializer
filter_fields = ('id', 'slug', 'name', 'descriptio... | ProjectViewSet | identifier_name |
rest.py | import shutil
import json
from rest_framework import routers, serializers, viewsets, parsers, filters
from rest_framework.views import APIView
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from django.core.exceptions import ValidationError
from django.core.files.uploa... |
"""
Viewset Classes.
Filtering is provided by django-filter.
Backend settings are in common_settings.py under REST_FRAMEWORK. Setting is:
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
This backend is supplied to every viewset by default. Alter query fields by adding
or removing it... | model = SeedsList | identifier_body |
main.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/. */
#![feature(env, os, start)]
#[cfg(target_os="android")]
extern crate libc;
extern crate servo;
extern crate time... | {
browser: Browser,
}
#[cfg(target_os="android")]
android_start!(main);
#[cfg(target_os="android")]
fn get_args() -> Vec<String> {
vec![
"servo".to_owned(),
"http://en.wikipedia.org/wiki/Rust".to_owned()
]
}
#[cfg(not(target_os="android"))]
fn get_args() -> Vec<String> {
use std::env... | BrowserWrapper | identifier_name |
main.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/. */
#![feature(env, os, start)]
#[cfg(target_os="android")]
extern crate libc;
extern crate servo;
extern crate time... | }
#[cfg(not(target_os="android"))]
fn setup_logging() {
}
fn main() {
if opts::from_cmdline_args(&*get_args()) {
setup_logging();
resource_task::global_init();
let window = if opts::get().headless {
None
} else {
Some(app::create_window())
};
... | random_line_split | |
main.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/. */
#![feature(env, os, start)]
#[cfg(target_os="android")]
extern crate libc;
extern crate servo;
extern crate time... |
}
| {
let is_resize = match event {
WindowEvent::Resize(..) => true,
_ => false,
};
if !self.browser.handle_event(event) {
return false
}
if is_resize {
self.browser.repaint_synchronously()
}
true
} | identifier_body |
regex_route.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn with_path<F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("regex_route", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[t... |
#[test]
fn ignores_query() {
with_path("/hello/world?foo=bar", |res| {
let s = read_body_to_string(res);
assert_eq!(s, "Hello world");
})
}
#[test]
// FIXME?
// Rym: I would expect this to 404, but its behavior is somewhat
// expected when compared to the regex provided. To get my expected
//... | {
with_path("/hello/world", |res| {
let s = read_body_to_string(res);
assert_eq!(s, "Hello world");
})
} | identifier_body |
regex_route.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn with_path<F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("regex_route", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[t... | // This seems like it might be a bit of a footgun.
fn fallthrough_too_many_params() {
with_path("/hello/beautiful/world", |res| {
let s = read_body_to_string(res);
assert_eq!(s, "Hello beautiful");
})
}
#[test]
fn fallthrough_with_no_match() {
with_path("/", |res| {
assert_eq!(res.s... | // Rym: I would expect this to 404, but its behavior is somewhat
// expected when compared to the regex provided. To get my expected
// behaviour, you'd need to append `$` to the regex in the example. | random_line_split |
regex_route.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn | <F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("regex_route", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[test]
fn with_param() {
with_path("/hello/world", |res| {
let s = read_body_... | with_path | identifier_name |
docker.js | ;
};
return promise;
};
function DockerTerminal(parent, channel) {
var self = this;
var term = new Terminal({
cols: 80,
rows: 24,
screenKeys: true,
useStyle: true,
inlineStyle: false,
});
var enable_in... | (seq, find) {
var f, fl = find.length;
var s, sl = (seq.length - fl) + 1;
for (s = 0; s < sl; s++) {
for (f = 0; f < fl; f++) {
if (seq[s + f] !== find[f])
break;
}
if (f == fl)
return s;
}
r... | sequence_find | identifier_name |
docker.js | * The returned element needs to have its .connect() method called to start the
* connection process.
*
* The returned value is an HTMLElement with the following extra methods/properties:
*
* cons.connected: true/false if connected or not
* cons.connect(): connect or reconnect
* c... | }
if (inword && depth == 1) | random_line_split | |
docker.js | ;
if (tty === undefined || tty === null)
tty = true;
exec = {
method: "POST",
path: "/v1.15/containers/" + encodeURIComponent(container_id) + "/exec",
headers: { "Content-Type": "application/json" },
body: JSON.stri... | {
return c == ' ';
} | identifier_body | |
docker.js | ;
};
return promise;
};
function DockerTerminal(parent, channel) {
var self = this;
var term = new Terminal({
cols: 80,
rows: 24,
screenKeys: true,
useStyle: true,
inlineStyle: false,
});
var enable_in... |
delete options.tty;
/* A promise being prepared */
var prep = null;
function failure(message) {
self.connected = false;
if (tty)
view = new DockerTerminal(self, message);
else
view = new DockerLogs(self, message);
... | {
docker_debug("preparing to attach");
options = command || { };
tty = options.tty;
} | conditional_block |
routing_graph.rs | pseudo_cells: pseudo_cells,
tmg_idx: tmg_idx,
});
}
}
pub struct IcWire {
pub name: IdString,
}
impl IcWire {
pub fn new(name: IdString) -> IcWire {
IcWire {
name: name,
}
}
}
pub struct IcPseudoCell {
pub bel: IdString,
pub pins: Vec<IdString>... | GraphBuilder {
g: IcGraph::new(ids, width, height),
ids: ids,
chip: chip,
glb: globals.clone(),
db: db,
tiletypes_by_xy: tiletypes_by_xy,
// the original tiletypes from the database
orig_tts: orig_tts,
}
... | let orig_tts = TileTypes::new(db, ids, &chip.family, &[&chip.device]);
let globals = db.device_globals(&chip.family, &chip.device);
| random_line_split |
routing_graph.rs | pseudo_cells: pseudo_cells,
tmg_idx: tmg_idx,
});
}
}
pub struct IcWire {
pub name: IdString,
}
impl IcWire {
pub fn new(name: IdString) -> IcWire {
IcWire {
name: name,
}
}
}
pub struct IcPseudoCell {
pub bel: IdString,
pub pins: Vec<IdString>... | (from_wire: &str, to_wire: &str) -> String {
let (src_rel, src_name) = Neighbour::parse_wire(from_wire);
let (dst_rel, dst_name) = Neighbour::parse_wire(to_wire);
let (src_x, src_y) = match src_rel {
Some(Neighbour::RelXY { rel_x: x, rel_y: y }) => (x, y),
_ => (0, 0)
... | get_pip_tmg_class | identifier_name |
routing_graph.rs | pseudo_cells: pseudo_cells,
tmg_idx: tmg_idx,
});
}
}
pub struct IcWire {
pub name: IdString,
}
impl IcWire {
pub fn new(name: IdString) -> IcWire {
IcWire {
name: name,
}
}
}
pub struct IcPseudoCell {
pub bel: IdString,
pub pins: Vec<IdString>... |
pub fn tile_at(&mut self, x: u32, y: u32) -> &mut IcTileInst {
let idx = self.tile_idx(x, y);
&mut self.tiles[idx]
}
pub fn type_at(&mut self, x: u32, y: u32) -> &mut IcTileType {
let idx = self.tile_at(x, y).type_idx;
self.tile_types.value_mut(idx)
}
pub fn map_node... | {
assert!(x < self.width);
assert!(y < self.height);
((y * self.width) + x) as usize
} | identifier_body |
checkboxTheming.component.tsx | import React from 'react';
import { StyleSheet } from 'react-native';
import { CheckBox, Layout } from '@ui-kitten/components';
export const CheckboxThemingShowcase = () => {
| const [indeterminate, setIndeterminate] = React.useState(true);
const onIndeterminateChange = (isChecked, isIndeterminate) => {
setIndeterminateChecked(isChecked);
setIndeterminate(isIndeterminate);
};
return (
<Layout style={styles.container} level='1'>
<CheckBox
style={styles.chec... | const [activeChecked, setActiveChecked] = React.useState(true);
const [indeterminateChecked, setIndeterminateChecked] = React.useState(false); | random_line_split |
dompoint.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::c... | (&self, value: f64) {
self.point.SetY(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn Z(&self) -> f64 {
self.point.Z()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn SetZ(&self, value: f64) {
self.poin... | SetY | identifier_name |
dompoint.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::c... |
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn SetW(&self, value: f64) {
self.point.SetW(value);
}
}
| {
self.point.W()
} | identifier_body |
dompoint.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::c... | fn SetZ(&self, value: f64) {
self.point.SetZ(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn W(&self) -> f64 {
self.point.W()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn SetW(&self, value: f64) {
... | self.point.Z()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z | random_line_split |
session.rs | /// Request middleware action
#[derive(Debug)]
pub enum MiddlewareAction {
/// Proceed with standard JSON-RPC behaviour.
Proceed,
/// Terminate the request and return a response.
Respond {
/// Response to return
response: ws::Response,
/// Should origin be validated before returning the response?
validate_o... | if !header_is_allowed(&self.allowed_origins, origin) {
warn!(
"Blocked connection to WebSockets server from untrusted origin: {:?}",
origin.and_then(|s| std::str::from_utf8(s).ok()),
);
Some(forbidden("URL Blocked", "Connection Origin has been rejected."))
} else {
None
}
}
fn verify_host(&... | req.header("origin").map(|x| &x[..])
}
fn verify_origin(&self, origin: Option<&[u8]>) -> Option<ws::Response> { | random_line_split |
session.rs | /// Request middleware action
#[derive(Debug)]
pub enum MiddlewareAction {
/// Proceed with standard JSON-RPC behaviour.
Proceed,
/// Terminate the request and return a response.
Respond {
/// Response to return
response: ws::Response,
/// Should origin be validated before returning the response?
validate_o... | (&self, req: &ws::Request) -> Option<ws::Response> {
let host = req.header("host").map(|x| &x[..]);
if !header_is_allowed(&self.allowed_hosts, host) {
warn!(
"Blocked connection to WebSockets server with untrusted host: {:?}",
host.and_then(|s| std::str::from_utf8(s).ok()),
);
Some(forbidden("URL B... | verify_host | identifier_name |
session.rs | }
impl Future for LivenessPoll {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = Pin::into_inner(self);
// if the future resolves ok then we've been signalled to return.
// it should never be cancelled, but if it was the session definitely
// isn't li... | {
for v in values {
if v.matches(val) {
return true;
}
}
false
} | conditional_block | |
session.rs | (cx) {
Poll::Ready(_) => Poll::Ready(()),
Poll::Pending => Poll::Pending,
}
}
}
impl Drop for LivenessPoll {
fn drop(&mut self) {
// remove the entry from the slab if it hasn't been destroyed yet.
self.task_slab.lock().remove(self.slab_handle);
}
}
pub struct Session<M: core::Metadata, S: core::Middlew... | {
let mut forbidden = ws::Response::new(403, "Forbidden", format!("{}\n{}\n", title, message).into_bytes());
{
let headers = forbidden.headers_mut();
headers.push(("Connection".to_owned(), b"close".to_vec()));
}
forbidden
} | identifier_body | |
mod.rs | use std::fs;
use std::path;
use std::io::Read;
use serialize::json;
use valico::json_schema;
fn visit_specs<F>(dir: &path::Path, cb: F) where F: Fn(&path::Path, json::Json) {
let contents = fs::read_dir(dir).ok().unwrap();
for entry in contents {
let path = entry.unwrap().path();
match fs::File... | let spec_set = spec_set.as_array().unwrap();
let exceptions: Vec<(String, String)> = vec![
("maxLength.json".to_string(), "two supplementary Unicode code points is long enough".to_string()),
("minLength.json".to_string(), "one supplementary Unicode code point is not long enough"... | let json_v4_schema: json::Json = content.parse().unwrap();
visit_specs(&path::Path::new("tests/schema/JSON-Schema-Test-Suite/tests/draft4"), |path, spec_set: json::Json| { | random_line_split |
mod.rs | use std::fs;
use std::path;
use std::io::Read;
use serialize::json;
use valico::json_schema;
fn visit_specs<F>(dir: &path::Path, cb: F) where F: Fn(&path::Path, json::Json) {
let contents = fs::read_dir(dir).ok().unwrap();
for entry in contents {
let path = entry.unwrap().path();
match fs::File... | () {
let mut content = String::new();
fs::File::open(&path::Path::new("tests/schema/schema.json")).ok().unwrap()
.read_to_string(&mut content).ok().unwrap();
let json_v4_schema: json::Json = content.parse().unwrap();
visit_specs(&path::Path::new("tests/schema/JSON-Schema-Test-Suite/tests/draf... | test_suite | identifier_name |
mod.rs | use std::fs;
use std::path;
use std::io::Read;
use serialize::json;
use valico::json_schema;
fn visit_specs<F>(dir: &path::Path, cb: F) where F: Fn(&path::Path, json::Json) |
#[test]
fn test_suite() {
let mut content = String::new();
fs::File::open(&path::Path::new("tests/schema/schema.json")).ok().unwrap()
.read_to_string(&mut content).ok().unwrap();
let json_v4_schema: json::Json = content.parse().unwrap();
visit_specs(&path::Path::new("tests/schema/JSON-Schem... | {
let contents = fs::read_dir(dir).ok().unwrap();
for entry in contents {
let path = entry.unwrap().path();
match fs::File::open(&path) {
Err(_) => continue,
Ok(mut file) => {
let metadata = file.metadata().unwrap();
if metadata.is_file() {... | identifier_body |
cliente.rs | use std::cmp::{Ordering, min};
use std::fs::File;
use std::io::{BufWriter, Write, Read};
use chrono::{DateTime, NaiveDateTime, Utc};
use serializable::Serializable;
use serializable::SerializeError;
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
#[derive(Debug, Clone)]
pub struct Cliente {
pub codigo:... | (&self, file: &mut File) -> Result<(), SerializeError> {
let mut file = BufWriter::new(file);
if self.codigo == 3763629520 {
println!("entra aqui arrombado");
}
file.write_u32::<BigEndian>(self.codigo)?;
let bytes = self.nome.as_bytes();
let bounda... | serialize | identifier_name |
cliente.rs | use std::cmp::{Ordering, min};
use std::fs::File;
use std::io::{BufWriter, Write, Read};
use chrono::{DateTime, NaiveDateTime, Utc};
use serializable::Serializable;
use serializable::SerializeError;
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
#[derive(Debug, Clone)]
pub struct Cliente {
pub codigo:... |
}
| {
let codigo = file.read_u32::<BigEndian>()?;
let mut nome = [0; 50];
file.read_exact(&mut nome)?;
let nul_pos = nome.iter().position(|&c| c == b'\0').unwrap_or(nome.len());
let nome = String::from_utf8(nome[..nul_pos].to_vec())?;
let data_nascimento = file.read_i64::<... | identifier_body |
cliente.rs | use std::cmp::{Ordering, min};
use std::fs::File;
use std::io::{BufWriter, Write, Read};
use chrono::{DateTime, NaiveDateTime, Utc};
use serializable::Serializable;
use serializable::SerializeError;
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
#[derive(Debug, Clone)]
pub struct Cliente {
pub codigo:... |
file.write_u32::<BigEndian>(self.codigo)?;
let bytes = self.nome.as_bytes();
let boundary = min(50, bytes.len());
let diff = 50 - boundary;
file.write_all(&bytes[..boundary])?;
for _ in 0..diff {
file.write_u8(0)?;
}
file.write_i6... | {
println!("entra aqui arrombado");
} | conditional_block |
cliente.rs | use std::cmp::{Ordering, min};
use std::fs::File;
use std::io::{BufWriter, Write, Read};
use chrono::{DateTime, NaiveDateTime, Utc};
use serializable::Serializable;
use serializable::SerializeError;
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
#[derive(Debug, Clone)]
pub struct Cliente {
pub codigo:... | let boundary = min(50, bytes.len());
let diff = 50 - boundary;
file.write_all(&bytes[..boundary])?;
for _ in 0..diff {
file.write_u8(0)?;
}
file.write_i64::<BigEndian>(self.data_nascimento.timestamp())?;
Ok(())
}
fn deserialize(file: &mut F... | random_line_split | |
traverser.ts | import {Parser} from './parser';
import INode = Parser.INode;
import AST = Parser.AST;
import CallExpression = Parser.CallExpression;
export namespace Traverser {
export let traverse = (ast: AST, visitor: Object) => {
let traverserArray = (array: INode[], parent: INode): void => {
array.forEach(child => t... | } else {
throw new TypeError(`Unknown type ${nodeType}`);
}
};
traverserNode(ast, null);
}
} | } else if (nodeType === 'CallExpression') {
traverserArray((node as CallExpression).params, node);
} else if (nodeType === 'NumberLiteral') {
// we've reached the brach botoom | random_line_split |
traverser.ts | import {Parser} from './parser';
import INode = Parser.INode;
import AST = Parser.AST;
import CallExpression = Parser.CallExpression;
export namespace Traverser {
export let traverse = (ast: AST, visitor: Object) => {
let traverserArray = (array: INode[], parent: INode): void => {
array.forEach(child => t... | else if (nodeType === 'CallExpression') {
traverserArray((node as CallExpression).params, node);
} else if (nodeType === 'NumberLiteral') {
// we've reached the brach botoom
} else {
throw new TypeError(`Unknown type ${nodeType}`);
}
};
traverserNode(ast, null);
}
}
| {
traverserArray((node as AST).body, node);
} | conditional_block |
lost_back_patients.py | # coding: utf-8
# Copyright 2017 Solthis.
#
# This file is part of Fugen 2.0.
#
# Fugen 2.0 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 ver... |
@classmethod
def get_key(cls):
return "ARV_LOST_BACK"
@classmethod
def get_display_label(cls):
return "Perdus de vue de retour dans le TARV"
def filter_patients_dataframe(self, limit_date, start_date=None,
include_null_dates=False):
lost_... | return False | identifier_body |
lost_back_patients.py | # coding: utf-8
# Copyright 2017 Solthis.
#
# This file is part of Fugen 2.0.
#
# Fugen 2.0 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 ver... | (cls):
return "ARV_LOST_BACK"
@classmethod
def get_display_label(cls):
return "Perdus de vue de retour dans le TARV"
def filter_patients_dataframe(self, limit_date, start_date=None,
include_null_dates=False):
lost_prev = LostPatients(self.fuchia_da... | get_key | identifier_name |
lost_back_patients.py | # coding: utf-8
# Copyright 2017 Solthis.
#
# This file is part of Fugen 2.0.
#
# Fugen 2.0 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 ver... | arv_dead = ArvDeadPatientsDuringPeriod(self.fuchia_database)
dead = arv_dead.get_filtered_patients_dataframe(
limit_date,
start_date=start_date,
include_null_dates=include_null_dates
)
seen_id = seen_id.union(dead.index)
# Transferred during th... | random_line_split | |
gulpfile.js | 'use strict';
// load gulp and gulp plugins
var gulp = require("gulp");
var $ = require('gulp-load-plugins')();
// load node modules
var del = require('del');
var fs = require('fs');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
//
// Gulp config
//
// Override defaults w... |
this.emit('end');
};
//
// Gulp Tasks
//
gulp.task('styles', function() {
var sassOptions = {
outputStyle: 'expanded'
};
var sourcemapsOptions = {
debug: true
};
var nanoOptions = {
autoprefixer: {
browsers: ['> 1%', 'last 2 versions', 'IE >= 8'],
... | {
// Tell Travis to Stop Bro
process.exit(1);
} | conditional_block |
gulpfile.js | 'use strict';
// load gulp and gulp plugins
var gulp = require("gulp");
var $ = require('gulp-load-plugins')();
// load node modules
var del = require('del');
var fs = require('fs');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
//
// Gulp config
//
// Override defaults w... | gulp.watch([config.theme + '/**/*.{twig,php}'], browserSync.reload);
gulp.watch([config.assets + '/scss/**/*.scss'], ['styles']);
gulp.watch([config.assets + '/js/**/*.js'], ['scripts', browserSync.reload]);
gulp.watch([config.assets + '/{img,fonts}/**'], ['copy', browserSync.reload]);
});
//
// Multi... | gulp.task('watch', function() { | random_line_split |
MyfastfileCom.py | # -*- coding: utf-8 -*-
from module.common.json_layer import json_loads
from module.network.RequestFactory import getURL
from module.plugins.internal.MultiHoster import MultiHoster
class MyfastfileCom(MultiHoster):
__name__ = "MyfastfileCom"
__type__ = "hook"
__version__ = "0.02"
__config__ = ... | json_data = getURL('http://myfastfile.com/api.php?hosts', decode=True)
self.logDebug("JSON data", json_data)
json_data = json_loads(json_data)
return json_data['hosts'] | identifier_body | |
MyfastfileCom.py | # -*- coding: utf-8 -*-
from module.common.json_layer import json_loads
from module.network.RequestFactory import getURL
from module.plugins.internal.MultiHoster import MultiHoster
class | (MultiHoster):
__name__ = "MyfastfileCom"
__type__ = "hook"
__version__ = "0.02"
__config__ = [("hosterListMode", "all;listed;unlisted", "Use for hosters (if supported)", "all"),
("hosterList", "str", "Hoster list (comma separated)", ""),
("unloadFailing", "boo... | MyfastfileCom | identifier_name |
MyfastfileCom.py | # -*- coding: utf-8 -*-
from module.common.json_layer import json_loads
from module.network.RequestFactory import getURL
from module.plugins.internal.MultiHoster import MultiHoster
class MyfastfileCom(MultiHoster):
__name__ = "MyfastfileCom" |
__config__ = [("hosterListMode", "all;listed;unlisted", "Use for hosters (if supported)", "all"),
("hosterList", "str", "Hoster list (comma separated)", ""),
("unloadFailing", "bool", "Revert to standard download if download fails", False),
("interval", "int", ... | __type__ = "hook"
__version__ = "0.02" | random_line_split |
relational_layers_test.py | # coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. 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
#
# Un... |
shouldbe = np.stack(results, axis=-2)
# Compute the solution based on the layer.
layer = relational_layers.StackAnswers(answer_axis=-1, stack_axis=-2)
result = self.evaluate(layer([tf.constant(context), tf.constant(answers)]))
# Check that they are the same.
self.assertAllClose(shouldbe, result... | results.append(
np.concatenate([context, answers[:, :, i:(i + 1)]], axis=-1)) | conditional_block |
relational_layers_test.py | # coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. 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
#
# Un... |
def test_pairwise_edge_embeddings_for_tensor(self):
a = np.array([[[1], [2]]])
shouldbe = np.array([[[[1, 1], [1, 2]], [[2, 1], [2, 2]]]])
layer = relational_layers.PairwiseEdgeEmbeddings()
result = self.evaluate(layer(tf.constant(a)))
self.assertAllClose(shouldbe, result)
def test_relational... | a = np.arange(24).reshape((1, 4, 3, 2))
shouldbe = np.concatenate([a] * 3, axis=-2)
result = self.evaluate(relational_layers.repeat(tf.constant(a), 3, axis=-2))
self.assertAllClose(shouldbe, result) | identifier_body |
relational_layers_test.py | # coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. 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
#
# Un... |
def test_pairwise_edge_embeddings_for_tensor(self):
a = np.array([[[1], [2]]])
shouldbe = np.array([[[[1, 1], [1, 2]], [[2, 1], [2, 2]]]])
layer = relational_layers.PairwiseEdgeEmbeddings()
result = self.evaluate(layer(tf.constant(a)))
self.assertAllClose(shouldbe, result)
def test_relational_... | result = self.evaluate(relational_layers.repeat(tf.constant(a), 3, axis=-2))
self.assertAllClose(shouldbe, result) | random_line_split |
relational_layers_test.py | # coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. 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
#
# Un... | (self):
value, shouldbe = _create_positional_encoding_matrices()
a = tf.constant(value)
output_tensor = relational_layers.positional_encoding_like(a, -3, -2)
result = self.evaluate(output_tensor)
self.assertEqual((1, 4, 4, 2), result.shape)
self.assertAllClose(shouldbe, result)
def test_posit... | test_positional_encoding_like_for_static_shape_tensor | identifier_name |
filter.stories.ts | import { OptColumn, OptRow } from '../types/options';
import Grid from '../src/grid';
import '../src/css/grid.css';
import 'tui-date-picker/dist/tui-date-picker.css';
function createGrid(columns: OptColumn[], data: OptRow[] = []) {
const options = { data, columns };
const el = document.createElement('div');
el.s... |
export const layerBasic = () => {
const columns: OptColumn[] = [{ name: 'age', filter: 'number' }];
const { el } = createGrid(columns);
clickFilterBtnAsync(el);
return el;
};
const layerBasicNote = `
## Filter Layer
- Basic UI for \`number\` and \`string\` type
- Using native select-box (will be replaced wi... | buttons.story = { parameters: { notes: iconNote } }; | random_line_split |
filter.stories.ts | import { OptColumn, OptRow } from '../types/options';
import Grid from '../src/grid';
import '../src/css/grid.css';
import 'tui-date-picker/dist/tui-date-picker.css';
function createGrid(columns: OptColumn[], data: OptRow[] = []) {
const options = { data, columns };
const el = document.createElement('div');
el.s... | (el: HTMLElement, callback?: () => void) {
setTimeout(() => {
const filterBtn: HTMLElement = el.querySelector('.tui-grid-btn-filter');
filterBtn.click();
if (callback) {
callback();
}
});
}
function clickLayerInputAsync(el: HTMLElement) {
setTimeout(() => {
const input: HTMLElement = el... | clickFilterBtnAsync | identifier_name |
filter.stories.ts | import { OptColumn, OptRow } from '../types/options';
import Grid from '../src/grid';
import '../src/css/grid.css';
import 'tui-date-picker/dist/tui-date-picker.css';
function createGrid(columns: OptColumn[], data: OptRow[] = []) {
const options = { data, columns };
const el = document.createElement('div');
el.s... |
});
}
function clickLayerInputAsync(el: HTMLElement) {
setTimeout(() => {
const input: HTMLElement = el.querySelector('.tui-grid-filter-input');
input.click();
});
}
export default {
title: 'Filter',
parameters: { options: { panelPosition: 'right' } }
};
export const buttons = () => {
const colu... | {
callback();
} | conditional_block |
filter.stories.ts | import { OptColumn, OptRow } from '../types/options';
import Grid from '../src/grid';
import '../src/css/grid.css';
import 'tui-date-picker/dist/tui-date-picker.css';
function createGrid(columns: OptColumn[], data: OptRow[] = []) |
function clickFilterBtnAsync(el: HTMLElement, callback?: () => void) {
setTimeout(() => {
const filterBtn: HTMLElement = el.querySelector('.tui-grid-btn-filter');
filterBtn.click();
if (callback) {
callback();
}
});
}
function clickLayerInputAsync(el: HTMLElement) {
setTimeout(() => {
... | {
const options = { data, columns };
const el = document.createElement('div');
el.style.width = '500px';
const grid = new Grid({ el, ...options, bodyHeight: 100 });
return { el, grid };
} | identifier_body |
lithium.dom.js | /**
* @class Li
*/
/**
* DOM utility methods
*/
(function (factory) {
if (typeof define === "function" && define.amd) {
define(['./lithium', 'jquery'], factory);
} else if (typeof exports === 'object') { //For NodeJS
module.exports = factory(require('./lithium'), require('jquery-node'));
... | (str) {
var o = {};
str.split(',').forEach(function (val) {
o[val] = true;
});
return o;
}
var voidTags = unwrap('area,base,basefont,br,col,command,embed,frame,hr,img,input,keygen,link,meta,param,source,track,wbr... | unwrap | identifier_name |
lithium.dom.js | /**
* @class Li
*/
/**
* DOM utility methods
*/
(function (factory) {
if (typeof define === "function" && define.amd) {
define(['./lithium', 'jquery'], factory);
} else if (typeof exports === 'object') { //For NodeJS
module.exports = factory(require('./lithium'), require('jquery-node'));
... | return function (frag) {
var html = '';
Li.traverse(frag, frag, function (node, isOpenTag) {
if (node.nodeType === 1) {
var tag = node.nodeName.toLowerCase();
if (isOpenTag) {
html... | var voidTags = unwrap('area,base,basefont,br,col,command,embed,frame,hr,img,input,keygen,link,meta,param,source,track,wbr');
| random_line_split |
lithium.dom.js | /**
* @class Li
*/
/**
* DOM utility methods
*/
(function (factory) {
if (typeof define === "function" && define.amd) {
define(['./lithium', 'jquery'], factory);
} else if (typeof exports === 'object') { //For NodeJS
module.exports = factory(require('./lithium'), require('jquery-node'));
... |
if (node.nextSibling && node !== ancestor && ret !== 'break') {
node = node.nextSibling;
isOpenTag = true;
ret = callback.call(scope, node, true, 'nextSibling');
} else if (node.parentNode && node !== ancestor) {
//Traverse up the dom till you find an element with n... | { // close open tag first
callback.call(scope, node, false, 'current');
} | conditional_block |
lithium.dom.js | /**
* @class Li
*/
/**
* DOM utility methods
*/
(function (factory) {
if (typeof define === "function" && define.amd) {
define(['./lithium', 'jquery'], factory);
} else if (typeof exports === 'object') { //For NodeJS
module.exports = factory(require('./lithium'), require('jquery-node'));
... |
var voidTags = unwrap('area,base,basefont,br,col,command,embed,frame,hr,img,input,keygen,link,meta,param,source,track,wbr');
return function (frag) {
var html = '';
Li.traverse(frag, frag, function (node, isOpenTag) {
if (node.nodeType === 1)... | {
var o = {};
str.split(',').forEach(function (val) {
o[val] = true;
});
return o;
} | identifier_body |
App.tsx | import {
AreaBump,
Bar,
Bullet,
Bump,
Calendar,
Chord,
Choropleth,
CirclePacking,
Funnel,
GeoMap,
HeatMap,
Line,
Marimekko,
Network,
ParallelCoordinates,
Pie,
Radar,
Sankey,
ScatterPlot,
Stream,
Sunburst,
SwarmPlot,
TreeMap,
Voronoi,
Waffle,
} from './charts'
import {
... | <Route path="choropleth" element={<Choropleth />} />
<Route path="circle-packing" element={<CirclePacking />} />
<Route path="funnel" element={<Funnel />} />
<Route path="geomap" element={<GeoMap />} />
<Route path="heatmap" element={<HeatMap />} />
... | {
return (
<Router>
<div className={css({ display: 'flex', height: '100vh' })}>
<Navigation />
<div
className={css({
display: 'flex',
flex: 1,
flexDirection: 'column',
})}>
<ChartContainer title={<Title />}>
<Route... | identifier_body |
App.tsx | import {
AreaBump,
Bar,
Bullet,
Bump,
Calendar,
Chord,
Choropleth,
CirclePacking,
Funnel,
GeoMap,
HeatMap,
Line,
Marimekko,
Network,
ParallelCoordinates,
Pie,
Radar,
Sankey,
ScatterPlot,
Stream,
Sunburst,
SwarmPlot,
TreeMap,
Voronoi,
Waffle,
} from './charts'
import {
... | import { css } from 'otion'
import { useChart } from './hooks'
import ChartContainer from './ChartContainer'
import Navigation from './Navigation'
console.clear()
function Title() {
const [, flavor] = useChart()
const { pathname } = useLocation()
const title = pathname
.slice(1)
.split('-')
.concat(... | Route,
Routes,
useLocation,
} from 'react-router-dom' | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.