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
padtwitch.py
from __future__ import print_function import asyncio from copy import deepcopy from datetime import datetime import errno import os import re import socket import threading import time from dateutil import tz import discord from discord.ext import commands from __main__ import user_allowed, send_cmd_...
@commands.group(pass_context=True) @checks.is_owner() async def padtwitch(self, ctx): """Manage twitter feed mirroring""" if ctx.invoked_subcommand is None: await send_cmd_help(ctx) @padtwitch.command(pass_context=True) async def setUserName(self, ctx, user_n...
cmd_name = query.strip() self.settings.rmCustomCommand(channel, cmd_name) self.stream.send_chat_message(channel, 'Done deleting ' + cmd_name)
identifier_body
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
rf.currentTerm = currentTerm rf.votedFor = votedFor rf.log = log } // // example RequestVote RPC arguments structure. // field names must start with capital letters! // type RequestVoteArgs struct { // Your data here (2A, 2B). Term int CandidateID int LastLogIndex int LastLogTerm int } // // exampl...
{ fmt.Fprintf(os.Stderr, "Peer #%d failed to decode state from persister, retrying...\n", rf.me) count++ if count > 5 { panic("Peer #%d failed to decode state from persister, abort\n") } }
conditional_block
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
// // save Raft's persistent state to stable storage, // where it can later be retrieved after a crash and restart. // see paper's Figure 2 for a description of what should be persistent. // this function can only be called when `rf` holds the lock func (rf *Raft) persist() { // Your code here (2C). // Example: // w...
random_line_split
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
// // the service using Raft (e.g. a k/v server) wants to start // agreement on the next command to be appended to Raft's log. if this // server isn't the leader, returns false. otherwise start the // agreement and return immediately. there is no guarantee that this // command will ever be committed to the Raft log, ...
{ if ok := rf.peers[server].Call("Raft.AppendEntries", args, reply); !ok { return } rf.mu.Lock() defer rf.mu.Unlock() // drop old reply if args.Term != reply.Term { return } if reply.Term > rf.currentTerm { rf.currentTerm = reply.Term rf.persist() rf.state = FOLLOWER return } if reply.Success {...
identifier_body
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
() { // comes to power, initialize fields rf.mu.Lock() rf.state = LEADER rf.votedFor = -1 peerNum := len(rf.peers) for i := 0; i < peerNum; i++ { rf.nextIndex[i] = len(rf.log) // leader last log index + 1 rf.matchIndex[i] = 0 } rf.mu.Unlock() go rf.startHeartBeat() // leader work for { if rf.killed()...
leader
identifier_name
dashboard.py
#!/usr/bin/env python3 import datetime import gc import json import os import py4j import sys import yaml import dash_utils import fp_001 import fp_002 import fp_003 import fp_004 import fp_005 import fp_006 import fp_007 import fp_008 import fp_009 import fp_011 import fp_012 import fp_016 import report_utils from ...
BIG_ONTS = ['bto', 'chebi', 'dron', 'gaz', 'ncbitaxon', 'ncit', 'pr', 'uberon'] OBO = 'http://purl.obolibrary.org/obo' PRINCIPLE_MAP = { 1: 'FP1 Open', 2: 'FP2 Common Format', 3: 'FP3 URIs', 4: 'FP4 Versioning', 5: 'FP5 Scope', 6: 'FP6 Textual Definitions', 7: 'FP7 Relations', 8: 'FP...
parser = ArgumentParser(description='Create dashboard files') parser.add_argument('ontology', type=str, help='Input ontology file') parser.add_argument('registry', type=FileType('r'), help='Registry YAML file') parser.add_argument('license', type=FileType('r'), help='License JSON schema') parser.add_arg...
identifier_body
dashboard.py
#!/usr/bin/env python3 import datetime import gc import json import os import py4j import sys import yaml import dash_utils import fp_001 import fp_002 import fp_003 import fp_004 import fp_005 import fp_006 import fp_007 import fp_008 import fp_009 import fp_011 import fp_012 import fp_016 import report_utils from ...
11: 'FP11 Locus of Authority', 12: 'FP12 Naming Conventions', 16: 'FP16 Maintenance' } if __name__ == '__main__': run()
5: 'FP5 Scope', 6: 'FP6 Textual Definitions', 7: 'FP7 Relations', 8: 'FP8 Documented', 9: 'FP9 Plurality of Users',
random_line_split
dashboard.py
#!/usr/bin/env python3 import datetime import gc import json import os import py4j import sys import yaml import dash_utils import fp_001 import fp_002 import fp_003 import fp_004 import fp_005 import fp_006 import fp_007 import fp_008 import fp_009 import fp_011 import fp_012 import fp_016 import report_utils from ...
else: summary = 'PASS' summary_comment = '' date = datetime.datetime.today() save_data = {'namespace': namespace, 'version': version_iri, 'date': date.strftime('%Y-%m-%d'), 'summary': {'status': summary, 'comment': summary_comment}, 'results': all_checks} # Save to YA...
summary = 'INFO' summary_comment = '{0} info messages'.format(info)
conditional_block
dashboard.py
#!/usr/bin/env python3 import datetime import gc import json import os import py4j import sys import yaml import dash_utils import fp_001 import fp_002 import fp_003 import fp_004 import fp_005 import fp_006 import fp_007 import fp_008 import fp_009 import fp_011 import fp_012 import fp_016 import report_utils from ...
(): # ---------------------------- # # PREPARE INPUT # ---------------------------- # # parse input args parser = ArgumentParser(description='Create dashboard files') parser.add_argument('ontology', type=str, help='Input ontology file') parser.add_argument('registry', type=FileType('r'), he...
run
identifier_name
bench.rs
use super::config::*; use super::errors::*; use super::out; use super::symbols; use bencher::stats::Summary; use libc::c_void; #[cfg(unix)] use libc::{RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NOW}; #[cfg(unix)] use libloading; use libloading::{Library, Symbol}; use precision::{self, Elapsed, Precision}; use std::collec...
let test_results = run_tests(config, global_ctx, tests)?; if let Some(global_teardown) = tests_runner.global_teardown { unsafe { global_teardown(global_ctx) } } Ok(test_results) } /// Run an optional guard command /// Returns `false` on success (return code = `0`), `true` on failure fn disable...
{ unsafe { global_setup(&mut global_ctx) } }
conditional_block
bench.rs
use super::config::*; use super::errors::*; use super::out; use super::symbols; use bencher::stats::Summary; use libc::c_void; #[cfg(unix)] use libc::{RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NOW}; #[cfg(unix)] use libloading; use libloading::{Library, Symbol}; use precision::{self, Elapsed, Precision}; use std::collec...
{ pub grand_summary: Summary, pub bodies_summary: Vec<TestBodySummary>, } impl Default for AnonymousTestResult { fn default() -> Self { Self { grand_summary: Summary::new(&[0.0]), bodies_summary: vec![], } } } impl From<TestResult> for AnonymousTestResult { ...
AnonymousTestResult
identifier_name
bench.rs
use super::config::*; use super::errors::*; use super::out; use super::symbols; use bencher::stats::Summary; use libc::c_void; #[cfg(unix)] use libc::{RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NOW}; #[cfg(unix)] use libloading; use libloading::{Library, Symbol}; use precision::{self, Elapsed, Precision}; use std::collec...
let test_results = bench_library(&config, Path::new(library_path))?; for test_result in test_results { let test_name_key = test_result.name.clone(); let anonymous_test_result = test_result.into(); if !test_suites_results.contains_key(&test_name_key) { ...
let library_path = &test_suite.library_path;
random_line_split
bench.rs
use super::config::*; use super::errors::*; use super::out; use super::symbols; use bencher::stats::Summary; use libc::c_void; #[cfg(unix)] use libc::{RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NOW}; #[cfg(unix)] use libloading; use libloading::{Library, Symbol}; use precision::{self, Elapsed, Precision}; use std::collec...
/// Run a sequence of tests fn run_tests( config: &Config, global_ctx: TestCtx, tests: Vec<Test>, ) -> Result<Vec<TestResult>, BenchError> { let mut test_results: Vec<TestResult> = vec![]; let precision = Precision::new(precision::Config::default())?; for test in tests { eprintln!(" -...
{ let mut ctx: TestCtx = ptr::null_mut(); if let Some(setup) = (*test).setup_fn { unsafe { setup(global_ctx, &mut ctx) } } let bench_runner = AdaptiveRunner::new( config .initial_round_size .unwrap_or(DEFAULT_INITIAL_ROUND_SIZE), config.min_sample_size.un...
identifier_body
opmapi.rs
// Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according ...
extern "system" { pub fn OPMGetVideoOutputsFromHMONITOR( hMonitor: HMONITOR, vos: OPM_VIDEO_OUTPUT_SEMANTICS, pulNumVideoOutputs: *mut ULONG, pppOPMVideoOutputArray: *mut *mut *mut IOPMVideoOutput, ) -> HRESULT; pub fn OPMGetVideoOutputForTarget( pAdapterLuid: *mut L...
{ ulBusTypeAndImplementation & OPM_BUS_IMPLEMENTATION_MODIFIER_NON_STANDARD }
identifier_body
opmapi.rs
// Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according ...
(ulBusTypeAndImplementation: ULONG) -> ULONG { (ulBusTypeAndImplementation & OPM_BUS_IMPLEMENTATION_MODIFIER_MASK) >> 16 } #[inline] pub fn IsNonStandardBusImplementation(ulBusTypeAndImplementation: ULONG) -> ULONG { ulBusTypeAndImplementation & OPM_BUS_IMPLEMENTATION_MODIFIER_NON_STANDARD } extern "system" { ...
GetBusImplementation
identifier_name
opmapi.rs
// Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according ...
OPM_PROTECTION_STANDARD_CEA805A_TYPEA_1125I = 0x80, OPM_PROTECTION_STANDARD_CEA805A_TYPEB_525P = 0x100, OPM_PROTECTION_STANDARD_CEA805A_TYPEB_750P = 0x200, OPM_PROTECTION_STANDARD_CEA805A_TYPEB_1125I = 0x400, OPM_PROTECTION_STANDARD_ARIBTRB15_525I = 0x800, OPM_PROTECTION_STANDARD_ARIBTRB15_525P ...
OPM_PROTECTION_STANDARD_CEA805A_TYPEA_525P = 0x20, OPM_PROTECTION_STANDARD_CEA805A_TYPEA_750P = 0x40,
random_line_split
oauth.rs
extern crate rand; //Concurrency stuff use std::io::Read; use std::sync::mpsc; use std::thread; use std::time::Duration; use tiny_http::{Response, Server}; use serde::{Deserialize, Serialize}; use curl::easy::{Easy, List}; #[derive(Debug)] enum OAuthState { IDLE, AUTHORIZED, ERROR, } #[derive(Serialize...
let mut file = File::create("access_token.rvp").expect("Unable to create file"); file.write_all(serialized_token.as_bytes()) .expect("Unable to write access token"); } fn generate_random_string(n: usize) -> String { use rand::Rng; const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ ...
{ fs::remove_file("access_token.rvp").expect("Could not remove file"); }
conditional_block
oauth.rs
extern crate rand; //Concurrency stuff use std::io::Read; use std::sync::mpsc; use std::thread; use std::time::Duration; use tiny_http::{Response, Server}; use serde::{Deserialize, Serialize}; use curl::easy::{Easy, List}; #[derive(Debug)] enum OAuthState { IDLE, AUTHORIZED, ERROR, } #[derive(Serialize...
{ client_id: String, client_state: String, authorization_link: String, auth_state: OAuthState, oauth_token: Option<OAuthToken>, pub error_state: String, pub code: String, } struct AuthBox { has_error: bool, error_msg: String, code: String, state: String, } impl OAuthClient...
OAuthClient
identifier_name
oauth.rs
extern crate rand; //Concurrency stuff use std::io::Read; use std::sync::mpsc; use std::thread; use std::time::Duration; use tiny_http::{Response, Server}; use serde::{Deserialize, Serialize}; use curl::easy::{Easy, List}; #[derive(Debug)] enum OAuthState { IDLE, AUTHORIZED, ERROR, } #[derive(Serialize...
} let auth_box = AuthBox { has_error: true, error_msg: "Reached timeout. User did not authorize usage of RPV in time".to_string(), code: "".to_string(), state: "".to_string(), }; println!("Timeout during authentication"); tx_countdo...
for passed_seconds in 0..wait_time { thread::sleep(Duration::from_secs(1));
random_line_split
make_index_file.py
#! /usr/bin/env python import time import sys import logging import subprocess import os import shutil import hashlib from pathlib import Path import click import numpy as np from astropy.io import fits from astropy.table import Table from astropy.table import join as table_join from astropy.time import Time import os ...
(self): return Path('run{:06d}-{:06d}'.format(self.obs_group[0], self.obs_group[1])) @property def _obs_folder(self): return Path('run{:06d}'.format(self.obs_id)) def folder(self, step=None): """Create folder for a given step. """ if step is None: return...
_obs_group_folder
identifier_name
make_index_file.py
#! /usr/bin/env python import time import sys import logging import subprocess import os import shutil import hashlib from pathlib import Path import click import numpy as np from astropy.io import fits from astropy.table import Table from astropy.table import join as table_join from astropy.time import Time import os ...
# Background modeling BG_MODEL_DIR = OUT_DIR / 'background' BG_MODEL_GROUPING = BG_MODEL_DIR / 'background_grouping.ecsv' BG_MODEL_OFF_RUNS = BG_MODEL_DIR / 'background_runs.ecsv' BG_MODEL_OFF_RUNS_GROUPED = BG_MODEL_DIR / 'background_runs_grouped.ecsv' class Observation: """Helper functions ...
random_line_split
make_index_file.py
#! /usr/bin/env python import time import sys import logging import subprocess import os import shutil import hashlib from pathlib import Path import click import numpy as np from astropy.io import fits from astropy.table import Table from astropy.table import join as table_join from astropy.time import Time import os ...
elif filetype == 'edisp': return self.folder('irfs') / 'edisp_{:06d}.fits.gz'.format(self.obs_id) elif filetype == 'psf_3gauss': return self.folder('irfs') / 'psf_3gauss_{:06d}.fits.gz'.format(self.obs_id) else: raise ValueError('Invalid {} {}'.format(filetyp...
return self.folder('irfs') / 'aeff_{:06d}.fits.gz'.format(self.obs_id)
conditional_block
make_index_file.py
#! /usr/bin/env python import time import sys import logging import subprocess import os import shutil import hashlib from pathlib import Path import click import numpy as np from astropy.io import fits from astropy.table import Table from astropy.table import join as table_join from astropy.time import Time import os ...
class ListObservations: def __init__(self, runlist_file, config): self.observations = [] runlist = np.loadtxt(runlist_file, ndmin=2) obs_ids = runlist[:, 0].astype(int) telcodes = runlist[:, 1].astype(int) for obs_id, telcode in zip(obs_ids, telcodes): obs = Ob...
"""Check if all out files exist""" for filetype in self.filetypes: filename = self.out_filename(filetype) if not filename.is_file(): log.error('MISSING: {}'.format(filename)) return False return True
identifier_body
user-management.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { CommonService } from '../../services/common.service'; import { MessageService } from 'primeng/api'; import { ToastModule } from 'primeng/toast'; import { HttpClient } from '@angular/common/http'; import { FormBuilder, FormGroup, Validators, FormCont...
import 'jspdf-autotable'; import { UserManagementService } from '../../services/user-management.service'; declare var $: any import * as FileSaver from 'file-saver'; import * as XLSX from 'xlsx'; import { analyzeFile } from '@angular/compiler'; import { environment } from 'src/environments/environment'; const EXCEL_TY...
random_line_split
user-management.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { CommonService } from '../../services/common.service'; import { MessageService } from 'primeng/api'; import { ToastModule } from 'primeng/toast'; import { HttpClient } from '@angular/common/http'; import { FormBuilder, FormGroup, Validators, FormCont...
else { this.BulkUploadDetailsForm.patchValue({ InputFile: { file: files.item(0) } }); } import('xlsx').then(xlsx => { let workBook = null; let userdata = null; const reader = new FileReader(); reader.onload = (event) => { const dat...
{ this.Errormessage("Invalid file upload"); this.fileName = 'Choose File'; return false; }
conditional_block
user-management.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { CommonService } from '../../services/common.service'; import { MessageService } from 'primeng/api'; import { ToastModule } from 'primeng/toast'; import { HttpClient } from '@angular/common/http'; import { FormBuilder, FormGroup, Validators, FormCont...
deleteUserConfirm() { var data = { // Id: this.uploadData.id, // //UserLoginId: this.userLoginId } this.UserManagement.deleteRequest1('api/v1/CAdocument/DeleteCAdocument?id='+this.currentUserId).subscribe((response) => { // if (response.status == 1) { this.GetUserManagementList...
{ debugger this.currentUserId = user.id; }
identifier_body
user-management.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { CommonService } from '../../services/common.service'; import { MessageService } from 'primeng/api'; import { ToastModule } from 'primeng/toast'; import { HttpClient } from '@angular/common/http'; import { FormBuilder, FormGroup, Validators, FormCont...
() { this.exportPdfcolumn = this.cols.map(col => ({ title: col.header, dataKey: col.field })); const doc = new jsPDF('l'); doc.autoTable(this.exportPdfcolumn,this.userManagement); doc.save('UDP_UserManagement' + new Date().getTime() + '.pdf'); } Open() { this.selectedValue = 'true'; ...
exportPdf
identifier_name
connection.rs
use byteorder::{ BigEndian, ByteOrder, LittleEndian, ReadBytesExt, WriteBytesExt }; use constants::VOICE_GATEWAY_VERSION; use internal::prelude::*; use internal::{ ws_impl::{ReceiverExt, SenderExt}, Timer }; use model::{ event::VoiceEvent, id::UserId }; use opus::{ packet as opus...
let index = HEADER_LEN + crypted.len(); packet[HEADER_LEN..index].clone_from_slice(&crypted); self.sequence = self.sequence.wrapping_add(1); self.timestamp = self.timestamp.wrapping_add(960); Ok(HEADER_LEN + crypted.len()) } fn set_speaking(&mut self, speaking: bool) -...
let crypted = { let slice = &packet[HEADER_LEN..HEADER_LEN + len]; secretbox::seal(slice, &nonce, &self.key) };
random_line_split
connection.rs
use byteorder::{ BigEndian, ByteOrder, LittleEndian, ReadBytesExt, WriteBytesExt }; use constants::VOICE_GATEWAY_VERSION; use internal::prelude::*; use internal::{ ws_impl::{ReceiverExt, SenderExt}, Timer }; use model::{ event::VoiceEvent, id::UserId }; use opus::{ packet as opus...
(&mut self, speaking: bool) -> Result<()> { if self.speaking == speaking { return Ok(()); } self.speaking = speaking; self.client.lock().send_json(&payload::build_speaking(speaking)) } } impl Drop for Connection { fn drop(&mut self) { let _ = self.thread_it...
set_speaking
identifier_name
connection.rs
use byteorder::{ BigEndian, ByteOrder, LittleEndian, ReadBytesExt, WriteBytesExt }; use constants::VOICE_GATEWAY_VERSION; use internal::prelude::*; use internal::{ ws_impl::{ReceiverExt, SenderExt}, Timer }; use model::{ event::VoiceEvent, id::UserId }; use opus::{ packet as opus...
, }; // May need to force interleave/copy. combine_audio(buffer, &mut mix_buffer, source_stereo, vol); len = len.max(temp_len); i += if temp_len > 0 { 1 } else { sources.remove(i); ...
{ let buffer_len = if source_stereo { 960 * 2 } else { 960 }; match stream.read_pcm_frame(&mut buffer[..buffer_len]) { Some(len) => len, None => 0, } }
conditional_block
connection.rs
use byteorder::{ BigEndian, ByteOrder, LittleEndian, ReadBytesExt, WriteBytesExt }; use constants::VOICE_GATEWAY_VERSION; use internal::prelude::*; use internal::{ ws_impl::{ReceiverExt, SenderExt}, Timer }; use model::{ event::VoiceEvent, id::UserId }; use opus::{ packet as opus...
fn generate_url(endpoint: &mut String) -> Result<WebsocketUrl> { if endpoint.ends_with(":80") { let len = endpoint.len(); endpoint.truncate(len - 3); } WebsocketUrl::parse(&format!("wss://{}/?v={}", endpoint, VOICE_GATEWAY_VERSION)) .or(Err(Error::Voice(VoiceError::EndpointUrl)))...
{ for i in 0..1920 { let sample_index = if true_stereo { i } else { i/2 }; let sample = (raw_buffer[sample_index] as f32) / 32768.0; float_buffer[i] = float_buffer[i] + sample * volume; } }
identifier_body
displayer.py
from __future__ import unicode_literals import datetime import json import logging import os import collections from jinja2 import Environment, PackageLoader jinja_env = Environment(loader=PackageLoader('serverinfo', 'templates')) logger = logging.getLogger(__name__) from serverinfo import utils data = {} data['ser...
simple_fields = ['hostname', 'buildout_directory', 'configfile', 'server_names', 'proxy_port', ] buildout = None server = None link_attributes = ['buildout', 'server', ...
class Nginx(Common): subdir = 'sites' template_name = 'nginx.html' title_prefix = 'NGINX configuration of'
random_line_split
displayer.py
from __future__ import unicode_literals import datetime import json import logging import os import collections from jinja2 import Environment, PackageLoader jinja_env = Environment(loader=PackageLoader('serverinfo', 'templates')) logger = logging.getLogger(__name__) from serverinfo import utils data = {} data['ser...
(Common): subdir = 'sites' template_name = 'nginx.html' title_prefix = 'NGINX configuration of' simple_fields = ['hostname', 'buildout_directory', 'configfile', 'server_names', 'proxy_port', ] bu...
Nginx
identifier_name
displayer.py
from __future__ import unicode_literals import datetime import json import logging import os import collections from jinja2 import Environment, PackageLoader jinja_env = Environment(loader=PackageLoader('serverinfo', 'templates')) logger = logging.getLogger(__name__) from serverinfo import utils data = {} data['ser...
class Buildout(Common): subdir = 'buildouts' template_name = 'buildout.html' title_prefix = 'Buildout directory' simple_fields = ['hostname', 'directory', 'extends', # TODO: fix this: missing KGS here. 'version_control_system', ...
title = "Who worked on this?" def __init__(self, vcs, url): assert(vcs == 'git') self.url = url @property def link(self): return self.url + '/graphs/contributors'
identifier_body
displayer.py
from __future__ import unicode_literals import datetime import json import logging import os import collections from jinja2 import Environment, PackageLoader jinja_env = Environment(loader=PackageLoader('serverinfo', 'templates')) logger = logging.getLogger(__name__) from serverinfo import utils data = {} data['ser...
collect_data() generate_html()
utils.clear_directory_contents(os.path.join( utils.html_dir(), subdir))
conditional_block
models.py
""" models.py: Domain models __author__ = "Fernando P. Lopes" __email__ = "fpedrosa@gmail.com" """ from app import db, login_manager from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask.ext.login import UserMixin ...
songs = db.relationship('Song', backref='user', lazy='dynamic', cascade="all, delete-orphan") shows = db.relationship('Show', backref='user', lazy='dynamic', cascade="all, delete-orphan") def __repr__(self): return 'User {0} ({1})'.format(self.name, self.email) @property def password(self)...
confirmed = db.Column(db.Boolean, default=False) bands = db.relationship('Band', backref='user', lazy='dynamic', cascade="all, delete-orphan")
random_line_split
models.py
""" models.py: Domain models __author__ = "Fernando P. Lopes" __email__ = "fpedrosa@gmail.com" """ from app import db, login_manager from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask.ext.login import UserMixin ...
def remove_all_songs(self): with db.engine.connect() as connection: delete_sql = text('delete from setlist where show_id = :show_id') delete_sql = delete_sql.bindparams(show_id=self.id) connection.execute(delete_sql.execution_options(autocommit=True)) def assign_po...
self.songs.remove(song)
identifier_body
models.py
""" models.py: Domain models __author__ = "Fernando P. Lopes" __email__ = "fpedrosa@gmail.com" """ from app import db, login_manager from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask.ext.login import UserMixin ...
(self): raise AttributeError('Password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) def generate_...
password
identifier_name
models.py
""" models.py: Domain models __author__ = "Fernando P. Lopes" __email__ = "fpedrosa@gmail.com" """ from app import db, login_manager from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask.ext.login import UserMixin ...
soup = getsoup(url) article = soup.find('article') html = str(article) if 'e-chords' in url: soup = getsoup(url) pre = soup.find('pre', id='core') # Remove Tab Div, keep raw tab div = pre.find('div') if div is not ...
url = 'https://www.' + url[10:] # So we don't have to deal with mobile URLs
conditional_block
client.go
package main import ( "context" "fmt" "math/rand" "sync" "time" pb "github.com/vyzo/libp2p-flare-test/pb" "github.com/vyzo/libp2p-flare-test/proto" "github.com/libp2p/go-libp2p-core/event" "github.com/libp2p/go-libp2p-core/host" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/...
// let identify get our observed addresses before starting time.Sleep(time.Second) err = c.connectToPeer(ci) c.tracer.Connect(ci, err) return err } func (c *Client) connectToPeer(ci *ClientInfo) error { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() err := c.host.Conn...
{ return fmt.Errorf("error connecting to bootstrappers: %w", err) }
conditional_block
client.go
package main import ( "context" "fmt" "math/rand" "sync" "time" pb "github.com/vyzo/libp2p-flare-test/pb" "github.com/vyzo/libp2p-flare-test/proto" "github.com/libp2p/go-libp2p-core/event" "github.com/libp2p/go-libp2p-core/host" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/...
if !isRelayConn(conn) { return nil } } select { case <-deadline: break poll case <-time.After(time.Second): } } return fmt.Errorf("no direct connection to peer") } func (c *Client) connectToBootstrappers() error { var pis []*peer.AddrInfo if c.domain == "TCP" { pis = bootstrappersTCP } ...
for _, conn := range c.host.Network().ConnsToPeer(ci.Info.ID) {
random_line_split
client.go
package main import ( "context" "fmt" "math/rand" "sync" "time" pb "github.com/vyzo/libp2p-flare-test/pb" "github.com/vyzo/libp2p-flare-test/proto" "github.com/libp2p/go-libp2p-core/event" "github.com/libp2p/go-libp2p-core/host" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/...
func (c *Client) connectToServer() (network.Stream, error) { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() err := c.host.Connect(ctx, *c.server) if err != nil { return nil, fmt.Errorf("error connecting to server: %w", err) } s, err := c.host.NewStream(ctx, c.server.ID,...
{ // connect to relay and reserve slot var rsvp *circuit.Reservation var err error for rsvp == nil { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) err = c.host.Connect(ctx, *c.relay) cancel() if err != nil { log.Warnf("error connecting to relay: %s; will retry in 1min", err) t...
identifier_body
client.go
package main import ( "context" "fmt" "math/rand" "sync" "time" pb "github.com/vyzo/libp2p-flare-test/pb" "github.com/vyzo/libp2p-flare-test/proto" "github.com/libp2p/go-libp2p-core/event" "github.com/libp2p/go-libp2p-core/host" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/...
(ci *ClientInfo) error { // check for existing connections first for _, conn := range c.host.Network().ConnsToPeer(ci.Info.ID) { if !isRelayConn(conn) { return nil } } err := c.connectToBootstrappers() if err != nil { return fmt.Errorf("error connecting to bootstrappers: %w", err) } // let identify ge...
Connect
identifier_name
initializer.rs
//! Reactor used to initialize a node. use std::fmt::{self, Display, Formatter}; use datasize::DataSize; use derive_more::From; use prometheus::Registry; use reactor::ReactorEvent; use serde::Serialize; use thiserror::Error; use tracing::info; use crate::{ components::{ chainspec_loader::{self, Chainspec...
(&self) -> Option<ReactorExit> { self.chainspec_loader.reactor_exit() } } #[cfg(test)] pub mod test { use super::*; use crate::{ components::network::ENABLE_LIBP2P_NET_ENV_VAR, testing::network::NetworkedReactor, types::Chainspec, }; use std::{env, sync::Arc}; impl Reac...
maybe_exit
identifier_name
initializer.rs
//! Reactor used to initialize a node. use std::fmt::{self, Display, Formatter}; use datasize::DataSize; use derive_more::From; use prometheus::Registry; use reactor::ReactorEvent; use serde::Serialize; use thiserror::Error; use tracing::info; use crate::{ components::{ chainspec_loader::{self, Chainspec...
NodeId::from(&self.network_identity) } } } }
random_line_split
initializer.rs
//! Reactor used to initialize a node. use std::fmt::{self, Display, Formatter}; use datasize::DataSize; use derive_more::From; use prometheus::Registry; use reactor::ReactorEvent; use serde::Serialize; use thiserror::Error; use tracing::info; use crate::{ components::{ chainspec_loader::{self, Chainspec...
} impl From<NetworkRequest<NodeId, gossiper::Message<GossipedAddress>>> for Event { fn from(_request: NetworkRequest<NodeId, gossiper::Message<GossipedAddress>>) -> Self { unreachable!("no gossiper events happen during initialization") } } impl From<ConsensusRequest> for Event { fn from(_request:...
{ unreachable!("no linear chain events happen during initialization") }
identifier_body
getMultiTractTemplate.py
import numpy as np import lsst.afw.image as afwImage import lsst.geom as geom import lsst.pex.config as pexConfig import lsst.pipe.base as pipeBase import lsst.afw.table as afwTable import lsst.afw.math as afwMath import lsst.afw.geom as afwGeom from lsst.meas.algorithms import CoaddPsf, CoaddPsfConfig from lsst.meas...
self.log.info("Central skyMap tract %s" % (centralTractInfo.getId(),)) skyCorners = [expWcs.pixelToSky(pixPos) for pixPos in expBoxD.getCorners()] tractPatchList = skyMap.findTractPatchList(skyCorners) if not tractPatchList: raise RuntimeError("No suitable tract found") ...
raise RuntimeError("No suitable tract found for central point")
conditional_block
getMultiTractTemplate.py
import numpy as np import lsst.afw.image as afwImage import lsst.geom as geom import lsst.pex.config as pexConfig import lsst.pipe.base as pipeBase import lsst.afw.table as afwTable import lsst.afw.math as afwMath import lsst.afw.geom as afwGeom from lsst.meas.algorithms import CoaddPsf, CoaddPsfConfig from lsst.meas...
"""Return coadd name for given task config Returns ------- CoaddDatasetName : `string` TODO: This nearly duplicates a method in CoaddBaseTask (DM-11985) """ warpType = self.config.warpType suffix = "" if warpType == "direct" else warpType[0].upper() + warpType[1:]...
identifier_body
getMultiTractTemplate.py
import numpy as np import lsst.afw.image as afwImage import lsst.geom as geom import lsst.pex.config as pexConfig import lsst.pipe.base as pipeBase import lsst.afw.table as afwTable import lsst.afw.math as afwMath import lsst.afw.geom as afwGeom from lsst.meas.algorithms import CoaddPsf, CoaddPsfConfig from lsst.meas...
(self, exposure, sensorRef, templateIdList=None): """Retrieve and mosaic a template coadd that overlaps the exposure where the template spans multiple tracts. The resulting template image will be an average of all the input templates from the separate tracts. The PSF on the tem...
run
identifier_name
getMultiTractTemplate.py
import numpy as np import lsst.afw.image as afwImage import lsst.geom as geom import lsst.pex.config as pexConfig import lsst.pipe.base as pipeBase import lsst.afw.table as afwTable import lsst.afw.math as afwMath import lsst.afw.geom as afwGeom from lsst.meas.algorithms import CoaddPsf, CoaddPsfConfig from lsst.meas...
patchInt = int(f"{patchInfo.getIndex()[0]}{patchInfo.getIndex()[1]}") innerBBox = geom.Box2I(tractInfo._minimumBoundingBox(finalWcs)) if itract == 0: # clip to image and tract boundaries patchSubBBox.clip(finalBBox) ...
# Local patch information patchSubBBox = geom.Box2I(patchInfo.getInnerBBox()) patchSubBBox.clip(coaddBBox)
random_line_split
arm.py
# Author(s): Jiaqi Xu # Created on: 2020-11 """ Arm wrapper Refer to: https://github.com/jhu-dvrk/dvrk-ros/blob/master/dvrk_python/src/dvrk/arm.py https://github.com/jhu-dvrk/dvrk-ros/blob/7b3d48ca164755ccfc88028e15baa9fbf7aa1360/dvrk_python/src/dvrk/arm.py """ from typing import Union import numpy as np import pybull...
return pose_tf def _set_collision(self): """ Set collision groups. """ pass def _set_constraint(self): """ Set if there is any constraint to maintain the parallel link. """ pass
pose_ori = pose.copy() if premultiply: pose_tf = np.matmul(mat, pose_ori) else: pose_tf = np.matmul(pose_ori, mat)
random_line_split
arm.py
# Author(s): Jiaqi Xu # Created on: 2020-11 """ Arm wrapper Refer to: https://github.com/jhu-dvrk/dvrk-ros/blob/master/dvrk_python/src/dvrk/arm.py https://github.com/jhu-dvrk/dvrk-ros/blob/7b3d48ca164755ccfc88028e15baa9fbf7aa1360/dvrk_python/src/dvrk/arm.py """ from typing import Union import numpy as np import pybull...
def get_joint_number(self) -> int: """ Get the number of joints on the arm specified. """ return self.DoF def dmove_joint(self, delta_pos: [list, np.ndarray]) -> [bool, np.ndarray]: """ Incremental move in joint space. """ if not isinstance(delta_pos, np.ndarray): ...
""" Get the 'desired joint position' of the arm. """ return self._position_joint_desired
identifier_body
arm.py
# Author(s): Jiaqi Xu # Created on: 2020-11 """ Arm wrapper Refer to: https://github.com/jhu-dvrk/dvrk-ros/blob/master/dvrk_python/src/dvrk/arm.py https://github.com/jhu-dvrk/dvrk-ros/blob/7b3d48ca164755ccfc88028e15baa9fbf7aa1360/dvrk_python/src/dvrk/arm.py """ from typing import Union import numpy as np import pybull...
return pose_eef def reset_joint(self, abs_input: [list, np.ndarray]) -> [bool, np.ndarray]: """ Helper function for PyBullet initial reset. Not recommend to use during simulation. """ if not self._check_joint_limits(abs_input): return joint_posit...
pose_eef = get_pose_2d_from_matrix(pose_eef)
conditional_block
arm.py
# Author(s): Jiaqi Xu # Created on: 2020-11 """ Arm wrapper Refer to: https://github.com/jhu-dvrk/dvrk-ros/blob/master/dvrk_python/src/dvrk/arm.py https://github.com/jhu-dvrk/dvrk-ros/blob/7b3d48ca164755ccfc88028e15baa9fbf7aa1360/dvrk_python/src/dvrk/arm.py """ from typing import Union import numpy as np import pybull...
(self): """ Set collision groups. """ pass def _set_constraint(self): """ Set if there is any constraint to maintain the parallel link. """ pass
_set_collision
identifier_name
user_controller.js
app.controller('user_controller', ['$scope','$cookies','$location','$anchorScroll','$routeParams','user_factory', function($scope,$cookies,$location,$anchorScroll,$routeParams,user_factory) { console.log('user_controller loaded'); //TRIED TO IMPLEMENT MAPS // // var cities = [ // // { // // ...
else if($scope.newSpot.street.length < 5) { $scope.error = {street: 'Invalid street'}; } else if (!$scope.newSpot.house_number.match(house_numberRegex)) { //if the house number entered does not match regex... $scope.error = {house_number: 'Invalid house_number'}; } else if (!$scope....
{ $scope.error = {contact: 'Invalid phone number'}; }
conditional_block
user_controller.js
app.controller('user_controller', ['$scope','$cookies','$location','$anchorScroll','$routeParams','user_factory', function($scope,$cookies,$location,$anchorScroll,$routeParams,user_factory) { console.log('user_controller loaded'); //TRIED TO IMPLEMENT MAPS // // var cities = [ // // { // // ...
(ts) { let dataF = new Date(); dataF.setTime(ts); let strDataF = dataF.toLocaleString(); return strDataF; } var firstdate = toDateStr($scope.newRenter.arriving_on) var seconddate = toDateStr($scope.newRenter.departing_on) $scope.diffe...
toDateStr
identifier_name
user_controller.js
app.controller('user_controller', ['$scope','$cookies','$location','$anchorScroll','$routeParams','user_factory', function($scope,$cookies,$location,$anchorScroll,$routeParams,user_factory) { console.log('user_controller loaded'); //TRIED TO IMPLEMENT MAPS // // var cities = [ // // { // // ...
var firstdate = toDateStr($scope.newRenter.arriving_on) var seconddate = toDateStr($scope.newRenter.departing_on) $scope.differenceInDays = function() { var dt1 = firstdate.split('/') var dt2 = seconddate.split('/') var x = dt1[2].split(',')[0] ...
{ let dataF = new Date(); dataF.setTime(ts); let strDataF = dataF.toLocaleString(); return strDataF; }
identifier_body
user_controller.js
app.controller('user_controller', ['$scope','$cookies','$location','$anchorScroll','$routeParams','user_factory', function($scope,$cookies,$location,$anchorScroll,$routeParams,user_factory) { console.log('user_controller loaded'); //TRIED TO IMPLEMENT MAPS // // var cities = [ // // { // // ...
} $scope.geocode = function() { if($scope.newSpot.contact.length < 10) { $scope.error = {contact: 'Invalid phone number'}; } else if($scope.newSpot.street.length < 5) { $scope.error = {street: 'Invalid street'}; } else if (!$scope.newSpot.house_number.m...
random_line_split
rip_show_statistics_bd.pb.go
/* Copyright 2019 Cisco Systems 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 writing, software d...
func (m *RipShowStatisticsBd) String() string { return proto.CompactTextString(m) } func (*RipShowStatisticsBd) ProtoMessage() {} func (*RipShowStatisticsBd) Descriptor() ([]byte, []int) { return fileDescriptor_66227cbf5e51e264, []int{1} } func (m *RipShowStatisticsBd) XXX_Unmarshal(b []byte) error { return xxx_...
{ *m = RipShowStatisticsBd{} }
identifier_body
rip_show_statistics_bd.pb.go
/* Copyright 2019 Cisco Systems 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 writing, software d...
} func (m *RipShowStatisticsBd_KEYS) XXX_DiscardUnknown() { xxx_messageInfo_RipShowStatisticsBd_KEYS.DiscardUnknown(m) } var xxx_messageInfo_RipShowStatisticsBd_KEYS proto.InternalMessageInfo func (m *RipShowStatisticsBd_KEYS) GetVrfName() string { if m != nil { return m.VrfName } return "" } type RipShowStati...
func (m *RipShowStatisticsBd_KEYS) XXX_Size() int { return xxx_messageInfo_RipShowStatisticsBd_KEYS.Size(m)
random_line_split
rip_show_statistics_bd.pb.go
/* Copyright 2019 Cisco Systems 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 writing, software d...
return 0 } func (m *RipShowStatisticsBd) GetSentMessageFailures() uint32 { if m != nil { return m.SentMessageFailures } return 0 } func (m *RipShowStatisticsBd) GetQueryResponses() uint32 { if m != nil { return m.QueryResponses } return 0 } func (m *RipShowStatisticsBd) GetPeriodicUpdates() uint32 { if ...
{ return m.SentMessages }
conditional_block
rip_show_statistics_bd.pb.go
/* Copyright 2019 Cisco Systems 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 writing, software d...
() ([]byte, []int) { return fileDescriptor_66227cbf5e51e264, []int{1} } func (m *RipShowStatisticsBd) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_RipShowStatisticsBd.Unmarshal(m, b) } func (m *RipShowStatisticsBd) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_RipShowS...
Descriptor
identifier_name
main.rs
use anyhow::{anyhow, Result}; use colored::*; use dunce::canonicalize; use git2::{Commit, ObjectType, Oid, Repository, Tree}; use regex::Regex; use std::{ collections::{HashMap, HashSet}, convert::{TryFrom, TryInto}, env, ffi::OsString, path::{Path, PathBuf}, }; use structopt::StructOpt; #[derive(D...
{ #[structopt( help = "The pattern to search for. Shall be a regular expression passed to regex crate." )] pattern: String, #[structopt(help = "Root repo to grep")] repo: Option<PathBuf>, #[structopt(short, long, help = "Branch name")] branch: Option<String>, #[structopt( ...
Opt
identifier_name
main.rs
use anyhow::{anyhow, Result}; use colored::*; use dunce::canonicalize; use git2::{Commit, ObjectType, Oid, Repository, Tree}; use regex::Regex; use std::{ collections::{HashMap, HashSet}, convert::{TryFrom, TryInto}, env, ffi::OsString, path::{Path, PathBuf}, }; use structopt::StructOpt; #[derive(D...
let blob = obj.peel_to_blob().ok()?; if blob.is_binary() { return None; } let ext = PathBuf::from(name).extension()?.to_owned(); if !self.settings.extensions.contains(&ext.to_ascii_lowercase()) { retu...
random_line_split
main.rs
use anyhow::{anyhow, Result}; use colored::*; use dunce::canonicalize; use git2::{Commit, ObjectType, Oid, Repository, Tree}; use regex::Regex; use std::{ collections::{HashMap, HashSet}, convert::{TryFrom, TryInto}, env, ffi::OsString, path::{Path, PathBuf}, }; use structopt::StructOpt; #[derive(D...
} } if settings.color_code { if settings.output_grouping && !*visited { println!("\ncommit {}:", commit.id().to_string().bright_blue()); *visited = true; } let mut content = if line_start < found.start() { ...
{ line_end = (i as usize).max(line_start); break; }
conditional_block
lib.rs
//! [![github]](https://github.com/dtolnay/trybuild)&ensp;[![crates-io]](https://crates.io/crates/trybuild)&ensp;[![docs-rs]](https://docs.rs/trybuild) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-f...
(&mut self) { if !thread::panicking() { self.runner.borrow_mut().run(); } } }
drop
identifier_name
lib.rs
//! [![github]](https://github.com/dtolnay/trybuild)&ensp;[![crates-io]](https://crates.io/crates/trybuild)&ensp;[![docs-rs]](https://docs.rs/trybuild) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-f...
} }
{ self.runner.borrow_mut().run(); }
conditional_block
lib.rs
//! [![github]](https://github.com/dtolnay/trybuild)&ensp;[![crates-io]](https://crates.io/crates/trybuild)&ensp;[![docs-rs]](https://docs.rs/trybuild) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-f...
//! [`ref-cast`]: https://github.com/dtolnay/ref-cast //! //! ```console //! error: RefCast trait requires #[repr(C)] or #[repr(transparent)] //! --> $DIR/missing-repr.rs:3:10 //! | //! 3 | #[derive(RefCast)] //! | ^^^^^^^ //! ``` //! //! Macros that consume helper attributes will want to check that unrec...
//! by a procedural macro. For example the derive macro from the [`ref-cast`] //! crate is required to be placed on a type that has either `#[repr(C)]` or //! `#[repr(transparent)]` in order for the expansion to be free of undefined //! behavior, which it enforces at compile time: //!
random_line_split
twitter.py
SOURCE_FILE = "D:\\temp\\twitter\\tweet.js" TWITTER_USERNAME = 'roytang' auto_tags = ["mtg"] syndicated_sources = ["IFTTT", "Tumblr", "instagram.com", "Mailchimp", "Twitter Web", "TweetDeck", "mtgstorm"] debug_id = None # debug_id = "11143081155" import frontmatter import json import requests import urllib.request fr...
continue # delete all the video files except for the one with the lowest bitrate for v in videos: if v == lowest_video: continue name = Path(v).name if name.fi...
print(mdfile) # move it to notes, since it's not a photo p = PostBuilder.from_mdfile(mdfile) p.kind = "notes" p.save() # delete the old files container = mdfile.parent ...
conditional_block
twitter.py
SOURCE_FILE = "D:\\temp\\twitter\\tweet.js" TWITTER_USERNAME = 'roytang' auto_tags = ["mtg"] syndicated_sources = ["IFTTT", "Tumblr", "instagram.com", "Mailchimp", "Twitter Web", "TweetDeck", "mtgstorm"] debug_id = None # debug_id = "11143081155" import frontmatter import json import requests import urllib.request fr...
def process_tweet(d1): orig_tweet_url = "https://twitter.com/%s/statuses/%s/" % (TWITTER_USERNAME, d1['id_str']) if orig_tweet_url in urlmap: og = urlmap.get(orig_tweet_url) if og['source_path'].startswith('post\\') or og['source_path'].startswith('photos\\'): # no need to process ...
print(d1["full_text"]) return True return False
random_line_split
twitter.py
SOURCE_FILE = "D:\\temp\\twitter\\tweet.js" TWITTER_USERNAME = 'roytang' auto_tags = ["mtg"] syndicated_sources = ["IFTTT", "Tumblr", "instagram.com", "Mailchimp", "Twitter Web", "TweetDeck", "mtgstorm"] debug_id = None # debug_id = "11143081155" import frontmatter import json import requests import urllib.request fr...
def import_all(): countbysource = {} replies = 0 retweets = 0 withmedia = 0 raw = 0 with Path(SOURCE_FILE).open(encoding='utf-8') as f: d = json.load(f) idx = 0 for d1 in d: if debug_id is not None and d1["id_str"] != debug_id: continue ...
orig_tweet_url = "https://twitter.com/%s/statuses/%s/" % (TWITTER_USERNAME, d1['id_str']) if orig_tweet_url in urlmap: og = urlmap.get(orig_tweet_url) if og['source_path'].startswith('post\\') or og['source_path'].startswith('photos\\'): # no need to process further any tweets that are ...
identifier_body
twitter.py
SOURCE_FILE = "D:\\temp\\twitter\\tweet.js" TWITTER_USERNAME = 'roytang' auto_tags = ["mtg"] syndicated_sources = ["IFTTT", "Tumblr", "instagram.com", "Mailchimp", "Twitter Web", "TweetDeck", "mtgstorm"] debug_id = None # debug_id = "11143081155" import frontmatter import json import requests import urllib.request fr...
(): with Path(SOURCE_FILE).open(encoding='utf-8') as f: d = json.load(f) idx = 0 for d1 in d: orig_tweet_url = "https://twitter.com/%s/statuses/%s/" % (TWITTER_USERNAME, d1["id_str"]) info = urlmap.get(orig_tweet_url) if info is None: conti...
cleanup_videos
identifier_name
lstm-english-french-word.py
from __future__ import print_function from keras.models import Model from keras.layers import Input, LSTM, Dense, Embedding from keras.callbacks import ModelCheckpoint import numpy as np import os from nltk.translate.bleu_score import sentence_bleu
import re import collections from sklearn.model_selection import train_test_split import numpy as np import tensorflow as tf import time from nltk.translate.bleu_score import sentence_bleu from nltk.tokenize import RegexpTokenizer, word_tokenize from keras.utils.np_utils import to_categorical from keras import models ...
import os
random_line_split
lstm-english-french-word.py
from __future__ import print_function from keras.models import Model from keras.layers import Input, LSTM, Dense, Embedding from keras.callbacks import ModelCheckpoint import numpy as np import os from nltk.translate.bleu_score import sentence_bleu import os import re import collections from sklearn.model_selection i...
(num_list): text = [output_index_word_dict[num] for num in num_list] return ' '.join(text) def pad_num_list(num_list, size): return num_list + [0] * (size - len(num_list)) def input_text_to_x(input_text): num_list = input_text_to_num(input_text) return pad_num_list(num_list, input_max_size) def o...
output_num_to_text
identifier_name
lstm-english-french-word.py
from __future__ import print_function from keras.models import Model from keras.layers import Input, LSTM, Dense, Embedding from keras.callbacks import ModelCheckpoint import numpy as np import os from nltk.translate.bleu_score import sentence_bleu import os import re import collections from sklearn.model_selection i...
# Tokenize input and output input_text_list = [split_input_texts(input_text) for input_text in input_texts] output_text_list = [split_output_texts(output_text) for output_text in output_texts] # Count unique number of English words input_text_flat_list = [] for input_text in input_text_list: input_text_flat_list...
return [word.lower() for word in word_tokenize(text, language='french')]
identifier_body
lstm-english-french-word.py
from __future__ import print_function from keras.models import Model from keras.layers import Input, LSTM, Dense, Embedding from keras.callbacks import ModelCheckpoint import numpy as np import os from nltk.translate.bleu_score import sentence_bleu import os import re import collections from sklearn.model_selection i...
except ValueError: print(line) input_texts = input_texts[:SAMPLE] output_texts = output_texts[:SAMPLE] # Preprocess def remove_blank(word_list): return [word for word in word_list if word.strip()] def is_curly_bracket(string): return string == '{' or string == '}' def remove_blank_curly_bracket(word_li...
input_text, output_text = line.split('\t') input_texts.append(input_text) output_texts.append('{'+output_text+'}') # { denotes the start of sentence, } denotes the end of sentence
conditional_block
pypro.py
from matplotlib import pyplot as plt from matplotlib import style import pandas as pd print('Welcome to the DATA VISUALISATION and ANALYSIS of WELLBEING OF PEOPLE in different parts of the world as of September, 2020') print('In this project, we are going to analize the opinions of people belonging to different GEN...
print('let us see how much trust females have on the society as a score out of 10') print(females) print('let us see how much trust youngsters have on society as a score out of 10') print(age_group_18_24) print('let us see how much trust middle-aged people have on society as a score out of 10') print(age_group_35_...
Europeans = pd.DataFrame({'People':[6.8], 'Health System':[7.1], 'Parliament':[6], 'Police':[8], 'Media':[4.5]}) #created dataframes using pandas to show how people from different catagories trusted the society print("let us see how much trust males have on the society as a score out of 10") print(males)
random_line_split
backup.py
#!/usr/bin/env python # including libraries import roslib import sys import rospy import cv2 import math from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError import numpy as np import matplotlib.pyplot as plt MAP = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...
newcenter = (newx, int(newy)) # read the reference map for animation map_ref = cv2.imread('/home/sunyue/catkin_ws/src/tracking/map.png') cv2.circle(map_ref,newcenter,radius,(0,0,255),-5) # SECOND transfer the real location to the 20x20 grid gridx = newcenter[0]/20+1 gridy = newcenter[1]/20+1 # A*...
newy = 0.955*(center[1] - checky)
random_line_split
backup.py
#!/usr/bin/env python # including libraries import roslib import sys import rospy import cv2 import math from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError import numpy as np import matplotlib.pyplot as plt MAP = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...
if __name__ == '__main__': main(sys.argv)
ic = labyrinth_solver() rospy.init_node('labyrinth_solver', anonymous=True) try: rospy.spin() except KeyboardInterrupt: print "Shutting down" cv2.destroyAllWindows()
identifier_body
backup.py
#!/usr/bin/env python # including libraries import roslib import sys import rospy import cv2 import math from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError import numpy as np import matplotlib.pyplot as plt MAP = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...
(args): ic = labyrinth_solver() rospy.init_node('labyrinth_solver', anonymous=True) try: rospy.spin() except KeyboardInterrupt: print "Shutting down" cv2.destroyAllWindows() if __name__ == '__main__': main(sys.argv)
main
identifier_name
backup.py
#!/usr/bin/env python # including libraries import roslib import sys import rospy import cv2 import math from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError import numpy as np import matplotlib.pyplot as plt MAP = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...
path = np.array([current]) backup = np.array([[0,0,0,0]]) while check!=0: # generate the potential candidate north = [current[0],current[1]-1] south = [current[0],current[1]+1] east = [current[0]+1,current[1]] west = [current[0]-1,current[1]] #print current # calculate the heuristic n...
check = 100
conditional_block
utils_test.go
//go:build integration_tests // +build integration_tests package integration import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/url" "os" "regexp" "strings" "testing" "time" "github.com/blang/semver/v4" "github.com/kong/kubernetes-testing-framework/pkg/clusters" "github.com/kong/kubernete...
return false } // ----------------------------------------------------------------------------- // Test.MAIN Utility Functions // ----------------------------------------------------------------------------- // exitOnErrWithCode is a helper function meant for us in the test.Main to simplify failing and exiting // t...
{ // once the route is torn down and returning 404's, ensure that we got the expected response body back from Kong // Expected: {"message":"no Route matched with those values"} b := new(bytes.Buffer) _, err := b.ReadFrom(resp.Body) require.NoError(t, err) body := struct { Message string `json:"message"` ...
conditional_block
utils_test.go
//go:build integration_tests // +build integration_tests package integration import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/url" "os" "regexp" "strings" "testing" "time" "github.com/blang/semver/v4" "github.com/kong/kubernetes-testing-framework/pkg/clusters" "github.com/kong/kubernete...
(err error, exitCode int) { if err == nil { return } fmt.Println("WARNING: failure occurred, performing test cleanup") if env != nil && existingCluster == "" && keepTestCluster == "" { ctx, cancel := context.WithTimeout(context.Background(), environmentCleanupTimeout) defer cancel() fmt.Printf("INFO: clus...
exitOnErrWithCode
identifier_name
utils_test.go
//go:build integration_tests // +build integration_tests package integration import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/url" "os" "regexp" "strings" "testing" "time" "github.com/blang/semver/v4" "github.com/kong/kubernetes-testing-framework/pkg/clusters" "github.com/kong/kubernete...
} // ----------------------------------------------------------------------------- // Testing Utility Functions - HTTP Requests // ----------------------------------------------------------------------------- // expect404WithNoRoute is used to check whether a given http response is (specifically) a Kong 404. func exp...
} return testCasesForFile, nil
random_line_split
utils_test.go
//go:build integration_tests // +build integration_tests package integration import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/url" "os" "regexp" "strings" "testing" "time" "github.com/blang/semver/v4" "github.com/kong/kubernetes-testing-framework/pkg/clusters" "github.com/kong/kubernete...
{ if err == nil { return } exitOnErrWithCode(err, ExitCodeEnvSetupFailed) }
identifier_body
20.rs
use std::io::{self, BufRead}; use std::collections::HashMap; const IMAGEDIM: usize = 8; type Image = [u16; IMAGEDIM]; // the bool encodes flip #[derive(Debug, Copy, Clone)] enum Orientation { Up(bool), Left(bool), Down(bool), Right(bool), } fn rot_orientation(ori: Orientation) -> Orientation { us...
if false { dump_sea(sea); println!(); } let monster_weight = (MONS0.count_ones() + MONS1.count_ones() + MONS2.count_ones()) as usize; println!("quick check: {}", initial_roughness - monsters.len() * monster_weight); for (y, row) in sea.iter().enumerate() { for c in (0..128...
println!("rouff with monsters {}, {} total", initial_roughness, monsters.len());
random_line_split
20.rs
use std::io::{self, BufRead}; use std::collections::HashMap; const IMAGEDIM: usize = 8; type Image = [u16; IMAGEDIM]; // the bool encodes flip #[derive(Debug, Copy, Clone)] enum Orientation { Up(bool), Left(bool), Down(bool), Right(bool), } fn rot_orientation(ori: Orientation) -> Orientation { us...
} fn flipbits(mut bits: u16) -> u16 { // careful, just the lowest 10 bits, not 16 // 0123456789 // 9876543210 let mut out = 0; for _ in 0..(IMAGEDIM + 2) { out <<= 1; out |= bits & 1; bits >>= 1; } out } // counting from the right, MSB is top fn img_column(image: &...
{ assert!(self.map[pos].is_none()); let x = pos % self.dim; let y = pos / self.dim; if y > 0 && self.bottom_border(self.coord(x, y - 1)).map(|border| border != tile.borders.0).unwrap_or(false) { return false; ...
identifier_body
20.rs
use std::io::{self, BufRead}; use std::collections::HashMap; const IMAGEDIM: usize = 8; type Image = [u16; IMAGEDIM]; // the bool encodes flip #[derive(Debug, Copy, Clone)] enum Orientation { Up(bool), Left(bool), Down(bool), Right(bool), } fn rot_orientation(ori: Orientation) -> Orientation { us...
(&self, pos: usize, tile: &Tile) -> bool { assert!(self.map[pos].is_none()); let x = pos % self.dim; let y = pos / self.dim; if y > 0 && self.bottom_border(self.coord(x, y - 1)).map(|border| border != tile.borders.0).unwrap...
accepts
identifier_name
snapshot_cmd.rs
// Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file is part of Parity Ethereum. // Parity Ethereum 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 yo...
// true, // self.max_round_blocks_to_import, // ); // // client_config.snapshot = self.snapshot_conf; // // let restoration_db_handler = db::restoration_db_handler(&client_path, &client_config); // let client_db = restoration_db_handler.open(&client_path) // .map_err(|e| format!("Failed to open database {:?}"...
random_line_split
snapshot_cmd.rs
// Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file is part of Parity Ethereum. // Parity Ethereum 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 yo...
{ pub cache_config: CacheConfig, pub dirs: Directories, pub spec: SpecType, pub pruning: Pruning, pub pruning_history: u64, pub pruning_memory: usize, pub tracing: Switch, pub fat_db: Switch, // pub compaction: DatabaseCompactionProfile, pub file_path: Option<String>, pub kind: Kind, pub block_at: BlockId, ...
SnapshotCommand
identifier_name
main.py
# -*- coding: utf-8 -*- """HW3_MLDL.ipynb Original file is located at https://colab.research.google.com/drive/1d05ErjIoe4qO3AH9x9qO6YIi_XcV1paT """ # Import models and utils from github import os if not os.path.isdir('./models'): !git clone https://github.com/robertofranceschi/Domain-adaptation-on-PACS-datase...
else : target_dataloader = test_dataloader # art_dataloader ### TRAIN current_step = 0 accuracies_train = [] accuracies_validation = [] loss_class_list = [] loss_target_list = [] loss_source_list = [] # Start iterating over the epochs for epoch in range(NUM_EPOCHS): net.train(True) print(f"--- Epoch {epoc...
target_dataloader = sketch_dataloader
conditional_block
main.py
# -*- coding: utf-8 -*- """HW3_MLDL.ipynb Original file is located at https://colab.research.google.com/drive/1d05ErjIoe4qO3AH9x9qO6YIi_XcV1paT """ # Import models and utils from github import os if not os.path.isdir('./models'): !git clone https://github.com/robertofranceschi/Domain-adaptation-on-PACS-datase...
# Calculate Accuracy accuracy = running_corrects / float(len(art_dataset)) print('\nTest Accuracy (art painting): {} ({} / {})'.format(accuracy, running_corrects, len(art_dataset))) ### Print results if USE_VALIDATION : print(f"Validation on: {transfer_set}") print(f"accuracy_valid: {accuracies_validation[-1]:....
# Update Corrects running_corrects += torch.sum(preds == labels.data).data.item()
random_line_split
evaluate_offline.py
""" 对验证集进行检测,并将检测结果保存,后续使用mAP进行计算。 """ from __future__ import division from models import * from utils.utils import * from utils.datasets import * import os import sys import time import shutil import datetime import argparse import pickle as pkl from PIL import Image import torch from torch.utils.data import DataL...
[:,:,::-1].copy() detections = detections[0].numpy() for i in range(detections.shape[0]): detect = detections[i] label = dict_names_of_class[int(detect[-1])] p1 = (int(detect[0]), int(detect[1])) p2 = (int(detect[2]), int(detect[3])) ...
输出图片大小 ''' h,w = img.shape[:2] #print(h,w) detections = detections[0].numpy() #print(detections.shape) diff_dim = int(np.abs(h - w)/2) scaler = (h / in_dim) if h>w else (w / in_dim) #print('scaler is: ',scaler) #print(detections) for i in r...
identifier_body
evaluate_offline.py
""" 对验证集进行检测,并将检测结果保存,后续使用mAP进行计算。 """ from __future__ import division from models import * from utils.utils import * from utils.datasets import * import os import sys import time import shutil import datetime import argparse import pickle as pkl from PIL import Image import torch from torch.utils.data import DataL...
data_config=path_data_config, path_detection_results=path_detection_results, file_pretrained_weights=path_weights) yolodetect.evalute2(pic_path) if __name__ == "__main__": test1()
yolodetect = YoloDetect(model_def=path_model_def,
random_line_split
evaluate_offline.py
""" 对验证集进行检测,并将检测结果保存,后续使用mAP进行计算。 """ from __future__ import division from models import * from utils.utils import * from utils.datasets import * import os import sys import time import shutil import datetime import argparse import pickle as pkl from PIL import Image import torch from torch.utils.data import DataL...
conditional_block
evaluate_offline.py
""" 对验证集进行检测,并将检测结果保存,后续使用mAP进行计算。 """ from __future__ import division from models import * from utils.utils import * from utils.datasets import * import os import sys import time import shutil import datetime import argparse import pickle as pkl from PIL import Image import torch from torch.utils.data import DataL...
a_config, file_pretrained_weights, path_detection_results, img_size=416, ): self.flag_show = False self.frame = None self.detections = [None] # data_config = parse_data_config...
dat
identifier_name
PMP.py
''' Pipelined Model Parallelism ''' from __future__ import print_function # 这个是python当中让print都以python3的形式进行print,即把print视为函数 import argparse import time import timeit import matplotlib.pyplot as plt import numpy as np import torch import torch.autograd.profiler as profiler import torch.nn as nn import torch.optim a...
cuda:1 s_prev = self.seq2(s_prev) ret.append(self.fc(s_prev.view(s_prev.size(0), -1))) # B. s_next runs on cuda:0, which can run concurrently with A s_prev = self.seq1(s_next).to('cuda:1') s_prev = self.seq2(s_prev) ret.append(self.fc(s_prev.view(s_prev....
uns on
identifier_name
PMP.py
''' Pipelined Model Parallelism ''' from __future__ import print_function # 这个是python当中让print都以python3的形式进行print,即把print视为函数 import argparse import time import timeit import matplotlib.pyplot as plt import numpy as np import torch import torch.autograd.profiler as profiler import torch.nn as nn import torch.optim a...
print(prof.key_averages(group_by_input_shape=True).table(sort_by="cpu_time_total", row_limit=10)) prof.export_chrome_trace(dir_name + "/profiler/PMP_inference_profiler_cpu.json") def train_time(model): num_batches = 3 batch_size = 120 image_w = 128 image_h = 128 num_classes = 1000 ...
batch_size)) else:
random_line_split
PMP.py
''' Pipelined Model Parallelism ''' from __future__ import print_function # 这个是python当中让print都以python3的形式进行print,即把print视为函数 import argparse import time import timeit import matplotlib.pyplot as plt import numpy as np import torch import torch.autograd.profiler as profiler import torch.nn as nn import torch.optim a...
/runs/PMP') data_iter = iter(train_loader) images, labels = data_iter.next() images = images.cuda() writer.add_graph(model, images) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum) train_acc_i = [] train_acc_list = [] a = [] ac_list = [] ...
s_prev = self.seq2(s_prev) ret.append(self.fc(s_prev.view(s_prev.size(0), -1))) return torch.cat(ret) model = PipelineParallelResNet50() if not args.no_tensorboard: writer = SummaryWriter('.
conditional_block
PMP.py
''' Pipelined Model Parallelism ''' from __future__ import print_function # 这个是python当中让print都以python3的形式进行print,即把print视为函数 import argparse import time import timeit import matplotlib.pyplot as plt import numpy as np import torch import torch.autograd.profiler as profiler import torch.nn as nn import torch.optim a...
. s_prev runs on cuda:1 s_prev = self.seq2(s_prev) ret.append(self.fc(s_prev.view(s_prev.size(0), -1))) # B. s_next runs on cuda:0, which can run concurrently with A s_prev = self.seq1(s_next).to('cuda:1') s_prev = self.seq2(s_prev) ret.append(self.fc(s_...
rev = self.seq1(s_next).to('cuda:1') ret = [] for s_next in splits: # A
identifier_body