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
bot.js
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // bot.js is your main bot dialog entry point for handling activity types // Import required Bot Builder const { ActionTypes, ActivityTypes, CardFactory } = require('botbuilder'); const { LuisRecognizer } = require('botbui...
this.helpMessage = `You can type "send <recipient_email>" to send an email, "recent" to view recent unread mail,` + ` "me" to see information about your, or "help" to view the commands` + ` again. For others LUIS displays intent with score.`; // Create a DialogSet that contains ...
// Instructions for the user with information about commands that this bot may handle.
random_line_split
bot.js
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // bot.js is your main bot dialog entry point for handling activity types // Import required Bot Builder const { ActionTypes, ActivityTypes, CardFactory } = require('botbuilder'); const { LuisRecognizer } = require('botbui...
await dc.continueDialog(); if (!dc.context.responded) { await dc.beginDialog(this._graphDialogId); } } } ; async promptStep(step) { const activity = step.context.activity; if (activity.type === ActivityTypes.Message && !(/\d{6...
{ //console.log(dc); switch (dc.context.activity.text.toLowerCase()) { case 'signout': case 'logout': case 'signoff': case 'logoff': // The bot adapter encapsulates the authentication processes and sends // activities to from the Bot Connector Serv...
identifier_body
parser_manager.py
FocusStack from CrystalMatch.dls_imagematch import logconfig from CrystalMatch.dls_imagematch.service import readable_config_dir from CrystalMatch.dls_imagematch.version import VersionHandler from CrystalMatch.dls_imagematch.service.readable_config_dir import ReadableConfigDir from CrystalMatch.dls_util.shape import P...
def get_formulatrix_image_path(self): path = self.get_args().Formulatrix_image.name self._check_is_file(path) return path def get_to_json(self): return self.get_args().to_json def get_job_id(self): return self.get_args().job # returns an error if the focused ...
return self.images_to_stack
identifier_body
parser_manager.py
FocusStack from CrystalMatch.dls_imagematch import logconfig from CrystalMatch.dls_imagematch.service import readable_config_dir from CrystalMatch.dls_imagematch.version import VersionHandler from CrystalMatch.dls_imagematch.service.readable_config_dir import ReadableConfigDir from CrystalMatch.dls_util.shape import P...
(self): return self.get_args().to_json def get_job_id(self): return self.get_args().job # returns an error if the focused image is not saved # may want to change this for saving done later def get_focused_image_path(self): focusing_path = abspath(self.get_args().beamline_stack_...
get_to_json
identifier_name
parser_manager.py
FocusStack from CrystalMatch.dls_imagematch import logconfig from CrystalMatch.dls_imagematch.service import readable_config_dir from CrystalMatch.dls_imagematch.version import VersionHandler from CrystalMatch.dls_imagematch.service.readable_config_dir import ReadableConfigDir from CrystalMatch.dls_util.shape import P...
type=file, help='Image file from the Formulatrix - selected_point should correspond to co-ordinates on ' 'this image.') else: parser.add_argument('Formulatrix_image', metavar="For...
metavar="Formulatrix_image_path",
random_line_split
parser_manager.py
FocusStack from CrystalMatch.dls_imagematch import logconfig from CrystalMatch.dls_imagematch.service import readable_config_dir from CrystalMatch.dls_imagematch.version import VersionHandler from CrystalMatch.dls_imagematch.service.readable_config_dir import ReadableConfigDir from CrystalMatch.dls_util.shape import P...
return selected_points def get_focused_image(self): focusing_path = abspath(self.get_args().beamline_stack_path) if "." not in focusing_path: files = self._sort_files_according_to_names(focusing_path) # Run focusstack stacker = FocusStack(files, self.get...
point_string = point_string.strip('()') match_results = point_expected_format.match(point_string) # Check the regex matches the entire string # DEV NOTE: can use re.full_match in Python v3 if match_results is not None and match_results.span()[1] == len(poi...
conditional_block
certificate_fetcher.go
(sub dir name) -> cert updateCheckInterval int forceUpdateInterval float64 mu *sync.RWMutex CertName string KeyName string initPollDone bool initPollMu *sync.RWMutex } func (fetcher *RCertificateFetcher) checkIfInitPollDone() bool
func (fetcher *RCertificateFetcher) setInitPollDone() { fetcher.initPollMu.Lock() fetcher.initPollDone = true fetcher.initPollMu.Unlock() } func (fetcher *RCertificateFetcher) FetchCertificates(lbMeta *LBMetadata, isDefaultCert bool) ([]*config.Certificate, error) { // fetch certificates either from mounted cert...
{ isDone := false fetcher.initPollMu.RLock() isDone = fetcher.initPollDone fetcher.initPollMu.RUnlock() return isDone }
identifier_body
certificate_fetcher.go
name (sub dir name) -> cert updateCheckInterval int forceUpdateInterval float64 mu *sync.RWMutex CertName string KeyName string initPollDone bool initPollMu *sync.RWMutex } func (fetcher *RCertificateFetcher) checkIfInitPollDone() bool { isDone := false fetcher.initPollMu.RLock() isDone = fetcher.ini...
} else { logrus.Infof("LookForCertUpdates: Force Update triggered, updating the cache from cert dir %v", fetcher.CertDir) } //there is some change, refresh certs fetcher.mu.Lock() fetcher.CertsCache = make(map[string]*config.Certificate) for path, newCert := range fetcher.temp...
} else { //compare with existing cache if forceUpdate || !reflect.DeepEqual(fetcher.CertsCache, fetcher.tempCertsMap) { if !forceUpdate { logrus.Infof("LookForCertUpdates: Found an update in cert dir %v, updating the cache", fetcher.CertDir)
random_line_split
certificate_fetcher.go
(sub dir name) -> cert updateCheckInterval int forceUpdateInterval float64 mu *sync.RWMutex CertName string KeyName string initPollDone bool initPollMu *sync.RWMutex } func (fetcher *RCertificateFetcher) checkIfInitPollDone() bool { isDone := false fetcher.initPollMu.RLock() isDone = fetcher.initPoll...
(certID string) (*config.Certificate, error) { if certID == "" { return nil, nil } opts := client.NewListOpts() opts.Filters["id"] = certID opts.Filters["removed_null"] = "1" cert, err := fetcher.Client.Certificate.ById(certID) if err != nil { return nil, fmt.Errorf("Coudln't get certificate by id [%s]. Err...
FetchRancherCertificate
identifier_name
certificate_fetcher.go
for _, certID := range lbMeta.CertificateIDs { cert, err := fetcher.FetchRancherCertificate(certID) if err != nil { return nil, err } certs = append(certs, cert) } } else { if lbMeta.DefaultCertificateID != "" { var err error defaultCert, err = fetcher.FetchRancherCertificate(lbM...
{ return nil, fmt.Errorf("File %s pointed by symlink %s does not exist, error: %v", targetPath, absFilePath, err) }
conditional_block
ProteinRNN.py
input_ids = tf.one_hot(input_ids,21) input_ids = ops.convert_to_tensor(input_ids, dtype=tf.float32) # Run the model. predicted_logits = self.model(inputs=input_ids) # Only use the last prediction. predicted_logits = predicted_logits / self.temperature # Apply the prediction m...
seq.append(ord(charList[i]) - ord('A') + 1) # grab the labels and convert seq into a one hot encoding of 21 if seq[len(seq)-1] > 20: seq[len(seq)-1] = 20 # get one hot tensor and test label label = seq[len(seq)-1] seq = tf.one_hot(seq,21) test.append(seq[:len(seq)-1]) testlabel.append(l...
testlabel = [] test = [] temp = line.split() charList = list(temp) seq = [] for i in range(50): # convert each letter into an int, randomly flip a char or more # these 3 if conditions randomly flip a character letter to find dependeny, can comment out either or for experimentation if i == 15: ...
identifier_body
ProteinRNN.py
input_ids = tf.one_hot(input_ids,21) input_ids = ops.convert_to_tensor(input_ids, dtype=tf.float32) # Run the model. predicted_logits = self.model(inputs=input_ids) # Only use the last prediction. predicted_logits = predicted_logits / self.temperature # Apply the prediction m...
(line): testlabel = [] test = [] temp = line.split() charList = list(temp) seq = [] for i in range(50): # convert each letter into an int, randomly flip a char or more # these 3 if conditions randomly flip a character letter to find dependeny, can comment out either or for experimentation if ...
FlipChars
identifier_name
ProteinRNN.py
.append(0) # grab the labels and convert seq into a one hot encoding of 21 seq = tf.one_hot(seq,21) test.append(seq[:len(seq)-1]) testlabel.append(label) seq = [] else: for i in range(100): # convert each letter into an int ...
continue
conditional_block
ProteinRNN.py
input_ids = tf.one_hot(input_ids,21) input_ids = ops.convert_to_tensor(input_ids, dtype=tf.float32) # Run the model. predicted_logits = self.model(inputs=input_ids) # Only use the last prediction. predicted_logits = predicted_logits / self.temperature # Apply the prediction m...
# line is the temp[0] pass as an argument here def FlipChars(line): testlabel = [] test = [] temp = line.split() charList = list(temp) seq = [] for i in range(50): # convert each letter into an int, randomly flip a char or more # these 3 if conditions randomly flip a character letter to find depe...
# convert made up sequence to a tensor
random_line_split
accounts.go
callGasLimit uint64 } func New(chain *chain.Chain, stateCreator *state.Creator, callGasLimit uint64) *Accounts { return &Accounts{ chain, stateCreator, callGasLimit, } } func (a *Accounts) getCode(addr polo.Address, stateRoot polo.Bytes32) ([]byte, error) { state, err := a.stateCreator.NewState(stateRoot) ...
Beneficiary: header.Beneficiary(), Signer: signer, Number: header.Number(), Time: header.Timestamp(), GasLimit: header.GasLimit(), TotalScore: header.TotalScore()}) results = make(BatchCallResults, 0) vmout := make(chan *runtime.Output, 1) for i, clause := range clauses { exe...
&xenv.BlockContext{
random_line_split
accounts.go
{ return polo.Bytes32{}, err } storage := state.GetStorage(addr, key) if err := state.Err(); err != nil { return polo.Bytes32{}, err } return storage, nil } func (a *Accounts) handleGetAccount(w http.ResponseWriter, req *http.Request) error { addr, err := polo.ParseAddress(mux.Vars(req)["address"]) if err ...
revision == "" || revision == "best" { return a.chain.BestBlock().Header(), nil } if len(revision) == 66 || len(revision) == 64 { blockID, err := polo.ParseBytes32(revision) if err != nil { return nil, utils.BadRequest(errors.WithMessage(err, "revision")) } h, err := a.chain.GetBlockHeader(blockID) if...
identifier_body
accounts.go
GasLimit uint64 } func New(chain *chain.Chain, stateCreator *state.Creator, callGasLimit uint64) *Accounts { return &Accounts{ chain, stateCreator, callGasLimit, } } func (a *Accounts) getCode(addr polo.Address, stateRoot polo.Bytes32) ([]byte, error) { state, err := a.stateCreator.NewState(stateRoot) if er...
esults = append(results, convertCallResultWithInputGas(out, gas)) if out.VMErr != nil { return results, nil } gas = out.LeftOverGas } } return results, nil } func (a *Accounts) handleBatchCallData(batchCallData *BatchCallData) (gas uint64, gasPrice *big.Int, caller *polo.Address, clauses []*tx.Clause,...
return nil, err } r
conditional_block
accounts.go
callGasLimit uint64 } func New(chain *chain.Chain, stateCreator *state.Creator, callGasLimit uint64) *Accounts { return &Accounts{ chain, stateCreator, callGasLimit, } } func (a *Accounts) getCode(addr polo.Address, stateRoot polo.Bytes32) ([]byte, error) { state, err := a.stateCreator.NewState(stateRoot) ...
w http.ResponseWriter, req *http.Request) error { addr, err := polo.ParseAddress(mux.Vars(req)["address"]) if err != nil { return utils.BadRequest(errors.WithMessage(err, "address")) } h, err := a.handleRevision(req.URL.Query().Get("revision")) if err != nil { return err } tokenAddress := req.URL.Query().Ge...
andleGetAccount(
identifier_name
main.rs
>, } #[derive(StructOpt, Debug)] #[structopt(name = "client")] struct Opt { /// Address to connect to #[structopt(long="url", default_value="quic://localhost:4433")] url: Url, /// TLS certificate in PEM format #[structopt(parse(from_os_str), short="c", long="cert", default_value="./certs/cert.pem"...
#[tokio::main] async fn run(options: Opt) -> Result<(), Box<dyn std::error::Error>> { let path = std::env::current_dir().unwrap(); println!("The current directory is {}", path.display()); tracing::subscriber::set_global_default( tracing_subscriber::FmtSubscriber::builder() .with_max_l...
{ let opt = Opt::from_args(); run(opt) }
identifier_body
main.rs
>, } #[derive(StructOpt, Debug)] #[structopt(name = "client")] struct Opt { /// Address to connect to #[structopt(long="url", default_value="quic://localhost:4433")] url: Url, /// TLS certificate in PEM format #[structopt(parse(from_os_str), short="c", long="cert", default_value="./certs/cert.pem"...
( mut state: ResMut<RequestTileOnConnectedState>, mut sender: ResMut<Events<SendEvent>>, receiver: ResMut<Events<ReceiveEvent>> ) { for evt in state.event_reader.iter(&receiver) { if let ReceiveEvent::Connected(connection, _) = evt { info!("Requesting tile because connected to server...
request_tile_on_connected
identifier_name
main.rs
_value="./certs/cert.pem")] cert: PathBuf, /// Accept any TLS certificate from the server even if it is invalid #[structopt(short="a", long="accept_any")] accept_any_cert: bool } fn main() -> Result<(), Box<dyn std::error::Error>> { let opt = Opt::from_args(); run(opt) } #[tokio::main] async ...
if !in_rect && ax.is_finite() && ay.is_finite() { mcam.right = Some(ax); mcam.forward = Some(ay); } else {
random_line_split
main.rs
, url, cert, accept_any_cert: options.accept_any_cert }); app.init_resource::<PingResponderState>(); app.add_system(respond_to_pings.system()); app.init_resource::<NetEventLoggerState>(); app.add_system(log_net_events.system()); app.init_resource::<MoveCam>(); app....
{ acts.send(CameraBPAction::MoveRight(Some(w))) }
conditional_block
rzline.py
', '海口市', '广州市', '深圳市', ] # 查询日期 quoteDate = time.mktime(time.strptime(Today, '%Y%m%d')) quoteDate = str(quoteDate).replace('.', '') + '00' quoteType_dict = { 'e': '电票', 'se': '小电票', # 's': '纸票', #...
# formdata['page'] += 1 # base_url = 'http://www.rzline.com/web/mobuser/market/quoteShow' # url = base_url + '&page=' + str(formdata['page']) # yield scrapy.Request( # url=url, # callback=self.parse_id, ...
# formdata = response.meta['data']
random_line_split
rzline.py
'海口市', '广州市', '深圳市', ] # 查询日期 quoteDate = time.mktime(time.strptime(Today, '%Y%m%d')) quoteDate = str(quoteDate).replace('.', '') + '00' quoteType_dict = { 'e': '电票', 'se': '小电票', # 's': '纸票', # '...
f data_list: for i in data_list: user_id = i['orgUserId'] company = i['orgSimpleName'] price_list = i['quotePriceDetailList'] if i['quotePriceDetailList'] else [] if len(price_list): formdata1 = copy...
i
identifier_name
rzline.py
'海口市', '广州市', '深圳市', ] # 查询日期 quoteDate = time.mktime(time.strptime(Today, '%Y%m%d')) quoteDate = str(quoteDate).replace('.', '') + '00' quoteType_dict = { 'e': '电票', 'se': '小电票', # 's': '纸票', # '...
flag = 1 city = response.meta['city'] data = response.body.decode() json_data = json.loads(data) id_url = 'http://www.rzline.com/web/mobuser/market/quoteDetail' print('当前页数:{}'.format(response.meta['data']['page'])) print('data=', response.meta['data']) t...
city}, ) def parse_id(self, response):
conditional_block
rzline.py
'海口市', '广州市', '深圳市', ] # 查询日期 quoteDate = time.mktime(time.strptime(Today, '%Y%m%d')) quoteDate = str(quoteDate).replace('.', '') + '00' quoteType_dict = { 'e': '电票', 'se': '小电票', # 's': '纸票', # '...
ta'] if data_list: for i in data_list: user_id = i['orgUserId'] company = i['orgSimpleName'] price_list = i['quotePriceDetailList'] if i['quotePriceDetailList'] else [] if len(price_list): ...
pass url = base_url + '&page=' + str(formdata['page']) yield scrapy.Request( url=url, dont_filter=True, callback=self.parse_id, errback=self.hand_error, meta={'data': formdata, 'heade...
identifier_body
mod.rs
er) = if fuzzy_terms.is_empty() { if exact_terms.is_empty() { (query.into(), QueryType::StartWith, UsageMatcher::default()) } else { ( exact_terms[0].text.clone(), QueryType::Exact, UsageMatcher::new(exact_terms, inverse_terms), ...
rent_lines = self .current_usages .as_ref() .unwrap_or(&self.cached_results.usages); if current_lines.is_empty() { return Ok(()); } let input = ctx.vim.input_get().await?; let lnum = ctx.vim.display_getcurlnum().await?; // lnum i...
identifier_body
mod.rs
the same. /// - the new query is a subset of last query. fn is_superset(&self, other: &Self) -> bool { self.keyword == other.keyword && self.query_type == other.query_type && self.usage_matcher.is_superset(&other.usage_matcher) } } /// Parses the raw user input and returns ...
// otherwise restore the fuzzy query as the keyword we are going to search. let (keyword, query_type, usage_matcher) = if fuzzy_terms.is_empty() { if exact_terms.is_empty() { (query.into(), QueryType::StartWith, UsageMatcher::default()) } else { ( exact_te...
random_line_split
mod.rs
same. /// - the new query is a subset of last query. fn is_superset(&self, other: &Self) -> bool { self.keyword == other.keyword && self.query_type == other.query_type && self.usage_matcher.is_superset(&other.usage_matcher) } } /// Parses the raw user input and returns the ...
else { ( exact_terms[0].text.clone(), QueryType::Exact, UsageMatcher::new(exact_terms, inverse_terms), ) } } else { ( fuzzy_terms.iter().map(|term| &term.text).join(" "), QueryType::StartWith, ...
{ (query.into(), QueryType::StartWith, UsageMatcher::default()) }
conditional_block
mod.rs
.usage_matcher.is_superset(&other.usage_matcher) } } /// Parses the raw user input and returns the final keyword as well as the constraint terms. /// Currently, only one keyword is supported. /// /// `hel 'fn` => `keyword ++ exact_term/inverse_term`. /// /// # Argument /// /// - `query`: Initial query typed in the...
, ctx:
identifier_name
service.go
cheduler *Scheduler } func NewService(lc fx.Lifecycle, config *config.Config, db *dbstore.DB) *Service { dir := config.TempDir if dir == "" { var err error dir, err = ioutil.TempDir("", "dashboard-logs") if err != nil { log.Fatal("Failed to create directory for storing logs", zap.Error(err)) } } ...
// @Summary Preview a log search task group // @Param id path string true "task group id" // @Security JwtAuth // @Success 200 {array} PreviewModel // @Failure 401 {object} utils.APIError "Unauthorized failure" // @Failure 500 {object} utils.APIError // @Router /logs/taskgroups/{id}/preview [get] func (s *Service) Ge...
{ taskGroupID := c.Param("id") var taskGroup TaskGroupModel var tasks []*TaskModel err := s.db.First(&taskGroup, "id = ?", taskGroupID).Error if err != nil { _ = c.Error(err) return } err = s.db.Where("task_group_id = ?", taskGroupID).Find(&tasks).Error if err != nil { _ = c.Error(err) return } resp :...
identifier_body
service.go
cheduler *Scheduler } func NewService(lc fx.Lifecycle, config *config.Config, db *dbstore.DB) *Service { dir := config.TempDir if dir == "" { var err error dir, err = ioutil.TempDir("", "dashboard-logs") if err != nil { log.Fatal("Failed to create directory for storing logs", zap.Error(err)) } } ...
if len(req.Targets) == 0 { utils.MakeInvalidRequestErrorWithMessage(c, "Expect at least 1 target") return } stats := model.NewRequestTargetStatisticsFromArray(&req.Targets) taskGroup := TaskGroupModel{ SearchRequest: &req.Request, State: TaskGroupStateRunning, TargetStats: stats, } if err := ...
{ utils.MakeInvalidRequestErrorFromError(c, err) return }
conditional_block
service.go
cheduler *Scheduler } func NewService(lc fx.Lifecycle, config *config.Config, db *dbstore.DB) *Service { dir := config.TempDir if dir == "" { var err error dir, err = ioutil.TempDir("", "dashboard-logs") if err != nil { log.Fatal("Failed to create directory for storing logs", zap.Error(err)) } } ...
(c *gin.Context) { taskGroupID := c.Param("id") var lines []PreviewModel err := s.db. Where("task_group_id = ?", taskGroupID). Order("time"). Limit(TaskMaxPreviewLines). Find(&lines).Error if err != nil { _ = c.Error(err) return } c.JSON(http.StatusOK, lines) } // @Summary Retry failed tasks in a log...
GetTaskGroupPreview
identifier_name
service.go
StoreDirectory: dir, db: db, scheduler: nil, // will be filled after scheduler is created } scheduler := NewScheduler(service) service.scheduler = scheduler lc.Append(fx.Hook{ OnStart: func(ctx context.Context) error { service.lifecycleCtx = ctx return nil }, }) return servi...
taskGroupID := c.Param("id")
random_line_split
create.go
8s.io/kubeadm/kinder/pkg/constants" "k8s.io/kubeadm/kinder/pkg/cri/host" "k8s.io/kubeadm/kinder/pkg/cri/nodes" "k8s.io/kubeadm/kinder/pkg/exec" ) // CreateOptions holds all the options used at create time type CreateOptions struct { controlPlanes int workers int image string e...
desiredNodes = append(desiredNodes, desiredNode) } for n := 0; n
Name: fmt.Sprintf("%s-%s-%d", clusterName, role, n+1), Role: role, }
random_line_split
create.go
CreateOptions) { c.retain = retain } } // Volumes option instructs create cluster to add volumes to the node containers func Volumes(volumes []string) CreateOption { return func(c *CreateOptions) { c.volumes = volumes } } // CreateCluster creates a new kinder cluster func CreateCluster(clusterName string, opti...
:= make(chan error, len(funcs)) for _, f := range funcs { f := f // capture f go func() { errCh <- f() }() } for i := 0; i < len(funcs); i++ { if err := <-errCh; err != nil { return err } } return nil }
identifier_body
create.go
8s.io/kubeadm/kinder/pkg/constants" "k8s.io/kubeadm/kinder/pkg/cri/host" "k8s.io/kubeadm/kinder/pkg/cri/nodes" "k8s.io/kubeadm/kinder/pkg/exec" ) // CreateOptions holds all the options used at create time type CreateOptions struct { controlPlanes int workers int image string e...
(volumes []string) CreateOption { return func(c *CreateOptions) { c.volumes = volumes } } // CreateCluster creates a new kinder cluster func CreateCluster(clusterName string, options ...CreateOption) error { flags := &CreateOptions{} for _, o := range options { o(flags) } // Check if the cluster name alread...
Volumes
identifier_name
create.go
8s.io/kubeadm/kinder/pkg/constants" "k8s.io/kubeadm/kinder/pkg/cri/host" "k8s.io/kubeadm/kinder/pkg/cri/nodes" "k8s.io/kubeadm/kinder/pkg/exec" ) // CreateOptions holds all the options used at create time type CreateOptions struct { controlPlanes int workers int image string e...
mt.Printf("Preparing nodes %s\n", strings.Repeat("📦", numberOfNodes)) // detect CRI runtime installed into images before actually creating nodes runtime, err := status.InspectCRIinImage(flags.image) if err != nil { log.Errorf("Error detecting CRI for images %s! %v", flags.image, err) return err } log.Infof("...
numberOfNodes++ } f
conditional_block
command_server.rs
worker that is registered interest to its Uuid fn send_messages(res: WrappedResponse, al: &Mutex<AlertList>) { let mut al_inner = al.lock().expect("Unable to unlock al n send_messages"); let pos_opt: Option<&mut (_, UnboundedSender<Result<Response, ()>>)> = al_inner.list.iter_mut().find(|x| x.0 == res.uuid ); ...
execute
identifier_name
command_server.rs
Results from the Tick Processor will be sent if they /// match the ID of the request the command `UnboundedSender` thread sent. struct AlertList { // Vec to hold the ids of responses we're waiting for and `Sender`s // to send the result back to the worker thread // Wrapped in Arc<Mutex<>> so that it can be...
for task in cmd_rx.wait() { let res = dispatch_worker( task.unwrap(), al, &mut client, &mut sleeper_tx, command_queue.clone() ); // exit if we're in the process of collapse if res.is_none() { break; } } } impl CommandServer { pub fn new(insta...
random_line_split
command_server.rs
from the Tick Processor will be sent if they /// match the ID of the request the command `UnboundedSender` thread sent. struct AlertList { // Vec to hold the ids of responses we're waiting for and `Sender`s // to send the result back to the worker thread // Wrapped in Arc<Mutex<>> so that it can be accesse...
} Ok(sleeper_tx) }).wait().ok().unwrap(); // block until a response is received or the command times out } /// Manually loop over the converted Stream of commands fn dispatch_worker( work: WorkerTask, al: &Mutex<AlertList>, mut client: &mut redis::Client, mut sleeper_tx: &mut UnboundedSend...
{ // timed out { al.lock().expect("Couldn't lock al in Err(_)") .deregister(&wr_cmd.uuid); } attempts += 1; if attempts >= CONF.cs_max_retries { // Let the main thread know it's safe to use th...
conditional_block
Workload.js
i = 0; i < data.length; i++) { var dd = data[i]; var month = new Date(dd.outTime).getMonth() + 1; if (load[month] == undefined) { load[month] = 1; } else { load[month]++; } } } else if (type == 1) {//月 //统计一年...
identifier_name
Workload.js
setXLimit: function () { //this.rectNum = this.Data.length; switch (this.type) { case 0: Workload.unitLengthX = (Workload.getXLength() - 40) / 24; break; case 1: Workload.unitLengthX = (Workload.getXLength() - 40) / 62; ...
} if (day < 10) { day = "0" + day; } var fromTime = ""; var days = 0; switch (type) { case 0: Workload.year = year; fromTime = year + "-01-01"; Workload.days = 365; Workload.rectNum = 12; break; case 1: ...
random_line_split
Workload.js
setXLimit: function () { //this.rectNum = this.Data.length; switch (this.type) { case 0: Workload.unitLengthX = (Workload.getXLength() - 40) / 24; break; case 1: Workload.unitLengthX = (Workload.getXLength() - 40) / 62; ...
} else { load[hour]++; } } } else if (type == 3) { for (i = 0; i < data.length; i++) { var dd = data[i]; var day = new Date(dd.outTime).getDate(); if (load[day] == undefined) { load[day] = 1; } el...
load[month]++; } } } else if (type == 1) {//月 //统计一年中每个月的工作量 for (i = 0; i < data.length; i++) { var dd = data[i]; var day = new Date(dd.outTime).getDate(); if (load[day] == undefined) { load[day] = 1; } e...
identifier_body
runningView.js
+ condition.qualifiedTime numId = STAR_FLAG + condition. +'-num', imageId = STAR_FLAG + name+'-image', numNodes = nodes[numId], imageNodes = nodes[imageId];*/ }, allRight: function(userData, condition){ //numNodes.textContent = userData[name] ? '全部答对' : '未全部答对'; //imageNodes.style.bo...
var renderData = methods[condition.name](condition.value, condition); lib.extend(condition, renderData); }); } }, scene: {}, tipObj: {}, tipPanel: lib.g('window-tip') } publicMethods = { hasInitEvents: false, initSet: function(id, ev, events, context){ privateMethods.scene[id] = { ...
methods[condition.name](condition.value, condition); lib.extend(condition, renderData); }); } if(conditions.star){ conditions.star.forEach(function(condition){
conditional_block
runningView.js
' + condition.qualifiedTime numId = STAR_FLAG + condition. +'-num', imageId = STAR_FLAG + name+'-image', numNodes = nodes[numId], imageNodes = nodes[imageId];*/ }, allRight: function(userData, condition){ //numNodes.textContent = userData[name] ? '全部答对' : '未全部答对'; //imageNodes.style.b...
changeTo: function(id){ var nodes = privateMethods.nodes, scene = privateMethods.scene[id], events = scene.ev, context = scene.context; Object.keys(events).forEach(function(ev){ var data = events[ev], node = nodes[ev]; node.onclick = data.click ? function(){ data.click.call(conte...
}; //lib },
random_line_split
p6.py
samples[:,1], s=0.2) plt.show() bins= 20 (counts, x_bins, y_bins) = np.histogram2d(samples[:, 0], samples[:, 1], bins=bins) plt.contourf(counts, extent=[x_bins[0], x_bins[-1], y_bins[0], y_bins[-1]]) plt.show() samples_for_f = samples # #### c. Consider a normal distribution specified by the following parameters: ...
(): plt.xlim([-10, 10]) plt.ylim([-10, 10]) ax = plt.gca() ax.spines['top'].set_color('none') ax.spines['bottom'].set_position('zero') ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') # In[5]: N =5000 # we changed N, because N=500 was too small for being visua...
setting_function
identifier_name
p6.py
# # for i in range(0, len(sigmas)): # s = np.random.normal(mu, sigmas[i], N) # print ("mu", mu, "Sigma", sigmas[i]) # plt.scatter (s, np.zeros(len(s)), s=0.1, color=colors[i]) # plt.xlim([485, 515]) # plt.show() # #### b) Generate samples from a normal distributions specified by the following pa...
s = np.random.normal(mu, sigmas[i], N) print ("mu", mu, "Sigma", sigmas[i]) sns.distplot(s, color=colors[i], bins=bins) plt.scatter (s, np.zeros(len(s)), s=0.2, color=colors[i]) plt.xlim([485, 515]) plt.show()
conditional_block
p6.py
samples[:,1], s=0.2) plt.show() bins= 20 (counts, x_bins, y_bins) = np.histogram2d(samples[:, 0], samples[:, 1], bins=bins) plt.contourf(counts, extent=[x_bins[0], x_bins[-1], y_bins[0], y_bins[-1]]) plt.show() samples_for_f = samples # #### c. Consider a normal distribution specified by the following parameters: ...
# In[5]: N =5000 # we changed N, because N=500 was too small for being visualized well samples = np.random.multivariate_normal(np.array([-5,5]), np.array([[1,0],[0,1]]), N) setting_function() plt.scatter (samples[:,0], samples[:,1], s=0.2) plt.show() # c.2) A diagonal line (/ shape) in the centre<br> # We...
plt.xlim([-10, 10]) plt.ylim([-10, 10]) ax = plt.gca() ax.spines['top'].set_color('none') ax.spines['bottom'].set_position('zero') ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none')
identifier_body
p6.py
samples[:,1], s=0.2) plt.show() bins= 20 (counts, x_bins, y_bins) = np.histogram2d(samples[:, 0], samples[:, 1], bins=bins) plt.contourf(counts, extent=[x_bins[0], x_bins[-1], y_bins[0], y_bins[-1]]) plt.show() samples_for_f = samples # #### c. Consider a normal distribution specified by the following parameters: ...
vec = np.array([samples[i]-estimated_mean]) tmp = np.matmul(vec.T, vec) estimated_var += tmp estimated_var /= (len(samples)-1) print ("estimated sigma") print (estimated_var) print ("real sigma:") print (np.array([[2,1],[1,3]]) ) # Comment: The estimated mean and sigma are close to real mean and real sigm...
print ("real mean [2,1]") estimated_var = 0 for i in range(0, len(samples)):
random_line_split
twitch.py
ness: %s', r.status) logger.error(await r.text()) except: logger.error('Twitch baddness') return None async def get_user(client_id, user_id): return await twitch_request(client_id, 'users', user_id) async def
(client_id, game_id, user_id): game = await twitch_request(client_id, 'games', game_id) if game: return game['name'] else: headers = { 'Client-ID': client_id, 'Accept': 'application/vnd.twitchtv.v5+json' } try: async with aiohttp.get('https://api.tw...
get_game_title
identifier_name
twitch.py
ness: %s', r.status) logger.error(await r.text()) except: logger.error('Twitch baddness') return None async def get_user(client_id, user_id): return await twitch_request(client_id, 'users', user_id) async def get_game_title(client_id, game_id, user_id):
async def lookup_users(config, user_list): headers = { 'Client-ID': config['twitch']['client-id'], 'Content-Type': 'application/json' } async with aiohttp.get('https://api.twitch.tv/helix/users', headers=headers, params=user_list) as r: if r.status == 200: user_json = await...
game = await twitch_request(client_id, 'games', game_id) if game: return game['name'] else: headers = { 'Client-ID': client_id, 'Accept': 'application/vnd.twitchtv.v5+json' } try: async with aiohttp.get('https://api.twitch.tv/kraken/streams/%s' % user_i...
identifier_body
twitch.py
ness: %s', r.status) logger.error(await r.text()) except: logger.error('Twitch baddness') return None async def get_user(client_id, user_id): return await twitch_request(client_id, 'users', user_id) async def get_game_title(client_id, game_id, user_id): game = await twitch_requ...
return (response, None) async def get_subs(config): headers = { 'Authorization': 'Bearer %s' % config['twitch']['app-token'] } get_more = True user_ids = [] params = None while get_more: get_more = False async with aiohttp.get('https://api.twitch.tv/helix/webhooks/subscriptions...
streams_json = await r.json() users = await parse_streams(client, config, server, streams_json) if len(users) > 0: response = "Announced %s" % (' '.join(users))
conditional_block
twitch.py
badness: %s', r.status) logger.error(await r.text()) except: logger.error('Twitch baddness') return None async def get_user(client_id, user_id): return await twitch_request(client_id, 'users', user_id) async def get_game_title(client_id, game_id, user_id): game = await twitch_...
sub_data['hub.topic'] = "https://api.twitch.tv/helix/streams?user_id=%s" % user['id'] # Send a (un)subcription request for each username async with aiohttp.post('https://api.twitch.tv/helix/webhooks/hub', headers=headers, data=json.dumps(sub_data)) as r: if r.status== 202: ...
user_ids = [] # Send a (un)subcription request for each username for user in users: logger.info('%s: %s' % (user['display_name'], user['id'])) sub_data['hub.callback'] = "%s?lb3.server=%s&lb3.user_id=%s" % (config['twitch']['webhook_uri'], config['discord']['server'], user['id'])
random_line_split
msg.go
riters = w } // Set the time format. If it is empty, set the default. if t == "" { obj.TimeFormat = "2006-01-02 15:05:05.000 MST" } else { obj.TimeFormat = t } // Set the format. If it is empty use the default. if f == "" { obj.Format = `%(-27)time %(-7)type %file %line - %msg` } else { obj.Format = f...
{ s = spec }
conditional_block
msg.go
string, a ...interface{}) Err(f string, a ...interface{}) ErrNoExit(f string, a ...interface{}) DebugWithLevel(l int, f string, a ...interface{}) InfoWithLevel(l int, f string, a ...interface{}) WarnWithLevel(l int, f string, a ...interface{}) ErrWithLevel(l int, f string, a ...interface{}) ErrNoExitWithLevel(...
It allows you to insert arbitrary text. Unlike the other functions it does not automatically append a new line. Example: msg.Printf("this is just random text that goes to all writers\n") */ func (o Object) Printf(f string, a ...interface{}) { // Create the formatted output string. s := fmt.Sprintf(f, a...) ...
/* Printf prints directly to the log without the format string.
random_line_split
msg.go
string, a ...interface{}) Err(f string, a ...interface{}) ErrNoExit(f string, a ...interface{}) DebugWithLevel(l int, f string, a ...interface{}) InfoWithLevel(l int, f string, a ...interface{}) WarnWithLevel(l int, f string, a ...interface{}) ErrWithLevel(l int, f string, a ...interface{}) ErrNoExitWithLevel(...
(f string, a ...interface{}) { if o.InfoEnabled { o.PrintMsg("INFO", 2, f, a...) } } /* InfoWithLevel prints an info message obtaining the filename, function and line number from the caller specified by level "l". l=2 is the same as Debug(). It automatically appends a new line. Example: msg.InfoWithLevel(2...
Info
identifier_name
msg.go
string, a ...interface{}) Err(f string, a ...interface{}) ErrNoExit(f string, a ...interface{}) DebugWithLevel(l int, f string, a ...interface{}) InfoWithLevel(l int, f string, a ...interface{}) WarnWithLevel(l int, f string, a ...interface{}) ErrWithLevel(l int, f string, a ...interface{}) ErrNoExitWithLevel(...
/* PrintMsg is the basis of all message printers except Printf. It prints the formatted messages and normally would not be called directly. t - is the type, normally one of DEBUG, INFO, WARNING or ERROR l - is the caller level: 0 is this function, 1 is the caller, 2 is the callers caller and so on ...
{ // Create the formatted output string. s := fmt.Sprintf(f, a...) // Output it for each writer. for _, w := range o.Writers { fmt.Fprintf(w, s) } }
identifier_body
examples.js
if(i % 5 === 0) { words += "Buzz"; } else { words += i; } console.log(words); } /*****************WHILE LOOPS**********************/ // PRINT EVEN NUMBERS BETWEEN 10 AND 40 var count = 10; while(count <= 40){ console.log(count); count+=2; } // PRINT ALL ODD NUMBERS BETWEEN 300 333 var count = 300; whi...
{ //create a new object with a name property with the value set to the name argument //add an age property to the object with the value set to the age argument //add a method called meow that returns the string 'Meow!' //return the object var newCat = { name: name, age: age, meow:function ...
identifier_body
examples.js
numbers between 300 and 333 for(var i = 300; i <= 333; i++) { if(i % 2 !== 0) { console.log(i); } } // fizz buzz question // print 1 to 100 any num / by 3 print fizz, / 5 buzz and both fizzbuzz for (var i = 1; i <= 100; i++) { var words = ""; if (i % 3 === 0 && i % 5 === 0) { words += "FizzB...
function colorOf(r,g,b){ var red = r.toString(16); if (red.length === 1) red = "0" + red; var green = g.toString(16); if (green.length === 1) green = "0" + green; var blue = b.toString(16); if (blue.length === 1) blue = "0" + blue; return "#" + red + green + blue; } colorOf(255,0,0); // outputs '#ff0000...
return num; } }
random_line_split
examples.js
(n) { if (n === 0) { return 1; } // This is it! Recursion!! return n * factorial(n - 1); } console.log(factorial(10)); /*****************FOR LOOPS**********************/ // print all odd numbers between 300 and 333 for(var i = 300; i <= 333; i++) { if(i % 2 !== 0) { console.log(i); ...
factorial
identifier_name
examples.js
between 300 and 333 for(var i = 300; i <= 333; i++) { if(i % 2 !== 0) { console.log(i); } } // fizz buzz question // print 1 to 100 any num / by 3 print fizz, / 5 buzz and both fizzbuzz for (var i = 1; i <= 100; i++) { var words = ""; if (i % 3 === 0 && i % 5 === 0) { words += "FizzBuzz"; }...
} return num > 1; } function isPrime(num) { //return true if num is prime. //otherwise return false //hint: a prime number is only evenly divisible by itself and 1 //hint2: you can solve this using a for loop //note: 0 and 1 are NOT considered prime numbers if(num < 2) return false; for (v...
{ return false; }
conditional_block
header.go
avoid an extra copy or using a // ByteReader, which would just have an internal buffer and be slower. r := unsafe.Slice((*int8)(unsafe.Pointer(&b[0])), len(b)) return r, nil case TypeChar: // Char and Bin are different because they're offset differently. r := make([]byte, int(e.count)) if _, err := sr...
UnmarshalBinary
identifier_name
header.go
header: error reading %T: %w", r[0], err) } r[i] = int32(binary.BigEndian.Uint32(b)) } return r, nil case TypeInt16: r := make([]int16, int(e.count)) b := make([]byte, 2) for i := range r { if _, err := io.ReadFull(sr, b); err != nil { return nil, fmt.Errorf("rpm: header: error readin...
{ if i, ok := tagByValue[key]; ok { t := tagTable[i].Type // Check the type. Some versions of string are typed incorrectly in a // compatible way. return t == typ || t.class() == typ.class() } // Unknown tags get a pass. return true }
identifier_body
header.go
.Errorf("rpm: failed to parse header: %w", err) } return nil } // ReadData returns a copy of the data indicated by the passed EntryInfo. // // If an error is not reported, the returned interface{} is the type indicated by the // EntryInfo's "Type" member. // // NB The TypeChar, TypeInt8, TypeInt16, TypeInt32, TypeIn...
if dataSz > dataMax { return fmt.Errorf("header botch: data length (%d) out of range", dataSz) } tagsSz := int64(tagsCt) * entryInfoSize // Sanity check, if possible: var inSz int64 switch v := r.(type) { case interface{ Size() int64 }: // Check for Size method. [ioSectionReader]s and [byte.Buffer]s have t...
{ return fmt.Errorf("header botch: number of tags (%d) out of range", tagsCt) }
conditional_block
header.go
++ { s[i] = sc.Text() } if err := sc.Err(); err != nil { return nil, fmt.Errorf("rpm: header: error reading string array: %w", err) } return s, nil case TypeString: // C-terminated string. r := bufio.NewReader(io.NewSectionReader(h.data, int64(e.offset), -1)) s, err := r.ReadString(0x00) if err !...
e, err := h.loadTag(ctx, i) if err != nil { return err
random_line_split
profiles.go
LOGSTASH_PROFILE" OriginProfileType = "ORG_PROFILE" // RiakProfileType is the type of a Profile used on the legacy RiakKV system // which used to be used as a back-end for Traffic Vault. // // Deprecated: Support for Riak as a Traffic Vault back-end is being dropped // in the near future. Profiles of typ...
{ count := 0 if err := tx.QueryRow(`SELECT count(*) from profile where id = $1`, id).Scan(&count); err != nil { return false, errors.New("querying profile existence from id: " + err.Error()) } return count > 0, nil }
identifier_body
profiles.go
, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import ( "database/sql" "errors" "fmt" "strconv" "strings" "time" "github.com/apache/trafficcontrol/lib/go-log" "github.co...
// Validate profile does not already exist if profile.Name != nil { if ok, err := ProfileExistsByName(*profile.Name, tx); err != nil { errString := fmt.Sprintf("checking profile name %v existence", *profile.Name) log.Errorf("%v: %v", errString, err.Error()) errs = append(errs, errors.New(errString)) } ...
{ if ok, err := CDNExistsByName(*profile.CDNName, tx); err != nil { errString := fmt.Sprintf("checking cdn name %v existence", *profile.CDNName) log.Errorf("%v: %v", errString, err.Error()) errs = append(errs, errors.New(errString)) } else if !ok { errs = append(errs, fmt.Errorf("%v CDN does not exist",...
conditional_block
profiles.go
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import ( "database/sql" "errors" "fmt" "strconv" "strings" "time" "github.com/apache/trafficcontrol/lib/go-log" "git...
} // ProfileCopyResponse represents the Traffic Ops API's response when a Profile // is copied. type ProfileCopyResponse struct { Response ProfileCopy `json:"response"` Alerts } // ProfileExportImportNullable is an object of the form used by Traffic Ops // to represent exported and imported profiles. type ProfileEx...
ID int `json:"id"` Name string `json:"name"` ExistingID int `json:"idCopyFrom"` ExistingName string `json:"profileCopyFrom"` Description string `json:"description"`
random_line_split
profiles.go
the License. */ import ( "database/sql" "errors" "fmt" "strconv" "strings" "time" "github.com/apache/trafficcontrol/lib/go-log" "github.com/apache/trafficcontrol/lib/go-tc/tovalidate" "github.com/apache/trafficcontrol/lib/go-util" validation "github.com/go-ozzo/ozzo-validation" "github.com/lib/pq" ) //...
ProfilesExistByIDs
identifier_name
lib.rs
//! 2. Ensure all subsequent reads to the memory following the zeroing operation //! will always see zeroes. //! //! This crate guarantees #1 is true: LLVM's volatile semantics ensure it. //! //! The story around #2 is much more complicated. In brief, it should be true that //! LLVM's current implementation does not...
//! ## What guarantees does this crate provide? //! //! Ideally a secure memory-zeroing function would guarantee the following: //! //! 1. Ensure the zeroing operation can't be "optimized away" by the compiler.
random_line_split
lib.rs
effort" to ensure that //! memory accesses will not be reordered ahead of the "zeroize" operation, //! but **cannot** yet guarantee that such reordering will not occur. //! //! ## Stack/Heap Zeroing Notes //! //! This crate can be used to zero values from either the stack or the heap. //! //! However, be aware that Ru...
atomic_fence
identifier_name
lib.rs
will not occur. //! //! ## Stack/Heap Zeroing Notes //! //! This crate can be used to zero values from either the stack or the heap. //! //! However, be aware that Rust's current memory semantics (e.g. `Copy` types) //! can leave copies of data in memory, and there isn't presently a good solution //! for ensuring all ...
{ atomic::fence(atomic::Ordering::SeqCst); atomic::compiler_fence(atomic::Ordering::SeqCst); }
identifier_body
fakes.rs
saved_networks: Mutex<HashMap<NetworkIdentifier, Vec<NetworkConfig>>>, connections_recorded: Mutex<Vec<ConnectionRecord>>, connect_results_recorded: Mutex<Vec<ConnectResultRecord>>, lookup_compatible_response: Mutex<LookupCompatibleResponse>, pub fail_all_stores: bool, pub active_scan_result_rec...
pub fn get_recorded_connect_reslts(&self) -> Vec<ConnectResultRecord> { self.connect_results_recorded .try_lock() .expect("expect locking self.connect_results_recorded to succeed") .clone() } /// Manually change the hidden network probabiltiy of a saved network...
{ self.connections_recorded .try_lock() .expect("expect locking self.connections_recorded to succeed") .clone() }
identifier_body
fakes.rs
client_types::Bssid, pub connect_result: fidl_sme::ConnectResult, pub scan_type: client_types::ScanObservation, } /// Use a struct so that the option can be updated from None to Some to allow the response to be /// set after FakeSavedNetworksManager is created. Use an optional response value rather than /// d...
rng.gen::<u8>().into(), ) }
random_line_split
fakes.rs
{ saved_networks: Mutex<HashMap<NetworkIdentifier, Vec<NetworkConfig>>>, connections_recorded: Mutex<Vec<ConnectionRecord>>, connect_results_recorded: Mutex<Vec<ConnectResultRecord>>, lookup_compatible_response: Mutex<LookupCompatibleResponse>, pub fail_all_stores: bool, pub active_scan_result_...
() -> (mpsc::Sender<String>, mpsc::Receiver<String>) { const DEFAULT_BUFFER_SIZE: usize = 100; // arbitrary value mpsc::channel(DEFAULT_BUFFER_SIZE) } /// Create past connection data with all random values. Tests can set the values they care about. pub fn random_connection_data() -> PastConnectionData { le...
create_inspect_persistence_channel
identifier_name
fakes.rs
{ saved_networks: Mutex<HashMap<NetworkIdentifier, Vec<NetworkConfig>>>, connections_recorded: Mutex<Vec<ConnectionRecord>>, connect_results_recorded: Mutex<Vec<ConnectResultRecord>>, lookup_compatible_response: Mutex<LookupCompatibleResponse>, pub fail_all_stores: bool, pub active_scan_result_...
else { None }, ) .flatten() .collect() } } } /// Note that the configs-per-NetworkIdentifier limit is set to 1 in /// this mock struct. If a NetworkIdentifier is already stored, writing /// a config to it will evict the pr...
{ Some(config.clone()) }
conditional_block
yahoo_plus_save.py
(self,logfile_name,dbpath): dbpath='''file:{}?mode=rw'''.format(dbpath) self.conn = sqlite3.connect(dbpath,uri=True) self.c = self.conn.cursor() self.logfile_name="yahoo_plus.log" self.requests_cnt=0 self.https_proxy=proxies[0] @staticmethod def convert_...
__init__
identifier_name
yahoo_plus_save.py
H:%M:%S"),string),file= open(self.logfile_name, "a")) print(str1,file= open(self.logfile_name, "a",encoding="utf8")) else: try: print(string) except UnicodeEncodeError: print("{0} : UnicodeEncodeError, String Contains Non-BMP character".f...
def parse_file(self,file): a_file = open(file, "r",encoding="utf8") list_of_lists = [] for line in a_file: stripped_line = line.strip() if stripped_line[0] =="#": #skip with sharp symbol continue if len(stripped_line)==0: ...
'''Get data from database, return a list without column name''' if arg is None: self.c.execute(sql) else: self.c.execute(sql,arg) b=self.c.fetchall() return b
identifier_body
yahoo_plus_save.py
H:%M:%S"),string),file= open(self.logfile_name, "a")) print(str1,file= open(self.logfile_name, "a",encoding="utf8")) else: try: print(string) except UnicodeEncodeError: print("{0} : UnicodeEncodeError, String Contains Non-BMP character".f...
else: self.c.execute('''INSERT OR IGNORE INTO answers (question_id,is_accepted,answer,datecreated,author_type,author_name,author_link,upvotecount) VALUES(?,?,?,?,?,?,?,?)''',(newqid,1,content2,date2,author_t2,author_n2,user_url[user_urlpos],upvote_c2)) user_urlpos+=1; ...
pass
conditional_block
yahoo_plus_save.py
except UnicodeEncodeError: print("{0} : UnicodeEncodeError, String Contains Non-BMP character".format(self._curtime())) #print("{0} : {1}".format(time.strftime("%d/%m/%Y %H:%M:%S"),string),file= open(self.logfile_name, "a")) print(str1,file= open(self.logfile_name,...
print(str1)
random_line_split
anichart.py
data into a single list The original root value (i.e.- tv, leftovers) is added as the "category" key and title()'d. """ out = list() ## API data is organized in {category (tv,tvshort,movie,etc.):[list of show dicts]} for cat,shows in data.items(): for show in shows: show['c...
@overwrite_season def cleanapidata_csv(data): """ Cleans the API data for use in a CSV and returns a list of headers along with the clean data. Converts startdate to EST startdate. Adds firstepisode date. Adds EST_airing time. Features overwrite_season decorator Returns ([list of Headers...
""" Replaces the season value of a list of Show objects or data dicts Mutates the objects in-place. """ if not SeasonCharts.matchseason(season): raise SeasonCharts.SeasonError ## Check data format if test_rawdata(data): for cat,shows in data.items(): for show in show...
identifier_body
anichart.py
## rankings contradicts eachother if not season: ## Defaults to None one way or another if it's not supplied season = ranking.get("season") if not year: year = ranking.get("year") ## Check if we made it if season and year: ## As above, this should always w...
continuing = show['category'].lower() == "leftovers" summary = f"(From {CHARTNAME})\n{show.get('description')}"
random_line_split
anichart.py
2]) - 1 ## This should normally pass; if it consistently does not, we'll have to investigate why try: return SeasonCharts.buildseason(season,year) ## If something goes wrong, we'll try another method except: print(f"Failed to parse season: {data['season']}") ## Next, we'll iterate ov...
converttostandard
identifier_name
anichart.py
into a single list The original root value (i.e.- tv, leftovers) is added as the "category" key and title()'d. """ out = list() ## API data is organized in {category (tv,tvshort,movie,etc.):[list of show dicts]} for cat,shows in data.items(): for show in shows: show['catego...
s = str(startdate) d,m,y = [max(dt,1) for dt in [int(s[6:8]),int(s[4:6]),int(s[:4])]] return f"{d:0>2}/{m:0>2}/{y:0>4}" def getseason(data): """ Tries to determine the season that an anime aired based on its season value and it's ratings """ ## Season key is the most reliable season = data.get...
return "01/01/2017"
conditional_block
runIPRscan.py
11) # Errors are indicated by HTTP status codes. try: # Set the User-agent. user_agent = getUserAgent() http_headers = {'User-Agent': user_agent} req = urllib.request.Request(url, None, http_headers) # Make the request (HTTP GET). reqH = urllib.request.urlopen(re...
params['sequence'] = readFile(options.input)
conditional_block
runIPRscan.py
to use, see --paramDetail appl') parser.add_argument('--crc', action="store_true", help='enable InterProScan Matches look-up (ignored)') parser.add_argument('--nocrc', action="store_true", help='disable InterProScan Matches look-up (ignored)') parser.add_argument('--goterms', ac...
(paramName): printDebugMessage('printGetParameterDetails', 'Begin', 1) doc = serviceGetParameterDetails(paramName) print(str(doc.name) + "\t" + str(doc.type)) print(doc.description) for value in doc.values: print(value.value, end=' ') if str(value.defaultValue) == 'true': ...
printGetParameterDetails
identifier_name
runIPRscan.py
% urllib2.__version__ clientRevision = '$Revision: 2809 $' clientVersion = '0' if len(clientRevision) > 11: clientVersion = clientRevision[11:-2] # Prepend client specific agent string. user_agent = 'EBI-Sample-Client/%s (%s; Python %s; %s) %s' % ( clientVersion, os.path.basename(__...
printDebugMessage('getResult', 'Begin', 1) printDebugMessage('getResult', 'jobId: ' + jobId, 1) # Check status and wait if necessary clientPoll(jobId) # Get available result types resultTypes = serviceGetResultTypes(jobId) for resultType in resultTypes: # Derive the filename for the resu...
identifier_body
runIPRscan.py
debug output level') options = parser.parse_args() # Increase output level if options.verbose: outputLevel += 1 # Decrease output level if options.quiet: outputLevel -= 1 # Debug level if options.debugLevel: debugLevel = options.debugLevel # Debug print def printDebugMessage(functionName, message, lev...
def getResult(jobId): printDebugMessage('getResult', 'Begin', 1) printDebugMessage('getResult', 'jobId: ' + jobId, 1) # Check status and wait if necessary
random_line_split
main.py
itemToStore = arg.lower() # get a list of all "description words" for each item in the inventory invDescWords = getAllDescWords(inventory) # Nice little easter egg :) if itemToStore == 'troll in bag': print(bcolors.start + "You cannot put troll in ...
do_clear
identifier_name
main.py
arg): """Go to the area downwards, if possible.""" moveDirection('down') # Since the code is the exact same, we can just copy the # methods with shortened names: do_n = do_north do_s = do_south do_e = do_east do_w = do_west do_u = do_up do_d = do_down ...
possibleItems = [] itemToDrop = text.lower() # get a list of all "description words" for each item in the inventory invDescWords = getAllDescWords(inventory) for descWord in invDescWords: if line.startswith('drop %s' % (descWord)): return [] # comman...
identifier_body
main.py
Books', LONGDESC: 'A pile of dusty old books pages half rotting away, its hard to make out what is written in them, Hitchickers Guide to the Galaxy, How to stew a ham in 43 different ways and various other, written, human detritus.', EDIBLE: False, USEABLE: False, DE...
print('Showing brief exit descriptions.')
random_line_split
main.py
chest': print(bcolors.start + "Your feeble arms buckle under the weight of the enormous chest, nice try you theiving git." + bcolors.end) return if cantTake: print('You cannot take "%s".' % (itemToTake)) else: print('That ...
print('\n'.join(textwrap.wrap(worldItems[item][LONGDESC], SCREEN_WIDTH))) return
conditional_block
render_global.rs
FramebufferAttachment::from_new_texture(AttachmentPoint::Color(2), ImageFormat::get(gl::RGB8))); // fbo.add_attachment(FramebufferAttachment::from_new_texture(AttachmentPoint::Color(1), ImageFormat::get(gl::RGBA8))); // fbo.add_attachment(FramebufferAttachment::from_new_texture(AttachmentPoint::Color(1), ImageFor...
// let mut program = RefCell::borrow_mut(&program); // program.delete(); // } // if let Some(program) = self.program_post_resolve.take() { // let mut program = RefCell::borrow_mut(&program); // program.delete(); // } // Reload shader from assets // // Load shaders // self.program_ehaa_scene = So...
// if let Some(program) = self.program_ehaa_scene.take() {
random_line_split
render_global.rs
else { // Create fbo self.framebuffer_scene_hdr_ehaa = Some(Rc::new(RefCell::new({ let mut fbo = Framebuffer::new(event.resolution.0, event.resolution.1); fbo.add_attachment(FramebufferAttachment::from_new_texture(AttachmentPoint::Depth, ImageFormat::get(gl::DEPTH_COMPONENT32F))); fbo.add_atta...
{ let mut fbo = RefCell::borrow_mut(t); fbo.resize(event.resolution.0, event.resolution.1); }
conditional_block
render_global.rs
FramebufferAttachment::from_new_texture(AttachmentPoint::Color(2), ImageFormat::get(gl::RGB8))); // fbo.add_attachment(FramebufferAttachment::from_new_texture(AttachmentPoint::Color(1), ImageFormat::get(gl::RGBA8))); // fbo.add_attachment(FramebufferAttachment::from_new_texture(AttachmentPoint::Color(1), ImageFor...
(&mut self) { // let asset_folder = demo::demo_instance().asset_folder.as_mut().unwrap(); // Log println!("Reloading shaders!"); // Reload shaders from asset self.program_ehaa_scene.reload_from_asset().expect("Failed to reload scene shader from asset"); self.program_post_composite.reload_from_asset().e...
reload_shaders
identifier_name
spinup.py
type=int, help="Writing interval for spatial time series", default=10) parser.add_argument( "-f", "--o_format", dest="oformat", choices=["netcdf3", "netcdf4_parallel", "pnetcdf"], help="output format", default="netcdf3", ) parser.add_argument( "-g", "--grid", dest="grid", type=int, choices=...
cmd = [ncgen, "-o", pism_config_nc, pism_config_cdl] sub.call(cmd) if not os.path.isdir(odir): os.mkdir(odir) state_dir = "state" scalar_dir = "scalar" spatial_dir = "spatial" for tsdir in (scalar_dir, spatial_dir, state_dir): if not os.path.isdir(os.path.join(odir, tsdir)): os.mkdir(os.path.join(odir...
ncgen = "ncgen"
conditional_block
spinup.py
", type=int, help="Writing interval for spatial time series", default=10) parser.add_argument( "-f", "--o_format", dest="oformat", choices=["netcdf3", "netcdf4_parallel", "pnetcdf"], help="output format", default="netcdf3", ) parser.add_argument( "-g", "--grid", dest="grid", type=int, choice...
ssa_n_values, ppq_values, tefo_values, phi_min_values, phi_max_values, topg_min_values, topg_max_values, ) ) tsstep = "yearly" scripts = [] scripts_post = [] simulation_start_year = options.start_year simulation_end_year = options.end_year for n, combinat...
itertools.product( sia_e_values,
random_line_split
polynom.py
def __bool__(self): return bool(self.v) def __add__(a, b): assert isinstance(b, ModInt) assert a.n == b.n return ModInt(a.v + b.v, a.n) def __radd__(a, b): assert isinstance(b, int) return ModInt(a.v + b, a.n) def __neg__(a): return ModInt(-a.v, a.n) ...
def __hash__(self): return hash((self.v, self.n))
random_line_split
polynom.py
a * x + b * y = gcd(a, b) """ A, B = a, b sa, sb = (1 if a >= 0 else -1), (1 if b >= 0 else -1) xp, yp = 1, 0 x, y = 0, 1 while b: assert A * xp + B * yp == a assert A * x + B * y == b r = a // b a, b = b, a % b ...
turn Polynomial([ModInt(c, p) for c in P])
identifier_body