file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
test_lms_matlab_problem.py | # -*- coding: utf-8 -*-
"""
Test for matlab problems
"""
import time
from ...pages.lms.matlab_problem import MatlabProblemPage
from ...fixtures.course import XBlockFixtureDesc
from ...fixtures.xqueue import XQueueResponseFixture
from .test_lms_problems import ProblemsTest
from textwrap import dedent
class MatlabProb... |
matlab_problem_page.set_response(self.submission)
matlab_problem_page.click_run_code()
self.assertEqual(
u'Submitted. As soon as a response is returned, this message will be replaced by that feedback.',
matlab_problem_page.get_grader_msg(".external-grader-message")[0]
... | XQueueResponseFixture(self.submission, self.xqueue_grade_response).install() | conditional_block |
test_lms_matlab_problem.py | # -*- coding: utf-8 -*-
"""
Test for matlab problems
"""
import time
from ...pages.lms.matlab_problem import MatlabProblemPage
from ...fixtures.course import XBlockFixtureDesc
from ...fixtures.xqueue import XQueueResponseFixture
from .test_lms_problems import ProblemsTest
from textwrap import dedent
class MatlabProb... | ) | random_line_split | |
test_lms_matlab_problem.py | # -*- coding: utf-8 -*-
"""
Test for matlab problems
"""
import time
from ...pages.lms.matlab_problem import MatlabProblemPage
from ...fixtures.course import XBlockFixtureDesc
from ...fixtures.xqueue import XQueueResponseFixture
from .test_lms_problems import ProblemsTest
from textwrap import dedent
class MatlabProb... |
def _goto_matlab_problem_page(self):
"""
Open matlab problem page with assertion.
"""
self.courseware_page.visit()
matlab_problem_page = MatlabProblemPage(self.browser)
self.assertEqual(matlab_problem_page.problem_name, 'TEST MATLAB PROBLEM')
return matlab_p... | """
Create a matlab problem for the test.
"""
problem_data = dedent("""
<problem markdown="null">
<text>
<p>
Write MATLAB code to create the following row vector and store it in a variable named <code>V</code>.
... | identifier_body |
cleanup_sst.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt;
use std::sync::Arc;
use kvproto::import_sstpb::SstMeta;
use crate::store::util::is_epoch_stale;
use crate::store::{StoreMsg, StoreRouter};
use engine_traits::KvEngine;
use pd_client::PdClient;
use sst_importer::SSTImporter;
use std::mar... | (
store_id: u64,
store_router: S,
importer: Arc<SSTImporter>,
pd_client: Arc<C>,
) -> Runner<EK, C, S> {
Runner {
store_id,
store_router,
importer,
pd_client,
_engine: PhantomData,
}
}
/// Deletes SS... | new | identifier_name |
cleanup_sst.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt;
use std::sync::Arc;
use kvproto::import_sstpb::SstMeta;
use crate::store::util::is_epoch_stale;
use crate::store::{StoreMsg, StoreRouter};
use engine_traits::KvEngine;
use pd_client::PdClient;
use sst_importer::SSTImporter;
use std::mar... |
}
impl<EK, C, S> Runnable for Runner<EK, C, S>
where
EK: KvEngine,
C: PdClient,
S: StoreRouter<EK>,
{
type Task = Task;
fn run(&mut self, task: Task) {
match task {
Task::DeleteSST { ssts } => {
self.handle_delete_sst(ssts);
}
Task::Vali... | {
let store_id = self.store_id;
let mut invalid_ssts = Vec::new();
for sst in ssts {
match self.pd_client.get_region(sst.get_range().get_start()) {
Ok(r) => {
// The region id may or may not be the same as the
// SST file, but i... | identifier_body |
cleanup_sst.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt;
use std::sync::Arc;
use kvproto::import_sstpb::SstMeta;
use crate::store::util::is_epoch_stale;
use crate::store::{StoreMsg, StoreRouter};
use engine_traits::KvEngine;
use pd_client::PdClient;
use sst_importer::SSTImporter;
use std::mar... | let mut invalid_ssts = Vec::new();
for sst in ssts {
match self.pd_client.get_region(sst.get_range().get_start()) {
Ok(r) => {
// The region id may or may not be the same as the
// SST file, but it doesn't matter, because the
... | fn handle_validate_sst(&self, ssts: Vec<SstMeta>) {
let store_id = self.store_id; | random_line_split |
cleanup_sst.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt;
use std::sync::Arc;
use kvproto::import_sstpb::SstMeta;
use crate::store::util::is_epoch_stale;
use crate::store::{StoreMsg, StoreRouter};
use engine_traits::KvEngine;
use pd_client::PdClient;
use sst_importer::SSTImporter;
use std::mar... |
}
}
// We need to send back the result to check for the stale
// peer, which may ingest the stale SST before it is
// destroyed.
let msg = StoreMsg::ValidateSSTResult { invalid_ssts };
if let Err(e) = self.store_router.send(msg) {
error!(%e; "sen... | {
error!(%e; "get region failed");
} | conditional_block |
protocol.py | #
# Copyright 2013 Quantopian, 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 agreed to in wr... | def datetime(self):
"""
Provides an alias from data['foo'].datetime -> data['foo'].dt
`datetime` was previously provided by adding a seperate `datetime`
member of the SIDData object via a generator that wrapped the incoming
data feed and added the field to each equity event.... | if initial_values:
self.__dict__.update(initial_values)
@property | random_line_split |
protocol.py | #
# Copyright 2013 Quantopian, 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 agreed to in wr... |
else:
return name in self._data
def has_key(self, name):
"""
DEPRECATED: __contains__ is preferred, but this method is for
compatibility with existing algorithms.
"""
return name in self
def __setitem__(self, name, value):
self._data[name] =... | return False | conditional_block |
protocol.py | #
# Copyright 2013 Quantopian, 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 agreed to in wr... | (self):
return "SIDData({0})".format(self.__dict__)
def _get_buffer(self, bars, field='price'):
"""
Gets the result of history for the given number of bars and field.
This will cache the results internally.
"""
cls = self.__class__
algo = get_algo_instance()... | __repr__ | identifier_name |
protocol.py | #
# Copyright 2013 Quantopian, 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 agreed to in wr... |
class SIDData(object):
# Cache some data on the class so that this is shared for all instances of
# siddata.
# The dt where we cached the history.
_history_cache_dt = None
# _history_cache is a a dict mapping fields to pd.DataFrames. This is the
# most data we have for a given field for the ... | pos = Position(key)
self[key] = pos
return pos | identifier_body |
project.component.ts | import { Component, OnInit } from '@angular/core';
import { TaskService, ProjectService, LabelService, UserService } from '../_services/index';
import { Task, Project, Label, User, Access } from '../_models/index';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { NotificationsService } from '... | (task) {
this.taskService.delete(task)
.subscribe(
data => {
if (this.selectedTask && this.selectedTask.id == task.id) {
this.selectedTask = null;
}
this.getListOfTasks();
this._notificationsService.success(
'Task deleted',
... | deleteTask | identifier_name |
project.component.ts | import { Component, OnInit } from '@angular/core';
import { TaskService, ProjectService, LabelService, UserService } from '../_services/index';
import { Task, Project, Label, User, Access } from '../_models/index';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { NotificationsService } from '... |
else {
// If task end_date is outdated
if (this.dates.indexOf('Outdated') < 0) {
this.dates.push('Outdated');
this.tasks['Outdated'] = [];
}
this.tasks['Outdated'].push(task);
}
}
getListOfTasks(endDate = null) {
this.tasks = {};
this... | {
// If task is in the future
if (this.dates.indexOf(task.getEndDateHuman()) < 0) {
this.dates.push(task.getEndDateHuman());
this.tasks[task.getEndDateHuman()] = [];
}
this.tasks[task.getEndDateHuman()].push(task);
} | conditional_block |
project.component.ts | import { Component, OnInit } from '@angular/core';
import { TaskService, ProjectService, LabelService, UserService } from '../_services/index';
import { Task, Project, Label, User, Access } from '../_models/index';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { NotificationsService } from '... | }
)
},
error => {
this.error = JSON.parse(error._body);
}
);
}
}
deleteTask(task) {
this.taskService.delete(task)
.subscribe(
data => {
if (this.selectedTask && this.selectedTask.id == task.id) {... | random_line_split | |
project.component.ts | import { Component, OnInit } from '@angular/core';
import { TaskService, ProjectService, LabelService, UserService } from '../_services/index';
import { Task, Project, Label, User, Access } from '../_models/index';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { NotificationsService } from '... |
addTask() {
this.selectedTask = new Task();
this.selectedTask.project.id = this.project_id;
}
changeSelectedTask(task) {
this.selectedTask = new Task(JSON.parse(JSON.stringify(task)));
}
close() {
this.selectedTask = null;
}
getLabelColor(label) {
return '#... | {
this.taskService.delete(task)
.subscribe(
data => {
if (this.selectedTask && this.selectedTask.id == task.id) {
this.selectedTask = null;
}
this.getListOfTasks();
this._notificationsService.success(
'Task deleted',
'Th... | identifier_body |
core.js | //Geolocation config
Ti.Geolocation.preferredProvider = "gps";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
Titanium.Geolocation.distanceFilter = 10;
// set the granularity of the location event
//Core variables
app.core.appClosed = false;
app.core.appDestroyed = false;
app.core.uploadingEvent =... | else {
//Show notification of firts event
var newEvent = values[0];
app.core.statusbarNotification.add('New event near you', newEvent.title, 'New events');
//Update sinceId
app.core.sinceId = newEvent... | //Si hay que meterlo al final
//Adding show more events button
var showMoreButton = Ti.UI.createButton({
title : 'Show more events',
witdh : '100%',
top : 5
}), end... | conditional_block |
core.js | //Geolocation config
Ti.Geolocation.preferredProvider = "gps";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
Titanium.Geolocation.distanceFilter = 10;
// set the granularity of the location event
//Core variables
app.core.appClosed = false;
app.core.appDestroyed = false;
app.core.uploadingEvent =... | if (!e.success || e.error) {
// manage the error
alert('geolocation error');
return;
}
callback(e);
//var accuracy = e.coords.accuracy;
});
}
//Actualiza los eventos cada X tiempo definido en app.core.updateEventsInterval
//dataPosition --> Indic... | random_line_split | |
resources.rs | use serde::de::Deserialize;
use serde_json;
use std::{collections::HashMap, str};
use economy::Commodity;
use entities::Faction;
use entities::PlanetEconomy;
/// Generic Resource trait to be implemented by all resource types which should
/// be loaded at compile time.
/// KEY must be unique to the specific resource (... | {
pub names: Vec<String>,
pub scientific_names: Vec<String>,
pub greek: Vec<String>,
pub roman: Vec<String>,
pub decorators: Vec<String>,
}
impl Resource for AstronomicalNamesResource {
const KEY: &'static str = "astronomical_names";
}
#[derive(Serialize, Deserialize, Debug)]
/// Resource con... | AstronomicalNamesResource | identifier_name |
resources.rs | use serde::de::Deserialize;
use serde_json;
use std::{collections::HashMap, str};
use economy::Commodity;
use entities::Faction;
use entities::PlanetEconomy;
/// Generic Resource trait to be implemented by all resource types which should
/// be loaded at compile time.
/// KEY must be unique to the specific resource (... | /// if the type has no resource or if the deserialization fails.
pub fn fetch_resource<T: Resource>() -> Option<T> {
let res_str = RESOURCES.get(T::KEY).unwrap();
match serde_json::from_str(res_str) {
Ok(res) => Some(res),
Err(msg) => {
error!("{}", msg);
None
}
... | random_line_split | |
gen.py | #!/usr/bin/python
import json
from random import randint
INPUT = "Tweet.size1000page1cnt849.json"
OUTPUT = 'new.json'
objs = json.load(open(INPUT,'r'))
print len(objs)
# for k,v in objs[0].items():
# print "%s=\n\t%s | " % (str(k),str(v))
def | (obj):
import datetime
return obj.strftime("%Y-%m-%d %H:%M:%S") if isinstance(obj,datetime.datetime) else obj
se = []
for o in objs:
# se.append( {'x':o['created_at'],'y':randint(0,1000)} )
se.append([o['created_at'],randint(0,1000)])
di = {'name':'LA','series':se}
# print json.dumps(di)
# print type(... | date_handler | identifier_name |
gen.py | #!/usr/bin/python
import json
from random import randint
INPUT = "Tweet.size1000page1cnt849.json"
OUTPUT = 'new.json'
objs = json.load(open(INPUT,'r'))
print len(objs)
# for k,v in objs[0].items():
# print "%s=\n\t%s | " % (str(k),str(v))
def date_handler(obj):
|
se = []
for o in objs:
# se.append( {'x':o['created_at'],'y':randint(0,1000)} )
se.append([o['created_at'],randint(0,1000)])
di = {'name':'LA','series':se}
# print json.dumps(di)
# print type(di['series'][0][0])
f = open(OUTPUT,'w+')
f.write(json.dumps(di,default=date_handler))
f.close()
| import datetime
return obj.strftime("%Y-%m-%d %H:%M:%S") if isinstance(obj,datetime.datetime) else obj | identifier_body |
gen.py | #!/usr/bin/python
import json
from random import randint
INPUT = "Tweet.size1000page1cnt849.json"
OUTPUT = 'new.json'
objs = json.load(open(INPUT,'r'))
print len(objs)
# for k,v in objs[0].items():
# print "%s=\n\t%s | " % (str(k),str(v))
def date_handler(obj):
import datetime
return obj.strftime("%Y-... | # print json.dumps(di)
# print type(di['series'][0][0])
f = open(OUTPUT,'w+')
f.write(json.dumps(di,default=date_handler))
f.close() | # se.append( {'x':o['created_at'],'y':randint(0,1000)} )
se.append([o['created_at'],randint(0,1000)])
di = {'name':'LA','series':se} | random_line_split |
gen.py | #!/usr/bin/python
import json
from random import randint
INPUT = "Tweet.size1000page1cnt849.json"
OUTPUT = 'new.json'
objs = json.load(open(INPUT,'r'))
print len(objs)
# for k,v in objs[0].items():
# print "%s=\n\t%s | " % (str(k),str(v))
def date_handler(obj):
import datetime
return obj.strftime("%Y-... |
di = {'name':'LA','series':se}
# print json.dumps(di)
# print type(di['series'][0][0])
f = open(OUTPUT,'w+')
f.write(json.dumps(di,default=date_handler))
f.close()
| se.append([o['created_at'],randint(0,1000)]) | conditional_block |
node.py | # Copyright (c) 2013 Red Hat, Inc.
# Author: William Benton (willb@redhat.com)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... |
return self.cm.fetch_json_resource("/config/node/%s" % urllib.quote_plus(self.name))
def makeProvisioned(self):
self.provisioned = True
self.update()
def explain(self):
not_implemented()
def checkin(self):
metapath = "/meta/node/%s" % self.name
... | return self.cm.fetch_json_resource("/config/node/%s" % urllib.quote_plus(self.name), {"commit":options["version"]}, {}) | conditional_block |
node.py | # Copyright (c) 2013 Red Hat, Inc.
# Author: William Benton (willb@redhat.com)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... |
def makeProvisioned(self):
self.provisioned = True
self.update()
def explain(self):
not_implemented()
def checkin(self):
metapath = "/meta/node/%s" % self.name
# now = datetime.utcnow().isoformat()
now = ts()
meta = self.cm.fetch_json_r... | if options.has_key("version"):
return self.cm.fetch_json_resource("/config/node/%s" % urllib.quote_plus(self.name), {"commit":options["version"]}, {})
return self.cm.fetch_json_resource("/config/node/%s" % urllib.quote_plus(self.name)) | identifier_body |
node.py | # Copyright (c) 2013 Red Hat, Inc.
# Author: William Benton (willb@redhat.com)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | return meta.has_key("last-checkin") and meta["last-checkin"] or 0
def whatChanged(self, old, new):
oc = self.cm.fetch_json_resource("/config/node/%s" % urllib.quote_plus(self.name), {"commit":old}, {})
nc = self.cm.fetch_json_resource("/config/node/%s" % urllib.quote_plus(self.name), {"... | metapath = "/meta/node/%s" % self.name
meta = self.cm.fetch_json_resource(metapath, False, default={}) | random_line_split |
node.py | # Copyright (c) 2013 Red Hat, Inc.
# Author: William Benton (willb@redhat.com)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | (self):
memberships = self.memberships
if not PARTITION_GROUP in memberships:
return []
else:
partition = memberships.index(PARTITION_GROUP)
return memberships[partition+1:]
labels=property(getLabels)
def modifyLabels(self, op, labels, **opti... | getLabels | identifier_name |
previous.rs | use std::path::Path;
use serde::{
Deserialize,
Serialize,
};
use anyhow::Result;
use rnc_core::grouper;
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct | {
pub id: usize,
pub urs_id: usize,
pub urs_taxid: String,
upi: String,
taxid: usize,
databases: Option<String>,
description: Option<String>,
has_coordinates: Option<bool>,
is_active: Option<bool>,
last_release: Option<usize>,
rna_type: Option<String>,
short_description:... | Previous | identifier_name |
previous.rs | use std::path::Path;
use serde::{
Deserialize,
Serialize,
};
use anyhow::Result;
use rnc_core::grouper;
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct Previous {
pub id: usize,
pub urs_id: usize,
pub urs_taxid: String,
upi: String,
taxid: usize,
databases: Opti... |
}
pub fn group(path: &Path, max: usize, output: &Path) -> Result<()> {
grouper::group::<Previous>(grouper::Criteria::ZeroOrOne, &path, 1, max, &output)
}
| {
self.id
} | identifier_body |
previous.rs | use std::path::Path;
use serde::{
Deserialize,
Serialize,
};
use anyhow::Result;
use rnc_core::grouper;
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct Previous {
pub id: usize,
pub urs_id: usize,
pub urs_taxid: String,
upi: String,
taxid: usize,
databases: Opti... | }
impl grouper::HasIndex for Previous {
fn index(&self) -> usize {
self.id
}
}
pub fn group(path: &Path, max: usize, output: &Path) -> Result<()> {
grouper::group::<Previous>(grouper::Criteria::ZeroOrOne, &path, 1, max, &output)
} | last_release: Option<usize>,
rna_type: Option<String>,
short_description: Option<String>,
so_rna_type: Option<String>, | random_line_split |
tomorrow-night-bright.js | 'use strict';
module.exports = {
colors: {
black: '#000000',
red: '#D54E53',
green: '#B9CA4A',
yellow: '#E7C547',
blue: '#7AA6DA',
magenta: '#C397D8',
cyan: '#70C0B1',
white: '#EAEAEA',
lightBlack: '#969896',
lightRed: '#D54E53',
lightGreen: '#B9CA4A',
lightYellow: '#E... | }; |
// Other
tabTitleColor: 'rgba(255, 255, 255, 0.2)',
selectedTabTitleColor: '#EAEAEA', | random_line_split |
parse.py | import sys, math
from test import goertzel
import wave
import pyaudio
import Queue
import numpy as np
if len(sys.argv) < 2:
print "Usage: %s <filename> " % sys.argv[0]
sys.exit(1)
filename = sys.argv[1]
w = wave.open(filename)
fs = w.getframerate()
width = w.getsampwidth()
chunkDuration = .2 #.2 second chunks... |
#gets freq of 1 second of audio
def get_freq(arr):
lo_count = 0
hi_count = 0
mid_count = 0
for i in arr:
if i=="lo":
lo_count+=1
if i=="hi":
hi_count+=1
if i=="mid":
mid_count+=1
if mid_count > hi_count and mid_count > lo_count:
return 2
if lo_count>hi_count:
return 0
else:
return 1
... | lst = arr[-15:]
first = 0
second = 0
third = 0
for i in range(0,5):
if lst[i]=="mid":
first += 1
for i in range(5,10):
if lst[i]=="mid":
second += 1
for i in range(10,15):
if lst[i]=="mid":
third += 1
if first >= 5 and second >= 5 and third >= 5:
return True
else:
return False | identifier_body |
parse.py | import sys, math
from test import goertzel
import wave
import pyaudio
import Queue
import numpy as np
if len(sys.argv) < 2:
print "Usage: %s <filename> " % sys.argv[0]
sys.exit(1)
filename = sys.argv[1]
w = wave.open(filename)
fs = w.getframerate()
width = w.getsampwidth()
chunkDuration = .2 #.2 second chunks... | (arr):
lo_count = 0
hi_count = 0
mid_count = 0
for i in arr:
if i=="lo":
lo_count+=1
if i=="hi":
hi_count+=1
if i=="mid":
mid_count+=1
if mid_count > hi_count and mid_count > lo_count:
return 2
if lo_count>hi_count:
return 0
else:
return 1
start = False
freq_list = []
offset = 0
bits =... | get_freq | identifier_name |
parse.py | import sys, math
from test import goertzel
import wave
import pyaudio
import Queue
import numpy as np
if len(sys.argv) < 2:
print "Usage: %s <filename> " % sys.argv[0]
sys.exit(1)
filename = sys.argv[1]
w = wave.open(filename)
fs = w.getframerate()
width = w.getsampwidth()
chunkDuration = .2 #.2 second chunks... | stream = p.open(format = p.get_format_from_width(w.getsampwidth()), channels = w.getnchannels(),rate = fs, output=True)
#read .2 second chunk
data = w.readframes(chunk)
chunk_data = []
#find the frequencies of each chunk
print "Running calculations on wav file"
num = 0
while data != '':
print "Calculating Chunk " ... | random_line_split | |
parse.py | import sys, math
from test import goertzel
import wave
import pyaudio
import Queue
import numpy as np
if len(sys.argv) < 2:
print "Usage: %s <filename> " % sys.argv[0]
sys.exit(1)
filename = sys.argv[1]
w = wave.open(filename)
fs = w.getframerate()
width = w.getsampwidth()
chunkDuration = .2 #.2 second chunks... |
if mid_count > hi_count and mid_count > lo_count:
return 2
if lo_count>hi_count:
return 0
else:
return 1
start = False
freq_list = []
offset = 0
bits = []
for i in range(5,len(chunk_data)):
a = chunk_data[i][0]
b = chunk_data[i][1]
hi_amp = []
lo_amp = []
mid_amp = []
#get averages for each freq
... | mid_count+=1 | conditional_block |
1Prelude.js | // Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of condit... | // contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANT... | // notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its | random_line_split |
1Prelude.js | // Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of condit... | function initializeModules() {
// load module load new instance of the given module every time
// this is a responsibility of prelude to manage instances of modules
var modules = _load_module('Modules');
// TODO: replace with createRequire($load_module)
modules.$load_module = _load_module;
ret... | _log("PROJECTIONS (JS): " + message);
}
| identifier_body |
1Prelude.js | // Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of condit... | yHandler) {
eventProcessor.partitionBy(byHandler);
return {
when: when,
};
}
function fromCategory(category) {
eventProcessor.fromCategory(category);
return {
partitionBy: partitionBy,
foreachStream: foreachStream,
when: wh... | rtitionBy(b | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of ... | {
PageError(PageError),
ConsoleAPI(ConsoleAPI),
}
#[derive(Debug, PartialEq)]
pub struct HttpRequest {
pub url: Url,
pub method: Method,
pub headers: Headers,
pub body: Option<Vec<u8>>,
pub pipeline_id: PipelineId,
pub startedDateTime: Tm
}
#[derive(Debug, PartialEq)]
pub struct HttpR... | CachedConsoleMessage | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of ... | extern crate ipc_channel;
extern crate msg;
extern crate serde;
extern crate time;
extern crate url;
extern crate util;
use hyper::header::Headers;
use hyper::http::RawStatus;
use hyper::method::Method;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use std::net::TcpStream;
use time::Duration... | #[macro_use]
extern crate bitflags;
extern crate heapsize;
extern crate hyper; | random_line_split |
lib.es2015.symbol.d.ts | /*! *****************************************************************************
Copyright (c) Microsoft Corporation. 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:/... | /** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): Object;
}
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Symbol;
/**
... | and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Symbol {
| random_line_split |
dev-server.js | var path = require('path')
var fs = require('fs')
var argv = require('optimist').argv;
var express = require('express')
var webpack = require('webpack')
var config = require('../config')
var opn = require('opn')
var proxyMiddleware = require('http-proxy-middleware')
var webpackConfig = process.env.NODE_ENV === 'testing... |
});
})(mockDir);;
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')({
index: '/index.html'
}))
// serve webpack bundle output
app.use(devMiddleware)
// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)
// serve pure static assets
v... | {
mock = require(filePath);
app.use(mock.api, argv.proxy ? proxyMiddleware({target: 'http://' + argv.proxy}) : mock.response);
} | conditional_block |
dev-server.js | var path = require('path')
var fs = require('fs')
var argv = require('optimist').argv;
var express = require('express')
var webpack = require('webpack')
var config = require('../config')
var opn = require('opn')
var proxyMiddleware = require('http-proxy-middleware')
var webpackConfig = process.env.NODE_ENV === 'testing... | // force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
// proxy api requests
// Object.keys(proxyTable).forEach(f... | chunks: false
}
})
var hotMiddleware = require('webpack-hot-middleware')(compiler) | random_line_split |
sha1Hash_test.py | #!/usr/bin/env python
""" sha1Hash_test.py
Unit tests for sha1.py
"""
from crypto.hash.sha1Hash import SHA1
import unittest
import struct
assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes'
class SHA1_FIPS180_TestCases(unittest.TestCase):
""" SHA-1 tests from FIPS180-1 Appendix A, B and ... | unittest.main() | conditional_block | |
sha1Hash_test.py | #!/usr/bin/env python
""" sha1Hash_test.py
Unit tests for sha1.py
"""
from crypto.hash.sha1Hash import SHA1
import unittest
import struct
assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes'
class SHA1_FIPS180_TestCases(unittest.TestCase):
""" SHA-1 tests from FIPS180-1 Appendix A, B and ... |
def testFIPS180_1_Appendix_C(self):
""" APPENDIX C. A THIRD SAMPLE MESSAGE AND ITS MESSAGE DIGEST
Let the message be the binary-coded form of the ASCII string which consists
of 1,000,000 repetitions of "a". """
hashAlg = SHA1()
message = 1000000*'a'
message... | """ APPENDIX B. A SECOND SAMPLE MESSAGE AND ITS MESSAGE DIGEST """
hashAlg = SHA1()
message = 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'
message_digest = 0x84983E44L, 0x1C3BD26EL, 0xBAAE4AA1L, 0xF95129E5L, 0xE54670F1L
md_string = _toBString(message_digest)
... | identifier_body |
sha1Hash_test.py | #!/usr/bin/env python
""" sha1Hash_test.py
Unit tests for sha1.py
"""
from crypto.hash.sha1Hash import SHA1
import unittest
import struct
assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes'
class SHA1_FIPS180_TestCases(unittest.TestCase):
""" SHA-1 tests from FIPS180-1 Appendix A, B and ... | (self):
""" APPENDIX B. A SECOND SAMPLE MESSAGE AND ITS MESSAGE DIGEST """
hashAlg = SHA1()
message = 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'
message_digest = 0x84983E44L, 0x1C3BD26EL, 0xBAAE4AA1L, 0xF95129E5L, 0xE54670F1L
md_string = _toBString(mes... | testFIPS180_1_Appendix_B | identifier_name |
sha1Hash_test.py | #!/usr/bin/env python
""" sha1Hash_test.py
Unit tests for sha1.py
"""
from crypto.hash.sha1Hash import SHA1
import unittest
import struct
assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes'
class SHA1_FIPS180_TestCases(unittest.TestCase):
""" SHA-1 tests from FIPS180-1 Appendix A, B and ... | # Run the tests from the command line
unittest.main() | random_line_split | |
adaboost.py | #!/usr/bin/python2 |
from util import get_split_training_dataset
from metrics import suite
import feature_selection_trees as fclassify
from sklearn.grid_search import GridSearchCV
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
def train(Xtrain, Ytrain):
""" Use entirety of provided X... |
# This is an Adaboost classifier
import sys | random_line_split |
adaboost.py | #!/usr/bin/python2
# This is an Adaboost classifier
import sys
from util import get_split_training_dataset
from metrics import suite
import feature_selection_trees as fclassify
from sklearn.grid_search import GridSearchCV
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifi... |
if __name__ == "__main__":
# Let's take our training data and train a decision tree
# on a subset. Scikit-learn provides a good module for cross-
# validation.
Xt, Xv, Yt, Yv = get_split_training_dataset()
Classifier = train(Xt, Yt)
print "Adaboost Classifier"
suite(Yv, Classifier.predict(... | """ Use entirety of provided X, Y to predict
Default Arguments
Xtrain -- Training data
Ytrain -- Training prediction
Named Arguments
C -- regularization parameter
Returns
classifier -- a tree fitted to Xtrain and Ytrain
"""
# Initialize classifier parameters for adaboost
# For... | identifier_body |
adaboost.py | #!/usr/bin/python2
# This is an Adaboost classifier
import sys
from util import get_split_training_dataset
from metrics import suite
import feature_selection_trees as fclassify
from sklearn.grid_search import GridSearchCV
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifi... | (Xtrain, Ytrain):
""" Use entirety of provided X, Y to predict
Default Arguments
Xtrain -- Training data
Ytrain -- Training prediction
Named Arguments
C -- regularization parameter
Returns
classifier -- a tree fitted to Xtrain and Ytrain
"""
# Initialize classifier parameters ... | train | identifier_name |
adaboost.py | #!/usr/bin/python2
# This is an Adaboost classifier
import sys
from util import get_split_training_dataset
from metrics import suite
import feature_selection_trees as fclassify
from sklearn.grid_search import GridSearchCV
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifi... | Xt, Xv, Yt, Yv = get_split_training_dataset()
Classifier = train(Xt, Yt)
print "Adaboost Classifier"
suite(Yv, Classifier.predict(Xv))
# smaller feature set
Xtimp, features = fclassify.get_important_data_features(Xt, Yt, max_features=25)
Xvimp = fclassify.compress_data_to_important_features(Xv,... | conditional_block | |
setup.py | '''
pyttsx setup script.
Copyright (c) 2009, 2013 Peter Parente
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHO... | packages=['pyttsx', 'pyttsx.drivers']
) | random_line_split | |
two-weakrefs.js | // Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --harmony-weak-refs --expose-gc --noincremental-marking --allow-natives-syntax
let o1 = {};
let o2 = {};
let wr1;
let wr2;
(function() {
wr... |
gc();
%PerformMicrotaskCheckpoint();
// New turn.
assertEquals(undefined, wr2.deref()); | %PerformMicrotaskCheckpoint();
// New turn.
assertEquals(undefined, wr1.deref()); | random_line_split |
fields.py | import os
from .provider_manager import ProviderManager
from .resolvers import resolver_registry
field_registry = {}
def register_field(name):
"""add resolver class to registry"""
def add_class(clazz):
field_registry[name] = clazz
return clazz
return add_class
class Field:
def __in... |
field_type = context["lookup"]
return field_registry[field_type](key, context["prop"])
@register_field("literal")
class LiteralField(Field):
def __init__(self, key, props):
super().__init__(key, props)
@property
def value(self):
return self.props["value"]
@regi... | context = {
"lookup": "literal",
"prop": {
"value": context
}
} | conditional_block |
fields.py | import os
from .provider_manager import ProviderManager
from .resolvers import resolver_registry
field_registry = {}
def | (name):
"""add resolver class to registry"""
def add_class(clazz):
field_registry[name] = clazz
return clazz
return add_class
class Field:
def __init__(self, key, props):
self.key = key
self.props = props
@staticmethod
def create(key, context):
# no... | register_field | identifier_name |
fields.py | import os
from .provider_manager import ProviderManager
from .resolvers import resolver_registry
field_registry = {}
def register_field(name):
"""add resolver class to registry"""
def add_class(clazz):
field_registry[name] = clazz
return clazz
return add_class
class Field:
def __in... |
@register_field("environment")
class EnvironmentField(Field):
def __init__(self, key, props):
super().__init__(key, props)
@property
def value(self):
return os.environ[self.props["variable"]]
@register_field("secretsmanager")
class SecretsManagerField(Field):
def __... | return self.props["value"] | identifier_body |
fields.py | import os
from .provider_manager import ProviderManager
from .resolvers import resolver_registry
field_registry = {}
def register_field(name): | def add_class(clazz):
field_registry[name] = clazz
return clazz
return add_class
class Field:
def __init__(self, key, props):
self.key = key
self.props = props
@staticmethod
def create(key, context):
# normalize
if isinstance(context, str):
... | """add resolver class to registry""" | random_line_split |
entry_point.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {AbsoluteFsPath} from '../../../src/ngtsc/path';
import {FileSystem} from '.... | return sourceFile.statements.length > 0 &&
parseStatementForUmdModule(sourceFile.statements[0]) !== null;
} | const sourceFile =
ts.createSourceFile(sourceFilePath, fs.readFile(sourceFilePath), ts.ScriptTarget.ES5); | random_line_split |
entry_point.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {AbsoluteFsPath} from '../../../src/ngtsc/path';
import {FileSystem} from '.... | {
const sourceFile =
ts.createSourceFile(sourceFilePath, fs.readFile(sourceFilePath), ts.ScriptTarget.ES5);
return sourceFile.statements.length > 0 &&
parseStatementForUmdModule(sourceFile.statements[0]) !== null;
} | identifier_body | |
entry_point.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {AbsoluteFsPath} from '../../../src/ngtsc/path';
import {FileSystem} from '.... | (
fs: FileSystem, logger: Logger, packageJsonPath: AbsoluteFsPath): EntryPointPackageJson|null {
try {
return JSON.parse(fs.readFile(packageJsonPath));
} catch (e) {
// We may have run into a package.json with unexpected symbols
logger.warn(`Failed to read entry point info from ${packageJsonPath} wi... | loadEntryPointPackage | identifier_name |
job.py | __author__ = 'Christof Pieloth'
import logging
from packbacker.errors import ParameterError
from packbacker.installers import installer_prototypes
from packbacker.utils import UtilsUI
class Job(object):
log = logging.getLogger(__name__)
def __init__(self):
self._installers = []
def add_instal... |
return job
@staticmethod
def read_parameter(line):
params = {}
i = line.find(': ') + 2
line = line[i:]
pairs = line.split(';')
for pair in pairs:
pair = pair.strip()
par = pair.split('=')
if len(par) == 2:
par... | if line[0] == '#':
continue
for p in prototypes:
if p.matches(line):
try:
params = Job.read_parameter(line)
cmd = p.instance(params)
... | conditional_block |
job.py | __author__ = 'Christof Pieloth'
import logging
from packbacker.errors import ParameterError
from packbacker.installers import installer_prototypes
from packbacker.utils import UtilsUI
class Job(object):
log = logging.getLogger(__name__)
def __init__(self):
self._installers = [] | errors = 0
for i in self._installers:
if not UtilsUI.ask_for_execute('Install ' + i.label):
continue
try:
if i.install():
Job.log.info(i.name + ' executed.')
else:
errors += 1
... |
def add_installer(self, installer):
self._installers.append(installer)
def execute(self): | random_line_split |
job.py | __author__ = 'Christof Pieloth'
import logging
from packbacker.errors import ParameterError
from packbacker.installers import installer_prototypes
from packbacker.utils import UtilsUI
class Job(object):
log = logging.getLogger(__name__)
def __init__(self):
self._installers = []
def add_instal... | (line):
params = {}
i = line.find(': ') + 2
line = line[i:]
pairs = line.split(';')
for pair in pairs:
pair = pair.strip()
par = pair.split('=')
if len(par) == 2:
params[par[0]] = par[1]
return params | read_parameter | identifier_name |
job.py | __author__ = 'Christof Pieloth'
import logging
from packbacker.errors import ParameterError
from packbacker.installers import installer_prototypes
from packbacker.utils import UtilsUI
class Job(object):
log = logging.getLogger(__name__)
def __init__(self):
self._installers = []
def add_instal... | params = {}
i = line.find(': ') + 2
line = line[i:]
pairs = line.split(';')
for pair in pairs:
pair = pair.strip()
par = pair.split('=')
if len(par) == 2:
params[par[0]] = par[1]
return params | identifier_body | |
zero.rs | #![feature(core, zero_one)]
extern crate core;
#[cfg(test)]
mod tests {
use core::num::Zero;
// pub trait Zero {
// /// The "zero" (usually, additive identity) for this type.
// fn zero() -> Self;
// }
// pub trait One {
// /// The "one" (usually, multiplicative identity) for ... | () {
let value: T = T::zero();
assert_eq!(value, 0x0000000000000000);
}
}
| zero_test1 | identifier_name |
zero.rs | #![feature(core, zero_one)]
extern crate core;
#[cfg(test)]
mod tests {
use core::num::Zero;
// pub trait Zero {
// /// The "zero" (usually, additive identity) for this type.
// fn zero() -> Self;
// }
// pub trait One {
// /// The "one" (usually, multiplicative identity) for ... | // impl One for $t {
// #[inline]
// fn one() -> Self { 1 }
// }
// )*)
// }
// zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
// macro_rules! zero_one_impl_float {
// ($($t:ty)*) => ($(
// impl Zero for $t {
... | // } | random_line_split |
zero.rs | #![feature(core, zero_one)]
extern crate core;
#[cfg(test)]
mod tests {
use core::num::Zero;
// pub trait Zero {
// /// The "zero" (usually, additive identity) for this type.
// fn zero() -> Self;
// }
// pub trait One {
// /// The "one" (usually, multiplicative identity) for ... |
}
| {
let value: T = T::zero();
assert_eq!(value, 0x0000000000000000);
} | identifier_body |
nzbToGamez.py | #!/usr/bin/env python2
#
##############################################################################
### NZBGET POST-PROCESSING SCRIPT ###
# Post-Process to CouchPotato, SickBeard, NzbDrone, Mylar, Gamez, HeadPhones.
#
# This script sends the download to your automated media... |
# Gamez host.
#
# The ipaddress for your Gamez server. e.g For the Same system use localhost or 127.0.0.1
#gzhost=localhost
# Gamez port.
#gzport=8085
# Gamez uses ssl (0, 1).
#
# Set to 1 if using ssl, else set to 0.
#gzssl=0
# Gamez library
#
# move downloaded games here.
#gzlibrary
# Gamez web_root
#
# set this... | # category that gets called for post-processing with Gamez.
#gzCategory=games
# Gamez api key.
#gzapikey= | random_line_split |
selectionRendererFactory.ts |
module awk.grid {
export class SelectionRendererFactory {
angularGrid: any;
selectionController: any;
init(angularGrid: any, selectionController: any) {
this.angularGrid = angularGrid;
this.selectionController = selectionController;
}
createCheckb... | else {
// isNodeSelected returns back undefined if it's a group and the children
// are a mix of selected and unselected
eCheckbox.indeterminate = true;
}
}
}
| {
eCheckbox.checked = state;
eCheckbox.indeterminate = false;
} | conditional_block |
selectionRendererFactory.ts | module awk.grid {
export class SelectionRendererFactory {
angularGrid: any;
selectionController: any;
init(angularGrid: any, selectionController: any) {
this.angularGrid = angularGrid;
this.selectionController = selectionController;
}
createCheckbo... | }
} | } else {
// isNodeSelected returns back undefined if it's a group and the children
// are a mix of selected and unselected
eCheckbox.indeterminate = true;
} | random_line_split |
selectionRendererFactory.ts |
module awk.grid {
export class SelectionRendererFactory {
angularGrid: any;
selectionController: any;
| (angularGrid: any, selectionController: any) {
this.angularGrid = angularGrid;
this.selectionController = selectionController;
}
createCheckboxColDef() {
return {
width: 30,
suppressMenu: true,
suppressSorting: true,
... | init | identifier_name |
selectionRendererFactory.ts |
module awk.grid {
export class SelectionRendererFactory {
angularGrid: any;
selectionController: any;
init(angularGrid: any, selectionController: any) {
this.angularGrid = angularGrid;
this.selectionController = selectionController;
}
createCheckb... |
}
| {
if (typeof state === 'boolean') {
eCheckbox.checked = state;
eCheckbox.indeterminate = false;
} else {
// isNodeSelected returns back undefined if it's a group and the children
// are a mix of selected and unselected
eCheckbox.indeterminate =... | identifier_body |
sock_serv.py | # -*- coding: utf-8 -*-
"""
Simple sockjs-tornado chat application. By default will listen on port 8080.
"""
import sys
import os
import json
from urllib import urlencode
import tornado.ioloop
import tornado.web
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
import sockjs.tornado
sys.path.... | def on_open(self, info):
self.joined_session = []
@gen.coroutine
def on_message(self, message):
recv_data = json.loads(message)
if recv_data['type']=='session_join':
session_name = recv_data['data']
if self.session_blocks.get(session_name, False) == False:
... | session_blocks = dict()
session_code_storage = dict()
http_client = AsyncHTTPClient()
| random_line_split |
sock_serv.py | # -*- coding: utf-8 -*-
"""
Simple sockjs-tornado chat application. By default will listen on port 8080.
"""
import sys
import os
import json
from urllib import urlencode
import tornado.ioloop
import tornado.web
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
import sockjs.tornado
sys.path.... | (self, message):
recv_data = json.loads(message)
if recv_data['type']=='session_join':
session_name = recv_data['data']
if self.session_blocks.get(session_name, False) == False:
self.session_blocks[session_name] = set()
session_id = self.session.conn_... | on_message | identifier_name |
sock_serv.py | # -*- coding: utf-8 -*-
"""
Simple sockjs-tornado chat application. By default will listen on port 8080.
"""
import sys
import os
import json
from urllib import urlencode
import tornado.ioloop
import tornado.web
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
import sockjs.tornado
sys.path.... |
chat_data['message'] = recv_data['data']
send_data['data'] = json.dumps(chat_data)
self.broadcast(self.session_blocks[session_name], json.dumps(send_data))
elif recv_data['type']=='run_code':
session_name = recv_data['session']
code = recv_data['data'... | chat_data['avatar_url'] = self.dj_user['avatar_url'] | conditional_block |
sock_serv.py | # -*- coding: utf-8 -*-
"""
Simple sockjs-tornado chat application. By default will listen on port 8080.
"""
import sys
import os
import json
from urllib import urlencode
import tornado.ioloop
import tornado.web
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
import sockjs.tornado
sys.path.... |
def on_close(self):
for session in self.joined_session:
self.session_blocks[session].remove(self)
self.session_list_update(session)
def session_list_update(self, session_name):
session_list = []
for session in self.session_blocks[session_name]:
... | recv_data = json.loads(message)
if recv_data['type']=='session_join':
session_name = recv_data['data']
if self.session_blocks.get(session_name, False) == False:
self.session_blocks[session_name] = set()
session_id = self.session.conn_info.cookies['sessionid']... | identifier_body |
canteenie_v1.py | #!/usr/bin/env python3
"""canteenie.py: A small python script that prints today's canteen/mensa menu for FAU on console."""
import requests
import datetime
import argparse
from lxml import html
from colorama import Fore, Style
import textwrap
import xmascc
# command line arguments
parser = argparse.ArgumentParser(de... | al_string):
prefix = "\t\t"
preferredWidth = 105
wrapper = textwrap.TextWrapper(subsequent_indent=prefix, width=preferredWidth)
print(wrapper.fill(meal_string))
return
# print normal meals
i = 1
while i < meal_count +1:
if "Essen %d" %i in menu_str: # check for missing menu
slice_amount = -8
if "- €" in menu... | p(me | identifier_name |
canteenie_v1.py | #!/usr/bin/env python3
"""canteenie.py: A small python script that prints today's canteen/mensa menu for FAU on console."""
import requests
import datetime
import argparse
from lxml import html
from colorama import Fore, Style
import textwrap
import xmascc
# command line arguments
parser = argparse.ArgumentParser(de... | # join to string and tidy up the text
menu_str = ' '.join(menu) # join list to one string
menu_str = menu_str.replace('\xa0', ' ') # remove no break space
menu_str = menu_str.replace('\n', ' ') # remove line feed
menu_str = menu_str.replace('\r', ' ') # remove carriage return
menu_str = " ".join(menu_str.split()) # rem... | page = requests.get('http://www.werkswelt.de/?id=%s' %args['mensa'])
tree = html.fromstring(page.content)
menu = tree.xpath('/html/body/div[3]/div/div[2]/div[2]/text()')
| random_line_split |
canteenie_v1.py | #!/usr/bin/env python3
"""canteenie.py: A small python script that prints today's canteen/mensa menu for FAU on console."""
import requests
import datetime
import argparse
from lxml import html
from colorama import Fore, Style
import textwrap
import xmascc
# command line arguments
parser = argparse.ArgumentParser(de... | ot args['lite']: print(Style.RESET_ALL + '', end="")
i += 1
else:
meal_count += 1
i += 1
# print special meals
if meal_special_count != 0:
print("")
i = 1
while i < meal_special_count + 1:
if "Aktionsessen %d" %i in menu_str: # check for missing menu
slice_amount = -8
if "- €" in menu_str.split("Akti... | eal_string)
if n | conditional_block |
canteenie_v1.py | #!/usr/bin/env python3
"""canteenie.py: A small python script that prints today's canteen/mensa menu for FAU on console."""
import requests
import datetime
import argparse
from lxml import html
from colorama import Fore, Style
import textwrap
import xmascc
# command line arguments
parser = argparse.ArgumentParser(de... | print normal meals
i = 1
while i < meal_count +1:
if "Essen %d" %i in menu_str: # check for missing menu
slice_amount = -8
if "- €" in menu_str.split("Essen %d" %i,1)[1].split("(Gäste)",1)[0][:-8]: # check for missing price
slice_amount = -5
if not args['lite']: print(Fore.CYAN + '', end="")
if not args[... | fix = "\t\t"
preferredWidth = 105
wrapper = textwrap.TextWrapper(subsequent_indent=prefix, width=preferredWidth)
print(wrapper.fill(meal_string))
return
# | identifier_body |
group-responses.service.ts | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class | {
constructor(
private httpClient:HttpClient
) { }
async list(groupId:string) {
return <Array<any>>await this.httpClient.get(`/group-responses/list/${groupId}`).toPromise()
}
async query(groupId:string, query:any) {
return <Array<any>>await this.httpClient.post(`/group-responses/query/${groupI... | GroupResponsesService | identifier_name |
group-responses.service.ts | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class GroupResponsesService {
constructor(
private httpClient:HttpClient
) { }
async list(groupId:string) {
return <Array<any>>await this.httpClient.get(`/group-re... | }
async updateResponse(groupId, device) {
return <any>await this.httpClient.post(`/group-responses/update/${groupId}`, {device}).toPromise()
}
async deleteResponse(groupId:string, deviceId:string) {
return <any>await this.httpClient.get(`/group-responses/delete/${groupId}/${deviceId}`).toPromise()
}... | }
async getResponse(groupId:string, deviceId:string) {
return <any>await this.httpClient.get(`/group-responses/read/${groupId}/${deviceId}`).toPromise() | random_line_split |
meta.rs | // Copyright (C) 2015 Steven Allen
//
// This file is part of gazetta.
//
// 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 version 3 of the
// License.
//
// This program is distributed in t... |
}
pub struct EntryMeta {
pub author: Option<Person>,
pub about: Option<Person>,
}
impl Meta for EntryMeta {
fn from_yaml(mut meta: Hash) -> Result<EntryMeta, &'static str> {
Ok(EntryMeta {
author: meta
.remove(&AUTHOR)
.map(Person::from_yaml)
... | {
Ok(SourceMeta {
nav: meta
.remove(&NAV)
.map(Link::many_from_yaml)
.bubble_result()?
.unwrap_or_else(Vec::new),
author: meta
.remove(&AUTHOR)
.map(Person::from_yaml)
.bubble_... | identifier_body |
meta.rs | // Copyright (C) 2015 Steven Allen
//
// This file is part of gazetta.
//
// 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 version 3 of the
// License.
//
// This program is distributed in t... | .remove(&AUTHOR)
.map(Person::from_yaml)
.bubble_result()?
.ok_or("websites must have authors")?,
})
}
}
pub struct EntryMeta {
pub author: Option<Person>,
pub about: Option<Person>,
}
impl Meta for EntryMeta {
fn from_yaml(mut me... | random_line_split | |
meta.rs | // Copyright (C) 2015 Steven Allen
//
// This file is part of gazetta.
//
// 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 version 3 of the
// License.
//
// This program is distributed in t... | {
pub author: Option<Person>,
pub about: Option<Person>,
}
impl Meta for EntryMeta {
fn from_yaml(mut meta: Hash) -> Result<EntryMeta, &'static str> {
Ok(EntryMeta {
author: meta
.remove(&AUTHOR)
.map(Person::from_yaml)
.bubble_result()?,... | EntryMeta | identifier_name |
anitoonstv.py | # -*- coding: utf-8 -*-
import re
from channels import renumbertools
from channelselector import get_thumb
from core import httptools
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
from channels import autoplay
IDIO... | tem):
logger.info()
thumb_series = get_thumb("channels_tvshow.png")
autoplay.init(item.channel, list_servers, list_quality)
itemlist = list()
itemlist.append(Item(channel=item.channel, action="lista", title="Anime", url=host,
thumbnail=thumb_series))
itemlist.append(It... | inlist(i | identifier_name |
anitoonstv.py | # -*- coding: utf-8 -*-
import re
from channels import renumbertools
from channelselector import get_thumb
from core import httptools
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
from channels import autoplay
IDIO... | itemlist.append(item.clone(url=url, action="play", server=server, contentQuality=quality,
thumbnail=scrapedthumbnail, plot=scrapedplot,
title="Enlace encontrado en %s: [%s]" % (server.capitalize(), quality)))
autoplay.start(itemlist, item)... | lity = quality.replace("Calidad Alta", "HQ")
server = server.lower().strip()
if "ok" == server:
server = 'okru'
if "netu" == server:
continue
| conditional_block |
anitoonstv.py | # -*- coding: utf-8 -*-
import re
from channels import renumbertools
from channelselector import get_thumb
from core import httptools
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
from channels import autoplay
IDIO... | # ...sino lo encontramos buscamos en todos los servidores disponibles
devuelve = servertools.findvideos(item.url, skip=True)
if devuelve:
# logger.debug(devuelve)
itemlist.append(Item(channel=item.channel, title=item.contentTitle, action="play", server=devuelve[0][2],
... | # Buscamos video por servidor ...
devuelve = servertools.findvideosbyserver(item.url, item.server)
if not devuelve: | random_line_split |
anitoonstv.py | # -*- coding: utf-8 -*-
import re
from channels import renumbertools
from channelselector import get_thumb
from core import httptools
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
from channels import autoplay
IDIO... | ger.info()
itemlist = []
# Buscamos video por servidor ...
devuelve = servertools.findvideosbyserver(item.url, item.server)
if not devuelve:
# ...sino lo encontramos buscamos en todos los servidores disponibles
devuelve = servertools.findvideos(item.url, skip=True)
if devuelve:
... | identifier_body | |
autotools_test.py | import os
from conan.tools.files.files import save_toolchain_args
from conan.tools.gnu import Autotools
from conans.test.utils.mocks import ConanFileMock
from conans.test.utils.test_files import temp_folder
def | ():
folder = temp_folder()
os.chdir(folder)
save_toolchain_args({
"configure_args": "-foo bar",
"make_args": ""}
)
conanfile = ConanFileMock()
conanfile.folders.set_base_install(folder)
sources = "/path/to/sources"
conanfile.folders.set_base_source(sources)
autotools ... | test_source_folder_works | identifier_name |
autotools_test.py | import os
from conan.tools.files.files import save_toolchain_args
from conan.tools.gnu import Autotools
from conans.test.utils.mocks import ConanFileMock
from conans.test.utils.test_files import temp_folder
def test_source_folder_works():
| folder = temp_folder()
os.chdir(folder)
save_toolchain_args({
"configure_args": "-foo bar",
"make_args": ""}
)
conanfile = ConanFileMock()
conanfile.folders.set_base_install(folder)
sources = "/path/to/sources"
conanfile.folders.set_base_source(sources)
autotools = Autoto... | identifier_body | |
autotools_test.py | import os
from conan.tools.files.files import save_toolchain_args
from conan.tools.gnu import Autotools
from conans.test.utils.mocks import ConanFileMock
from conans.test.utils.test_files import temp_folder
def test_source_folder_works():
folder = temp_folder()
os.chdir(folder)
save_toolchain_args({ | sources = "/path/to/sources"
conanfile.folders.set_base_source(sources)
autotools = Autotools(conanfile)
autotools.configure(build_script_folder="subfolder")
assert conanfile.command.replace("\\", "/") == '"/path/to/sources/subfolder/configure" -foo bar'
autotools.configure()
assert conanfi... | "configure_args": "-foo bar",
"make_args": ""}
)
conanfile = ConanFileMock()
conanfile.folders.set_base_install(folder) | random_line_split |
test_mlbam_util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase, main
from pitchpx.mlbam_util import MlbamUtil, MlbAmHttpNotFound
__author__ = 'Shinichi Nakagawa'
class TestMlbamUtil(TestCase):
"""
MLBAM Util Class Test
"""
def setUp(self):
pass
def tearDown(self):
p... | (self):
"""
Get html content(status:404, head:original)
"""
req = MlbamUtil._get_content(
'http://gd2.mlb.com/components/game/mlb/year_2016/month_04/day_06/gid_2016_04_06_chnmlb_anamlb_1/game.xml',
headers={'Accept': 'text/html', 'User-Agent': 'Python-urllib/3.5'}... | test_get_content_404_setting_header | identifier_name |
test_mlbam_util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase, main
from pitchpx.mlbam_util import MlbamUtil, MlbAmHttpNotFound
__author__ = 'Shinichi Nakagawa'
class TestMlbamUtil(TestCase):
"""
MLBAM Util Class Test
"""
def setUp(self):
pass
def tearDown(self):
p... | """
Get html content(status:404, head:original)
"""
req = MlbamUtil._get_content(
'http://gd2.mlb.com/components/game/mlb/year_2016/month_04/day_06/gid_2016_04_06_chnmlb_anamlb_1/game.xml',
headers={'Accept': 'text/html', 'User-Agent': 'Python-urllib/3.5'}
... | self.assertEqual(req.status_code, 200)
self.assertEqual(req.request.headers['Accept'], 'text/html')
self.assertEqual(req.request.headers['User-Agent'], 'Python-urllib/3.5')
def test_get_content_404_setting_header(self): | random_line_split |
test_mlbam_util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase, main
from pitchpx.mlbam_util import MlbamUtil, MlbAmHttpNotFound
__author__ = 'Shinichi Nakagawa'
class TestMlbamUtil(TestCase):
|
if __name__ == '__main__':
main() | """
MLBAM Util Class Test
"""
def setUp(self):
pass
def tearDown(self):
pass
def test_get_content_200(self):
"""
Get html content(status:200, head:default)
"""
req = MlbamUtil._get_content(
'http://gd2.mlb.com/components/game/mlb/year_20... | identifier_body |
test_mlbam_util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase, main
from pitchpx.mlbam_util import MlbamUtil, MlbAmHttpNotFound
__author__ = 'Shinichi Nakagawa'
class TestMlbamUtil(TestCase):
"""
MLBAM Util Class Test
"""
def setUp(self):
pass
def tearDown(self):
p... | main() | conditional_block | |
test-pvservice.js | var PvService = require('../service/PvService');
var path = require('path');
var StatisticsServicePV = require('../service/StatisticsService_PV');
GLOBAL.pjconfig = {
"mysql": {
"url": "mysql://badjs:pass4badjs@10.198.30.62:4250/badjs"
}, | "queryCountUrl": "http://10.185.14.28:9000/queryCount",
"querySvgUrl": "http://10.185.14.28:9000/errorCountSvg"
},
"acceptor": {
"pushProjectUrl": "http://10.185.14.28:9001/getProjects"
},
"zmq": {
"url": "tcp://10.185.14.28:10000",
"subscribe": "badjs"
},
... | "storage": {
"errorMsgTopUrl": "http://10.185.14.28:9000/errorMsgTop",
"errorMsgTopCacheUrl": "http://10.185.14.28:9000/errorMsgTopCache",
"queryUrl": "http://10.185.14.28:9000/query", | random_line_split |
CorsCheck.js | import React, {useState, useEffect} from 'react'
import {Text, Container, Flex, Spinner, Stack} from '@sanity/ui'
import {versionedClient} from './versionedClient'
const checkCors = () =>
Promise.all([
versionedClient.request({uri: '/ping', withCredentials: false}).then(() => true),
versionedClient
.re... | ({result, children}) {
const response = result && result.error && result.error.response
const message = response && response.body && response.body.message
if (!message) {
return <>{children}</>
}
return (
<div>
<Text>Error message:</Text>
<pre>
<code>{response.body.message}</code>... | CorsWrapper | identifier_name |
CorsCheck.js | import React, {useState, useEffect} from 'react'
import {Text, Container, Flex, Spinner, Stack} from '@sanity/ui'
import {versionedClient} from './versionedClient'
const checkCors = () =>
Promise.all([
versionedClient.request({uri: '/ping', withCredentials: false}).then(() => true),
versionedClient
.re... |
return (
<div>
<Text>Error message:</Text>
<pre>
<code>{response.body.message}</code>
</pre>
{children}
</div>
)
}
export default function CorsCheck() {
const [state, setState] = useState({isLoading: true})
useEffect(() => {
checkCors().then((res) =>
setStat... | {
return <>{children}</>
} | conditional_block |
CorsCheck.js | import React, {useState, useEffect} from 'react'
import {Text, Container, Flex, Spinner, Stack} from '@sanity/ui'
import {versionedClient} from './versionedClient'
const checkCors = () =>
Promise.all([
versionedClient.request({uri: '/ping', withCredentials: false}).then(() => true),
versionedClient
.re... | )
}
const tld = versionedClient.config().apiHost.replace(/.*?sanity\.([a-z]+).*/, '$1')
const projectId = versionedClient.config().projectId
const corsUrl = `https://manage.sanity.${tld}/projects/${projectId}/settings/api`
const response = result.error && result.error.response
if (response) {
cons... | </Container> | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.