file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
ItemView.js | /**
* @file View that builds the map by showing the items' images at their specified locations.
*/
"use strict";
/**
* @class ItemView
*/
function ItemView() {
// Private variables
// These are jQuery objects corresponding to elements
let $mapImage;
let $carpet;
let $backArrow;
let $forw... |
}
};
/**
* To update the order number of the item currently visited as shown between the arrows.
* The total number of items is shown as well.
*
* @param item
*/
const updateItemOrderNumbers = (item) => {
if (item)
$itemOrderNumbers.html("<span>" + i... | {
const viewport = viewModel.getViewPort();
// When performing the animation the View Model needs to know so that it
// can tell other views
viewModel.setAnimationToNextItemRunning(true);
// left and top attributes to give to the map to ... | conditional_block |
ItemView.js | /**
* @file View that builds the map by showing the items' images at their specified locations.
*/
"use strict";
/**
* @class ItemView
*/
function | () {
// 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 | /**
* @file View that builds the map by showing the items' images at their specified locations.
*/
"use strict";
/**
* @class ItemView
*/
function ItemView() | {
// 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 | use crate::expat_external_h::XML_Char;
use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert};
use crate::lib::xmltok::{ENCODING, XML_Convert_Result};
use bumpalo::Bump;
use bumpalo::collections::vec::Vec as BumpVec;
use fallible_collections::FallibleBox;
use libc::c_int;
use std::cell::{Cell, RefCell};
... | () -> 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 | use crate::expat_external_h::XML_Char;
use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert};
use crate::lib::xmltok::{ENCODING, XML_Convert_Result};
use bumpalo::Bump;
use bumpalo::collections::vec::Vec as BumpVec;
use fallible_collections::FallibleBox;
use libc::c_int;
use std::cell::{Cell, RefCell};
... |
/// 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 | use crate::expat_external_h::XML_Char;
use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert};
use crate::lib::xmltok::{ENCODING, XML_Convert_Result};
use bumpalo::Bump;
use bumpalo::collections::vec::Vec as BumpVec;
use fallible_collections::FallibleBox;
use libc::c_int;
use std::cell::{Cell, RefCell};
... | pool.copy_c_string(S.as_ptr())
};
assert_eq!(new_string.unwrap(), [A, C, D, D, C, NULL]);
assert!(pool.append_char(B));
pool.current_slice(|s| assert_eq!(s, [B]));
let new_string2 = unsafe {
pool.copy_c_string_n(S.as_ptr(), 4)
};
assert_eq!(new_string2.unwrap(), [B, C, D, ... | let new_string = unsafe { | random_line_split |
string_pool.rs | use crate::expat_external_h::XML_Char;
use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert};
use crate::lib::xmltok::{ENCODING, XML_Convert_Result};
use bumpalo::Bump;
use bumpalo::collections::vec::Vec as BumpVec;
use fallible_collections::FallibleBox;
use libc::c_int;
use std::cell::{Cell, RefCell};
... |
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 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
// 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 | #!/usr/bin/python
#==========================================================================
#
# Copyright Insight Software Consortium
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at... | (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 | #!/usr/bin/python
#==========================================================================
#
# Copyright Insight Software Consortium
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at... | os.system( command )
# remove Copyright files we don't want to touch later
os.system( "rm -rf %s" % (op.join(HeadOfTempTree,"Copyright") ) )
os.system( "rm -rf %s" % (op.join(HeadOfTempTree,"RELEASE_NOTES.txt") ) )
os.system( "rm -rf %s" % (op.join(HeadOfTempTree,"README") ) )
# PREPARE MIGRATION COMMIT ON A CLONE... | # 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 | #!/usr/bin/python
#==========================================================================
#
# Copyright Insight Software Consortium
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at... |
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 | #!/usr/bin/python
#==========================================================================
#
# Copyright Insight Software Consortium
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at... |
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 | #!/usr/bin/python
from __future__ import print_function
import solidscraper as ss
import traceback
import argparse
import codecs # utf-8 text files
import json
import os
from collections import defaultdict
from datetime import datetime
from datetime import timedelta
from dateutil import tz
import time
def toFixed(s... | 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 | #!/usr/bin/python
from __future__ import print_function
import solidscraper as ss
import traceback
import argparse
import codecs # utf-8 text files
import json
import os
from collections import defaultdict
from datetime import datetime
from datetime import timedelta
from dateutil import tz
import time
def toFixed(s... | (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 | #!/usr/bin/python
from __future__ import print_function
import solidscraper as ss
import traceback
import argparse
import codecs # utf-8 text files
import json
import os
from collections import defaultdict
from datetime import datetime
from datetime import timedelta
from dateutil import tz
import time
def toFixed(s... |
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 | #!/usr/bin/python
from __future__ import print_function
import solidscraper as ss
import traceback
import argparse
import codecs # utf-8 text files
import json
import os
from collections import defaultdict
from datetime import datetime
from datetime import timedelta
from dateutil import tz
import time
def toFixed(s... |
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 | //! A library for analysis of Boolean networks. As of now, the library supports:
//! - Regulatory graphs with monotonicity and observability constraints.
//! - Boolean networks, possibly with partially unknown and parametrised update functions.
//! - Full SBML-qual support for import/export as well as custom string ... | {
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 | //! A library for analysis of Boolean networks. As of now, the library supports:
//! - Regulatory graphs with monotonicity and observability constraints.
//! - Boolean networks, possibly with partially unknown and parametrised update functions.
//! - Full SBML-qual support for import/export as well as custom string ... | pub struct ModelAnnotation {
value: Option<String>,
inner: HashMap<String, ModelAnnotation>,
} | random_line_split | |
broker.go | package flow
import (
"context"
"sync"
"sync/atomic"
"time"
)
// MessageHandler represents a callback function for handling incoming messages.
// The binary parts of the passed message should be assumed to be valid
// only during the function call. It is the handler's responsibility to
// copy the data which shou... | (ctx context.Context, msg msg, partition Key) {
var lock, slot = sync.Locker(nullLock{}), -1
if len(msg.pkey) != 0 && len(b.partitionLocks) != 0 {
slot = int(partition % Key(len(b.partitionLocks)))
lock = &b.partitionLocks[slot]
}
var reply reply
if h := b.messageHandlers[string(msg.stream)]; h != nil {
loc... | dispatchMsg | identifier_name |
broker.go | package flow
import (
"context"
"sync"
"sync/atomic"
"time"
)
// MessageHandler represents a callback function for handling incoming messages.
// The binary parts of the passed message should be assumed to be valid
// only during the function call. It is the handler's responsibility to
// copy the data which shou... | 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 | package flow
import (
"context"
"sync"
"sync/atomic"
"time"
)
// MessageHandler represents a callback function for handling incoming messages.
// The binary parts of the passed message should be assumed to be valid
// only during the function call. It is the handler's responsibility to
// copy the data which shou... |
// 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 | package flow
import (
"context"
"sync"
"sync/atomic"
"time"
)
// MessageHandler represents a callback function for handling incoming messages.
// The binary parts of the passed message should be assumed to be valid
// only during the function call. It is the handler's responsibility to
// copy the data which shou... |
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 | import * as fs from "fs";
import * as path from "path";
import * as chokidar from "chokidar";
import * as prettier from "prettier";
import { Node, Project, StructureKind } from "ts-morph";
import * as ts from "typescript";
import {
APP_DIR,
CONFIGURATION_DIR,
LIBRARY_IMPORT,
} from "../common/constants";
import... |
});
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 | import * as fs from "fs";
import * as path from "path";
import * as chokidar from "chokidar";
import * as prettier from "prettier";
import { Node, Project, StructureKind } from "ts-morph";
import * as ts from "typescript";
import {
APP_DIR,
CONFIGURATION_DIR,
LIBRARY_IMPORT,
} from "../common/constants";
import... |
async removeInjection(fromClassId: string, toClassId: string) {
const sourceFile = this.getAppSourceFile(toClassId);
ast.removeImportDeclaration(sourceFile, `../${fromClassId}`);
const classNode = sourceFile.getClass(toClassId);
if (!classNode) {
throw new Error("Can not find class node");
... | {
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 | import * as fs from "fs";
import * as path from "path";
import * as chokidar from "chokidar";
import * as prettier from "prettier";
import { Node, Project, StructureKind } from "ts-morph";
import * as ts from "typescript";
import {
APP_DIR,
CONFIGURATION_DIR,
LIBRARY_IMPORT,
} from "../common/constants";
import... | (listeners: {
onClassChange: (e: ExtractedClass) => void;
onClassCreate: (e: ExtractedClass) => void;
onClassDelete: (name: string) => void;
}) {
await this.ensureConfigurationDir();
await this.ensureAppDir();
await this.ensureContainerEntry();
this.classes = await this.getClasses();
t... | initialize | identifier_name |
FilesManager.ts | import * as fs from "fs";
import * as path from "path";
import * as chokidar from "chokidar";
import * as prettier from "prettier";
import { Node, Project, StructureKind } from "ts-morph";
import * as ts from "typescript";
import {
APP_DIR,
CONFIGURATION_DIR,
LIBRARY_IMPORT,
} from "../common/constants";
import... | 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 | """
Specs for the various files in the CSS 3.0 schema
Each tuple of tuples defines the name, storage type, external format, and
position of each field.
The schema was taken from here:
http://jkmacc-lanl.github.io/pisces/data/Anderson1990.pdf
"""
affiliation = (
("net", 1, "c8", "aS", 1, 8),
("sta", 2, "c6... |
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 | // Copyright 2017-2018, Square, Inc.
package chain
import (
"fmt"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/square/spincycle/job-runner/runner"
"github.com/square/spincycle/proto"
rm "github.com/square/spincycle/request-manager"
"github.com/square/spincycle/retry"
)
var (
// Returned when ... |
// sendJL sends a job log to the Request Manager.
func (t *traverser) sendJL(job proto.Job, err error) {
jLogger := t.logger.WithFields(log.Fields{"job_id": job.Id})
jl := proto.JobLog{
RequestId: t.chain.RequestId(),
JobId: job.Id,
Name: job.Name,
Type: job.Type,
Try: t.chai... | {
// 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 | // Copyright 2017-2018, Square, Inc.
package chain
import (
"fmt"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/square/spincycle/job-runner/runner"
"github.com/square/spincycle/proto"
rm "github.com/square/spincycle/request-manager"
"github.com/square/spincycle/retry"
)
var (
// Returned when ... | (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 | // Copyright 2017-2018, Square, Inc.
package chain
import (
"fmt"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/square/spincycle/job-runner/runner"
"github.com/square/spincycle/proto"
rm "github.com/square/spincycle/request-manager"
"github.com/square/spincycle/retry"
)
var (
// Returned when ... |
jcStatus := proto.JobChainStatus{
RequestId: t.chain.RequestId(),
JobStatuses: status,
}
return jcStatus, nil
}
// -------------------------------------------------------------------------- //
// runJobs loops on the runJobChan, and runs each job that comes through the
// channel. When the job is done, it s... | {
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 | // Copyright 2017-2018, Square, Inc.
package chain
import (
"fmt"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/square/spincycle/job-runner/runner"
"github.com/square/spincycle/proto"
rm "github.com/square/spincycle/request-manager"
"github.com/square/spincycle/retry"
)
var (
// Returned when ... | }(job)
}
}
// sendJL sends a job log to the Request Manager.
func (t *traverser) sendJL(job proto.Job, err error) {
jLogger := t.logger.WithFields(log.Fields{"job_id": job.Id})
jl := proto.JobLog{
RequestId: t.chain.RequestId(),
JobId: job.Id,
Name: job.Name,
Type: job.Type,
Try: ... | random_line_split | |
table.go | // Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package leveldb
import (
"fmt"
"sort"
"sync/atomic"
"github.com/syndtr/goleveldb/leveldb/cache"
"github.com/syndtr/gol... |
// 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 | // Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package leveldb
import (
"fmt"
"sort"
"sync/atomic"
"github.com/syndtr/goleveldb/leveldb/cache"
"github.com/syndtr/gol... | }
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 | // Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package leveldb
import (
"fmt"
"sort"
"sync/atomic"
"github.com/syndtr/goleveldb/leveldb/cache"
"github.com/syndtr/gol... | () 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 | // Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package leveldb
import (
"fmt"
"sort"
"sync/atomic"
"github.com/syndtr/goleveldb/leveldb/cache"
"github.com/syndtr/gol... |
defer ch.Release()
return ch.Value().(*table.Reader).OffsetOf(key)
}
// Creates an iterator from the given table.
func (t *tOps) newIterator(f *tFile, slice *util.Range, ro *opt.ReadOptions) iterator.Iterator {
ch, err := t.open(f)
if err != nil {
return iterator.NewEmptyIterator(err)
}
iter := ch.Value().(*t... | {
return
} | conditional_block |
main.go | package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus/promhttp"
etcdraft "github.com/coreos/etcd/raft"
"gith... |
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 | package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus/promhttp"
etcdraft "github.com/coreos/etcd/raft"
"gith... |
func runetcd(
logger logrus.FieldLogger,
lis net.Listener, grpcServer *grpc.Server,
id uint64, ids []uint64, nodes []string,
lat *raft.Latency, event *raft.Event,
) {
peers := make([]etcdraft.Peer, len(ids))
for i, nid := range ids {
addr := nodes[i]
host, port, err := net.SplitHostPort(addr)
if err != n... | {
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 | package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus/promhttp"
etcdraft "github.com/coreos/etcd/raft"
"gith... | () {
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 | package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus/promhttp"
etcdraft "github.com/coreos/etcd/raft"
"gith... | }()
host, port, err := net.SplitHostPort(nodes[id-1])
if err != nil {
logger.Fatal(err)
}
p, _ := strconv.Atoi(port)
selflis := host + ":" + strconv.Itoa(p-100)
lishttp, err := net.Listen("tcp", selflis)
if err != nil {
logger.Fatal(err)
}
logger.Fatal(http.Serve(lishttp, node.Handler()))
}
func rung... | logger.Fatal(grpcServer.Serve(lis)) | random_line_split |
post_trees.rs | use std::collections::HashMap;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
use timely::dataflow::{Scope, Stream};
use colored::*;
use crate::event::{Event, ID};
use crate::operators::active_posts::StatUpdate;
use crate::operators::active_pos... | (&self, num_spaces: usize) {
let spaces = " ".repeat(num_spaces);
println!("{}---- ooo_events", spaces);
for (post_id, events) in self.ooo_events.iter() {
println!(
"{}{:?} -- \n{} {}",
spaces,
post_id,
spaces,
... | dump_ooo_events | identifier_name |
post_trees.rs | use std::collections::HashMap;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
use timely::dataflow::{Scope, Stream};
use colored::*;
use crate::event::{Event, ID};
use crate::operators::active_posts::StatUpdate;
use crate::operators::active_pos... |
/// process events that have `root_event` as their target post,
/// recursively process the newly inserted events
fn process_ooo_events(&mut self, root_event: &Event) {
let id = root_event.id().unwrap();
if let Some(events) = self.ooo_events.remove(&id) {
println!("-- {} for id... | {
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 | use std::collections::HashMap;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
use timely::dataflow::{Scope, Stream};
use colored::*;
use crate::event::{Event, ID};
use crate::operators::active_posts::StatUpdate;
use crate::operators::active_pos... | /// 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 | /*
* Minio Cloud Storage, (C) 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... | {
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 | /*
* Minio Cloud Storage, (C) 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... | (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 | /*
* Minio Cloud Storage, (C) 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... | }
// Create one lock server for every local storage rpc server.
func newLockServers(serverConfig serverCmdConfig) (lockServers []*lockServer) {
// Initialize posix storage API.
exports := serverConfig.disks
ignoredExports := serverConfig.ignoredDisks
// Save ignored disks in a map
skipDisks := make(map[string]bo... |
// Initialize distributed lock.
func initDistributedNSLock(mux *router.Router, serverConfig serverCmdConfig) {
lockServers := newLockServers(serverConfig)
registerStorageLockers(mux, lockServers) | random_line_split |
lock-rpc-server.go | /*
* Minio Cloud Storage, (C) 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... | 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 | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use deno_broadcast_channel::InMemoryBroadcastChannel;
use deno_cac... | (
&mut self,
module_specifier: &ModuleSpecifier,
) -> Result<(), AnyError> {
let id = self.preload_main_module(module_specifier).await?;
self.evaluate_module(id).await
}
fn wait_for_inspector_session(&mut self) {
if self.should_break_on_first_statement {
self
.js_runtime
... | execute_main_module | identifier_name |
worker.rs | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use deno_broadcast_channel::InMemoryBroadcastChannel;
use deno_cac... |
}
impl MainWorker {
pub fn bootstrap_from_options(
main_module: ModuleSpecifier,
permissions: PermissionsContainer,
options: WorkerOptions,
) -> Self {
let bootstrap_options = options.bootstrap.clone();
let mut worker = Self::from_options(main_module, permissions, options);
worker.bootstra... | {
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 | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use deno_broadcast_channel::InMemoryBroadcastChannel;
use deno_cac... |
let bootstrap_fn_global = {
let context = js_runtime.main_context();
let scope = &mut js_runtime.handle_scope();
let context_local = v8::Local::new(scope, context);
let global_obj = context_local.global(scope);
let bootstrap_str =
v8::String::new_external_onebyte_static(scope... | {
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 | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use deno_broadcast_channel::InMemoryBroadcastChannel;
use deno_cac... | 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 | # coding=utf-8
"""
Forum views
"""
from __future__ import absolute_import, print_function
from datetime import datetime, date
from itertools import groupby
from urllib import quote
import sqlalchemy as sa
from sqlalchemy.orm import joinedload
from werkzeug.exceptions import NotFound, BadRequest
from flask import (
... |
attachments_to_remove.append(self.obj.attachments[idx])
for att in attachments_to_remove:
session.delete(att)
for handle in request.form.getlist('attachments'):
fileobj = uploads.get_file(current_user, handle)
if fileobj is None:
continue
meta = uploads.get_metadata(cu... | continue | conditional_block |
views.py | # coding=utf-8
"""
Forum views
"""
from __future__ import absolute_import, print_function
from datetime import datetime, date
from itertools import groupby
from urllib import quote
import sqlalchemy as sa
from sqlalchemy.orm import joinedload
from werkzeug.exceptions import NotFound, BadRequest
from flask import (
... | (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 | # coding=utf-8
"""
Forum views
"""
from __future__ import absolute_import, print_function
from datetime import datetime, date
from itertools import groupby
from urllib import quote
import sqlalchemy as sa
from sqlalchemy.orm import joinedload
from werkzeug.exceptions import NotFound, BadRequest
from flask import (
... | session.delete(att)
for handle in request.form.getlist('attachments'):
fileobj = uploads.get_file(current_user, handle)
if fileobj is None:
continue
meta = uploads.get_metadata(current_user, handle)
name = meta.get('filename', handle)
mimetype = meta.get('mimetype', Non... | attachments_to_remove.append(self.obj.attachments[idx])
for att in attachments_to_remove: | random_line_split |
views.py | # coding=utf-8
"""
Forum views
"""
from __future__ import absolute_import, print_function
from datetime import datetime, date
from itertools import groupby
from urllib import quote
import sqlalchemy as sa
from sqlalchemy.orm import joinedload
from werkzeug.exceptions import NotFound, BadRequest
from flask import (
... |
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 | /*
Copyright 2023.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed un... | oldVal, oldOk := event.ObjectOld.(*corev1.Node).Status.Allocatable[NvidiaGPU]
newVal, newOk := event.ObjectNew.(*corev1.Node).Status.Allocatable[NvidiaGPU]
return oldOk && newOk && oldVal != newVal
},
DeleteFunc: func(event event.DeleteEvent) bool {
return hasGPU(event.Object)
},
})).
Comp... | UpdateFunc: func(event event.UpdateEvent) bool { | random_line_split |
gpu_controller.go | /*
Copyright 2023.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed un... |
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 | /*
Copyright 2023.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed un... |
func (r *GpuReconciler) initGPUInfoCM(ctx context.Context, clientSet *kubernetes.Clientset) error {
// filter for nodes that have GPU
req1, _ := labels.NewRequirement(NvidiaGPUProduct, selection.Exists, []string{})
req2, _ := labels.NewRequirement(NvidiaGPUMemory, selection.Exists, []string{})
selector := labels.... | {
/*
"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 | /*
Copyright 2023.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed un... | (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 | var hive_service_types = require('shib/engines/hiveserver/hive_service_types'),
hive_metastore_types = require('shib/engines/hiveserver/hive_metastore_types'),
queryplan_types = require('shib/engines/hiveserver/queryplan_types');
var chars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', ... | ];
var partsNum = Number(matched[2]);
var parts = [];
for (var i = 0; i < partsNum; i++) {
var current_part = parent_part + fieldname + '=' + i;
if (children_label) {
parts = parts.concat(generate_subtree(children_label, current_part));
}
else {
parts.push(current_part);
}
}
re... | 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 hive_service_types = require('shib/engines/hiveserver/hive_service_types'),
hive_metastore_types = require('shib/engines/hiveserver/hive_metastore_types'),
queryplan_types = require('shib/engines/hiveserver/queryplan_types');
var chars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', ... | 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()) + pad(d2.getMi... | .na | identifier_name |
ThriftHiveMock.js | var hive_service_types = require('shib/engines/hiveserver/hive_service_types'),
hive_metastore_types = require('shib/engines/hiveserver/hive_metastore_types'),
queryplan_types = require('shib/engines/hiveserver/queryplan_types');
var chars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', ... | = 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()) + pad(d2.getMinutes());
case 'id':
re... |
case 'date':
var d1 | identifier_body |
ThriftHiveMock.js | var hive_service_types = require('shib/engines/hiveserver/hive_service_types'),
hive_metastore_types = require('shib/engines/hiveserver/hive_metastore_types'),
queryplan_types = require('shib/engines/hiveserver/queryplan_types');
var chars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', ... | 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 | // Copyright (c) 2015-2017 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wtxmgr
import (
"fmt"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"gi... | return nil, err
}
pkScripts = append(pkScripts, pkScript)
continue
}
_, credKey := existsUnspent(ns, prevOut)
if credKey != nil {
k := extractRawCreditTxRecordKey(credKey)
v = existsRawTxRecord(ns, k)
pkScript, err := fetchRawTxRecordPkScript(k, v,
prevOut.Index)
if err !... | }
pkScript, err := fetchRawTxRecordPkScript(
prevOut.Hash[:], v, prevOut.Index)
if err != nil { | random_line_split |
query.go | // Copyright (c) 2015-2017 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wtxmgr
import (
"fmt"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"gi... |
var blockIter blockIterator
var advance func(*blockIterator) bool
if begin < end {
// Iterate in forwards order
blockIter = makeReadBlockIterator(ns, begin)
advance = func(it *blockIterator) bool {
if !it.next() {
return false
}
return it.elem.Height <= end
}
} else {
// Iterate in backward... | {
end = int32(^uint32(0) >> 1)
} | conditional_block |
query.go | // Copyright (c) 2015-2017 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wtxmgr
import (
"fmt"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"gi... |
// 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 | // Copyright (c) 2015-2017 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wtxmgr
import (
"fmt"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"gi... | (ns walletdb.ReadBucket, begin, end int32,
f func([]TxDetails) (bool, error)) error {
var addedUnmined bool
if begin < 0 {
brk, err := s.rangeUnminedTransactions(ns, f)
if err != nil || brk {
return err
}
addedUnmined = true
}
brk, err := s.rangeBlockTransactions(ns, begin, end, f)
if err == nil && !... | RangeTransactions | identifier_name |
settings.py | # Django settings for isbio project.
# from configurations import Settings
import logging
import os
import socket
import time
from datetime import datetime
from utilz import git, TermColoring, recur, recur_rec, get_key, import_env, file_content, is_host_online, test_url, \
magic_const, get_md5
ENABLE_DATADOG = False... |
PROJECT_FHRB_PM_PATH = '/%s/fhrb_pm/' % PROJECT_FOLDER_NAME
JDBC_BRIDGE_PATH = PROJECT_FHRB_PM_PATH + 'bin/start-jdbc-bridge' # Every other path has a trailing /
TEMP_FOLDER = SOURCE_ROOT + 'tmp/'
####
# 'db' folder, containing : reports, scripts, jobs, datasets, pipelines, upload_temp
####
DATA_TEMPLATES_FN = 'moul... | PROJECT_FOLDER = '/%s/' % PROJECT_FOLDER_NAME
R_ENGINE_PATH = PROD_PATH + R_ENGINE_SUB_PATH # FIXME Legacy | conditional_block |
settings.py | # Django settings for isbio project.
# from configurations import Settings
import logging
import os
import socket
import time
from datetime import datetime
from utilz import git, TermColoring, recur, recur_rec, get_key, import_env, file_content, is_host_online, test_url, \
magic_const, get_md5
ENABLE_DATADOG = False... |
# FIXME obsolete
if os.path.isfile('running'):
# First time
print '__breeze__started__'
logging.info('__breeze__started__')
os.remove('running')
else:
make_run_file()
# Second time
time.sleep(1)
print '__breeze__load/reload__'
logging.info('__breeze__load/reload__')
print 'source home : ' + SOURCE_ROOT
lo... | f = open('running', 'w+')
f.write(str(datetime.now().strftime(USUAL_DATE_FORMAT)))
f.close() | identifier_body |
settings.py | # Django settings for isbio project.
# from configurations import Settings
import logging
import os
import socket
import time
from datetime import datetime
from utilz import git, TermColoring, recur, recur_rec, get_key, import_env, file_content, is_host_online, test_url, \
magic_const, get_md5
ENABLE_DATADOG = False... | 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 | # Django settings for isbio project.
# from configurations import Settings
import logging
import os
import socket
import time
from datetime import datetime
from utilz import git, TermColoring, recur, recur_rec, get_key, import_env, file_content, is_host_online, test_url, \
magic_const, get_md5
ENABLE_DATADOG = False... | (breeze_folder=BREEZE_FOLDER):
return PROJECT_FOLDER + breeze_folder
| project_folder_path | identifier_name |
sign-up.js | import react, { useState, useRef, useEffect } from "react";
import styled from "styled-components";
import { useSelector, useDispatch } from "react-redux";
import { userLogin } from "../../actions/index";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTimes } from "@fortawesome/free-solid-... | ) : 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 | import react, { useState, useRef, useEffect } from "react";
import styled from "styled-components";
import { useSelector, useDispatch } from "react-redux";
import { userLogin } from "../../actions/index";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTimes } from "@fortawesome/free-solid-... | </Logo>
<InputBox>
<EmailIcon>
<Align>
<EmailInput
name="email"
value={user.email}
placeholder="email"
onChange={handleChange}
/>
<EmailButton type="button" onClick={() => send(user.... | 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 | import react, { useState, useRef, useEffect } from "react";
import styled from "styled-components";
import { useSelector, useDispatch } from "react-redux";
import { userLogin } from "../../actions/index";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTimes } from "@fortawesome/free-solid-... | 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 | #-*- coding:utf-8 -*-
import model
import input
import os
import numpy as np
import argparse
import sys
import tensorflow as tf
import aug
import numpy as np
import random
from PIL import Image
import time
import pickle
parser =argparse.ArgumentParser()
#parser.add_argument('--saves' , dest='should_save_model' , act... | ter):
if step % ckpt==0:
""" #### testing ### """
print '### Testing ###'
test_fetches = [ accuracy_op, loss_op, pred_op , lr_op]
val_acc_mean , val_loss_mean , pred_all = [] , [] , []
for i in range(share): #여기서 테스트 셋을 sess.run()할수 있게 쪼갭니다
test_feedDict = {x_: te... | sys.stdout.write(msg)
sys.stdout.flush()
count_trainable_params()
for step in range(max_i | identifier_body |
run_this_code_CACSSEOUL.py | #-*- coding:utf-8 -*-
import model
import input
import os
import numpy as np
import argparse
import sys
import tensorflow as tf
import aug
import numpy as np
import random
from PIL import Image
import time
import pickle
parser =argparse.ArgumentParser()
#parser.add_argument('--saves' , dest='should_save_model' , act... | an(np.asarray(val_acc_mean))
val_loss_mean=np.mean(np.asarray(val_loss_mean))
if val_acc_mean > max_acc: #best acc
max_acc=val_acc_mean
print 'max acc : {}'.format(max_acc)
best_acc_folder=os.path.join( best_acc_root, 'step_{}_acc_{}'.format(step , max_acc))
... | 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 | #-*- coding:utf-8 -*-
import model
import input
import os
import numpy as np
import argparse
import sys
import tensorflow as tf
import aug
import numpy as np
import random
from PIL import Image
import time
import pickle
parser =argparse.ArgumentParser()
#parser.add_argument('--saves' , dest='should_save_model' , act... | rmat(step, max_iter)
sys.stdout.write(msg)
sys.stdout.flush()
count_trainable_params()
for step in range(max_iter):
if step % ckpt==0:
""" #### testing ### """
print '### Testing ###'
test_fetches = [ accuracy_op, loss_op, pred_op , lr_op]
val_acc_mean , val_loss_mean , pred... | ess {}/{}'.fo | identifier_name |
run_this_code_CACSSEOUL.py | #-*- coding:utf-8 -*-
import model
import input
import os
import numpy as np
import argparse
import sys
import tensorflow as tf
import aug
import numpy as np
import random
from PIL import Image
import time
import pickle
parser =argparse.ArgumentParser()
#parser.add_argument('--saves' , dest='should_save_model' , act... | 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 | import requests
import json
import io
import random
import time
import re
import pyDes
import base64
import uuid
import sys
import os
import hashlib
from Crypto.Cipher import AES
class DailyCP:
def __init__(self, schoolName="北部湾大学"):
self.key = "ST83=@XV" # dynamic when app update
self.session = ... | username}&pwdEncrypt2=pwdEncryptSalt".format(
username=username), parseJson=False).text
return ret == "true"
def loginAuthserver(self, username, password, captcha=""):
ret = self.request(self.loginUrl, parseJson=False)
body = dict(re.findall(
r'''<input type="hidden"... | 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 | import requests
import json
import io
import random
import time
import re
import pyDes
import base64
import uuid
import sys
import os
import hashlib
from Crypto.Cipher import AES
class DailyCP:
def __init__(self, schoolName="北部湾大学"):
self.key = "ST83=@XV" # dynamic when app update
self.session = ... | 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 | import requests
import json
import io
import random
import time
import re
import pyDes
import base64
import uuid
import sys
import os
import hashlib
from Crypto.Cipher import AES
class DailyCP:
def __init__(self, schoolName="北部湾大学"):
self.key = "ST83=@XV" # dynamic when app update
self.session = ... | (
"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 | import requests
import json
import io
import random
import time
import re
import pyDes
import base64
import uuid
import sys
import os
import hashlib
from Crypto.Cipher import AES
class DailyCP:
def __init__(self, schoolName="北部湾大学"):
self.key = "ST83=@XV" # dynamic when app update
self.session = ... | # By:AUST HACKER
# 2020/5/20 重要更新:修复登录过程,移除验证码(不需要),优化代码格式,感谢giteee及时反馈。
# 2020/5/28 更改为使用自动获取学校URL的方式,更改为使用参数形式,添加另一种登录形式AuthServer的支持(已完成但未测试)。感谢柠火的反馈。
# 2020/6/1 修复BUG,发现AuthServer的登录方式每个学校都不一样。支持任意表单内容自定义(详情见输出信息和formdb/1129.json)。感谢涅灵的反馈。
# 2020/6/2 AuthServer的登录网址不再使用硬编码的方式,理论上能支持所有学校了吧?感谢涅灵的反馈。
# 2020/6/17 修复cr... | app.autoComplete(sys.argv[4], sys.argv[5])
# Author:HuangXu,FengXinYang,ZhouYuYang. | random_line_split |
yolo.py | import os
import cv2
import numpy as np
import ast
from timeit import default_timer as timer
from keras import backend as K
from keras.layers import Input
from PIL import Image, ImageFont, ImageDraw
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
from model import evaluation, yolo_body
... |
else:
pts = np.array(right_clicks[np.sum(polygon_list[0:poly_index], dtype=int):np.sum(polygon_list[0:poly_index], dtype=int) + len(right_clicks)],np.int32)
cv2.polylines(params, [pts], False, (R,G,B), thickness=2)
def color_result(value,th_low,th_high):
th_mid=(th_low+th_high)/2
... | pts=np.array(right_clicks) | conditional_block |
yolo.py | import os
import cv2
import numpy as np
import ast
from timeit import default_timer as timer
from keras import backend as K
from keras.layers import Input
from PIL import Image, ImageFont, ImageDraw
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
from model import evaluation, yolo_body
... | (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 | import os
import cv2
import numpy as np
import ast
from timeit import default_timer as timer
from keras import backend as K
from keras.layers import Input
from PIL import Image, ImageFont, ImageDraw
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
from model import evaluation, yolo_body
... | 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 | import os
import cv2
import numpy as np
import ast
from timeit import default_timer as timer
from keras import backend as K
from keras.layers import Input
from PIL import Image, ImageFont, ImageDraw
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
from model import evaluation, yolo_body
... |
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 crate::alias::create_alias;
use crate::archive::{self, extract::Error as ExtractError, extract::Extract};
use crate::config::FrumConfig;
use crate::input_version::InputVersion;
use crate::outln;
use crate::version::Version;
use crate::version_file::get_user_version_for_directory;
use anyhow::Result;
use colored::Co... | ;
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 | use crate::alias::create_alias;
use crate::archive::{self, extract::Error as ExtractError, extract::Extract};
use crate::config::FrumConfig;
use crate::input_version::InputVersion;
use crate::outln;
use crate::version::Version;
use crate::version_file::get_user_version_for_directory;
use anyhow::Result;
use colored::Co... | () {
let config = FrumConfig {
base_dir: Some(tempdir().unwrap().path().to_path_buf()),
..Default::default()
};
Install {
version: Some(InputVersion::Full(Version::Semver(
semver::Version::parse("2.6.4").unwrap(),
))),
... | test_install_default_version | identifier_name |
install.rs | use crate::alias::create_alias;
use crate::archive::{self, extract::Error as ExtractError, extract::Extract};
use crate::config::FrumConfig;
use crate::input_version::InputVersion;
use crate::outln;
use crate::version::Version;
use crate::version_file::get_user_version_for_directory;
use anyhow::Result; | 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 crate::alias::create_alias;
use crate::archive::{self, extract::Error as ExtractError, extract::Extract};
use crate::config::FrumConfig;
use crate::input_version::InputVersion;
use crate::outln;
use crate::version::Version;
use crate::version_file::get_user_version_for_directory;
use anyhow::Result;
use colored::Co... |
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 | // Copyright 2019+ Klaus Post. All rights reserved.
// License information can be found in the LICENSE file.
// Based on work by Yann Collet, released under BSD License.
package zstd
import (
"errors"
"fmt"
"math"
)
const (
// For encoding we only support up to
maxEncTableLog = 8
maxEncTablesize = 1 << ma... | (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 | // Copyright 2019+ Klaus Post. All rights reserved.
// License information can be found in the LICENSE file.
// Based on work by Yann Collet, released under BSD License.
package zstd
import (
"errors"
"fmt"
"math"
)
const (
// For encoding we only support up to
maxEncTableLog = 8
maxEncTablesize = 1 << ma... |
// normalizeCount will normalize the count of the symbols so
// the total is equal to the table size.
// If successful, compression tables will also be made ready.
func (s *fseEncoder) normalizeCount(length int) error {
if s.reUsed {
return nil
}
s.optimalTableLog(length)
var (
tableLog = s.actualTab... | {
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 | // Copyright 2019+ Klaus Post. All rights reserved.
// License information can be found in the LICENSE file.
// Based on work by Yann Collet, released under BSD License.
package zstd
import (
"errors"
"fmt"
"math"
)
const (
// For encoding we only support up to
maxEncTableLog = 8
maxEncTablesize = 1 << ma... | 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 | // Copyright 2019+ Klaus Post. All rights reserved.
// License information can be found in the LICENSE file.
// Based on work by Yann Collet, released under BSD License.
package zstd
import (
"errors"
"fmt"
"math"
)
const (
// For encoding we only support up to
maxEncTableLog = 8
maxEncTablesize = 1 << ma... |
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 | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// This module tests the property that pkg_resolver does not enter a bad
/// state (successfully handles retries) when the TUF server errors while
/// ser... |
#[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 | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// This module tests the property that pkg_resolver does not enter a bad
/// state (successfully handles retries) when the TUF server errors while
/// ser... | .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 | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// This module tests the property that pkg_resolver does not enter a bad
/// state (successfully handles retries) when the TUF server errors while
/// ser... | () {
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 | // Copyright 2021 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | 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 | // Copyright 2021 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | (&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 | // Copyright 2021 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
fn cancel(&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) {
... | {
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 | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use proc_macro2::Ident;
use proc_macro2::Span;
use proc_macro2::TokenStream;
use quote::quote;
use quote::ToToken... | (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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.