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 |
|---|---|---|---|---|
server.go | /*
Copyright 2015 Cesanta Software Ltd.
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... |
return result, labels, nil
}
// Deny by default.
glog.Warningf("%s did not match any authn rule", ar)
return false, nil, nil
}
func (as *AuthServer) authorizeScope(ai *api.AuthRequestInfo) ([]string, error) {
for i, a := range as.authorizers {
result, err := a.Authorize(ai)
glog.V(2).Infof("Authz %s %s -> ... | {
if err == api.NoMatch {
continue
} else if err == api.WrongPass {
glog.Warningf("Failed authentication with %s: %s", err, ar.Account)
return false, nil, nil
}
err = fmt.Errorf("authn #%d returned error: %s", i+1, err)
glog.Errorf("%s: %s", ar, err)
return false, nil, err
} | conditional_block |
server.go | /*
Copyright 2015 Cesanta Software Ltd.
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agree... | (ar *authRequest) ([]authzResult, error) {
ares := []authzResult{}
for _, scope := range ar.Scopes {
ai := &api.AuthRequestInfo{
Account: ar.Account,
Type: scope.Type,
Name: scope.Name,
Service: ar.Service,
IP: ar.RemoteIP,
Actions: scope.Actions,
Labels: ar.Labels,
}
actions, e... | Authorize | identifier_name |
main.rs | extern crate argparse;
extern crate chrono;
extern crate colored;
extern crate rand;
extern crate serde;
extern crate serde_json;
extern crate time;
#[macro_use]
extern crate serde_derive;
use argparse::{ArgumentParser, Store, StoreOption};
use rand::Rng;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufR... | "Task: {} {} | {} | {} {}",
self.id,
priority_str,
self.task.bold(),
status_str,
deadline_str
)
}
}
const DATA_FOLDER: &str = ".todo.d";
const DATA_FILENAME: &str = "data.json";
const NOUNS_FILENAME: &str = "nouns.txt";
fn data_fo... | format!( | random_line_split |
main.rs | extern crate argparse;
extern crate chrono;
extern crate colored;
extern crate rand;
extern crate serde;
extern crate serde_json;
extern crate time;
#[macro_use]
extern crate serde_derive;
use argparse::{ArgumentParser, Store, StoreOption};
use rand::Rng;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufR... | (task: String, priority: u8, deadline_vague: &Option<VagueTime>) {
let mut data = load_data_catch();
let id = pick_name(&data);
println!("Adding {} - '{}'", id, task);
let deadline = deadline_vague.as_ref().map(|x| x.concretise());
let new_entry = Entry::new(id, task, priority, deadline);
data... | do_add | identifier_name |
metrics.go | /*
Copyright 2020 The Kubernetes 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/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
// handle errors wrapped with fmt.Errorf and similar
var s gRPCError
if errors.As(err, &s) {
return s.GRPCStatus().Code().String()
}
// This is not gRPC error. The operation must have failed before gRPC
// method was called, otherwise we would get gRPC error.
return "unknown-non-grpc"
}
func getHash(data s... | {
return codes.OK.String()
} | conditional_block |
metrics.go | /*
Copyright 2020 The Kubernetes 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/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | if deleted := KeyIDHashTotal.DeleteLabelValues(item.transformationType, item.providerName, item.keyIDHash); deleted {
klog.InfoS("Deleted keyIDHashTotalMetricLabels", "transformationType", item.transformationType,
"providerName", item.providerName, "keyIDHash", item.keyIDHash)
}
if deleted := KeyIDHashLast... | item := key.(metricLabels) | random_line_split |
metrics.go | /*
Copyright 2020 The Kubernetes 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/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
func RecordArrival(transformationType string, start time.Time) {
switch transformationType {
case FromStorageLabel:
lockLastFromStorage.Lock()
defer lockLastFromStorage.Unlock()
if lastFromStorage.IsZero() {
lastFromStorage = start
}
dekCacheInterArrivals.WithLabelValues(transformationType).Observe(st... | {
InvalidKeyIDFromStatusTotal.WithLabelValues(providerName, errCode).Inc()
} | identifier_body |
metrics.go | /*
Copyright 2020 The Kubernetes 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/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (transformationType string, start time.Time) {
switch transformationType {
case FromStorageLabel:
lockLastFromStorage.Lock()
defer lockLastFromStorage.Unlock()
if lastFromStorage.IsZero() {
lastFromStorage = start
}
dekCacheInterArrivals.WithLabelValues(transformationType).Observe(start.Sub(lastFromStor... | RecordArrival | identifier_name |
prepare_data_for_nlp.py | """
- Script takes input years and output years and loads the corresponding year's
(processed) visits tables.
- It then sorts the visits based on krypht.
- merges the visits table with the combined diagnosis table
- sets the target
"""
import os
import sys
import time
import gc
import pandas as pd
import numpy as n... |
logging.info("visits data loaded...")
logging.info("dropping rows with missing krypht id...")
df_x = df_x.query("krypht != -1")
df_y = df_y.query("krypht != -1")
logging.info("merging visits with diag..."),
df_x.set_index("isoid", inplace=True)
df_y.set_index("isoid", inplace=True)
c... | df_x = pd.concat(
[
df_x,
pd.read_csv(
VOLUME_PATH / Path(f"visits_norm_{year}.csv"), parse_dates=["tupva"]
),
]
) | conditional_block |
prepare_data_for_nlp.py | """
- Script takes input years and output years and loads the corresponding year's
(processed) visits tables.
- It then sorts the visits based on krypht.
- merges the visits table with the combined diagnosis table
- sets the target
"""
import os
import sys
import time
import gc
import pandas as pd
import numpy as n... |
def _yh_grouper(partition):
yh_seq = ";".join(partition["yhteystapa"].values.tolist())
return yh_seq
def _pal_grouper(partition):
pal_seq = ";".join(partition["palvelumuoto"].values.tolist())
return pal_seq
def _admittime_grouper(partition):
pal_seq = ";".join(part... | return ";".join(time_delta_seq) | random_line_split |
prepare_data_for_nlp.py | """
- Script takes input years and output years and loads the corresponding year's
(processed) visits tables.
- It then sorts the visits based on krypht.
- merges the visits table with the combined diagnosis table
- sets the target
"""
import os
import sys
import time
import gc
import pandas as pd
import numpy as n... | (paritition):
diag_seq = ";".join(paritition["diagnosis"].values.tolist())
return diag_seq
def _time_delta_grouper(partition):
time_delta_seq = partition["days_from_prev"].values.tolist()
time_delta_seq[0] = "0.0"
return ";".join(time_delta_seq)
def _yh_grouper(partitio... | _diag_grouper | identifier_name |
prepare_data_for_nlp.py | """
- Script takes input years and output years and loads the corresponding year's
(processed) visits tables.
- It then sorts the visits based on krypht.
- merges the visits table with the combined diagnosis table
- sets the target
"""
import os
import sys
import time
import gc
import pandas as pd
import numpy as n... |
def _yh_grouper(partition):
yh_seq = ";".join(partition["yhteystapa"].values.tolist())
return yh_seq
def _pal_grouper(partition):
pal_seq = ";".join(partition["palvelumuoto"].values.tolist())
return pal_seq
def _admittime_grouper(partition):
pal_seq = ";".join(par... | time_delta_seq = partition["days_from_prev"].values.tolist()
time_delta_seq[0] = "0.0"
return ";".join(time_delta_seq) | identifier_body |
bootstrap.go | /*
*
* Copyright 2019 gRPC 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/LICENSE-2.0
*
* Unless required by applicable law or agree... | {
if c.TransportAPI == version.TransportV3 {
v3, _ := c.NodeProto.(*v3corepb.Node)
if v3 == nil {
v3 = &v3corepb.Node{}
}
v3.UserAgentName = gRPCUserAgentName
v3.UserAgentVersionType = &v3corepb.Node_UserAgentVersion{UserAgentVersion: grpc.Version}
v3.ClientFeatures = append(v3.ClientFeatures, clientFea... | identifier_body | |
bootstrap.go | /*
*
* Copyright 2019 gRPC 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/LICENSE-2.0
*
* Unless required by applicable law or agree... |
config.NodeProto = n
case "xds_servers":
var servers []*xdsServer
if err := json.Unmarshal(v, &servers); err != nil {
return nil, fmt.Errorf("xds: json.Unmarshal(%v) for field %q failed during bootstrap: %v", string(v), k, err)
}
if len(servers) < 1 {
return nil, fmt.Errorf("xds: bootstrap fil... | {
return nil, fmt.Errorf("xds: jsonpb.Unmarshal(%v) for field %q failed during bootstrap: %v", string(v), k, err)
} | conditional_block |
bootstrap.go | /*
*
* Copyright 2019 gRPC 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/LICENSE-2.0
*
* Unless required by applicable law or agree... | () error {
if c.TransportAPI == version.TransportV3 {
v3, _ := c.NodeProto.(*v3corepb.Node)
if v3 == nil {
v3 = &v3corepb.Node{}
}
v3.UserAgentName = gRPCUserAgentName
v3.UserAgentVersionType = &v3corepb.Node_UserAgentVersion{UserAgentVersion: grpc.Version}
v3.ClientFeatures = append(v3.ClientFeatures, ... | updateNodeProto | identifier_name |
bootstrap.go | /*
*
* Copyright 2019 gRPC 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/LICENSE-2.0
*
* Unless required by applicable law or agree... | * limitations under the License.
*
*/
// Package bootstrap provides the functionality to initialize certain aspects
// of an xDS client by reading a bootstrap file.
package bootstrap
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
v2corepb "github.com/envoyproxy/go-control-plane/envoy/api/v2/core"
v3core... | random_line_split | |
convert2coco.py | import argparse
import sys
import os
import os.path as osp
import sqlite3
import json
import re |
def get_img_size(image_filename):
im = Image.open(image_filename)
return im.size[0], im.size[1]
def exec_sqlite_query(cursor, select_str, from_str=None, where_str=None):
query_str = 'SELECT {}'.format(select_str)
query_str += ' FROM {}'.format(from_str)
if where_str:
query_str += ' WHERE ... | from PIL import Image
# Number of facial landmarks provided by AFLW dataset
N_LANDMARK = 21
| random_line_split |
convert2coco.py | import argparse
import sys
import os
import os.path as osp
import sqlite3
import json
import re
from PIL import Image
# Number of facial landmarks provided by AFLW dataset
N_LANDMARK = 21
def get_img_size(image_filename):
im = Image.open(image_filename)
return im.size[0], im.size[1]
def exec_sqlite_query(c... |
if args.verbose:
print("Done!")
# Close database
if args.verbose:
print(" \\__Close the AFLW SQLight database...", end="")
sys.stdout.flush()
cursor.close()
if args.verbose:
print("Done!")
# Close database
if args.verbose:
print(" \\__Convert to ... | invalid_face_ids.append(face_id) | conditional_block |
convert2coco.py | import argparse
import sys
import os
import os.path as osp
import sqlite3
import json
import re
from PIL import Image
# Number of facial landmarks provided by AFLW dataset
N_LANDMARK = 21
def get_img_size(image_filename):
im = Image.open(image_filename)
return im.size[0], im.size[1]
def exec_sqlite_query(c... |
def main():
# Set up a parser for command line arguments
parser = argparse.ArgumentParser("Convert AFLW dataset's annotation into COCO json format")
parser.add_argument('-v', '--verbose', action="store_true", help="increase output verbosity")
parser.add_argument('--dataset_root', type=str, required=T... | bar_length, status = 20, ""
progress = float(progress) / float(total)
if progress >= 1.:
progress, status = 1, "\r\n"
block = int(round(bar_length * progress))
text = "\r{}[{}] {:.0f}% {}".format(msg, "#" * block + "-" * (bar_length - block), round(progress * 100, 0), status)
sys.stdout.writ... | identifier_body |
convert2coco.py | import argparse
import sys
import os
import os.path as osp
import sqlite3
import json
import re
from PIL import Image
# Number of facial landmarks provided by AFLW dataset
N_LANDMARK = 21
def get_img_size(image_filename):
im = Image.open(image_filename)
return im.size[0], im.size[1]
def exec_sqlite_query(c... | (msg, total, progress):
bar_length, status = 20, ""
progress = float(progress) / float(total)
if progress >= 1.:
progress, status = 1, "\r\n"
block = int(round(bar_length * progress))
text = "\r{}[{}] {:.0f}% {}".format(msg, "#" * block + "-" * (bar_length - block), round(progress * 100, 0),... | progress_updt | identifier_name |
main.go | // Copyright (c) 2020 Michael Madgett
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
package main
import (
"fmt"
"github.com/magic53/go-chainloader/block"
"github.com/magic53/go-chainloader/btc"
"github.com/magic53/go-chain... | // TODO Handle lookup requests
//func startServer() *http.Server {
// handler := func(w http.ResponseWriter, req *http.Request) {
// _, _ = io.WriteString(w, "Hello, world!\n")
// }
// server := &http.Server{Addr: ":8080", Handler: handler}
// return server
//}
func debugBLOCK(blockPlugin *block.Plugin, config *data.... | }
}
| random_line_split |
main.go | // Copyright (c) 2020 Michael Madgett
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
package main
import (
"fmt"
"github.com/magic53/go-chainloader/block"
"github.com/magic53/go-chainloader/btc"
"github.com/magic53/go-chain... | (btcPlugin *btc.Plugin, config *data.TokenConfig) {
var err error
//var txids []string
//txids, err = data.RPCRawMempool(config)
//if err != nil {
// fmt.Println(err.Error())
//}
//// block 1922810
//txids = []string{
//}
//if rawtxs, err := data.RPCGetRawTransactions(ltcPlugin, txids, config); err != nil {
... | debugBTC | identifier_name |
main.go | // Copyright (c) 2020 Michael Madgett
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
package main
import (
"fmt"
"github.com/magic53/go-chainloader/block"
"github.com/magic53/go-chainloader/btc"
"github.com/magic53/go-chain... |
}
func debugBTC(btcPlugin *btc.Plugin, config *data.TokenConfig) {
var err error
//var txids []string
//txids, err = data.RPCRawMempool(config)
//if err != nil {
// fmt.Println(err.Error())
//}
//// block 1922810
//txids = []string{
//}
//if rawtxs, err := data.RPCGetRawTransactions(ltcPlugin, txids, config... | {
fmt.Println("error", err.Error())
} | conditional_block |
main.go | // Copyright (c) 2020 Michael Madgett
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
package main
import (
"fmt"
"github.com/magic53/go-chainloader/block"
"github.com/magic53/go-chainloader/btc"
"github.com/magic53/go-chain... |
// watchMempools watches the mempool on a timer and saves new transaction data
// to disk.
func watchMempools(plugins []interface{}, writeFiles bool) {
var counter uint64
for {
if data.IsShuttingDown() {
break
}
if counter%30000 == 0 { // every ~30 seconds
var wg sync.WaitGroup
wg.Add(len(plugins))
... | {
var err error
// Trace
//f, err := os.Create("trace.out")
//if err != nil {
// panic(err)
//}
//defer f.Close()
//err = trace.Start(f)
//if err != nil {
// panic(err)
//}
//defer trace.Stop()
// Memory profiler
//defer func() {
// f, err := os.Create("mem.prof")
// if err != nil {
// log.Fatal("co... | identifier_body |
ssl-audit.py | import OpenSSL , ssl, argparse ,json, os.path, validators, requests, logging
from datetime import datetime
from dateutil.parser import parse
from urllib.parse import urljoin
from akamai.edgegrid import EdgeGridAuth, EdgeRc
from pathlib import Path
#TODO: FIX logger format
#turn off logger
#send ouput to tmp file
#imp... |
else:
errors.append(er)
item_list.append(currentConfig)
return
def propertyManagerAPI(action:str,config:str=None,p:list=None):
try:
home = str(Path.home())
edgerc = EdgeRc(home+"/.edgerc")
if args['section']:
section = args['section']
... | currentConfig['errors'] = er | conditional_block |
ssl-audit.py | import OpenSSL , ssl, argparse ,json, os.path, validators, requests, logging
from datetime import datetime
from dateutil.parser import parse
from urllib.parse import urljoin
from akamai.edgegrid import EdgeGridAuth, EdgeRc
from pathlib import Path
#TODO: FIX logger format
#turn off logger
#send ouput to tmp file
#imp... | ():
if args['version']:
print(version)
return
if not args['audit']:
parser.print_help()
if args['verbose']:
configure_logging()
logger.info("[start]")
if args['audit'] == "list":
if args['domains'] is None:
parser.error("--domains is... | main | identifier_name |
ssl-audit.py | import OpenSSL , ssl, argparse ,json, os.path, validators, requests, logging
from datetime import datetime
from dateutil.parser import parse
from urllib.parse import urljoin
from akamai.edgegrid import EdgeGridAuth, EdgeRc
from pathlib import Path
#TODO: FIX logger format
#turn off logger
#send ouput to tmp file
#imp... |
if __name__ == '__main__':
main()
| if args['version']:
print(version)
return
if not args['audit']:
parser.print_help()
if args['verbose']:
configure_logging()
logger.info("[start]")
if args['audit'] == "list":
if args['domains'] is None:
parser.error("--domains is required to ... | identifier_body |
ssl-audit.py | import OpenSSL , ssl, argparse ,json, os.path, validators, requests, logging
from datetime import datetime
from dateutil.parser import parse
from urllib.parse import urljoin
from akamai.edgegrid import EdgeGridAuth, EdgeRc
from pathlib import Path
#TODO: FIX logger format
#turn off logger
#send ouput to tmp file
#imp... |
getCertificates(origins,configName)
else:
parser.error("The File {} does not exist!".format(File))
else:
if args['verbose']:
logger.debug("Reading rules for the property '{}' .".format(configName))
findOrigins(File,origins,configName)
... | else:
findOrigins(dictdump,origins,configName) | random_line_split |
LSTM-cartpole4.py | import gym, random, pickle, os.path, math, glob
import argparse
import rlscope.api as rlscope
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, LSTM, Activation
from tensorflow.keras.optimizers import RMSprop
import numpy as np
import tensorflow as tf
| # from tensorboardX import SummaryWriter
# USE_CUDA = torch.cuda.is_available()
# dtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor
# Variable = lambda *args, **kwargs: autograd.Variable(*args, **kwargs).cuda() if USE_CUDA else autograd.Variable(*args, **kwargs)
#physical_device... | random_line_split | |
LSTM-cartpole4.py | import gym, random, pickle, os.path, math, glob
import argparse
import rlscope.api as rlscope
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, LSTM, Activation
from tensorflow.keras.optimizers import RMSprop
import numpy as np
import tensorflow as tf
# from tensorb... |
class DRQNAgent:
# DRQN agent
def __init__(self, action_space=None, USE_CUDA=False, memory_size=10000, epsilon=1, lr=1e-4,
max_seq=8, batch_size=32):
self.USE_CUDA = USE_CUDA
# self.device = torch.device("cuda:0" if USE_CUDA else "cpu")
self.max_seq = max_seq... | def __init__(self, memory_size=1000, max_seq=10):
self.buffer = []
self.memory_size = memory_size
self.max_seq = max_seq
self.next_idx = 0
def push(self, state, action, reward, next_state, done):
data = (state, action, reward, next_state, done)
if len(self.bu... | identifier_body |
LSTM-cartpole4.py | import gym, random, pickle, os.path, math, glob
import argparse
import rlscope.api as rlscope
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, LSTM, Activation
from tensorflow.keras.optimizers import RMSprop
import numpy as np
import tensorflow as tf
# from tensorb... | (self, num_actions=2, state=None): # device=torch.device("cpu")):
"""
Initialize a deep Q-learning network as described in
Arguments:
in_channels: number of channel of input.
i.e The number of most recent frames stacked together as describe in the paper
... | __init__ | identifier_name |
LSTM-cartpole4.py | import gym, random, pickle, os.path, math, glob
import argparse
import rlscope.api as rlscope
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, LSTM, Activation
from tensorflow.keras.optimizers import RMSprop
import numpy as np
import tensorflow as tf
# from tensorb... |
# summary_writer.close()
observation = env.reset()
count = 0
reward_sum = 0
random_episodes = 0
while random_episodes < 10:
# env.render()
x = observation.reshape(-1, 4)
x = [x]
x = np.array(x)
q_values = agent.DRQN.model.predict(x)
... | print("IT IS DONE")
print('i is', i)
print("--------------------------------------------------------------------------------------")
frame = env.reset()
# reset hidden to None
all_rewards.append(episode_reward)
print("all reward now is: ", al... | conditional_block |
linker.rs | use crate::{
Extern, ExternType, Func, FuncType, GlobalType, ImportType, Instance, IntoFunc, Module, Store,
};
use anyhow::{anyhow, bail, Result};
use std::collections::hash_map::{Entry, HashMap};
use std::rc::Rc;
/// Structure used to link wasm modules/instances together.
///
/// This structure is used to assist ... | /// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// # let store = Store::default();
/// let mut linker = Linker::new(&store);
/// linker.func("host", "double", |x: i32| x * 2)?;
/// linker.func("host", "log_i32", |x: i32| println!("{}", x))?;
/// linker.func("host"... | /// # Examples
/// | random_line_split |
linker.rs | use crate::{
Extern, ExternType, Func, FuncType, GlobalType, ImportType, Instance, IntoFunc, Module, Store,
};
use anyhow::{anyhow, bail, Result};
use std::collections::hash_map::{Entry, HashMap};
use std::rc::Rc;
/// Structure used to link wasm modules/instances together.
///
/// This structure is used to assist ... | (&mut self, module: &str, name: &str, ty: ExternType) -> ImportKey {
ImportKey {
module: self.intern_str(module),
name: self.intern_str(name),
kind: self.import_kind(ty),
}
}
fn import_kind(&self, ty: ExternType) -> ImportKind {
match ty {
... | import_key | identifier_name |
linker.rs | use crate::{
Extern, ExternType, Func, FuncType, GlobalType, ImportType, Instance, IntoFunc, Module, Store,
};
use anyhow::{anyhow, bail, Result};
use std::collections::hash_map::{Entry, HashMap};
use std::rc::Rc;
/// Structure used to link wasm modules/instances together.
///
/// This structure is used to assist ... |
/// Aliases one module's name as another.
///
/// This method will alias all currently defined under `module` to also be
/// defined under the name `as_module` too.
///
/// # Errors
///
/// Returns an error if any shadowing violations happen while defining new
/// items.
pub fn... | {
if !Store::same(&self.store, instance.store()) {
bail!("all linker items must be from the same store");
}
for export in instance.exports() {
self.insert(module_name, export.name(), export.into_extern())?;
}
Ok(self)
} | identifier_body |
latcontrol_pid.py | import numpy as np
from selfdrive.controls.lib.pid import PIController
from selfdrive.controls.lib.drive_helpers import get_steer_max
from cereal import car
from cereal import log
from selfdrive.kegman_conf import kegman_conf
from common.numpy_fast import interp
import common.log as trace1
import common.MoveAvg as ... | kBP0 = 1
self.pid_BP0_time -= 1
else:
kBP0 = 0
self.pid_change_flag = 3
self.steerKpV = [ float(self.steer_Kp1[ kBP0 ]), float(self.steer_Kp2[ kBP0 ]) ]
self.steerKiV = [ float(self.steer_Ki1[ kBP0 ]), float(self.steer_Ki2[ kBP0 ]) ]
xp = CP.lateralTuning.pid.kpBP
fp = [float(se... | g = 2
##
self.pid_BP0_time = 300
elif self.pid_BP0_time:
| conditional_block |
latcontrol_pid.py | import numpy as np
from selfdrive.controls.lib.pid import PIController
from selfdrive.controls.lib.drive_helpers import get_steer_max
from cereal import car
from cereal import log
from selfdrive.kegman_conf import kegman_conf
from common.numpy_fast import interp
import common.log as trace1
import common.MoveAvg as ... | o ): # 곡률에 의한 변화.
cv_value = self.v_curvature
cv = [ 100, 200 ] # 곡률
# Kp
fKp1 = [float(self.steer_Kp1[ 1 ]), float(self.steer_Kp1[ 0 ]) ]
fKp2 = [float(self.steer_Kp2[ 1 ]), float(self.steer_Kp2[ 0 ]) ]
self.steerKp1 = interp( cv_value, cv, fKp1 )
self.steerKp2 = interp( cv_value, cv... | f, CP, v_eg | identifier_name |
latcontrol_pid.py | import numpy as np
from selfdrive.controls.lib.pid import PIController
from selfdrive.controls.lib.drive_helpers import get_steer_max
from cereal import car
from cereal import log
from selfdrive.kegman_conf import kegman_conf
from common.numpy_fast import interp
import common.log as trace1
import common.MoveAvg as ... | md = sm['model']
if len(md.path.poly):
path = list(md.path.poly)
self.l_poly = np.array(md.leftLane.poly)
self.r_poly = np.array(md.rightLane.poly)
self.p_poly = np.array(md.path.poly)
# Curvature of polynomial https://en.wikipedia.org/wiki/Curvature#Curvature_of_the_grap... | random_line_split | |
latcontrol_pid.py | import numpy as np
from selfdrive.controls.lib.pid import PIController
from selfdrive.controls.lib.drive_helpers import get_steer_max
from cereal import car
from cereal import log
from selfdrive.kegman_conf import kegman_conf
from common.numpy_fast import interp
import common.log as trace1
import common.MoveAvg as ... |
def reset( self ):
self.pid.reset()
def linear2_tune( self, CP, v_ego ): # angle(조향각에 의한 변화)
cv_angle = abs(self.angle_steers_des)
cv = [ 2, 15 ] # angle
# Kp
fKp1 = [float(self.steer_Kp1[ 0 ]), float(self.steer_Kp1[ 1 ]) ]
fKp2 = [float(self.steer_Kp2[ 0 ]), float(self.steer_Kp2[ 1 ... | self.v_curvature, self.model_sum = self.calc_va( sm, CS.vEgo ) | identifier_body |
manifest.go | // Copyright 2018 Google LLC 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 l... |
sort.Strings(tags)
// https://github.com/opencontainers/distribution-spec/blob/b505e9cc53ec499edbd9c1be32298388921bb705/detail.md#tags-paginated
// Offset using last query parameter.
if last := req.URL.Query().Get("last"); last != "" {
for i, t := range tags {
if t > last {
tags = tags[i:]
br... | {
if !strings.Contains(tag, "sha256:") {
tags = append(tags, tag)
}
} | conditional_block |
manifest.go | // Copyright 2018 Google LLC 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 l... | (resp http.ResponseWriter, req *http.Request) *regError {
// Ensure this is a GET request
if req.Method != "GET" {
return ®Error{
Status: http.StatusBadRequest,
Code: "METHOD_UNKNOWN",
Message: "We don't understand your method + url",
}
}
elem := strings.Split(req.URL.Path, "/")
elem = elem[1:... | handleReferrers | identifier_name |
manifest.go | // Copyright 2018 Google LLC 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 l... |
func isCatalog(req *http.Request) bool {
elems := strings.Split(req.URL.Path, "/")
elems = elems[1:]
if len(elems) < 2 {
return false
}
return elems[len(elems)-1] == "_catalog"
}
// Returns whether this url should be handled by the referrers handler
func isReferrers(req *http.Request) bool {
elems := string... | {
elems := strings.Split(req.URL.Path, "/")
elems = elems[1:]
if len(elems) < 4 {
return false
}
return elems[len(elems)-2] == "tags"
} | identifier_body |
manifest.go | // Copyright 2018 Google LLC 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 l... | referenceDigest := refPointer.Subject.Digest
if referenceDigest.String() != target {
continue
}
// At this point, we know the current digest references the target
var imageAsArtifact struct {
Config struct {
MediaType string `json:"mediaType"`
} `json:"config"`
}
json.Unmarshal(manifest.blob,... | continue
} | random_line_split |
api-compose-object.go | /*
* MinIO Go Library for Amazon S3 Compatible Cloud Storage
* Copyright 2017, 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/... | }
if dstOpts.Internal.ReplicationValidityCheck {
headers.Set(minIOBucketReplicationCheck, "true")
}
if !dstOpts.Internal.LegalholdTimestamp.IsZero() {
headers.Set(minIOBucketReplicationObjectLegalHoldTimestamp, dstOpts.Internal.LegalholdTimestamp.Format(time.RFC3339Nano))
}
if !dstOpts.Internal.RetentionTimes... | if dstOpts.Internal.SourceETag != "" {
headers.Set(minIOBucketSourceETag, dstOpts.Internal.SourceETag)
}
if dstOpts.Internal.ReplicationRequest {
headers.Set(minIOBucketReplicationRequest, "true") | random_line_split |
api-compose-object.go | /*
* MinIO Go Library for Amazon S3 Compatible Cloud Storage
* Copyright 2017, 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/... |
}
}
// toDestinationInfo returns a validated copyOptions object.
func (opts CopyDestOptions) validate() (err error) {
// Input validation.
if err = s3utils.CheckValidBucketName(opts.Bucket); err != nil {
return err
}
if err = s3utils.CheckValidObjectName(opts.Object); err != nil {
return err
}
if opts.Prog... | {
if isAmzHeader(k) || isStandardHeader(k) || isStorageClassHeader(k) {
header.Set(k, v)
} else {
header.Set("x-amz-meta-"+k, v)
}
} | conditional_block |
api-compose-object.go | /*
* MinIO Go Library for Amazon S3 Compatible Cloud Storage
* Copyright 2017, 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/... |
// ComposeObject - creates an object using server-side copying
// of existing objects. It takes a list of source objects (with optional offsets)
// and concatenates them into a new object using only server-side copying
// operations. Optionally takes progress reader hook for applications to
// look at current progres... | {
// Build query parameters
urlValues := make(url.Values)
urlValues.Set("partNumber", strconv.Itoa(partNumber))
urlValues.Set("uploadId", uploadID)
// Send upload-part-copy request
resp, err := c.executeMethod(ctx, http.MethodPut, requestMetadata{
bucketName: bucket,
objectName: object,
customHeader: h... | identifier_body |
api-compose-object.go | /*
* MinIO Go Library for Amazon S3 Compatible Cloud Storage
* Copyright 2017, 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/... | (header http.Header) {
const replaceDirective = "REPLACE"
if opts.ReplaceTags {
header.Set(amzTaggingHeaderDirective, replaceDirective)
if tags := s3utils.TagEncode(opts.UserTags); tags != "" {
header.Set(amzTaggingHeader, tags)
}
}
if opts.LegalHold != LegalHoldStatus("") {
header.Set(amzLegalHoldHeade... | Marshal | identifier_name |
integration.js | 'use strict';
const request = require('postman-request');
const _ = require('lodash');
const async = require('async');
const config = require('./config/config');
const fs = require('fs');
let Logger;
let requestWithDefaults;
let previousDomainRegexAsString = '';
let domainBlocklistRegex = null;
const BASE_URI = 'htt... |
// function that creates the Json object to be passed to the payload
function _createJsonErrorObject(msg, pointer, httpCode, code, title, meta) {
let error = {
detail: msg,
status: httpCode.toString(),
title: title,
code: 'IRIS_' + code.toString()
};
if (pointer) {
error.source = {
po... | {
return {
errors: [_createJsonErrorObject(msg, pointer, httpCode, code, title, meta)]
};
} | identifier_body |
integration.js | 'use strict';
const request = require('postman-request');
const _ = require('lodash');
const async = require('async');
const config = require('./config/config');
const fs = require('fs');
let Logger;
let requestWithDefaults;
let previousDomainRegexAsString = '';
let domainBlocklistRegex = null;
const BASE_URI = 'htt... |
return R;
}
function doLookup(entities, options, cb) {
let lookupResults = [];
let entityLookup = {};
let entityLists = [];
_setupRegexBlocklists(options);
entities.forEach((entityObj) => {
if (_isInvalidEntity(entityObj) || _isEntityBlocklisted(entityObj, options)) {
return;
}
entity... | {
R.push(arr.slice(i, i + chunkSize));
} | conditional_block |
integration.js | 'use strict';
const request = require('postman-request');
const _ = require('lodash');
const async = require('async');
const config = require('./config/config');
const fs = require('fs');
let Logger;
let requestWithDefaults;
let previousDomainRegexAsString = '';
let domainBlocklistRegex = null;
const BASE_URI = 'htt... | (entityObj) {
// DomaintTools API does not accept entities over 100 characters long so if we get any of those we don't look them up
if (entityObj.value.length > MAX_ENTITY_LENGTH) {
return true;
}
// Domain labels (the parts in between the periods, must be 63 characters or less
if (entityObj.isDomain) {
... | _isInvalidEntity | identifier_name |
integration.js | 'use strict';
const request = require('postman-request');
const _ = require('lodash');
const async = require('async');
const config = require('./config/config');
const fs = require('fs');
let Logger;
let requestWithDefaults;
let previousDomainRegexAsString = '';
let domainBlocklistRegex = null;
const BASE_URI = 'htt... |
function chunk(arr, chunkSize) {
const R = [];
for (let i = 0, len = arr.length; i < len; i += chunkSize) {
R.push(arr.slice(i, i + chunkSize));
}
return R;
}
function doLookup(entities, options, cb) {
let lookupResults = [];
let entityLookup = {};
let entityLists = [];
_setupRegexBlocklists(opti... | random_line_split | |
amazon_ff_review.py | #%%
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
import json
from sklearn import metrics
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support,mean_squared_error
imp... |
#%%
def get_reviews():
con=sqlite3.connect('database.sqlite')
df=pd.read_sql('Select * from Reviews',con=con)
s=df['Score']
sample=resample(df,n_samples=10000,replace=False,stratify=s)
cleaned_review=pd.DataFrame(columns=['Summary','Helpful','Score','Sentiment','Sentiment_Polarity'])
ret... | if np.abs(polarity) < threshold :
return "Neutral"
elif np.sign(polarity)>0:
return "Positive"
else:
return "Negative" | identifier_body |
amazon_ff_review.py | #%%
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
import json
from sklearn import metrics
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support,mean_squared_error
imp... |
#%%
def make_json(df=None,model_data=None,upsample=False,stratified_column=None,metrics=None,test_size=0.49,nfold=5):
''' Preparation of Metadata in Dictionary Format'''
if upsample:
sampling='Upsampling'
else:
sampling='Stratified Sampling stratified on '+ stratified_column
encoding={... | m=i | conditional_block |
amazon_ff_review.py | #%%
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
import json
from sklearn import metrics
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support,mean_squared_error
imp... |
t=t+(end-start)
t=t/n
print(f"Cross validation scores ={kscores}")
print(f"Best model index ={best_model_index}")
best_model=kmodels[best_model_index]
print(f"Best model ={best_model}")
y_pred=best_model.predict(X_test)
return y_test,y_pred,t,best_model
#%%
def run():
clea... | random_line_split | |
amazon_ff_review.py | #%%
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
import json
from sklearn import metrics
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support,mean_squared_error
imp... | (cleaned_review=None,sample=None,threshold=0):
cleaned_review['Score']=sample['Score']
cleaned_review['Summary']=sample['Summary']
######################Preprocessing###########################
stop_words=set(stopwords.words("english"))
punc = list(string.punctuation)
punc.extend(["`","``","''",... | preprocess_and_get_sentiments | identifier_name |
lib.rs | //! # Acteur Actor System
//!
//! An safe & opinionated actor-like framework written in Rust that just works. Simple, robust, fast, documented.
//!
//!<div align="center">
//! <!-- Crates version -->
//! <a href="https://crates.io/crates/acteur">
//! <img src="https://img.shields.io/crates/v/acteur.svg?style=fl... | //!
//! ## Subscription or Pub/Sub
//!
//! Sometime we don't want to know who should receive the message but to subscribe to a type and wait.
//! Acteur models the Pub/Sub patter with Services. Actors in Acteur can't perform subscriptions as
//! that would require the framework to know all possible IDs of all possible ... | //! calculations of some sort that doesn't belong to any Actor, etc) and for subscribing to messages (Pub/Sub) | random_line_split |
preprocessing_poland.py | import logging
from contextlib import closing
from pathlib import Path
import numpy as np
import pandas as pd
from tqdm import tqdm
from openpyxl import load_workbook
from xlrd import XLRDError
from src.data.datasets import *
def prepare_family_structure_from_voivodship(data_folder: Path) -> pd.DataFrame:
"""
... | (df, headcount, family_type, relationship, house_master):
"""
Given a headcount, family type (0,1,2,3), relationship between families
(if applicable) and who the housemaster is (in multi-family households), this method returns all matching
households in the df dataframe.
"""
if house_master not... | draw_generation_configuration_for_household | identifier_name |
preprocessing_poland.py | import logging
from contextlib import closing
from pathlib import Path
import numpy as np
import pandas as pd
from tqdm import tqdm
from openpyxl import load_workbook
from xlrd import XLRDError
from src.data.datasets import *
def prepare_family_structure_from_voivodship(data_folder: Path) -> pd.DataFrame:
|
def temporary_hack(fcn):
# FIXME: introducing a hack that is actually going to destroy the probability distribution
# since it is not possible to have 3 generations in a household where only 2 people live
# but there is no distribution given for that
# the input data has to be replaced with a proper... | """
Preprocesses the family structure excel for a voivodship from pivoted to melted table for easier further processing.
"""
if (data_folder / household_family_structure_xlsx.file_name).is_file():
return pd.read_excel(str(data_folder / household_family_structure_xlsx.file_name))
headcount_colum... | identifier_body |
preprocessing_poland.py | import logging
from contextlib import closing
from pathlib import Path
import numpy as np
import pandas as pd
from tqdm import tqdm
from openpyxl import load_workbook
from xlrd import XLRDError
from src.data.datasets import *
def prepare_family_structure_from_voivodship(data_folder: Path) -> pd.DataFrame:
"""
... | * young - flag whether people younger than 30 years old live in a household
* middle - flag, whether people between 30 and 59 inclusive live in a household
* elderly - flag, whether people older than 59 live in a household
:param data_folder: data folder
:param output_folder: where to save an ou... | * family_structure_regex - auxiliary description of a household | random_line_split |
preprocessing_poland.py | import logging
from contextlib import closing
from pathlib import Path
import numpy as np
import pandas as pd
from tqdm import tqdm
from openpyxl import load_workbook
from xlrd import XLRDError
from src.data.datasets import *
def prepare_family_structure_from_voivodship(data_folder: Path) -> pd.DataFrame:
"""
... |
if family_type == 3:
return df[(df.family_type == family_type)]
if family_type == 0:
if headcount == 1:
return df[(df.family_type == family_type) & (df.relationship == 'Jednoosobowe')]
return df[(df.family_type == family_type) & (df.relationship == 'Wieloosobowe')]
raise... | if house_master not in (np.nan, '', None):
out_df = df[(df.family_type == family_type) & (df.relationship == relationship)
& (df.house_master == house_master)]
if len(out_df) > 0:
return out_df
if relationship not in (np.nan, '', None):
... | conditional_block |
progress.rs | use num_enum::IntoPrimitive;
use once_cell::sync::Lazy;
use std::sync::mpsc::Sender;
use std::{mem, pin::Pin, ptr};
use wchar::*;
use widestring::*;
use winapi::shared::basetsd;
use winapi::shared::minwindef as win;
use winapi::shared::windef::*;
use winapi::um::commctrl;
use winapi::um::errhandlingapi;
use winapi::um:... | /// Signal that progress should be cancelled.
pub fn cancel(&self) {
if let Some(tx) = &self.cancel_sender {
tx.send(()).unwrap_or_else(|_| {
log::error!("Failed to send cancel signal");
});
}
}
/// Close main window.
pub fn close(&self) {
... | random_line_split | |
progress.rs | use num_enum::IntoPrimitive;
use once_cell::sync::Lazy;
use std::sync::mpsc::Sender;
use std::{mem, pin::Pin, ptr};
use wchar::*;
use widestring::*;
use winapi::shared::basetsd;
use winapi::shared::minwindef as win;
use winapi::shared::windef::*;
use winapi::um::commctrl;
use winapi::um::errhandlingapi;
use winapi::um:... | () -> bool {
unsafe {
let instance = libloaderapi::GetModuleHandleW(ptr::null_mut());
let mut wc: winuser::WNDCLASSEXW = mem::zeroed();
winuser::GetClassInfoExW(instance, WND_CLASS.as_ptr(), &mut wc) != 0
}
}
/// Register window class.
pub fn register_win... | is_window_class_registered | identifier_name |
progress.rs | use num_enum::IntoPrimitive;
use once_cell::sync::Lazy;
use std::sync::mpsc::Sender;
use std::{mem, pin::Pin, ptr};
use wchar::*;
use widestring::*;
use winapi::shared::basetsd;
use winapi::shared::minwindef as win;
use winapi::shared::windef::*;
use winapi::um::commctrl;
use winapi::um::errhandlingapi;
use winapi::um:... |
let hwnd = self.get_control_handle(Control::ProgressBar);
unsafe { SendMessageW(hwnd, PBM_SETPOS, current, 0) };
// if done, close cancellation channel
if current == max {
self.cancel_sender.take();
}
}
/// Check whether progress bar is in marquee mode.
... | {
self.set_progress_to_range_mode();
} | conditional_block |
typescript.rs | //! Generation of Typescript types from Stencila Schema
use std::{
collections::HashSet,
fs::read_dir,
path::{Path, PathBuf},
};
use common::{
async_recursion::async_recursion,
eyre::{bail, Context, Report, Result},
futures::future::try_join_all,
inflector::Inflector,
itertools::Iterto... | (dest: &Path, title: &String, schema: &Schema) -> Result<String> {
let path = dest.join(format!("{}.ts", title));
if path.exists() {
return Ok(title.to_string());
}
let description = schema
.description
.as_ref()
.unwrap_or(title)
... | typescript_object | identifier_name |
typescript.rs | //! Generation of Typescript types from Stencila Schema
use std::{
collections::HashSet,
fs::read_dir,
path::{Path, PathBuf},
};
use common::{
async_recursion::async_recursion,
eyre::{bail, Context, Report, Result},
futures::future::try_join_all,
inflector::Inflector,
itertools::Iterto... |
/// Generate a TypeScript type for a schema
///
/// Returns the name of the type and whether:
/// - it is an array
/// - it is a type (rather than an enum variant)
#[async_recursion]
async fn typescript_type(dest: &Path, schema: &Schema) -> Result<(String, bool, bool)> {
use Type... | {
let Some(title) = &schema.title else {
bail!("Schema has no title");
};
if NO_GENERATE_MODULE.contains(&title.as_str()) || schema.r#abstract {
return Ok(());
}
if schema.any_of.is_some() {
Self::typescript_any_of(dest, schema).await?;
... | identifier_body |
typescript.rs | //! Generation of Typescript types from Stencila Schema
use std::{
collections::HashSet,
fs::read_dir,
path::{Path, PathBuf},
};
use common::{
async_recursion::async_recursion,
eyre::{bail, Context, Report, Result},
futures::future::try_join_all,
inflector::Inflector,
itertools::Iterto... | "Object",
"Primitive",
"String",
"TextValue",
"UnsignedInteger",
];
/// Types for which native to TypesScript types are used directly
/// Note that this excludes `Integer`, `UnsignedInteger` and `Object`
/// which although they are implemented as native types have different semantics.
const NATIVE_... | "Null",
"Number", | random_line_split |
server.go | package shardmaster
import "net"
import "fmt"
import "net/rpc"
import "log"
import "paxos"
import "sync"
import "os"
import "syscall"
import "encoding/gob"
import "math/rand"
import "time"
import "strconv"
import "sort"
import "reflect"
const (
Debug = false
InitTimeout = 10 * time.Millisecond
)
type Shard... | sm := new(ShardMaster)
sm.me = me
sm.configs = make([]Config, 1)
sm.configs[0].Groups = make(map[int64][]string)
sm.lastAppliedSeq = -1
rpcs := rpc.NewServer()
rpcs.Register(sm)
sm.px = paxos.Make(servers, me, rpcs)
os.Remove(servers[me])
l, e := net.Listen("unix", servers[me])
if e != nil {
... | random_line_split | |
server.go | package shardmaster
import "net"
import "fmt"
import "net/rpc"
import "log"
import "paxos"
import "sync"
import "os"
import "syscall"
import "encoding/gob"
import "math/rand"
import "time"
import "strconv"
import "sort"
import "reflect"
const (
Debug = false
InitTimeout = 10 * time.Millisecond
)
type Shard... |
switch op.Operation {
case Join:
args := op.Args.(JoinArgs)
return sm.applyJoin(args.GID, args.Servers)
case Leave:
args := op.Args.(LeaveArgs)
return sm.applyLeave(args.GID)
case Move:
args := op.Args.(MoveArgs)
return sm.applyMove(args.Shard, args.GID)
case Query:
args := op.Ar... | {
return &Config{}, ErrNoop
} | conditional_block |
server.go | package shardmaster
import "net"
import "fmt"
import "net/rpc"
import "log"
import "paxos"
import "sync"
import "os"
import "syscall"
import "encoding/gob"
import "math/rand"
import "time"
import "strconv"
import "sort"
import "reflect"
const (
Debug = false
InitTimeout = 10 * time.Millisecond
)
type Shard... | (i, j int) bool { return a[i].NumShards > a[j].NumShards }
type ShardMaster struct {
mu sync.Mutex
l net.Listener
me int
dead bool // for testing
unreliable bool // for testing
px *paxos.Paxos
configs []Config // indexed by config num
lastAppliedSeq int
}
... | Less | identifier_name |
server.go | package shardmaster
import "net"
import "fmt"
import "net/rpc"
import "log"
import "paxos"
import "sync"
import "os"
import "syscall"
import "encoding/gob"
import "math/rand"
import "time"
import "strconv"
import "sort"
import "reflect"
const (
Debug = false
InitTimeout = 10 * time.Millisecond
)
type Shard... |
func MakeConfig(num int, shards [NShards]int64, groups map[int64][]string) *Config {
config := &Config{}
config.Num = num
config.Shards = shards
config.Groups = groups
return config
}
func CopyGroups(src map[int64][]string) map[int64][]string {
dst := make(map[int64][]string)
for k, v := range src {
... | {
return time.Duration(rand.Int()%100) * time.Millisecond
} | identifier_body |
main.js | /**
* ===================================================================
* Main js
*
* -------------------------------------------------------------------
*/
(function($) {
"use strict";
/* --------------------------------------------------- */
/* Preloader
------------------------... | appendHTML: function() {
// if this has already been added we don't need to add it again
if ($('.simplePopupBackground').length === 0) {
var background = '<div class="simplePopupBackground"></div>';
$('body').prepend(background);
... | Append HTML
*******************************/
| random_line_split |
main.js | /**
* ===================================================================
* Main js
*
* -------------------------------------------------------------------
*/
(function($) {
"use strict";
/* --------------------------------------------------- */
/* Preloader
------------------------... | // There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
... | sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
| conditional_block |
version_info.rs | /*!
Version Information.
See [Microsoft's documentation](https://docs.microsoft.com/en-us/windows/desktop/menurc/version-information) for more information.
*/
use std::{char, cmp, fmt, mem, slice};
use std::collections::HashMap;
use crate::image::VS_FIXEDFILEINFO;
use crate::{Error, Result, _Pod as Pod};
use crate:... |
/// Gets the strings in a hash map.
pub fn to_hash_map(self) -> HashMap<String, String> {
let mut hash_map = HashMap::new();
self.visit(&mut hash_map);
hash_map
}
/// Parse the version information.
///
/// Because of the super convoluted format, the visitor pattern is used.
/// Implement the [`Visit` tra... | {
self.visit(&mut ForEachString(&mut f));
} | identifier_body |
version_info.rs | /*!
Version Information.
See [Microsoft's documentation](https://docs.microsoft.com/en-us/windows/desktop/menurc/version-information) for more information.
*/
use std::{char, cmp, fmt, mem, slice};
use std::collections::HashMap;
use crate::image::VS_FIXEDFILEINFO;
use crate::{Error, Result, _Pod as Pod};
use crate:... | (&mut self, _lang: &'a [u16], key: &'a [u16], value: &'a [u16]) {
if Iterator::eq(self.key.chars().map(Ok), char::decode_utf16(key.iter().cloned())) {
self.value = Some(value);
}
}
}
//----------------------------------------------------------------
/*
"version_info": {
"fixed": { .. },
"strings": { .. }... | string | identifier_name |
version_info.rs | /*!
Version Information.
See [Microsoft's documentation](https://docs.microsoft.com/en-us/windows/desktop/menurc/version-information) for more information.
*/
use std::{char, cmp, fmt, mem, slice};
use std::collections::HashMap;
use crate::image::VS_FIXEDFILEINFO;
use crate::{Error, Result, _Pod as Pod};
use crate:... | // TLV length field larger than the data
parser = Parser::new_zero(&[12, 0, 0, 0]);
assert_eq!(parser.next(), Some(Err(Error::Invalid)));
assert_eq!(parser.next(), None);
// TLV key not nul terminated
parser = Parser::new_zero(&[16, 0, 1, 20, 20, 20, 20, 20]);
assert_eq!(parser.next(), Some(Err(Error::Invalid))... | parser = Parser::new_zero(&[0, 0]);
assert_eq!(parser.next(), Some(Err(Error::Invalid)));
assert_eq!(parser.next(), None);
| random_line_split |
version_info.rs | /*!
Version Information.
See [Microsoft's documentation](https://docs.microsoft.com/en-us/windows/desktop/menurc/version-information) for more information.
*/
use std::{char, cmp, fmt, mem, slice};
use std::collections::HashMap;
use crate::image::VS_FIXEDFILEINFO;
use crate::{Error, Result, _Pod as Pod};
use crate:... |
}
let mut digits = [0u16; 8];
for i in 0..8 {
digits[i] = digit(lang[i]);
}
let lang_id = (digits[0] << 12) | (digits[1] << 8) | (digits[2] << 4) | digits[3];
let charset_id = (digits[4] << 12) | (digits[5] << 8) | (digits[6] << 4) | digits[7];
Ok(Language { lang_id, charset_id })
}
}
impl fmt::Displ... | { num } | conditional_block |
symbols.py | # Copyright (c) 2021, nla group, manchester
# All rights reserved.
# Redistribution and use in source and binary forms, with or without | # modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditio... | random_line_split | |
symbols.py | # Copyright (c) 2021, nla group, manchester
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condition... |
self.number_of_symbols = k
self.return_list = return_list
self.mu, self.std = 0, 1
def transform(self, time_series):
if self.width is None:
self.width = len(time_series) // self.n_paa_segments
self.mu = np.mean(time_series)
self.std = np... | self.n_paa_segments = None
self.width = width | conditional_block |
symbols.py | # Copyright (c) 2021, nla group, manchester
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condition... |
def paa_mean(self, ts):
if len(ts) % self.width != 0:
warnings.warn("Result truncates, width does not divide length")
return [np.mean(ts[i*self.width:np.min([len(ts), (i+1)*self.width])]) for i in range(int(np.floor(len(ts)/self.width)))]
def _digitize(self, ts):
... | compressed_time_series = self._reverse_digitize(symbolic_time_series)
time_series = self._reconstruct(compressed_time_series)
time_series = time_series*self.std + self.mu
return time_series | identifier_body |
symbols.py | # Copyright (c) 2021, nla group, manchester
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condition... | elf, pieces):
if len(pieces) == 1:
pieces[0,0] = round(pieces[0,0])
else:
for p in range(len(pieces)-1):
corr = round(pieces[p,0]) - pieces[p,0]
pieces[p,0] = round(pieces[p,0] + corr)
pieces[p+1,0] = pieces[p+1,0] - corr
... | antize(s | identifier_name |
texture.rs | // texture.rs
// Creation and handling of images and textures.
// (c) 2019, Ryan McGowan <ryan@internally-combusted.net>
//! Loading and management of textures.
use gfx_backend_metal as backend;
use nalgebra_glm as glm;
use gfx_hal::{
command::{BufferImageCopy, CommandBuffer, OneShot},
format::{Aspects, Form... | let row_pitch = (row_size + row_alignment_mask) & !row_alignment_mask; // what wizardry is this
let mut writer = device.acquire_mapping_writer::<u8>(buffer_memory, data_range)?;
// Write the data row by row.
for row in 0..image.height() {
let image_offset = (row * row_size)... | // TODO: Not sure why I have a function to do this but then write it out twice.
let row_size = pixel_size * image.width();
let row_alignment_mask = limits.min_buffer_copy_pitch_alignment as u32 - 1; | random_line_split |
texture.rs | // texture.rs
// Creation and handling of images and textures.
// (c) 2019, Ryan McGowan <ryan@internally-combusted.net>
//! Loading and management of textures.
use gfx_backend_metal as backend;
use nalgebra_glm as glm;
use gfx_hal::{
command::{BufferImageCopy, CommandBuffer, OneShot},
format::{Aspects, Form... | (
&mut self,
device: &<Backend as GfxBackend>::Device,
image_memory: &<Backend as GfxBackend>::Memory,
image_memory_offset: u64,
command_pool: &mut gfx_hal::CommandPool<Backend, Graphics>,
command_queue: &mut gfx_hal::CommandQueue<Backend, Graphics>,
staging_buffe... | copy_image_to_memory | identifier_name |
texture.rs | // texture.rs
// Creation and handling of images and textures.
// (c) 2019, Ryan McGowan <ryan@internally-combusted.net>
//! Loading and management of textures.
use gfx_backend_metal as backend;
use nalgebra_glm as glm;
use gfx_hal::{
command::{BufferImageCopy, CommandBuffer, OneShot},
format::{Aspects, Form... |
// Extracted from copy_image_to_memory to clean it up a bit.
/// Switches an Image to the given state/format, handling the synchronization
/// involved.
fn reformat_image(
command_buffer: &mut CommandBuffer<Backend, Graphics>,
source_format: (Access, Layout),
target_format: (Ac... | {
device.bind_image_memory(
&image_memory,
image_memory_offset,
&mut self.image.as_mut().unwrap(),
)?;
// Creating an Image is basically like drawing a regular frame except
// the data gets rendered to memory instead of the screen, so we go
//... | identifier_body |
write.py | """
Write tables to text.
"""
import numpy as np
from collections import OrderedDict
### String and table formatting #################################
def pad_delimiters(string1, number, delimiter=',', slen=None, ):
"""
Pad string1 to the requested number of delimiters.
Parameters
... | """
d = []
for k in self.labels:
if key in k:
d.append(self[k])
return np.column_stack(d)
def __getitem__(self, key):
try:
return self.dict[key]
except:
return self.data[key]
... | returns:
------
array of shape (a, b) | random_line_split |
write.py | """
Write tables to text.
"""
import numpy as np
from collections import OrderedDict
### String and table formatting #################################
def pad_delimiters(string1, number, delimiter=',', slen=None, ):
"""
Pad string1 to the requested number of delimiters.
Parameters
... |
return np.array(names, dtype = str)
class StringTable(object):
"""
Standardardized string table for file output.
Parameters
----------
sfmt : str
formatting specifier for string formatting, ex. '%16s'.
nfmt : str
formatting specifier for numeric formatting, ex. '%1... | line = f.readline()
list_ = line.split(delimiter)
names.append(list_) | conditional_block |
write.py | """
Write tables to text.
"""
import numpy as np
from collections import OrderedDict
### String and table formatting #################################
def pad_delimiters(string1, number, delimiter=',', slen=None, ):
"""
Pad string1 to the requested number of delimiters.
Parameters
... |
#
# def _build_header(self):
#
# list1 = []
# for key, val in self.header_info.items():
# fkey = key + '='
# try:
# fval = self.sfmt % val
# except TypeError:
# fval = self.nfmt % val
# lis... | s_tables = []
for table in self.columnlabels:
table = np.array(table)
if np.ndim(table) <= 1:
table = np.reshape(table, (1, -1))
s_table = format_narray(table, self.sfmt, self.delimiter)
s_tables.append(s_table)
slist = h... | identifier_body |
write.py | """
Write tables to text.
"""
import numpy as np
from collections import OrderedDict
### String and table formatting #################################
def pad_delimiters(string1, number, delimiter=',', slen=None, ):
"""
Pad string1 to the requested number of delimiters.
Parameters
... | (self):
"""Read columnn headers/labels"""
lines = self.lines
hlines = [lines[i] for i in self.labelrows]
header = np.genfromtxt(hlines, delimiter=',', dtype=str)
header = np.core.defchararray.strip(header)
add = np.core.defchararray.add
... | _read_labels | identifier_name |
final_cnn_mydata.py | from __future__ import print_function, division
import os
import time
import torch
import pandas as pd
#from skarr import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from torch.utils.tensorboard import Summar... | from torchsummary import summary
from pathlib import Path
from datetime import date
from datetime import datetime
import sys,re
from sklearn.metrics import confusion_matrix
# Ignore warnings
import warnings
warnings.filterwarnings("ignore")
writer = SummaryWriter()
class mydataset(Dataset):
def __init__(self,... | from torchvision import datasets
from torchvision import transforms | random_line_split |
final_cnn_mydata.py | from __future__ import print_function, division
import os
import time
import torch
import pandas as pd
#from skarr import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from torch.utils.tensorboard import Summar... | device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print('Device:', device)
# Hyperparameters
learning_rate = 0.001
num_epochs = 30
# GLOBAL VARIABLES
num_features = 64*64
#num_classes = 16
num_classes = 25
num_batch=32
model = VGG16(num_features=num_feat... | conditional_block | |
final_cnn_mydata.py | from __future__ import print_function, division
import os
import time
import torch
import pandas as pd
#from skarr import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from torch.utils.tensorboard import Summar... | (self,filepath,str_type="Train", batch_len=5):
self.filepath = filepath
self.str_type = str_type
self.batch_len = batch_len
def create_dataloader(self):
#transformed_ds = mydataset(hdf_filepath=str(filepath), transform = transforms.Compose([transforms.Grayscale(num_output_channels... | __init__ | identifier_name |
final_cnn_mydata.py | from __future__ import print_function, division
import os
import time
import torch
import pandas as pd
#from skarr import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from torch.utils.tensorboard import Summar... |
def compute_accuracy(model, data_loader):
correct_pred, num_examples, data_loss = 0, 0, 0
for i, (features, targets) in enumerate(data_loader):
features = features.to(device)
targets = targets.to(device)
logits, probs = model(features)
cost = F.cross_entropy(logits, targets)... | def __init__(self, num_features, num_classes):
super(VGG16, self).__init__()
self.block_1 = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=64, kernel_size=(3,3), stride=(1,1), padding=1),
nn.ReLU(),
nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3,3),stride... | identifier_body |
scripts.js | 'use strict';
// fixed svg show
//-----------------------------------------------------------------------------
svg4everybody();
// checking if element for page
//-----------------------------------------------------------------------------------
function isOnPage(selector) {
return ($(selector).length) ? $(select... |
$('.section-block').slick({
infinite: true,
dots: false,
arrows: true,
slidesToShow: 1,
slidesToScroll: 1,
prevArrow: '<button type="button" class="slick-prev slick-arrow"><svg class="icon icon-arrow mod-arrow"><use xlink:href="assets/img/symbol/sprite.svg#arrow"></use></svg></button>',
n... | {
var widgetWrap = $('<div class="widget_wrap"><ul class="widget_list"></ul></div>');
widgetWrap.prependTo("body");
for (var i = 0; i < pages.length; i++) {
if (pages[i][0] === '#') {
$('<li class="widget_item"><a class="widget_link" href="' + pages[i] +'">' + pages[i] + '</a></li>').appendTo('.widget_l... | identifier_body |
scripts.js | 'use strict';
// fixed svg show
//-----------------------------------------------------------------------------
svg4everybody();
// checking if element for page
//-----------------------------------------------------------------------------------
function isOnPage(selector) {
return ($(selector).length) ? $(select... | }
}
]
});
$('.trainer-block').slick({
infinite: true,
dots: true,
arrows: true,
slidesToShow: 4,
slidesToScroll: 4,
prevArrow: '<button type="button" class="slick-prev slick-arrow"><svg class="icon icon-arrow mod-arrow"><use xlink:href="assets/img/symbol/sprite.svg#arrow"></use></svg></button>... | slidesToShow: 1,
slidesToScroll: 1,
infinite: true,
dots: false,
arrows: false, | random_line_split |
scripts.js | 'use strict';
// fixed svg show
//-----------------------------------------------------------------------------
svg4everybody();
// checking if element for page
//-----------------------------------------------------------------------------------
function isOnPage(selector) {
return ($(selector).length) ? $(select... | () {
// The location of Uluru
var uluru = {lat: 49.421036, lng: 26.976296};
// The map, centered at Uluru
var map = new google.maps.Map(
document.getElementById('map'), {
zoom: 15,
center: uluru,
disableDefaultUI: true,
zoomControl: false
});
// The marker, positi... | initMap | identifier_name |
scripts.js | 'use strict';
// fixed svg show
//-----------------------------------------------------------------------------
svg4everybody();
// checking if element for page
//-----------------------------------------------------------------------------------
function isOnPage(selector) {
return ($(selector).length) ? $(select... |
});
},
setError: function ($el, message) {
$el = this.defineElement($el);
if ($el) this.domWorker.error($el, message);
},
defineElement: function ($el) {
return $el;
},
domWorker: {
error: function ($el, message) {
$el.closest('.el-text-fel').addClass('erro... | {
var rules = validator.valitatorRules[name];
$form.validate({
rules: rules,
errorElement: 'b',
errorClass: 'error',
focusInvalid: true,
focusCleanup: false,
errorPlacement: function (error, element) {
... | conditional_block |
objects.rs | use ggez::input::keyboard;
use ggez::{graphics, Context, GameResult};
use graphics::{Mesh, MeshBuilder, DrawParam};
use crate::game;
use game::movement::Movement;
use game::Draw;
//#region Ship
/// The Ship.\
/// Width and Height is sort of switched here.\
/// This is because the mesh is made to face the right but th... |
/// Handle keyboard inputs and update the location of the Ship accordingly
pub fn update_movement(&mut self, ctx: &Context) {
/* The current implementation does not allow external forces
This could be easily achieved by having this call take additional params which set
some force befo... | {
let (ctx_width, ctx_height) = graphics::drawable_size(ctx);
let ship_width = 18.0;
let ship_height = 20.0;
Ship {
width: ship_width,
height: ship_height,
x: (ctx_width - ship_width)/ 2.0,
y: (ctx_height- ship_height) / 2.0,
... | identifier_body |
objects.rs | use ggez::input::keyboard;
use ggez::{graphics, Context, GameResult};
use graphics::{Mesh, MeshBuilder, DrawParam};
use crate::game;
use game::movement::Movement;
use game::Draw;
//#region Ship
/// The Ship.\
/// Width and Height is sort of switched here.\
/// This is because the mesh is made to face the right but th... | (&mut self) {
self.x += self.speed_x;
self.y += self.speed_y;
self.rotation += self.rotation_speed;
}
/// Returns a boolean that states if someone is within the hitbox of this asteroid
pub fn in_hitbox(&self, (x, y): (f32, f32)) -> bool {
let size;
match &... | update | identifier_name |
objects.rs | use ggez::input::keyboard;
use ggez::{graphics, Context, GameResult};
use graphics::{Mesh, MeshBuilder, DrawParam};
use crate::game;
use game::movement::Movement;
use game::Draw;
//#region Ship
/// The Ship.\
/// Width and Height is sort of switched here.\
/// This is because the mesh is made to face the right but th... | self.mov.force_y,
self.mov.acceleration_x,
self.mov.acceleration_y,
self.mov.speed_x,
self.mov.speed_y,
self.rotation_speed
)
}
}
impl game::Draw for Ship {
fn mesh(&self, ctx: &mut Context) -> GameResult<Mesh> {
let mut m... | Rotation speed: {}\n",
self.mov.force_x, | random_line_split |
made.py | # Import the PyQt and QGIS libraries
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
# Initialize Qt resources from file resources.py
import resources
import locale
locale.setlocale(locale.LC_ALL, '')
# Import the code for the dialog
from dalacalcdialog import DalaCalcDialog
class DalaCal... | (self):
# membaca layer yg akan digunakan sebagai exposure
try:
comboindex = self.dlg.ui.BahayaComboBox.currentIndex()
layerBahaya = self.layermap[self.layerids[comboindex]]
except: #Crashes without valid shapefiles
return
def bantuan(self):
# membaca m... | bacaBahaya | identifier_name |
made.py | # Import the PyQt and QGIS libraries
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
# Initialize Qt resources from file resources.py
import resources
import locale
locale.setlocale(locale.LC_ALL, '')
# Import the code for the dialog
from dalacalcdialog import DalaCalcDialog
class DalaCal... | # menampilkan hasil
stringHasil = ("Hasil analisis kerugian dan kerusakan: \n"
"\n- Total jumlah fasilitas terdampak = "+str(len(selection))+
"\n- Total luas semua fasilitas terdampak "
"\n = "+str(luasAkhirTerdampak)+ " m2"... | persentase = 90.0*(0.01)
hasilKali = luasAkhirTerdampak * nilaiKerugian * persentase | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.