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 |
|---|---|---|---|---|
symtab.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
pub struct | {
parent: Option<Rc<SymTab>>,
names: RefCell<HashMap<String, usize>>,
}
impl SymTab {
pub fn new(parent: Rc<SymTab>, names: &[Rc<String>]) -> SymTab {
let mut hash_names = HashMap::new();
for (i, name) in names.iter().enumerate() {
hash_names.insert((**name).clone(), i);
... | SymTab | identifier_name |
awstools.py | Args:
config: Configuration for current optimization run
internal_conf: Internal CSAOpt configuration
"""
def __init__(self, config: ConfigTree, internal_conf: ConfigTree) -> None:
self.region = config.get('remote.aws.region', internal_conf['remote.aws.default_region'])
if ... | """The AWSTools class provides an abstraction over boto3 and EC2 for the use with CSAOpt
This is a context manager and creates required instances on `__enter__()`, disposing of the managed instances in
`__exit__()`. These two methods as well as :meth:`instancemanager.awstools.AWSTools.get_running_instances` ar... | identifier_body | |
awstools.py | new) group with AmazonEC2FullAccess
* Store the access key and secret key
Args:
config: Configuration for current optimization run
internal_conf: Internal CSAOpt configuration
"""
def __init__(self, config: ConfigTree, internal_conf: ConfigTree) -> None:
self.region = conf... | log.warning('Cannot remove security group, because none was created. Skipping...') | conditional_block | |
awstools.py | ) and config.get('remote.aws.access_key', False):
self.ec2_resource: boto3.session.Session.resource = boto3.resource(
'ec2',
aws_access_key_id=config['remote.aws.access_key'],
aws_secret_access_key=config['remote.aws.secret_key'],
region_name=s... | try:
response = self.ec2_client.create_security_group(GroupName=name, Description='Security Group for CSAOpt')
security_group_id = response['GroupId'] | random_line_split | |
awstools.py | called by the Runner (i.e. the only public methods).
This class will use boto3 to (1) create a security group, (2) configure ingress to the broker backend (currently
Redis, as used by Dramatiq). It then (3) creates as many worker instances as requested and runs 'user-data' scripts
after startup, which is ... | (self) -> None:
"""Block until broker and workers are up"""
self.broker.wait_until_running()
for worker in self.workers:
worker.wait_until_running()
def _run_start_scripts(self, timeout_ms: int) -> None:
"""Run any required setup procedures after the initial startup of ... | _wait_for_instances | identifier_name |
carbon-upgrade.js | #!/usr/bin/env node
/**
* Copyright IBM Corp. 2019, 2019
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable no-console */
'use strict';
// Makes the script crash on unhandled rejections instead of silently
//... |
var main = require('../src/cli');
main(process).catch((error) => {
console.error(error);
process.exit(1);
});
| {
console.error(
chalk.red(
`You are running Node ${currentNodeVersion}.\n` +
`carbon-upgrade requires Node 14 or higher, please update your ` +
`version of Node.`
)
);
process.exit(1);
} | conditional_block |
carbon-upgrade.js | #!/usr/bin/env node
/**
* Copyright IBM Corp. 2019, 2019
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable no-console */
'use strict';
// Makes the script crash on unhandled rejections instead of silently
//... | }
var main = require('../src/cli');
main(process).catch((error) => {
console.error(error);
process.exit(1);
}); | process.exit(1); | random_line_split |
status.ts | import { api, id, task, Action, actionheroVersion } from "./../index";
import * as path from "path";
const packageJSON = require(path.normalize(
path.join(__dirname, "..", "..", "package.json")
));
// These values are probably good starting points, but you should expect to tweak them for your application
const maxEv... |
}
async run(data) {
data.response.uptime = new Date().getTime() - api.bootTime;
data.response.nodeStatus = data.connection.localize("Node Healthy");
data.response.problems = [];
data.response.id = id;
data.response.actionheroVersion = actionheroVersion;
data.response.name = packageJSON.na... | {
data.response.nodeStatus = data.connection.localize("Node Unhealthy");
data.response.problems.push(
data.connection.localize([
"Resque Queues over {{maxResqueQueueLength}} jobs",
{ maxResqueQueueLength: maxResqueQueueLength },
])
);
} | conditional_block |
status.ts | import { api, id, task, Action, actionheroVersion } from "./../index";
import * as path from "path";
const packageJSON = require(path.normalize(
path.join(__dirname, "..", "..", "package.json")
));
// These values are probably good starting points, but you should expect to tweak them for your application
const maxEv... | () {
super();
this.name = "status";
this.description = "I will return some basic information about the API";
this.outputExample = {
id: "192.168.2.11",
actionheroVersion: "9.4.1",
uptime: 10469,
};
}
async checkRam(data) {
const consumedMemoryMB =
Math.round((process... | constructor | identifier_name |
status.ts | import { api, id, task, Action, actionheroVersion } from "./../index";
import * as path from "path";
const packageJSON = require(path.normalize(
path.join(__dirname, "..", "..", "package.json")
));
// These values are probably good starting points, but you should expect to tweak them for your application
const maxEv... |
};
| {
data.response.uptime = new Date().getTime() - api.bootTime;
data.response.nodeStatus = data.connection.localize("Node Healthy");
data.response.problems = [];
data.response.id = id;
data.response.actionheroVersion = actionheroVersion;
data.response.name = packageJSON.name;
data.response.de... | identifier_body |
status.ts | import { api, id, task, Action, actionheroVersion } from "./../index";
import * as path from "path";
const packageJSON = require(path.normalize(
path.join(__dirname, "..", "..", "package.json")
));
// These values are probably good starting points, but you should expect to tweak them for your application
const maxEv... | async run(data) {
data.response.uptime = new Date().getTime() - api.bootTime;
data.response.nodeStatus = data.connection.localize("Node Healthy");
data.response.problems = [];
data.response.id = id;
data.response.actionheroVersion = actionheroVersion;
data.response.name = packageJSON.name;
... | );
}
}
| random_line_split |
experiments.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# b... | ():
"""
Returns the test suite.
:return: the test suite
:rtype: unittest.TestSuite
"""
return unittest.TestLoader().loadTestsFromTestCase(TestExperiments)
if __name__ == '__main__':
jvm.start()
unittest.TextTestRunner().run(suite())
jvm.stop()
| suite | identifier_name |
experiments.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# b... | jvm.start()
unittest.TextTestRunner().run(suite())
jvm.stop() | conditional_block | |
experiments.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# b... | tester.resultmatrix = matrix
comparison_col = data.attribute_by_name("Correlation_coefficient").index
tester.instances = data
tester.header(comparison_col)
tester.multi_resultset_full(0, comparison_col)
# plot
plot.plot_experiment(matrix, title="Random split (w/ ... | random_line_split | |
experiments.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# b... | exp.run()
# evaluate
loader = converters.loader_for_file(outfile)
data = loader.load_file(outfile)
matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText")
tester = experiments.Tester("weka.experiment.PairedCorrectedTTester")
tester.resultmatrix... | def test_plot_experiment(self):
"""
Tests the plot_experiment method.
"""
datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")]
cls = [
classifiers.Classifier("weka.classifiers.trees.REPTree"),
classifiers... | identifier_body |
asynch_result.py | # coding: utf-8
import time
import config_mqtt
class Asynch_result:
def __init__(self, correlation_id, requests, yield_to):
self.correlation_id = correlation_id
self._requests_need_result = requests
self.yield_to = yield_to
| def get(self, timeout = config_mqtt.ASYNCH_RESULT_TIMEOUT):
# time.sleep(config_mqtt.ASYNCH_RESULT_WAIT_BEFORE_GET)
start_time = time.time()
request = self._requests_need_result.get(self.correlation_id)
if request:
while True:
current_time = time.... | random_line_split | |
asynch_result.py | # coding: utf-8
import time
import config_mqtt
class Asynch_result:
| if current_time - start_time > timeout: # timeout
# self._requests_need_result.pop(self.correlation_id)
raise Exception('Timeout: no result returned for request with correlation_id {}'.format(self.correlation_id))
else:
... | def __init__(self, correlation_id, requests, yield_to):
self.correlation_id = correlation_id
self._requests_need_result = requests
self.yield_to = yield_to
def get(self, timeout = config_mqtt.ASYNCH_RESULT_TIMEOUT):
# time.sleep(config_mqtt.ASYNCH_RESULT_WAIT_BEFOR... | identifier_body |
asynch_result.py | # coding: utf-8
import time
import config_mqtt
class Asynch_result:
def __init__(self, correlation_id, requests, yield_to):
self.correlation_id = correlation_id
self._requests_need_result = requests
self.yield_to = yield_to
def get(self, timeout = config_mq... |
else:
if current_time - start_time > timeout: # timeout
# self._requests_need_result.pop(self.correlation_id)
raise Exception('Timeout: no result returned for request with correlation_id {}'.format(self.correlation_id))
... | result = request.get('result')
# self._requests_need_result.pop(self.correlation_id)
return result | conditional_block |
asynch_result.py | # coding: utf-8
import time
import config_mqtt
class | :
def __init__(self, correlation_id, requests, yield_to):
self.correlation_id = correlation_id
self._requests_need_result = requests
self.yield_to = yield_to
def get(self, timeout = config_mqtt.ASYNCH_RESULT_TIMEOUT):
# time.sleep(config_mqtt.ASYNCH_RE... | Asynch_result | identifier_name |
err.rs |
}
impl<T> ErrorResult<T> {
#[inline]
pub fn unwrap(self) -> T {
match self {
Ok(d) => d,
Err(err) => sys::fail(err.msg())
}
}
#[inline]
pub fn is_error(&self) -> bool {
match *self {
Ok(_) => false,
Err(a) => a.is_err()
... | {
(-1*self.n) == code
} | identifier_body | |
err.rs | pub static EBADF : int = 9;
pub static ECHILD : int = 10;
pub static EAGAIN : int = 11;
pub static ENOMEM : int = 12;
pub static EACCES : int = 13;
pub static EFAULT : int = 14;
pub static ENOTBLK : int = 15;
pub static EBUSY : int = 16;
pub stat... | pub static EADDRINUSE : int = 98;
pub static EADDRNOTAVAIL : int = 99;
pub static ENETDOWN : int = 100;
pub static ENETUNREACH : int = 101;
pub static ENETRESET : int = 102;
pub static ECONNABORTED : int = 103;
pub static ECONNRESET : int = 104;
pub static ENOBUFS : int = 105;
pu... | random_line_split | |
err.rs | pub static ENONET : int = 64;
pub static ENOPKG : int = 65;
pub static EREMOTE : int = 66;
pub static ENOLINK : int = 67;
pub static EADV : int = 68;
pub static ESRMNT : int = 69;
pub static ECOMM : int = 70;
pub static EPROTO : int = 71;
pub stat... | {
"Unknown Error"
} | conditional_block | |
err.rs | (&self) -> bool {
match *self {
Ok(_) => false,
Err(a) => a.is_err()
}
}
}
pub static EPERM : int = 1;
pub static ENOENT : int = 2;
pub static ESRCH : int = 3;
pub static EINTR : int = 4;
pub static EIO : int = 5;
pub s... | is_error | identifier_name | |
demo_mean.py | #!/usr/bin/env python
# This is a demonstration of how to compute S2 order parameters from bond vector correlation functions.
# The S2 estimation is done with the method described in:
# Trbovic et al. Proteins (2008). doi:10.1002/prot.21750
from __future__ import print_function, division
import sys, os, glob
import M... |
# load correlation functions
corrFilenames = glob.glob(corrpath + '/*.zip')
op = mops.OrderParameter(corrfilenames=corrFilenames)
# predict order parameters, take only converged correlation functions into account
op.estimate("mean", converged=True)
# extract information
S2 = op.S2mean
S2_std = op.S2std... | print("No correlation functions found.")
print("Please run test_corr_fit.py first.")
sys.exit(1) | conditional_block |
demo_mean.py | #!/usr/bin/env python
# This is a demonstration of how to compute S2 order parameters from bond vector correlation functions.
# The S2 estimation is done with the method described in:
# Trbovic et al. Proteins (2008). doi:10.1002/prot.21750
from __future__ import print_function, division
import sys, os, glob
import M... | S2 = op.S2mean
S2_std = op.S2std
S2_err = op.S2error # = S2.std / <number subtrajectories>
avgcorr = op.avgcorr # correlation function object with averaged correlation functions over all subtrajectories
corr = avgcorr.corr # numerical correlation functions, array of shape = (nresidues, timef... | # predict order parameters, take only converged correlation functions into account
op.estimate("mean", converged=True)
# extract information | random_line_split |
describe_acls_v0.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | schema = [
{'name': 'throttle_time_ms', 'type': 'int32'},
{'name': 'error_code', 'type': 'int16'},
{'name': 'error_message', 'type': 'string'},
{'name': 'resources',
'type': 'array',
'item_type': [
{'name': 'resource_type', 'type': 'int8'},
{'n... | identifier_body | |
describe_acls_v0.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | {'name': 'resources',
'type': 'array',
'item_type': [
{'name': 'resource_type', 'type': 'int8'},
{'name': 'resource_name', 'type': 'string'},
{'name': 'acls',
'type': 'array',
'item_type': [
{'name': 'principa... | {'name': 'throttle_time_ms', 'type': 'int32'},
{'name': 'error_code', 'type': 'int16'},
{'name': 'error_message', 'type': 'string'}, | random_line_split |
describe_acls_v0.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | (BaseResponse):
schema = [
{'name': 'throttle_time_ms', 'type': 'int32'},
{'name': 'error_code', 'type': 'int16'},
{'name': 'error_message', 'type': 'string'},
{'name': 'resources',
'type': 'array',
'item_type': [
{'name': 'resource_type', 'type': 'int8... | DescribeAclsV0Response | identifier_name |
client.rs | use std::io;
use error::RbtError;
use amqp::{self, Session, Options, Channel};
use amqp::protocol::basic::{Deliver, BasicProperties};
use amqp::Basic;
use amqp::{Table, TableEntry};
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
use std::error::Error;
pub struct Sendable {
pub exchange: String,
... | pub rpctimeout: u64
}
pub type ReceiveCb = FnMut(&mut Channel, Deliver, BasicProperties, Vec<u8>) -> Result<(), RbtError> + Send;
pub struct Receiver {
pub exchange:String,
pub routing_key: Option<String>,
pub auto_ack: bool,
pub callback:Box<ReceiveCb>,
}
pub fn open_send(o:Options, s:Sendable,... | pub reader: Box<io::Read>,
pub priority: u8, | random_line_split |
client.rs | use std::io;
use error::RbtError;
use amqp::{self, Session, Options, Channel};
use amqp::protocol::basic::{Deliver, BasicProperties};
use amqp::Basic;
use amqp::{Table, TableEntry};
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
use std::error::Error;
pub struct Sendable {
pub exchange: String,
... |
// send properties
let mut props = BasicProperties {
content_type: Some(s.content_type),
headers: Some(headers),
priority: Some(s.priority),
..Default::default()
};
// if we are doing rpc, there is a receiver in this optional
let isrpc = match r {
Some(recei... | {
// open the channel
let (mut session, mut channel) = _open(o)?;
// table of headers, parsed from input
let mut headers = Table::new();
for st in s.headers {
let idx = st.find(':').ok_or("Header must have a :")?;
let (name, value) = st.split_at(idx);
let key = name.trim();... | identifier_body |
client.rs | use std::io;
use error::RbtError;
use amqp::{self, Session, Options, Channel};
use amqp::protocol::basic::{Deliver, BasicProperties};
use amqp::Basic;
use amqp::{Table, TableEntry};
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
use std::error::Error;
pub struct Sendable {
pub exchange: String,
... | if err.description() == "timed out waiting on channel".to_string() {
println!("Error timeout");
}
}
}
}
session.close(200, "Good Bye");
}
else {
// and unwind if not rpc
channel.close(200, "B... | {
let (tx, rx) = mpsc::channel();
thread::Builder::new().name("consumer_thread".to_string()).spawn(move || {
channel.start_consuming();
tx.send(channel).unwrap();
}).unwrap();
let timeout = s.rpctimeout;
if timeout == 0 {
// Block forever unt... | conditional_block |
client.rs | use std::io;
use error::RbtError;
use amqp::{self, Session, Options, Channel};
use amqp::protocol::basic::{Deliver, BasicProperties};
use amqp::Basic;
use amqp::{Table, TableEntry};
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
use std::error::Error;
pub struct Sendable {
pub exchange: String,
... | {
pub exchange:String,
pub routing_key: Option<String>,
pub auto_ack: bool,
pub callback:Box<ReceiveCb>,
}
pub fn open_send(o:Options, s:Sendable, r:Option<Receiver>) -> Result<(),RbtError> {
// open the channel
let (mut session, mut channel) = _open(o)?;
// table of headers, parsed fro... | Receiver | identifier_name |
views.py | from django.utils.translation import gettext_lazy as _
from wagtail.admin.ui.tables import Column, StatusFlagColumn, TitleColumn
from wagtail.admin.views import generic
from wagtail.admin.viewsets.model import ModelViewSet
from wagtail.core.models import Site
from wagtail.core.permissions import site_permission_policy | class IndexView(generic.IndexView):
page_title = _("Sites")
add_item_label = _("Add a site")
context_object_name = 'sites'
default_ordering = 'hostname'
columns = [
TitleColumn('hostname', label=_("Site"), sort_key='hostname', url_name='wagtailsites:edit'),
Column('port', sort_key='p... | from wagtail.sites.forms import SiteForm
| random_line_split |
views.py | from django.utils.translation import gettext_lazy as _
from wagtail.admin.ui.tables import Column, StatusFlagColumn, TitleColumn
from wagtail.admin.views import generic
from wagtail.admin.viewsets.model import ModelViewSet
from wagtail.core.models import Site
from wagtail.core.permissions import site_permission_policy... | (generic.EditView):
success_message = _("Site '{0}' updated.")
error_message = _("The site could not be saved due to errors.")
delete_item_label = _("Delete site")
context_object_name = 'site'
template_name = 'wagtailsites/edit.html'
class DeleteView(generic.DeleteView):
success_message = _("S... | EditView | identifier_name |
views.py | from django.utils.translation import gettext_lazy as _
from wagtail.admin.ui.tables import Column, StatusFlagColumn, TitleColumn
from wagtail.admin.views import generic
from wagtail.admin.viewsets.model import ModelViewSet
from wagtail.core.models import Site
from wagtail.core.permissions import site_permission_policy... |
class EditView(generic.EditView):
success_message = _("Site '{0}' updated.")
error_message = _("The site could not be saved due to errors.")
delete_item_label = _("Delete site")
context_object_name = 'site'
template_name = 'wagtailsites/edit.html'
class DeleteView(generic.DeleteView):
succe... | page_title = _("Add site")
success_message = _("Site '{0}' created.")
template_name = 'wagtailsites/create.html' | identifier_body |
algorithm_to_midi_test.py | from player import Player
import pandas as pd
import time
import asyncio
from midiutil import MIDIFile
PATTERNS = [[0, 0, 0, 0, 0, 0, 0, 0], #0
[1, 0, 0, 0, 0, 0, 0, 0], #1
[1, 0, 0, 0, 1, 0, 0, 0], #2
[1, 0, 1, 0, 1, 0, 0, 0], #3
[1, 0, 1, 0, 1, 0, 1, 0], #4
[1, 1, 1, 0, 1, 0, 1, 0], #5
... | return all_patterns
def group_patterns(all_patterns):
'''group the patterns into 16 x N matrix'''
counter = 0
all_pat = []
new_pat = []
for pattern in all_patterns:
new_pat.append(pattern)
counter+=1
if counter > 15:
counter = 0
all_pat.append(new_pat)
new_pat = []
return all_pat
... | all_patterns.append(pattern_from_mb_interval(row[6], MAX_MB[0]))
all_patterns.append(pattern_from_mb_interval(row[7], MAX_MB[1]))
all_patterns.append(pattern_from_mb_interval(row[8], MAX_MB[2]))
all_patterns.append(pattern_from_mb_interval(row[9], MAX_MB[3]))
| random_line_split |
algorithm_to_midi_test.py | from player import Player
import pandas as pd
import time
import asyncio
from midiutil import MIDIFile
PATTERNS = [[0, 0, 0, 0, 0, 0, 0, 0], #0
[1, 0, 0, 0, 0, 0, 0, 0], #1
[1, 0, 0, 0, 1, 0, 0, 0], #2
[1, 0, 1, 0, 1, 0, 0, 0], #3
[1, 0, 1, 0, 1, 0, 1, 0], #4
[1, 1, 1, 0, 1, 0, 1, 0], #5
... |
index+=1
return new_list
def group_to_regions(fixed_data):
'''groups the data into lists of 4 items'''
pats = []
for a, b, c, d in zip(*[iter(fixed_data)]*4):
pat = []
for i in [a,b,c,d]:
pat.append(i)
pats.append(pat)
return pats
def get_patterns(grouped_data):
'''convert data ... | counter+=1 | conditional_block |
algorithm_to_midi_test.py | from player import Player
import pandas as pd
import time
import asyncio
from midiutil import MIDIFile
PATTERNS = [[0, 0, 0, 0, 0, 0, 0, 0], #0
[1, 0, 0, 0, 0, 0, 0, 0], #1
[1, 0, 0, 0, 1, 0, 0, 0], #2
[1, 0, 1, 0, 1, 0, 0, 0], #3
[1, 0, 1, 0, 1, 0, 1, 0], #4
[1, 1, 1, 0, 1, 0, 1, 0], #5
... |
'''DATA PROCESSING'''
def fix_empty_regions(arr):
''' fills empty values so there would always be 4 rows for each second'''
new_list = []
counter = 1
index = 0
while True:
try:
i = arr[index]
except:
break
if counter == int(i[3]):
new_list.append(i)
else:
new_list.append((... | '''patterns are converted into a 16 x N matrix where each column is patterns for one of the 16 notes.
given the index of the column, this returns the midi code of the note'''
dt = {0:36, 1:38, 2:41, 3:43,4:48,5:50,6:53,7:55,8:60,9:96,10:65,11:67,12:72,13:74,14:77,15:79}
return dt[index] | identifier_body |
algorithm_to_midi_test.py | from player import Player
import pandas as pd
import time
import asyncio
from midiutil import MIDIFile
PATTERNS = [[0, 0, 0, 0, 0, 0, 0, 0], #0
[1, 0, 0, 0, 0, 0, 0, 0], #1
[1, 0, 0, 0, 1, 0, 0, 0], #2
[1, 0, 1, 0, 1, 0, 0, 0], #3
[1, 0, 1, 0, 1, 0, 1, 0], #4
[1, 1, 1, 0, 1, 0, 1, 0], #5
... | (pattern, file, note, start_time, duration = 1, volume=127):
'''writes one pattern to midi'''
track = 0
channel = 0
for ping in pattern:
if ping != 0:
file.addNote(track, channel, note, start_time, duration,volume)
start_time+=1
def patterns_to_midi(patterns, file, start_time):
'''writes 16 patte... | pattern_to_midi | identifier_name |
main.py | kivy.uix.screenmanager import SlideTransition
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.clock import Clock
import logging
import time
import utils
import os
import json
import sys
import screens.HomeScreen as HomeScreen
import overrides
class TopActionBar(ActionBar):
def __init_... | (self, text):
try:
self.logger.debug("Getting string for %s" % text)
return_string = self.lang[text]
except (ValueError, KeyError):
self.logger.error("No string found for %s in %s language file" % (text, self.language))
return_string = 'Language Error'
... | get_string | identifier_name |
main.py | (ActionBar):
def __init__(self, PlungeApp, **kwargs):
super(TopActionBar, self).__init__(**kwargs)
self.PlungeApp = PlungeApp
self.top_action_view = self.ids.top_action_view.__self__
self.top_action_previous = self.ids.top_action_previous.__self__
self.top_settings_button = s... |
def show_popup(self, title, text): | random_line_split | |
main.py | kivy.uix.screenmanager import SlideTransition
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.clock import Clock
import logging
import time
import utils
import os
import json
import sys
import screens.HomeScreen as HomeScreen
import overrides
class TopActionBar(ActionBar):
def __init_... |
else:
self.top_size_button.text = self.PlungeApp.get_string("Minimise")
self.top_action_previous.color = (1, 1, 1, 1)
self.PlungeApp.homeScreen.clear_widgets()
self.PlungeApp.homeScreen.add_widget(self.PlungeApp.homeScreen.max_layout)
self.PlungeApp.i... | self.top_size_button.text = self.PlungeApp.get_string("Maximise")
self.top_action_previous.bind(on_release=self.minimise)
self.PlungeApp.homeScreen.clear_widgets()
self.PlungeApp.homeScreen.add_widget(self.PlungeApp.homeScreen.min_layout)
self.PlungeApp.is_min = True | conditional_block |
main.py | kivy.uix.screenmanager import SlideTransition
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.clock import Clock
import logging
import time
import utils
import os
import json
import sys
import screens.HomeScreen as HomeScreen
import overrides
class TopActionBar(ActionBar):
def __init_... | self.mainScreenManager.add_widget(self.homeScreen)
self.topActionBar = TopActionBar(self)
self.root.add_widget(self.topActionBar)
self.root.add_widget(self.mainScreenManager)
self.homeScreen.clear_widgets()
if self.config.getint('standard', 'start_min') == 1:
... | self.logger.info("Fetching language from config")
self.language = self.config.get('standard', 'language')
try:
self.lang = json.load(open('res/json/languages/' + self.language.lower() + '.json', 'r'))
except (ValueError, IOError) as e:
self.logger.error('')
se... | identifier_body |
retention.rs | use crate::{Error, FsStats};
use iml_command_utils::wait_for_cmds_success;
use iml_influx::{Client as InfluxClient, InfluxClientExt as _};
use iml_manager_client::{graphql, Client};
use iml_postgres::{sqlx, PgPool};
use iml_tracing::tracing;
use iml_wire_types::{snapshot, Command};
use std::collections::HashMap;
async... |
Ok(None)
}
async fn get_snapshots(
pool: &sqlx::PgPool,
fs_name: &str,
) -> Result<Vec<snapshot::SnapshotRecord>, Error> {
let xs = sqlx::query_as!(
snapshot::SnapshotRecord,
"SELECT * FROM snapshot WHERE filesystem_name = $1 ORDER BY create_time ASC",
fs_name
)
.fetch... | {
if nodes.is_empty() {
return Ok(None);
} else {
let bytes_avail = nodes[0].bytes_avail;
let bytes_total = nodes[0].bytes_total;
let bytes_free = nodes[0].bytes_free;
let bytes_used = bytes_total - bytes_free;
return Ok(Some((byte... | conditional_block |
retention.rs | use crate::{Error, FsStats};
use iml_command_utils::wait_for_cmds_success;
use iml_influx::{Client as InfluxClient, InfluxClientExt as _};
use iml_manager_client::{graphql, Client};
use iml_postgres::{sqlx, PgPool};
use iml_tracing::tracing;
use iml_wire_types::{snapshot, Command};
use std::collections::HashMap;
async... | "stats record: {:?} - bytes free: {}",
stats_record.get(&fs_name),
bytes_free
);
let retention = get_retention_policy(pool, &fs_name).await?;
if let Some(retention) = retention {
let snapshots = get_snapshots(pool, &fs_... | {
let filesystems = get_retention_filesystems(pool).await?;
tracing::debug!("Filesystems with retentions: {:?}", filesystems);
for fs_name in filesystems {
let stats = get_stats_from_influx(&fs_name, &influx_client).await?;
if let Some((bytes_avail, bytes_free, bytes_used)) = stats {
... | identifier_body |
retention.rs | use crate::{Error, FsStats};
use iml_command_utils::wait_for_cmds_success;
use iml_influx::{Client as InfluxClient, InfluxClientExt as _};
use iml_manager_client::{graphql, Client};
use iml_postgres::{sqlx, PgPool};
use iml_tracing::tracing;
use iml_wire_types::{snapshot, Command};
use std::collections::HashMap;
async... | );
let retention = get_retention_policy(pool, &fs_name).await?;
if let Some(retention) = retention {
let snapshots = get_snapshots(pool, &fs_name).await?;
tracing::debug!(
"percent_left: {}, reserve value: {}",
... | bytes_free | random_line_split |
retention.rs | use crate::{Error, FsStats};
use iml_command_utils::wait_for_cmds_success;
use iml_influx::{Client as InfluxClient, InfluxClientExt as _};
use iml_manager_client::{graphql, Client};
use iml_postgres::{sqlx, PgPool};
use iml_tracing::tracing;
use iml_wire_types::{snapshot, Command};
use std::collections::HashMap;
async... | (
client: Client,
influx_client: InfluxClient,
pool: PgPool,
) -> Result<(), Error> {
let mut prev_stats: HashMap<String, u64> = vec![].into_iter().collect::<HashMap<String, u64>>();
loop {
prev_stats =
match process_retention(&client, &influx_client, &pool, prev_stats.clone()).... | handle_retention_rules | identifier_name |
comments.py | import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.templating import render_mako_def
from kai.lib.base import BaseController, render
from kai.lib.helpers import textilize
from kai.lib.serialization import render_feed
fro... | urlonly=True).strip()
comment['doc_id'] = comment_doc.doc_id
comment['description'] = textilize(comment_doc.content)
commentdata.append(comment)
response.content_type = 'application/atom+xml'
return render_feed(
... | if format == 'html':
abort(404)
elif format in ['atom', 'rss']:
# Pull comments and grab the docs with them for their info
comments = list(Comment.by_anytime(c.db, descending=True, limit=20))
commentdata = []
for comment_doc in comments:
... | identifier_body |
comments.py | import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.templating import render_mako_def
from kai.lib.base import BaseController, render
from kai.lib.helpers import textilize
from kai.lib.serialization import render_feed
fro... | (BaseController):
def preview(self):
data = request.POST['content']
return textilize(data)
def create(self, doc_id):
if not c.user:
abort(401)
# Ensure the doc exists
doc = self.db.get(doc_id)
if not doc:
abort(404)
... | CommentsController | identifier_name |
comments.py | import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.templating import render_mako_def |
from kai.lib.base import BaseController, render
from kai.lib.helpers import textilize
from kai.lib.serialization import render_feed
from kai.model import Comment
log = logging.getLogger(__name__)
class CommentsController(BaseController):
def preview(self):
data = request.POST['content']
return te... | random_line_split | |
comments.py | import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.templating import render_mako_def
from kai.lib.base import BaseController, render
from kai.lib.helpers import textilize
from kai.lib.serialization import render_feed
fro... | response.content_type = 'application/atom+xml'
return render_feed(
title="PylonsHQ Comment Feed", link=url.current(qualified=True),
description="Recent PylonsHQ comments", objects=commentdata,
pub_date='created')
| comments = list(Comment.by_anytime(c.db, descending=True, limit=20))
commentdata = []
for comment_doc in comments:
comment = {}
displayname = comment_doc.displayname or 'Anonymous'
comment['created'] = comment_doc.created
id = comme... | conditional_block |
rlptraits.rs | <D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// Internal helper trait. Implement `Decodable` for custom types.
pub trait RlpDecodable: Sized {
/// Decode a value from RLP bytes
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// A view into RLP encoded data
pub t... |
}
/// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list
pub trait RlpEncodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
}
/// RLP encoding stream
pub trait Stream: Sized {
/// Initializes instance of empty `Stream`.
fn new() ... | {
let mut s = RlpStream::new();
self.rlp_append(&mut s);
s.drain()
} | identifier_body |
rlptraits.rs | decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// Internal helper trait. Implement `Decodable` for custom types.
pub trait RlpDecodable: Sized {
/// Decode a value from RLP bytes
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// A view into RLP encoded dat... | (&self) -> ElasticArray1024<u8> {
let mut s = RlpStream::new();
self.rlp_append(&mut s);
s.drain()
}
}
/// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list
pub trait RlpEncodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
}
... | rlp_bytes | identifier_name |
rlptraits.rs | decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// Internal helper trait. Implement `Decodable` for custom types.
pub trait RlpDecodable: Sized {
/// Decode a value from RLP bytes
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// A view into RLP encoded dat... | /// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let strings: Vec<String> = rlp.iter().map(| i | i.as_val()).collect();
/// }
/// ```
fn iter(&'view self) -> Self::Iter;
/// Decode data into an object
fn as_val<T>(&self) -> Resul... | /// extern crate rlp;
/// use rlp::*;
/// | random_line_split |
evaluationinfo.py | __author__="Sergey Karakovskiy"
__date__ ="$Mar 18, 2010 10:48:28 PM$"
class Inspectable(object):
""" All derived classes gains the ability to print the names and values of all their fields"""
def | (self):
return '<%s: %s>' % (self.__class__.__name__,
dict([(x,y) for (x,y) in self.__dict__.items() if not x.startswith('_')]) )
class EvaluationInfo(Inspectable):
def __init__(self, evInfo):
print "widthCells = ", evInfo[0]
print "widthPhys = ", evInfo[1]
print "flow... | __repr__ | identifier_name |
evaluationinfo.py | __author__="Sergey Karakovskiy"
__date__ ="$Mar 18, 2010 10:48:28 PM$"
class Inspectable(object):
""" All derived classes gains the ability to print the names and values of all their fields"""
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__,
dict([(x,y) for (x,y) in self.__... | self.killsByStomp = evInfo[5]
self.killsTotal = evInfo[6]
self.marioMode = evInfo[7]
self.marioStatus = evInfo[8]
self.mushroomsDevoured = evInfo[9]
self.marioCoinsGained = evInfo[10]
self.timeLeft = evInfo[11]
self.timeSpent = evInfo[12]
self.hidd... | print "widthCells = ", evInfo[0]
print "widthPhys = ", evInfo[1]
print "flowersDevoured = ", evInfo[2]
print "killsByFire = ", evInfo[3]
print "killsByShell = ", evInfo[4]
print "killsByStomp = ", evInfo[5]
print "killsTotal = ", evInfo[6]
print "marioMode = ", ... | identifier_body |
evaluationinfo.py | __author__="Sergey Karakovskiy"
__date__ ="$Mar 18, 2010 10:48:28 PM$"
class Inspectable(object):
""" All derived classes gains the ability to print the names and values of all their fields"""
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__,
dict([(x,y) for (x,y) in self.__... | self.marioStatus = evInfo[8]
self.mushroomsDevoured = evInfo[9]
self.marioCoinsGained = evInfo[10]
self.timeLeft = evInfo[11]
self.timeSpent = evInfo[12]
self.hiddenBlocksFound = evInfo[13] | self.killsByFire = evInfo[3]
self.killsByShell = evInfo[4]
self.killsByStomp = evInfo[5]
self.killsTotal = evInfo[6]
self.marioMode = evInfo[7] | random_line_split |
read_dir.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::CStr;
use std::io::Result;
use std::mem::size_of;
use std::os::unix::io::AsRawFd;
use data_model::DataInit;
use crate::syscall;
#[repr... | () {
assert_eq!(strip_padding(b".\0\0\0\0\0\0\0").to_bytes(), b".");
assert_eq!(strip_padding(b"..\0\0\0\0\0\0").to_bytes(), b"..");
assert_eq!(
strip_padding(b"normal cstring\0").to_bytes(),
b"normal cstring"
);
assert_eq!(strip_padding(b"\0\0\0\0").to_by... | padded_cstrings | identifier_name |
read_dir.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::CStr;
use std::io::Result;
use std::mem::size_of;
use std::os::unix::io::AsRawFd;
use data_model::DataInit;
use crate::syscall;
#[repr... | end: 0,
})
}
// Like `CStr::from_bytes_with_nul` but strips any bytes after the first '\0'-byte. Panics if `b`
// doesn't contain any '\0' bytes.
fn strip_padding(b: &[u8]) -> &CStr {
// It would be nice if we could use memchr here but that's locked behind an unstable gate.
let pos = b
.ite... | Ok(ReadDir {
buf: [0u8; 256],
dir,
current: 0, | random_line_split |
html.js |
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Argume... | { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) re... | identifier_body | |
html.js | (o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLike... | } finally {
_iterator.f();
}
}
return e;
},
m = function m(e, t) {
return a(d(o(e != null ? u(g(e)) : {}, "default", !t && e && e.__esModule ? {
get: function get() {
return e.default;
},
enumerable: !0
} : {
value... | {
var _iterator = _createForOfIteratorHelper(x(t)),
_step;
try {
var _loop = function _loop() {
var r = _step.value;
!y.call(e, r) && (n || r !== "default") && o(e, r, {
get: function get() {
return t[r];
},
... | conditional_block |
html.js | (o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clam... | _unsupportedIterableToArray | identifier_name | |
html.js | ToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _ar... | v = {
defaultToken: "",
tokenPostfix: ".html",
ignoreCase: !0,
tokenizer: {
root: [[/<!DOCTYPE/, "metatag", "@doctype"], [/<!--/, "comment", "@comment"], [/(<)((?:[\w\-]+:)?[\w\-]+)(\s*)(\/>)/, ["delimiter", "tag", "", "delimiter"]], [/(<)(script)/, ["delimiter", {
toke... | }
}, | random_line_split |
static.py | from django import template
from django.apps import apps
from django.utils.encoding import iri_to_uri
from django.utils.six.moves.urllib.parse import urljoin
register = template.Library()
class PrefixNode(template.Node):
def __repr__(self):
return "<PrefixNode for %r>" % self.name
def __init__(self... |
@classmethod
def handle_token(cls, parser, token):
"""
Class method to parse prefix node and return a Node.
"""
bits = token.split_contents()
if len(bits) < 2:
raise template.TemplateSyntaxError(
"'%s' takes at least one argument (path to fi... | if apps.is_installed('django.contrib.staticfiles'):
from django.contrib.staticfiles.storage import staticfiles_storage
return staticfiles_storage.url(path)
else:
return urljoin(PrefixNode.handle_simple("STATIC_URL"), path) | identifier_body |
static.py | from django import template
from django.apps import apps
from django.utils.encoding import iri_to_uri
from django.utils.six.moves.urllib.parse import urljoin
register = template.Library()
class PrefixNode(template.Node):
def __repr__(self):
return "<PrefixNode for %r>" % self.name
def __init__(self... | Examples::
{% get_static_prefix %}
{% get_static_prefix as static_prefix %}
"""
return PrefixNode.handle_token(parser, token, "STATIC_URL")
@register.tag
def get_media_prefix(parser, token):
"""
Populates a template variable with the media prefix,
``settings.MEDIA_URL``.
... |
Usage::
{% get_static_prefix [as varname] %}
| random_line_split |
static.py | from django import template
from django.apps import apps
from django.utils.encoding import iri_to_uri
from django.utils.six.moves.urllib.parse import urljoin
register = template.Library()
class PrefixNode(template.Node):
def __repr__(self):
return "<PrefixNode for %r>" % self.name
def __init__(self... | (parser, token):
"""
Populates a template variable with the media prefix,
``settings.MEDIA_URL``.
Usage::
{% get_media_prefix [as varname] %}
Examples::
{% get_media_prefix %}
{% get_media_prefix as media_prefix %}
"""
return PrefixNode.handle_token(parser, token,... | get_media_prefix | identifier_name |
static.py | from django import template
from django.apps import apps
from django.utils.encoding import iri_to_uri
from django.utils.six.moves.urllib.parse import urljoin
register = template.Library()
class PrefixNode(template.Node):
def __repr__(self):
return "<PrefixNode for %r>" % self.name
def __init__(self... |
else:
varname = None
return cls(varname, name)
@classmethod
def handle_simple(cls, name):
try:
from django.conf import settings
except ImportError:
prefix = ''
else:
prefix = iri_to_uri(getattr(settings, name, ''))
... | varname = tokens[2] | conditional_block |
servlet.py | # Copyright 2013 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.
class RequestHeaders(object):
'''A custom dictionary impementation for headers which ignores the case
of requests, since different HTTP libraries seem t... | return self._buf[0]
def __str__(self):
return self.ToString()
def __len__(self):
return len(self.ToString())
def _Collapse(self):
self._buf = [''.join(self._buf)]
class Response(object):
'''The response from Get().
'''
def __init__(self, content=None, headers=None, status=None):
self... | def ToString(self):
self._Collapse() | random_line_split |
servlet.py | # Copyright 2013 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.
class RequestHeaders(object):
'''A custom dictionary impementation for headers which ignores the case
of requests, since different HTTP libraries seem t... |
class _ContentBuilder(object):
'''Builds the response content.
'''
def __init__(self):
self._buf = []
def Append(self, content):
if isinstance(content, unicode):
content = content.encode('utf-8', 'replace')
self._buf.append(content)
def ToString(self):
self._Collapse()
return sel... | '''Request data.
'''
def __init__(self, path, host, headers):
self.path = path.lstrip('/')
self.host = host.rstrip('/')
self.headers = RequestHeaders(headers)
@staticmethod
def ForTest(path, host=None, headers=None):
return Request(path, host or 'http://developer.chrome.com', headers or {})
... | identifier_body |
servlet.py | # Copyright 2013 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.
class RequestHeaders(object):
'''A custom dictionary impementation for headers which ignores the case
of requests, since different HTTP libraries seem t... |
return (self.headers.get('Location'), self.status == 301)
def IsNotFound(self):
return self.status == 404
def __eq__(self, other):
return (isinstance(other, self.__class__) and
str(other.content) == str(self.content) and
other.headers == self.headers and
other.stat... | return (None, None) | conditional_block |
servlet.py | # Copyright 2013 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.
class RequestHeaders(object):
'''A custom dictionary impementation for headers which ignores the case
of requests, since different HTTP libraries seem t... | (self):
return 'Request(path=%s, host=%s, headers=%s)' % (
self.path, self.host, self.headers)
def __str__(self):
return repr(self)
class _ContentBuilder(object):
'''Builds the response content.
'''
def __init__(self):
self._buf = []
def Append(self, content):
if isinstance(content,... | __repr__ | identifier_name |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
use core::iter::ExactSizeIterator;
use core::iter::Enumerate;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A... | match y {
Some(v) => { assert_eq!(v, (9 - x as usize, 19 - x)); }
None => { assert!(false); }
}
}
assert_eq!(enumerate.next_back(), None::<(usize, T)>);
}
} | random_line_split | |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
use core::iter::ExactSizeIterator;
use core::iter::Enumerate;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A... |
}
impl ExactSizeIterator for A<T> {
// fn len(&self) -> usize {
// let (lower, upper) = self.size_hint();
// // Note: This assertion is overly defensive, but it checks the invariant
// // guaranteed by the trait. If this trait were rust-internal,
// // we could use debug_assert!; assert_e... | {
if self.begin < self.end {
self.end = self.end.wrapping_sub(1);
Some::<Self::Item>(self.end)
} else {
None::<Self::Item>
}
} | identifier_body |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
use core::iter::ExactSizeIterator;
use core::iter::Enumerate;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A... |
None => { assert!(false); }
}
}
assert_eq!(enumerate.next_back(), None::<(usize, T)>);
}
}
| { assert_eq!(v, (9 - x as usize, 19 - x)); } | conditional_block |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
use core::iter::ExactSizeIterator;
use core::iter::Enumerate;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A... | (&mut self) -> Option<Self::Item> {
if self.begin < self.end {
self.end = self.end.wrapping_sub(1);
Some::<Self::Item>(self.end)
} else {
None::<Self::Item>
}
}
}
impl ExactSizeIterator for A<T> {
// fn len(&self) -> usize {
// let (lower, upper) = self.size_hint();
// // Note:... | next_back | identifier_name |
urls.py | #!/usr/bin/env python3
"""CnbetaApi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.h... | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib imp... | random_line_split | |
lib.rs | // Copyright GFX Developers 2014-2017
//
// 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 ... | Line, Lines, EmitLines};
pub use triangulate::{EmitTriangles, Triangulate, TriangulateIterator};
pub use indexer::{Indexer, LruIndexer};
pub use neighbors::Neighbors;
mod triangulate;
mod poly;
mod indexer;
mod generator;
mod neighbors;
mod cone;
mod cube;
mod cylinder;
mod plane;
mod sphere;
mod to... | extern crate cgmath;
extern crate mint;
pub use poly::{Quad, Triangle, Polygon, Vertices, VerticesIterator, MapToVertices, MapVertex, | random_line_split |
lib.rs | // Copyright GFX Developers 2014-2017
//
// 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 ... | {
/// Vertex position
pub pos: Position,
/// Vertex normal
pub normal: Normal,
}
| Vertex | identifier_name |
BaseDbContext.js | /**
* Imports
*/
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
/**
* BaseDbContext class
* @param {Object} options
*/
var BaseDbContext = module.exports = function(options) {
options || (options = {});
this.entities = {};
this._loadModels();
this.initialize.a... | (protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function() {
return parent.apply(this, arguments);
};
}
_.extend(child, parent, staticProps);
... | extend | identifier_name |
BaseDbContext.js | /**
* Imports
*/
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
/**
* BaseDbContext class
* @param {Object} options
*/
var BaseDbContext = module.exports = function(options) {
options || (options = {});
this.entities = {};
this._loadModels();
this.initialize.a... | }
});
if (protoProps) _.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
return child;
}
;
BaseDbContext.extend = extend;
module.exports = BaseDbContext; | {
var parent = this;
var child;
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function() {
return parent.apply(this, arguments);
};
}
_.extend(child, parent, staticProps);
child.prototype = Object... | identifier_body |
BaseDbContext.js | /**
* Imports
*/
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
/**
* BaseDbContext class
* @param {Object} options
*/
var BaseDbContext = module.exports = function(options) {
options || (options = {});
this.entities = {};
this._loadModels();
this.initialize.a... |
_.extend(child, parent, staticProps);
child.prototype = Object.create(parent.prototype, {
constructor: {
value: child,
enumerable: false,
writable: true,
configurable: true
}
});
if (protoProps) _.extend(child.prototype, protoProps);
... | {
child = function() {
return parent.apply(this, arguments);
};
} | conditional_block |
BaseDbContext.js | /**
* Imports
*/
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
/** | * @param {Object} options
*/
var BaseDbContext = module.exports = function(options) {
options || (options = {});
this.entities = {};
this._loadModels();
this.initialize.apply(this, arguments);
}
_.extend(BaseDbContext.prototype, {
initialize: function () {},
modelsFolder: [],
_loadModels: func... | * BaseDbContext class | random_line_split |
app_lcd_tiva_c.rs | #![feature(plugin)]
#![crate_type="staticlib"]
#![no_std]
extern crate core; |
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
xtal = "X16_0MHz";
pll = false;
}
gpio {
a {
d7@5 { direction = "out"; }
}
b {
rs@0 { direction = "out"; }
en@1 { direction = "out"; }
d6@4 { direction = "out"; }
}
e... | extern crate zinc;
#[macro_use] #[plugin] #[no_link] extern crate macro_platformtree;
use zinc::drivers::chario::CharIO;
use zinc::drivers::lcd::hd44780u::{Hd44780u, Font}; | random_line_split |
app_lcd_tiva_c.rs | #![feature(plugin)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[macro_use] #[plugin] #[no_link] extern crate macro_platformtree;
use zinc::drivers::chario::CharIO;
use zinc::drivers::lcd::hd44780u::{Hd44780u, Font};
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
... | lcd.custom_char_5x8(1,
[0b00100,
0b01010,
0b00100,
0b11111,
0b00100,
0b01010,
0b10001,
0b00000]);
// Enable blinking
lcd.display_c... | {
let lcd = Hd44780u::new(args.timer,
args.rs,
args.en,
[ args.d4, args.d5, args.d6, args.d7 ]);
lcd.init(true, Font::Font5x8);
// Create custom 'heart' character at index 0.
lcd.custom_char_5x8(0,
[0b00000,
... | identifier_body |
app_lcd_tiva_c.rs | #![feature(plugin)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[macro_use] #[plugin] #[no_link] extern crate macro_platformtree;
use zinc::drivers::chario::CharIO;
use zinc::drivers::lcd::hd44780u::{Hd44780u, Font};
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
... | (args: &pt::run_args) {
let lcd = Hd44780u::new(args.timer,
args.rs,
args.en,
[ args.d4, args.d5, args.d6, args.d7 ]);
lcd.init(true, Font::Font5x8);
// Create custom 'heart' character at index 0.
lcd.custom_char_5x8(0,
... | run | identifier_name |
vec_resource.rs | use super::{Resource, ResourceSeek};
use alloc::boxed::Box;
use collections::{String, Vec};
use core::cmp::{max, min};
use system::error::Result;
use system::syscall::Stat;
/// A vector resource
pub struct VecResource {
path: String,
data: Vec<u8>,
mode: u16,
seek: usize,
}
impl VecResource {
... |
fn truncate(&mut self, len: usize) -> Result<()> {
while len > self.data.len() {
self.data.push(0);
}
self.data.truncate(len);
self.seek = min(self.seek, self.data.len());
Ok(())
}
}
| {
Ok(())
} | identifier_body |
vec_resource.rs | use super::{Resource, ResourceSeek};
use alloc::boxed::Box;
use collections::{String, Vec};
use core::cmp::{max, min};
use system::error::Result;
use system::syscall::Stat;
/// A vector resource
pub struct VecResource {
path: String,
data: Vec<u8>,
mode: u16,
seek: usize,
}
impl VecResource {
... | (&mut self) -> Result<()> {
Ok(())
}
fn truncate(&mut self, len: usize) -> Result<()> {
while len > self.data.len() {
self.data.push(0);
}
self.data.truncate(len);
self.seek = min(self.seek, self.data.len());
Ok(())
}
}
| sync | identifier_name |
vec_resource.rs | use super::{Resource, ResourceSeek};
use alloc::boxed::Box;
use collections::{String, Vec};
use core::cmp::{max, min};
use system::error::Result;
use system::syscall::Stat;
/// A vector resource
pub struct VecResource {
path: String,
data: Vec<u8>,
mode: u16,
seek: usize,
}
impl VecResource {
... | ResourceSeek::Start(offset) => self.seek = min(self.data.len(), offset),
ResourceSeek::Current(offset) =>
self.seek = max(0, min(self.seek as isize, self.seek as isize + offset)) as usize,
ResourceSeek::End(offset) =>
self.seek = max(0,
... | random_line_split | |
debug_hover_layout.py | # Copyright 2020 Makani Technologies LLC
#
# 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 agreed to... | (hover_template.HoverLayout):
"""The hover layout."""
_NAME = 'Debug (Hover)'
_MODE = common.FULL_COMMS_MODE
| DebugHoverLayout | identifier_name |
debug_hover_layout.py | # Copyright 2020 Makani Technologies LLC
#
# 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 | # See the License for the specific language governing permissions and
# limitations under the License.
"""Layout to monitor hover status through full telemetry."""
from makani.gs.monitor2.apps.plugins import common
from makani.gs.monitor2.apps.plugins.layouts import hover_template
class DebugHoverLayout(hover_templ... | #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | random_line_split |
debug_hover_layout.py | # Copyright 2020 Makani Technologies LLC
#
# 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 agreed to... | """The hover layout."""
_NAME = 'Debug (Hover)'
_MODE = common.FULL_COMMS_MODE | identifier_body | |
client.py | import re
from typing import Any
import numpy as np
import pandas as pd
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
import ibis.expr.types as ir
fully_qualified_re = re.compile(r"(.*)\.(?:`(.*)`|(.*))")
base_typename_re = re.compile(r"(\w+)")
_clickhouse_dtypes = {
'Null': dt.Null,
... | }
_ibis_dtypes = {v: k for k, v in _clickhouse_dtypes.items()}
_ibis_dtypes[dt.String] = 'String'
_ibis_dtypes[dt.Timestamp] = 'DateTime'
class ClickhouseDataType:
__slots__ = 'typename', 'base_typename', 'nullable'
def __init__(self, typename, nullable=False):
m = base_typename_re.match(typename)
... | 'Array': dt.Array, | random_line_split |
client.py | import re
from typing import Any
import numpy as np
import pandas as pd
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
import ibis.expr.types as ir
fully_qualified_re = re.compile(r"(.*)\.(?:`(.*)`|(.*))")
base_typename_re = re.compile(r"(\w+)")
_clickhouse_dtypes = {
'Null': dt.Null,
... | (name: str) -> str:
lbracket_pos = name.find('(')
rbracket_pos = name.rfind(')')
if lbracket_pos == -1 or rbracket_pos == -1:
return ''
subname = name[lbracket_pos + 1 : rbracket_pos]
return subname
@staticmethod
def get_typename_from_ibis_dtype(dtype):
... | get_subname | identifier_name |
client.py | import re
from typing import Any
import numpy as np
import pandas as pd
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
import ibis.expr.types as ir
fully_qualified_re = re.compile(r"(.*)\.(?:`(.*)`|(.*))")
base_typename_re = re.compile(r"(\w+)")
_clickhouse_dtypes = {
'Null': dt.Null,
... |
@property
def _database(self):
return self._match_name()[0]
def invalidate_metadata(self):
self._client.invalidate_metadata(self._qualified_name)
def metadata(self) -> Any:
"""Return the parsed results of a `DESCRIBE FORMATTED` statement.
Returns
-------
... | m = fully_qualified_re.match(self._qualified_name)
if not m:
raise com.IbisError(
'Cannot determine database name from {}'.format(
self._qualified_name
)
)
db, quoted, unquoted = m.groups()
return db, quoted or unquoted | identifier_body |
client.py | import re
from typing import Any
import numpy as np
import pandas as pd
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
import ibis.expr.types as ir
fully_qualified_re = re.compile(r"(.*)\.(?:`(.*)`|(.*))")
base_typename_re = re.compile(r"(\w+)")
_clickhouse_dtypes = {
'Null': dt.Null,
... |
else:
return self.typename
def __repr__(self):
return f'<Clickhouse {str(self)}>'
@classmethod
def parse(cls, spec):
# TODO(kszucs): spare parsing, depends on clickhouse-driver#22
if spec.startswith('Nullable'):
return cls(spec[9:-1], nullable=True)... | return f'Nullable({self.typename})' | conditional_block |
basic.py | """A basic implementation of a Neural Network
by following the tutorial by Andrew Trask
http://iamtrask.github.io/2015/07/12/basic-python-network/
"""
import numpy as np
# sigmoid function
def nonlin(x, deriv=False):
|
# input dataset
x = np.array([[0, 0, 1],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1]])
# output dataset
y = np.array([[0, 0, 1, 1]]).T
# seed random numbers to make calculation
# deterministic (good practice)
np.random.seed(1)
# initialize weights randomly with mean 0
syn0 = 2*n... | if deriv==True:
return x * (1-x)
return 1 / (1 + np.exp(-x)) | identifier_body |
basic.py | """A basic implementation of a Neural Network
by following the tutorial by Andrew Trask
http://iamtrask.github.io/2015/07/12/basic-python-network/
"""
import numpy as np
# sigmoid function
def nonlin(x, deriv=False):
if deriv==True:
return x * (1-x)
return 1 / (1 + np.exp(-x))
# input dataset
x = np.... | print l1 | # update weights
syn0 += np.dot(l0.T, l1_delta)
print 'Output after training:' | random_line_split |
basic.py | """A basic implementation of a Neural Network
by following the tutorial by Andrew Trask
http://iamtrask.github.io/2015/07/12/basic-python-network/
"""
import numpy as np
# sigmoid function
def | (x, deriv=False):
if deriv==True:
return x * (1-x)
return 1 / (1 + np.exp(-x))
# input dataset
x = np.array([[0, 0, 1],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1]])
# output dataset
y = np.array([[0, 0, 1, 1]]).T
# seed random numbers to make calculation
# determi... | nonlin | identifier_name |
basic.py | """A basic implementation of a Neural Network
by following the tutorial by Andrew Trask
http://iamtrask.github.io/2015/07/12/basic-python-network/
"""
import numpy as np
# sigmoid function
def nonlin(x, deriv=False):
if deriv==True:
|
return 1 / (1 + np.exp(-x))
# input dataset
x = np.array([[0, 0, 1],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1]])
# output dataset
y = np.array([[0, 0, 1, 1]]).T
# seed random numbers to make calculation
# deterministic (good practice)
np.random.seed(1)
# initialize weights... | return x * (1-x) | conditional_block |
cost.py | # Copyright (c) 2016, the GPyOpt Authors
# Licensed under the BSD 3-clause license (see LICENSE.txt)
from ...models import GPModel
import numpy as np
class CostModel(object):
"""
Class to handle the cost of evaluating the function.
param cost_withGradients: function that returns the cost of evaluating ... |
def _cost_gp_withGradients(self,x):
"""
Predicts the time cost and its gradient of evaluating the function at x.
"""
m, _, dmdx, _= self.cost_model.predict_withGradients(x)
return np.exp(m), np.exp(m)*dmdx
def update_cost_model(self, x, cost_x):
"""
Upd... | """
Predicts the time cost of evaluating the function at x.
"""
m, _, _, _ = self.cost_model.predict_withGradients(x)
return np.exp(m) | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.