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
server.go
(as.authenticators, gha) as.gha = gha } if c.OIDCAuth != nil { oidc, err := authn.NewOIDCAuth(c.OIDCAuth) if err != nil { return nil, err } as.authenticators = append(as.authenticators, oidc) as.oidc = oidc } if c.GitlabAuth != nil { glab, err := authn.NewGitlabAuth(c.GitlabAuth) if err != nil { ...
Authorize
identifier_name
main.rs
; use colored::*; use chrono::prelude::*; enum VagueTime { Tomorrow, Today, Evening, NextWeek, Day(u8), } impl FromStr for VagueTime { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { use VagueTime::*; match s { "tomorrow" => Ok(Tomorrow), ...
"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
VagueTime::*; match s { "tomorrow" => Ok(Tomorrow), "today" => Ok(Today), "tonight" => Ok(Today), "evening" => Ok(Evening), "week" => Ok(NextWeek), "next week" => Ok(NextWeek), d => Ok(match u8::from_str(d) { Ok...
do_add
identifier_name
metrics.go
Level: metrics.ALPHA, Buckets: metrics.ExponentialBuckets(60, 2, 10), }, []string{"transformation_type"}, ) // These metrics are made public to be used by unit tests. KMSOperationsLatencyMetric = metrics.NewHistogramVec( &metrics.HistogramOpts{ Namespace: namespace, Subsystem: subsys...
{ return codes.OK.String() }
conditional_block
metrics.go
string keyIDHash string } /* * By default, all the following metrics are defined as falling under * ALPHA stability level https://github.com/kubernetes/enhancements/blob/master/keps/sig-instrumentation/1209-metrics-stability/kubernetes-control-plane-metrics-stability.md#stability-classes) * * Promoting ...
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
ability/kubernetes-control-plane-metrics-stability.md#stability-classes) * * Promoting the stability level of the metric is a responsibility of the component owner, since it * involves explicitly acknowledging support for the metric across multiple releases, in accordance with * the metric stability policy. */ var...
{ InvalidKeyIDFromStatusTotal.WithLabelValues(providerName, errCode).Inc() }
identifier_body
metrics.go
-metrics-stability.md#stability-classes) * * Promoting the stability level of the metric is a responsibility of the component owner, since it * involves explicitly acknowledging support for the metric across multiple releases, in accordance with * the metric stability policy. */ var ( lockLastFromStorage sync.M...
RecordArrival
identifier_name
prepare_data_for_nlp.py
target year needed" assert len(input_years) > 0, "at least 1 input year needed" VOLUME_PATH = Path("/home/ykuv/pummel_data/volume/") df_basics = pd.concat( [pd.read_csv(VOLUME_PATH / Path(f"basics_norm_{year}.csv")) for year in all_years] ) df_basics.sort_values(["krypht", "ika"], ascending=False, inplace=True...
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
target year needed" assert len(input_years) > 0, "at least 1 input year needed" VOLUME_PATH = Path("/home/ykuv/pummel_data/volume/") df_basics = pd.concat( [pd.read_csv(VOLUME_PATH / Path(f"basics_norm_{year}.csv")) for year in all_years] ) df_basics.sort_values(["krypht", "ika"], ascending=False, inplace=True...
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
1 target year needed" assert len(input_years) > 0, "at least 1 input year needed" VOLUME_PATH = Path("/home/ykuv/pummel_data/volume/") df_basics = pd.concat( [pd.read_csv(VOLUME_PATH / Path(f"basics_norm_{year}.csv")) for year in all_years] ) df_basics.sort_values(["krypht", "ika"], ascending=False, inplace=Tru...
(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
target year needed" assert len(input_years) > 0, "at least 1 input year needed" VOLUME_PATH = Path("/home/ykuv/pummel_data/volume/") df_basics = pd.concat( [pd.read_csv(VOLUME_PATH / Path(f"basics_norm_{year}.csv")) for year in all_years] ) df_basics.sort_values(["krypht", "ika"], ascending=False, inplace=True...
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
"` Config json.RawMessage `json:"config"` } type xdsServer struct { ServerURI string `json:"server_uri"` ChannelCreds []channelCreds `json:"channel_creds"` } // NewConfig returns a new instance of Config initialized by reading the // bootstrap file found at ${GRPC_XDS_BOOTSTRAP}. // // The format of the...
{ 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
olang.org/grpc/xds/internal/env" "google.golang.org/grpc/xds/internal/version" ) const ( // The "server_features" field in the bootstrap file contains a list of // features supported by the server. A value of "xds_v3" indicates that the // server supports the v3 version of the xDS transport protocol. serverFeatur...
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
API version of xDS transport protocol to use. // This describes the xDS gRPC endpoint and version of // DiscoveryRequest/Response used on the wire. TransportAPI version.TransportAPI // NodeProto contains the Node proto to be used in xDS requests. The actual // type depends on the transport protocol version used. ...
updateNodeProto
identifier_name
bootstrap.go
* 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
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
.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 {}'.format(where_str) return [row for row in ...
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
.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 {}'.format(where_str) return [row for row in ...
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
.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 {}'.format(where_str) return [row for row in ...
(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
.(data.Plugin) if !ok { return } mempoolPlugin, ok := plugin.(data.RPCMempoolPlugin) if !ok { return } rawTxPlugin, ok := plugin.(data.RPCRawTransactionsPlugin) if !ok { return } listTxPlugin, ok := plugin.(data.ListTransactionsPlugin) if !ok { r...
// 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
e20b91850fba66d22", // "d2fad87261dcb381883e51953bbf7800ad02186180423a3138547296c165f0cd", // "760f9f3385a0ada632c750f4603867504bdcda7be245b0b99de7bd065c27d5a3", // "754421493b42ae1c2940b307d489b59c7bbdcb88d3535464b65519a997ca21a2", // "e1ae5692f3b1189f4e38b9e0c8544d300fe83a4f1d40f524efec50e369b37901", // "e0df0fd...
debugBTC
identifier_name
main.go
68ddd1e20b91850fba66d22", // "d2fad87261dcb381883e51953bbf7800ad02186180423a3138547296c165f0cd", // "760f9f3385a0ada632c750f4603867504bdcda7be245b0b99de7bd065c27d5a3", // "754421493b42ae1c2940b307d489b59c7bbdcb88d3535464b65519a997ca21a2", // "e1ae5692f3b1189f4e38b9e0c8544d300fe83a4f1d40f524efec50e369b37901", // "e...
{ fmt.Println("error", err.Error()) }
conditional_block
main.go
// } // defer f.Close() // error handling omitted for example // runtime.GC() // get up-to-date statistics // if err := pprof.WriteHeapProfile(f); err != nil { // log.Fatal("could not write memory profile: ", err) // } //}() shutdown := make(chan os.Signal, 1) go func() { c := make(chan os.Signal, 1) sig...
{ 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
', help='Show debug information', required=False, action='store_true') parser.add_argument('--section', type=str, help='Select a Edgerc section other than the Default', required=False) parser.add_argument('--account-key', type=str, help='Account ID to Query for multi account man...
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
with the value '{}' on the configuration '{}'.".format(dict(obj["options"])["hostname"],configName)) origins.append (dict(obj["options"])["hostname"]) for k, v in obj.items(): if isinstance(v,dict) or isinstance(v,list): if "values" not in k.lower(): if isinstanc...
main
identifier_name
ssl-audit.py
['verbose']: logger.debug("Printing JSON.") logger.debug("[end]") if len(item_list) == 0: logger.error("No output generated to print!") return None if item_list[0] != {}: items['items'] = item_list if args['audit'] == "list": if len(errors) != 0: i...
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
', help='Show debug information', required=False, action='store_true') parser.add_argument('--section', type=str, help='Select a Edgerc section other than the Default', required=False) parser.add_argument('--account-key', type=str, help='Account ID to Query for multi account man...
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
# 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
84) # DRQN input B*C*feature (32*seq_len 4 84 84) # x = F.relu(self.conv1(x)) # x = F.relu(self.conv2(x)) # x = F.relu(self.conv3(x)) # x = F.relu(self.fc4(x.reshape(x.size(0), -1))) # hidden = self.init_hidden(batch_size) if hidden is None else hidden # be...
data = self.buffer[begin:finish] state, action, reward, next_state, done = zip(*data) states.append(np.concatenate([self.observe(state_i) for state_i in state])) actions.append(action) rewards.append(reward) next_states.append(np.concatenate...
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
(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
) # shape: [batch_size * seq_len] rewards = tf.convert_to_tensor(rewards) # shape: [batch_size * seq_len] is_done = tf.convert_to_tensor(is_done) # shape: [batch_size * seq_len] actions = tf.reshape(actions, [-1]) rewards = tf.reshape(rewards, [-1]) is_done = tf.reshape...
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
/// # Examples /// /// ``` /// use wasmtime::{Linker, Store}; /// /// let store = Store::default(); /// let mut linker = Linker::new(&store); /// // ... /// ``` pub fn new(store: &Store) -> Linker { Linker { store: store.clone(), map: HashMap::new(), ...
/// ``` /// # 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
); /// // ... /// ``` pub fn new(store: &Store) -> Linker { Linker { store: store.clone(), map: HashMap::new(), string2idx: HashMap::new(), strings: Vec::new(), allow_shadowing: false, } } /// Configures whether this [`Link...
import_key
identifier_name
linker.rs
/// # Examples /// /// ``` /// use wasmtime::{Linker, Store}; /// /// let store = Store::default(); /// let mut linker = Linker::new(&store); /// // ... /// ``` pub fn new(store: &Store) -> Linker { Linker { store: store.clone(), map: HashMap::new(), ...
/// 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
self.path_x = np.arange(192) def calc_va(self, sm, v_ego ): 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 p...
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
self.path_x = np.arange(192) def calc_va(self, sm, v_ego ): 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 p...
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
self.path_x = np.arange(192) def calc_va(self, sm, v_ego ):
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
self.path_x = np.arange(192) def calc_va(self, sm, v_ego ): 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 p...
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
} func isManifest(req *http.Request) bool { elems := strings.Split(req.URL.Path, "/") elems = elems[1:] if len(elems) < 4 { return false } return elems[len(elems)-2] == "manifests" } func isTags(req *http.Request) bool { elems := strings.Split(req.URL.Path, "/") elems = elems[1:] if len(elems) < 4 { retur...
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
lems := 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 := strings.Split(req.URL.Path, "/") elems = elems[1:]...
handleReferrers
identifier_name
manifest.go
} func isManifest(req *http.Request) bool { elems := strings.Split(req.URL.Path, "/") elems = elems[1:] if len(elems) < 4 { return false } return elems[len(elems)-2] == "manifests" } func isTags(req *http.Request) bool
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
6(bytes.NewReader(m.blob)) resp.Header().Set("Docker-Content-Digest", h.String()) resp.Header().Set("Content-Type", m.contentType) resp.Header().Set("Content-Length", fmt.Sprint(len(m.blob))) resp.WriteHeader(http.StatusOK) io.Copy(resp, bytes.NewReader(m.blob)) return nil case http.MethodHead: m.lock.L...
continue }
random_line_split
api-compose-object.go
zLegalHoldHeader, opts.LegalHold.String()) } if opts.Mode != RetentionMode("") && !opts.RetainUntilDate.IsZero() { header.Set(amzLockMode, opts.Mode.String()) header.Set(amzLockRetainUntil, opts.RetainUntilDate.Format(time.RFC3339)) } if opts.Encryption != nil { opts.Encryption.Marshal(header) } if opts....
} 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
LegalHoldHeader, opts.LegalHold.String()) } if opts.Mode != RetentionMode("") && !opts.RetainUntilDate.IsZero() { header.Set(amzLockMode, opts.Mode.String()) header.Set(amzLockRetainUntil, opts.RetainUntilDate.Format(time.RFC3339)) } if opts.Encryption != nil { opts.Encryption.Marshal(header) } if opts.R...
} } // 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
{ header.Set(amzLockMode, opts.Mode.String()) header.Set(amzLockRetainUntil, opts.RetainUntilDate.Format(time.RFC3339)) } if opts.Encryption != nil { opts.Encryption.Marshal(header) } if opts.ReplaceMetadata { header.Set("x-amz-metadata-directive", replaceDirective) for k, v := range filterCustomMeta(o...
{ // 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
(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
aintools.com/iris/search/?q='; function _setupRegexBlocklists(options) { if (options.domainBlocklistRegex !== previousDomainRegexAsString && options.domainBlocklistRegex.length === 0) { Logger.debug('Removing Domain Blocklist Regex Filtering'); previousDomainRegexAsString = ''; domainBlocklistRegex = nul...
// 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(),
{ return { errors: [_createJsonErrorObject(msg, pointer, httpCode, code, title, meta)] }; }
identifier_body
integration.js
aintools.com/iris/search/?q='; function _setupRegexBlocklists(options) { if (options.domainBlocklistRegex !== previousDomainRegexAsString && options.domainBlocklistRegex.length === 0) { Logger.debug('Removing Domain Blocklist Regex Filtering'); previousDomainRegexAsString = ''; domainBlocklistRegex = nul...
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
.domaintools.com/iris/search/?q='; function _setupRegexBlocklists(options) { if (options.domainBlocklistRegex !== previousDomainRegexAsString && options.domainBlocklistRegex.length === 0) { Logger.debug('Removing Domain Blocklist Regex Filtering'); previousDomainRegexAsString = ''; domainBlocklistRegex =...
(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
.domaintools.com/iris/search/?q='; function _setupRegexBlocklists(options) { if (options.domainBlocklistRegex !== previousDomainRegexAsString && options.domainBlocklistRegex.length === 0) { Logger.debug('Removing Domain Blocklist Regex Filtering'); previousDomainRegexAsString = ''; domainBlocklistRegex =...
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
(df)) #%% def get_sentiments_from_polarity(polarity=0,threshold=0):
#%% 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
_polarity(sentiment.polarity,threshold) print(s) sentiment_result.append(s) print(sentiment.polarity) sentiment_polarity.append(sentiment.polarity) i+=1 deno=sample['HelpfulnessDenominator'] nume=sample['HelpfulnessNumerator'] sample.index=cleaned_review.index cl...
m=i
conditional_block
amazon_ff_review.py
(type(df)) #%% def get_sentiments_from_polarity(polarity=0,threshold=0): if np.abs(polarity) < threshold : return "Neutral" elif np.sign(polarity)>0: return "Positive" else: return "Negative" #%% def get_reviews(): con=sqlite3.connect('database.sqlite') df=pd.read_sql('Sele...
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
(df)) #%% def get_sentiments_from_polarity(polarity=0,threshold=0): if np.abs(polarity) < threshold : return "Neutral" elif np.sign(polarity)>0: return "Positive" else: return "Negative" #%% def get_reviews(): con=sqlite3.connect('database.sqlite') df=pd.read_sql('Select * ...
(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
//! to write business logic. //! //! Said that, Acteur is provably **not** the tool you want if: //! //! - You want to have a full ACID compliant system //! - You want to fully follow the Actor model //! - You need to scale to A LOT of traffic. In which case you will need more than one server. (I'm planning to //! ...
//! //! ## 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
house master': 'house_master'}) df2.to_excel(str(data_folder / household_family_structure_xlsx.file_name), index=False) return df2 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 ...
(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
df.to_excel(writer, sheet_name=voivodship_cities_household_family_structure_xlsx.sheet_name, index=False) df2 = pd.melt(df, id_vars=['family_type', 'relationship', 'house master'], value_vars=[1, 2, 3, 4, 5, 6, 7], var_name='household_headcount', va...
""" 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
={'house master': 'house_master'}) df2.to_excel(str(data_folder / household_family_structure_xlsx.file_name), index=False) return df2 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...
* 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
house master': 'house_master'}) df2.to_excel(str(data_folder / household_family_structure_xlsx.file_name), index=False) return df2 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 ...
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
// register window class if !Self::is_window_class_registered() { Self::register_window_class()?; } let mut wnd = Pin::new(Box::new(Self::default())); wnd.high_limit = high_limit; wnd.cancel_sender = Some(cancel_sender); let instance = unsafe { libloaderapi::...
/// 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
// register window class if !Self::is_window_class_registered() { Self::register_window_class()?; } let mut wnd = Pin::new(Box::new(Self::default())); wnd.high_limit = high_limit; wnd.cancel_sender = Some(cancel_sender); let instance = unsafe { libloaderapi::...
() -> 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
// register window class if !Self::is_window_class_registered() { Self::register_window_class()?; } let mut wnd = Pin::new(Box::new(Self::default())); wnd.high_limit = high_limit; wnd.cancel_sender = Some(cancel_sender); let instance = unsafe { libloaderapi::...
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
= &["null", "boolean", "number", "string"]; impl Schemas { /// Generate a TypeScript module for each schema pub async fn typescript(&self) -> Result<()> { eprintln!("Generating TypeScript types"); // The top level destination let dest = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("...
(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
= &["null", "boolean", "number", "string"]; impl Schemas { /// Generate a TypeScript module for each schema pub async fn typescript(&self) -> Result<()> { eprintln!("Generating TypeScript types"); // The top level destination let dest = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("...
/// 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
"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
Reply) error { sm.log("Join RPC: gid=%d, servers=%s", args.GID, args.Servers) op := Op{Operation: Join, Args: *args} sm.resolveOp(op) return nil } func (sm *ShardMaster) Leave(args *LeaveArgs, reply *LeaveReply) error { sm.log("Leave RPC: gid=%d", args.GID) op := Op{Operation: Leave, Args: *args} sm.reso...
random_line_split
server.go
= "ErrGIDAlreadyJoined" ErrGIDAlreadyLeft = "ErrGIDAlreadyLeft" ) type Err string const ( Join = "Join" Leave = "Leave" Move = "Move" Query = "Query" Noop = "Noop" ) type Operation string type Op struct { Operation Operation Args interface{} } func RandMTime() time.Duration { return ti...
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
{ return &Config{}, ErrNoop }
conditional_block
server.go
(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
= "ErrGIDAlreadyJoined" ErrGIDAlreadyLeft = "ErrGIDAlreadyLeft" ) type Err string const ( Join = "Join" Leave = "Leave" Move = "Move" Query = "Query" Noop = "Noop" ) type Operation string type Op struct { Operation Operation Args interface{} } func RandMTime() time.Duration
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
the loading animation $("#loader").fadeOut("slow", function(){ // will fade out the whole DIV that covers the website. $("#preloader").delay(300).fadeOut("slow"); }); }) /*---------------------------------------------------- */ /* FitVids ---------...
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
the loading animation $("#loader").fadeOut("slow", function(){ // will fade out the whole DIV that covers the website. $("#preloader").delay(300).fadeOut("slow"); }); }) /*---------------------------------------------------- */ /* FitVids ---------...
// 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
/// 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
data is skipped. pub fn visit(self, visit: &mut dyn Visit<'a>) { let words = unsafe { slice::from_raw_parts(self.bytes.as_ptr() as *const u16, self.bytes.len() / 2) }; for version_info_r in Parser::new_bytes(words) { if let Ok(version_info) = version_info_r { const VS_FIXEDFILEINFO_SIZEOF: usize = mem::si...
(&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
105, 118, 97, 116, 101, 66, 117, 105, 108, 100]; // static ProductName: [u16; 11] = [80u16, 114, 111, 100, 117, 99, 116, 78, 97, 109, 101]; // static ProductVersion: [u16; 14] = [80u16, 114, 111, 100, 117, 99, 116, 86, 101, 114, 115, 105, 111, 110]; // static SpecialBuild: [u16; 12] = [83u16, 112, 101, 99, 105, 97,...
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
} 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
# 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
n_paa_segments''") self.n_paa_segments = n_paa_segments self.width = None else:
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
n_paa_segments''") self.n_paa_segments = n_paa_segments self.width = None else: self.n_paa_segments = None self.width = width self.number_of_symbols = k self.return_list = return_list self.mu, self.std = 0, 1 def tra...
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
start = end - 1 # pieces = np.vstack([pieces, np.array([end-start-1, lastinc, lasterr])]) pieces.append([end-start-1, lastinc, lasterr]) return pieces class fABBA: def __init__ (self, tol=0.1, alpha=0.5, sorting='2-norm', scl=1, verbose=1, max_len=np.inf): """ ...
antize(s
identifier_name
texture.rs
::Kind::D2(texture_data.width(), texture_data.height(), 1, 1), 1, Format::Rgba8Srgb, gfx_hal::image::Tiling::Optimal, Usage::TRANSFER_DST | Usage::SAMPLED, gfx_hal::image::ViewCapabilities::empty(), )?; // Copy texture data to the given buffer...
// 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
`s and `ImageView`s. #[derive(Debug, Deserialize)] pub struct Texture { pub index: Index, /// The size in texels. pub size: Size, pub file: Filename, /// When this `Texture` is bound to buffer memory, this stores the range of bytes within /// the buffer that this `Texture` occupies. #[serd...
( &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
`s and `ImageView`s. #[derive(Debug, Deserialize)] pub struct Texture { pub index: Index, /// The size in texels. pub size: Size, pub file: Filename, /// When this `Texture` is bound to buffer memory, this stores the range of bytes within /// the buffer that this `Texture` occupies. #[serd...
PipelineStage::TOP_OF_PIPE, PipelineStage::TRANSFER, ); // Figure out the size of the texture data. let pixel_size = mem::size_of::<Rgba<u8>>() as u32; let row_size = pixel_size * self.size.x as u32; let row_alignment_mask = limits.min_buffer_copy_pitch_a...
{ 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
columns defined by delimiter. for sl in str_lists: max_clen = max(len(line) for line in sl) max_col_lengths.append(max_clen) max_columns = max(line.count(delimiter) for line in sl) + 1 max_col_nums.append(max_columns) max_row_length = max(len(sl) for ...
returns: ------ array of shape (a, b)
random_line_split
write.py
except TypeError: outlist.append(sfmt % h) string1 = delimiter.join(outlist) + '\n' return string1 def wrap_list(list1, fmt = '%16s', delimiter = ",", maxcols = 8): """ format a list and wrap by max number of columns """ len1 = len(list1) string = "" fo...
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
s_tables = [] for table in arrays: table = np.asarray(table) if np.ndim(table) <= 1: table = np.reshape(table, (-1, 1)) try: s_table = format_narray(table, nfmt, delimiter) except TypeError: s_table = format_narray(table, sfmt, delimiter) ...
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
# max_clen = max_col_lengths[i] # # if rows < maxrows: # newline = max_clen * ' ' # padding = [newline] * (maxrows - rows) # slist.extend(padding) # # # # # # # return # def hstack_str_list(str_lists, delimiter...
_read_labels
identifier_name
final_cnn_mydata.py
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
_channels=64, kernel_size=(3,3),stride=(1,1),padding=1), # nn.ReLU(), # nn.MaxPool2d(kernel_size=(2,2), stride=(2,2)) # ) #self.block_3 = nn.Sequential(nn.Conv2d(in_channels=128, out_channels=256, kernel_size=(3,3), stride=(1,1), padding=1), # nn.ReL...
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
(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
aloader class VGG16(torch.nn.Module):
#self.block_3 = nn.Sequential(nn.Conv2d(in_channels=128, out_channels=256, kernel_size=(3,3), stride=(1,1), padding=1), # nn.ReLU(), # nn.Conv2d(in_channels=256, out_channels=256, kernel_size=(3,3),stride=(1,1),padding=1), # nn.ReLU(), # nn.MaxPool2d...
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
$('.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
50% 50%;cursor:pointer}.widget_wrap:hover{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.widget_item{padding:0 0 10px}.widget_link{color:#fff;text-decoration:none;font-size:15px;}.widget_link:hover{text-decoration:underline} </style>'); widgetStilization.prependTo(".widget_wr...
} } ] }); $('.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
50% 50%;cursor:pointer}.widget_wrap:hover{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.widget_item{padding:0 0 10px}.widget_link{color:#fff;text-decoration:none;font-size:15px;}.widget_link:hover{text-decoration:underline} </style>'); widgetStilization.prependTo(".widget_wra...
() { // 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
50% 50%;cursor:pointer}.widget_wrap:hover{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.widget_item{padding:0 0 10px}.widget_link{color:#fff;text-decoration:none;font-size:15px;}.widget_link:hover{text-decoration:underline} </style>'); widgetStilization.prependTo(".widget_wra...
$el.closest('.el-text-fel').removeClass(validClass).addClass(errorClass); } } }, unhighlight: function (element, errorClass, validClass) { var $el = validator.defineElement($(element)); if ($el){ $el.clos...
{ 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
} /// 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 forc...
{ 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
triangle This would make writing hit detection easier, and would make the offset trivial. But I did not immediately implement it like this and I don't want to redo the rocket fire mesh right now, so I am leaving this comment instead [-self.height/2.0, -self.width/2....
update
identifier_name
objects.rs
= 0.0; self.moving = false; if keyboard::is_key_pressed(ctx, keyboard::KeyCode::A) { self.rotation -= self.rotation_speed; } if keyboard::is_key_pressed(ctx, keyboard::KeyCode::D) { self.rotation += self.rotation_speed; } if keyboard::...
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
.qgisUserDbFilePath()).path() + "/python/plugins/dalacalc" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale").toString()[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/dalacalc_" + locale + ".qm" i...
(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
.qgisUserDbFilePath()).path() + "/python/plugins/dalacalc" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale").toString()[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/dalacalc_" + locale + ".qm" i...
# 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
made.py
(self.action) self.iface.addPluginToMenu(u"&Hitungan Kerusakan Kerugian", self.action) def unload(self): # Remove the plugin menu item and icon self.iface.removePluginMenu(u"&Hitungan Kerusakan Kerugian", self.action) self.iface.removeToolBarIcon(self.action) # run method that ...
scalefactor = (mc.extent().height() / mc.scale())
conditional_block