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 |
|---|---|---|---|---|
train_nn.py | (object):
def __init__(self, data_dir, model_dir, task_id, isInteractive=True, OOV=False,
memory_size=50, random_state=None, batch_size=32, learning_rate=0.001, epsilon=1e-8,
max_grad_norm=40.0, evaluation_interval=10, hops=3, epochs=200, embedding_size=20, save_model=10,
... | chatBot | identifier_name | |
train_nn.py | , data_dir, model_dir, task_id, isInteractive=True, OOV=False,
memory_size=50, random_state=None, batch_size=32, learning_rate=0.001, epsilon=1e-8,
max_grad_norm=40.0, evaluation_interval=10, hops=3, epochs=200, embedding_size=20, save_model=10,
checkpoint_path='./mode... | parser.add_argument('--epochs', default=200, type=int, help='Number of epochs to train for')
parser.add_argument('--embedding_size', default=20, type=int,
help='Embedding size for embedding matrices')
parser.add_argument('--memory_size', default=50, type=int, help='Maximum size of me... | help='Evaluate and print results every x epochs')
parser.add_argument('--batch_size', default=32, type=int, help='Batch size for training')
parser.add_argument('--hops', default=3, type=int, help='Number of hops in the Memory Network') | random_line_split |
train_nn.py | , data_dir, model_dir, task_id, isInteractive=True, OOV=False,
memory_size=50, random_state=None, batch_size=32, learning_rate=0.001, epsilon=1e-8,
max_grad_norm=40.0, evaluation_interval=10, hops=3, epochs=200, embedding_size=20, save_model=10,
checkpoint_path='./mode... |
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--learning_rate', default=0.001, type=float,
help='Learning rate for Optimizer')
parser.add_argument('--epsilon', default=1e-8, type=float,
help='Epsilon value for Adam Optim... | model_dir = "task" + str(params['task_id']) + "_" + params['model_dir']
if not os.path.exists(model_dir):
os.makedirs(model_dir)
chatbot = chatBot(data_dir=params['data_dir'], model_dir=model_dir, task_id=params['task_id'], isInteractive=params['interactive'], OOV=params['OOV'], memory_size=params['memo... | identifier_body |
01_calculate_MMR_from_draws.py | cause
dalynator_dir = '/ihme/centralcomp/dalynator/%s/draws/hdfs/' % model_vers
files = []
for root, dirnames, filenames in os.walk('%s' % dalynator_dir):
for filename in fnmatch.filter(filenames, '*%s.h5' % year_id):
files.append(os.path.join(root, filename))
def read_file(f):
return pd.read_hdf(f, ... |
draws = pd.concat(draw_list)
draws.reset_index(inplace=True)
draws = draws[draws.age_group_id.isin(ages)]
draws['location_id'] = draws['location_id'].astype('int')
draws['age_group_id'] = draws['age_group_id'].astype('int')
draws['sex_id'] = draws['sex_id'].astype('int')
draws['year_id'] = draws['year_id'].astype('in... | draw_list.append(df) | conditional_block |
01_calculate_MMR_from_draws.py | cause
dalynator_dir = '/ihme/centralcomp/dalynator/%s/draws/hdfs/' % model_vers
files = []
for root, dirnames, filenames in os.walk('%s' % dalynator_dir):
for filename in fnmatch.filter(filenames, '*%s.h5' % year_id):
files.append(os.path.join(root, filename))
def read_file(f):
|
draw_list = []
with cf.ProcessPoolExecutor(max_workers=14) as e:
for df in e.map(read_file, files):
draw_list.append(df)
draws = pd.concat(draw_list)
draws.reset_index(inplace=True)
draws = draws[draws.age_group_id.isin(ages)]
draws['location_id'] = draws['location_id'].astype('int')
draws['age_group_id'... | return pd.read_hdf(f, 'data', where=[("'cause_id'==%d & 'measure_id'==1"
"& 'metric_id'==1 & 'sex_id'==2"
"& 'rei_id'==0") % cause_id]) | identifier_body |
01_calculate_MMR_from_draws.py | (df):
df['measure_id'] = 25
df['metric_id'] = 3
df['cause_id'] = cause_id
return df
# get best dalynator version
query = ('SELECT '
'distinct(val) AS daly_id '
'FROM '
'gbd.gbd_process_version_metadata gpvm '
'JOIN '
'gbd.gbd_process_version USING (gbd_proc... | add_cols | identifier_name | |
01_calculate_MMR_from_draws.py | query_tools.query_2_df(query, engine=enginer.engines["cod_prod"])
# load regional scalars for cod and outputs location aggregation
print "loading and reshaping regional scalars"
region_locs = loc_df[loc_df["location_type_id"] == 6]['location_id'].tolist()
scalar_list = []
root_dir = '/home/j/WORK/10_gbd/01_dalynator/... | columns={'2.5%': 'lower', '97.5%': 'upper'}, inplace=True) | random_line_split | |
prime_field.rs | pub struct PrimeField<P: Parameters> {
// TODO: un-pub. They are pub so FieldElement can have const-fn constructors.
pub uint: P::UInt,
pub _parameters: PhantomData<P>,
}
/// Required constant parameters for the prime field
// TODO: Fix naming
#[allow(clippy::module_name_repetitions)]
// UInt can no... | // Derive fails for Clone, PartialEq, Eq, Hash | random_line_split | |
prime_field.rs | }
/// Convert to `UInt`.
#[inline(always)] // Simple wrapper for `from_montgomery`
pub fn to_uint(&self) -> P::UInt {
debug_assert!(self.uint < Self::modulus());
P::UInt::from_montgomery::<Montgomery<P>>(self.as_montgomery())
}
/// Construct from `UInt`
///
/// It does the... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "field_element!(\"{:?}\")", self.to_uint())
}
}
impl<P: Parameters> Zero for PrimeField<P> {
#[inline(always)]
fn zero() -> Self {
Self::from_montgomery(P::UInt::zero())
}
#[inline(always)]
fn is_zero(&self) -> bool... | fmt | identifier_name |
prime_field.rs | }
/// Convert to `UInt`.
#[inline(always)] // Simple wrapper for `from_montgomery`
pub fn to_uint(&self) -> P::UInt {
debug_assert!(self.uint < Self::modulus());
P::UInt::from_montgomery::<Montgomery<P>>(self.as_montgomery())
}
/// Construct from `UInt`
///
/// It does the... | else {
None
}
} else {
Some(Self::one())
}
}
}
// TODO: Generalize over order type
// Lint has a false positive here
#[allow(single_use_lifetimes)]
impl<U, P> Root<&U> for PrimeField<P>
where
U: FieldUInt + Binary + for<'a> DivRem<&'a U, Quotient = U, Re... | {
Some(Self::generator().pow(&q))
} | conditional_block |
prime_field.rs | : FieldElement =
field_element!("0548c135e26faa9c977fb2eda057b54b2e0baa9a77a0be7c80278f4f03462d4c");
assert_eq!(SMALL, FieldElement::from(15));
assert_eq!(
NUM,
u256h!("0548c135e26faa9c977fb2eda057b54b2e0baa9a77a0be7c80278f4f03462d4c").into()
);
}
#[t... | {
let powers_of_two = (0..193).map(|n| U256::ONE << n);
let roots_of_unity: Vec<_> = powers_of_two
.map(|n| FieldElement::root(&n).unwrap())
.collect();
for (smaller_root, larger_root) in roots_of_unity[1..].iter().zip(roots_of_unity.as_slice())
{
ass... | identifier_body | |
mod.rs | 34, 171, 176, 198, 42, 235, 172, 180, 214,
106, 235, 173, 184, 230, 170, 235, 174, 188, 246, 234, 235, 175, 192, 6, 43, 236, 176,
196, 22, 107, 236, 177, 200, 38, 171, 236, 178, 204, 54, 235, 236, 179, 208, 70, 43,
237, 180, 212, 86, 107, 237, 181, 216, 102, 171, 237, 182, 220, 118, ... | zero_bit_width | identifier_name | |
mod.rs | }
enum State<'a> {
None,
Bitpacked(bitpacking::Decoder<'a>),
Rle(std::iter::Take<std::iter::Repeat<u32>>),
}
// Decoder of Hybrid-RLE encoded values.
pub struct HybridRleDecoder<'a> {
decoder: Decoder<'a>,
state: State<'a>,
remaining: usize,
}
#[inline]
fn read_next<'a, 'b>(decoder: &'b mut D... | Bitpacked(&'a [u8]),
/// A RLE-encoded slice. The first attribute corresponds to the slice (that can be interpreted)
/// the second attribute corresponds to the number of repetitions.
Rle(&'a [u8], usize), | random_line_split | |
mod.rs | 208, 64, 4, 21, 100, 208, 65, 8, 37, 164, 208, 66, 12, 53, 228, 208, 67, 16, 69, 36,
209, 68, 20, 85, 100, 209, 69, 24, 101, 164, 209, 70, 28, 117, 228, 209, 71, 32, 133,
36, 210, 72, 36, 149, 100, 210, 73, 40, 165, 164, 210, 74, 44, 181, 228, 210, 75, 48,
197, 36, 211, 7... | {
// data encoded from pyarrow representing (0..1000)
let data = vec![
127, 0, 4, 32, 192, 0, 4, 20, 96, 192, 1, 8, 36, 160, 192, 2, 12, 52, 224, 192, 3, 16,
68, 32, 193, 4, 20, 84, 96, 193, 5, 24, 100, 160, 193, 6, 28, 116, 224, 193, 7, 32,
132, 32, 194, 8, 36, 148, ... | identifier_body | |
mod.rs | else {
self.state = read_next(&mut self.decoder, self.remaining);
self.next()
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining, Some(self.remaining))
}
}
impl<'a> ExactSizeIterator for HybridRleDecoder<'a> {}
#[cfg(test)]
mod tests {
use sup... | {
self.remaining -= 1;
Some(result)
} | conditional_block | |
framebuffer_server.rs | ;
use fuchsia_component::{client::connect_channel_to_protocol, server::ServiceFs};
use fuchsia_framebuffer::{sysmem::BufferCollectionAllocator, FrameUsage};
use fuchsia_scenic::{BufferCollectionTokenPair, ViewRefPair};
use fuchsia_zircon as zx;
use futures::{StreamExt, TryStreamExt};
use std::sync::{mpsc::channel, Arc}... |
let sysmem_buffer_collection_token =
executor.run_singlethreaded(buffer_allocator.duplicate_token())?;
// Notify the async code that the sysmem buffer collection token is available.
collection_sender.send(sysmem_buffer_collection_token).expect("Failed to send collection");
... | {
let (collection_sender, collection_receiver) = channel();
let (allocation_sender, allocation_receiver) = channel();
// This thread is spawned to deal with the mix of asynchronous and synchronous proxies.
// In particular, we want to keep Framebuffer creation synchronous, while still making use of
... | identifier_body |
framebuffer_server.rs | async;
use fuchsia_component::{client::connect_channel_to_protocol, server::ServiceFs};
use fuchsia_framebuffer::{sysmem::BufferCollectionAllocator, FrameUsage};
use fuchsia_scenic::{BufferCollectionTokenPair, ViewRefPair};
use fuchsia_zircon as zx;
use futures::{StreamExt, TryStreamExt};
use std::sync::{mpsc::channel,... | {
/// The Flatland proxy associated with this server.
flatland: fuicomposition::FlatlandSynchronousProxy,
/// The buffer collection that is registered with Flatland.
collection: fsysmem::BufferCollectionInfo2,
}
impl FramebufferServer {
/// Returns a `FramebufferServer` that has created a scene a... | FramebufferServer | identifier_name |
framebuffer_server.rs | _WIDTH: u32 = 720;
/// The height of the framebuffer image.
pub const IMAGE_HEIGHT: u32 = 1200;
/// The offset at which the framebuffer will be placed. Assume a display width of 1920.
pub const TRANSLATION_X: i32 = 1920 / 2 - IMAGE_WIDTH as i32 / 2;
/// The Flatland identifier for the framebuffer image.
const IMAGE_... | random_line_split | ||
base.py | Sequence(sequence)
def lineReceived(self, line):
if not self.chanRequest:
# server sending random unrequested data.
self.transport.loseConnection()
return
self.setTimeout(None)
try:
self.chanRequest.lineReceived(line)
self.setTimeout(self.timeOut)
except Exception, err:
self.chanRequest.a... | size = len(self.hostsPool)
if size == 0:
return None
if size > 15:
tries = 15
else:
tries = size
pools = self.hostsPool.values()
idx = random.randint(1, size)
for t in xrange(tries):
pool = pools[idx % size]
idx += 1
p = pool.get(wait)
if p is not None: | identifier_body | |
base.py | finished writing data."""
self.finishedWriting = True
def abortWithError(self, err):
if self.stream is not None:
self.stream.finish(err)
if self.responseDefer:
d = self.responseDefer
del self.responseDefer
d.errback(err)
self.finishRequest()
def connectionLost(self, reason):
if not self.finis... | self.hostsDead.remove(addr) | conditional_block | |
base.py | Request(self):
self.finished = True
self.channel.requestFinished(self)
def submit(self):
self.submitHeaders()
if self.request.stream:
d = stream_mod.StreamProducer(self.request.stream).beginProducing(self)
d.addCallback(self.finishWriting).addErrback(self.abortWithError)
else:
self.finishWriti... | def lineReceived(self, line):
if not self.chanRequest:
# server sending random unrequested data.
self.transport.loseConnection()
return
self.setTimeout(None)
try:
self.chanRequest.lineReceived(line)
self.setTimeout(self.timeOut)
except Exception, err:
self.chanRequest.abortWithError(failur... | self.setTimeout(self.timeOut)
self.transport.writeSequence(sequence)
| random_line_split |
base.py | Request(self):
self.finished = True
self.channel.requestFinished(self)
def submit(self):
self.submitHeaders()
if self.request.stream:
d = stream_mod.StreamProducer(self.request.stream).beginProducing(self)
d.addCallback(self.finishWriting).addErrback(self.abortWithError)
else:
self.finishWriti... | (self, line):
if not self.chanRequest:
# server sending random unrequested data.
self.transport.loseConnection()
return
self.setTimeout(None)
try:
self.chanRequest.lineReceived(line)
self.setTimeout(self.timeOut)
except Exception, err:
self.chanRequest.abortWithError(failure.Failure(err))
... | lineReceived | identifier_name |
temperature_driver.py | C ADDRESS/BITS/SETTINGS
# -----------------------------------------------------------------------
_BME280_ADDRESS = const(0x77)
_BME280_CHIPID = const(0x58)
_BME280_REGISTER_CHIPID = const(0xD0)
_BME280_REGISTER_DIG_T1 = const(0x88)
_BME280_REGISTER_DIG_H1 = const(0xA1)
_BME280_REGISTER_DIG_H2 = const(0xE1)... |
if var1:
pressure = 1048576.0 - adc
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
var1 = self._pressure_calib[8] * pressure * pressure / 2147483648.0
var2 = pressure * self._pressure_calib[7] / 32768.0
pressure = pressure + (var1 + var... | return 0 | conditional_block |
temperature_driver.py | 80_REGISTER_CTRL_MEAS, 0xFE) # high res, forced mode
# Wait for conversion to complete
while self._read_byte(_BME280_REGISTER_STATUS) & 0x08:
time.sleep(0.002)
raw_temperature = self._read24(_BME280_REGISTER_TEMPDATA) / 16 # lowest 4 bits get dropped
#print("raw temp:... | """Driver for BME280 connected over I2C"""
def __init__(self, i2c, address=_BME280_ADDRESS):
import adafruit_bus_device.i2c_device as i2c_device
self._i2c = i2c_device.I2CDevice(i2c, address)
super().__init__()
def _read_register(self, register, length):
with self._i2c as... | identifier_body | |
temperature_driver.py | 8192.0)) * self._temp_calib[2]
#print(var2)
self._t_fine = int(var1 + var2)
#print("t_fine: ", self.t_fine)
@property
def temperature(self):
"""The compensated temperature in degrees celsius."""
self._read_temperature()
return self._t_fine / 5120.0
... | _write_register_byte | identifier_name | |
temperature_driver.py | C ADDRESS/BITS/SETTINGS
# -----------------------------------------------------------------------
_BME280_ADDRESS = const(0x77)
_BME280_CHIPID = const(0x58)
_BME280_REGISTER_CHIPID = const(0xD0)
_BME280_REGISTER_DIG_T1 = const(0x88)
_BME280_REGISTER_DIG_H1 = const(0xA1)
_BME280_REGISTER_DIG_H2 = const(0xE1)... | def _read_coefficients(self):
"""Read & save the calibration coefficients"""
coeff = self._read_register(_BME280 | """The altitude based on current ``pressure`` versus the sea level pressure
(``sea_level_pressure``) - which you must enter ahead of time)"""
pressure = self.pressure # in Si units for hPascal
return 44330 * (1.0 - math.pow(pressure / self.sea_level_pressure, 0.1903))
| random_line_split |
main.go | .Manifest.Images {
imageMapping := ImageMapping{
ManifestName: manifestImage.FullName(),
}
imageMapping.Objects.Manifest = manifestImage
imageMapping.Objects.GitHubRepo = cache.GithubRepos[manifestImage.RepoPath()]
imageMapping.Objects.GitHubLastRef = cache.GithubLastRefs[manifestImage.RepoPath()]
manife... | name := strings.ToLower(inputName)
name = regexp.MustCompile(`[^a-z0-9-]`).ReplaceAllString(name, "-")
name = regexp.MustCompile(`--+`).ReplaceAllString(name, "-")
name = strings.Trim(name, "-")
return name
}
func main() {
router := gin.Default()
router.StaticFile("/", "./static/index.html")
router.Static("/s... | func ImageCodeName(inputName string) string { | random_line_split |
main.go | (#a)"><path fill="#555" d="M0 0h37v20H0z"/><path fill="#9f9f9f" d="M37 0h78v20H37z"/><path fill="url(#b)" d="M0 0h115v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"><text x="18.5" y="15" fill="#010101" fill-opacity=".3">build</text><text x="18.5" y="14... | {
logrus.Infof("Fetching manifest...")
manifest, err := scwManifest.GetManifest()
if err != nil {
logrus.Errorf("Cannot get manifest: %v", err)
} else {
cache.Manifest = manifest
logrus.Infof("Manifest fetched: %d images", len(manifest.Images))
cache.MapImages()
}
time.Sleep(5 * time.Minute)
} | conditional_block | |
main.go | .Images {
imageMapping := ImageMapping{
ManifestName: manifestImage.FullName(),
}
imageMapping.Objects.Manifest = manifestImage
imageMapping.Objects.GitHubRepo = cache.GithubRepos[manifestImage.RepoPath()]
imageMapping.Objects.GitHubLastRef = cache.GithubLastRefs[manifestImage.RepoPath()]
manifestImageNa... | (left string, err error) string {
logrus.Warnf("Failed to get badge: %v", err)
// FIXME: remove the switch and compute the left width automatically
switch left {
case "build":
return `<svg xmlns="http://www.w3.org/2000/svg" width="115" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-col... | errBadge | identifier_name |
main.go | ImageName := ImageCodeName(manifestImage.Name)
apiImages := c.Api.Images
for idx := range *apiImages {
apiImage := (*apiImages)[idx]
apiImageName := ImageCodeName(apiImage.Name)
if rankMatch := fuzzy.RankMatch(manifestImageName, apiImageName); rankMatch > -1 {
imageMapping.ApiUUID = apiImage.Identifier... | {
c.JSON(http.StatusOK, gin.H{
"cache": cache,
})
} | identifier_body | |
timeline-custom-shiny.js | stringToDate(item.startDate);
obj.content = html;
processedDatas.push(obj);
}
this.parsedData = processedDatas;
return this;
};
timeline.prototype.drawVisualization = function() { // Create and populate a data table.
options = {
'height': "200px",
'width': "100%",
'start': new Date(vi... | });
})(jQuery);
timeline.prototype.addSlider = function(){
var self = this;
this.drawSliderBackground();
$("#slider-range").dragslider({
range: true,
min: self.startDate,
max: self.endDate,
animate: true,
rangeDrag: true,
values: [self.visibleFirstDate, self.visibleLastDate],
sli... | this._rangeStart = newVal;
}
}
} | random_line_split |
timeline-custom-shiny.js |
obj.start = stringToDate(item.startDate);
obj.content = html;
processedDatas.push(obj);
}
this.parsedData = processedDatas;
return this;
};
timeline.prototype.drawVisualization = function() { // Create and populate a data table.
options = {
'height': "200px",
'width': "100%",
'st... | {
obj.end = stringToDate(item.endDate);
} | conditional_block | |
api_op_CreateGovCloudAccount.go | and support purposes.
// The account in the commercial Region is automatically a member of the
// organization whose credentials made the request. Both accounts are associated
// with the same email address. A role is created in the new account in the
// commercial Region that allows the management account in the orga... | dOperationCreateGovCloudAccountMiddlewares(s | identifier_name | |
api_op_CreateGovCloudAccount.go | string
// Specifies the email address of the owner to assign to the new member account in
// the commercial Region. This email address must not already be associated with
// another Amazon Web Services account. You must use a valid email address to
// complete account creation. The rules for a valid email address:... | resolvedEndpoint.Headers.Get(k),
)
}
| random_line_split | |
api_op_CreateGovCloudAccount.go | ://console.aws.amazon.com/support/home#/)
// .
// - Using CreateGovCloudAccount to create multiple temporary accounts isn't
// recommended. You can only close an account from the Amazon Web Services Billing
// and Cost Management console, and you must be signed in as the root user. For
// information ... | return err
}
| conditional_block | |
api_op_CreateGovCloudAccount.go | it, IAM users and roles that have appropriate
// permissions can view billing information for the account. If you disable it,
// only the account root user can access billing information. For information about
// how to disable this switch for an account, see Granting access to your billing
// information and tools (h... | return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "organizations",
OperationName: "CreateGovCloudAccount",
}
}
| identifier_body | |
lib.rs | [`str::to_lowercase`]: https://doc.rust-lang.org/std/primitive.str.html#method.to_lowercase
//! [`str::to_uppercase`]: https://doc.rust-lang.org/std/primitive.str.html#method.to_uppercase
//!
//! <br>
//!
//! # Pasting documentation strings
//!
//! Within the `paste!` macro, arguments to a #\[doc ...\] attribute are
/... | continue;
}
}
} | random_line_split | |
lib.rs | Tree};
use std::char;
use std::iter;
use std::panic;
#[proc_macro]
pub fn paste(input: TokenStream) -> TokenStream {
let mut contains_paste = false;
let flatten_single_interpolation = true;
match expand(
input.clone(),
&mut contains_paste,
flatten_single_interpolation,
) {
... | {
let mut tokens = TokenStream::new();
#[cfg(not(no_literal_fromstr))]
{
use proc_macro::{LexError, Literal};
use std::str::FromStr;
if pasted.starts_with(|ch: char| ch.is_ascii_digit()) {
let literal = match panic::catch_unwind(|| Literal::from_str(&pasted)) {
... | identifier_body | |
lib.rs | elaborate example
//!
//! The next example shows a macro that generates accessor methods for some
//! struct fields. It demonstrates how you might find it useful to bundle a
//! paste invocation inside of a macro\_rules macro.
//!
//! ```
//! use paste::paste;
//!
//! macro_rules! make_a_struct_and_getters {
//! (... | {
Init,
Ident,
Literal,
Apostrophe,
Lifetime,
Colon1,
Colon2,
}
let mut state = State::Init;
for tt in input.clone() {
state = match (state, &tt) {
(State::Init, TokenTree::Ident(_)) => State::Ident,
(State::Init, Toke... | State | identifier_name |
k_means_anchor_points.py | )
if avg_iou > best_avg_iou:
best_avg_iou = avg_iou
best_clusters = clusters
best_avg_iou_iteration = iter_count
print(f"\nIteration {iter_count}")
print(f"Average iou to closest centroid = {avg_iou}")
print(f"Sum of all distances (cost) = {np.sum(clu... | h = img['height']
for ann in anns:
b = ann['bbox']
bb = convert_coco_bbox((w, h), b)
data.append(bb[2:])
return np.array(data)
if __name__ == "__main__":
# examples
# k, pascal, coco
# 1, 0.30933335617, 0.252004954777
# 2, ... | name = 'coco'
data = []
for dataset in datasets:
annfile = f'{source_dir}/{name}/annotations/instances_{dataset}.json'
coco = COCO(annfile)
cats = coco.loadCats(coco.getCatIds())
base_classes = {cat['id']: cat['name'] for cat in cats}
img_id_set = set()
for cat_... | identifier_body |
k_means_anchor_points.py | if avg_iou > best_avg_iou:
best_avg_iou = avg_iou
best_clusters = clusters
best_avg_iou_iteration = iter_count
print(f"\nIteration {iter_count}")
print(f"Average iou to closest centroid = {avg_iou}")
print(f"Sum of all distances (cost) = {np.sum(clust... |
ifs_img_ids.close()
return np.array(data)
def load_coco_dataset():
name = 'coco'
data = []
for dataset in datasets:
annfile = f'{source_dir}/{name}/annotations/instances_{dataset}.json'
coco = COCO(annfile)
cats = coco.loadCats(coco.getCatIds())
base_classes ... | anno_filename = f'{source_dir}/{name}/VOCdevkit/VOC{year}/Annotations/{image_id}.xml'
ifs_anno = open(anno_filename)
tree = ET.parse(ifs_anno)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height... | conditional_block |
k_means_anchor_points.py | if avg_iou > best_avg_iou:
best_avg_iou = avg_iou
best_clusters = clusters
best_avg_iou_iteration = iter_count
print(f"\nIteration {iter_count}")
print(f"Average iou to closest centroid = {avg_iou}")
print(f"Sum of all distances (cost) = {np.sum(clust... | ():
name = 'pascal'
data = []
for year, image_set in datasets:
img_ids_filename = f'{source_dir}/{name}/VOCdevkit/VOC{year}/ImageSets/Main/{image_set}.txt'
ifs_img_ids = open(img_ids_filename)
img_ids = ifs_img_ids.read().strip().split()
for image_id in img_ids:
... | load_pascal_dataset | identifier_name |
k_means_anchor_points.py | import IO
# Original code @ferada http://codereview.stackexchange.com/questions/128315/k-means-clustering-algorithm-implementation
def area(x):
if len(x.shape) == 1:
return x[0] * x[1]
else:
return x[:, 0] * x[:, 1]
def kmeans_iou(k, centroids, points, iter_count=0, iteration_cutoff=25, fea... | import matplotlib.patches as patches
import xml.etree.ElementTree as ET
from pycocotools.coco import COCO
from utils import convert_bbox, convert_coco_bbox, BoundingBox | random_line_split | |
Titanic_RandomForest_0526.py | ['Age']<=40) & (train['Sex']=="male")
train['Young_f'] = (train['Age']>=18) & (train['Age']<=40) & (train['Sex']=="female")
train['Cabin_known'] = train['Cabin'].isnull() == False
train['Age_known'] = train['Age'].isnull() == False
train['Family'] = train['SibSp'] + train['Parch']
train['Alone'] = (train['SibSp'] + tr... | conditional_block | ||
Titanic_RandomForest_0526.py | [152])
# # 特征工程
# 生成新的特征列
# In[16]:
train = train_data
test = test_data
train['Child'] = train['Age']<=10
train['Young'] = (train['Age']>=18) & (train['Age']<=40)
train['Young_m'] = (train['Age']>=18) & (train['Age']<=40) & (train['Sex']=="male")
train['Young_f'] = (train['Age']>=18) & (train['Age']<=40) & (train[... | 有8个人实际幸存了但被预测为死亡,有22个 | identifier_name | |
Titanic_RandomForest_0526.py | )
plt.subplot(337)
sns.distplot(surv['Fare'].dropna().values,bins = range(0,513,1),kde=False, color='blue')
sns.distplot(nosurv['Fare'].dropna().values,bins = range(0,513,1),kde=False, color='red', axlabel='Fare')
plt.subplot(338)
sns.distplot(np.log10(surv['Fare'].dropna().values+1), kde=False, color='blue')
sns.distp... | # In[28]:
pd.Series(predict1).value_counts() | random_line_split | |
Titanic_RandomForest_0526.py | ['Age']<=40) & (train['Sex']=="male")
train['Young_f'] = (train['Age']>=18) & (train['Age']<=40) & (train['Sex']=="female")
train['Cabin_known'] = train['Cabin'].isnull() == False
train['Age_known'] = train['Age'].isnull() == False
train['Family'] = train['SibSp'] + train['Parch']
train['Alone'] = (train['SibSp'] + tr... | 40]:
from evaluate.ClassificationEvaluate import ClassificationEvaluate
ce = ClassificationEvaluate(labelColName='Survived',scoreColName='predict_score')
ce.transform(predict)
# fpr-横坐标,rpr-纵坐标,fpr越小越好,tpr越大越好;AUC为ROC曲线下面的面积
# In[ ]:
| identifier_body | |
kube.go | d)", apierrors.FromObject(obj).Error(), r.StatusCode)
}
if s, ok := obj.(*metav1.Status); ok {
d := s.Details
if d == nil {
return obj, s.Message, nil
}
return obj, fmt.Sprintf("%s%s `%s", d.Kind, d.Group, d.Name), nil
}
if in, ok := obj.(metav1.Object); ok {
return obj, fmt.Sprintf("%s%s `%s'", stri... | random_line_split | ||
kube.go | resArg[1].(starlark.String)
if !ok {
err = errors.New("expected string for resource name")
return
}
name = string(nameArg)
return
}
// kubePutFn is entry point for `kube.put' callable.
// TODO(dmitry-ilyevskiy): Return Status object from the response as Starlark dict.
func (m *kubePackage) kubePutFn(t *starla... | kubeExistsFn | identifier_name | |
kube.go | err != nil {
return nil, err
}
v, k := gvk.ToAPIVersionAndKind()
unknownBytes, err := proto.Marshal(&runtime.Unknown{
TypeMeta: runtime.TypeMeta{
APIVersion: v,
Kind: k,
},
Raw: msgBytes,
})
if err != nil {
return nil, err
}
return append(k8sProtoMagic, unknownBytes...), nil
}
var decode... | {
if err := printUnifiedDiff(os.Stdout, live, msg.(runtime.Object), r.GVK, maybeNamespaced(r.Name, r.Namespace), m.diffFilters); err != nil {
return err
}
} | conditional_block | |
kube.go | Ctx.Attrs["addon_version"])
if err != nil {
return err
}
if len(version) >= 2 && version[0] == '"' && version[len(version)-1] == '"' {
ls["addon_version"] = string(version[1 : len(version)-1])
}
}
if err := a.SetLabels(obj, ls); err != nil {
return err
}
as, err := a.Annotations(obj)
if err != nil... | namespace = ss[0]
name = ss[1]
}
}
// Optional api_group argument.
var apiGroup starlark.String
var foreground starlark.Bool
for _, kv := range kwargs[1:] {
switch string(kv[0].(starlark.String)) {
case apiGroupKW:
var ok bool
if apiGroup, ok = kv[1].(starlark.String); !ok {
return nil, fmt.... | {
if len(args) != 0 {
return nil, fmt.Errorf("<%v>: positional args not supported by `kube.delete': %v", b.Name(), args)
}
if len(kwargs) < 1 {
return nil, fmt.Errorf("<%v>: expected at least <resource>=<name>", b.Name())
}
resource, name, err := getResourceAndName(kwargs[0])
if err != nil {
return nil, f... | identifier_body |
run_model.py | plt.ylabel("backwater lengths")
cem = Cem()
raf = Rafem()
waves = Waves()
args = cem.setup("_run_cem", number_of_cols=120, number_of_rows=100, grid_spacing=100.0)
cem.initialize(*args)
args = raf.setup(
"_run_rafem",
n_cols=120,
n_rows=100,
dy=0.1,
dx=0.1,
time_step= 0.05, # timestep (da... | import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
land = plt.cm.terrain(np.linspace(0.4, 1, 128))
ocean = plt.cm.ocean(np.linspace(0.5, 0.8, 128))
colors = np.vstack((ocean, land))
m = LinearSegmentedColormap.from_list("land_ocean", colors)
(x, y) = np.meshg... | identifier_body | |
run_model.py | (spacing, z):
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
land = plt.cm.terrain(np.linspace(0.4, 1, 128))
ocean = plt.cm.ocean(np.linspace(0.5, 0.8, 128))
colors = np.vstack((ocean, land))
m = LinearSegmentedColormap.from_list("land_ocean", colors)
... | plot_coast | identifier_name | |
run_model.py | , 0, 10])
# plt.colorbar(orientation='horizontal').ax.set_xlabel('Elevation (m)')
plt.xlabel("backwater lengths")
plt.ylabel("backwater lengths")
cem = Cem()
raf = Rafem()
waves = Waves()
args = cem.setup("_run_cem", number_of_cols=120, number_of_rows=100, grid_spacing=100.0)
cem.initialize(*args)
args =... |
raf_z.reshape(shape[0] * shape[1])
cem.set_value("land_surface__elevation", raf_z)
# update wave climate
waves.update()
angle = waves.get_value(
"sea_surface_water_wave__azimuth_angle_of_opposite_of_phase_velocity"
)
cem.set_value(
"sea_surface_water_wave__azimuth_angle_o... | if raf_z[riv_j[k], riv_i[k]] < 1:
if mouth_cell_count < 1:
mouth_cell_count += 1
else:
raf_z[riv_j[k], riv_i[k]] = 1 | conditional_block |
run_model.py | , 0, 10])
# plt.colorbar(orientation='horizontal').ax.set_xlabel('Elevation (m)')
plt.xlabel("backwater lengths")
plt.ylabel("backwater lengths")
cem = Cem()
raf = Rafem()
waves = Waves()
args = cem.setup("_run_cem", number_of_cols=120, number_of_rows=100, grid_spacing=100.0)
cem.initialize(*args)
args =... |
### set CEM wave angle if not updating waves ###
# cem.set_value("sea_surface_water_wave__azimuth_angle_of_opposite_of_phase_velocity", 0. * np.pi / 180.)
grid_id = cem.get_var_grid("land_surface__elevation")
spacing = cem.get_grid_spacing(grid_id)
shape = cem.get_grid_shape(grid_id)
z0 = raf.get_value("land_surface... | cem.set_value("sea_surface_water_wave__period", 9.0) | random_line_split |
schedule.rs | ::new(0);
thread_local! {
static CURRENT_CONTEXT: RefCell<InnerContext> = {
RefCell::new(InnerContext::new())
};
}
type RequestSender = std_mpsc::Sender<Request>;
type RequestReceiver = std_mpsc::Receiver<Request>;
/// The identifier of a scheduler.
pub type SchedulerId = usize;
/// Scheduler of spa... | let is_runnable = {
CURRENT_CONTEXT.with(|context| {
let mut context = context.borrow_mut();
if context
.scheduler
.as_ref()
.map_or(true, |s| s.id != self.scheduler_id)
{
... | let finished; | random_line_split |
schedule.rs | new(0);
thread_local! {
static CURRENT_CONTEXT: RefCell<InnerContext> = {
RefCell::new(InnerContext::new())
};
}
type RequestSender = std_mpsc::Sender<Request>;
type RequestReceiver = std_mpsc::Receiver<Request>;
/// The identifier of a scheduler.
pub type SchedulerId = usize;
/// Scheduler of spawn... |
Err(std_mpsc::TryRecvError::Disconnected) => unreachable!(),
Ok(request) => {
did_something = true;
self.handle_request(request);
}
}
// Task
if let Some(fiber_id) = self.next_runnable() {
... | {} | conditional_block |
schedule.rs | ::new(0);
thread_local! {
static CURRENT_CONTEXT: RefCell<InnerContext> = {
RefCell::new(InnerContext::new())
};
}
type RequestSender = std_mpsc::Sender<Request>;
type RequestReceiver = std_mpsc::Receiver<Request>;
/// The identifier of a scheduler.
pub type SchedulerId = usize;
/// Scheduler of spa... | <'a> {
scheduler: &'a mut CurrentScheduler,
fiber: &'a mut FiberState,
}
impl<'a> Context<'a> {
/// Returns the identifier of the current exeuction context.
pub fn context_id(&self) -> super::ContextId {
(self.scheduler.id, self.fiber.fiber_id)
}
/// Parks the current fiber.
pub fn ... | Context | identifier_name |
schedule.rs | new(0);
thread_local! {
static CURRENT_CONTEXT: RefCell<InnerContext> = {
RefCell::new(InnerContext::new())
};
}
type RequestSender = std_mpsc::Sender<Request>;
type RequestReceiver = std_mpsc::Receiver<Request>;
/// The identifier of a scheduler.
pub type SchedulerId = usize;
/// Scheduler of spawn... |
fn next_runnable(&mut self) -> Option<fiber::FiberId> {
while let Some(fiber_id) = self.run_queue.pop_front() {
if let Some(fiber) = self.fibers.get_mut(&fiber_id) {
fiber.in_run_queue = false;
return Some(fiber_id);
}
}
None
}
}
... | {
let fiber = assert_some!(self.fibers.get_mut(&fiber_id));
if !fiber.in_run_queue {
self.run_queue.push_back(fiber_id);
fiber.in_run_queue = true;
}
} | identifier_body |
HttpServiceSparqlEndpoint.ts | value\\" : \\"http://fragments.dbpedia.org/2015/en\\" }]}" [-p port] [-t timeout] [-l log-level] [-i] [--help]
Options:
-p The HTTP port to run on (default: 3000)
-t The query execution timeout in seconds (default: 60)
-l Sets the log level (e.g., debug, info, warn, ... defaults ... | (engine: ActorInitSparql, variants: { type: string, quality: number }[],
stdout: Writable, stderr: Writable,
request: http.IncomingMessage, response: http.ServerResponse) {
const mediaType: string = request.headers.accept && request.headers.accept !== '*/*'
... | handleRequest | identifier_name |
HttpServiceSparqlEndpoint.ts | @param {(code: number) => void} exit The callback to invoke to stop the script.
* @return {Promise<void>} A promise that resolves when the server has been started.
*/
public static runArgsInProcess(argv: string[], stdout: Writable, stderr: Writable,
moduleRootPath: string, env:... | }
try { response.end(); } catch (e) { /* ignore error */ }
clearTimeout(killTimeout);
} | random_line_split | |
HttpServiceSparqlEndpoint.ts | (args, moduleRootPath, env, defaultConfigPath);
return new Promise<void>((resolve) => {
new HttpServiceSparqlEndpoint(options).run(stdout, stderr)
.then(resolve)
.catch((reason) => {
stderr.write(reason);
exit(1);
resolve();
});
});
}
... | {
return resolve(body);
} | conditional_block | |
HttpServiceSparqlEndpoint.ts | => {
stderr.write(reason);
exit(1);
resolve();
});
});
}
/**
* Takes parsed commandline arguments and turns them into an object used in the HttpServiceSparqlEndpoint constructor
* @param {args: minimist.ParsedArgs} args The commandline arguments that the scr... | {
return new Promise((resolve, reject) => {
let body = '';
request.setEncoding('utf8');
request.on('error', reject);
request.on('data', (chunk) => { body += chunk; });
request.on('end', () => {
const contentType: string = request.headers['content-type'];
if (contentType... | identifier_body | |
__init__.py | from collections import deque
from functools import partial
import voluptuous as vol
from camacq.exceptions import TemplateError
from camacq.helper import BASE_ACTION_SCHEMA, get_module, has_at_least_one_key
from camacq.helper.template import make_template, render_template
from camacq.const import CAMACQ_STOP_EVENT, ... | (**kwargs):
"""Enable or disable an automation."""
name = kwargs[NAME]
automation = automations[name]
enabled = kwargs.get(ENABLED, not automation.enabled)
if enabled:
automation.enable()
else:
automation.disable()
toggle_action_schema = BASE_... | handle_action | identifier_name |
__init__.py | from collections import deque
from functools import partial
import voluptuous as vol
from camacq.exceptions import TemplateError
from camacq.helper import BASE_ACTION_SCHEMA, get_module, has_at_least_one_key
from camacq.helper.template import make_template, render_template
from camacq.const import CAMACQ_STOP_EVENT, ... |
else:
automation.disable()
toggle_action_schema = BASE_ACTION_SCHEMA.extend(
{
vol.Required(NAME): vol.All(vol.Coerce(str), vol.In(automations)),
ENABLED: vol.Boolean(), # pylint: disable=no-value-for-parameter
}
)
# register action to enable/d... | automation.enable() | conditional_block |
__init__.py |
from collections import deque
from functools import partial
import voluptuous as vol
from camacq.exceptions import TemplateError
from camacq.helper import BASE_ACTION_SCHEMA, get_module, has_at_least_one_key
from camacq.helper.template import make_template, render_template
from camacq.const import CAMACQ_STOP_EVENT,... | rendered_kwargs = action.render(variables)
seconds = rendered_kwargs.get("seconds")
self.delay(float(seconds), variables, waiting)
else:
_LOGGER.debug(
"Calling action %s.%s", action.action_type, action.action_id
... | while waiting:
action = waiting.popleft()
if action.action_type == "automations" and action.action_id == ACTION_DELAY: | random_line_split |
__init__.py | from collections import deque
from functools import partial
import voluptuous as vol
from camacq.exceptions import TemplateError
from camacq.helper import BASE_ACTION_SCHEMA, get_module, has_at_least_one_key
from camacq.helper.template import make_template, render_template
from camacq.const import CAMACQ_STOP_EVENT, ... |
return remove_triggers
class Automation:
"""Automation class."""
# pylint: disable=too-many-arguments
def __init__(
self, center, name, attach_triggers, cond_func, action_sequence, enabled=True
):
"""Set up instance."""
self._center = center
self.name = name
... | """Remove attached triggers."""
for remove in remove_funcs:
remove() | identifier_body |
cosmos.go | : registryContractAddress,
PrivateKey: key,
DB: db,
SugaredLogger: sugaredLogger,
}
}
// Start a Cosmos chain subscription
func (sub CosmosSub) Start(completionEvent *sync.WaitGroup, symbolTranslator *symbol_translator.SymbolTranslator) {
defer completionEvent.Done()... | signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
defer close(quit)
var lastProcessedBlock int64
data, err := sub.DB.Get([]byte(cosmosLevelDBKey), nil)
if err != nil {
log.Println("Error getting the last cosmos block from level db", err)
lastProcessedBlock = 0
} else {
lastProcessedBlock = new(big.Int)... |
quit := make(chan os.Signal, 1) | random_line_split |
cosmos.go | Address: registryContractAddress,
PrivateKey: key,
DB: db,
SugaredLogger: sugaredLogger,
}
}
// Start a Cosmos chain subscription
func (sub CosmosSub) Start(completionEvent *sync.WaitGroup, symbolTranslator *symbol_translator.SymbolTranslator) {
defer completionEvent... | // the prophecy claim not sent by me
continue
}
if len(tx.Data()) < 4 {
log.Println("the tx is not a smart contract call")
continue
}
// compare method id to check if it is NewProphecyClaim method
if bytes.Compare(tx.Data()[0:4], methodID) != 0 {
continue
}
// decode data via... | {
log.Printf("getAllProphecyClaim current blockNumber is %d\n", blockNumber)
block, err := client.BlockByNumber(context.Background(), big.NewInt(blockNumber))
if err != nil {
log.Printf("failed to get block from ethereum, block number is %d\n", blockNumber)
blockNumber++
continue
}
for _, tx := ran... | conditional_block |
cosmos.go | : registryContractAddress,
PrivateKey: key,
DB: db,
SugaredLogger: sugaredLogger,
}
}
// Start a Cosmos chain subscription
func (sub CosmosSub) Start(completionEvent *sync.WaitGroup, symbolTranslator *symbol_translator.SymbolTranslator) {
defer completionEvent.Done()... | (symbolTranslator *symbol_translator.SymbolTranslator, fromBlock int64, toBlock int64, ethFromBlock int64, ethToBlock int64) {
// Start Ethereum client
ethClient, err := ethclient.Dial(sub.EthProvider)
if err != nil {
log.Printf("%s \n", err.Error())
return
}
clientChainID, err := ethClient.NetworkID(context.... | Replay | identifier_name |
cosmos.go | {
sub.SugaredLogger.Errorw("sifchain client failed to extract event data from new block.",
"EventDataNewBlock", fmt.Sprintf("%v", e.Data))
}
blockHeight := data.Block.Height
// Just start from current block number if never process any block before
if lastProcessedBlock == 0 {
lastProcessedBlo... | {
var claimType types.Event
switch eventType {
case types.MsgBurn.String():
claimType = types.MsgBurn
case types.MsgLock.String():
claimType = types.MsgLock
default:
claimType = types.Unsupported
}
return claimType
} | identifier_body | |
mod.rs | I2C_SL_DELAY_COUNT: Mmio<u32>,
pub I2C_SL_INT_MASK: Mmio<u32>,
pub I2C_SL_INT_SOURCE: Mmio<u32>,
pub I2C_SL_INT_SET: Mmio<u32>,
_0x4C: Mmio<u32>,
pub I2C_TX_PACKET_FIFO: Mmio<u32>,
pub I2C_RX_FIFO: Mmio<u32>,
pub PACKET_TRANSFER_STATUS: Mmio<u32>,
pub FIFO_CONTROL: Mmio<u32>,
pub FI... | device.
self.write(device, register, &byte.to_le_bytes())
}
/// Reads a register of a d | identifier_body | |
mod.rs | The [`Sync`] trait is implemented for [`I2c`], it is considered
//! safe to share references between threads.
//!
//! - [`send_pmic_cpu_shutdown_cmd`], [`read_ti_charger_bit_7`],
//! [`clear_ti_charger_bit_7`] and [`set_ti_charger_bit_7`] are helper
//! functions which wrap common I2C operations.
//!
//! [`Registers`]... | pub I2C_CMD_DATA2: Mmio<u32>,
_0x14: Mmio<u32>,
_0x18: Mmio<u32>,
pub I2C_STATUS: Mmio<u32>,
pub I2C_SL_CNFG: Mmio<u32>,
pub I2C_SL_RCVD: Mmio<u32>,
pub I2C_SL_STATUS: Mmio<u32>,
pub I2C_SL_ADDR1: Mmio<u32>,
pub I2C_SL_ADDR2: Mmio<u32>,
pub I2C_TLOW_SEXT: Mmio<u32>,
_0x38: Mm... | pub struct Registers {
pub I2C_CNFG: Mmio<u32>,
pub I2C_CMD_ADDR0: Mmio<u32>,
pub I2C_CMD_ADDR1: Mmio<u32>,
pub I2C_CMD_DATA1: Mmio<u32>, | random_line_split |
mod.rs | pub I2C_SL_INT_SOURCE: Mmio<u32>,
pub I2C_SL_INT_SET: Mmio<u32>,
_0x4C: Mmio<u32>,
pub I2C_TX_PACKET_FIFO: Mmio<u32>,
pub I2C_RX_FIFO: Mmio<u32>,
pub PACKET_TRANSFER_STATUS: Mmio<u32>,
pub FIFO_CONTROL: Mmio<u32>,
pub FIFO_STATUS: Mmio<u32>,
pub INTERRUPT_MASK_REGISTER: Mmio<u32>,
... | u8, | identifier_name | |
mod.rs | 2 = 0x36;
/// The I²C device address for the Maxim 77620 PWR.
pub const MAX77620_PWR_I2C_ADDR: u32 = 0x3C;
/// The I²C device address for the Maxim 77620 RTC.
pub const MAX77620_RTC_I2C_ADDR: u32 = 0x68;
/// The I²C device address for the TI BQ24193.
pub const BQ24193_I2C_ADDR: u32 = 0x6B;
/// Enumeration of possible ... | ::QueryFailed);
}
// Read result and c | conditional_block | |
FP.py | for item in x:
tree.delete(item)
def LbClick1(event):#listbox点击
try:
showPic3(lb.get(lb.curselection()))
except:
pass
def LbClick2(event):#listbox双击
try:
print (lb.get(lb.curselection()))
#读取图像
im=Image.open(lb.get(lb.curselection()))
#显示图像
... | random_line_split | ||
FP.py |
f2 = 1.0*h_box/h
factor = min([f1, f2])
width = int(w*factor)
height = int(h*factor)
return pil_image.resize((width, height), Image.ANTIALIAS)
def selectPath1():#图片选择
path_img = askopenfilename()
print(path_img)
var1.set(path_img)
def selectPath():#路径选择
path_folder = as... | for index, (val, k) in enumerate(l):
tv.move(k, '', index)
tv.heading(col, command=lambda: treeview_sort_column1(tv, col, not reverse))
def treeview_sort_column2(tv, col, reverse):#Treeview、列名、排列方式(数字排序)
l = [(tv.set(k, col), k) for k in tv.get_children('')]
l.sort(key=lambda t: float(t[0]), rev... | age1_resized = resize(w, h, w_box, h_box, image1)#改成合适比例函数
image11= ImageTk.PhotoImage(image1_resized) #转成XX对象
label1.configure(image = image11)
def treeview_sort_column1(tv, col, reverse):#Treeview、列名、排列方式(桶排序)
l = [(tv.set(k, col), k) for k in tv.get_children('')]
l.sort(reverse=reverse)
| identifier_body |
FP.py |
f2 = 1.0*h_box/h
factor = min([f1, f2])
width = int(w*factor)
height = int(h*factor)
return pil_image.resize((width, height), Image.ANTIALIAS)
def selectPath1():#图片选择
path_img = askopenfilename()
print(path_img)
var1.set(path_img)
def selectPath():#路径选择
path_folder = as... | try:
showPic3(lb.get(lb.curselection()))
except:
pass
def LbClick2(event):#listbox双击
try:
print (lb.get(lb.curselection()))
#读取图像
im=Image.open(lb.get(lb.curselection()))
#显示图像
im.show()
except:
pass
def lbExecute(listT):#listbox处理
... | 1(event):#listbox点击
| conditional_block |
FP.py | retrieval.imagehash_retrieval(var1, var2,'dhash',thred=0)
print(hash_res)
def clicked3():
hash_res = imagehash_retrieval.imagehash_retrieval(var1, var2,'phash',thred=0)
print(hash_res)
def clicked4():
hash_res = imagehash_retrieval.imagehash_retrieval(var1, var2,'whas... | agehash_ | identifier_name | |
get_block_template.rs | invalid proposal format", parse_error.into()).into(),
);
}
};
let block_verifier_router_response = block_verifier_router
.ready()
.await
.map_err(|error| Error {
code: ErrorCode::ServerError(0),
message: error.to_string(),
data: No... | combine_coinbase_outputs | identifier_name | |
get_block_template.rs | data: Some(_),
..
} => Err(Error {
code: ErrorCode::InvalidParams,
message: "\"data\" parameter must be \
omitted in \"template\" mode"
.to_string(),
data: None,
}),
}
}
/// Returns the miner address, or an e... |
/// Returns the transactions that are currently in `mempool`, or None if the
/// `last_seen_tip_hash` from the mempool response doesn't match the tip hash from the state.
///
/// You should call `check_synced_to_tip()` before calling this function.
/// If the mempool is inactive because Zebra is not synced to the tip... | {
let request = zebra_state::ReadRequest::ChainInfo;
let response = state
.oneshot(request.clone())
.await
.map_err(|error| Error {
code: ErrorCode::ServerError(0),
message: error.to_string(),
data: None,
})?;
let chain_info = match respon... | identifier_body |
get_block_template.rs | transparent,
};
use zebra_consensus::{
funding_stream_address, funding_stream_values, miner_subsidy, FundingStreamReceiver,
};
use zebra_node_services::mempool;
use zebra_state::GetBlockTemplateChainInfo;
use crate::methods::get_block_template_rpcs::{
constants::{MAX_ESTIMATED_DISTANCE_TO_NETWORK_CHAIN_TIP... | parameters::Network,
serialization::ZcashDeserializeInto,
transaction::{Transaction, UnminedTx, VerifiedUnminedTx}, | random_line_split | |
server.rs | layerinfos: format!("{}", layerinfos.join(", ")),
hasviewer: hasviewer,
}
}
}
struct StaticFiles {
files: HashMap<&'static str, (&'static [u8], MediaType)>,
}
impl StaticFiles {
fn init() -> StaticFiles {
let mut static_files = StaticFiles {
files: Hash... | {
let mut hasviewer = true;
let layerinfos: Vec<String> = set.layers
.iter()
.map(|l| {
let geom_type = l.geometry_type.clone().unwrap_or("UNKNOWN".to_string());
hasviewer = hasviewer
&& [
"POINT",
... | identifier_body | |
server.rs | MediaType::Ico,
);
static_files.add(
"index.html",
include_bytes!("static/index.html"),
MediaType::Html,
);
static_files.add(
"viewer.js",
include_bytes!("static/viewer.js"),
MediaType::Js,
);
static... |
} else {
None
}
}
None => None,
};
}
pub fn service_from_args(args: &ArgMatches) -> (MvtService, ApplicationCfg) {
if let Some(cfgpath) = args.value_of("config") {
info!("Reading configuration from '{}'", cfgpath);
for argname in vec!["db... | {
Some(0)
} | conditional_block |
server.rs | () -> StaticFiles {
let mut static_files = StaticFiles {
files: HashMap::new(),
};
static_files.add(
"favicon.ico",
include_bytes!("static/favicon.ico"),
MediaType::Ico,
);
static_files.add(
"index.html",
inc... | init | identifier_name | |
server.rs | .html".to_string()
} else {
name
};
if let Some(path) = base {
key = format!("{}/{}", path, key);
}
self.files.get(&key as &str)
}
}
include!(concat!(env!("OUT_DIR"), "/fonts.rs"));
static DINO: &'static str = " xxxxxxxxx
xxxxxxxx... | let json = service.get_mbtiles_metadata(&tileset).unwrap(); | random_line_split | |
mod.rs | as_ref()
.join(crate::cfg::TEMPLATE_SAMPLES_DIRNAME);
let samples = Sample::find_from_folder(template_loc, &samples_folder, &tmp_dir)?;
info!(nb_samples_detected = samples.len(), ?samples_folder);
for sample in samples {
info!(sample = ?sample.name, args = ?sample.args, "checking...");
... | else if crate::ui::ask_to_update_sample("Accept to add into sample ?")? {
let path = self.actual_base_path.join(&self.relative_path);
let is_dir = std::fs::metadata(&path)?.is_dir();
if is_dir {
std::fs::create_dir_all(self.expect_base... | {
let path = self.expect_base_path.join(&self.relative_path);
let is_dir = std::fs::metadata(&path)?.is_dir();
if crate::ui::ask_to_update_sample("Accept to remove from sample ?")? {
if is_dir {
std::fs::remo... | conditional_block |
mod.rs | (), ?samples_folder);
for sample in samples {
info!(sample = ?sample.name, args = ?sample.args, "checking...");
let run = SampleRun::run(&sample)?;
is_success = is_success && run.is_success();
show_differences(&sample.name, &run.diffs, review_mode)?;
}
Ok(is_success || review... | {
// ALTERNATIVE: fork a sub-process to run current ffizer in apply mode
let destination = &sample.args.dst_folder;
if sample.existing.exists() {
copy(&sample.existing, destination)?;
}
let ctx = crate::Ctx {
cmd_opt: sample.args.clone(),
};
... | identifier_body | |
mod.rs | as_ref()
.join(crate::cfg::TEMPLATE_SAMPLES_DIRNAME);
let samples = Sample::find_from_folder(template_loc, &samples_folder, &tmp_dir)?;
info!(nb_samples_detected = samples.len(), ?samples_folder);
for sample in samples {
info!(sample = ?sample.name, args = ?sample.args, "checking...");
... | samples_folder: B,
tmp_dir: &TempDir,
) -> Result<Vec<Sample>> {
let mut out = vec![];
for e in fs::read_dir(&samples_folder).map_err(|source| Error::ListFolder {
path: samples_folder.as_ref().into(),
source,
})? {
let path = e?.path();
... | fn find_from_folder<B: AsRef<Path>>(
template_loc: &SourceLoc, | random_line_split |
mod.rs | as_ref()
.join(crate::cfg::TEMPLATE_SAMPLES_DIRNAME);
let samples = Sample::find_from_folder(template_loc, &samples_folder, &tmp_dir)?;
info!(nb_samples_detected = samples.len(), ?samples_folder);
for sample in samples {
info!(sample = ?sample.name, args = ?sample.args, "checking...");
... | <P: AsRef<Path>>(file: P) -> Result<Self> {
let v = if file.as_ref().exists() {
let cfg_str = fs::read_to_string(file.as_ref()).map_err(|source| Error::ReadFile {
path: file.as_ref().into(),
source,
})?;
serde_yaml::from_str::<SampleCfg>(&cfg_s... | from_file | identifier_name |
train.py | time
import torch
import pickle
import shutil
import math
import evaluator
import net
import optimizer as optim
from torchtext import data
import utils
from config import get_train_args
def save_checkpoint(state, is_best, model_path_, best_model_path_):
torch.save(state, model_path_)
if is_best:
shu... |
bleu_score, _ = CalculateBleu(model,
dev_data,
'Dev Bleu',
batch=args.batchsize // 4,
beam_size=args.beam_size,
... | print('Validation perplexity: %g' % valid_stats.ppl())
print('Validation accuracy: %g' % valid_stats.accuracy()) | random_line_split |
train.py | time
import torch
import pickle
import shutil
import math
import evaluator
import net
import optimizer as optim
from torchtext import data
import utils
from config import get_train_args
def save_checkpoint(state, is_best, model_path_, best_model_path_):
torch.save(state, model_path_)
if is_best:
shu... |
print('Train perplexity: %g' % train_stats.ppl())
print('Train accuracy: %g' % train_stats.accuracy())
print('Validation perplexity: %g' % valid_stats.ppl())
print('Validation accuracy: %g' % valid_stats.accuracy())
bleu_score, _ = Calc... | model.eval()
in_arrays = utils.seq2seq_pad_concat_convert(dev_batch, -1)
loss_test, stat = model(*in_arrays)
valid_stats.update(stat) | conditional_block |
train.py | time
import torch
import pickle
import shutil
import math
import evaluator
import net
import optimizer as optim
from torchtext import data
import utils
from config import get_train_args
def save_checkpoint(state, is_best, model_path_, best_model_path_):
torch.save(state, model_path_)
if is_best:
shu... | (new, count, sofar):
# return sofar + len(new[0]) + len(new[1])
return sofar + (2 * max(len(new[0]), len(new[1])))
def save_output(hypotheses, vocab, outf):
# Save the Hypothesis to output file
with io.open(outf, 'w') as fp:
for sent in hypotheses:
words = [vocab[y] for y in sent]
... | batch_size_func | identifier_name |
train.py | time
import torch
import pickle
import shutil
import math
import evaluator
import net
import optimizer as optim
from torchtext import data
import utils
from config import get_train_args
def save_checkpoint(state, is_best, model_path_, best_model_path_):
torch.save(state, model_path_)
if is_best:
shu... | ys = self.model.translate(sources,
self.max_length,
beam=self.beam_size,
alpha=self.alpha)
else:
ys = [y.tolist() for y in
self.... | def __init__(self, model, test_data, key, batch=50, max_length=50,
beam_size=1, alpha=0.6, max_sent=None):
self.model = model
self.test_data = test_data
self.key = key
self.batch = batch
self.device = -1
self.max_length = max_length
self.beam_size... | identifier_body |
remotenode.go | Local node is nil")
}
if conn == nil {
return nil, errors.New("conn is nil")
}
node, err := NewNode(nil, "")
if err != nil {
return nil, err
}
txMsgCache := cache.NewGoCache(txMsgCacheExpiration, txMsgCacheCleanupInterval)
remoteNode := &RemoteNode{
Node: node,
LocalNode: localNode,
conn: ... | if len(msg.MessageId) == 0 {
return nil, errors.New("Message ID is empty")
}
| random_line_split | |
remotenode.go |
// Max message size in bytes
maxMsgSize = 20 * 1024 * 1024
)
// RemoteNode is a remote node
type RemoteNode struct {
*Node
LocalNode *LocalNode
IsOutbound bool
conn net.Conn
rxMsgChan chan *protobuf.Message
txMsgChan chan *protobuf.Message
txMsgCache cache.Cache
ready bool
readyLock sync.RW... |
for _, f := range rn.LocalNode.middlewareStore.remoteNodeDisconnected {
if !f(rn) {
break
}
}
})
})
}
// handleMsg starts a loop that handles received msg
func (rn *RemoteNode) handleMsg() {
var msg *protobuf.Message
var remoteMsg *RemoteMessage
var msgChan chan *RemoteMessage
var err error... | {
rn.StopOnce.Do(func() {
if err != nil {
log.Warningf("Remote node %v stops because of error: %s", rn, err)
} else {
log.Infof("Remote node %v stops", rn)
}
err = rn.NotifyStop()
if err != nil {
log.Warning("Notify remote node stop error:", err)
}
time.AfterFunc(stopGracePeriod, func() {
r... | identifier_body |
remotenode.go | remoteNode, ok := value.(*RemoteNode)
if ok && remoteNode.IsReady() && bytes.Equal(remoteNode.Id, n.Id) {
if remoteNode.IsStopped() {
log.Warningf("Remove stopped remote node %v from list", remoteNode)
rn.LocalNode.neighbors.Delete(key)
} else {
existing = remoteNode
}
return f... | {
return nil, err
} | conditional_block | |
remotenode.go |
// Max message size in bytes
maxMsgSize = 20 * 1024 * 1024
)
// RemoteNode is a remote node
type RemoteNode struct {
*Node
LocalNode *LocalNode
IsOutbound bool
conn net.Conn
rxMsgChan chan *protobuf.Message
txMsgChan chan *protobuf.Message
txMsgCache cache.Cache
ready bool
readyLock sync.RW... | (err error) {
rn.StopOnce.Do(func() {
if err != nil {
log.Warningf("Remote node %v stops because of error: %s", rn, err)
} else {
log.Infof("Remote node %v stops", rn)
}
err = rn.NotifyStop()
if err != nil {
log.Warning("Notify remote node stop error:", err)
}
time.AfterFunc(stopGracePeriod, f... | Stop | identifier_name |
neurosky_ecg.py | #parse length byte
while True:
pLength = ord(self.ser.read(1))
if pLength != SYNC_BYTE:
break
if pLength > 169:
continue
#print "L: %i" % pLength
# collect payload bytes
payload =... | random_line_split | ||
neurosky_ecg.py | t1.daemon = True
t1.start()
print "Started CardioChip reader"
def check(self):
""" checks if thread currently exists """
return self.connected
def stop(self):
|
def setHRVUpdate(self, numRRI):
"""
set the number of RR intervals to count
between updating the HRV value
"""
self.HRV_UPDATE = numRRI
def _parseData(self, payload):
"""
given the byte payload from the serial connection, parse the first byte
... | """ stops running thread """
self.connected = False | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.