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 |
|---|---|---|---|---|
ItemView.js | () {
// Private variables
// These are jQuery objects corresponding to elements
let $mapImage;
let $carpet;
let $backArrow;
let $forwardArrow;
let $avatar;
let $arrowsAndItemOrderNumbers;
let $itemOrderNumbers;
let previousAngle = 0;
let viewModel;
let itemsDetails;
... | ItemView | identifier_name | |
ItemView.js |
// Private functions
const cacheJQueryObjects = () => {
$mapImage = $("#MapImage");
$carpet = $('#Carpet');
$arrowsAndItemOrderNumbers = $('#ArrowsAndItemOrderNumbers');
$backArrow = $('#ArrowBack');
$forwardArrow = $('#ArrowForward');
$itemOrderNumbers = $('#I... | {
// Private variables
// These are jQuery objects corresponding to elements
let $mapImage;
let $carpet;
let $backArrow;
let $forwardArrow;
let $avatar;
let $arrowsAndItemOrderNumbers;
let $itemOrderNumbers;
let previousAngle = 0;
let viewModel;
let itemsDetails;
... | identifier_body | |
string_pool.rs | () -> Result<Self, ()> {
let bump = Bump::try_with_capacity(INIT_BLOCK_SIZE).map_err(|_| ())?;
let boxed_bump = Box::try_new(bump).map_err(|_| ())?;
Ok(StringPool(Some(InnerStringPool::new(
boxed_bump,
|bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))),
)... | try_new | identifier_name | |
string_pool.rs | = Box::try_new(bump).map_err(|_| ())?;
Ok(StringPool(Some(InnerStringPool::new(
boxed_bump,
|bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))),
))))
}
/// # Safety
///
/// The inner type is only ever None in middle of the clear()
/// method. Therefo... |
/// Resets the current Bump and deallocates its contents.
/// The `inner` method must never be called here as it assumes
/// self.0 is never `None`
pub(crate) fn clear(&mut self) {
let mut inner_pool = self.0.take();
let mut bump = inner_pool.unwrap().into_head();
bump.reset(... | {
self.inner().rent(|vec| {
let mut vec = vec.borrow_mut();
while *s != 0 {
if !vec.append_char(*s) {
return false;
}
s = s.offset(1)
}
true
})
} | identifier_body |
string_pool.rs | Vec(BumpVec::new_in(&pool.bump));
let sl = pool.current_bump_vec.replace(vec).0.into_bump_slice_mut();
Cell::from_mut(sl).as_slice_of_cells()
})
}
/// Resets the current bump vec to the beginning
pub(crate) fn clear_current(&self) {
self.inner().rent(|v| v.borrow_mut... | let new_string = unsafe { | random_line_split | |
string_pool.rs | = Box::try_new(bump).map_err(|_| ())?;
Ok(StringPool(Some(InnerStringPool::new(
boxed_bump,
|bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))),
))))
}
/// # Safety
///
/// The inner type is only ever None in middle of the clear()
/// method. Therefo... |
s = s.offset(1)
}
true
})
}
/// Resets the current Bump and deallocates its contents.
/// The `inner` method must never be called here as it assumes
/// self.0 is never `None`
pub(crate) fn clear(&mut self) {
let mut inner_pool = self.0.take(... | {
return false;
} | conditional_block |
index.js | copyright ownership. The ASF licenses this file
* to you 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 a... |
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
$(document).ready(function (e) {
app.load_update_data();
});
do... | random_line_split | |
modulizer.py | (path):
sourceList = []
nbFields = 6
fd = open(path,'rb')
# skip first line and detect separator
firstLine = fd.readline()
sep = ','
if (len(firstLine.split(sep)) != nbFields):
sep = ';'
if (len(firstLine.split(sep)) != nbFields):
sep = '\t'
if (len(firstLine.split(sep)) != nbFields):
prin... | parseFullManifest | identifier_name | |
modulizer.py | in sourceList:
if op.basename(item["path"]) == op.basename(srcf) and \
moduleName == item["module"]:
appDir = op.basename(op.dirname(item["path"]))
cmakeListPath = op.join(HeadOfOTBTree,op.join("Testing/Applications"),op.join(appDir,"CMakeLists.txt"))
break
... | # apply patches in OTB_Modular
curdir = op.abspath(op.dirname(__file__))
command = "cd " + op.join(OutputDir,"OTB_Modular") + " && patch -p1 < " + curdir + "/patches/otbmodular.patch"
print "Executing " + command | random_line_split | |
modulizer.py |
if len(sys.argv) < 4:
print("USAGE: {0} monolithic_OTB_PATH OUTPUT_DIR Manifest_Path [module_dep [test_dep [mod_description]]]".format(sys.argv[0]))
print(" monolithic_OTB_PATH : checkout of OTB repository (will not be modified)")
print(" OUTPUT_DIR : output directory where OTB_Modular an... | output = {}
sep = '|'
nbFields = 2
fd = open(path,'rb')
for line in fd:
if (line.strip()).startswith("#"):
continue
words = line.split(sep)
if len(words) != nbFields:
continue
moduleName = words[0].strip(" \"\t\n\r")
description = words[1].strip(" \"\t\n\r")
output[moduleName... | identifier_body | |
modulizer.py |
modDescriptionPath = ""
if len(sys.argv) >= 7:
modDescriptionPath = sys.argv[6]
enableMigration = False
if len(sys.argv) >= 8:
migrationPass = sys.argv[7]
if migrationPass == "redbutton":
enableMigration = True
# copy the whole OTB tree over to a temporary dir
HeadOfTempTree = op.join(OutputDir,"OTB_remai... | testDependPath = sys.argv[5] | conditional_block | |
scraper-twitter-user.py |
user_isFamous = False
user_location = ""
user_joinDate = ""
user_following = 0
user_followers = 0 | mention_tweet_counter = 0
url_tweet_counter = 0
retweet_counter = 0
tweet_id = 0
tweet_lang = ""
tweet_raw_text = ""
tweet_datetime = None
tweet_mentions = None
tweet_hashtags = None
tweet_owner_id = 0
tweet_retweeter = False
tweet_timestamp = 0
tweet_owner_name = ""... |
tweet_counter = 0
comments_counter = 0 | random_line_split |
scraper-twitter-user.py | (user):
_XML_TWEETS = ""
_XML_ = ""
_USER_ = user
logged_in = True
has_more_items = True
min_position = ""
items_html = ""
document = None
i = 0
user_id = 0
user_bio = ""
user_url = ""
user_name = ""
user_favs = 0
user_tweets = 0
user_isFamous = False
... | scrapes | identifier_name | |
scraper-twitter-user.py |
user_isFamous = False
user_location = ""
user_joinDate = ""
user_following = 0
user_followers = 0
tweet_counter = 0
comments_counter = 0
mention_tweet_counter = 0
url_tweet_counter = 0
retweet_counter = 0
tweet_id = 0
tweet_lang = ""
tweet_raw_text = ""
tweet_d... |
user_profilePic = document.select(".ProfileAvatar").andThen("img").getAttribute("src")[0]
print("\n> downloading profile picture...")
ss.download(user_profilePic, _BASE_PHOTOS)
print("\n\nAbout to start downloading user's timeline:")
timeline_url = "https://twitter.com/i/profiles/show/%s/timelin... | user_favs = "" | conditional_block |
scraper-twitter-user.py |
def sumc(collection):
total = 0
if type(collection) == list or type(collection) == set or type(collection) == tuple:
for e in collection:
total += e
else:
for e in collection:
total += collection[e]
return float(total)
parser = argparse.ArgumentParser(
des... | if isinstance(strn, list) or type(strn) == int:
strn = str(strn)
return (u"{:<%i}" % (length)).format(strn[:length]) | identifier_body | |
lib.rs | _display;
/// **(internal)** Implements experimental `.bnet` parser for `BooleanNetwork`.
mod _impl_boolean_network_from_bnet;
/// **(internal)** Implements an experimental `.bnet` writer for `BooleanNetwork`.
mod _impl_boolean_network_to_bnet;
/// **(internal)** All methods implemented by the `ExtendedBoolean` object.... | {
name: String,
arity: u32,
}
/// Describes an interaction between two `Variables` in a `RegulatoryGraph`
/// (or a `BooleanNetwork`).
///
/// Every regulation can be *monotonous*, and can be set as *observable*:
///
/// - Monotonicity is either *positive* or *negative* and signifies that the influence of th... | Parameter | identifier_name |
lib.rs | u32,
}
/// Describes an interaction between two `Variables` in a `RegulatoryGraph`
/// (or a `BooleanNetwork`).
///
/// Every regulation can be *monotonous*, and can be set as *observable*:
///
/// - Monotonicity is either *positive* or *negative* and signifies that the influence of the
/// `regulator` on the `targe... | random_line_split | ||
broker.go | : opts.codec,
onError: opts.errorHandler,
routing: newRoutingTable(opts),
pubsub: newPubSub(pubsub, opts),
leaving: make(chan struct{}),
pendingReplies: make(map[uint64]pendingReply),
messageHandlers: opts.messageHandlers,
requestHandlers: opts.requestHandlers,
... | dispatchMsg | identifier_name | |
broker.go | ackTimeout: opts.ackTimeout,
reqTimeout: opts.reqTimeout,
codec: opts.codec,
onError: opts.errorHandler,
routing: newRoutingTable(opts),
pubsub: newPubSub(pubsub, opts),
leaving: make(chan struct{}),
pendingReplies: make(map[uint64]pendingReply),
m... | b.dispatchMsg(ctx, msg, partition)
return
}
reply := b.awaitReply(ctx, succ, b.ackTimeout, func(ctx context.Context, id uint64) error {
return b.sendTo(ctx, succ, marshalFwd(fwd{
id: id,
ack: b.routing.local,
msg: msg,
}))
})
if reply.err == nil {
return
} else if reply.err != Err... |
for {
succ := b.routing.successor(partition)
if succ == b.routing.local { | random_line_split |
broker.go | ackTimeout: opts.ackTimeout,
reqTimeout: opts.reqTimeout,
codec: opts.codec,
onError: opts.errorHandler,
routing: newRoutingTable(opts),
pubsub: newPubSub(pubsub, opts),
leaving: make(chan struct{}),
pendingReplies: make(map[uint64]pendingReply),
m... |
// Shutdown gracefully shuts down the broker. It notifies all clique
// members about a leaving broker and waits until all messages and
// requests are processed. If the given context expires before, the
// context's error will be returned.
func (b *Broker) Shutdown(ctx context.Context) error {
return b.shutdown(ctx... | {
return b.shutdown(context.Background(), func() error { return nil })
} | identifier_body |
broker.go | ackTimeout: opts.ackTimeout,
reqTimeout: opts.reqTimeout,
codec: opts.codec,
onError: opts.errorHandler,
routing: newRoutingTable(opts),
pubsub: newPubSub(pubsub, opts),
leaving: make(chan struct{}),
pendingReplies: make(map[uint64]pendingReply),
m... |
err = b.sendTo(ctx, ping.sender, marshalInfo(info{
id: ping.id,
neighbors: b.routing.neighbors(),
}))
if err != nil {
b.onError(errorf("send info: %v", err))
}
}
func (b *Broker) handleFwd(ctx context.Context, f frame) {
fwd, err := unmarshalFwd(f)
if err != nil {
b.onError(errorf("unmarshal fwd... | {
b.onError(errorf("unmarshal ping: %v", err))
return
} | conditional_block |
FilesManager.ts | // Already exists
}
}
private getAppSourceFile(classId: string) {
const fullPath =
classId === "index"
? path.resolve(APP_DIR, "index.ts")
: path.resolve(APP_DIR, classId, `index.ts`);
const sourceFile = this.project.getSourceFile(fullPath);
if (sourceFile) {
sourceFi... |
});
methods.forEach((property) => {
if (observables.action.includes(property.name)) {
property.type = "action";
}
});
return {
classId,
mixins,
injectors,
properties,
methods,
};
}
private async getClass(fileName: string): Promise<ExtractedCl... | {
property.type = "computed";
} | conditional_block |
FilesManager.ts | // Already exists
}
}
private getAppSourceFile(classId: string) {
const fullPath =
classId === "index"
? path.resolve(APP_DIR, "index.ts")
: path.resolve(APP_DIR, classId, `index.ts`);
const sourceFile = this.project.getSourceFile(fullPath);
if (sourceFile) {
sourceFi... |
classNode.insertProperty(1, {
name,
hasExclamationToken: true,
isReadonly: true,
type: `TFeature<typeof ${fromClassId}>`,
trailingTrivia: writeLineBreak,
});
ast.updateInjectFeatures(classNode, (config) => {
config.addProperty({
name,
kind: StructureKind... | {
const sourceFile = this.getAppSourceFile(toClassId);
ast.addImportDeclaration(sourceFile, LIBRARY_IMPORT, "TFeature");
ast.addImportDeclaration(
sourceFile,
`../${fromClassId}`,
fromClassId,
true
);
const classNode = sourceFile.getClass(toClassId);
if (!classNode) {
... | identifier_body |
FilesManager.ts | {
const classId = this.getClassIdFromFileName(fileName);
return this.extractClass(classId);
}
private getClassIdFromFileName(fileName: string) {
return path.dirname(fileName).split(path.sep).pop()!;
}
private async getClasses() {
const appDir = path.resolve(APP_DIR)!;
try {
const d... | initialize | identifier_name | |
FilesManager.ts | await fs.promises.mkdir(path.dirname(fileName));
} catch {
// Already exists
}
return fs.promises.writeFile(
fileName,
new TextEncoder().encode(
prettier.format(content, {
...prettierConfig,
parser: path.extname(fileName) === ".json" ? "json" : "typescrip... | private async writePrettyFile(fileName: string, content: string) {
try { | random_line_split | |
specs.py |
event = (
("evid", 1, "i4", "i8", 1, 8),
("evname", 2, "c15", "a15", 10, 24),
("prefor", 3, "i4", "i8", 26, 33),
("auth", 4, "c15", "al5", 35, 49),
("commid", 5, "i4", "i8", 51, 58),
("lddate", 6, "date", "al7", 60, 76),
)
gregion = (
("gm", 1, "i4", "i8", 1, 8),
("gmame", 2, "c40", "a... | ("lddate", 19, "date", "al7", 136, 152),
) | random_line_split | |
traverser.go |
SendTimeout time.Duration
}
func NewTraverser(cfg TraverserConfig) *traverser {
// Include request id in all logging.
logger := log.WithFields(log.Fields{"requestId": cfg.Chain.RequestId()})
// Channels used to communicate between traverser + reaper(s)
doneJobChan := make(chan proto.Job)
runJobChan := make(c... | {
// Run all jobs that come in on runJobChan. The loop exits when runJobChan
// is closed after the running reaper finishes.
for job := range t.runJobChan {
// Explicitly pass the job into the func, or all goroutines would share
// the same loop "job" variable.
go func(job proto.Job) {
jLogger := t.logger.W... | identifier_body | |
traverser.go | (jobChain *proto.JobChain) (Traverser, error) {
// Convert/wrap chain from proto to Go object.
chain := NewChain(jobChain, make(map[string]uint), make(map[string]uint), make(map[string]uint))
return f.make(chain)
}
// MakeFromSJC makes a Traverser from a suspended job chain.
func (f *traverserFactory) MakeFromSJC(s... | Make | identifier_name | |
traverser.go | .
// And traverser and chain have the same lifespan: traverser is done when
// chain is done.
cfg := TraverserConfig{
Chain: chain,
ChainRepo: f.chainRepo,
RunnerFactory: f.rf,
RMClient: f.rmc,
ShutdownChan: f.shutdownChan,
StopTimeout: defaultTimeout,
SendTimeout: defaultTimeout,... | {
runner := activeRunners[jobId]
if runner == nil {
// The job finished between the call to chain.Running() and now,
// so it's runner no longer exists in the runner.Repo.
jobStatus.Status = "(finished)"
} else {
jobStatus.Status = runner.Status()
}
status[i] = jobStatus
i++
} | conditional_block | |
traverser.go | ) and we can return right away.
//
// We don't check if the chain was suspended, since that can only
// happen via the other case in this select.
t.stopMux.Lock()
if !t.stopped {
t.stopMux.Unlock()
return
}
t.stopMux.Unlock()
case <-t.shutdownChan:
// The Job Runner is shutting down. Stop the run... | random_line_split | ||
table.go | 5MB of IO:
// 1MB read from this level
// 10-12MB read from next level (boundaries may be misaligned)
// 10-12MB written to next level
// This implies that 25 seeks cost the same as the compaction
// of 1MB of data. I.e., one seek costs approximately the
// same as the compaction of 40KB ... |
// Returns true if i file number is greater than j.
// This used for sort by file number in descending order.
func (tf tFiles) lessByNum(i, j int) bool {
return tf[i].fd.Num > tf[j].fd.Num
}
// Sorts tables by key in ascending order.
func (tf tFiles) sortByKey(icmp *iComparer) {
sort.Sort(&tFilesSortByKey{tFiles: ... | {
a, b := tf[i], tf[j]
n := icmp.Compare(a.imin, b.imin)
if n == 0 {
return a.fd.Num < b.fd.Num
}
return n < 0
} | identifier_body |
table.go | 25MB of IO:
// 1MB read from this level
// 10-12MB read from next level (boundaries may be misaligned)
// 10-12MB written to next level
// This implies that 25 seeks cost the same as the compaction
// of 1MB of data. I.e., one seek costs approximately the
// same as the compaction of 40KB... | }
func (x *tFilesSortByNum) Less(i, j int) bool {
return x.lessByNum(i, j)
}
// Table operations.
type tOps struct {
s *session
noSync bool
evictRemoved bool
cache *cache.Cache
bcache *cache.Cache
bpool *util.BufferPool
}
// Creates an empty table and returns table writer.... | type tFilesSortByNum struct {
tFiles | random_line_split |
table.go | 25MB of IO:
// 1MB read from this level
// 10-12MB read from next level (boundaries may be misaligned)
// 10-12MB written to next level
// This implies that 25 seeks cost the same as the compaction
// of 1MB of data. I.e., one seek costs approximately the
// same as the compaction of 40KB... | () string {
x := "[ "
for i, f := range tf {
if i != 0 {
x += ", "
}
x += fmt.Sprint(f.fd.Num)
}
x += " ]"
return x
}
// Returns true if i smallest key is less than j.
// This used for sort by key in ascending order.
func (tf tFiles) lessByKey(icmp *iComparer, i, j int) bool {
a, b := tf[i], tf[j]
n :=... | nums | identifier_name |
table.go | .Num
}
// Sorts tables by key in ascending order.
func (tf tFiles) sortByKey(icmp *iComparer) {
sort.Sort(&tFilesSortByKey{tFiles: tf, icmp: icmp})
}
// Sorts tables by file number in descending order.
func (tf tFiles) sortByNum() {
sort.Sort(&tFilesSortByNum{tFiles: tf})
}
// Returns sum of all tables size.
func ... | {
return
} | conditional_block | |
main.go | "How often a heartbeat should be sent")
entriesPerMsg = flag.Uint64("entriespermsg", 64, "Entries per Appendentries message")
catchupMultiplier = flag.Uint64("catchupmultiplier", 1024, "How many more times entries per message allowed during catch up")
cache = flag.Int("cache", 1024*1024*64, "How man... |
grpclog.SetLogger(logger)
lis, err := net.Listen("tcp", nodes[*id-1])
if err != nil {
logger.Fatal(err)
}
grpcServer := grpc.NewServer(grpc.MaxMsgSize(*maxgrpc))
if *serverMetrics {
go func() {
http.Handle("/metrics", promhttp.Handler())
logger.Fatal(http.ListenAndServe(fmt.Sprintf(":590%d", *id),... | {
logger.Out = ioutil.Discard
grpc.EnableTracing = false
} | conditional_block |
main.go | "How often a heartbeat should be sent")
entriesPerMsg = flag.Uint64("entriespermsg", 64, "Entries per Appendentries message")
catchupMultiplier = flag.Uint64("catchupmultiplier", 1024, "How many more times entries per message allowed during catch up")
cache = flag.Int("cache", 1024*1024*64, "How man... | }
}
addr, err := net.ResolveTCPAddr("tcp", string(servers[id-1].Address))
if err != nil {
logger.Fatal(err)
}
trans, err := hashic.NewTCPTransport(string(servers[id-1].Address), addr, len(nodes)+1, 10*time.Second, os.Stderr)
if err != nil {
logger.Fatal(err)
}
path := fmt.Sprintf("hashicorp%.2d.bolt", i... | {
servers := make([]hashic.Server, len(nodes))
for i, addr := range nodes {
host, port, err := net.SplitHostPort(addr)
if err != nil {
logger.Fatal(err)
}
p, _ := strconv.Atoi(port)
addr = host + ":" + strconv.Itoa(p-100)
suffrage := hashic.Voter
if !contains(uint64(i+1), ids) {
suffrage = hashi... | identifier_body |
main.go | "How often a heartbeat should be sent")
entriesPerMsg = flag.Uint64("entriespermsg", 64, "Entries per Appendentries message")
catchupMultiplier = flag.Uint64("catchupmultiplier", 1024, "How many more times entries per message allowed during catch up")
cache = flag.Int("cache", 1024*1024*64, "How man... | () {
var (
id = flag.Uint64("id", 0, "server ID")
servers = flag.String("servers", ":9201,:9202,:9203,:9204,:9205,:9206,:9207", "comma separated list of server addresses")
cluster = flag.String("cluster", "1,2,3", "comma separated list of server ids to form cluster with, [1 >= id <= len(servers)]")
backen... | main | identifier_name |
main.go | sid := range selected {
id, err := strconv.ParseUint(sid, 10, 64)
if err != nil {
fmt.Print("could not parse -cluster argument\n\n")
flag.Usage()
os.Exit(1)
}
if id <= 0 || id > uint64(len(nodes)) {
fmt.Print("invalid -cluster argument\n\n")
flag.Usage()
os.Exit(1)
}
ids = append(ids, ... | logger.Fatal(grpcServer.Serve(lis)) | random_line_split | |
post_trees.rs | &self,
worker_id: usize,
) -> (Stream<G, StatUpdate>, Stream<G, RecommendationUpdate>) {
let mut state: PostTreesState = PostTreesState::new(worker_id);
let mut builder = OperatorBuilder::new("PostTrees".to_owned(), self.scope());
let mut input = builder.new_input(self, Pipeline);... | dump_ooo_events | identifier_name | |
post_trees.rs | ` operator
/// that implements query 1
/// 2) RecommendationUpdates: will be fed into the `friend_recommendation`
/// operator that implements query 2
///
/// In case of multiple workers, an upstream `exchange` operator
/// will partition the events by root post id. Thus this... | let node = Node { person_id: comment.person_id, root_post_id: root_post_id };
self.root_of.insert(comment.comment_id, node);
(Some(reply_to_id), Some(root_post_id))
} else {
(Some(reply_to_id), None)
}
... | {
match event {
Event::Post(post) => {
let node = Node { person_id: post.person_id, root_post_id: post.post_id };
self.root_of.insert(post.post_id, node);
(None, Some(post.post_id))
}
Event::Like(like) => {
// li... | identifier_body |
post_trees.rs | _posts` operator
/// that implements query 1
/// 2) RecommendationUpdates: will be fed into the `friend_recommendation`
/// operator that implements query 2
/// | /// will handle only a subset of the posts.
///
/// "Reply to comments" events are broadcasted to all workers
/// as they don't carry the root post id in the payload.
///
/// When the `post_trees` operator receives an Reply event that
/// cannot match to any currently received comment, it stores
/// it in an out-of-ord... | /// In case of multiple workers, an upstream `exchange` operator
/// will partition the events by root post id. Thus this operator | random_line_split |
lock-rpc-server.go | attempted on a read locked entity: %s (%d read locks active)", args.Name, len(lri))
}
if l.removeEntry(args.Name, args.UID, &lri) {
return nil
}
return fmt.Errorf("Unlock unable to find corresponding lock for uid: %s", args.UID)
}
// RLock - rpc handler for read lock operation.
func (l *lockServer) RLock(args *... | {
for _, lockServer := range lockServers {
lockRPCServer := rpc.NewServer()
lockRPCServer.RegisterName("Dsync", lockServer)
lockRouter := mux.PathPrefix(reservedBucket).Subrouter()
lockRouter.Path(path.Join("/lock", lockServer.rpcPath)).Handler(lockRPCServer)
}
} | identifier_body | |
lock-rpc-server.go | the supplied value.
func (l *LockArgs) SetTimestamp(tstamp time.Time) {
l.Timestamp = tstamp
}
// lockRequesterInfo stores various info from the client for each lock that is requested
type lockRequesterInfo struct {
writer bool // Bool whether write or read lock
node string // Network addre... | (args *LockArgs, reply *bool) error {
l.mutex.Lock()
defer l.mutex.Unlock()
if err := l.verifyArgs(args); err != nil {
return err
}
var lri []lockRequesterInfo
if lri, *reply = l.lockMap[args.Name]; !*reply {
return nil // No lock is held on the given name so return false
}
// Check whether uid is still act... | Active | identifier_name |
lock-rpc-server.go | RPC call.
func (l *lockServer) LoginHandler(args *RPCLoginArgs, reply *RPCLoginReply) error {
jwt, err := newJWT(defaultTokenExpiry)
if err != nil {
return err
}
if err = jwt.Authenticate(args.Username, args.Password); err != nil {
return err
}
token, err := jwt.GenerateToken(args.Username)
if err != nil {
... |
// Initialize distributed lock.
func initDistributedNSLock(mux *router.Router, serverConfig serverCmdConfig) {
lockServers := newLockServers(serverConfig)
registerStorageLockers(mux, lockServers) | random_line_split | |
lock-rpc-server.go | the supplied value.
func (l *LockArgs) SetTimestamp(tstamp time.Time) {
l.Timestamp = tstamp
}
// lockRequesterInfo stores various info from the client for each lock that is requested
type lockRequesterInfo struct {
writer bool // Bool whether write or read lock
node string // Network addre... | else {
// Remove the appropriate read lock
*lri = append((*lri)[:index], (*lri)[index+1:]...)
l.lockMap[name] = *lri
}
return true
}
}
return false
}
// nameLockRequesterInfoPair is a helper type for lock maintenance
type nameLockRequesterInfoPair struct {
name string
lri lockRequesterInfo
}
... | {
delete(l.lockMap, name) // Remove the (last) lock
} | conditional_block |
worker.rs | .blob_store.clone(),
options.bootstrap.location.clone(),
),
deno_fetch::deno_fetch::init_ops_and_esm::<PermissionsContainer>(
deno_fetch::Options {
user_agent: options.bootstrap.user_agent.clone(),
root_cert_store_provider: options.root_cert_store_provider.clone(),
... | execute_main_module | identifier_name | |
worker.rs | <ops::worker_host::CreateWebWorkerCb>,
pub format_js_error_fn: Option<Arc<FormatJsErrorFn>>,
/// Source map reference for errors.
pub source_map_getter: Option<Box<dyn SourceMapGetter>>,
pub maybe_inspector_server: Option<Arc<InspectorServer>>,
// If true, the worker will wait for inspector session and break... | root_cert_store_provider: Default::default(),
npm_resolver: Default::default(),
blob_store: Default::default(),
extensions: Default::default(),
startup_snapshot: Default::default(),
create_params: Default::default(),
bootstrap: Default::default(),
stdio: Default::default(... | {
Self {
create_web_worker_cb: Arc::new(|_| {
unimplemented!("web workers are not supported")
}),
fs: Arc::new(deno_fs::RealFs),
module_loader: Rc::new(FsModuleLoader),
seed: None,
unsafely_ignore_certificate_errors: Default::default(),
should_break_on_first_stateme... | identifier_body |
worker.rs | possibility of sharing
/// SharedArrayBuffers, they should use the same [SharedArrayBufferStore]. If
/// no [SharedArrayBufferStore] is specified, SharedArrayBuffer can not be
/// serialized.
pub shared_array_buffer_store: Option<SharedArrayBufferStore>,
/// The store to use for transferring `WebAssembly.Mo... | {
server.register_inspector(
main_module.to_string(),
&mut js_runtime,
options.should_break_on_first_statement
|| options.should_wait_for_inspector_session,
);
// Put inspector handle into the op state so we can put a breakpoint when
// executing a CJS entrypoi... | conditional_block | |
worker.rs | Arc<ops::worker_host::CreateWebWorkerCb>,
pub format_js_error_fn: Option<Arc<FormatJsErrorFn>>,
/// Source map reference for errors.
pub source_map_getter: Option<Box<dyn SourceMapGetter>>,
pub maybe_inspector_server: Option<Arc<InspectorServer>>,
// If true, the worker will wait for inspector session and b... | state = |state, options| {
state.put::<PermissionsContainer>(options.permissions);
state.put(ops::UnstableChecker { unstable: options.unstable });
state.put(ops::TestingFeaturesEnabled(options.enable_testing_features));
},
);
// Permissions: many ops depend on this
let u... | permissions: PermissionsContainer,
unstable: bool,
enable_testing_features: bool,
}, | random_line_split |
views.py | grouped_entities
@route('/archives/')
def archives():
all_threads = Thread.query \
.filter(Thread.community_id == g.community.id) \
.order_by(Thread.created_at.desc()).all()
grouped_threads = group_monthly(all_threads)
return render_template('forum/archives.html',
grouped_thre... | continue | conditional_block | |
views.py | = u'post_{:d}'.format(obj.id)
return kw
@forum.url_value_preprocessor
def init_forum_values(endpoint, values):
g.current_tab = 'forum'
g.breadcrumb.append(
nav.BreadcrumbItem(label=_l(u'Conversations'),
url=nav.Endpoint('forum.index',
communit... | (self):
del self.form['attachments']
self.message_body = self.form.message.data
del self.form['message']
if 'send_by_email' in self.form:
self.send_by_email = (self.can_send_by_mail()
and self.form.send_by_email.data)
del self.form['send_by_email']
def after_p... | before_populate_obj | identifier_name |
views.py | filter(Thread.community_id == g.community.id) \
.order_by(Thread.created_at.desc()).all()
grouped_threads = group_monthly(all_threads)
return render_template('forum/archives.html',
grouped_threads=grouped_threads)
@route('/attachments/')
def attachments():
# XXX: there is probably ... | attachments_to_remove.append(self.obj.attachments[idx])
for att in attachments_to_remove: | random_line_split | |
views.py | = u'post_{:d}'.format(obj.id)
return kw
@forum.url_value_preprocessor
def init_forum_values(endpoint, values):
g.current_tab = 'forum'
g.breadcrumb.append(
nav.BreadcrumbItem(label=_l(u'Conversations'),
url=nav.Endpoint('forum.index',
communit... |
grouped_entities = groupby(entities_list, grouper)
grouped_entities = [(format_month(year, month), list(entities))
for (year, month), entities in grouped_entities]
return grouped_entities
@route('/archives/')
def archives():
all_threads = Thread.query \
.filter(Thread.community_id ... | month = format_date(date(year, month, 1), "MMMM").capitalize()
return u"%s %s" % (month, year) | identifier_body |
gpu_controller.go | =configmaps,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch;create;update;patch;delete
func (r *GpuReconciler) Reconcile(ctx context.Context, _ ctrl.Request) (ctrl.Result, error) {
nodeList := &corev1.NodeList{}
if err := r.List(ctx, nodeList, client.... | UpdateFunc: func(event event.UpdateEvent) bool { | random_line_split | |
gpu_controller.go | 8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/source"
)
type GpuReconciler struct {
client.Client
Scheme ... |
r.Logger.V(1).Info("gpu-info configmap status", "gpu", configmap.Data[GPU])
return ctrl.Result{}, nil
}
func (r *GpuReconciler) initGPUInfoCM(ctx context.Context, clientSet *kubernetes.Clientset) error {
// filter for nodes that have GPU
req1, _ := labels.NewRequirement(NvidiaGPUProduct, selection.Exists, []stri... | {
configmap.Data[GPU] = nodeMapStr
if err := r.Update(ctx, configmap); err != nil && !errors.IsConflict(err) {
r.Logger.Error(err, "failed to update gpu-info configmap")
return ctrl.Result{}, err
}
} | conditional_block |
gpu_controller.go | 8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/source"
)
type GpuReconciler struct {
client.Client
Scheme ... | }
nodeMap[nodeName][GPUProduct] = gpuProduct
nodeMap[nodeName][GPUMemory] = gpuMemory
nodeMap[nodeName][GPUCount] = gpuCount.String()
}
// get the number of GPU used by pods that are using GPU
for _, pod := range podList.Items {
phase := pod.Status.Phase
if phase == corev1.PodSucceeded {
continue
}
... | {
/*
"nodeMap": {
"sealos-poc-gpu-master-0":{},
"sealos-poc-gpu-node-1":{"gpu.count":"1","gpu.memory":"15360","gpu.product":"Tesla-T4"}}
}
*/
nodeMap := make(map[string]map[string]string)
var nodeName string
// get the GPU product, GPU memory, GPU allocatable number on the node
for _, node := range node... | identifier_body |
gpu_controller.go | 8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/source"
)
type GpuReconciler struct {
client.Client
Scheme ... | (ctx context.Context, nodeList *corev1.NodeList, podList *corev1.PodList, clientSet *kubernetes.Clientset) (ctrl.Result, error) {
/*
"nodeMap": {
"sealos-poc-gpu-master-0":{},
"sealos-poc-gpu-node-1":{"gpu.count":"1","gpu.memory":"15360","gpu.product":"Tesla-T4"}}
}
*/
nodeMap := make(map[string]map[string... | applyGPUInfoCM | identifier_name |
ThriftHiveMock.js | ({
taskTrackers: 1,
mapTasks: 0,
reduceTasks: 0,
maxMapTasks: 2,
maxReduceTasks: 2,
state: 2
});
};
var idlist = ['hadoop_20110408154949_8b2be199-02ae-40fe-9492-d197ade572f2',
'hadoop_20110408154949_8b2be199-03ff-40fe-9492-d197ade572f2',
'hadoop_20110408154949_8b2b... | bstring(0, separator);
children_label = subtree_label.substring(separator + 1);
}
var matched = /^([a-z]+)(\d+)$/.exec(current_depth_label);
var fieldname = matched[1 | conditional_block | |
ThriftHiveMock.js | ', 'せ', 'そ', 'た', 'ち', 'つ', 'て', 'と',
'な', 'に', 'ぬ', 'ね', 'の', 'は', 'ひ', 'ふ', 'へ', 'ほ',
'ま', 'み', 'む', 'め', 'も', 'や', 'ゆ', 'よ',
'ら', 'り', 'る', 'れ', 'ろ', 'わ', 'を', 'ん'
];
var random_num = function(max){ return Math.floor(Math.random() * max) + 1; };
var random_index = function(max){ return Math.floor(Math.random()... | me;
case 'date':
var d1 = new Date((new Date()).getTime() - random_num(50) * 86400 * 1000);
return '' + d1.getFullYear() + pad(d1.getMonth()+1) + pad(d1.getDate());
case 'time':
var d2 = new Date((new Date()).getTime() - random_num(12 * 60) * 60 * 1000);
return '' + pad(d2.getHours()) | .na | identifier_name |
ThriftHiveMock.js | ', 'せ', 'そ', 'た', 'ち', 'つ', 'て', 'と',
'な', 'に', 'ぬ', 'ね', 'の', 'は', 'ひ', 'ふ', 'へ', 'ほ',
'ま', 'み', 'む', 'め', 'も', 'や', 'ゆ', 'よ',
'ら', 'り', 'る', 'れ', 'ろ', 'わ', 'を', 'ん'
];
var random_num = function(max){ return Math.floor(Math.random() * max) + 1; };
var random_index = function(max){ return Math.floor(Math.random()... | = new Date((new Date()).getTime() - random_num(50) * 86400 * 1000);
return '' + d1.getFullYear() + pad(d1.getMonth()+1) + pad(d1.getDate());
case 'time':
var d2 = new Date((new Date()).getTime() - random_num(12 * 60) * 60 * 1000);
return '' + pad(d2.getHours()) + |
case 'date':
var d1 | identifier_body |
ThriftHiveMock.js | す', 'せ', 'そ', 'た', 'ち', 'つ', 'て', 'と',
'な', 'に', 'ぬ', 'ね', 'の', 'は', 'ひ', 'ふ', 'へ', 'ほ',
'ま', 'み', 'む', 'め', 'も', 'や', 'ゆ', 'よ',
'ら', 'り', 'る', 'れ', 'ろ', 'わ', 'を', 'ん'
];
var random_num = function(max){ return Math.floor(Math.random() * max) + 1; };
var random_index = function(max){ return Math.floor(Math.random(... | type = 'bigint';
ex = 'count';
}
else if (/^(sum|avg|min|max)/im.exec(column)) {
type = 'bigint';
ex = 'aggr';
}
else if (/id$/.exec(name)) {
type = 'bigint';
ex = 'id';
}
if (/^"(.*)"$/.exec(name)) {
name = /^"(.*)"$/.exec(name)[1];
ex = "strcopy";
}
else if (name == 'y... | name = match[1];
}
if (/^count/im.exec(column)) { | random_line_split |
query.go | in it, or the specific txHash does not have a label, an empty
// string and no error are returned.
func (s *Store) TxLabel(ns walletdb.ReadBucket, txHash chainhash.Hash) (string,
error) {
label, err := FetchTxLabel(ns, txHash)
switch err {
// If there are no saved labels yet (the bucket has not been created) or
... | }
pkScript, err := fetchRawTxRecordPkScript(
prevOut.Hash[:], v, prevOut.Index)
if err != nil { | random_line_split | |
query.go | Tx.TxOut) {
str := "saved credit index exceeds number of outputs"
return nil, storeError(ErrData, str, nil)
}
// The credit iterator does not record whether this credit was
// spent by an unmined transaction, so check that here.
if !credIter.elem.Spent {
k := canonicalOutPoint(txHash, credIter.elem.In... |
var blockIter blockIterator
var advance func(*blockIterator) bool
if begin | {
end = int32(^uint32(0) >> 1)
} | conditional_block |
query.go | Tx.TxOut) {
str := "saved credit index exceeds number of outputs"
return nil, storeError(ErrData, str, nil)
}
// The credit iterator does not record whether this credit was
// spent by an unmined transaction, so check that here.
if !credIter.elem.Spent {
k := canonicalOutPoint(txHash, credIter.elem.In... |
// UniqueTxDetails looks up all recorded details for a transaction recorded
// mined in some particular block, or an unmined transaction if block is nil.
//
// Not finding a transaction with this hash from this block is not an error. In
// this case, a nil TxDetails is returned.
func (s *Store) UniqueTxDetails(ns wa... | {
// First, check whether there exists an unmined transaction with this
// hash. Use it if found.
v := existsRawUnmined(ns, txHash[:])
if v != nil {
return s.unminedTxDetails(ns, txHash, v)
}
// Otherwise, if there exists a mined transaction with this matching
// hash, skip over to the newest and begin fetch... | identifier_body |
query.go | , they
// must be looked up for each transaction input manually. There are two
// kinds of previous credits that may be debited by an unmined
// transaction: mined unspent outputs (which remain marked unspent even
// when spent by an unmined transaction), and credits from other unmined
// transactions. Both situ... | RangeTransactions | identifier_name | |
settings.py | according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/... | PROJECT_FOLDER = '/%s/' % PROJECT_FOLDER_NAME
R_ENGINE_PATH = PROD_PATH + R_ENGINE_SUB_PATH # FIXME Legacy | conditional_block | |
settings.py | container
FULL_HOST_NAME = socket.gethostname()
HOST_NAME = str.split(FULL_HOST_NAME, '.')[0]
# do not move. here because some utils function useses it
FIMM_NETWORK = '128.214.0.0/16'
from config import *
# Super User on breeze can Access all data
SU_ACCESS_OVERRIDE = True
PROJECT_PATH = PROJECT_FOLDER + BREEZE_FO... | f = open('running', 'w+')
f.write(str(datetime.now().strftime(USUAL_DATE_FORMAT)))
f.close() | identifier_body | |
settings.py | set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aw... | CLOUD_PROD = ['breeze.fimm.fi', '13.79.158.135', ]
CLOUD_DEV = ['breeze-dev.northeurope.cloudapp.azure.com', '52.164.209.61', ]
FIMM_PH = ['breeze-newph.fimm.fi', 'breeze-ph.fimm.fi', ]
FIMM_DEV = ['breeze-dev.fimm.fi', ]
FIMM_PROD = ['breeze-fimm.fimm.fi', 'breeze-new.fimm.fi', ]
@classmethod
def get_current_... | }
}
class DomainList(object): | random_line_split |
settings.py | _SH = SOURCE_ROOT + 're_run.sh'
MEDIA_ROOT = PROJECT_PATH + 'db/'
RORA_LIB = PROJECT_PATH + 'RORALib/'
UPLOAD_FOLDER = MEDIA_ROOT + 'upload_temp/'
DATASETS_FOLDER = MEDIA_ROOT + 'datasets/'
STATIC_ROOT = SOURCE_ROOT + 'static_source/' # static files for the website
DJANGO_CONFIG_FOLDER = SOURCE_ROOT + 'config/' # Wher... | project_folder_path | identifier_name | |
sign-up.js | `, {
email: email,
})
.then((res) => {
setVerifyCode(res.data.data.emailcode);
})
.catch((err) => {});
// 오류는 중복되거나 또는 서버 오류
setIsSend(true);
};
const verify = (code) => {
axios
.post(
`${process.env.REACT_APP_SERVER_URL}/sign/email-verification?cod... | ) : isSend && user.verifyEmail ? (
"인증 되지 않았습니다"
) : (
""
)}
</Message>
</EmailIcon>
<Repassword>
<RepasswordInput
name="password"
value={user.password}
type="p... | {isVerify ? (
<div style={{ color: `${theme.colors.green}` }}>
인증되었습니다
</div> | random_line_split |
sign-up.js | `, {
email: email,
})
.then((res) => {
setVerifyCode(res.data.data.emailcode);
})
.catch((err) => {});
// 오류는 중복되거나 또는 서버 오류
setIsSend(true);
};
const verify = (code) => {
axios
.post(
`${process.env.REACT_APP_SERVER_URL}/sign/email-verification?cod... |
</Logo>
<InputBox>
<EmailIcon>
<Align>
<EmailInput
name="email"
value={user.email}
placeholder="email"
onChange={handleChange}
/>
<EmailButton type="button" onClick={() => se... | user.password) {
if (pw.length < 8 || pw.length > 20) {
return "8자리 ~ 20자리 이내로 입력해주세요.";
} else if (pw.search(/\s/) != -1) {
return "비밀번호는 공백 없이 입력해주세요.";
} else if (num < 0 || eng < 0 || spe < 0) {
return "영문,숫자, 특수문자를 혼합하여 입력해주세요.";
} else {
return "통과";
}... | identifier_body |
sign-up.js | `, {
email: email,
})
.then((res) => {
setVerifyCode(res.data.data.emailcode);
})
.catch((err) => {});
// 오류는 중복되거나 또는 서버 오류
setIsSend(true);
};
const verify = (code) => {
axios
.post(
`${process.env.REACT_APP_SERVER_URL}/sign/email-verification?cod... | if (user.password) {
if (pw.length < 8 || pw.length > 20) {
return "8자리 ~ 20자리 이내로 입력해주세요.";
} else if (pw.search(/\s/) != -1) {
return "비밀번호는 공백 없이 입력해주세요.";
} else if (num < 0 || eng < 0 || spe < 0) {
return "영문,숫자, 특수문자를 혼합하여 입력해주세요.";
} else {
return "통과";
... | identifier_name | |
run_this_code_CACSSEOUL.py | .add_argument('--folder_name' ,help='ex model/fundus_300/folder_name/0 .. logs/fundus_300/folder_name/0 , type2/folder_name/0')
args=parser.parse_args()
print 'aug : ' , args.use_aug
print 'aug_lv1 : ' , args.use_aug_lv1
print 'actmap : ' , args.use_actmap
print 'use_l2_loss: ' , args.use_l2_loss
print 'weight_decay'... | sys.stdout.write(msg)
sys.stdout.flush()
count_trainable_params()
for step in range(max_i | identifier_body | |
run_this_code_CACSSEOUL.py | : ',args.data_dir
def count_trainable_params():
total_parameters = 0
for variable in tf.trainable_variables():
shape = variable.get_shape()
variable_parametes = 1
for dim in shape:
variable_parametes *= dim.value
total_parameters += variable_parametes
print("T... | y_: test_labs[i * batch_size:(i + 1) * batch_size], is_training: False, global_step: step}
val_acc, val_loss, pred, learning_rate = sess.run(fetches=test_fetches, feed_dict=test_feedDict)
val_acc_mean.append(val_acc)
val_loss_mean.append(val_loss)
pred_all... | conditional_block | |
run_this_code_CACSSEOUL.py | ='init learning rate ')
parser.add_argument('--lr_decay_step' ,type=int , help='decay step for learning rate')
parser.add_argument('--folder_name' ,help='ex model/fundus_300/folder_name/0 .. logs/fundus_300/folder_name/0 , type2/folder_name/0')
args=parser.parse_args()
print 'aug : ' , args.use_aug
print 'aug_lv1 : '... | ess {}/{}'.fo | identifier_name | |
run_this_code_CACSSEOUL.py | parser.add_argument('--clahe' , dest='use_clahe', action='store_true' , help='augmentation')
parser.add_argument('--no_clahe' , dest='use_clahe', action='store_false' , help='augmentation')
parser.add_argument('--actmap', dest='use_actmap' ,action='store_true')
parser.add_argument('--no_actmap', dest='use_actmap', act... | random_line_split | ||
DailyCP.py | 201314",
"appVersion": "8.1.13", "model": "红星一号量子计算机", "lon": 0.0, "systemVersion": "初号机", "lat": 0.0}
self.session.headers.update(
{"Cpdaily-Extension": self.encrypt(json.dumps(extension))})
self.setHostBySchoolName(schoolName)
def setHostBySchoolName(self, schoolN... | else:
return False
def checkNeedCaptchaAuthServer(self, username):
ret = self.request("http://{host}/authserver/needCaptcha.html?username={
username}&pwdEncrypt2=pwdEncryptSalt".format(
username=username), parseJson=False).text
return ret == "true"
def loginAuth... | ogin?service=https://{host}/portal/login".format(host=self.host)).url
client = ret[ret.find("=")+1:]
ret = self.request("https://{host}/iap/security/lt",
"lt={client}".format(client=client), True, False)
client = ret["result"]["_lt"]
# self.encryptSalt = ret["r... | identifier_body |
DailyCP.py | 201314",
"appVersion": "8.1.13", "model": "红星一号量子计算机", "lon": 0.0, "systemVersion": "初号机", "lat": 0.0}
self.session.headers.update(
{"Cpdaily-Extension": self.encrypt(json.dumps(extension))})
self.setHostBySchoolName(schoolName)
def setHostBySchoolName(self, schoolN... | lf.loginUrl)[0]
def encrypt(self, text):
k = pyDes.des(self.key, pyDes.CBC, b"\x01\x02\x03\x04\x05\x06\x07\x08",
pad=None, padmode=pyDes.PAD_PKCS5)
ret = k.encrypt(text)
return base64.b64encode(ret).decode()
def passwordEncrypt(self, text: str, key: str):
... | lName, url=self.loginUrl))
self.host = re.findall(r"//(.*?)/", se | conditional_block |
DailyCP.py | 201314",
"appVersion": "8.1.13", "model": "红星一号量子计算机", "lon": 0.0, "systemVersion": "初号机", "lat": 0.0}
self.session.headers.update(
{"Cpdaily-Extension": self.encrypt(json.dumps(extension))})
self.setHostBySchoolName(schoolName)
def setHostBySchoolName(self, schoolN... | (
"https://static.campushoy.com/apicache/tenantListSort")
school = [j for i in ret["data"]
for j in i["datas"] if j["name"] == schoolName]
if len(school) == 0:
print("不支持的学校或者学校名称错误,以下是支持的学校列表")
print(ret)
exit()
ret = self.reques... | ret = self.request | identifier_name |
DailyCP.py | .MODE_CBC,
str.encode("ya8C45aRrBEn8sZH"))
return base64.b64encode(aes.encrypt(text))
def request(self, url: str, body=None, parseJson=True, JsonBody=True, Referer=None):
url = url.format(host=self.host)
if Referer != None:
self.session.headers.update({"Ref... | app.autoComplete(sys.argv[4], sys.argv[5])
# Author:HuangXu,FengXinYang,ZhouYuYang. | random_line_split | |
yolo.py | 1:, p] == 0)[0][0]
velocity_and_view_time[0,p]=video_fps
velocity_and_view_time[1,p] = (np.array(polygon_dist_list_vel_mode)[p] * np.array(pixel_to_dist_ratio)[p] * 3.6) / (number_of_frames[0][p] / video_fps)
if(itr_number>=num_of_frames_for_mean):
mean_of_p... | pts=np.array(right_clicks) | conditional_block | |
yolo.py | (cls, n):
if n in cls._defaults:
return cls._defaults[n]
else:
return "Unrecognized attribute name '" + n + "'"
def __init__(self, **kwargs):
self.__dict__.update(self._defaults)
self.__dict__.update(kwargs)
self.class_names = self._get_class()
... | get_defaults | identifier_name | |
yolo.py | start = timer()
num_anchors = len(self.anchors)
num_classes = len(self.class_names)
self.yolo_model = yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes)
self.yolo_model.load_weights(self.model_path)
end = timer()
print('{} model, anchors, and classes load... | if th_mode == "counting":
draw.text([10+c*(rectangle_width+space_between_rect), 65], "vehicles:" + str(mean_polygon[c]), fill=(0, 0, 0),font=font_number_of_vehicles)
elif th_mode == "density":
draw.text([10 + c * (rectangle_width + space_between_rect), 65],'densit... | R,G,B=color_result(mean_polygon[c],th_low,th_high)
draw.rectangle([tuple([10+c*(rectangle_width+space_between_rect), 60]), tuple([10 + c*(rectangle_width+space_between_rect)+rectangle_width, 60 + 40])], fill=(R, G, B))
draw.rectangle([tuple([10 + c * (rectangle_width + space_between_... | random_line_split |
yolo.py |
def detect_image(self, image,itr_number,th_mode,car_for_each_polygon_list,polygon_density,pixel_to_dist_ratio,polygon_dist_list_vel_mode,video_fps,velocity_and_view_time,th_low,th_high):
start = timer()
num_of_frames_for_mean=10
number_of_point_in_polygons=np.zeros((1,len(polygon_list)),dt... | model_path = os.path.expanduser(self.model_path)
assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'
start = timer()
num_anchors = len(self.anchors)
num_classes = len(self.class_names)
self.yolo_model = yolo_body(Input(shape=(None,None,3)), num_anchors... | identifier_body | |
install.rs | ;
use reqwest::Url;
use std::io::prelude::*;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum FrumError {
#[error(transparent)]
HttpError(#[from] reqwest::Error),
#[error(transparent)]
IoError(#[from] std::io::Error),
#[e... | ;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::Command;
use crate::config::FrumConfig;
use crate::version::Version;
use tempfile::tempdir;
#[test]
fn test_install_second_version() {
let config = FrumConfig {
base_dir: Some(tempdir().unwrap().p... | {
return Err(FrumError::CantBuildRuby {
stderr: format!(
"make install: {}",
String::from_utf8_lossy(&make_install.stderr).to_string()
),
});
} | conditional_block |
install.rs | Command;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum FrumError {
#[error(transparent)]
HttpError(#[from] reqwest::Error),
#[error(transparent)]
IoError(#[from] std::io::Error),
#[error("Can't find the number of cores")]
FromUtf8Error(#[from] std::string::FromUtf8Error),
#[error("... | test_install_default_version | identifier_name | |
install.rs | use log::debug;
use reqwest::Url;
use std::io::prelude::*;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum FrumError {
#[error(transparent)]
HttpError(#[from] reqwest::Error),
#[error(transparent)]
IoError(#[from] std::io::E... | use colored::Colorize; | random_line_split | |
install.rs | ;
use reqwest::Url;
use std::io::prelude::*;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum FrumError {
#[error(transparent)]
HttpError(#[from] reqwest::Error),
#[error(transparent)]
IoError(#[from] std::io::Error),
#[e... |
fn package_url(mirror_url: Url, version: &Version) -> Url {
debug!("pakage url");
Url::parse(&format!(
"{}/{}/{}",
mirror_url.as_str().trim_end_matches('/'),
match version {
Version::Semver(version) => format!("{}.{}", version.major, version.minor),
_ => unreach... | {
#[cfg(unix)]
let extractor = archive::tar_xz::TarXz::new(response);
#[cfg(windows)]
let extractor = archive::zip::Zip::new(response);
extractor
.extract_into(path)
.map_err(|source| FrumError::ExtractError { source })?;
Ok(())
} | identifier_body |
fse_encoder.go | return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize)
}
cumul[s.symbolLen] = int16(tableSize) + 1
}
// Spread symbols
s.zeroBits = false
{
step := tableStep(tableSize)
tableMask := tableSize - 1
var position uint32
// if any symbol > larg... | (val byte) {
s.allocCtable()
s.actualTableLog = 0
s.ct.stateTable = s.ct.stateTable[:1]
s.ct.symbolTT[val] = symbolTransform{
deltaFindState: 0,
deltaNbBits: 0,
}
if debugEncoder {
println("setRLE: val", val, "symbolTT", s.ct.symbolTT[val])
}
s.rleVal = val
s.useRLE = true
}
// setBits will set outpu... | setRLE | identifier_name |
fse_encoder.go | return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize)
}
cumul[s.symbolLen] = int16(tableSize) + 1
}
// Spread symbols
s.zeroBits = false
{
step := tableStep(tableSize)
tableMask := tableSize - 1
var position uint32
// if any symbol > larg... | }
s.maxBits = 0
for i, v := range transform[:s.symbolLen] {
s.ct.symbolTT[i].outBits = v
if v > s.maxBits {
// We could assume bits always going up, but we play safe.
s.maxBits = v
}
}
}
// normalizeCount will normalize the count of the symbols so
// the total is equal to the table size.
// If success... | {
if s.reUsed || s.preDefined {
return
}
if s.useRLE {
if transform == nil {
s.ct.symbolTT[s.rleVal].outBits = s.rleVal
s.maxBits = s.rleVal
return
}
s.maxBits = transform[s.rleVal]
s.ct.symbolTT[s.rleVal].outBits = s.maxBits
return
}
if transform == nil {
for i := range s.ct.symbolTT[:s.sym... | identifier_body |
fse_encoder.go | u := byte(ui) // one less than reference
if v == -1 {
// Low proba symbol
cumul[u+1] = cumul[u] + 1
tableSymbol[highThreshold] = u
highThreshold--
} else {
cumul[u+1] = cumul[u] + v
}
}
// Encode last symbol separately to avoid overflowing u
u := int(s.symbolLen - 1)
v := s.norm[... | cumul[0] = 0
for ui, v := range s.norm[:s.symbolLen-1] { | random_line_split | |
fse_encoder.go |
s.ct.symbolTT = s.ct.symbolTT[:256]
}
// buildCTable will populate the compression table so it is ready to be used.
func (s *fseEncoder) buildCTable() error {
tableSize := uint32(1 << s.actualTableLog)
highThreshold := tableSize - 1
var cumul [256]int16
s.allocCtable()
tableSymbol := s.ct.tableSymbol[:tableSiz... | {
s.ct.symbolTT = make([]symbolTransform, 256)
} | conditional_block | |
resolve_recovers_from_http_errors.rs | HttpResponder>(
pkg: Package,
responder: H,
failure_error: fidl_fuchsia_pkg::ResolveError,
) {
let env = TestEnvBuilder::new().build().await;
let repo = Arc::new(
RepositoryBuilder::from_template_dir(EMPTY_REPO_PATH)
.add_package(&pkg)
.build()
.await
... |
#[fuchsia::test]
async fn second_resolve_succeeds_disconnect_before_far_complete() {
let pkg = PackageBuilder::new("second_resolve_succeeds_disconnect_before_far_complete")
.add_resource_at(
"meta/large_file",
vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING].as_slice(),
... | {
let blob = vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING];
let pkg = PackageBuilder::new("second_resolve_succeeds_when_blob_errors_mid_download")
.add_resource_at("blobbity/blob", blob.as_slice())
.build()
.await
.unwrap();
let path_to_override = format!(
... | identifier_body |
resolve_recovers_from_http_errors.rs | HttpResponder>(
pkg: Package,
responder: H,
failure_error: fidl_fuchsia_pkg::ResolveError,
) {
let env = TestEnvBuilder::new().build().await;
let repo = Arc::new(
RepositoryBuilder::from_template_dir(EMPTY_REPO_PATH)
.add_package(&pkg)
.build()
.await
... | .await
.unwrap();
verify_resolve_fails_then_succeeds(
pkg,
responder::ForPath::new("/2.snapshot.json", responder::OneByteShortThenDisconnect),
fidl_fuchsia_pkg::ResolveError::Internal,
)
.await
}
// The hyper clients used by the pkg-resolver to download blobs and TUF... | let pkg = PackageBuilder::new("second_resolve_succeeds_when_tuf_metadata_update_fails")
.build() | random_line_split |
resolve_recovers_from_http_errors.rs | HttpResponder>(
pkg: Package,
responder: H,
failure_error: fidl_fuchsia_pkg::ResolveError,
) {
let env = TestEnvBuilder::new().build().await;
let repo = Arc::new(
RepositoryBuilder::from_template_dir(EMPTY_REPO_PATH)
.add_package(&pkg)
.build()
.await
... | () {
let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_blob_404", 1).await;
let path_to_override = format!(
"/blobs/{}",
MerkleTree::from_reader(
extra_blob_contents("second_resolve_succeeds_when_blob_404", 0).as_slice()
)
.expect("merkle slice")
... | second_resolve_succeeds_when_blob_404 | identifier_name |
value_textbox.rs | during editing;
/// this can be used to report errors further back up the tree.
pub struct ValueTextBox<T> {
child: TextBox<String>,
formatter: Box<dyn Formatter<T>>,
callback: Option<Box<dyn ValidationDelegate>>,
is_editing: bool,
validate_while_editing: bool,
update_data_while_editing: bool,
... | last_known_data: None,
validate_while_editing: true,
update_data_while_editing: false,
old_buffer: String::new(),
buffer: String::new(),
force_selection: None,
}
}
/// Builder-style method to set an optional [`ValidationDelegate`] ... | random_line_split | |
value_textbox.rs | during editing;
/// this can be used to report errors further back up the tree.
pub struct ValueTextBox<T> {
child: TextBox<String>,
formatter: Box<dyn Formatter<T>>,
callback: Option<Box<dyn ValidationDelegate>>,
is_editing: bool,
validate_while_editing: bool,
update_data_while_editing: bool,
... | (&mut self, ctx: &mut EventCtx, data: &T) {
self.is_editing = false;
self.buffer = self.formatter.format(data);
ctx.request_update();
ctx.resign_focus();
self.send_event(ctx, TextBoxEvent::Cancel);
}
fn begin(&mut self, ctx: &mut EventCtx, data: &T) {
self.is_edi... | cancel | identifier_name |
value_textbox.rs | during editing;
/// this can be used to report errors further back up the tree.
pub struct ValueTextBox<T> {
child: TextBox<String>,
formatter: Box<dyn Formatter<T>>,
callback: Option<Box<dyn ValidationDelegate>>,
is_editing: bool,
validate_while_editing: bool,
update_data_while_editing: bool,
... | }
self.send_event(ctx, TextBoxEvent::Invalid(err));
// our content isn't valid
// ideally we would flash the background or something
false
}
}
}
fn cancel(&mut self, ctx: &mut EventCtx, data: &T) {
self... | {
match self.formatter.value(&self.buffer) {
Ok(new_data) => {
*data = new_data;
self.buffer = self.formatter.format(data);
self.is_editing = false;
ctx.request_update();
self.send_event(ctx, TextBoxEvent::Complete);
... | identifier_body |
has_loc.rs | ned::Spanned;
use syn::Attribute;
use syn::Data;
use syn::DataEnum;
use syn::DataStruct;
use syn::DeriveInput;
use syn::Error;
use syn::Lit;
use syn::Meta;
use syn::NestedMeta;
use syn::Result;
use syn::Variant;
use crate::simple_type::SimpleType;
use crate::util::InterestingFields;
/// Builds a HasLoc impl.
///
/// ... | (input: TokenStream) -> Result<TokenStream> {
let input = syn::parse2::<DeriveInput>(input)?;
match &input.data {
Data::Enum(data) => build_has_loc_enum(&input, data),
Data::Struct(data) => build_has_loc_struct(&input, data),
Data::Union(_) => Err(Error::new(input.span(), "Union not hand... | build_has_loc | identifier_name |
has_loc.rs | syn::Meta;
use syn::NestedMeta;
use syn::Result;
use syn::Variant;
use crate::simple_type::SimpleType;
use crate::util::InterestingFields;
/// Builds a HasLoc impl.
///
/// The build rules are as follows:
/// - For a struct it just looks for a field with a type of LocId.
/// - For an enum it does a match on each var... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.