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 |
|---|---|---|---|---|
lib.rs | #[macro_use]
extern crate compre_combinee;
extern crate combine;
mod errors;
mod details;
mod traits;
mod stop_watch;
use std::collections::{HashMap};
use combine::{parser, eof, satisfy, choice, attempt};
use combine::parser::range::{take_while1};
use combine::parser::char::*;
use combine::{Parser, many, optional, sk... |
fn null_parser<'a>() -> impl Parser<&'a str, Output = Node> {
c_hx_do!{
_word <- string("null");
Node::Null
}
}
macro_rules! ref_parser {
($parser_fn:ident) => {
parser(|input| {
let _: &mut &str = input;
$parser_fn().parse_stream(input).into_result()
... | {
c_hx_do!{
word <- string("true").or(string("false"));
match word {
"true" => Node::Boolean(true),
_ => Node::Boolean(false)
}
}
} | identifier_body |
lib.rs | #[macro_use]
extern crate compre_combinee;
extern crate combine;
mod errors;
mod details;
mod traits;
mod stop_watch;
use std::collections::{HashMap};
use combine::{parser, eof, satisfy, choice, attempt};
use combine::parser::range::{take_while1};
use combine::parser::char::*;
use combine::{Parser, many, optional, sk... | <'a>() -> impl Parser<&'a str, Output = Node> {
c_hx_do!{
word <- string("true").or(string("false"));
match word {
"true" => Node::Boolean(true),
_ => Node::Boolean(false)
}
}
}
fn null_parser<'a>() -> impl Parser<&'a str, Output = Node> {
c_hx_do!{
_... | bool_parser | identifier_name |
main.rs | // ~Similar to the ST Heart Rate Sensor example
#![no_main]
#![no_std]
#![allow(non_snake_case)]
use panic_rtt_target as _;
// use panic_halt as _;
use rtt_target::{rprintln, rtt_init_print};
use stm32wb_hal as hal;
use core::time::Duration;
use cortex_m_rt::{entry, exception};
use nb::block;
use byteorder::{ByteOr... | extended_packet_length_enable: 1,
pr_write_list_size: 0x3A,
mb_lock_count: 0x79,
att_mtu: 312,
slave_sca: 500,
master_sca: 0,
ls_source: 1,
max_conn_event_length: 0xFFFFFFFF,
hs_startup_time: 0x148,
viterbi_enable: 1,
ll_only: 0,
... | num_attr_serv: 10,
attr_value_arr_size: 3500, //2788,
num_of_links: 8, | random_line_split |
main.rs | // ~Similar to the ST Heart Rate Sensor example
#![no_main]
#![no_std]
#![allow(non_snake_case)]
use panic_rtt_target as _;
// use panic_halt as _;
use rtt_target::{rprintln, rtt_init_print};
use stm32wb_hal as hal;
use core::time::Duration;
use cortex_m_rt::{entry, exception};
use nb::block;
use byteorder::{ByteOr... | else {
rprintln!("Unexpected response to init_gap command");
return Err(());
};
perform_command(|rc| {
rc.update_characteristic_value(&UpdateCharacteristicValueParameters {
service_handle,
characteristic_handle: dev_name_handle,
offset: 0,
... | {
(service_handle, dev_name_handle, appearance_handle)
} | conditional_block |
main.rs | // ~Similar to the ST Heart Rate Sensor example
#![no_main]
#![no_std]
#![allow(non_snake_case)]
use panic_rtt_target as _;
// use panic_halt as _;
use rtt_target::{rprintln, rtt_init_print};
use stm32wb_hal as hal;
use core::time::Duration;
use cortex_m_rt::{entry, exception};
use nb::block;
use byteorder::{ByteOr... | () -> BdAddr {
let mut bytes = [0u8; 6];
let lhci_info = LhciC1DeviceInformationCcrp::new();
bytes[0] = (lhci_info.uid64 & 0xff) as u8;
bytes[1] = ((lhci_info.uid64 >> 8) & 0xff) as u8;
bytes[2] = ((lhci_info.uid64 >> 16) & 0xff) as u8;
bytes[3] = lhci_info.device_type_id;
bytes[4] = (lhci_... | get_bd_addr | identifier_name |
main.rs | // ~Similar to the ST Heart Rate Sensor example
#![no_main]
#![no_std]
#![allow(non_snake_case)]
use panic_rtt_target as _;
// use panic_halt as _;
use rtt_target::{rprintln, rtt_init_print};
use stm32wb_hal as hal;
use core::time::Duration;
use cortex_m_rt::{entry, exception};
use nb::block;
use byteorder::{ByteOr... |
const DISCOVERY_PARAMS: DiscoverableParameters = DiscoverableParameters {
advertising_type: AdvertisingType::ConnectableUndirected,
advertising_interval: Some((
Duration::from_millis(ADV_INTERVAL_MS),
Duration::from_millis(ADV_INTERVAL_MS),
)),
address_type: OwnAddressType::Public,
... | {
EncryptionKey(BLE_CFG_ERK)
} | identifier_body |
main.rs | // Rust notes
fn main () {
let mut x = String::from("Hey there");
let mut y = String::from("Hello dawg woof");
println!("{}",first_word(&x));
println!("{}",second_word(&y));
}
fn | (x : &String) -> &str {
let bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &x[0..i];
}
}
&x[..]
}
fn second_word(x : &String) -> &str {
let mut bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' '{
let y = &x[i+1..];
byt... | first_word | identifier_name |
main.rs | // Rust notes
fn main () {
let mut x = String::from("Hey there");
let mut y = String::from("Hello dawg woof");
println!("{}",first_word(&x));
println!("{}",second_word(&y));
}
fn first_word(x : &String) -> &str |
fn second_word(x : &String) -> &str {
let mut bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' '{
let y = &x[i+1..];
bytes = y.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &y[0..i];
}
}
// Return this IF there were ... | {
let bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &x[0..i];
}
}
&x[..]
} | identifier_body |
main.rs | // Rust notes
fn main () {
let mut x = String::from("Hey there");
let mut y = String::from("Hello dawg woof");
println!("{}",first_word(&x));
println!("{}",second_word(&y));
}
fn first_word(x : &String) -> &str {
let bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
retu... | &x[..]
}
fn second_word(x : &String) -> &str {
let mut bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' '{
let y = &x[i+1..];
bytes = y.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &y[0..i];
}
}
// Return this IF th... | random_line_split | |
main.rs | // Rust notes
fn main () {
let mut x = String::from("Hey there");
let mut y = String::from("Hello dawg woof");
println!("{}",first_word(&x));
println!("{}",second_word(&y));
}
fn first_word(x : &String) -> &str {
let bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
retu... |
}
&x[..]
}
//__________________________________________________________________________________________________________ //
//--------------------------------------------------//
//*** GENERAL NOTES ***
//*** Info: Random Notes I found either important, ***
//*** hard to remember, funny, coo... | {
let y = &x[i+1..];
bytes = y.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &y[0..i];
}
}
// Return this IF there were only two words.
return &y[..];
} | conditional_block |
SocialSpiderAlgorithm.py | import math
import numpy as np
from numpy import linalg as la
import random
from termcolor import colored
import matplotlib.pyplot as plt
Minimize_problem = True
Maximize_problem = False
class Spider:
def __init__(self, s, s_previous, fs, vibration, cs, mask):
self.s = s # The position of s on the web.
... |
# Sphere function minimum = 0
def test_function_0():
global c, ra, pc, pm, y, n, population, bounds, lim
c = 1E-100 # where C is a small constant such fitness values are larger than C
set_ra = {1 / 10, 1 / 5, 1 / 4, 1 / 3, 1 / 2, 1, 2, 3, 4, 5}
ra = random.choice(tuple(set_ra))
set_pc_and_pm = {... | lobal spiders
spiders = []
create_population_of_spiders()
minimize = spiders[0].s
number_of_iterations = 0
initialization_graphics(graph)
# In the iteration phase
while number_of_iterations <= lim:
# Calculates the fitness , update the global optimum and generate vibrations
g... | identifier_body |
SocialSpiderAlgorithm.py | import math
import numpy as np
from numpy import linalg as la
import random
from termcolor import colored
import matplotlib.pyplot as plt
Minimize_problem = True
Maximize_problem = False
class Spider:
def __init__(self, s, s_previous, fs, vibration, cs, mask):
self.s = s # The position of s on the web.
... | a):
z = []
if Minimize_problem:
z.extend(a)
return eval(y)
elif Maximize_problem:
z.extend(-a)
return -eval(y)
# there is a array with 100 elements with one and zero,100*p elements with 0 , 100(1-p) with 1,0=false,1=true
# where p is the probability
def probability(p):
... | ( | identifier_name |
SocialSpiderAlgorithm.py | import math
import numpy as np
from numpy import linalg as la
import random
from termcolor import colored
import matplotlib.pyplot as plt
Minimize_problem = True
Maximize_problem = False
class Spider:
def __init__(self, s, s_previous, fs, vibration, cs, mask):
self.s = s # The position of s on the web.
... | set_pc_and_pm = {0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.99}
pc = random.choice(tuple(set_pc_and_pm))
pm = random.choice(tuple(set_pc_and_pm))
print('\n'+"ra = " + str(ra) + '\n' + "pc = " + str(pc) + " pm = " + str(pm) + '\n')
y = "math.sin(z[0] + z[1]) + (z[0] - z[1])**2 - 1.5 * z[0]... | random_line_split | |
SocialSpiderAlgorithm.py | import math
import numpy as np
from numpy import linalg as la
import random
from termcolor import colored
import matplotlib.pyplot as plt
Minimize_problem = True
Maximize_problem = False
class Spider:
def __init__(self, s, s_previous, fs, vibration, cs, mask):
self.s = s # The position of s on the web.
... | else:
return False
def show(generate_vibration):
for x in range(population):
print("")
print("spider" + str(x))
spiders[x].printout()
print("generate vibration = " + str(generate_vibration[x].intensity))
print("")
# if return true then it is out of bounds [a,b... | eturn True
| conditional_block |
__init__.py | import collections
import os
import abc
import copy
import datetime
import logging
import munge
from future.utils import with_metaclass
from vaping.config import parse_interval
import vaping.io
class PluginBase(vaping.io.Thread):
"""
Base plugin interface
# Instanced Attributes
- config (`dict`): p... | If it doesnt, because file has been deleted, we close
the filehander and try to reopen
"""
if self.fh.closed:
try:
self.fh = open(self.path, "r")
self.fh.seek(0, 2)
except OSError as err:
logging.error("Could not reo... | random_line_split | |
__init__.py | import collections
import os
import abc
import copy
import datetime
import logging
import munge
from future.utils import with_metaclass
from vaping.config import parse_interval
import vaping.io
class PluginBase(vaping.io.Thread):
"""
Base plugin interface
# Instanced Attributes
- config (`dict`): p... | (self, filename, from_time, to_time):
"""
Retrieve data from database for the specified
timespan
**Arguments**
- filename (`str`): database filename
- from_time (`int`): epoch timestamp start
- to_time (`int`): epoch timestamp end
"""
raise NotIm... | get | identifier_name |
__init__.py | import collections
import os
import abc
import copy
import datetime
import logging
import munge
from future.utils import with_metaclass
from vaping.config import parse_interval
import vaping.io
class PluginBase(vaping.io.Thread):
"""
Base plugin interface
# Instanced Attributes
- config (`dict`): p... |
emit = self._emit_queue.get()
emit()
def emit_all(self):
"""
emit and remove all emissions in the queue
"""
while not self._emit_queue.empty():
self.send_emission()
class TimedProbe(ProbeBase):
"""
Probe class that calls probe every config defi... | return | conditional_block |
__init__.py | import collections
import os
import abc
import copy
import datetime
import logging
import munge
from future.utils import with_metaclass
from vaping.config import parse_interval
import vaping.io
class PluginBase(vaping.io.Thread):
"""
Base plugin interface
# Instanced Attributes
- config (`dict`): p... |
@abc.abstractmethod
def emit(self, message):
""" accept message to emit """
class TimeSeriesDB(EmitBase):
"""
Base interface for timeseries db storage plugins
# Config
- filename (`str`): database file name template
- field (`str`): fieeld name to read the value from
# Ins... | super(EmitBase, self).__init__(config, ctx) | identifier_body |
integratedAnalysisPipeline.py | from generateIntegratedConfigurationFiles import generateIntAnalysisConfig
import subprocess, os, shutil, sys
from multiprocessing import Pool
"""
try:
import syntenyFinal
except:
print'cannot find syntenyFinal analysis'
exit()
try:
import circosFiguresPipeline
except:
print'cannot find circos analy... | (stringFind,configFile):
"""findPath will find path or value of associated specified string or info from config file"""
for line in configFile:
if stringFind in line: # if find string specified, return pathname or specific value trying to find
configFile.seek(0)
return line.split... | parseConfigFindPath | identifier_name |
integratedAnalysisPipeline.py | from generateIntegratedConfigurationFiles import generateIntAnalysisConfig
import subprocess, os, shutil, sys
from multiprocessing import Pool
"""
try:
import syntenyFinal
except:
print'cannot find syntenyFinal analysis'
exit()
try:
import circosFiguresPipeline
except:
print'cannot find circos analy... | try:
int(BPsMergeDist)
except:
BPsMergeDist = '100000'
# write syntenic Config text
generateIntAnalysisConfig('syntenyAnalysis',(NameAnalysis,writeFastaOut,Loci_Threshold,pathPython,pathUnOut,pathSort, BPsMergeDist,softmask,
NameAnalysis,multipleSeqAlignFastasPath,s... | random_line_split | |
integratedAnalysisPipeline.py | from generateIntegratedConfigurationFiles import generateIntAnalysisConfig
import subprocess, os, shutil, sys
from multiprocessing import Pool
"""
try:
import syntenyFinal
except:
print'cannot find syntenyFinal analysis'
exit()
try:
import circosFiguresPipeline
except:
print'cannot find circos analy... |
# perform allmaps but not circos
elif int(performALLMAPS) and not int(performCircos):
print 'allmaps'
#os.chdir(pathALLMAPS)
# if online
if int(online):
# try to run allmaps
allmap = open('runAllmaps.sh', 'w')
allmap.write( '#!/bin/bash\ncd %s\npython createNewGenome.py'%pathAL... | print 'circos'
# try to run circos online
if int(online):
open('runCircos.sh', 'w').close()
# writing shell script to run circos
circos = open('runCircos.sh', 'w')
circos.write('#!/bin/bash\npython circosFiguresPipeline.py')
circos.close()
try:
# try t... | conditional_block |
integratedAnalysisPipeline.py | from generateIntegratedConfigurationFiles import generateIntAnalysisConfig
import subprocess, os, shutil, sys
from multiprocessing import Pool
"""
try:
import syntenyFinal
except:
print'cannot find syntenyFinal analysis'
exit()
try:
import circosFiguresPipeline
except:
print'cannot find circos analy... |
def parseConfigFindPath(stringFind,configFile):
"""findPath will find path or value of associated specified string or info from config file"""
for line in configFile:
if stringFind in line: # if find string specified, return pathname or specific value trying to find
configFile.seek(0)
... | """parseConfigFindList inputs a particular string to find and read file after and a configuration file object
outputs list of relevant filenames"""
read = 0
listOfItems = []
for line in configFile:
if line:
if read == 1:
if 'Stop' in line:
configFi... | identifier_body |
vector_test.go | // Author: slowpoke <proxypoke at lavabit dot com>
// Repository: https://gist.github.com/proxypoke/vector
//
// This program is free software under the non-terms
// of the Anti-License. Do whatever the fuck you want.
package vector
import (
"math"
"math/rand"
"testing"
)
// ========================== [ Construct... | (t *testing.T) {
var i, j uint
for i = 0; i < 100; i++ {
randslice := makeRandSlice(i)
v := NewFrom(randslice)
if v.Dim() != i {
t.Errorf("Wrong dimension. Got %d, expected %d.", v.Dim(), i)
}
for j = 0; j < i; j++ {
val, _ := v.Get(j)
if val != randslice[j] {
t.Error(
"Wrong values in vec... | TestNewFrom | identifier_name |
vector_test.go | // Author: slowpoke <proxypoke at lavabit dot com>
// Repository: https://gist.github.com/proxypoke/vector
//
// This program is free software under the non-terms
// of the Anti-License. Do whatever the fuck you want.
package vector
import (
"math"
"math/rand"
"testing"
)
// ========================== [ Construct... | // then as an in-place operations, checking if both operation were correct.
func TestAdd(t *testing.T) {
var i, j uint
for i = 1; i < 100; i++ {
a := makeRandomVector(i)
b := makeRandomVector(i)
c, _ := Add(a, b)
for j = 0; j < i; j++ {
if c.dims[j] != a.dims[j]+b.dims[j] {
t.Error("Addition failed, d... | // =========================== [ Operation Tests ] ============================
// Creates pesudo-random vectors, then adds them first as a non-destructive, | random_line_split |
vector_test.go | // Author: slowpoke <proxypoke at lavabit dot com>
// Repository: https://gist.github.com/proxypoke/vector
//
// This program is free software under the non-terms
// of the Anti-License. Do whatever the fuck you want.
package vector
import (
"math"
"math/rand"
"testing"
)
// ========================== [ Construct... | pseudo-random Vector with dimension dim.
func makeRandomVector(dim uint) *Vector {
return NewFrom(makeRandSlice(dim))
}
| , length)
for i := range randslice {
randslice[i] = rand.ExpFloat64()
}
return
}
// Helper function, make a | identifier_body |
vector_test.go | // Author: slowpoke <proxypoke at lavabit dot com>
// Repository: https://gist.github.com/proxypoke/vector
//
// This program is free software under the non-terms
// of the Anti-License. Do whatever the fuck you want.
package vector
import (
"math"
"math/rand"
"testing"
)
// ========================== [ Construct... |
}
// =========================== [ Operation Tests ] ============================
// Creates pesudo-random vectors, then adds them first as a non-destructive,
// then as an in-place operations, checking if both operation were correct.
func TestAdd(t *testing.T) {
var i, j uint
for i = 1; i < 100; i++ {
a := make... | {
t.Error("Equal() == true for unequal vectors.")
} | conditional_block |
preprocessing.py | # Globals #
import numpy as np
import pandas as pd
import dateutil.parser as dp
from itertools import islice
from scipy.stats import boxcox
from scipy.integrate import simps
from realtime_talib import Indicator
from sklearn.model_selection import train_test_split
from sklearn.utils import resample
from pprint import ... |
def power_transform(dataset):
print("\tApplying a box-cox transform to selected features")
for header in dataset.drop(["Date", "Trend"], axis=1).columns:
if not (dataset[header] < 0).any() and not (dataset[header] == 0).any():
dataset[header] = boxcox(dataset[header])[0]
return dataset
def split(dataset,... | print("\tAdding lag variables")
new_df_dict = {}
for col_header in dataset.drop(["Date", "Trend"], axis=1):
new_df_dict[col_header] = dataset[col_header]
for lag in range(1, lag + 1):
new_df_dict["%s_lag%d" % (col_header, lag)] = dataset[col_header].shift(-lag)
new_df = pd.DataFrame(new_df_dict, index=datas... | identifier_body |
preprocessing.py | # Globals #
import numpy as np
import pandas as pd
import dateutil.parser as dp
from itertools import islice
from scipy.stats import boxcox
from scipy.integrate import simps
from realtime_talib import Indicator
from sklearn.model_selection import train_test_split
from sklearn.utils import resample
from pprint import ... |
def integral_transform(dataset, interval):
integral = integrate(list(dataset["Sentiment"]), interval)
dataset["Sentiment_integrals"] = pd.Series(integral) | if balanced:
return balanced_split(dataset, test_size)
else:
return unbalanced_split(dataset, test_size) | random_line_split |
preprocessing.py | # Globals #
import numpy as np
import pandas as pd
import dateutil.parser as dp
from itertools import islice
from scipy.stats import boxcox
from scipy.integrate import simps
from realtime_talib import Indicator
from sklearn.model_selection import train_test_split
from sklearn.utils import resample
from pprint import ... | (headlines):
sentiment_scores = {}
numer, denom = 0.0, 0.0
for index, currRow in headlines.iterrows():
print(currRow)
currDate = currRow["Date"]
if currDate in sentiment_scores:
pass
else:
numer = currRow["Sentiment"] * currRow["Tweets"]
denom = currRow["Tweets"]
for index, nextRow in headlines.... | calculate_sentiment | identifier_name |
preprocessing.py | # Globals #
import numpy as np
import pandas as pd
import dateutil.parser as dp
from itertools import islice
from scipy.stats import boxcox
from scipy.integrate import simps
from realtime_talib import Indicator
from sklearn.model_selection import train_test_split
from sklearn.utils import resample
from pprint import ... |
else:
break
sentiment_scores[currDate] = numer / denom
numer, denom = 0.0, 0.0
sentiment_scores_df = pd.DataFrame(list(sentiment_scores.items()), columns=["Date", "Sentiment"])
return sentiment_scores_df
def merge_datasets(origin, other_sets):
print("\tMerging datasets")
merged = origin
for s... | numer += (nextRow["Sentiment"] * nextRow["Tweets"])
denom += nextRow["Tweets"] | conditional_block |
networking.go | /*
<!--
Copyright (c) 2016 Christoph Berger. Some rights reserved.
Use of this text is governed by a Creative Commons Attribution Non-Commercial
Share-Alike License that can be found in the LICENSE.txt file.
The source code contained in this file may import third-party source code
whose licenses are provided in... |
log.Println("Flush the buffer.")
err = rw.Flush()
if err != nil {
return errors.Wrap(err, "Flush failed.")
}
// Read the reply.
log.Println("Read the reply.")
response, err := rw.ReadString('\n')
if err != nil {
return errors.Wrap(err, "Client: Failed to read the reply: '"+response+"'")
}
... | {
return errors.Wrap(err, "Could not send additional STRING data ("+strconv.Itoa(n)+" bytes written)")
} | conditional_block |
networking.go | /*
<!--
Copyright (c) 2016 Christoph Berger. Some rights reserved.
Use of this text is governed by a Creative Commons Attribution Non-Commercial
Share-Alike License that can be found in the LICENSE.txt file.
The source code contained in this file may import third-party source code
whose licenses are provided in... | * It dispatches incoming commands to the associated handler based on the commands
name.
*/
// HandleFunc is a function that handles an incoming command.
// It receives the open connection wrapped in a `ReadWriter` interface.
type HandleFunc func(*bufio.ReadWriter)
// Endpoint provides an endpoint to other... | The nature of the data depends on the respective command. To handle this, we
create an `Endpoint` object with the following properties:
* It allows to register one or more handler functions, where each can handle a
particular command.
| random_line_split |
networking.go | /*
<!--
Copyright (c) 2016 Christoph Berger. Some rights reserved.
Use of this text is governed by a Creative Commons Attribution Non-Commercial
Share-Alike License that can be found in the LICENSE.txt file.
The source code contained in this file may import third-party source code
whose licenses are provided in... |
// The Lshortfile flag includes file name and line number in log messages.
func init() {
log.SetFlags(log.Lshortfile)
}
/*
## How to get and run the code
Step 1: `go get` the code. Note the `-d` flag that prevents auto-installing
the binary into `$GOPATH/bin`.
go get -d github.com/appliedgo/netwo... | {
connect := flag.String("connect", "", "IP address of process to join. If empty, go into listen mode.")
flag.Parse()
// If the connect flag is set, go into client mode.
if *connect != "" {
err := client(*connect)
if err != nil {
log.Println("Error:", errors.WithStack(err))
}
log.Println("Clie... | identifier_body |
networking.go | /*
<!--
Copyright (c) 2016 Christoph Berger. Some rights reserved.
Use of this text is governed by a Creative Commons Attribution Non-Commercial
Share-Alike License that can be found in the LICENSE.txt file.
The source code contained in this file may import third-party source code
whose licenses are provided in... | (ip string) error {
// Some test data. Note how GOB even handles maps, slices, and
// recursive data structures without problems.
testStruct := complexData{
N: 23,
S: "string data",
M: map[string]int{"one": 1, "two": 2, "three": 3},
P: []byte("abc"),
C: &complexData{
N: 256,
S: "Recursive s... | client | identifier_name |
model_seq.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Identify and label symptom phrases in narrative
import sys
sys.path.append('/u/sjeblee/research/va/git/verbal-autopsy')
import data_util
import models_pytorch
import word2vec
import xmltoseq
from keras.models import Model
from keras.layers import Input, GRU, LSTM, Dense, Dr... |
elif lab in e_labels:
time_seq.append('O')
event_seq.append(lab)
else:
time_seq.append(lab)
event_seq.append(lab)
y_time.append(time_seq)
y_event.append(event_seq)
return y_time, y_event
'''
Get word vectors... | time_seq.append(lab)
event_seq.append('O') | conditional_block |
model_seq.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Identify and label symptom phrases in narrative
import sys
sys.path.append('/u/sjeblee/research/va/git/verbal-autopsy')
import data_util
import models_pytorch
import word2vec
import xmltoseq
from keras.models import Model
from keras.layers import Input, GRU, LSTM, Dense, Dr... | (encoder_model, decoder_model, testx, output_seq_len, output_dim, vec_labels=False):
testy_pred = []
print "output_seq_len: " + str(output_seq_len)
print "output_dim: " + str(output_dim)
print "vec_labels: " + str(vec_labels)
for test_seq in testx:
input_seq = []
input_seq.append(tes... | predict_seqs | identifier_name |
model_seq.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Identify and label symptom phrases in narrative
import sys
sys.path.append('/u/sjeblee/research/va/git/verbal-autopsy')
import data_util
import models_pytorch
import word2vec
import xmltoseq
from keras.models import Model
from keras.layers import Input, GRU, LSTM, Dense, Dr... |
def sent2tokens(sent):
return [token for token, label in sent]
def ispunc(input_string, start, end):
punc = ' :;,./?'
s = input_string[start:end]
for char in s:
if char not in punc:
return False
return True
if __name__ == "__main__":main()
| return [label for token, label in sent] | identifier_body |
model_seq.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Identify and label symptom phrases in narrative
import sys
sys.path.append('/u/sjeblee/research/va/git/verbal-autopsy')
import data_util
import models_pytorch
import word2vec
import xmltoseq
from keras.models import Model
from keras.layers import Input, GRU, LSTM, Dense, Dr... | #'postag[:2]': postag[:2],
}
if i > 0:
word1 = sent[i-1][0]
postag1 = sent[i-1][1]
features.update({
'-1:word.lower()': word1.lower(),
'-1:word.istitle()': word1.istitle(),
'-1:word.isupper()': word1.isupper(),
#'-1:postag': postag1... | 'word.isdigit()': word.isdigit(),
#'postag': postag, | random_line_split |
ChoiceSet.js | /**
* ChoiceSet is a weighted random solution that allows the each of the
* items that are being chosen to have simply a name or full suite of
* values other than their weights and names.
*
* Once the items have been setup with a name and weight, the system works
* by creating a one to one array. Each item in the... |
/**
* Simulates rolling dice with n-number of sides. In pen and paper
* role-playing games, 3d6 means to roll three six sided dice together
* and sum their results. Calling ChoiceSet.rollDice(3, 6) will simulate
* the same effect.
*
* Optionally, if repeat is set to a number greater than 1, an arr... | {
let choices = [];
for (let i = 0; i < count; i++) {
choices.push(this.chooseProp(prop))
}
return choices;
} | identifier_body |
ChoiceSet.js | /**
* ChoiceSet is a weighted random solution that allows the each of the
* items that are being chosen to have simply a name or full suite of
* values other than their weights and names.
*
* Once the items have been setup with a name and weight, the system works
* by creating a one to one array. Each item in the... | }
/**
* Allows easy adjustment of a weight for a given index. The weight is
* modified and then calcIntervals() is called to realign things for
* the next choosing.
*
* NOTE see if this is the optimal setting for adjusting the weights
*
* @param {Number} index the index of the choice to modify... | return cur + array.slice(0,idx).reduce((p, c) => p + c, 0);
});
this.intervals = intervals;
this.maxInterval = intervals[intervals.length - 1]; | random_line_split |
ChoiceSet.js | /**
* ChoiceSet is a weighted random solution that allows the each of the
* items that are being chosen to have simply a name or full suite of
* values other than their weights and names.
*
* Once the items have been setup with a name and weight, the system works
* by creating a one to one array. Each item in the... |
}
if (index === -1) {
console.log('ERROR');
console.log(roll, index);
}
return this.choices[index];
}
/**
* Using the probability counts on http://www.anydice.com in
* conjunction with rolling 3 six sided dice and adding their
* results, you can achieve a more realistically ... | {
index = i;
break;
} | conditional_block |
ChoiceSet.js | /**
* ChoiceSet is a weighted random solution that allows the each of the
* items that are being chosen to have simply a name or full suite of
* values other than their weights and names.
*
* Once the items have been setup with a name and weight, the system works
* by creating a one to one array. Each item in the... | (prop = 'name')
{
return this.chooseProp(prop);
}
/**
* Returns an array of results equivalent to those returned by
* chooseOne.
*
* @param {Number} count an integer denoting the number of choices to pick
* @param {String} prop the property of the randomly chosen item
* @return {Mixed} the ... | chooseOne | identifier_name |
canvas.go | // Copyright 2012 - 2018 The ASCIIToSVG Contributors
// All rights reserved.
package asciitosvg
import (
"bytes"
"encoding/json"
"fmt"
"image"
"regexp"
"sort"
"strconv"
"unicode/utf8"
)
// Canvas provides methods for returning objects from an underlying textual grid.
type Canvas interface {
// A canvas has ... |
// findObjects finds all objects (lines, polygons, and text) within the underlying grid.
func (c *canvas) findObjects() {
p := Point{}
// Find any new paths by starting with a point that wasn't yet visited, beginning at the top
// left of the grid.
for y := 0; y < c.size.Y; y++ {
p.Y = y
for x := 0; x < c.si... | {
maxTL := Point{X: -1, Y: -1}
var q []Object
for _, o := range c.objects {
// An object can't really contain another unless it is a polygon.
if !o.IsClosed() {
continue
}
if o.HasPoint(p) && o.Corners()[0].X > maxTL.X && o.Corners()[0].Y > maxTL.Y {
q = append(q, o)
maxTL.X = o.Corners()[0].X
... | identifier_body |
canvas.go | // Copyright 2012 - 2018 The ASCIIToSVG Contributors
// All rights reserved.
package asciitosvg
import (
"bytes"
"encoding/json"
"fmt"
"image"
"regexp"
"sort"
"strconv"
"unicode/utf8"
)
// Canvas provides methods for returning objects from an underlying textual grid.
type Canvas interface {
// A canvas has ... |
// Trim the right side of the text object.
for len(obj.points) != 0 && c.at(obj.points[len(obj.points)-1]).isSpace() {
obj.points = obj.points[:len(obj.points)-1]
}
obj.seal(c)
return obj
}
func (c *canvas) at(p Point) char {
return c.grid[p.Y*c.size.X+p.X]
}
func (c *canvas) isVisited(p Point) bool {
retu... | obj.SetTag(t)
c.options[t] = m.(map[string]interface{})
} | random_line_split |
canvas.go | // Copyright 2012 - 2018 The ASCIIToSVG Contributors
// All rights reserved.
package asciitosvg
import (
"bytes"
"encoding/json"
"fmt"
"image"
"regexp"
"sort"
"strconv"
"unicode/utf8"
)
// Canvas provides methods for returning objects from an underlying textual grid.
type Canvas interface {
// A canvas has ... | (p Point) {
o := p.Y*c.size.X + p.X
if !c.visited[o] {
panic(fmt.Errorf("internal error: point %+v never visited", p))
}
c.visited[o] = false
}
func (c *canvas) canLeft(p Point) bool {
return p.X > 0
}
func (c *canvas) canRight(p Point) bool {
return p.X < c.size.X-1
}
func (c *canvas) canUp(p Point) bool {
... | unvisit | identifier_name |
canvas.go | // Copyright 2012 - 2018 The ASCIIToSVG Contributors
// All rights reserved.
package asciitosvg
import (
"bytes"
"encoding/json"
"fmt"
"image"
"regexp"
"sort"
"strconv"
"unicode/utf8"
)
// Canvas provides methods for returning objects from an underlying textual grid.
type Canvas interface {
// A canvas has ... |
return objs
}
// The next returns the points that can be used to make progress, scanning (in order) horizontal
// progress to the left or right, vertical progress above or below, or diagonal progress to NW,
// NE, SW, and SE. It skips any points already visited, and returns all of the possible progress
// points.
fu... | {
if c.isVisited(n) {
continue
}
c.visit(n)
p2 := make([]Point, len(points)+1)
copy(p2, points)
p2[len(p2)-1] = n
objs = append(objs, c.scanPath(p2)...)
} | conditional_block |
client.rs | use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
use std::cmp;
use rand::{Rng, OsRng};
use alert;
use tls_result::{TlsResult, TlsError, TlsErrorKind};
use tls_result::TlsErrorKind::{UnexpectedMessage, InternalError, DecryptError, IllegalParameter};
use util::{SurugaError, crypto_compare};
use cipher::{se... | (&mut self, buf: &[u8]) -> io::Result<()> {
let result = self.writer.write_application_data(buf);
match result {
Ok(()) => Ok(()),
Err(err) => {
let err = self.send_tls_alert(err);
// FIXME more verbose io error
Err(io::Error::new(i... | write_all | identifier_name |
client.rs | use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
use std::cmp;
use rand::{Rng, OsRng};
use alert;
use tls_result::{TlsResult, TlsError, TlsErrorKind};
use tls_result::TlsErrorKind::{UnexpectedMessage, InternalError, DecryptError, IllegalParameter};
use util::{SurugaError, crypto_compare};
use cipher::{se... | try!(self.writer.write_handshake(&client_key_exchange));
try!(self.writer.write_change_cipher_spec());
// SECRET
let master_secret = {
let mut label_seed = b"master secret".to_vec();
label_seed.extend(&cli_random);
label_seed.extend(&server_hello_dat... | random_line_split | |
client.rs | use std::io;
use std::io::prelude::*;
use std::net::TcpStream;
use std::cmp;
use rand::{Rng, OsRng};
use alert;
use tls_result::{TlsResult, TlsError, TlsErrorKind};
use tls_result::TlsErrorKind::{UnexpectedMessage, InternalError, DecryptError, IllegalParameter};
use util::{SurugaError, crypto_compare};
use cipher::{se... |
impl<R: Read, W: Write> Read for TlsClient<R, W> {
// if ssl connection is failed, return `EndOfFile`.
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let mut pos: usize = 0;
let len = buf.len();
while pos < len {
let remaining = len - pos;
if self.buf... | {
to.write(from).unwrap()
} | identifier_body |
analysis.py | #Mkhanyisi Gamedze
# CS 251 - Spring 2017
# project 2
# global fields
import sys
import numpy as np
import csv
import data
import scipy.stats
import scipy.cluster.vq as vq
import random
# functions
def range_(headers, data):
""" Takes in a list of column headers and the Data object and returns a list of 2-element ... | (A, means):
# set up some useful constants
MIN_CHANGE = 1e-7
MAX_ITERATIONS = 100
D = means.shape[1]
K = means.shape[0]
N = A.shape[0]
# iterate no more than MAX_ITERATIONS
for i in range(MAX_ITERATIONS):
# calculate the codes
codes, errors = kmeans_classify( A, means )
# calculate the new means
newme... | kmeans_algorithm | identifier_name |
analysis.py | #Mkhanyisi Gamedze
# CS 251 - Spring 2017
# project 2
# global fields
import sys
import numpy as np
import csv
import data
import scipy.stats
import scipy.cluster.vq as vq
import random
# functions
def range_(headers, data):
""" Takes in a list of column headers and the Data object and returns a list of 2-element ... |
column_max=column_matrix.max(1)
column_min=column_matrix.min(1)
final=np.concatenate((column_min, column_max), axis=1)
rng=final.tolist()
return rng
def mean(headers, data):
""" Takes in a list of column headers and the Data object and returns a list of the
mean values for each column. Use the built-in num... | print "wrong headers, not present in data Object"
return [] | conditional_block |
analysis.py | #Mkhanyisi Gamedze
# CS 251 - Spring 2017
# project 2
# global fields
import sys
import numpy as np
import csv
import data
import scipy.stats
import scipy.cluster.vq as vq
import random
# functions
def range_(headers, data):
""" Takes in a list of column headers and the Data object and returns a list of 2-element ... | index=index+1
#the projected data
pdata=np.dot(V,(D.T))
pdata=pdata.T
pcad=data.PCAData(headers,pdata,S,V,m)
return pcad
def kmeans_numpy( d, headers, K, whiten = True):
'''Takes in a Data object, a set of headers, and the number of clusters to create
Computes and returns the codebook, codes, and repre... | e=(d*d)/(U.shape[0]-1)
S[index]=e | random_line_split |
analysis.py | #Mkhanyisi Gamedze
# CS 251 - Spring 2017
# project 2
# global fields
import sys
import numpy as np
import csv
import data
import scipy.stats
import scipy.cluster.vq as vq
import random
# functions
def range_(headers, data):
""" Takes in a list of column headers and the Data object and returns a list of 2-element ... |
"""
def kmeans_algorithm(A, means):
# set up some useful constants
MIN_CHANGE = 1e-7
MAX_ITERATIONS = 100
D = means.shape[1]
K = means.shape[0]
N = A.shape[0]
# iterate no more than MAX_ITERATIONS
for i in range(MAX_ITERATIONS):
# calculate the codes
codes, errors = kmeans_classify( A, means )
# calcu... | ID=[] # list of ID values
mindistances=[] # minimum distances algorithm
for dpoint in d:
distances=[] # distances from each mean
for mean in means: # compute distance of each mean, using the distance formula
differences=dpoint-mean
squares=np.square(differences)
sums=np.sum(squares)
distance=np.sqr... | identifier_body |
bundle.js | /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ re... | beautify(number){ // to add "0" before 0,1,2,3,4,5,6,7,8,9
if (number < 10){
number = `0${number}`;
}
return number;
}
hours.textContent = beautify(t.hours);
minutes.textContent = beautify(t.minutes);
seconds.textContent = beautify(t.seconds);
if (t.tot... | function | identifier_name |
bundle.js | /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ re... | info.addEventListener('click', function(event){
let target = event.target;
if (target && target.classList.contains('info-header-tab')){
// Using for-loop to assign a particular content element to a particular tab
for (let i = 0; i < tab.length; i++) {
if (target == tab[i]){
hideT... | lassList.contains('hide')){
tabContent[b].classList.remove('hide');
tabContent[b].classList.add('show');
}
}
// attaching EventListener to the parent using delegetion
| identifier_body |
bundle.js | /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ re... |
});
days.addEventListener('blur', function(){
daysSum = +this.value;
totalSum = (peopleSum + daysSum) * 4000 * placeIndex;
if (days.value == '' || people.value == '' || days.value == '0' || people.value == '0'){
totalOutput.innerHTML = 0;
} else {
totalOutput.innerHTML = totalSu... | {
totalOutput.innerHTML = totalSum;
} | conditional_block |
bundle.js | /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ re... | /*!***************************!*\
!*** ./js/parts/timer.js ***!
\***************************/
/*! no static exports found */
/***/ (function(module, exports) {
function timer() {
// TIMER
let deadline = "2019-06-14";//if the date expires, change the date so the timer works appropriately
function getRemai... | random_line_split | |
codec.rs | use std::pin::Pin;
use std::task::{Context, Poll};
use async_trait::async_trait;
use bytes::BytesMut;
// We use `futures::stream::Stream` because `std::async_iter::AsyncIterator` (previously known as
// `std::stream::Stream`) is still a bare-bones implementation - it does not even have an
// `async fn next` method!
us... | buffer.put_u8(item.len().try_into().unwrap());
buffer.put_slice(item.as_bytes());
}
#[tokio::test]
async fn sink() {
let (stream, mut mock) = SendStream::new_mock(4096);
let mut sink = Sink::new(stream, encode);
assert_matches!(sink.feed("hello world".to_string()).a... | fn encode(item: &String, buffer: &mut BytesMut) { | random_line_split |
codec.rs | use std::pin::Pin;
use std::task::{Context, Poll};
use async_trait::async_trait;
use bytes::BytesMut;
// We use `futures::stream::Stream` because `std::async_iter::AsyncIterator` (previously known as
// `std::stream::Stream`) is still a bare-bones implementation - it does not even have an
// `async fn next` method!
us... |
#[tokio::test]
async fn source() {
let (stream, mut mock) = RecvStream::new_mock(4096);
let mut source = Source::new(stream, decode);
mock.write_all(b"\x0bhello world\x03foo\x03bar")
.await
.unwrap();
drop(mock);
assert_matches!(source.next().awa... | {
if buffer.remaining() < 1 {
return Ok(None);
}
let size = usize::from(buffer[0]);
if buffer.remaining() < 1 + size {
return Ok(None);
}
let mut vec = vec![0u8; size];
buffer.get_u8();
buffer.copy_to_slice(&mut vec);
Ok(Som... | identifier_body |
codec.rs | use std::pin::Pin;
use std::task::{Context, Poll};
use async_trait::async_trait;
use bytes::BytesMut;
// We use `futures::stream::Stream` because `std::async_iter::AsyncIterator` (previously known as
// `std::stream::Stream`) is still a bare-bones implementation - it does not even have an
// `async fn next` method!
us... | (&mut self, stream: &mut Stream) -> Result<Option<Self::Item>, Self::Error> {
loop {
if let Some(item) = self(&mut stream.buffer())? {
return Ok(Some(item));
}
if stream.recv_or_eof().await?.is_none() {
if stream.buffer().is_empty() {
... | decode | identifier_name |
issued_certificate.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: github.com/solo-io/gloo-mesh/api/certificates/issued_certificate.proto
package v1alpha2
import (
bytes "bytes"
fmt "fmt"
math "math"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
_ "github.com/gogo/protobuf/types"
v1... | func (m *IssuedCertificateSpec) XXX_Merge(src proto.Message) {
xxx_messageInfo_IssuedCertificateSpec.Merge(m, src)
}
func (m *IssuedCertificateSpec) XXX_Size() int {
return xxx_messageInfo_IssuedCertificateSpec.Size(m)
}
func (m *IssuedCertificateSpec) XXX_DiscardUnknown() {
xxx_messageInfo_IssuedCertificateSpec.Dis... | random_line_split | |
issued_certificate.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: github.com/solo-io/gloo-mesh/api/certificates/issued_certificate.proto
package v1alpha2
import (
bytes "bytes"
fmt "fmt"
math "math"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
_ "github.com/gogo/protobuf/types"
v1... |
func init() {
proto.RegisterFile("github.com/solo-io/gloo-mesh/api/certificates/issued_certificate.proto", fileDescriptor_86ade12c22739639)
}
var fileDescriptor_86ade12c22739639 = []byte{
// 479 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x53, 0x5d, 0x... | {
proto.RegisterEnum("certificates.mesh.gloo.solo.io.IssuedCertificateStatus_State", IssuedCertificateStatus_State_name, IssuedCertificateStatus_State_value)
proto.RegisterType((*IssuedCertificateSpec)(nil), "certificates.mesh.gloo.solo.io.IssuedCertificateSpec")
proto.RegisterType((*IssuedCertificateStatus)(nil), "... | identifier_body |
issued_certificate.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: github.com/solo-io/gloo-mesh/api/certificates/issued_certificate.proto
package v1alpha2
import (
bytes "bytes"
fmt "fmt"
math "math"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
_ "github.com/gogo/protobuf/types"
v1... | () string {
if m != nil {
return m.Org
}
return ""
}
func (m *IssuedCertificateSpec) GetSigningCertificateSecret() *v1.ObjectRef {
if m != nil {
return m.SigningCertificateSecret
}
return nil
}
func (m *IssuedCertificateSpec) GetIssuedCertificateSecret() *v1.ObjectRef {
if m != nil {
return m.IssuedCerti... | GetOrg | identifier_name |
issued_certificate.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: github.com/solo-io/gloo-mesh/api/certificates/issued_certificate.proto
package v1alpha2
import (
bytes "bytes"
fmt "fmt"
math "math"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
_ "github.com/gogo/protobuf/types"
v1... |
if this.Error != that1.Error {
return false
}
if this.State != that1.State {
return false
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
| {
return false
} | conditional_block |
mprocessing.py | """
by oPromessa, 2018
Published on https://github.com/oPromessa/flickr-uploader/
mprocessing = Helper function to run function in multiprocessing mode
"""
# -----------------------------------------------------------------------------
# Import section for Python 2 and 3 compatible code
# from __future__... |
else:
# Control for when running multiprocessing release locking
logging.debug('===Multiprocessing=== <--[ ].lock.release')
try:
adb_lock.release()
use_dblock_return = True
except Exception:
NPR.niceerror(caught=Tru... | logging.debug('===Multiprocessing=== -->[ ].lock.acquire')
try:
if adb_lock.acquire():
use_dblock_return = True
except Exception:
NPR.niceerror(caught=True,
caughtprefix='+++ ',
caught... | conditional_block |
mprocessing.py | """
by oPromessa, 2018
Published on https://github.com/oPromessa/flickr-uploader/
mprocessing = Helper function to run function in multiprocessing mode
"""
# -----------------------------------------------------------------------------
# Import section for Python 2 and 3 compatible code
# from __future__... |
# -----------------------------------------------------------------------------
# mprocessing
#
def mprocessing(nprocs, lockdb, running, mutex, itemslist, a_fn, cur):
""" mprocessing Function
nprocs = Number of processes to launch (int)
lockdb = lock for access to Database (lock obj ... | """ use_lock
adb_lock = lock to be used
operation = True => Lock
= False => Release
nprocs = >0 when in multiprocessing mode
>>> alock = multiprocessing.Lock()
>>> use_lock(alock, True, 2)
True
>>> use_lock(alock, False, 2)
True
... | identifier_body |
mprocessing.py | """
by oPromessa, 2018
Published on https://github.com/oPromessa/flickr-uploader/
mprocessing = Helper function to run function in multiprocessing mode
"""
# -----------------------------------------------------------------------------
# Import section for Python 2 and 3 compatible code
# from __future__... | logger = multiprocessing.get_logger()
logger.setLevel(log_level)
logging.debug('===Multiprocessing=== Logging defined!')
# ---------------------------------------------------------
# chunk
#
# Divides an iterable in slices/chunks of size size
#
def chunk(iter_list, size):
"... | # CODING No need for such low level debugging to stderr
# multiprocessing.log_to_stderr() | random_line_split |
mprocessing.py | """
by oPromessa, 2018
Published on https://github.com/oPromessa/flickr-uploader/
mprocessing = Helper function to run function in multiprocessing mode
"""
# -----------------------------------------------------------------------------
# Import section for Python 2 and 3 compatible code
# from __future__... | (nprocs, lockdb, running, mutex, itemslist, a_fn, cur):
""" mprocessing Function
nprocs = Number of processes to launch (int)
lockdb = lock for access to Database (lock obj to be created)
running = Value to count processed items (count obj to be created)
mutex ... | mprocessing | identifier_name |
aes.rs | use std::ops::BitXor;
use std::ops::BitXorAssign;
use util;
use xor;
const RCON: [u8; 11] = [
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
];
const SBOX: [u8; 256] = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xF... |
const COLUMN_MATRIX: [u8; 16] = [2, 3, 1, 1, 1, 2, 3, 1, 1, 1, 2, 3, 3, 1, 1, 2];
const INV_COLUMN_MATRIX: [u8; 16] = [14, 11, 13, 9, 9, 14, 11, 13, 13, 9, 14, 11, 11, 13, 9, 14];
fn gmul(mut a: u8, mut b: u8) -> u8 {
let mut p = 0;
for _ in 0..8 {
if (b & 0x1) != 0 {
p.bitxor_assign(a);
}
let ... | {
let mut rows = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
shift_rows(&mut rows);
assert_ne!(
rows,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
);
inv_shift_rows(&mut rows);
assert_eq!(
rows,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
);
} | identifier_body |
aes.rs | use std::ops::BitXor;
use std::ops::BitXorAssign;
use util;
use xor;
const RCON: [u8; 11] = [
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
];
const SBOX: [u8; 256] = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xF... | (key: &[u8]) -> Vec<u8> {
let key_length = key.len();
let (rounds, sbox_round, extra_expansions) = match key_length {
16 => (10, false, 0),
24 => (12, false, 2),
32 => (14, true, 3),
len => panic!("Unsupported key length {}", len),
};
let expanded_key_size = 16 * (rounds + 1);
let mut expanded... | expand_key | identifier_name |
aes.rs | use std::ops::BitXor;
use std::ops::BitXorAssign;
use util;
use xor;
const RCON: [u8; 11] = [
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
];
const SBOX: [u8; 256] = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xF... | impl CBCCipherMode {
fn transform(&mut self, chunk: &[u8; 16], transform: &Fn(&[u8; 16]) -> [u8; 16]) -> [u8; 16] {
match self.operation {
Operation::Encrypt => {
xor::buffer_mut(&mut self.initialization_vector, xor::Key::FullBuffer(chunk));
self.initialization_vector = transform(&self.initi... | }
| random_line_split |
tcp.rs | //! TcpStream wrappers that supports connecting with options
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
use std::{
io::{self, ErrorKind},
net::SocketAddr,
ops::{Deref, DerefMut... | debug!(
"0.0.0.0:{} may have already been occupied, retry with IPV6_V6ONLY",
addr.port()
);
set_only_v6(&socket, true);
socket.bind(*addr)?;
}
Err(err) => retu... | // This is probably 0.0.0.0 with the same port has already been occupied | random_line_split |
tcp.rs | //! TcpStream wrappers that supports connecting with options
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
use std::{
io::{self, ErrorKind},
net::SocketAddr,
ops::{Deref, DerefMut... | (self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
self.project().0.poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
self.project().0.poll_shutdown(cx)
}
}
/// `TcpListener` for accepting inbound connect... | poll_flush | identifier_name |
tcp.rs | //! TcpStream wrappers that supports connecting with options
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
use std::{
io::{self, ErrorKind},
net::SocketAddr,
ops::{Deref, DerefMut... | #[cfg(windows)]
impl AsRawSocket for TcpStream {
fn as_raw_socket(&self) -> RawSocket {
self.0.as_raw_socket()
}
}
| self.0.as_raw_fd()
}
}
| identifier_body |
signature.go | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package idemix
import (
"github.com/hyperledger/fabric-amcl/amcl"
"github.com/hyperledger/fabric-amcl/amcl/FP256BN"
"github.com/pkg/errors"
)
// signLabel is the label used in zero-knowledge proof (ZKP) to identify that this ZKP i... | (Disclosure []byte) []int {
HiddenIndices := make([]int, 0)
for index, disclose := range Disclosure {
if disclose == 0 {
HiddenIndices = append(HiddenIndices, index)
}
}
return HiddenIndices
}
// NewSignature creates a new idemix signature (Schnorr-type signature)
// The []byte Disclosure steers which attri... | hiddenIndices | identifier_name |
signature.go | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package idemix
import (
"github.com/hyperledger/fabric-amcl/amcl"
"github.com/hyperledger/fabric-amcl/amcl/FP256BN"
"github.com/pkg/errors"
)
// signLabel is the label used in zero-knowledge proof (ZKP) to identify that this ZKP i... |
HiddenIndices := hiddenIndices(Disclosure)
// Start sig
r1 := RandModOrder(rng)
r2 := RandModOrder(rng)
r3 := FP256BN.NewBIGcopy(r1)
r3.Invmodp(GroupOrder)
Nonce := RandModOrder(rng)
A := EcpFromProto(cred.A)
B := EcpFromProto(cred.B)
APrime := FP256BN.G1mul(A, r1) // A' = A^{r1}
ABar := FP256BN.G1mul(B... | {
return nil, errors.Errorf("cannot create idemix signature: received nil input")
} | conditional_block |
signature.go | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package idemix
import (
"github.com/hyperledger/fabric-amcl/amcl"
"github.com/hyperledger/fabric-amcl/amcl/FP256BN"
"github.com/pkg/errors"
)
// signLabel is the label used in zero-knowledge proof (ZKP) to identify that this ZKP i... | {
HiddenIndices := hiddenIndices(Disclosure)
APrime := EcpFromProto(sig.GetAPrime())
ABar := EcpFromProto(sig.GetABar())
BPrime := EcpFromProto(sig.GetBPrime())
Nym := EcpFromProto(sig.GetNym())
ProofC := FP256BN.FromBytes(sig.GetProofC())
ProofSSk := FP256BN.FromBytes(sig.GetProofSSk())
ProofSE := FP256BN.Fro... | identifier_body | |
signature.go | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package idemix
import (
"github.com/hyperledger/fabric-amcl/amcl"
"github.com/hyperledger/fabric-amcl/amcl/FP256BN"
"github.com/pkg/errors"
)
// signLabel is the label used in zero-knowledge proof (ZKP) to identify that this ZKP i... | Htp1 := H.Mul(temp1)
e2 := FP256BN.Ate(W,Htp1)
e2.Inverse()
e2.Mul(e1)
Htp2 := H.Mul(temp2)
e4 := FP256BN.Ate(GenG2,Htp2)
e4.Inverse()
e4.Mul(e2)
R3 := FP256BN.Fexp(e4)
R4 := FP256BN.G1mul(T1,rx)
R4.Sub(U.Mul(rDelta1))
R5 := FP256BN.G1mul(T2,rx)
R5.Sub(V.Mul(rDelta2))
// proofData is the data being hash... |
//compute pairing
Grx := GenG2.Mul(rx)
T4 := H.Mul(temp)
e1 := FP256BN.Ate2(Grx,Ax,Grx,T4) | random_line_split |
in-memory-plants-db-service.ts | import { InMemoryDbService, RequestInfo } from 'angular-in-memory-web-api';
import { ResponseOptions } from '@angular/http';
import { Category } from '../app/products/models/category';
export class InMemoryPlantsDbService implements InMemoryDbService {
categories: Category[];
| () {
this.categories = [
{
'id': 0,
'name': 'Balkonnövények',
'plantsCount': 3
},
{
'id': 1,
'name': 'Rózsák',
'plantsCount': 4
},
{
'id': 2,
'name': 'Bogyós gyülömcsök',
'plantsCount': 5
},
{
'... | constructor | identifier_name |
in-memory-plants-db-service.ts | import { InMemoryDbService, RequestInfo } from 'angular-in-memory-web-api';
import { ResponseOptions } from '@angular/http';
import { Category } from '../app/products/models/category';
export class InMemoryPlantsDbService implements InMemoryDbService {
categories: Category[];
constructor() {
this.categories =... | 'description': 'Tűzpiros virágai fehéren csíkozottak. Mindehhez elragadó illat párosul.',
'plantingTime': ['MARCH', 'APRIL', 'MAY', 'OCT', 'NOV'],
'waterReq': 'MEDIUM',
'nutritionReq': 'BIWEEKLY',
'isFavorite': true,
'imageUrl': 'https://www.starkl.hu/img/eshop/thumbnails... | 'categoryId': 1,
'isFrostProof': true,
'lightReq': 'HALF_SHADY', | random_line_split |
in-memory-plants-db-service.ts | import { InMemoryDbService, RequestInfo } from 'angular-in-memory-web-api';
import { ResponseOptions } from '@angular/http';
import { Category } from '../app/products/models/category';
export class InMemoryPlantsDbService implements InMemoryDbService {
categories: Category[];
constructor() {
this.categories =... | conditional_block | ||
piv.rs | // Copyright 2021 Gravitational, 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 agree... | else {
let mut ret: Vec<u8> = len
.to_be_bytes()
.iter()
.skip_while(|&x| *x == 0)
.cloned()
.collect();
ret.insert(0, 0x80 | ret.len() as u8);
ret
}
}
| {
vec![len as u8]
} | conditional_block |
piv.rs | // Copyright 2021 Gravitational, 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 agree... |
}
// SELECT command tags.
const TLV_TAG_PIV_APPLICATION_PROPERTY_TEMPLATE: u8 = 0x61;
const TLV_TAG_AID: u8 = 0x4F;
const TLV_TAG_COEXISTENT_TAG_ALLOCATION_AUTHORITY: u8 = 0x79;
const TLV_TAG_DATA_FIELD: u8 = 0x53;
const TLV_TAG_FASC_N: u8 = 0x30;
const TLV_TAG_GUID: u8 = 0x34;
const TLV_TAG_EXPIRATION_DATE: u8 = 0x3... | {
let mut buf = Vec::new();
if let Some(data) = &self.data {
buf.extend_from_slice(data);
}
let status: [u8; 2] = self.status.into();
buf.extend_from_slice(&status);
buf
} | identifier_body |
piv.rs | // Copyright 2021 Gravitational, 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 agree... | status,
}
}
pub fn encode(&self) -> Vec<u8> {
let mut buf = Vec::new();
if let Some(data) = &self.data {
buf.extend_from_slice(data);
}
let status: [u8; 2] = self.status.into();
buf.extend_from_slice(&status);
buf
}
}
// SELEC... | random_line_split | |
piv.rs | // Copyright 2021 Gravitational, 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 agree... | (len: usize) -> Vec<u8> {
if len < 0x7f {
vec![len as u8]
} else {
let mut ret: Vec<u8> = len
.to_be_bytes()
.iter()
.skip_while(|&x| *x == 0)
.cloned()
.collect();
ret.insert(0, 0x80 | ret.len() as u8);
ret
}
}
| len_to_vec | identifier_name |
monitor.go | package command
import (
"fmt"
"strings"
"sync"
"time"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/mitchellh/cli"
)
const (
// updateWait is the amount of time to wait between status
// updates. Because the monitor is poll-based, we use this
// delay to avoid ove... | out += fmt.Sprintf("%s* Constraint %q filtered %d nodes\n", prefix, cs, num)
}
// Print exhaustion info
if ne := metrics.NodesExhausted; ne > 0 {
out += fmt.Sprintf("%s* Resources exhausted on %d nodes\n", prefix, ne)
}
for class, num := range metrics.ClassExhausted {
out += fmt.Sprintf("%s* Class %q exhaus... | for cs, num := range metrics.ConstraintFiltered { | random_line_split |
monitor.go | package command
import (
"fmt"
"strings"
"sync"
"time"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/mitchellh/cli"
)
const (
// updateWait is the amount of time to wait between status
// updates. Because the monitor is poll-based, we use this
// delay to avoid ove... |
// monitor is used to start monitoring the given evaluation ID. It
// writes output directly to the monitor's ui, and returns the
// exit code for the command. If allowPrefix is false, monitor will only accept
// exact matching evalIDs.
//
// The return code will be 0 on successful evaluation. If there are
// problem... | {
m.Lock()
defer m.Unlock()
existing := m.state
// Swap in the new state at the end
defer func() {
m.state = update
}()
// Check if the evaluation was triggered by a node
if existing.node == "" && update.node != "" {
m.ui.Output(fmt.Sprintf("Evaluation triggered by node %q",
limit(update.node, m.lengt... | identifier_body |
monitor.go | package command
import (
"fmt"
"strings"
"sync"
"time"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/mitchellh/cli"
)
const (
// updateWait is the amount of time to wait between status
// updates. Because the monitor is poll-based, we use this
// delay to avoid ove... |
if len(evals) == 0 {
m.ui.Error(fmt.Sprintf("No evaluation(s) with prefix or id %q found", evalID))
return 1
}
if len(evals) > 1 {
// Format the evaluations
out := make([]string, len(evals)+1)
out[0] = "ID|Priority|Type|Triggered By|Status"
for i, eval := range evals {
out[i+1] = ... | {
m.ui.Error(fmt.Sprintf("Error reading evaluation: %s", err))
return 1
} | conditional_block |
monitor.go | package command
import (
"fmt"
"strings"
"sync"
"time"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/mitchellh/cli"
)
const (
// updateWait is the amount of time to wait between status
// updates. Because the monitor is poll-based, we use this
// delay to avoid ove... | (ui cli.Ui, alloc *api.Allocation, length int) {
// Print filter stats
ui.Output(fmt.Sprintf("Allocation %q status %q (%d/%d nodes filtered)",
limit(alloc.ID, length), alloc.ClientStatus,
alloc.Metrics.NodesFiltered, alloc.Metrics.NodesEvaluated))
ui.Output(formatAllocMetrics(alloc.Metrics, true, " "))
}
func ... | dumpAllocStatus | identifier_name |
git.rs | use anyhow::{anyhow, Context, Result};
use git2::{
build::CheckoutBuilder, ApplyLocation, Delta, Diff, DiffFormat, DiffOptions, ErrorCode,
IndexAddOption, Oid, Repository, ResetType, Signature, StashApplyOptions, Time,
};
use itertools::Itertools;
use std::cell::RefCell;
use std::collections::HashSet;
use std::... | {
stash_id: Oid,
merge_status: MergeStatus,
}
#[derive(Debug)]
struct MergeStatus {
merge_head: Option<String>,
merge_mode: Option<String>,
merge_msg: Option<String>,
}
| Stash | identifier_name |
git.rs | use anyhow::{anyhow, Context, Result};
use git2::{
build::CheckoutBuilder, ApplyLocation, Delta, Diff, DiffFormat, DiffOptions, ErrorCode,
IndexAddOption, Oid, Repository, ResetType, Signature, StashApplyOptions, Time,
};
use itertools::Itertools;
use std::cell::RefCell;
use std::collections::HashSet;
use std::... |
pub fn save_snapshot(&mut self, staged_files: Vec<PathBuf>) -> Result<Snapshot> {
let inner = || -> Result<Snapshot> {
let deleted_files = self.get_deleted_files()?;
let unstaged_diff = self.save_unstaged_diff()?;
let backup_stash = self.save_snapshot_stash()?;
... | {
// When strict hash verification is disabled, it means libgit2 will not
// compute the "object id" of Git objects (which is a SHA-1 hash) after
// reading them to verify they match the object ids being used to look
// them up. This improves performance, and I don't have in front of me
... | identifier_body |
git.rs | use anyhow::{anyhow, Context, Result};
use git2::{
build::CheckoutBuilder, ApplyLocation, Delta, Diff, DiffFormat, DiffOptions, ErrorCode,
IndexAddOption, Oid, Repository, ResetType, Signature, StashApplyOptions, Time,
};
use itertools::Itertools;
use std::cell::RefCell;
use std::collections::HashSet;
use std::... |
Ok(())
}
}
#[derive(Debug)]
pub struct Snapshot {
pub staged_files: Vec<PathBuf>,
backup_stash: Option<Stash>,
unstaged_diff: Option<Vec<u8>>,
}
#[derive(Debug)]
struct Stash {
stash_id: Oid,
merge_status: MergeStatus,
}
#[derive(Debug)]
struct MergeStatus {
merge_head: Option<St... | "Encountered error when deleting {}.",
file.as_ref().display()
)
})?;
} | random_line_split |
client.rs | //! Common client functionalities.
use crate::rdsys;
use crate::rdsys::types::*;
use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw::c_char;
use std::os::raw::c_void;
use std::ptr;
use std::slice;
use std::string::ToString;
use std::time::Duration;
use serde_json;
use crate::config::{ClientConfig, NativeC... | let mut group_list_ptr: *const RDKafkaGroupList = ptr::null_mut();
trace!("Starting group list fetch");
let ret = unsafe {
rdsys::rd_kafka_list_groups(
self.native_ptr(),
group_c_ptr,
&mut group_list_ptr as *mut *const RDKafkaGroupList,... | random_line_split | |
client.rs | //! Common client functionalities.
use crate::rdsys;
use crate::rdsys::types::*;
use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw::c_char;
use std::os::raw::c_void;
use std::ptr;
use std::slice;
use std::string::ToString;
use std::time::Duration;
use serde_json;
use crate::config::{ClientConfig, NativeC... |
pub(crate) unsafe extern "C" fn native_stats_cb<C: ClientContext>(
_conf: *mut RDKafka,
json: *mut c_char,
json_len: usize,
opaque: *mut c_void,
) -> i32 {
let context = Box::from_raw(opaque as *mut C);
let mut bytes_vec = Vec::new();
bytes_vec.extend_from_slice(slice::from_raw_parts(json... | {
let fac = CStr::from_ptr(fac).to_string_lossy();
let log_message = CStr::from_ptr(buf).to_string_lossy();
let context = Box::from_raw(rdsys::rd_kafka_opaque(client) as *mut C);
(*context).log(
RDKafkaLogLevel::from_int(level),
fac.trim(),
log_message.trim(),
);
mem::fo... | identifier_body |
client.rs | //! Common client functionalities.
use crate::rdsys;
use crate::rdsys::types::*;
use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw::c_char;
use std::os::raw::c_void;
use std::ptr;
use std::slice;
use std::string::ToString;
use std::time::Duration;
use serde_json;
use crate::config::{ClientConfig, NativeC... | <T: Into<Option<Duration>>>(
&self,
topic: &str,
partition: i32,
timeout: T,
) -> KafkaResult<(i64, i64)> {
let mut low = -1;
let mut high = -1;
let topic_c = CString::new(topic.to_string())?;
let ret = unsafe {
rdsys::rd_kafka_query_waterm... | fetch_watermarks | identifier_name |
three-d-bar-chart.component.ts | import { Component, OnInit, ViewChild, ElementRef, Input, ViewEncapsulation } from '@angular/core';
import * as _ from 'lodash';
import * as d3 from 'd3';
declare var $: any;
declare var svgHelp: any;
declare var bar3d: any;
@Component({
selector: 'app-three-d-bar-chart',
templateUrl: './three-d-bar-chart.compone... | (private hostRef: ElementRef) { }
ngOnInit() {
if (this.data) {
this.createChart(this.data)
}
}
createChart(data) {
let el = this.chartContainer.nativeElement;
d3.select(el).select("svg").remove();
var margin = {
top: 30,
right: 20,
bottom: 40,
left: 20,
... | constructor | identifier_name |
three-d-bar-chart.component.ts | import { Component, OnInit, ViewChild, ElementRef, Input, ViewEncapsulation } from '@angular/core';
import * as _ from 'lodash';
import * as d3 from 'd3';
declare var $: any;
declare var svgHelp: any;
declare var bar3d: any;
@Component({
selector: 'app-three-d-bar-chart',
templateUrl: './three-d-bar-chart.compone... |
}
createChart(data) {
let el = this.chartContainer.nativeElement;
d3.select(el).select("svg").remove();
var margin = {
top: 30,
right: 20,
bottom: 40,
left: 20,
front: 0,
back: 0
},
width =
$(this.hostRef.nativeElement).parent().width() - margi... | {
this.createChart(this.data)
} | conditional_block |
three-d-bar-chart.component.ts | import { Component, OnInit, ViewChild, ElementRef, Input, ViewEncapsulation } from '@angular/core';
import * as _ from 'lodash';
import * as d3 from 'd3';
declare var $: any;
declare var svgHelp: any;
declare var bar3d: any;
@Component({
selector: 'app-three-d-bar-chart',
templateUrl: './three-d-bar-chart.compone... |
// gridlines in y axis function
function make_y_gridlines() {
return d3.axisLeft(gridY)
.ticks(5)
}
function type(d) {
d.value = +d.value;
return d;
}
function wrap(text, width, windowWidth) {
text.each(function () {
var text = d3.select(this),
... | {
return d3.axisBottom(x)
.ticks(5)
} | identifier_body |
three-d-bar-chart.component.ts | import { Component, OnInit, ViewChild, ElementRef, Input, ViewEncapsulation } from '@angular/core';
import * as _ from 'lodash';
import * as d3 from 'd3';
declare var $: any;
declare var svgHelp: any;
declare var bar3d: any;
@Component({
selector: 'app-three-d-bar-chart',
templateUrl: './three-d-bar-chart.compone... | .on("mouseover", function (d) {
if(d.value)
showPopover.call(this, d)
}).on("mouseout", function (d) {
removePopovers()
}) // sort based on distance from center, so we draw outermost
// bars first. otherwise, bars drawn later might overlap bars drawn first
.sort... | .style("cursor", "pointer") | random_line_split |
pageserver.rs | //
// Main entry point for the Page Server executable
//
use log::*;
use pageserver::defaults::*;
use serde::{Deserialize, Serialize};
use std::{
env,
net::TcpListener,
path::{Path, PathBuf},
str::FromStr,
thread,
};
use zenith_utils::{auth::JwtAuth, logging, postgres_backend::AuthType};
use anyho... | () -> Result<()> {
let arg_matches = App::new("Zenith page server")
.about("Materializes WAL stream to pages and serves them to the postgres")
.arg(
Arg::with_name("listen-pg")
.short("l")
.long("listen-pg")
.alias("listen") // keep some co... | main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.