file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
binder.rs | capability::{
CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability,
OptionalTask,
},
channel,
model::{
component::{BindReason, WeakComponentInstance},
error::ModelError,
hooks::{Event, EventPayload, EventType, ... | (components: Vec<(&'static str, ComponentDecl)>) -> Self {
let TestModelResult { builtin_environment, .. } =
TestEnvironmentBuilder::new().set_components(components).build().await;
BinderCapabilityTestFixture { builtin_environment }
}
async fn new_event_stream(
... | new | identifier_name |
consolidate_data.py | [..., :3], [1.0/3.0, 1.0/3.0, 1.0/3.0]), mi, mx)
# https://github.com/CSBDeep/CSBDeep/blob/master/csbdeep/utils/utils.py
def normalize_percentile(x, pmin=3, pmax=99.8, axis=None, clip=False,
eps=1e-20, dtype=np.float32):
mi = np.percentile(x, pmin, axis=axis, keepdims=True)
ma = np.pe... |
elif args.normalize == "percentile":
raw = normalize_percentile(raw, mn, mx)
logger.debug(
"%s after norm %s: min %s, max %s, mean %s, std %s, median %s",
sample, args.normalize, np.min(raw), np.max(raw), np.mean(raw),
np.std(raw), np.median(raw))
return raw
def preproce... | raw = normalize_min_max(raw, mn, mx) | conditional_block |
consolidate_data.py | [..., :3], [1.0/3.0, 1.0/3.0, 1.0/3.0]), mi, mx)
# https://github.com/CSBDeep/CSBDeep/blob/master/csbdeep/utils/utils.py
def normalize_percentile(x, pmin=3, pmax=99.8, axis=None, clip=False,
eps=1e-20, dtype=np.float32):
mi = np.percentile(x, pmin, axis=axis, keepdims=True)
ma = np.pe... | (args, array, mode):
if args.padding != 0:
array = np.pad(array,
((args.padding, args.padding),
(args.padding, args.padding),
(args.padding, args.padding)),
mode)
return array
def get_arguments():
parser ... | pad | identifier_name |
consolidate_data.py | )
# https://github.com/CSBDeep/CSBDeep/blob/master/csbdeep/utils/utils.py
def normalize_percentile(x, pmin=3, pmax=99.8, axis=None, clip=False,
eps=1e-20, dtype=np.float32):
mi = np.percentile(x, pmin, axis=axis, keepdims=True)
ma = np.percentile(x, pmax, axis=axis, keepdims=True)
... |
if args.out_format == "hdf":
f = h5py.File(out_fn + '.hdf', 'w')
elif args.out_format == "zarr": | random_line_split | |
consolidate_data.py | [..., :3], [1.0/3.0, 1.0/3.0, 1.0/3.0]), mi, mx)
# https://github.com/CSBDeep/CSBDeep/blob/master/csbdeep/utils/utils.py
def normalize_percentile(x, pmin=3, pmax=99.8, axis=None, clip=False,
eps=1e-20, dtype=np.float32):
mi = np.percentile(x, pmin, axis=axis, keepdims=True)
ma = np.pe... |
def work(args, sample):
logger.info("Processing %s, %s", args.in_dir, sample)
out_fn = os.path.join(args.out_dir, sample)
raw_fns = natsorted(glob.glob(
os.path.join(args.in_dir,
"BBBC010_v2_images", "*_" + sample + "_*.tif")))
# print(raw_fns)
raw_gfp = load_array(r... | logging.basicConfig(level='INFO')
args = get_arguments()
files = map(
lambda fn: fn.split("/")[-1].split(".")[0].split("_")[6],
glob.glob(os.path.join(args.in_dir, 'BBBC010_v2_images/*.tif')))
files = sorted(list(set(files)))
print(files)
if args.parallel > 1:
Parallel(n_j... | identifier_body |
lib.rs | _fn(name: &syn::Ident, fn_name: &str) -> syn::Ident {
syn::Ident::new(&format!("{}{}_{}", SwigTag::SwigInject, fn_name, name), Span::call_site())
}
fn swig_free(name: &syn::Ident) -> syn::Ident {
swig_fn(name, "free")
}
impl ToSwig for syn::DeriveInput {
fn to_swig(&self) -> String {
/// Generate ... | debug!("{:#?}", iim);
if iim.sig.ident.to_string().starts_with(SwigTag::SwigInject.to_str()) {
acc.extend_from_slice(&iim.attrs[..]); | random_line_split | |
lib.rs | need to do some pointer/box stuff
if ac.ty.clone().into_token_stream().to_string().ends_with("str") {
caller_ref.push(quote!{@str #id});
} else if let syn::Type::Reference(_) = ac.ty {
caller_ref.push(quote!{@ref #id});
... | {
let ifn = InternalFn {
base: base_name,
fn_def: ast,
};
let tok = ifn.as_extern();
let comment = ifn.to_swig();
let hidden = swig_fn(&ast.ident, "hidden_ffi");
quote! {
#[allow(non_snake_case)]
#[doc=#comment]
fn #hidden(){}
#tok
}
} | identifier_body | |
lib.rs | igTag::CodeStart.to_string();
let mut swigged_h = SwigTag::HdrStart.to_string();
let name = &self.fn_def.ident;
let cb_fn = cbindgen::ir::Function::load(name.to_string(),
&self.fn_def.decl,
... | split_out_externs | identifier_name | |
park.rs | the `lazy_static!` macro.
///
/// This type uses the blocking synchronization mechanism provided by the
/// underlying operating system.
///
/// For the API of this type alias, see the API of the generic
/// [`Lazy`](crate::doc::Lazy) type.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// # #[cfg(featu... | (state: &AtomicOnceState) {
// spin a little before parking the thread in case the state is
// quickly unlocked again
let back_off = BackOff::new();
let blocked = match Self::try_block_spinning(state, &back_off) {
Ok(_) => return,
Err(blocked) => blocked,
... | block | identifier_name |
park.rs | the `lazy_static!` macro.
///
/// This type uses the blocking synchronization mechanism provided by the
/// underlying operating system.
///
/// For the API of this type alias, see the API of the generic
/// [`Lazy`](crate::doc::Lazy) type.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// # #[cfg(featu... | // SAFETY: `head` is a valid pointer to a `StackWaiter` that will live
// for the duration of this function, which in turn will only return
// when no other thread can still observe any pointer to it
// (wait:2) this acq-rel CAS syncs-with itself and the acq load (wait:1)
while l... | {
// spin a little before parking the thread in case the state is
// quickly unlocked again
let back_off = BackOff::new();
let blocked = match Self::try_block_spinning(state, &back_off) {
Ok(_) => return,
Err(blocked) => blocked,
};
// create a li... | identifier_body |
park.rs | the `lazy_static!` macro.
///
/// This type uses the blocking synchronization mechanism provided by the
/// underlying operating system.
///
/// For the API of this type alias, see the API of the generic
/// [`Lazy`](crate::doc::Lazy) type.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// # #[cfg(featu... | }
}
}
impl Unblock for ParkThread {
/// Unblocks all blocked waiting threads.
#[inline]
unsafe fn on_unblock(state: BlockedState) {
let mut curr = state.as_ptr() as *const StackWaiter;
while !curr.is_null() {
let thread = {
// SAFETY: no mutable refer... | back_off.spin(); | random_line_split |
zapis.py | (2,), wiec odwoluje sie bezposrednio do zmiennej ustawienia
if ustawienia.shape == (2,):
parametry[re.sub('"','',ustawienia[0])] = ustawienia[1]
# jak mamy wiecej parametrow odwoluje sie do kolejnych linijek macierzy
# ustawienia
else:
for l in ustawienia:
paramet... | utwor, procent = 0):
"""
zmienia glosnosc utworu (jego amplitudy)
arg:
numpy.ndarray (numpy.int16): utwor - dzwiek, ktory ma byc zglosniony
lub zciszony
float: procent - liczba obrazujaca zmiane glosnosci utworu, osiaga
... | miana_glosnosci( | identifier_name |
zapis.py | znik = 1 + procent
else:
# obliczamy najwyzsza amplitude w danym utworze i ona bedzie
# wyznaczac jak bardzo mozemy podglosnic
maks_ampli = 0
maks_ampli = max(abs(utwor))
mnoznik = 32767/maks_ampli # maksymalny mnoznik
# mnoznik min... | poczatek_cwiercnuty:(poczatek_cwiercnuty + maksik)]=\
cwiercnuta[0:len(T[poczatek_cwiercnuty:(poczatek_cwiercnuty +\
maksik)])]
| conditional_block | |
zapis.py | noznik-1) mnozymy o procent zglosnienia
# i dodajemy do podstawy (czyli 1)
mnoznik = 1 + (mnoznik - 1)*procent
glosniej = mnoznik * utwor
#glosniej = np.array(glosniej, dtype=np.int16)
glosniej = glosniej.astype(np.int16)
return glosniej
else:
... | #pios, k = wczytywanie_sciezek(a)
#wierszyk = tworzenie_piosenki(pios, k, bpm = b['bpm'], freq = b['freq'], \
| random_line_split | |
zapis.py | 2,), wiec odwoluje sie bezposrednio do zmiennej ustawienia
if ustawienia.shape == (2,):
parametry[re.sub('"','',ustawienia[0])] = ustawienia[1]
# jak mamy wiecej parametrow odwoluje sie do kolejnych linijek macierzy
# ustawienia
else:
for l in ustawienia:
parametry... | maxa, -1 - sciszamy na maxa
wyjscie:
numpy.ndarray (numpy.int16): gotowy utwór
"""
# macierz piosenki byla pusta, piosenka nie zostala utworzona
if(czy_pelna == False):
print("Nie utworzono piosenki")
return None
... | ""
glowna funkcja generujaca cala piosenke
arg:
numpy.ndarray (str: U2): macierz_piosenki - macierz zawierajaca
definicje kolejnych cwiercnut (co ma byc grane
w danej cwiercnucie)
b... | identifier_body |
proof.rs | the `Proof`
pub lemma: Lemma,
/// The value concerned by this `Proof`
pub value: T,
}
#[cfg(feature = "serialization-serde")]
mod algorithm_serde {
use ring::digest::{self, Algorithm};
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S... |
}
impl<T: Ord> Ord for Proof<T> {
fn cmp(&self, other: &Proof<T>) -> Ordering {
self.root_hash
.cmp(&other.root_hash)
.then(self.value.cmp(&other.value))
.then_with(|| self.lemma.cmp(&other.lemma))
}
}
impl<T: Hash> Hash for Proof<T> {
fn hash<H: Hasher>(&self,... | {
Some(self.cmp(other))
} | identifier_body |
proof.rs | the `Proof`
pub lemma: Lemma,
/// The value concerned by this `Proof`
pub value: T,
}
#[cfg(feature = "serialization-serde")]
mod algorithm_serde {
use ring::digest::{self, Algorithm};
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S... | else {
None
}
}
fn new_tree_proof<T>(
hash: &[u8],
needle: &[u8],
| {
Some(Lemma {
node_hash: hash.into(),
sibling_hash: None,
sub_lemma: None,
})
} | conditional_block |
proof.rs | the `Proof`
pub lemma: Lemma,
/// The value concerned by this `Proof`
pub value: T,
}
#[cfg(feature = "serialization-serde")]
mod algorithm_serde {
use ring::digest::{self, Algorithm};
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S... | <T>(
hash: &[u8],
needle: &[u8],
| new_tree_proof | identifier_name |
proof.rs | of the `Proof`
pub lemma: Lemma,
/// The value concerned by this `Proof`
pub value: T,
}
#[cfg(feature = "serialization-serde")]
mod algorithm_serde {
use ring::digest::{self, Algorithm};
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serializ... | ref hash,
ref value,
..
} => {
if count != 1 {
return None;
}
let lemma = Lemma {
node_hash: hash.clone(),
sibling_hash: None,
sub_l... | random_line_split | |
main.rs | Session},
};
fn run(
display_index: usize,
output_path: &str,
bit_rate: u32,
frame_rate: u32,
resolution: Resolution,
encoder_index: usize,
verbose: bool,
wait_for_debugger: bool,
console_mode: bool,
) -> Result<()> {
unsafe {
RoInitialize(RO_INIT_MULTITHREADED)?;
}
... |
if verbose {
println!(
"Using index \"{}\" and path \"{}\".",
display_index, output_path
);
}
// Get the display handle using the provided index
let display_handle = get_display_handle_from_index(display_index)
.expect("The provided display index was out... | if !required_capture_features_supported()? {
exit_with_error("The required screen capture features are not supported on this device for this release of Windows!\nPlease update your operating system (minimum: Windows 10 Version 1903, Build 18362).");
} | random_line_split |
main.rs | let encoder_devices = VideoEncoderDevice::enumerate()?;
if encoder_devices.is_empty() {
exit_with_error("No hardware H264 encoders found!");
}
if verbose {
println!("Encoders ({}):", encoder_devices.len());
for encoder_device in &encoder_devices {
println!(" {}", enc... | {
ApiInformation::IsApiContractPresentByMajor("Windows.Foundation.UniversalApiContract", 8)
} | identifier_body | |
main.rs | },
};
fn run(
display_index: usize,
output_path: &str,
bit_rate: u32,
frame_rate: u32,
resolution: Resolution,
encoder_index: usize,
verbose: bool,
wait_for_debugger: bool,
console_mode: bool,
) -> Result<()> {
unsafe {
RoInitialize(RO_INIT_MULTITHREADED)?;
}
uns... |
if verbose {
println!(
"Using index \"{}\" and path \"{}\".",
display_index, output_path
);
}
// Get the display handle using the provided index
let display_handle = get_display_handle_from_index(display_index)
.expect("The provided display index was ou... | {
exit_with_error("The required screen capture features are not supported on this device for this release of Windows!\nPlease update your operating system (minimum: Windows 10 Version 1903, Build 18362).");
} | conditional_block |
main.rs | Session},
};
fn | (
display_index: usize,
output_path: &str,
bit_rate: u32,
frame_rate: u32,
resolution: Resolution,
encoder_index: usize,
verbose: bool,
wait_for_debugger: bool,
console_mode: bool,
) -> Result<()> {
unsafe {
RoInitialize(RO_INIT_MULTITHREADED)?;
}
unsafe { MFStart... | run | identifier_name |
utils.py |
def create_table_descriptive_row_from_analysis(
attribute_name: Text,
base_analysis: Analysis,
additional_analysis: Analysis,
figure_base_path: Text
) -> Text:
# pylint: disable-msg=too-many-locals
"""Create makrdown formatted descriptive analysis result
Args: | figure_base_path: (string), the folder for holding figures
Returns:
string, markdown formatted content
"""
row_template = template.TABLE_DESCRIPTIVE_ROW_TEMPLATE
stats_template = template.TABLE_DESCRIPTIVE_STATS_TEMPLATE
metrics = base_analysis.smetrics
attribute_type = base_analysis.features[... | attribute_name: (string), name of the attribute
base_analysis: (analysis_entity_pb2.Analysis), analysis holding
all the metrics
additional_analysis: (analysis_entity_pb2.Analysis), histogram for
numerical attribute, value_counts for categorical attributes | random_line_split |
utils.py |
def create_table_descriptive_row_from_analysis(
attribute_name: Text,
base_analysis: Analysis,
additional_analysis: Analysis,
figure_base_path: Text
) -> Text:
# pylint: disable-msg=too-many-locals
"""Create makrdown formatted descriptive analysis result
Args:
attribute_name: (string), n... | row_list=row_list,
column_list=column_list,
name_value_map=analysis_name_value_map,
same_match_value=same_match_value)
def create_target_metrics_highlight(
target_name: Text,
metric_name_list: List[Text],
metric_analysis_list: List[List[Analysis]]
) -> Text:
# pylint: disable-ms... | """Create metric table for pairwise comparison
Args:
analysis_list: (List[analysis_entity_pb2.Analysis])
same_match_value: (Union[str, float])
Returns:
string
"""
row_list = set()
column_list = set()
# a dictionary with {attributeone-attributetwo: metric_value}
analysis_name_value_map ... | identifier_body |
utils.py | def create_table_descriptive_row_from_analysis(
attribute_name: Text,
base_analysis: Analysis,
additional_analysis: Analysis,
figure_base_path: Text
) -> Text:
# pylint: disable-msg=too-many-locals
"""Create makrdown formatted descriptive analysis result
Args:
attribute_name: (string), name... | (
row_list: Set[Text],
column_list: Set[Text],
name_value_map: Dict[Text, float],
same_match_value
) -> Text:
"""Construct table for pair-wise computed metrics, e.g.,
PEARSON_CORRELATION, ANOVA, CHI_SQUARE, INFORMATION_GAIN
Examples:
​|tips|tolls|trip_total
:-----:|:-----:|:-----:|:---... | create_pairwise_metric_table | identifier_name |
utils.py | .append(stats_template.format(
metric=item,
value=result_holder[item]
))
figure_path = visualization.plot_bar_chart(additional_analysis,
figure_base_path)
return row_template.format(
name=attribute_name,
type=Attribute.Type.Name(attribute... | metric_name = Analysis.Name.Name(analysis.name)
attribute_name = [att.name for att in analysis.features
if att.name != target_name][0]
attribute_set.add(attribute_name)
metric_value = analysis.smetrics[0].value
metric_holders[metric_name][attribute_name] = metric_value | conditional_block | |
receiver.rs |
.loss_list
.iter_mut()
.filter(|lle| lle.feedback_time < now - lle.k * rtt)
{
pak.k += 1;
pak.feedback_time = now;
ret.push(pak.seq_num);
}
ret
};
if seq_nums.is_empty(... | {
let vec: Vec<_> = lost_seq_nums.collect();
debug!("Sending NAK for={:?}", vec);
let pack = self.make_control_packet(ControlTypes::Nak(
compress_loss_list(vec.iter().cloned()).collect(),
));
self.send_to_remote(cx, pack)?;
Ok(())
} | identifier_body | |
receiver.rs | hs_returner,
sock,
rtt: 10_000,
rtt_variance: 1_000,
listen_timeout: Duration::from_secs(1),
loss_list: Vec::new(),
ack_history_window: Vec::new(),
packet_history_window: Vec::new(),
packet_pair_window: Vec::new(),
... | (&mut self, cx: &mut Context, packet: Packet) -> Result<(), Error> {
self.send_wrapper
.send(&mut self.sock, (packet, self.settings.remote), cx)
}
fn reset_timeout(&mut self) {
self.timeout_timer.reset(time::Instant::from_std(
Instant::now() + self.listen_timeout,
... | send_to_remote | identifier_name |
receiver.rs | ::new(&mut self.ack_interval)
}
fn nak_interval(&mut self) -> Pin<&mut Delay> {
Pin::new(&mut self.nak_interval)
}
fn release_delay(&mut self) -> Pin<&mut Delay> {
Pin::new(&mut self.release_delay)
}
fn send_to_remote(&mut self, cx: &mut Context, packet: Packet) -> Result<(), ... | info!(
"Packet send to socket id ({}) that does not match local ({})",
packet.dest_sockid().0,
self.settings.local_sockid.0
); | random_line_split | |
cluster.go | Amazon *ClusterAmazon `json:"amazon"`
}
// ClusterAmazon offers Amazon-specific settings for that instance pool
type ClusterAmazon struct {
// This fields contains ARNs for additional IAM policies to be added to
// this instance pool
AdditionalIAMPolicies []string `json:"additionalIAMPolicies,omitempty"`
// When s... |
return &Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
}
}
| identifier_body | |
cluster.go | Type string `json:"-"` // This specifies if a cluster is a hub, single or multi
// Amazon specific options
Amazon *ClusterAmazon `json:"amazon"`
}
// ClusterAmazon offers Amazon-specific settings for that instance pool
type ClusterAmazon struct {
// This fields contains ARNs for additional IAM policies to be adde... | ewCluster( | identifier_name | |
cluster.go | Azure = "azure"
CloudGoogle = "google"
CloudBaremetal = "baremetal"
CloudDigitalOcean = "digitalocean"
)
const (
ClusterTypeHub = "hub"
ClusterTypeClusterSingle = "cluster-single"
ClusterTypeClusterMulti = "cluster-multi"
)
const (
// represents Terraform in a destroy state
StateDes... | // expose the API server through a public load balancer
Public bool `json:"public,omitempty"`
AllowCIDRs []string `json:"allowCIDRs,omitempty"`
// create DNS record for the private load balancer, and optionally lock it down
PrivateRecord bool `json:"privateRecord,omitempty"`
... | Image string `json:"image,omitempty"`
Version string `json:"version,omitempty"`
}
type ClusterKubernetesAPIServer struct { | random_line_split |
orderbook.go | "suspended"
}
func updatePos(ord *Order) {
securityId := ord.Security.Id
p := getPos(ord.Acc, securityId)
var outstand *float64
if ord.Side == "buy" {
outstand = &p.OutstandBuyQty
} else {
outstand = &p.OutstandSellQty
}
switch ord.St {
case "unconfirmed", "unconfirmed_replace":
*outstand += ord.Qty - ... | ParsePnl | identifier_name | |
orderbook.go | tmp = make(map[int64]*Position)
Positions[acc] = tmp
}
p := tmp[securityId]
if p == nil {
p = &Position{}
p.Acc = acc
p.Security = SecurityMapById[securityId]
if p.Security == nil {
log.Println("unknown securityId", securityId)
return p
}
tmp[securityId] = p
used := usedSecurities[securityId]
... | {
acc := int(msg[1].(float64)) // msg[2] is acc name
for _, v := range Positions[acc] {
v.Target = 0.
}
if len(msg) < 4 {
return
}
if _, ok := msg[3].([]interface{}); !ok {
return
}
for _, v := range msg[3].([]interface{}) {
t := v.([]interface{})
securityId := int64(t[0].(float64))
target := t[1].(... | identifier_body | |
orderbook.go | Sector: msg[13].(string),
IndustryGroup: msg[14].(string),
Industry: msg[15].(string),
SubIndustry: msg[16].(string),
Bbgid: msg[17].(string),
Cusip: msg[18].(string),
Sedol: msg[19].(string),
Isin: msg[20].(string),
}
if sec.Market == "CURRENCY" |
if sec.Multiplier <= 0 {
sec.Multiplier = 1
}
if sec.Rate <= 0 {
sec.Rate = 1
}
sec0 := SecurityMapById[sec.Id]
if sec0 == nil {
SecurityMapById[sec.Id] = sec
} else {
*sec0 = *sec
sec = sec0
}
tmp := SecurityMapByMarket[sec.Market]
if tmp == nil {
tmp = make(map[string]*Security)
SecurityMapBy... | {
sec.Market = "FX"
} | conditional_block |
orderbook.go | 64
St string
Security *Security
// UserId int
Acc int
Qty float64
Px float64
Side string
Type string
// Tif string
CumQty float64
AvgPx float64
LastQty float64
LastPx float64
}
var orders = make(map[int64]*Order)
type PositionBase struct {
Qty float64
AvgPx float64
Commissi... | random_line_split | ||
main.rs | _lowercase().as_str() {
"y" => break,
"n" => return,
_ => println!("Unknown response: {}", answer),
}
}
for scan_position in config.scan_positions() {
println!("Colorizing {}:", scan_position.name);
let translations = config.translations(scan_position... | }
Err(err) => {
use std::io::ErrorKind; | random_line_split | |
main.rs | ").unwrap()).unwrap();
let image_dir = PathBuf::from(matches.value_of("IMAGE_DIR").unwrap());
let las_dir = Path::new(matches.value_of("LAS_DIR").unwrap()).to_path_buf();
let min_reflectance = value_t!(matches, "min-reflectance", f32).unwrap();
let max_reflectance = value_t!(matches, "ma... | temperature | identifier_name | |
main.rs | ().flush().unwrap();
let answer: String = read!();
println!();
match answer.to_lowercase().as_str() {
"y" => break,
"n" => return,
_ => println!("Unknown response: {}", answer),
}
}
for scan_position in config.scan_positions() {
printl... | {
None
} | conditional_block | |
data_collection.py | RUNNING = 1
FINISHED = 2
class DataCollection:
def __init__(self, user, mode, iterations, museID = None):
self.user = user
self.museID = museID
pygame.init()
self.width = 600
self.height = 600
pygame.display.set_caption(user + ' Data Collection Session')
... |
def save_data(self):
info = self.eegInlet.info()
desc = info.desc()
chanNum = info.channel_count()
channels = desc.child('channels').first_child()
channelNames = [channels.child_value('label')]
for i in range(1, chanNum):
channels = channels.next_siblin... | print('Number of samples: {0} | Time since last: {1}'.format(timestampCount, time() - self.lastEEGSampleTime))
self.lastEEGSampleTime = time()
for i in range(0, len(timestamps)):
self.eegData.append([timestamps[i]] + samples[i]) | conditional_block |
data_collection.py |
RUNNING = 1
FINISHED = 2
class DataCollection:
def __init__(self, user, mode, iterations, museID = None):
self.user = user
self.museID = museID
pygame.init()
self.width = 600
self.height = 600
pygame.display.set_caption(user + ' Data Collection Session')
... | def setup_marker_streaming(self):
streamName = self.user + ' Training Session Markers'
self.markerInfo = StreamInfo(streamName, 'Keystroke Markers', 1, 0, 'string', str(uuid.uuid1()))
self.markerOutlet = StreamOutlet(self.markerInfo)
def get_eeg_stream(self, timeout):
eeg_inlet_... | random_line_split | |
data_collection.py | RUNNING = 1
FINISHED = 2
class DataCollection:
def __init__(self, user, mode, iterations, museID = None):
self.user = user
self.museID = museID
pygame.init()
self.width = 600
self.height = 600
pygame.display.set_caption(user + ' Data Collection Session')
... | (self):
if self.state == DataCollectionState.MUSE_DISCONNECTED:
if self.doneCheckEEG == True:
self.doneCheckEEG = False
threading.Thread(target = self.get_eeg_stream, kwargs={'timeout' : 5}).start()
elif self.state == DataCollection | process_logic | identifier_name |
data_collection.py |
RUNNING = 1
FINISHED = 2
class DataCollection:
| self.state = DataCollectionState.MUSE_DISCONNECTED # 0 = Muse Disconnected, 1 = Session Running, 2 = Finished
self.setup_marker_streaming()
self.markers = [[]] # Each item is array of 2 items - timestamp + the key which was pressed.
self.eegData = [[]] # Each item is array of timestamp ... | def __init__(self, user, mode, iterations, museID = None):
self.user = user
self.museID = museID
pygame.init()
self.width = 600
self.height = 600
pygame.display.set_caption(user + ' Data Collection Session')
self.screen = pygame.display.set_mode((self.width, self.... | identifier_body |
mp4TagWriter.ts | atoms.length > 0) throw new Error("Buffer already parsed");
let offset = 0;
let atom: Atom;
while (true) {
atom = this._readAtom(offset);
if (!atom || atom.length < 1) break;
this._atoms.push(atom);
offset = atom.offset + atom.length;
}
if (this._atoms.length < 1) throw... | (name: string, data: ArrayBuffer | string | number) {
if (name.length > 4 || name.length < 1) throw new Error(`Unsupported atom name: '${name}'`);
let dataBuffer: ArrayBuffer;
if (data instanceof ArrayBuffer) {
dataBuffer = data;
} else if (typeof data === "string") {
dataBuffer = this._ge... | addMetadataAtom | identifier_name |
mp4TagWriter.ts | .length > 0) throw new Error("Buffer already parsed");
let offset = 0;
let atom: Atom;
while (true) {
atom = this._readAtom(offset);
if (!atom || atom.length < 1) break;
this._atoms.push(atom);
offset = atom.offset + atom.length;
}
if (this._atoms.length < 1) throw new ... | }
return {
name,
length,
offset,
};
}
private _getHeaderBufferFromAtom(atom: Atom) {
if (!atom || atom.length < 1 || !atom.name || !atom.data)
throw new Error("Can not compute header buffer for this atom");
const headerBuffer = new ArrayBuffer(ATOM_HEADER_LENGTH);
... | {
const begin = offset;
const end = offset + ATOM_HEAD_LENGTH;
const buffer = this._buffer.slice(begin, end);
if (buffer.byteLength < ATOM_HEAD_LENGTH) {
return {
length: buffer.byteLength,
offset,
};
}
const dataView = new DataView(buffer);
let length = dataV... | identifier_body |
mp4TagWriter.ts | .length < 1) throw new Error(`Unsupported atom name: '${name}'`);
let dataBuffer: ArrayBuffer;
if (data instanceof ArrayBuffer) {
dataBuffer = data;
} else if (typeof data === "string") {
dataBuffer = this._getBufferFromString(data);
} else if (typeof data === "number") {
dataBuffer ... | this._mp4.addMetadataAtom("©nam", title);
}
setArtists(artists: string[]): void {
if (!artists || artists.length < 1) throw new Error("Invalid value for artists"); | random_line_split | |
mp4TagWriter.ts | .length > 0) throw new Error("Buffer already parsed");
let offset = 0;
let atom: Atom;
while (true) {
atom = this._readAtom(offset);
if (!atom || atom.length < 1) break;
this._atoms.push(atom);
offset = atom.offset + atom.length;
}
if (this._atoms.length < 1) throw new ... |
return children;
}
private _readAtom(offset: number): Atom {
const begin = offset;
const end = offset + ATOM_HEAD_LENGTH;
const buffer = this._buffer.slice(begin, end);
if (buffer.byteLength < ATOM_HEAD_LENGTH) {
return {
length: buffer.byteLength,
offset,
};
... | {
if (childOffset >= childEnd) break;
const childAtom = this._readAtom(childOffset);
if (!childAtom || childAtom.length < 1) break;
childOffset = childAtom.offset + childAtom.length;
children.push(childAtom);
} | conditional_block |
types.d.ts | asks/functionsaccessingociresources.htm | Accessing Other Oracle Cloud Infrastructure Resources from Running Functions}
* for more information. Use Resouce Principal by setting
* {@link IAMConfig#useResourcePrincipal} property to true.</li>
* </ol>
* <p>
* Note that when using Instance Principal or Resource Princ... | * <p>
* You may provide these credentials in one of the following ways, in order of
* increased security:
* <ul>
* <li>Directly as properties of {@link IAMConfig}.
* In this case, set properties {@link tenantId}, {@link userId},
* {@link privateKey} or {@link privateKeyFile}, {@link fingerprint} and
* {@link pa... | random_line_split | |
mqttclient.go | o *handler) handle(client mqtt.Client, msg mqtt.Message) {
// We extract the count and write that out first to simplify checking for missing values
var m Message
var resp Session
if err := json.Unmarshal(msg.Payload(), &resp); err != nil {
fmt.Printf("Message could not be parsed (%s): %s", msg.Payload(), err... | req := &Session{}
req.Type = "discoveryrsp"
req.DeviceId = "kvm1"
req.Data = enc.Encode(dev) //enc.Encode(answer)
answermsg := PublishMsg{
Topic: "discoveryrsp",
Msg: req,
}
fmt.Println("discoveryrsp", answermsg)
SendMsg(answermsg) //response)
case DEVICE_ONVIF:
case DEV... | random_line_split | |
mqttclient.go | *handler) handle(client mqtt.Client, msg mqtt.Message) {
// We extract the count and write that out first to simplify checking for missing values
var m Message
var resp Session
if err := json.Unmarshal(msg.Payload(), &resp); err != nil {
fmt.Printf("Message could not be parsed (%s): %s", msg.Payload(), err)... | t, "[CRITICAL] ", 0)
// mqtt.WARN = log.New(os.Stdout, "[WARN] ", 0)
// mqtt.DEBUG = log.New(os.Stdout, "[DEBUG] ", 0)
// Create a handler that will deal with incoming messages
h := NewHandler()
defer h.Close()
msgChans = make(chan PublishMsg, 10)
// Now we establish the connection to the mqtt broker
... | tMqtt() {
// Enable logging by uncommenting the below
// mqtt.ERROR = log.New(os.Stdout, "[ERROR] ", 0)
// mqtt.CRITICAL = log.New(os.Stdou | identifier_body |
mqttclient.go | o *handler) handle(client mqtt.Client, msg mqtt.Message) {
// We extract the count and write that out first to simplify checking for missing values
var m Message
var resp Session
if err := json.Unmarshal(msg.Payload(), &resp); err != nil {
fmt.Printf("Message could not be parsed (%s): %s", msg.Payload(), err... | 0)
// mqtt.WARN = log.New(os.Stdout, "[WARN] ", 0)
// mqtt.DEBUG = log.New(os.Stdout, "[DEBUG] ", 0)
// Create a handler that will deal with incoming messages
h := NewHandler()
defer h.Close()
msgChans = make(chan PublishMsg, 10)
// Now we establish the connection to the mqtt broker
opts := mqtt.NewCl... | ICAL] ", | identifier_name |
mqttclient.go |
o.f = nil
}
}
// handle is called when a message is received
func (o *handler) handle(client mqtt.Client, msg mqtt.Message) {
// We extract the count and write that out first to simplify checking for missing values
var m Message
var resp Session
if err := json.Unmarshal(msg.Payload(), &resp); err != ... | {
fmt.Printf("ERROR closing file: %s", err)
} | conditional_block | |
background.js | (proxy.http !== null && proxy.https === null) {
proxyRules = `http=${proxy.http},${proxyRules}`
}
if (proxy.http !== null && proxy.https !== null) {
proxyRules = `http=${proxy.http};https=${proxy.https},${proxyRules}`
}
}
win.webContents.session.setProxy({
proxyRules: proxyRules,
p... | handleInoreader(url)
})
nativeTheme.on('updated', () => {
store.set('isDarkMode', nativeTheme.shouldUseDarkColors)
win.webContents.send('Dark mode', {
darkmode: nativeTheme.shouldUseDarkColors
})
})
ipcMain.handle('article-selected', (event, status) => {
const menuItemViewBrowser = menu.getMenuItemById(... | random_line_split | |
background.js | // Maximize window on startup when not in development
if (!isDevelopment && win !== null) {
win.maximize()
}
i18nextBackend.mainBindings(ipcMain, win, fs)
ElectronBlocker.fromPrebuiltAdsAndTracking(fetch).then((blocker) => {
blocker.enableBlockingInSession(session.defaultSession)
})
win.setTouc... | {
// Create the browser window.
win = new BrowserWindow({
minWidth: 1280,
minHeight: 720,
width: 1400,
height: 768,
title: 'Raven Reader',
maximizable: true,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-elec... | identifier_body | |
background.js |
i18nextBackend.mainBindings(ipcMain, win, fs)
ElectronBlocker.fromPrebuiltAdsAndTracking(fetch).then((blocker) => {
blocker.enableBlockingInSession(session.defaultSession)
})
win.setTouchBar(touchBar)
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mod... | {
win.maximize()
} | conditional_block | |
background.js | () {
// Create the browser window.
win = new BrowserWindow({
minWidth: 1280,
minHeight: 720,
width: 1400,
height: 768,
title: 'Raven Reader',
maximizable: true,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-... | createWindow | identifier_name | |
click.component.ts | : ['./click.component.scss']
})
export class ClickComponent implements OnInit {
@ViewChild(DatatableComponent) newstable:DatatableComponent;
@ViewChild('form') form;
value:any;
serviceHost = BackendHost;
bannerblockrows = [];
paring=[];
bannerblocktemp = [];
bannerblocklist = [];
modalRef: NgbModalRe... |
}
filesToUploads: Array<File> = [];
urls=[];
filenames = "";
fileChangeEvents(fileInput: any) {
this.filesToUploads=[];
var path = fileInput.target.files[0].type;
if(path == "image/jpeg" || path == "image/gif" || path == "image/jpg" || path == "image/png")
{
this.filesToUploads = <Ar... | {
return 'with: ${reason}';
} | conditional_block |
click.component.ts | : ['./click.component.scss']
})
export class ClickComponent implements OnInit {
@ViewChild(DatatableComponent) newstable:DatatableComponent;
@ViewChild('form') form;
value:any;
serviceHost = BackendHost;
bannerblockrows = [];
paring=[];
bannerblocktemp = [];
bannerblocklist = [];
modalRef: NgbModalRe... | this.defsearch_news = "";
this.newsloadfn();
}
//end of the function
setPage_banner(pageInfo){
this.bannerblocklist = [];
this.bannerblockrows = this.bannerblocklist;
this.bannerblocktemp = this.bannerblocklist;
this.page_banner.pageNumber = pageInfo.offset;
this.loadbannerlist(this.... | size: this.limits_banner[0].value,totalElements:0,totalPages:0,pageNumber:0
}
this.defsort_banner= {dir: "desc", prop: "datetime"}; | random_line_split |
click.component.ts | : ['./click.component.scss']
})
export class ClickComponent implements OnInit {
@ViewChild(DatatableComponent) newstable:DatatableComponent;
@ViewChild('form') form;
value:any;
serviceHost = BackendHost;
bannerblockrows = [];
paring=[];
bannerblocktemp = [];
bannerblocklist = [];
modalRef: NgbModalRe... | (event) {
this.page_banner.pageNumber = 0;
this.defsort_banner = event.sorts[0];
this.loadbannerlist(this.page_banner,this.defsort_banner,this.defsearch_news);
}
//search bar function
updateFilter_news() {
this.limits_banner = [
{ key: '5', value: 5 },
{ key: '10', value: 10 },
... | onSort_banner | identifier_name |
click.component.ts | : ['./click.component.scss']
})
export class ClickComponent implements OnInit {
@ViewChild(DatatableComponent) newstable:DatatableComponent;
@ViewChild('form') form;
value:any;
serviceHost = BackendHost;
bannerblockrows = [];
paring=[];
bannerblocktemp = [];
bannerblocklist = [];
modalRef: NgbModalRe... | this.toastr.error('Please choose a right file!', 'Error');
this.filesToUploads=[];
this.urls=[];
this.filenames='';
this.img_selected=false;
}
}
onsubmit(form: NgForm){
if(this.paring.length > 0){
if(this.img_selected == false){
this.toastr.error('Please | {
this.filesToUploads=[];
var path = fileInput.target.files[0].type;
if(path == "image/jpeg" || path == "image/gif" || path == "image/jpg" || path == "image/png")
{
this.filesToUploads = <Array<File>>fileInput.target.files;
this.filenames = fileInput.target.files[0].name;
let files =... | identifier_body |
main.go | nil
}
func InputExpiresTime() (int64, error) {
var (
err error
expiresAt int64
)
fmt.Printf("%s\n", "请输入过期时间(格式:数字+单位,例如12d, 单位:天[d] 分钟[m] 秒[s] 年[y]):")
input, err := inputReader.ReadString('\n')
if err != nil {
return 0, err
}
defer inputReader.Reset(os.Stdin)
inputString := strings.TrimSpace(i... | }
expiresAt = int64(days * OneDaySeconds)
duration := time.Duration(expiresAt) * time.Second
fmt.Println()
fmt.Printf("过期天数: %d days, 过期日期:%s \n", days, time.Now().Add(duration).Format("2006-01-02 15:04:05"))
fmt.Println()
} else if strings.HasSuffix(inputString, "m") {
inputString = inputStrin... | random_line_split | |
main.go | }
func InputExpiresTime() (int64, error) {
var (
err error
expiresAt int64
)
fmt.Printf("%s\n", "请输入过期时间(格式:数字+单位,例如12d, 单位:天[d] 分钟[m] 秒[s] 年[y]):")
input, err := inputReader.ReadString('\n')
if err != nil {
return 0, err
}
defer inputReader.Reset(os.Stdin)
inputString := strings.TrimSpace(input)... | fmt.Println(base64.URLEncoding.Encod
eToString(licenseActive))
// fmt.Println(string(licenseActive))
}
func ReadCustomKV(productName string) ([]AttrKV, error) {
type Option struct {
XMLName xml.Name `xml:"option"`
Desc string `xml:"desc"`
Key string `xml:"key"`
Value string `xml:"val"`
}
t... |
fmt.Println()
fmt.Printf("你输入的机器码是: %s\n", inputString)
fmt.Println()
}
return inputString, nil
}
func ShowActiveCode(dir, fileName, uuid string) {
fmt.Printf("序号:%s \n", uuid)
fmt.Printf("\n%s\n", "激活码是:")
readPath := filepath.Join(dir, fileName)
licenseActive, err := public.ReadLicensePem(readPath)
i... | identifier_body |
main.go |
}
func InputExpiresTime() (int64, error) {
var (
err error
expiresAt int64
)
fmt.Printf("%s\n", "请输入过期时间(格式:数字+单位,例如12d, 单位:天[d] 分钟[m] 秒[s] 年[y]):")
input, err := inputReader.ReadString('\n')
if err != nil {
return 0, err
}
defer inputReader.Reset(os.Stdin)
inputString := strings.TrimSpace(input... | l {
return nil, err
}
defer inputReader.Reset(os.Stdin)
inputString := strings.TrimSpace(input)
if inputString != "" {
if strings.HasPrefix(inputString, "q") {
os.Exit(0)
}
arrayIndx := strings.Split(inputString, ",")
for i := 0; i < len(arrayIndx); i++ {
num := strings.TrimSpace(array... | ing('\n')
if err != ni | conditional_block |
main.go |
}
func InputExpiresTime() (int64, error) {
var (
err error
expiresAt int64
)
fmt.Printf("%s\n", "请输入过期时间(格式:数字+单位,例如12d, 单位:天[d] 分钟[m] 秒[s] 年[y]):")
input, err := inputReader.ReadString('\n')
if err != nil {
return 0, err
}
defer inputReader.Reset(os.Stdin)
inputString := strings.TrimSpace(input... | {
os.Exit(0)
}
fmt.Println()
fmt.Printf("你输入的机器码是: %s\n", inputString)
fmt.Println()
}
return inputString, nil
}
func ShowActiveCode(dir, fileName, uuid string) {
fmt.Printf("序号:%s \n", uuid)
fmt.Printf("\n%s\n", "激活码是:")
readPath := filepath.Join(dir, fileName)
licenseActive, err := public.ReadLice... | tString, "q") | identifier_name |
scope-auth.go | }
}
} else {
// Access token: Get authorization from header or coockie.
jwtStr, jwtExists = extractJWT(ctx, logger)
}
// Get scopes of endpoint.
validScopes, err := scopeauth.GetScopes(service,
strings.ToUpper(ctx.Request.Method), ctx.Request.URL.Path)
if err != nil {
logger.Info("can't fi... | {
return result.Error
} | conditional_block | |
scope-auth.go | s.",
ctx.Request.Method, service, ctx.Request.URL.Path)
ctx.Abort()
return
}
appCtx.RequiredScopes = validScopes
logger.Debug("required scopes: %s", validScopes)
validScopeMap := make(map[types.Scope]struct{})
hasPublicScope := false
for _, s := range validScopes {
if s == types.ScopePublic {
... | extractJWT | identifier_name | |
scope-auth.go | bool
if len(strings.Split(ctx.GetHeader("Authorization"), ".")) == 4 {
// API token
vErr := validateAPIToken(appCtx, store,
ctx.GetHeader("Authorization"))
if vErr != nil {
logger.Error("api token is invalid: %v", vErr)
} else {
jwtExists = true
}
} else if len(strings.Split(ctx.GetHeade... | logger.Error("authentication failed with invalid JWT. err: %+v", err)
appCtx.SetError(apierrors.AuthenticationError)
}
return
}
logger.SetLabel(logging.LabelUserDeviceID, deviceAuthorizationID.String())
appCtx.Platform = devicePlatform
appCtx.UserID = userID
appCtx.AccessTokenID = acce... | ctx.Next()
} else { | random_line_split |
scope-auth.go | appCtx.UserID = userID
appCtx.AccessTokenID = accessTokenID
appCtx.DeviceAuthorizationID = deviceAuthorizationID
appCtx.UserAuthorizationScopes = userScopes
}
logger.SetLabel(logging.LabelUserID, appCtx.UserID.String())
logger.Debug("user scopes: %s", appCtx.UserAuthorizationScopes)
if hasPublicSc... | {
claims, isExpired, delErr := jwtFactory.Build(jwtFactory.AccessTokenObj{}).
Validate(jwtStr, serviceName)
if delErr != nil || isExpired {
userID = nil
deviceAuthorizationID = nil
accessTokenID = nil
userScopes = nil
if isExpired {
err = fmt.Errorf("token <%v> expired", accessTokenID)
} else {
er... | identifier_body | |
ts_analyzer.py | str(last_section_number)+"</last_section_number>")
for i in range(0,(section_length-5-4)/4):
# print(" <program>")
cursor+=4
program_num = (ord(f[9+i:10+i]) << 8) | ord(f[10+i:11+i])
b1 = ord(f[11+i:12+i])
b2 = ord(f[12+i:13+i])
if b1 & 0xE0 != 0xE0:
... |
length = additional_length+1 # size byte
additional_length-=1 # flags
def read_pcr():
pcr_byte_1 = ord(f.read(1)) # base
pcr_byte_2 = ord(f.read(1)) # base
pcr_byte_3 = ord(f.read(1)) # base
pcr_byte_4 = ord(f.read(1)) # base
pcr_byte_5 = ord(f.read(1)) # 1 bit bas... | print(" <elementary_stream_priority/>\n") | conditional_block |
ts_analyzer.py | (program_num)+"</program_num>")
# print(" <program_pid>"+hex(program_pid)+"</program_pid>")
# print(" </program>\n")
#program_map_pids.add(program_pid)
crc32 = f[cursor:cursor+4]; cursor+=4
length -= cursor
if length>0:
rest = f[cursor:cursor+length]
... | from platform import uname
hostname = uname()[1]
self.render('self_log.html',buf=buf, hostname=hostname) | identifier_body | |
ts_analyzer.py | .datetime.now()-start_time_packet
if diff.total_seconds() >= '30':
bits_second=1
start_time_packet=datetime.datetime.now()
else:
bits_second=1+bits_second
for i in range(0,len(data),188):
offset =+ i
#print(offset)
sync = or... | random_line_split | ||
ts_analyzer.py | (sig, frame):
tornado.ioloop.IOLoop.instance().add_callback(tornado.ioloop.IOLoop.instance().stop)
if sys.version_info >= (3, 0):
LINESEP = os.linesep.encode()
else:
LINESEP = os.linesep
def output_program_association_table(f, length, payload_start):
#pids[mcast][pid]['extra']='test'
#print(" <... | handle_signal | identifier_name | |
map_output_tracker.rs | Ext,
};
use tokio_util::compat::{Tokio02AsyncReadCompatExt, Tokio02AsyncWriteCompatExt};
const CAPNP_BUF_READ_OPTS: ReaderOptions = ReaderOptions {
traversal_limit_in_words: std::u64::MAX,
nesting_limit: 64,
};
pub(crate) enum MapOutputTrackerMessage {
// Contains shuffle_id
GetMapOutputLocations(i64)... | random_line_split | ||
map_output_tracker.rs | };
use capnp_futures::serialize as capnp_serialize;
use dashmap::{DashMap, DashSet};
use parking_lot::Mutex;
use thiserror::Error;
use tokio::{
net::{TcpListener, TcpStream},
stream::StreamExt,
};
use tokio_util::compat::{Tokio02AsyncReadCompatExt, Tokio02AsyncWriteCompatExt};
const CAPNP_BUF_READ_OPTS: Reader... | (is_master: bool, master_addr: SocketAddr) -> Self {
let output_tracker = MapOutputTracker {
is_master,
server_uris: Arc::new(DashMap::new()),
fetching: Arc::new(DashSet::new()),
generation: Arc::new(Mutex::new(0)),
master_addr,
};
outp... | new | identifier_name |
map_output_tracker.rs | };
use capnp_futures::serialize as capnp_serialize;
use dashmap::{DashMap, DashSet};
use parking_lot::Mutex;
use thiserror::Error;
use tokio::{
net::{TcpListener, TcpStream},
stream::StreamExt,
};
use tokio_util::compat::{Tokio02AsyncReadCompatExt, Tokio02AsyncWriteCompatExt};
const CAPNP_BUF_READ_OPTS: Reader... | else {
// TODO: error logging
}
}
pub async fn get_server_uris(&self, shuffle_id: usize) -> Result<Vec<String>> {
log::debug!(
"trying to get uri for shuffle task #{}, current server uris: {:?}",
shuffle_id,
self.server_uris
);
i... | {
if arr.get(map_id).unwrap() == &Some(server_uri) {
self.server_uris
.get_mut(&shuffle_id)
.unwrap()
.insert(map_id, None)
}
self.increment_generation();
} | conditional_block |
core.py | , -1, style=wx.LC_REPORT)
ListCtrlAutoWidthMixin.__init__(self)
class Core(wx.Frame):
def __init__(self, parent, controller, title):
super(Core, self).__init__(parent=parent, title=title)
self.parent = parent
self.controller = controller
self.child = None
self.panel... |
# noinspection PyUnusedLocal
def on_quit(self, event):
self.parent.Enable()
self.Destroy()
class PanelExtract(wx.Panel):
def __init__(self, parent):
super(PanelExtract, self).__init__(parent)
# Attributes
self.day = wx.TextCtrl(self)
# Layout
text_... | wx.MessageBox('Please set a day to extract!', '', OK) | conditional_block |
core.py | parent, -1, style=wx.LC_REPORT)
ListCtrlAutoWidthMixin.__init__(self)
class Core(wx.Frame):
def __init__(self, parent, controller, title):
super(Core, self).__init__(parent=parent, title=title)
self.parent = parent
self.controller = controller
self.child = None
sel... | def on_new_player(self, event):
self.child = ViewPlayer(parent=self, title='New Player')
self.show_child()
# noinspection PyUnusedLocal
def on_quit(self, event):
self.Destroy()
# noinspection PyUnusedLocal
def on_refresh(self, event):
self.panel.players.DeleteAllIte... | ViewPlayer(parent=self, title='Edit Player', is_editor=True)
# noinspection PyUnusedLocal | random_line_split |
core.py | , -1, style=wx.LC_REPORT)
ListCtrlAutoWidthMixin.__init__(self)
class Core(wx.Frame):
def __init__(self, parent, controller, title):
super(Core, self).__init__(parent=parent, title=title)
self.parent = parent
self.controller = controller
self.child = None
self.panel... |
# noinspection PyUnusedLocal
def on_extract(self, event):
day = self.panel.day.GetValue()
if day:
if self.controller.are_evaluations_ready(day):
self.controller.extract_evaluations(day)
self.parent.Enable()
self.Destroy()
... | self.parent = parent
self.title = title
super(ViewExtract, self).__init__(parent=self.parent, title=title)
self.controller = self.parent.controller
self.panel = PanelExtract(parent=self)
self.SetSize((300, 150))
# bindings
self.Bind(wx.EVT_CLOSE, self.on_quit)
... | identifier_body |
core.py | , -1, style=wx.LC_REPORT)
ListCtrlAutoWidthMixin.__init__(self)
class Core(wx.Frame):
def __init__(self, parent, controller, title):
super(Core, self).__init__(parent=parent, title=title)
self.parent = parent
self.controller = controller
self.child = None
self.panel... | (self, parent):
super(PanelExtract, self).__init__(parent)
# Attributes
self.day = wx.TextCtrl(self)
# Layout
text_sizer = wx.FlexGridSizer(rows=1, cols=2, hgap=5, vgap | __init__ | identifier_name |
index.js | Info(function(u) {
that.__loadComdata();
that.__loadRecent();
that.__loadRecommend();
// that.__checkTwxx();
that.__checkToken();
setTimeout(function() {
that.__checkCoupon();
}, 666);
});
_my.getSt... | _subjects[i][10] = sname.substr(0, 7);
_subjects[i][11] = sname.substr(7);
if (sname.indexOf("下午题") > -1) {
_subjects[i][12] = "T2";
if (sname.indexOf("Ⅱ") > -1) {
_subjects[i][12] = "T3";
}
}
if (_... | etData(_data);
});
},
__formatSubject: function(_subjects) {
for (let i = 0; i < _subjects.length; i++) {
let sname = _subjects[i][1];
| conditional_block |
index.js | app.getUserInfo(function(u) {
that.__loadComdata();
that.__loadRecent();
that.__loadRecommend();
// that.__checkTwxx();
that.__checkToken();
setTimeout(function() {
that.__checkCoupon();
}, 666);
});
... | for (let k in _data.reddot) {
app.showReddot(_data.reddot[k], k);
}
}
that.setData({
icontext: _data.icontext || null,
declaration: _data.declaration || null,
openAis: _data.open_ais === true
... | });
} // 红点
if (_data.reddot) { | random_line_split |
main.py | hello = data["credits"]
hello1 = hello["crew"]
for x in hello1:
if x["job"] == "Director":
directors.append(x["name"])
training_texts.append(str(directors))
#Goes through the movies that the user doesn't like and pulls the above mentioned parameters from TMDB to store in training_texts
for x in... |
#Looking at how the code makes its decisions visually is alot easier so I export the model to the tree.dot file. Upon copying all the data in tree.dot and pasting it in the textbox on http://www.webgraphviz.com/ you can see what the decision making process looks like.
tree.export_graphviz( | random_line_split | |
main.py | = response.json()
training_texts.append(data["results"][0]["overview"])
training_texts.append(str(data["results"][0]["genre_ids"]))
movie_id = data["results"][0]["id"]
httpRequest2 = "https://api.themoviedb.org/3/movie/" + str(movie_id) + "?api_key=" + APIKey + "&append_to_response=credits"
response = reque... | likeDict['will probably not like'] += (movie + ", ") | conditional_block | |
data.py | , app, backend, moduleRefs, locations, modules, version, checkout, silent
):
"""Collects TF data according to specifications.
The specifications are passed as arguments when the object is initialized.
Parameters
----------
backend: string
`github` or `gitlab` or... | provenance = self.provenance
self.mLocations = []
mLocations = self.mLocations
self.locations = None
self.modules = None
self.good = True
self.seen = set()
self.getMain()
self.getRefs()
self.getStandard()
version = self.version
... | random_line_split | |
data.py | , app, backend, moduleRefs, locations, modules, version, checkout, silent
):
"""Collects TF data according to specifications.
The specifications are passed as arguments when the object is initialized.
Parameters
----------
backend: string
`github` or `gitlab` or... |
info = {}
for item in (
("doi", None),
("corpus", f"{org}/{repo}{relative}"),
):
(key, default) = item
info[key] = (
getattr(aContext, key)
if isBase
else specs[key]
if specs and key... | app.repoLocation = repoLocation | conditional_block |
data.py | :
def __init__(
self, app, backend, moduleRefs, locations, modules, version, checkout, silent
):
"""Collects TF data according to specifications.
The specifications are passed as arguments when the object is initialized.
Parameters
----------
backend: string
... | AppData | identifier_name | |
data.py | One or more directory path segments. They will be appended to the
paths given by the `locations` argument to form search locations
for TF data files.
version: string
The version of TF data that should be retrievend. Version is a directory
level just be... | def __init__(
self, app, backend, moduleRefs, locations, modules, version, checkout, silent
):
"""Collects TF data according to specifications.
The specifications are passed as arguments when the object is initialized.
Parameters
----------
backend: string
... | identifier_body | |
preprocess_03.py | print('Check: ' + str(length) + ' < ' + str(total_time*fs1//(2*q)))
raise ValueError('Length FFT_side != length: ' + str(len(FFT_side)) + ' != ' + str(length))
FFT_log = []
# normalize FFT
for value in FFT_side:
value = np.log(value)
FFT_log.append(value)
ma... | # self.X is dictionary of dir:[input_nodes1,input_nodes2]
# self.Y is dictionary of dir:[output_nodes1,output_nodes2]
# self.Y corresponds to self.X
self.X = [] # list of input vectors
self.Y = [] # list of output vectors
#if process == False:
#self.loadData(... | def __init__(self):
"""data_file (string): contains the file to load or store data, ex)data.txt
process (bool): if False, load data from data_file,
if True, process data in directory & store in data_file
directory (string): (optional) directory of data to be p... | identifier_body |
preprocess_03.py | print('Check: ' + str(length) + ' < ' + str(total_time*fs1//(2*q)))
raise ValueError('Length FFT_side != length: ' + str(len(FFT_side)) + ' != ' + str(length))
FFT_log = []
# normalize FFT
for value in FFT_side:
value = np.log(value)
FFT_log.append(value)
ma... |
m = getMax(output)[1]
for i,value in enumerate(output):
output[i] = value/m
return np.array(output)
def mean(array_list):
"""Returns the mean of an array or list"""
count = 0.0
for value in array_list:
count += value
return count/len(array_list)
def downsampl... | for i in range(len(mfcc)):
for j in range(len(mfcc[0])):
output.append(mfcc[i][j]) | random_line_split |
preprocess_03.py | ])
plt.plot(freqs_divided,FFT_divided) # plotting the complete fft spectrum
plt.show()
return FFT_divided
def processMPCC(filename,subsample=2048):
#assume 8000Hz
#amplify high frequencies
#Setup
try:
fs, signal = wavfile.read(filename) # File assumed to be in the sa... | getOutputNames | identifier_name | |
preprocess_03.py | ): contains the file to load or store data, ex)data.txt
process (bool): if False, load data from data_file,
if True, process data in directory & store in data_file
directory (string): (optional) directory of data to be processed
"""
# Ex) self.output['... | y = []
for ele in self.Y[i]:
y.append(float(ele))
Y.append(y) # -> fine | conditional_block | |
lib.rs | VertexHandle};
/// The three basic elements in a polygon mesh.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum | {
Edge,
Face,
Vertex,
}
// ===========================================================================
// ===== `Sealed` trait
// ===========================================================================
pub(crate) mod sealed {
/// A trait that cannot be implemented outside of this crate.
///
... | MeshElement | identifier_name |
lib.rs | VertexHandle};
/// The three basic elements in a polygon mesh.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MeshElement {
Edge,
Face,
Vertex,
}
// ===========================================================================
// ===== `Sealed` trait
// =============================================... | /// };
///
///
/// #[derive(MemSource)]
/// struct MyMesh {
/// #[lox(core_mesh)]
/// mesh: SharedVertexMesh,
///
/// #[lox(vertex_position)]
/// positions: DenseMap<VertexHandle, Point3<f32>>,
/// }
/// ```
///
/// Deriving this trait works very similar to deriving [`MemSink`]. See its
/// documentatio... | /// MemSource, VertexHandle,
/// cgmath::Point3,
/// ds::SharedVertexMesh,
/// map::DenseMap, | random_line_split |
main.rs | .iter().enumerate() {
raw_futures.push(get_listing(&client, &marker.id, index));
}
let unpin_futures: Vec<_> = raw_futures.into_iter().map(Box::pin).collect();
let mut mut_futures = unpin_futures;
let mut documents: HashMap<String, Html> = HashMap::new();
let mut size: usize = 0;
let mut current: f32 = 0.0;
... | filename: &str) - | identifier_name | |
main.rs | Ok(())
}
async fn get_session_id(client: &request::Client) -> SureResult<String> {
let re = Regex::new(r#"(PHPSESSID=[\w\S]+);"#).unwrap();
let res = client
.get("https://www.utahrealestate.com/index/public.index")
.header(USER_AGENT, SURE_USER_AGENT)
.send()
.await?;
let sessid = res.headers().get("set-c... | io::stdout()
.write(
format!(
"\rdownloading listings {}/{}: [{}>{}]",
current,
total,
"=".repeat(percentage),
" ".repeat(50 - percentage),
)
.as_bytes(),
)
.unwrap();
io::stdout().flush().unwrap();
size += content_length;
documents.ins... | (Ok((id, _idx, document, content_length)), _index, remaining) => {
current += 1.0;
let percentage = (((current / total as f32) * 100.0) / 2.0) as usize; | random_line_split |
main.rs | Ok(())
}
async fn get_session_id(client: &request::Client) -> SureResult<String> {
let re = Regex::new(r#"(PHPSESSID=[\w\S]+);"#).unwrap();
let res = client
.get("https://www.utahrealestate.com/index/public.index")
.header(USER_AGENT, SURE_USER_AGENT)
.send()
.await?;
let sessid = res.headers().get("set-co... | // Utility Functions
///
fn get_checked_listings() -> Vec<String> {
let mut checked_mls: Vec<String> = vec![];
if let Ok(lines) = read_lines(&get_sure_filepath("listings.txt")) {
for line in lines {
if let Ok(l) = line {
checked_mls.push(String::from(l.trim()))
}
| ror!(
"error sending message: {:?}\n\t└──{}\n\t└──{:?}",
res.status(),
res.text().await?,
params
)
}
Ok(())
}
///
/ | conditional_block |
main.rs |
/// easily remove all the neighbors of a vertex from a state very efficiently.
neighbors: Vec<BitSet>,
/// For each vertex 'i', the value of 'weight[i]' denotes the weight associated
/// to vertex i in the problem instance. The goal of MISP is to select the nodes
/// from the underlying graph such ... |
}
/// In addition to a dynamic programming (DP) model of the problem you want to solve,
/// the branch and bound with MDD algorithm (and thus ddo) requires that you provide
/// an additional relaxation allowing to control the maximum amount of space used by
/// the decision diagrams that are compiled.
///
/// That... | {
state.contains(var.id())
} | identifier_body |
main.rs | /// of the DP model. That DP model is pretty straightforward, still you might want
/// to check the implementation of the branching heuristic (next_variable method)
/// since it does interesting stuffs.
impl Problem for Misp {
type State = BitSet;
fn nb_variables(&self) -> usize {
self.nb_vars
}
... | {
continue;
} | conditional_block | |
main.rs |
/// easily remove all the neighbors of a vertex from a state very efficiently.
neighbors: Vec<BitSet>,
/// For each vertex 'i', the value of 'weight[i]' denotes the weight associated
/// to vertex i in the problem instance. The goal of MISP is to select the nodes
/// from the underlying graph such ... |
fn initial_state(&self) -> Self::State {
(0..self.nb_variables()).collect()
}
fn initial_value(&self) -> isize {
0
}
fn transition(&self, state: &Self::State, decision: Decision) -> Self::State {
let mut res = state.clone();
res.remove(decision.variable.id());
... | fn nb_variables(&self) -> usize {
self.nb_vars
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.