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 |
|---|---|---|---|---|
binder.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{
capability::{
CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability,
OptionalTas... | (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 | import argparse
import glob
import logging
import os
import h5py
from joblib import Parallel, delayed
from natsort import natsorted
import numpy as np
import scipy.ndimage
import scipy.stats
import skimage.io as io
import tifffile
import zarr
logger = logging.getLogger(__name__)
def load_array(filename):
if file... |
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 | import argparse
import glob
import logging
import os
import h5py
from joblib import Parallel, delayed
from natsort import natsorted
import numpy as np
import scipy.ndimage
import scipy.stats
import skimage.io as io
import tifffile
import zarr
logger = logging.getLogger(__name__)
def load_array(filename):
if file... | (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 | import argparse
import glob
import logging
import os
import h5py
from joblib import Parallel, delayed
from natsort import natsorted
import numpy as np
import scipy.ndimage
import scipy.stats
import skimage.io as io
import tifffile
import zarr
logger = logging.getLogger(__name__)
def load_array(filename):
if file... | f = zarr.open(out_fn + '.zarr', 'w')
f.create_dataset(
'volumes/raw',
data=raw,
chunks=(2, 256, 256),
compression='gzip')
f.create_dataset(
'volumes/raw_gfp',
data=raw_gfp,
chunks=(1, 256, 256),
compression='gzip')
f.create_dataset(
... |
if args.out_format == "hdf":
f = h5py.File(out_fn + '.hdf', 'w')
elif args.out_format == "zarr": | random_line_split |
consolidate_data.py | import argparse
import glob
import logging
import os
import h5py
from joblib import Parallel, delayed
from natsort import natsorted
import numpy as np
import scipy.ndimage
import scipy.stats
import skimage.io as io
import tifffile
import zarr
logger = logging.getLogger(__name__)
def load_array(filename):
if file... |
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 | #![allow(unused_doc_comment)]
/// # swiggen
///
/// The `swiggen` library is used to generate `extern "C"` definitions and
/// SWIG wrapper code from Rust functions.
///
/// This basically does two things: generates the `extern "C"` methods by
/// applying typemaps from cbindgen, or some fairly crude heuristics -
//... | }
acc
},
_ => Vec::new(),
}
})
},
syn::Item::Struct(syn::ItemStruct { attrs, ident, .. }) |
syn::Item::Fn(syn::ItemFn { attrs, ident... | 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 | #![allow(unused_doc_comment)]
/// # swiggen
///
/// The `swiggen` library is used to generate `extern "C"` definitions and
/// SWIG wrapper code from Rust functions.
///
/// This basically does two things: generates the `extern "C"` methods by
/// applying typemaps from cbindgen, or some fairly crude heuristics -
//... |
/// Write the swig code (injected via doc comments) into `swig.i`.
/// This parses expanded Rust code, and writes the SWIG code to a file.
pub fn gen_swig(pkg_name: &str, src: &str) {
let mut tmp_file = File::create("swig.i").unwrap();
tmp_file.write_all(format!("\
%module {name}
#define PKG_NAME {name}
%inc... | {
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 | #![allow(unused_doc_comment)]
/// # swiggen
///
/// The `swiggen` library is used to generate `extern "C"` definitions and
/// SWIG wrapper code from Rust functions.
///
/// This basically does two things: generates the `extern "C"` methods by
/// applying typemaps from cbindgen, or some fairly crude heuristics -
//... | (ast: &syn::ItemImpl) -> TokenStream {
let mut tokens = TokenStream::new();
tokens.append_all(ast.items.iter().filter_map(|item| {
match item {
syn::ImplItem::Method(iim) => {
if iim.sig.abi.is_c(){
Some(item.into_token_stream())
} else {
... | split_out_externs | identifier_name |
park.rs | use std::{
cell::Cell,
sync::atomic::{AtomicBool, Ordering},
thread::{self, Thread},
};
use conquer_util::BackOff;
use crate::{
cell::{Block, Unblock},
state::{
AtomicOnceState, BlockedState,
OnceState::{Ready, Uninit, WouldBlock},
},
POISON_PANIC_MSG,
};
use self::interna... | (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 | use std::{
cell::Cell,
sync::atomic::{AtomicBool, Ordering},
thread::{self, Thread},
};
use conquer_util::BackOff;
use crate::{
cell::{Block, Unblock},
state::{
AtomicOnceState, BlockedState,
OnceState::{Ready, Uninit, WouldBlock},
},
POISON_PANIC_MSG,
};
use self::interna... |
}
/// A linked list node that lives on the stack of a parked thread.
#[repr(align(4))]
pub(crate) struct StackWaiter {
/// The flag marking the waiter as either blocked or ready to proceed.
///
/// This is read by the owning thread and is set by the thread that gets to
/// run the initialization closu... | {
// 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 | use std::{
cell::Cell,
sync::atomic::{AtomicBool, Ordering},
thread::{self, Thread},
};
use conquer_util::BackOff;
use crate::{
cell::{Block, Unblock},
state::{
AtomicOnceState, BlockedState,
OnceState::{Ready, Uninit, WouldBlock},
},
POISON_PANIC_MSG,
};
use self::interna... | }
}
}
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 | # -*- coding: utf-8 -*-
"""
Modul do zapisu piosenki (wczytywanie ustawien (defs.txt), tworzenie .wav,
"zglasnianie utworu")
"""
print("Laduje modul o nazwie: "+__name__)
import numpy as np
def wczytywanie_ustawien(plik_konfiguracyjny = "defs.txt"):
"""
wczytywanie pl... | 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 | # -*- coding: utf-8 -*-
"""
Modul do zapisu piosenki (wczytywanie ustawien (defs.txt), tworzenie .wav,
"zglasnianie utworu")
"""
print("Laduje modul o nazwie: "+__name__)
import numpy as np
def wczytywanie_ustawien(plik_konfiguracyjny = "defs.txt"):
"""
wczytywanie pl... |
else:
T[poczatek_cwiercnuty:(poczatek_cwiercnuty + maksik)] += \
cwiercnuta
T= np.array(T, dtype=np.int16)
#ustalamy glosnosc utworu
T = zmiana_glosnosci(T,... | poczatek_cwiercnuty:(poczatek_cwiercnuty + maksik)]=\
cwiercnuta[0:len(T[poczatek_cwiercnuty:(poczatek_cwiercnuty +\
maksik)])]
| conditional_block |
zapis.py | # -*- coding: utf-8 -*-
"""
Modul do zapisu piosenki (wczytywanie ustawien (defs.txt), tworzenie .wav,
"zglasnianie utworu")
"""
print("Laduje modul o nazwie: "+__name__)
import numpy as np
def wczytywanie_ustawien(plik_konfiguracyjny = "defs.txt"):
"""
wczytywanie pl... | #wages = b['wages'])
#wierszyk = tworzenie_piosenki(pios, k, **b)
#wierszyk | #pios, k = wczytywanie_sciezek(a)
#wierszyk = tworzenie_piosenki(pios, k, bpm = b['bpm'], freq = b['freq'], \
| random_line_split |
zapis.py | # -*- coding: utf-8 -*-
"""
Modul do zapisu piosenki (wczytywanie ustawien (defs.txt), tworzenie .wav,
"zglasnianie utworu")
"""
print("Laduje modul o nazwie: "+__name__)
import numpy as np
def wczytywanie_ustawien(plik_konfiguracyjny = "defs.txt"):
"""
wczytywanie pl... |
#pios, k = wczytywanie_sciezek(a)
#wierszyk = tworzenie_piosenki(pios, k, bpm = b['bpm'], freq = b['freq'], \
#wages = b['wages'])
#wierszyk = tworzenie_piosenki(pios, k, **b)
#wierszyk | ""
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 | use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use ring::digest::Algorithm;
use crate::hashutils::HashUtils;
use crate::tree::Tree;
/// An inclusion proof represent the fact that a `value` is a member
/// of a `MerkleTree` with root hash `root_hash`, and hash function `algorithm`.
#[cfg_attr(feature = "seria... |
}
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 | use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use ring::digest::Algorithm;
use crate::hashutils::HashUtils;
use crate::tree::Tree;
/// An inclusion proof represent the fact that a `value` is a member
/// of a `MerkleTree` with root hash `root_hash`, and hash function `algorithm`.
#[cfg_attr(feature = "seria... | else {
None
}
}
fn new_tree_proof<T>(
hash: &[u8],
needle: &[u8],
left: &Tree<T>,
right: &Tree<T>,
) -> Option<Lemma> {
Lemma::new(left, needle)
.map(|lemma| {
let right_hash = right.hash().clone();
let... | {
Some(Lemma {
node_hash: hash.into(),
sibling_hash: None,
sub_lemma: None,
})
} | conditional_block |
proof.rs | use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use ring::digest::Algorithm;
use crate::hashutils::HashUtils;
use crate::tree::Tree;
/// An inclusion proof represent the fact that a `value` is a member
/// of a `MerkleTree` with root hash `root_hash`, and hash function `algorithm`.
#[cfg_attr(feature = "seria... | <T>(
hash: &[u8],
needle: &[u8],
left: &Tree<T>,
right: &Tree<T>,
) -> Option<Lemma> {
Lemma::new(left, needle)
.map(|lemma| {
let right_hash = right.hash().clone();
let sub_lemma = Some(Positioned::Right(right_hash));
... | new_tree_proof | identifier_name |
proof.rs | use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use ring::digest::Algorithm;
use crate::hashutils::HashUtils;
use crate::tree::Tree;
/// An inclusion proof represent the fact that a `value` is a member
/// of a `MerkleTree` with root hash `root_hash`, and hash function `algorithm`.
#[cfg_attr(feature = "seria... | 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 | mod capture;
mod d3d;
mod displays;
mod hotkey;
mod media;
mod resolution;
mod video;
use std::{path::Path, time::Duration};
use clap::{App, Arg, SubCommand};
use hotkey::HotKey;
use windows::{
core::{Result, RuntimeName},
Foundation::Metadata::ApiInformation,
Graphics::{
Capture::{GraphicsCapture... |
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 | mod capture;
mod d3d;
mod displays;
mod hotkey;
mod media;
mod resolution;
mod video;
use std::{path::Path, time::Duration};
use clap::{App, Arg, SubCommand};
use hotkey::HotKey;
use windows::{
core::{Result, RuntimeName},
Foundation::Metadata::ApiInformation,
Graphics::{
Capture::{GraphicsCapture... |
fn required_capture_features_supported() -> Result<bool> {
let result = ApiInformation::IsTypePresent(GraphicsCaptureSession::NAME)? && // Windows.Graphics.Capture is present
GraphicsCaptureSession::IsSupported()? && // The CaptureService is available
win32_programmatic_capture_supported()?;
Ok(result... | {
ApiInformation::IsApiContractPresentByMajor("Windows.Foundation.UniversalApiContract", 8)
} | identifier_body |
main.rs | mod capture;
mod d3d;
mod displays;
mod hotkey;
mod media;
mod resolution;
mod video;
use std::{path::Path, time::Duration};
use clap::{App, Arg, SubCommand};
use hotkey::HotKey;
use windows::{
core::{Result, RuntimeName},
Foundation::Metadata::ApiInformation,
Graphics::{
Capture::{GraphicsCapture... |
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 | mod capture;
mod d3d;
mod displays;
mod hotkey;
mod media;
mod resolution;
mod video;
use std::{path::Path, time::Duration};
use clap::{App, Arg, SubCommand};
use hotkey::HotKey;
use windows::{
core::{Result, RuntimeName},
Foundation::Metadata::ApiInformation,
Graphics::{
Capture::{GraphicsCapture... | (
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 | # Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 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 | # Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
def create_target_metrics_highlight(
target_name: Text,
metric_name_list: List[Text],
metric_analysis_list: List[List[Analysis]]
) -> Text:
# pylint: disable-msg=too-many-locals
"""Create the content for highlight section regarding a target attribute
Args:
target_name: (string)
metric_... | """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 | # Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | (
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 | # Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
row_content_list = []
for attribute in attribute_set:
values_str = '|'.join(
[formatting.numeric_formatting(metric_holders[metric][attribute])
for metric in metric_name_list])
row_content_list.append(row_template.format(
name=attribute,
values=values_str
))
return t... | 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 | use bytes::Bytes;
use failure::Error;
use futures::prelude::*;
use futures::ready;
use log::{debug, info, trace, warn};
use tokio::time::{self, delay_for, interval, Delay, Interval};
use crate::connection::HandshakeReturner;
use crate::loss_compression::compress_loss_list;
use crate::packet::{ControlPacket, ControlTyp... |
fn make_control_packet(&self, control_type: ControlTypes) -> Packet {
Packet::Control(ControlPacket {
timestamp: self.get_timestamp_now(),
dest_sockid: self.settings.remote_sockid,
control_type,
})
}
/// Timestamp in us
fn get_timestamp_now(&self) -... | {
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 | use bytes::Bytes;
use failure::Error;
use futures::prelude::*;
use futures::ready;
use log::{debug, info, trace, warn};
use tokio::time::{self, delay_for, interval, Delay, Interval};
use crate::connection::HandshakeReturner;
use crate::loss_compression::compress_loss_list;
use crate::packet::{ControlPacket, ControlTyp... | (&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 | use bytes::Bytes;
use failure::Error;
use futures::prelude::*;
use futures::ready;
use log::{debug, info, trace, warn};
use tokio::time::{self, delay_for, interval, Delay, Interval};
use crate::connection::HandshakeReturner;
use crate::loss_compression::compress_loss_list;
use crate::packet::{ControlPacket, ControlTyp... | return Ok(());
}
trace!("Received packet: {:?}", packet);
match packet {
Packet::Control(ctrl) => {
// handle the control packet
match &ctrl.control_type {
ControlTypes::Ack { .. } => warn!("Receiver received ACK pack... | 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 | // Copyright Jetstack Ltd. See LICENSE for details.
// Copyright © 2017 The Kubicorn Authors
//
// 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/LICEN... |
return &Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
}
}
| identifier_body | |
cluster.go | // Copyright Jetstack Ltd. See LICENSE for details.
// Copyright © 2017 The Kubicorn Authors
//
// 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/LICEN... | name string) *Cluster {
return &Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
}
}
| ewCluster( | identifier_name |
cluster.go | // Copyright Jetstack Ltd. See LICENSE for details.
// Copyright © 2017 The Kubicorn Authors
//
// 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/LICEN... | // 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 | package main
import (
"log"
"math"
"strings"
)
type MD struct {
Open float64
High float64
Low float64
Close float64
Qty float64
Vol float64
Vwap float64
Ask float64
Bid float64
AskSize float64
BidSize float64
}
type Security struct {
Id int64
Symbol st... | (msg []interface{}) {
acc := int(msg[1].(float64))
securityId := int64(msg[2].(float64))
p := getPos(acc, securityId)
// ignore unrealizedPnl and realizedPnl which we can deduce ourself
if len(msg) > 4 {
p.Commission = msg[4].(float64)
}
}
func ParseMd(msg []interface{}) {
for i := 1; i < len(msg); i++ {
da... | ParsePnl | identifier_name |
orderbook.go | package main
import (
"log"
"math"
"strings"
)
type MD struct {
Open float64
High float64
Low float64
Close float64
Qty float64
Vol float64
Vwap float64
Ask float64
Bid float64
AskSize float64
BidSize float64
}
type Security struct {
Id int64
Symbol st... |
func ParseBod(msg []interface{}) {
acc := int(msg[1].(float64))
securityId := int64(msg[2].(float64))
qty := msg[3].(float64)
avgPx := msg[4].(float64)
commission := msg[5].(float64)
realizedPnl := msg[6].(float64)
// brokerAcc := int(msg[7])
// tm := int64(msg[8].(float64))
p := getPos(acc, securityId)
p.Q... | {
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 | package main
import (
"log"
"math"
"strings"
)
type MD struct {
Open float64
High float64
Low float64
Close float64
Qty float64
Vol float64
Vwap float64
Ask float64
Bid float64
AskSize float64
BidSize float64
}
type Security struct {
Id int64
Symbol st... |
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 | package main
import (
"log"
"math"
"strings"
)
type MD struct {
Open float64
High float64
Low float64
Close float64
Qty float64
Vol float64
Vwap float64
Ask float64
Bid float64
AskSize float64
BidSize float64
}
type Security struct {
Id int64
Symbol st... | case "new_rejected", "replace_rejected":
ord := orders[clOrdId]
if ord != nil {
st0 := ord.St
ord.St = st
if isLive(st0) {
updatePos(ord)
}
} else {
log.Println("can not find order for", clOrdId)
}
case "risk_rejected":
ord := orders[clOrdId]
if ord != nil {
ord.St = st
updatePos(... | random_line_split | |
main.rs | #[macro_use]
extern crate clap;
extern crate irb;
extern crate las;
extern crate palette;
extern crate riscan_pro;
extern crate scanifc;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate text_io;
extern crate toml;
use clap::{App, ArgMatches};
use irb::Irb;
use las::Color;
use las::point::Format;
use p... | match err.kind() {
ErrorKind::NotFound => Vec::new(),
_ => panic!("io error: {}", err),
}
}
}
}
fn outfile<P: AsRef<Path>>(&self, scan_position: &ScanPosition, infile: P) -> PathBuf {
let mut outfile = self.las_... | }
Err(err) => {
use std::io::ErrorKind; | random_line_split |
main.rs | #[macro_use]
extern crate clap;
extern crate irb;
extern crate las;
extern crate palette;
extern crate riscan_pro;
extern crate scanifc;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate text_io;
extern crate toml;
use clap::{App, ArgMatches};
use irb::Irb;
use las::Color;
use las::point::Format;
use p... | (&self, socs: &Point<Socs>) -> Option<f64> {
let cmcs = socs.to_cmcs(self.image.cop, self.mount_calibration);
self.camera_calibration.cmcs_to_ics(&cmcs).map(|(mut u,
mut v)| {
if self.rotate {
let new_u = self.camera_calibration.height as f64 - v;
v ... | temperature | identifier_name |
main.rs | #[macro_use]
extern crate clap;
extern crate irb;
extern crate las;
extern crate palette;
extern crate riscan_pro;
extern crate scanifc;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate text_io;
extern crate toml;
use clap::{App, ArgMatches};
use irb::Irb;
use las::Color;
use las::point::Format;
use p... |
})
.collect()
}
Err(err) => {
use std::io::ErrorKind;
match err.kind() {
ErrorKind::NotFound => Vec::new(),
_ => panic!("io error: {}", err),
}
}
}... | {
None
} | conditional_block |
data_collection.py | import pygame
import random
import math
from password_types import PasswordTypes
from textbox import TextBox
from time import time, strftime, gmtime, sleep, mktime
import datetime
import uuid
import asyncio
import threading
import csv
import helpers
import os
from pylsl import StreamInfo, StreamOutlet, LostError
from e... |
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 | import pygame
import random
import math
from password_types import PasswordTypes
from textbox import TextBox
from time import time, strftime, gmtime, sleep, mktime
import datetime
import uuid
import asyncio
import threading
import csv
import helpers
import os
from pylsl import StreamInfo, StreamOutlet, LostError
from e... | 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 | import pygame
import random
import math
from password_types import PasswordTypes
from textbox import TextBox
from time import time, strftime, gmtime, sleep, mktime
import datetime
import uuid
import asyncio
import threading
import csv
import helpers
import os
from pylsl import StreamInfo, StreamOutlet, LostError
from e... | (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 == DataCollectionState.RUNNING:
... | process_logic | identifier_name |
data_collection.py | import pygame
import random
import math
from password_types import PasswordTypes
from textbox import TextBox
from time import time, strftime, gmtime, sleep, mktime
import datetime
import uuid
import asyncio
import threading
import csv
import helpers
import os
from pylsl import StreamInfo, StreamOutlet, LostError
from e... | 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 | import { concatArrayBuffers } from "../utils/download";
import { TagWriter } from "./tagWriter";
interface Atom {
length: number;
name?: string;
offset?: number;
children?: Atom[];
data?: ArrayBuffer;
}
interface AtomLevel {
parent: Atom;
offset: number;
childIndex: number;
}
// length(4) + name(4)
c... | (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 | import { concatArrayBuffers } from "../utils/download";
import { TagWriter } from "./tagWriter";
interface Atom {
length: number;
name?: string;
offset?: number;
children?: Atom[];
data?: ArrayBuffer;
}
interface AtomLevel {
parent: Atom;
offset: number;
childIndex: number;
}
// length(4) + name(4)
c... |
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 headerBufferView = new DataView(headerBuffer);
// length at... | {
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 | import { concatArrayBuffers } from "../utils/download";
import { TagWriter } from "./tagWriter";
interface Atom {
length: number;
name?: string;
offset?: number;
children?: Atom[];
data?: ArrayBuffer;
}
interface AtomLevel {
parent: Atom;
offset: number;
childIndex: number;
}
// length(4) + name(4)
c... |
this._mp4.addMetadataAtom("©ART", artists.join(", "));
}
setAlbum(album: string): void {
if (!album) throw new Error("Invalid value for album");
this._mp4.addMetadataAtom("©alb", album);
}
setComment(comment: string): void {
if (!comment) throw new Error("Invalid value for comment");
th... | 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 | import { concatArrayBuffers } from "../utils/download";
import { TagWriter } from "./tagWriter";
interface Atom {
length: number;
name?: string;
offset?: number;
children?: Atom[];
data?: ArrayBuffer;
}
interface AtomLevel {
parent: Atom;
offset: number;
childIndex: number;
}
// length(4) + name(4)
c... |
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 | /*-
* Copyright (c) 2018, 2023 Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* https://oss.oracle.com/licenses/upl/
*/
/**
* Defines types used for NoSQL driver configuration for Oracle Cloud
* Infrastructure Identity and Access Managem... | * <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 | package kvm
// Connect to the broker, subscribe, and write messages received to a file
import (
"encoding/json"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
//"github.com/didi/nightingale/src/modules/agent/config"
//"github.com/didi/nightingale/src/modules/agent/wol"
"github.com/pion/rtsp-be... | 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 | package kvm
// Connect to the broker, subscribe, and write messages received to a file
import (
"encoding/json"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
//"github.com/didi/nightingale/src/modules/agent/config"
//"github.com/didi/nightingale/src/modules/agent/wol"
"github.com/pion/rtsp-be... | 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 | package kvm
// Connect to the broker, subscribe, and write messages received to a file
import (
"encoding/json"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
//"github.com/didi/nightingale/src/modules/agent/config"
//"github.com/didi/nightingale/src/modules/agent/wol"
"github.com/pion/rtsp-be... | 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 | package kvm
// Connect to the broker, subscribe, and write messages received to a file
import (
"encoding/json"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
//"github.com/didi/nightingale/src/modules/agent/config"
//"github.com/didi/nightingale/src/modules/agent/wol"
"github.com/pion/rtsp-be... |
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 | 'use strict'
import { app, protocol, BrowserWindow, globalShortcut, nativeTheme, ipcMain, dialog, Notification, shell, powerMonitor, session } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
import {
E... | 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 | 'use strict'
import { app, protocol, BrowserWindow, globalShortcut, nativeTheme, ipcMain, dialog, Notification, shell, powerMonitor, session } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
import {
E... |
function signInInoreader () {
shell.openExternal(`https://www.inoreader.com/oauth2/auth?client_id=${process.env.VUE_APP_INOREADER_CLIENT_ID}&redirect_uri=ravenreader://inoreader/auth&response_type=code&scope=read%20write&state=ravenreader`)
}
function signInPocketWithPopUp () {
if (os.platform() === 'darwin') {
... | {
// 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 | 'use strict'
import { app, protocol, BrowserWindow, globalShortcut, nativeTheme, ipcMain, dialog, Notification, shell, powerMonitor, session } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
import {
E... |
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 | 'use strict'
import { app, protocol, BrowserWindow, globalShortcut, nativeTheme, ipcMain, dialog, Notification, shell, powerMonitor, session } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
import {
E... | () {
// 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 | import { Component, OnInit, OnDestroy, Input, ViewChild, ViewEncapsulation,ViewContainerRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { DatatableComponent } from '@swimlane/ngx-datatable';
import { NgbModal, ModalDismissReasons, NgbTabChangeEvent,Ng... |
}
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 | import { Component, OnInit, OnDestroy, Input, ViewChild, ViewEncapsulation,ViewContainerRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { DatatableComponent } from '@swimlane/ngx-datatable';
import { NgbModal, ModalDismissReasons, NgbTabChangeEvent,Ng... | 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 | import { Component, OnInit, OnDestroy, Input, ViewChild, ViewEncapsulation,ViewContainerRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { DatatableComponent } from '@swimlane/ngx-datatable';
import { NgbModal, ModalDismissReasons, NgbTabChangeEvent,Ng... | (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 | import { Component, OnInit, OnDestroy, Input, ViewChild, ViewEncapsulation,ViewContainerRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { DatatableComponent } from '@swimlane/ngx-datatable';
import { NgbModal, ModalDismissReasons, NgbTabChangeEvent,Ng... |
onsubmit(form: NgForm){
if(this.paring.length > 0){
if(this.img_selected == false){
this.toastr.error('Please select image to continue','Error')
}
else{
const formData: any = new FormData();
const files: Array<File> = this.filesToUploads;
for(let i =0; i < files... | {
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 | package main
import (
"bufio"
"encoding/base64"
"encoding/json"
"encoding/xml"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"license/public"
)
const (
OneYearSeconds = 31536000
OneDaySeconds = 86400
OneMinuteSeconds = 60
DataDir = "data"
)
var (
LicenseID ... | }
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 | package main
import (
"bufio"
"encoding/base64"
"encoding/json"
"encoding/xml"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"license/public"
)
const (
OneYearSeconds = 31536000
OneDaySeconds = 86400
OneMinuteSeconds = 60
DataDir = "data"
)
var (
LicenseID ... | 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"`
}
type XMLProduct struct {
XMLName xml.... |
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 | package main
import (
"bufio"
"encoding/base64"
"encoding/json"
"encoding/xml"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"license/public"
)
const (
OneYearSeconds = 31536000
OneDaySeconds = 86400
OneMinuteSeconds = 60
DataDir = "data"
)
var (
LicenseID ... | 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 | package main
import (
"bufio"
"encoding/base64"
"encoding/json"
"encoding/xml"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"license/public"
)
const (
OneYearSeconds = 31536000
OneDaySeconds = 86400
OneMinuteSeconds = 60
DataDir = "data"
)
var (
LicenseID ... | {
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 | package middleware
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/satori/go.uuid"
cobxtypes "github.com/jiarung/mochi/apps/exchange/cobx-types"
"github.com/jiarung/mochi/cache"
"github.com/jiarung/mochi/cache/helper"
"github.com/jiarung/mochi/cache/keys"
apicontext "gith... |
expireSec := int(oauth2Token.ExpireAt.Sub(time.Now()) / time.Second)
appCtx.Cache.Set(oauth2TokenKey, 1, expireSec)
}
userScopes := make([]types.Scope, 0)
for _, scope := range scopes {
scopeStr, ok := scope.(string)
if ok {
userScopes = append(userScopes, types.Scope(scopeStr))
}
}
appCtx.UserAut... | {
return result.Error
} | conditional_block |
scope-auth.go | package middleware
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/satori/go.uuid"
cobxtypes "github.com/jiarung/mochi/apps/exchange/cobx-types"
"github.com/jiarung/mochi/cache"
"github.com/jiarung/mochi/cache/helper"
"github.com/jiarung/mochi/cache/keys"
apicontext "gith... | (ctx *gin.Context, logger logging.Logger) (jwtString string, exists bool) {
var jwtStr string
jwtStr = ctx.GetHeader("Authorization")
if len(jwtStr) != 0 {
jwtString = jwtStr
exists = true
return
}
var err error
jwtStr, err = ctx.Cookie("Authorization")
if err == nil && len(jwtStr) != 0 {
jwtString = jw... | extractJWT | identifier_name |
scope-auth.go | package middleware
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/satori/go.uuid"
cobxtypes "github.com/jiarung/mochi/apps/exchange/cobx-types"
"github.com/jiarung/mochi/cache"
"github.com/jiarung/mochi/cache/helper"
"github.com/jiarung/mochi/cache/keys"
apicontext "gith... | 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 | package middleware
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/satori/go.uuid"
cobxtypes "github.com/jiarung/mochi/apps/exchange/cobx-types"
"github.com/jiarung/mochi/cache"
"github.com/jiarung/mochi/cache/helper"
"github.com/jiarung/mochi/cache/keys"
apicontext "gith... | {
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 | #!/usr/bin/env python
from __future__ import print_function
from colorprint import *
#import tornado_pyuv
#tornado_pyuv.install()
from tornado.ioloop import IOLoop
from tornado_pyuv import UVLoop
IOLoop.configure(UVLoop)
import signal
import tornado.ioloop
import tornado.web
import os
import sys
import pyuv
impor... |
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 | #!/usr/bin/env python
from __future__ import print_function
from colorprint import *
#import tornado_pyuv
#tornado_pyuv.install()
from tornado.ioloop import IOLoop
from tornado_pyuv import UVLoop
IOLoop.configure(UVLoop)
import signal
import tornado.ioloop
import tornado.web
import os
import sys
import pyuv
impor... |
class LogsHandler(tornado.web.RequestHandler):
def get(self):
from platform import uname
hostname = uname()[1]
self.render('logs.html',buf=buf, peers=peers, hostname=hostname )
class ChannelHandler(tornado.web.RequestHandler):
def get(self):
pids_new=pids.copy()
for ke... | from platform import uname
hostname = uname()[1]
self.render('self_log.html',buf=buf, hostname=hostname) | identifier_body |
ts_analyzer.py | #!/usr/bin/env python
from __future__ import print_function
from colorprint import *
#import tornado_pyuv
#tornado_pyuv.install()
from tornado.ioloop import IOLoop
from tornado_pyuv import UVLoop
IOLoop.configure(UVLoop)
import signal
import tornado.ioloop
import tornado.web
import os
import sys
import pyuv
impor... | servers={}
for key in addresses:
print ('%s corresponds to' % key[0])
servers[counter] = pyuv.UDP(loop._loop)
servers[counter].bind(key)
servers[counter].set_membership(key[0], pyuv.UV_JOIN_GROUP)
servers[counter].start_recv(on_read)
counter = counter + 1
# se... | random_line_split | |
ts_analyzer.py | #!/usr/bin/env python
from __future__ import print_function
from colorprint import *
#import tornado_pyuv
#tornado_pyuv.install()
from tornado.ioloop import IOLoop
from tornado_pyuv import UVLoop
IOLoop.configure(UVLoop)
import signal
import tornado.ioloop
import tornado.web
import os
import sys
import pyuv
impor... | (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 | use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;
use crate::serialized_data_capnp::serialized_data;
use crate::{Error, NetworkError, Result};
use capnp::message::{Builder as MsgBuilder, ReaderOptions};
use capnp_futures::serialize as capnp_serialize;
use dashmap::{DashMap, Das... | pub fn update_generation(&mut self, new_gen: i64) {
if new_gen > *self.generation.lock() {
self.server_uris = Arc::new(DashMap::new());
*self.generation.lock() = new_gen;
}
}
}
#[derive(Debug, Error)]
pub enum MapOutputError {
#[error("Shuffle id output #{0} not foun... | random_line_split | |
map_output_tracker.rs | use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;
use crate::serialized_data_capnp::serialized_data;
use crate::{Error, NetworkError, Result};
use capnp::message::{Builder as MsgBuilder, ReaderOptions};
use capnp_futures::serialize as capnp_serialize;
use dashmap::{DashMap, Das... | (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 std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;
use crate::serialized_data_capnp::serialized_data;
use crate::{Error, NetworkError, Result};
use capnp::message::{Builder as MsgBuilder, ReaderOptions};
use capnp_futures::serialize as capnp_serialize;
use dashmap::{DashMap, Das... | 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 | import wx
import sys
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
from player import ViewPlayer
OK = wx.OK | wx.ICON_EXCLAMATION
ACV = wx.ALIGN_CENTER_VERTICAL
YN = wx.YES_NO | wx.ICON_WARNING
class AutoWidthListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
def __init__(self, parent):
wx.ListC... |
# 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 | import wx
import sys
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
from player import ViewPlayer
OK = wx.OK | wx.ICON_EXCLAMATION
ACV = wx.ALIGN_CENTER_VERTICAL
YN = wx.YES_NO | wx.ICON_WARNING
class AutoWidthListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
def __init__(self, parent):
wx.ListC... | 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 | import wx
import sys
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
from player import ViewPlayer
OK = wx.OK | wx.ICON_EXCLAMATION
ACV = wx.ALIGN_CENTER_VERTICAL
YN = wx.YES_NO | wx.ICON_WARNING
class AutoWidthListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
def __init__(self, parent):
wx.ListC... |
# 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 | import wx
import sys
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
from player import ViewPlayer
OK = wx.OK | wx.ICON_EXCLAMATION
ACV = wx.ALIGN_CENTER_VERTICAL
YN = wx.YES_NO | wx.ICON_WARNING
class AutoWidthListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
def __init__(self, parent):
wx.ListC... | (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=5)
text_sizer.Add(wx.StaticText(self, label="Day:"), 0, ACV)
text_sizer.Add(self.day, 0, ACV)
... | __init__ | identifier_name |
index.js | const _Page = require("/__antmove/component/componentClass.js")("Page");
const _my = require("/__antmove/api/index.js")(my);
const app = app || getApp();
const zutils = require("../../utils/zutils.js");
_Page({
data: {
hideCoupon: true,
hideBanners: false,
banners: [
[
... | _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 | const _Page = require("/__antmove/component/componentClass.js")("Page");
const _my = require("/__antmove/api/index.js")(my);
const app = app || getApp();
const zutils = require("../../utils/zutils.js");
_Page({
data: {
hideCoupon: true,
hideBanners: false,
banners: [
[
... | 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 | from sklearn import tree
from sklearn.feature_extraction.text import CountVectorizer
import http.client
import json
import requests
print("This program takes the movies you like, the ones you don't, and the ones you are curious about if you will like or not. It uses Machine Learning with the data obtained from The Movi... | classifier,
out_file='tree.dot',
feature_names=vectorizer.get_feature_names(),
class_names=["bad","good"]
) |
#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 |
from sklearn import tree
from sklearn.feature_extraction.text import CountVectorizer
import http.client
import json
import requests
print("This program takes the movies you like, the ones you don't, and the ones you are curious about if you will like or not. It uses Machine Learning with the data obtained from The Mov... |
for x in likeDict:
if likeDict[x] != "":
print("You", x, likeDict[x][0:-2])
print()
#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... | likeDict['will probably not like'] += (movie + ", ") | conditional_block |
data.py | from ..core.helpers import itemize
from ..core.files import backendRep, expandDir, prefixSlash, normpath
from .helpers import splitModRef
from .repo import checkoutRepo
from .links import provenanceLink
# GET DATA FOR MAIN SOURCE AND ALL MODULES
class AppData:
def __init__(
self, app, backend, moduleRef... | 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 | from ..core.helpers import itemize
from ..core.files import backendRep, expandDir, prefixSlash, normpath
from .helpers import splitModRef
from .repo import checkoutRepo
from .links import provenanceLink
# GET DATA FOR MAIN SOURCE AND ALL MODULES
class AppData:
def __init__(
self, app, backend, moduleRef... |
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 | from ..core.helpers import itemize
from ..core.files import backendRep, expandDir, prefixSlash, normpath
from .helpers import splitModRef
from .repo import checkoutRepo
from .links import provenanceLink
# GET DATA FOR MAIN SOURCE AND ALL MODULES
class | :
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 | from ..core.helpers import itemize
from ..core.files import backendRep, expandDir, prefixSlash, normpath
from .helpers import splitModRef
from .repo import checkoutRepo
from .links import provenanceLink
# GET DATA FOR MAIN SOURCE AND ALL MODULES
class AppData:
|
def getModulesData(*args):
"""Retrieve all data for a corpus.
Parameters
----------
args: list
All parameters needed to retrieve all associated data.
They are the same as are needed to construct an `AppData` object.
"""
mData = AppData(*args)
mData.getModules()
if n... | 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 | """
DESCRIPTION
Preprocesses audio data before sending to Neural Network
See demo in in main()
MIT License
Copyright (c) 2018 The-Instrumental-Specialists
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the So... |
def main():
# Note: Preprocessed data should be in folder preprocessed
v = processMPCC('instruments_07/banjo/banjo_A3_very-long_forte_normal.wav')
print('len(input layer) = ' + str(len(v)))
#raise Exception
P = Preprocess()
#P.processData('preprocessed/proce... | 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 | """
DESCRIPTION
Preprocesses audio data before sending to Neural Network
See demo in in main()
MIT License
Copyright (c) 2018 The-Instrumental-Specialists
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the So... |
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 | """
DESCRIPTION
Preprocesses audio data before sending to Neural Network
See demo in in main()
MIT License
Copyright (c) 2018 The-Instrumental-Specialists
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the So... | (self):
"""Returns a list of the names of the output vectors
ex) ['cel', 'cla', 'flu', 'gac', 'gel', 'org', 'pia', 'sax', 'tru', 'vio', 'voi']
"""
return self.dirs
def loadData(self,data_file):
"""Loads the data in data_file into Trainer"""
#Load the data from the js... | getOutputNames | identifier_name |
preprocess_03.py | """
DESCRIPTION
Preprocesses audio data before sending to Neural Network
See demo in in main()
MIT License
Copyright (c) 2018 The-Instrumental-Specialists
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the So... |
store = {}
store['dirs'] = self.dirs # good
store['output'] = output # good
store['files'] = self.files # good
store['X'] = X # good
store['Y'] = Y # good
store['comment'] = comment
with open(data_file, 'w') as outfile:
json.dump(... | y = []
for ele in self.Y[i]:
y.append(float(ele))
Y.append(y) # -> fine | conditional_block |
lib.rs | //! Everything related to meshes.
//!
//! **TODO**: Everything.
#![feature(trivial_bounds)]
#![feature(never_type)]
#![feature(doc_cfg)]
#![feature(proc_macro_hygiene)]
#![feature(try_blocks)]
#![feature(specialization)]
#![feature(associated_type_defaults)]
#![feature(associated_type_bounds)]
#![feature(array_value_i... | {
Edge,
Face,
Vertex,
}
// ===========================================================================
// ===== `Sealed` trait
// ===========================================================================
pub(crate) mod sealed {
/// A trait that cannot be implemented outside of this crate.
///
... | MeshElement | identifier_name |
lib.rs | //! Everything related to meshes.
//!
//! **TODO**: Everything.
#![feature(trivial_bounds)]
#![feature(never_type)]
#![feature(doc_cfg)]
#![feature(proc_macro_hygiene)]
#![feature(try_blocks)]
#![feature(specialization)]
#![feature(associated_type_defaults)]
#![feature(associated_type_bounds)]
#![feature(array_value_i... | /// };
///
///
/// #[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 | #[macro_use]
extern crate log;
extern crate simplelog;
use futures::future;
use futures::future::{BoxFuture, FutureExt};
use reqwest as request;
use base64::encode;
use dirs::home_dir;
use futures::io::SeekFrom;
use regex::Regex;
use request::header::{HeaderMap, AUTHORIZATION, CONTENT_TYPE, USER_AGENT};
use scraper::... | > String {
let mut home_path = home_dir().unwrap();
home_path.push(".sure");
home_path.push(filename);
String::from(home_path.to_str().unwrap())
}
///
///
/// Definitions and Implementations
///
///
///
/// DesiredListing
///
#[derive(Debug)]
struct DesiredListing {
active: bool,
interested: bool,
mls: String,... | filename: &str) - | identifier_name |
main.rs | #[macro_use]
extern crate log;
extern crate simplelog;
use futures::future;
use futures::future::{BoxFuture, FutureExt};
use reqwest as request;
use base64::encode;
use dirs::home_dir;
use futures::io::SeekFrom;
use regex::Regex;
use request::header::{HeaderMap, AUTHORIZATION, CONTENT_TYPE, USER_AGENT};
use scraper::... | 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 | #[macro_use]
extern crate log;
extern crate simplelog;
use futures::future;
use futures::future::{BoxFuture, FutureExt};
use reqwest as request;
use base64::encode;
use dirs::home_dir;
use futures::io::SeekFrom;
use regex::Regex;
use request::header::{HeaderMap, AUTHORIZATION, CONTENT_TYPE, USER_AGENT};
use scraper::... | // 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()))
}
}
}
checked_mls
}
fn write_checked_... | ror!(
"error sending message: {:?}\n\t└──{}\n\t└──{:?}",
res.status(),
res.text().await?,
params
)
}
Ok(())
}
///
/ | conditional_block |
main.rs | // Copyright 2020 Xavier Gillard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, di... |
}
/// 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 | // Copyright 2020 Xavier Gillard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, di... |
if comment.is_match(line) {
continue;
}
if let Some(caps) = pb_decl.captures(line) {
let n = caps["vars"].to_string().parse::<usize>()?;
let full = (0..n).collect();
g.nb_vars = n;
g.neighbors = vec![full; n];
g.wei... | {
continue;
} | conditional_block |
main.rs | // Copyright 2020 Xavier Gillard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, di... |
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.