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
controlPanel.go
package main import ( "fmt" "golang.org/x/exp/shiny/gesture" "golang.org/x/exp/shiny/iconvg" "golang.org/x/exp/shiny/materialdesign/icons" "golang.org/x/exp/shiny/screen" "golang.org/x/exp/shiny/unit" "golang.org/x/exp/shiny/widget" "golang.org/x/exp/shiny/widget/node" "golang.org/x/exp/shiny/widget/theme" "...
() *Button { return p.NewButton("Highlight Active AI", icons.ActionFavorite, true, func() string { if p.world.highlightActive { p.world.highlightActive = false } else { p.world.highlightActive = true } p.r.w.Send(UpdateEvent{p.world}) return "Highlight Active AI" }) } func (p *ControlPanel) NewExitBu...
NewHighlightActiveButton
identifier_name
timer.rs
use std::fmt; use std::mem; use std::pin::Pin; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::{Arc, Mutex, Weak}; use std::task::{Context, Poll}; use std::time::Instant; use std::future::Future; use super::AtomicWaker; use super::{global, ArcList, Heap, HeapTimer, Node, Sl...
(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Pin::new(&mut self.inner).waker.register(cx.waker()); let mut list = self.inner.list.take(); while let Some(node) = list.pop() { let at = *node.at.lock().unwrap(); match at { Some(at)...
poll
identifier_name
timer.rs
use std::fmt; use std::mem; use std::pin::Pin; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::{Arc, Mutex, Weak}; use std::task::{Context, Poll}; use std::time::Instant; use std::future::Future; use super::AtomicWaker; use super::{global, ArcList, Heap, HeapTimer, Node, Sl...
} fallback = HANDLE_FALLBACK.load(SeqCst); } // At this point our fallback handle global was configured so we use // its value to reify a handle, clone it, and then forget our reified // handle as we don't actually have an owning reference to it. assert!(...
random_line_split
openapi_terraform_provider_doc_generator.go
package openapiterraformdocsgenerator import ( "errors" "fmt" "github.com/dikhan/terraform-provider-openapi/v3/openapi" "github.com/mitchellh/hashstructure" "log" "sort" ) // TerraformProviderDocGenerator defines the struct that holds the configuration needed to be able to generate the documentation type Terraf...
} } return Property{ Name: specSchemaDefinitionProperty.GetTerraformCompliantPropertyName(), Type: string(specSchemaDefinitionProperty.Type), ArrayItemsType: string(specSchemaDefinitionProperty.ArrayItemsType), Required: specSchemaDefinitionProperty.IsRequired(), ...
{ schema = append(schema, t.resourceSchemaToProperty(*p)) }
conditional_block
openapi_terraform_provider_doc_generator.go
package openapiterraformdocsgenerator import ( "errors" "fmt" "github.com/dikhan/terraform-provider-openapi/v3/openapi" "github.com/mitchellh/hashstructure" "log" "sort" ) // TerraformProviderDocGenerator defines the struct that holds the configuration needed to be able to generate the documentation type Terraf...
func getSecurity(s openapi.SpecAnalyser) (openapi.SpecSecuritySchemes, *openapi.SpecSecurityDefinitions, error) { security := s.GetSecurity() if security != nil { globalSecuritySchemes, err := security.GetGlobalSecuritySchemes() if err != nil { return nil, nil, err } securityDefinitions, err := security....
{ backendConfig, err := s.GetAPIBackendConfiguration() if err != nil { return nil, err } if backendConfig != nil { _, _, regions, err := backendConfig.IsMultiRegion() if err != nil { return nil, err } return regions, nil } return nil, nil }
identifier_body
openapi_terraform_provider_doc_generator.go
package openapiterraformdocsgenerator import ( "errors" "fmt" "github.com/dikhan/terraform-provider-openapi/v3/openapi" "github.com/mitchellh/hashstructure" "log" "sort" ) // TerraformProviderDocGenerator defines the struct that holds the configuration needed to be able to generate the documentation type Terraf...
(s openapi.SpecAnalyser) ([]string, error) { backendConfig, err := s.GetAPIBackendConfiguration() if err != nil { return nil, err } if backendConfig != nil { _, _, regions, err := backendConfig.IsMultiRegion() if err != nil { return nil, err } return regions, nil } return nil, nil } func getSecurity...
getRegions
identifier_name
openapi_terraform_provider_doc_generator.go
package openapiterraformdocsgenerator import ( "errors" "fmt" "github.com/dikhan/terraform-provider-openapi/v3/openapi" "github.com/mitchellh/hashstructure" "log" "sort" ) // TerraformProviderDocGenerator defines the struct that holds the configuration needed to be able to generate the documentation type Terraf...
return TerraformProviderDocumentation{}, errors.New("namespace not provided, this is required to be able to render the provider installation section containing the required_providers block with the source address configuration in the form of [<HOSTNAME>/]<NAMESPACE>/<TYPE>") } if t.PluginVersionConstraint == "" { ...
if t.Namespace == "" {
random_line_split
Teach.js
// 教学控制器,zsd,student,topic-teach Ext.define('Youngshine.controller.Teach', { extend: 'Ext.app.Controller', config: { refs: { course: 'course', //zsd: 'zsd', //student: 'student', topic: 'topic', topicshow: 'topic-show', pdf: 'pdf-file' }, control: { course:...
}, // 删除教学图片 topicteachphotosDelete: function(rec){ var me = this; Ext.Viewport.setMasked({xtype:'loadmask',message:'正在删除'}); Ext.data.JsonP.request({ url: me.getApplication().dataUrl + 'deleteStudyPhotos.php', callbackKey: 'callback', params:{ data: '{"studyphotoID":' + rec.data.studyphotoID + '...
topicteachphotosBack: function(){ var me = this Ext.Viewport.setActiveItem(me.topicteach) Ext.Viewport.remove(me.topicteachphotos,true)
random_line_split
Teach.js
// 教学控制器,zsd,student,topic-teach Ext.define('Youngshine.controller.Teach', { extend: 'Ext.app.Controller', config: { refs: { course: 'course', //zsd: 'zsd', //student: 'student', topic: 'topic', topicshow: 'topic-show', pdf: 'pdf-file' }, control: { course:...
icshowDelete: function(record,oldView){ var me = this; Ext.Viewport.setMasked({xtype:'loadmask',message:'正在删除'}); Ext.data.JsonP.request({ // 删除服务端记录: 最好做个标记,别真正删除?或者过期的和定期的不能删除? // 否则,删除过的题目,添加时候可能再出现 url: me.getApplication().dataUrl + 'deleteOne2nTopic.php', callbackKey: 'callback', params:{ ...
html: record.data.content, itemId: 'topicContent', styleHtmlContent: true }], }) this.overlay.show() } }, topicshowBack: function(oldView){ var me = this; Ext.Viewport.setActiveItem(me.topic) Ext.Viewport.remove(me.topicshow,true) }, top
conditional_block
networkBuilder.go
package builders import ( "bytes" "encoding/hex" "encoding/json" "fmt" "html/template" "io" "math/rand" "net" "os" "strings" "github.com/emicklei/dot" "github.com/pkg/errors" "github.com/threefoldtech/tfexplorer/client" "github.com/threefoldtech/tfexplorer/models/generated/workloads" "github.com/threef...
// WithStatsAggregator sets the stats aggregators to the network func (n *NetworkBuilder) WithStatsAggregator(aggregators []workloads.StatsAggregator) *NetworkBuilder { n.Network.StatsAggregator = aggregators return n } // WithNetworkResources sets the network resources to the network func (n *NetworkBuilder) With...
{ n.Network.Iprange = ipRange return n }
identifier_body
networkBuilder.go
package builders import ( "bytes" "encoding/hex" "encoding/json" "fmt" "html/template" "io" "math/rand" "net" "os" "strings" "github.com/emicklei/dot" "github.com/pkg/errors" "github.com/threefoldtech/tfexplorer/client" "github.com/threefoldtech/tfexplorer/models/generated/workloads" "github.com/threef...
func (n *NetworkBuilder) WithStatsAggregator(aggregators []workloads.StatsAggregator) *NetworkBuilder { n.Network.StatsAggregator = aggregators return n } // WithNetworkResources sets the network resources to the network func (n *NetworkBuilder) WithNetworkResources(netResources []workloads.NetworkNetResource) *Netw...
// WithStatsAggregator sets the stats aggregators to the network
random_line_split
networkBuilder.go
package builders import ( "bytes" "encoding/hex" "encoding/json" "fmt" "html/template" "io" "math/rand" "net" "os" "strings" "github.com/emicklei/dot" "github.com/pkg/errors" "github.com/threefoldtech/tfexplorer/client" "github.com/threefoldtech/tfexplorer/models/generated/workloads" "github.com/threef...
(subnet schema.IPRange) bool { _, block, err := net.ParseCIDR("100.64.0.0/10") if err != nil { panic(err) } return block.Contains(subnet.IP) } func (n *NetworkBuilder) extractAccessPoints() { // gather all actual nodes, using their wg pubkey as key in the map (NodeID // can't be seen in the actual peer struct)...
isCGN
identifier_name
networkBuilder.go
package builders import ( "bytes" "encoding/hex" "encoding/json" "fmt" "html/template" "io" "math/rand" "net" "os" "strings" "github.com/emicklei/dot" "github.com/pkg/errors" "github.com/threefoldtech/tfexplorer/client" "github.com/threefoldtech/tfexplorer/models/generated/workloads" "github.com/threef...
} // If the length is 0, then its a hidden node return endpoints, nil }
{ for _, ip := range iface.Addrs { if !ip.IP.IsGlobalUnicast() || isPrivateIP(ip.IP) { continue } endpoints = append(endpoints, ip) } }
conditional_block
mf6_data_tutorial06.py
# --- # jupyter: # jupytext: # text_representation:
# format_version: "1.5" # jupytext_version: 1.5.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # metadata: # section: mf6 # --- # # MODFLOW 6: Working with MODFLOW List Data. # # This tutorial shows how to view, access, and change the underlying data # varia...
# extension: .py # format_name: light
random_line_split
business-export-import.component.ts
//Import library import { Component, ViewChild, ElementRef, OnInit, AfterViewInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { MatTableDataSource } from '@angular/material/table'; import { MatPaginator } from '@angular/material/paginator'; import { Router } from '@angular/router'; import { tap, startW...
urrentDate = new Date(); return currentDate.getMonth() + 1; } public getCurrentYear() { var currentDate = new Date(); return currentDate.getFullYear(); } public getCurrentQuarter() { let currentDate = new Date(); let month = currentDate.getMonth() + 1; return month <= 3 ? 1 : month <= 6 ...
rn ''; } else { return value.trim(); } } public getCurrentMonth() { var c
identifier_body
business-export-import.component.ts
//Import library import { Component, ViewChild, ElementRef, OnInit, AfterViewInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { MatTableDataSource } from '@angular/material/table'; import { MatPaginator } from '@angular/material/paginator'; import { Router } from '@angular/router'; import { tap, startW...
valueOfYear, valueOfPeriodDetail); this._marketService.GetAllCompanyExport(valueOfPeriod, valueOfYear, valueOfPeriodDetail, this.isSCT).subscribe( allrecords => { if (allrecords.data.length > 0) { this.dataSource = new MatTableDataSource<CompanyDetailModel>(allrecords.data[0]); if...
valueOfYear = this.selectedYear; console.log(valueOfPeriod,
conditional_block
business-export-import.component.ts
//Import library import { Component, ViewChild, ElementRef, OnInit, AfterViewInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { MatTableDataSource } from '@angular/material/table'; import { MatPaginator } from '@angular/material/paginator'; import { Router } from '@angular/router'; import { tap, startW...
istrict()"); this._marketService.GetAllDistrict().subscribe( allrecords => { this.districtList = allrecords.data as DistrictModel[]; this.districtList.forEach(element => this.addresses.push(element.ten_quan_huyen)); }); } public getAllNganhNghe() { console.log("+ Function: GetAll...
ction: GetAllD
identifier_name
business-export-import.component.ts
//Import library import { Component, ViewChild, ElementRef, OnInit, AfterViewInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { MatTableDataSource } from '@angular/material/table'; import { MatPaginator } from '@angular/material/paginator'; import { Router } from '@angular/router'; import { tap, startW...
this.selectedYear = this.getCurrentYear(); break; case "Năm": this.selectedYear = this.getCurrentYear(); break; case "6 Tháng": this.selectedYear = this.getCurrentYear(); this.selectedHalf = 1; break; default: break; } } //Functio...
random_line_split
merge_queryable.go
package tenantfederation import ( "context" "fmt" "sort" "strings" "github.com/pkg/errors" "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb/chunkenc" tsdb_errors "github.com/prometheus/prometheus/tsdb/errors" "github.com/weavewor...
// rewrite label name to be more readable in error output func rewriteLabelName(s string) string { return strings.TrimRight(strings.TrimLeft(s, "_"), "_") } // this outputs a more readable error format func labelsToString(labels labels.Labels) string { parts := make([]string, len(labels)) for pos, l := range labe...
{ upstream := m.upstream.Warnings() warnings := make(storage.Warnings, len(upstream)) for pos := range upstream { warnings[pos] = errors.Wrapf(upstream[pos], "warning querying %s", labelsToString(m.labels)) } return warnings }
identifier_body
merge_queryable.go
package tenantfederation import ( "context" "fmt" "sort" "strings" "github.com/pkg/errors" "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb/chunkenc" tsdb_errors "github.com/prometheus/prometheus/tsdb/errors" "github.com/weavewor...
(src labels.Labels, additionalLabels ...labels.Label) labels.Labels { lb := labels.NewBuilder(src) for _, additionalL := range additionalLabels { if oldValue := src.Get(additionalL.Name); oldValue != "" { lb.Set( retainExistingPrefix+additionalL.Name, oldValue, ) } lb.Set(additionalL.Name, additi...
setLabelsRetainExisting
identifier_name
merge_queryable.go
package tenantfederation import ( "context" "fmt" "sort" "strings" "github.com/pkg/errors" "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb/chunkenc" tsdb_errors "github.com/prometheus/prometheus/tsdb/errors" "github.com/weavewor...
} // rewrite label name to be more readable in error output func rewriteLabelName(s string) string { return strings.TrimRight(strings.TrimLeft(s, "_"), "_") } // this outputs a more readable error format func labelsToString(labels labels.Labels) string { parts := make([]string, len(labels)) for pos, l := range lab...
} return warnings
random_line_split
merge_queryable.go
package tenantfederation import ( "context" "fmt" "sort" "strings" "github.com/pkg/errors" "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb/chunkenc" tsdb_errors "github.com/prometheus/prometheus/tsdb/errors" "github.com/weavewor...
return errs.Err() } type selectJob struct { pos int querier storage.Querier tenantID string } // Select returns a set of series that matches the given label matchers. If the // tenantLabelName is matched on it only considers those queriers matching. The // forwarded labelSelector is not containing those th...
{ errs.Add(errors.Wrapf(m.queriers[pos].Close(), "failed to close querier for %s %s", rewriteLabelName(defaultTenantLabel), tenantID)) }
conditional_block
model.py
# Imports here import torch import numpy as np from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from collections import OrderedDict from workspace_utils import active_session from PIL import Image import sys import os import json # Define...
(self, arch, learning_rate, hidden_units): ''' Function to build model ''' print('Building model...') # Select & load pre-trained model try: arch = arch.lower() self.model = models.__dict__[arch](pretrained=True) self.arch = arch excep...
build
identifier_name
model.py
# Imports here import torch import numpy as np from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from collections import OrderedDict from workspace_utils import active_session from PIL import Image import sys import os import json # Define...
def __init__(self, gpu): ''' Initialise model object ''' # Set device if (gpu): self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") else: self.device = "cpu" # Function to build model def build(self, arch, learning_rate,...
identifier_body
model.py
# Imports here import torch import numpy as np from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from collections import OrderedDict from workspace_utils import active_session from PIL import Image import sys import os import json # Define...
# Switch to evaluation mode - dropout inactive self.model.eval() # Disable gradients - not needed for model prediction with torch.no_grad(): # Do forward pass through network logps = self.model.forward(image_tensor) # Get actual probabilties output f...
# Convert to float tensor image_tensor = image_tensor.float()
random_line_split
model.py
# Imports here import torch import numpy as np from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from collections import OrderedDict from workspace_utils import active_session from PIL import Image import sys import os import json # Define...
# Classifier architecture parameters classifier_output_neurons = 102 classifier_dropout = 0.2 # Build new classifier for recognising flowers to work with model self.model.classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(classifi...
print("Unable to determine classifier input units number - unable to create model") return
conditional_block
longfruit.py
#!/usr/bin/env python3 from random import choice, choices, expovariate, randint, randrange, shuffle, uniform import configparser import os import re import string import subprocess import sys def georand(lmb): # roughly geometrically distributed return int(expovariate(lmb)) def random_id(): return ''.joi...
if c2 > c1: passed = True config = write_config(source_file, arch, abi, c1, c2) print('reducing') reduce_case(source_file) c1, c2, asm1, asm2 = run_test(source_file, arch, abi) write_result(sys.stdout, config, as...
passed = False for arch, abi in scenarios: c1, c2, asm1, asm2 = run_test(source_file, arch, abi) print(c1, c2)
random_line_split
longfruit.py
#!/usr/bin/env python3 from random import choice, choices, expovariate, randint, randrange, shuffle, uniform import configparser import os import re import string import subprocess import sys def georand(lmb): # roughly geometrically distributed return int(expovariate(lmb)) def random_id(): return ''.joi...
else: v = f'i{self.var_counter}' self.var_counter = self.var_counter + 1 self.vars.append(v) return v def gen_vars(self, num): return [self.gen_var() for i in range(randint(1, num))] def rand_var(self): return choice(self.vars) def copy(self): ...
v = f'v{self.var_counter}'
conditional_block
longfruit.py
#!/usr/bin/env python3 from random import choice, choices, expovariate, randint, randrange, shuffle, uniform import configparser import os import re import string import subprocess import sys def georand(lmb): # roughly geometrically distributed return int(expovariate(lmb)) def random_id(): return ''.joi...
def gen_test(filename): with open(filename, 'w') as f: ctx = Context() print(gen_unit(ctx), file=f) def test_file(filename, arch, abi): asm_gcc = compile('gcc', arch, abi, filename) c1 = get_cost(asm_gcc) asm_clang = compile('clang', arch, abi, filename) c2 = get_cost(asm_clang) ...
unit = gen_globals(ctx) unit = f'{unit}{gen_func(ctx)}\n' return unit
identifier_body
longfruit.py
#!/usr/bin/env python3 from random import choice, choices, expovariate, randint, randrange, shuffle, uniform import configparser import os import re import string import subprocess import sys def georand(lmb): # roughly geometrically distributed return int(expovariate(lmb)) def random_id(): return ''.joi...
(filename, arch, abi, cost1, cost2): config = configparser.ConfigParser() config.add_section('scenario') config['scenario']['filename'] = filename config['scenario']['arch'] = str(arch) config['scenario']['abi'] = str(abi) config['scenario']['cost1'] = str(cost1) config['scenario']['cost2'] ...
write_config
identifier_name
main.rs
use { serde::Deserialize, serde_json, serde_repr::Deserialize_repr, std::{collections::BTreeMap, io::Read, fs::File, process::Command}, }; fn main() -> Result<(), Failure> { let mut file = File::open("token")?; let mut token = String::new(); file.read_to_string(&mut token)?; token.inser...
(u64); #[derive(Debug, Deserialize)] struct Filter { id: FilterId, name: String, query: String, color: Color, item_order: Order, is_deleted: Flag, is_favorite: Flag, } #[derive(Debug, Deserialize)] struct FilterId(u64); #[derive(Debug, Deserialize)] struct Collaborator { id: Collabora...
LabelId
identifier_name
main.rs
use {
std::{collections::BTreeMap, io::Read, fs::File, process::Command}, }; fn main() -> Result<(), Failure> { let mut file = File::open("token")?; let mut token = String::new(); file.read_to_string(&mut token)?; token.insert_str(0, "token="); let output = &Command::new("curl").args(&["https://api.t...
serde::Deserialize, serde_json, serde_repr::Deserialize_repr,
random_line_split
secrets.go
package secret import ( "context" "encoding/json" "fmt" "sort" "strings" "time" "github.com/mittwald/kubernetes-replicator/replicate/common" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/types" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s...
// ReplicateDataFrom takes a source object and copies over data to target object func (r *Replicator) ReplicateDataFrom(sourceObj interface{}, targetObj interface{}) error { source := sourceObj.(*v1.Secret) target := targetObj.(*v1.Secret) // make sure replication is allowed logger := log. WithField("kind", r....
{ repl := Replicator{ GenericReplicator: common.NewGenericReplicator(common.ReplicatorConfig{ Kind: "Secret", ObjType: &v1.Secret{}, AllowAll: allowAll, ResyncPeriod: resyncPeriod, Client: client, ListFunc: func(lo metav1.ListOptions) (runtime.Object, error) { return clie...
identifier_body
secrets.go
package secret import ( "context" "encoding/json" "fmt" "sort" "strings" "time" "github.com/mittwald/kubernetes-replicator/replicate/common" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/types" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s...
replicatedKeys = append(replicatedKeys, key) delete(prevKeys, key) } if hasPrevKeys { for k := range prevKeys { logger.Debugf("removing previously present key %s: not present in source secret any more", k) delete(resourceCopy.Data, k) } } return replicatedKeys } func (r *Replicator) PatchDeleteDepen...
resourceCopy.Data[key] = newValue
random_line_split
secrets.go
package secret import ( "context" "encoding/json" "fmt" "sort" "strings" "time" "github.com/mittwald/kubernetes-replicator/replicate/common" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/types" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s...
} resourceCopy.Name = source.Name resourceCopy.Labels = labelsCopy resourceCopy.Type = targetResourceType resourceCopy.Annotations[common.ReplicatedAtAnnotation] = time.Now().Format(time.RFC3339) resourceCopy.Annotations[common.ReplicatedFromVersionAnnotation] = source.ResourceVersion resourceCopy.Annotations[...
{ for key, value := range source.Labels { labelsCopy[key] = value } }
conditional_block
secrets.go
package secret import ( "context" "encoding/json" "fmt" "sort" "strings" "time" "github.com/mittwald/kubernetes-replicator/replicate/common" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/types" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s...
(sourceKey string, target interface{}) (interface{}, error) { dependentKey := common.MustGetKey(target) logger := log.WithFields(log.Fields{ "kind": r.Kind, "source": sourceKey, "target": dependentKey, }) targetObject, ok := target.(*v1.Secret) if !ok { err := errors.Errorf("bad type returned from Store...
PatchDeleteDependent
identifier_name
lib.rs
#![recursion_limit = "1024"] #[macro_use] extern crate derive_new; #[macro_use] extern crate derive_setters; #[macro_use] extern crate log; #[macro_use] extern crate thiserror; pub mod checksum; mod range; mod systems; pub use self::systems::*; use std::{ fmt::Debug, io, num::{NonZeroU16, NonZeroU32, No...
async fn supports_range( client: &Client, uri: &str, length: u64, ) -> Result<bool, Error> { let response = client .head(uri) .header("Expect", "") .header("range", range::to_string(0, length).as_str()) .await?; if response.status() == StatusCode::PartialContent { ...
}
random_line_split
lib.rs
#![recursion_limit = "1024"] #[macro_use] extern crate derive_new; #[macro_use] extern crate derive_setters; #[macro_use] extern crate log; #[macro_use] extern crate thiserror; pub mod checksum; mod range; mod systems; pub use self::systems::*; use std::{ fmt::Debug, io, num::{NonZeroU16, NonZeroU32, No...
{ /// Signals that this file was already fetched. AlreadyFetched, /// States that we know the length of the file being fetched. ContentLength(u64), /// Notifies that the file has been fetched. Fetched, /// Notifies that a file is being fetched. Fetching, /// Reports the amount of by...
FetchEvent
identifier_name
lib.rs
#![recursion_limit = "1024"] #[macro_use] extern crate derive_new; #[macro_use] extern crate derive_setters; #[macro_use] extern crate log; #[macro_use] extern crate thiserror; pub mod checksum; mod range; mod systems; pub use self::systems::*; use std::{ fmt::Debug, io, num::{NonZeroU16, NonZeroU32, No...
trait ResponseExt { fn content_length(&self) -> Option<u64>; fn last_modified(&self) -> Option<DateTime<Utc>>; } impl ResponseExt for Response { fn content_length(&self) -> Option<u64> { let header = self.header("content-lenght")?.get(0)?; header.as_str().parse::<u64>().ok() } fn...
{ let status = response.status(); if status.is_informational() || status.is_success() { Ok(response) } else { Err(Error::Status(status)) } }
identifier_body
statformat.py
#!/usr/bin/env python3 # ====================================================================== # # This file contains functions used for formatting statistical data # returned by SPARQL queries on NIDM-Results packs. # # Authors: Peter Williams, Tom Maullin, Camille Maumet (10/01/18) # # ==============================...
peakPVals = [float(peakQueryResult[i]) for i in list( range(4, len(peakQueryResult), 5))] # This is a temporary bug fix due to the FSL exporter currently not # recording corrected peak P-values. except ValueError: peakPVals = [math.nan for row i...
peakPVals = [float(peakQueryResult[i]) for i in list( range(3, len(peakQueryResult), 5))] else:
random_line_split
statformat.py
#!/usr/bin/env python3 # ====================================================================== # # This file contains functions used for formatting statistical data # returned by SPARQL queries on NIDM-Results packs. # # Authors: Peter Williams, Tom Maullin, Camille Maumet (10/01/18) # # ==============================...
elif stat == "http://purl.obolibrary.org/obo/STATO_0000282": return("F") elif stat == "http://purl.obolibrary.org/obo/STATO_0000176": return("T") else: return("P") # This function returns the cluster forming threshold type of an image. def height_thresh_type(graph, imageType...
return("Z")
conditional_block
statformat.py
#!/usr/bin/env python3 # ====================================================================== # # This file contains functions used for formatting statistical data # returned by SPARQL queries on NIDM-Results packs. # # Authors: Peter Williams, Tom Maullin, Camille Maumet (10/01/18) # # ==============================...
# This function takes in an excursion set name and a graph and generates # an FSL-like name for the HTML output display for the excursionset. # # e.g. ExcursionSet_F001.nii.gz -> cluster_zfstat1_std.html def get_clus_filename(g, excName): # For SPM data we can't work out the filename we want from just # the...
from matplotlib import pyplot as plt conLength = len(data) # We invert the values so the colours appear correctly (i. # e. 1 -> white, 0 -> black). data = np.ones(len(data))-data # Make the contrast vector larger so we can make an image. data = np.kron(data, np.ones((10, 30))) # Add bord...
identifier_body
statformat.py
#!/usr/bin/env python3 # ====================================================================== # # This file contains functions used for formatting statistical data # returned by SPARQL queries on NIDM-Results packs. # # Authors: Peter Williams, Tom Maullin, Camille Maumet (10/01/18) # # ==============================...
(statImage): if statImage == "T": return("T") elif statImage == "F": return("F") elif statImage == "Z": return("Z (Gaussianised T/F)") def format_cluster_stats(g, excName): # ---------------------------------------------------------------------- # First we gather dat...
statistic_type_string
identifier_name
message_partition.go
package store import ( "encoding/binary" "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "sync" ) var MAGIC_NUMBER = []byte{42, 249, 180, 108, 82, 75, 222, 182} var FILE_FORMAT_VERSION = []byte{1} var MESSAGES_PER_FILE = uint64(10000) var INDEX_ENTRY_SIZE = 12 type fetchEntry struct { messageI...
func (p *MessagePartition) Close() error { p.mutex.Lock() defer p.mutex.Unlock() return p.closeAppendFiles() } func (p *MessagePartition) DoInTx(fnToExecute func(maxMessageId uint64) error) error { p.mutex.Lock() defer p.mutex.Unlock() return fnToExecute(p.maxMessageId) } func (p *MessagePartition) StoreTx(pa...
return nil }
random_line_split
message_partition.go
package store import ( "encoding/binary" "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "sync" ) var MAGIC_NUMBER = []byte{42, 249, 180, 108, 82, 75, 222, 182} var FILE_FORMAT_VERSION = []byte{1} var MESSAGES_PER_FILE = uint64(10000) var INDEX_ENTRY_SIZE = 12 type fetchEntry struct { messageI...
(file *os.File, indexPosition int64) (msgOffset uint64, msgSize uint32, err error) { msgOffsetBuff := make([]byte, INDEX_ENTRY_SIZE) if _, err := file.ReadAt(msgOffsetBuff, indexPosition); err != nil { return 0, 0, err } msgOffset = binary.LittleEndian.Uint64(msgOffsetBuff) msgSize = binary.LittleEndian.Uint32(m...
readIndexEntry
identifier_name
message_partition.go
package store import ( "encoding/binary" "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "sync" ) var MAGIC_NUMBER = []byte{42, 249, 180, 108, 82, 75, 222, 182} var FILE_FORMAT_VERSION = []byte{1} var MESSAGES_PER_FILE = uint64(10000) var INDEX_ENTRY_SIZE = 12 type fetchEntry struct { messageI...
index, errIndex := os.OpenFile(p.indexFilenameByMessageId(firstMessageIdForFile), os.O_RDWR|os.O_CREATE, 0666) if errIndex != nil { defer file.Close() defer os.Remove(file.Name()) return err } p.appendFile = file p.appendIndexFile = index p.appendFirstId = firstMessageIdForFile p.appendLastId = firstMes...
{ p.appendFileWritePosition = uint64(stat.Size()) _, err = file.Write(MAGIC_NUMBER) if err != nil { return err } _, err = file.Write(FILE_FORMAT_VERSION) if err != nil { return err } }
conditional_block
message_partition.go
package store import ( "encoding/binary" "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "sync" ) var MAGIC_NUMBER = []byte{42, 249, 180, 108, 82, 75, 222, 182} var FILE_FORMAT_VERSION = []byte{1} var MESSAGES_PER_FILE = uint64(10000) var INDEX_ENTRY_SIZE = 12 type fetchEntry struct { messageI...
func (p *MessagePartition) store(msgId uint64, msg []byte) error { if msgId != 1+p.maxMessageId { return fmt.Errorf("Invalid message id for partition %v. Next id should be %v, but was %q", p.name, 1+p.maxMessageId, msgId) } if msgId > p.appendLastId || p.appendFile == nil || p.appendIndexFile == nil { if...
{ p.mutex.Lock() defer p.mutex.Unlock() return p.store(msgId, msg) }
identifier_body
credential.rs
//! Internal `Credential` and external `CredentialId` ("keyhandle"). use core::cmp::Ordering; use trussed::{client, syscall, try_syscall, types::KeyId}; pub(crate) use ctap_types::{ // authenticator::{ctap1, ctap2, Error, Request, Response}, ctap2::credential_management::CredentialProtectionPolicy, sizes...
<UP: UserPresence, T: client::Client + client::Chacha8Poly1305>( authnr: &mut Authenticator<UP, T>, rp_id_hash: &Bytes<32>, id: &[u8], ) -> Result<Self> { let mut cred: Bytes<MAX_CREDENTIAL_ID_LENGTH> = Bytes::new(); cred.extend_from_slice(id) .map_err(|_| Error::...
try_from_bytes
identifier_name
credential.rs
//! Internal `Credential` and external `CredentialId` ("keyhandle"). use core::cmp::Ordering; use trussed::{client, syscall, try_syscall, types::KeyId}; pub(crate) use ctap_types::{ // authenticator::{ctap1, ctap2, Error, Request, Response}, ctap2::credential_management::CredentialProtectionPolicy, sizes...
#[derive(Copy, Clone, Debug, serde::Deserialize, serde::Serialize)] pub enum CtapVersion { U2fV2, Fido20, Fido21Pre, } /// External ID of a credential, commonly known as "keyhandle". #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct CredentialId(pub Bytes<MAX_CREDENTIAL_ID_L...
/// As signaled in `get_info`. /// /// Eventual goal is full support for the CTAP2.1 specification.
random_line_split
credential.rs
//! Internal `Credential` and external `CredentialId` ("keyhandle"). use core::cmp::Ordering; use trussed::{client, syscall, try_syscall, types::KeyId}; pub(crate) use ctap_types::{ // authenticator::{ctap1, ctap2, Error, Request, Response}, ctap2::credential_management::CredentialProtectionPolicy, sizes...
} } pub fn try_from<UP: UserPresence, T: client::Client + client::Chacha8Poly1305>( authnr: &mut Authenticator<UP, T>, rp_id_hash: &Bytes<32>, descriptor: &PublicKeyCredentialDescriptor, ) -> Result<Self> { Self::try_from_bytes(authnr, rp_id_hash, &descriptor.id) ...
{ info_now!("could not deserialize {:?}", bytes); Err(Error::Other) }
conditional_block
dns.go
package dns import ( "bufio" "encoding/binary" "errors" "fmt" "net" "os" "strings" "time" "unsafe" "k8s.io/klog/v2" "github.com/kubeedge/kubeedge/edge/pkg/metamanager/client" "github.com/kubeedge/kubeedge/edgemesh/pkg/common" "github.com/kubeedge/kubeedge/edgemesh/pkg/config" "github.com/kubeedge/kubee...
offset := uint16(unsafe.Sizeof(dnsHeader{})) // DNS NS <ROOT> operation if req[offset] == 0x0 { que.event = eventUpstream return } que.getQuestion(req, offset, head) err = nil return } // isAQuery judges if the dns pkg is a query func (h *dnsHeader) isAQuery() bool { return h.flags&dnsQR != dnsQR } // g...
{ que.event = eventUpstream return }
conditional_block
dns.go
package dns import ( "bufio" "encoding/binary" "errors" "fmt" "net" "os" "strings" "time" "unsafe" "k8s.io/klog/v2" "github.com/kubeedge/kubeedge/edge/pkg/metamanager/client" "github.com/kubeedge/kubeedge/edgemesh/pkg/common" "github.com/kubeedge/kubeedge/edgemesh/pkg/config" "github.com/kubeedge/kubee...
(que *dnsQuestion, req []byte) (rsp []byte, err error) { var exist bool var ip string // qType should be 1 for ipv4 if que.name != nil && que.qType == aRecord { domainName := string(que.name) exist, ip = lookupFromMetaManager(domainName) } if !exist || que.event == eventUpstream { // if this service doesn'...
recordHandle
identifier_name
dns.go
package dns
"bufio" "encoding/binary" "errors" "fmt" "net" "os" "strings" "time" "unsafe" "k8s.io/klog/v2" "github.com/kubeedge/kubeedge/edge/pkg/metamanager/client" "github.com/kubeedge/kubeedge/edgemesh/pkg/common" "github.com/kubeedge/kubeedge/edgemesh/pkg/config" "github.com/kubeedge/kubeedge/edgemesh/pkg/liste...
import (
random_line_split
dns.go
package dns import ( "bufio" "encoding/binary" "errors" "fmt" "net" "os" "strings" "time" "unsafe" "k8s.io/klog/v2" "github.com/kubeedge/kubeedge/edge/pkg/metamanager/client" "github.com/kubeedge/kubeedge/edgemesh/pkg/common" "github.com/kubeedge/kubeedge/edgemesh/pkg/config" "github.com/kubeedge/kubee...
// setRspRCode sets dns response return code func (h *dnsHeader) setRspRCode(que *dnsQuestion) { if que.qType != aRecord { h.flags &= (^errNotImplemented) h.flags |= errNotImplemented } else if que.event == eventNxDomain { h.flags &= (^errRefused) h.flags |= errRefused } } // getByteFromDNSHeader converts...
{ h.anCount = num }
identifier_body
getprimers.py
import pandas as pd import re import sqlite3 as lite import os from pybedtools import BedTool import django from checkprimers import CheckPrimers from pandas import ExcelWriter import datetime os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' django.setup() class GetPrimers(object): """Extracts data from e...
df_primers_dups = pd.read_excel(self.excel_file, header=0, parse_cols='A:M, O:X', skiprows=2, names=['Gene', 'Exon', 'Direction', 'Version', 'Primer_seq', 'Chrom', 'M13_tag', 'Batch', 'project', 'Order_date', 'Frag_size', 'an...
:param sheetname: sheet data to be extracted from :return df_primers_dups: data frame containing extracted data which may include duplicates. :return df_primers: data frame containing only data necessary to get genome coordinates. """
random_line_split
getprimers.py
import pandas as pd import re import sqlite3 as lite import os from pybedtools import BedTool import django from checkprimers import CheckPrimers from pandas import ExcelWriter import datetime os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' django.setup() class GetPrimers(object): """Extracts data from e...
(self, csv): """Runs virtual PCR on a CSV file using the isPcr and pslToBed tools installed from UCSC. :param csv: a csv file is need as an input with format "name, forward, reverse". :return bedfile: with results of virtual PCR if there is a match. """ print "Ru...
run_pcr
identifier_name
getprimers.py
import pandas as pd import re import sqlite3 as lite import os from pybedtools import BedTool import django from checkprimers import CheckPrimers from pandas import ExcelWriter import datetime os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' django.setup() class GetPrimers(object): """Extracts data from e...
forwards = primer_list[::2] reverses = primer_list[1::2] while list_position < len(forwards): ser = pd.Series([names[list_position], forwards[list_position], reverses[list_position]]) primer_seqs = primer_seqs.append(ser, ignore_index=True) list_position +=...
names.append(item)
conditional_block
getprimers.py
import pandas as pd import re import sqlite3 as lite import os from pybedtools import BedTool import django from checkprimers import CheckPrimers from pandas import ExcelWriter import datetime os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' django.setup() class GetPrimers(object): """Extracts data from e...
def all(self): """Combines all methods""" sheetname = self.get_sheet_name() df_primers_dups, df_primers = self.get_primers(sheetname) df_coords = self.get_coords(df_primers) df_combined, gene = self.combine_coords_primers(df_coords, df_primers_dups) info, archived_f...
"""Creates tables and adds data into the database. Function modifies the given data frame to generate three tables in the database (Primers, SNPs, Genes) and performs data checks. If data for a particular gene is already in the database, this is overridden and the previous data is saved...
identifier_body
lib.rs
/* * Copyright 2015-2017 Two Pore Guys, Inc. * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted providing that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of...
{ code: u32, message: String, stack_trace: Box<Value>, extra: Box<Value> } #[link(name = "rpc")] extern { /* rpc/object.h */ pub fn rpc_get_type(value: *mut RawObject) -> RawType; pub fn rpc_hash(value: *mut RawObject) -> u32; pub fn rpc_null_create() -> *mut RawObject; pub fn rpc_...
Error
identifier_name
lib.rs
/* * Copyright 2015-2017 Two Pore Guys, Inc. * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted providing that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of...
Uint64, Int64, Double, Date, String, Binary, Fd, Dictionary, Array, Error, } #[repr(C)] #[derive(Debug)] pub enum CallStatus { InProgress, MoreAvailable, Done, Error, Aborted, Ended } pub enum RawObject {} pub enum RawConnection {} pub enum RawClient {} ...
random_line_split
pirep.py
"""Pilot Reports (PIREP) This module attempts to process and store atomic data from PIREPs. These are encoded products that look like so: UBUS01 KMSC 221700 EAU UA /OV EAU360030/TM 1715/FL350/TP B737/TB CONT LGT-MOD CHOP = EHY UA /OV MBW253036 /TM 1729 /FL105 /TP C206 /SK FEW250 /TA M06 /TB NEG /RM SMTH= Un...
(BaseModel): """ A Pilot Report. """ base_loc: str = None text: str = None priority: Priority = None latitude: float = None longitude: float = None valid: datetime.datetime = None cwsu: str = None aircraft_type: str = None is_duplicate: bool = False class Pirep(product.TextPro...
PilotReport
identifier_name
pirep.py
"""Pilot Reports (PIREP) This module attempts to process and store atomic data from PIREPs. These are encoded products that look like so: UBUS01 KMSC 221700 EAU UA /OV EAU360030/TM 1715/FL350/TP B737/TB CONT LGT-MOD CHOP = EHY UA /OV MBW253036 /TM 1729 /FL105 /TP C206 /SK FEW250 /TA M06 /TB NEG /RM SMTH= Un...
return res def sql(self, txn): """ Save the reports to the database via the transaction """ for report in self.reports: if report.is_duplicate: continue txn.execute( "INSERT into pireps(valid, geom, is_urgent, " "aircr...
res -= datetime.timedelta(hours=24)
conditional_block
pirep.py
"""Pilot Reports (PIREP) This module attempts to process and store atomic data from PIREPs. These are encoded products that look like so: UBUS01 KMSC 221700 EAU UA /OV EAU360030/TM 1715/FL350/TP B737/TB CONT LGT-MOD CHOP = EHY UA /OV MBW253036 /TM 1729 /FL105 /TP C206 /SK FEW250 /TA M06 /TB NEG /RM SMTH= Un...
def compute_pirep_valid(self, hour, minute): """ Based on what utcnow is set to, compute when this is valid """ res = self.utcnow.replace( hour=hour, minute=minute, second=0, microsecond=0 ) if hour > self.utcnow.hour: res -= datetime.timedelta(hours=24) ...
""" Figure out the lon/lat for this location """ lat = self.nwsli_provider[loc]["lat"] lon = self.nwsli_provider[loc]["lon"] # shortcut if dist == 0: return lon, lat meters = distance(float(dist), "MI").value("M") northing = meters * math.cos(math.radians(bear...
identifier_body
pirep.py
"""Pilot Reports (PIREP) This module attempts to process and store atomic data from PIREPs. These are encoded products that look like so: UBUS01 KMSC 221700 EAU UA /OV EAU360030/TM 1715/FL350/TP B737/TB CONT LGT-MOD CHOP = EHY UA /OV MBW253036 /TM 1729 /FL105 /TP C206 /SK FEW250 /TA M06 /TB NEG /RM SMTH= Un...
report.text, ), ) def assign_cwsu(self, txn): """ Use this transaction object to assign CWSUs for the pireps """ for report in self.reports: txn.execute( "select distinct id from cwsu WHERE " "st_contains(ge...
report.aircraft_type,
random_line_split
requester.go
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicabl...
} // sync send func (b *Work) syncSend(throttle <-chan time.Time, client http.Client) { for i := 0; ; i++ { if time.Now().Sub(b.startTime) > b.PerformanceTimeout { break } if b.QPS > 0 { <-throttle } select { case <-b.stopCh: break default: requestParam := b.getRequestParam(i) b.makeRequ...
{ if b.QPS > 0 { <-throttle } select { case <-b.stopCh: break default: requestParam := b.getRequestParam(i*b.C + widx) b.makeRequest(&client, &requestParam) } }
conditional_block
requester.go
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicabl...
return os.Stdout } return b.Writer } // Run makes all the requests, prints the summary. It blocks until // all work is done. func (b *Work) Run() { // append hey's user agent ua := b.Request.UserAgent() if ua == "" { ua = megSenderUA } else { ua += " " + megSenderUA } b.results = make(chan *result) b.s...
func (b *Work) writer() io.Writer { if b.Writer == nil {
random_line_split
requester.go
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicabl...
() io.Writer { if b.Writer == nil { return os.Stdout } return b.Writer } // Run makes all the requests, prints the summary. It blocks until // all work is done. func (b *Work) Run() { // append hey's user agent ua := b.Request.UserAgent() if ua == "" { ua = megSenderUA } else { ua += " " + megSenderUA } ...
writer
identifier_name
requester.go
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicabl...
/** // cloneRequest returns a clone of the provided *http.Request. // The clone is a shallow copy of the struct and its Header map. func cloneRequest(r *http.Request, body []byte) *http.Request { // shallow copy of the struct r2 := new(http.Request) *r2 = *r // deep copy of the Header r2.Header = make(http.Heade...
{ var wg sync.WaitGroup wg.Add(b.C) for i := 0; i < b.C; i++ { go func(i int) { b.runWorker(b.N/(b.C), i) defer wg.Done() }(i) } wg.Wait() }
identifier_body
type_check.rs
use std::collections::HashMap; use std::rc::Rc; use parsing::{AST, Statement, Declaration, Signature, Expression, ExpressionType, Operation, Variant, TypeName, TypeSingletonName}; // from Niko's talk /* fn type_check(expression, expected_ty) -> Ty { let ty = bare_type_check(expression, expected_type); if ty ...
{ symbol_table: HashMap<PathSpecifier, TypeContextEntry>, evar_table: HashMap<u64, Type>, existential_type_label_count: u64 } impl TypeContext { pub fn new() -> TypeContext { TypeContext { symbol_table: HashMap::new(), evar_table: HashMap::new(), existential_type_label_count: 0, } }...
ypeContext
identifier_name
type_check.rs
use std::collections::HashMap; use std::rc::Rc; use parsing::{AST, Statement, Declaration, Signature, Expression, ExpressionType, Operation, Variant, TypeName, TypeSingletonName}; // from Niko's talk /* fn type_check(expression, expected_ty) -> Ty { let ty = bare_type_check(expression, expected_type); if ty ...
}, (ref t1, &TVar(Exist(ref a))) => { let x = self.evar_table.get(a).map(|x| x.clone()); match x { Some(ref t2) => self.unify(t2.clone().clone(), t1.clone().clone()), None => { self.evar_table.insert(*a, t1.clone().clone()); Ok(t1.clone().clone()) ...
}
random_line_split
chinpnr_account_pull.py
#!/usr/bin/python # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait import pymysql db = py...
'6000060295245128', '6000060295298124', '6000060295371605', '6000060295427413', '6000060295767894', '6000060295876437'] # usrids = ['6000060269448244', '6000060269448119', '6000060269652085'] import time import requests from lxml import html browser = webdriver.Chrome() browser.get("https...
'6000060291243806', '6000060291340862', '6000060291431540', '6000060291483681', '6000060291553294', '6000060291706959', '6000060292219430', '6000060292566439', '6000060292741605', '6000060293019252', '6000060293381519', '6000060293320112', '6000060293384730', '6000060293387871', '6000060...
random_line_split
chinpnr_account_pull.py
#!/usr/bin/python # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait import pymysql db = py...
(data): # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 插入语句 sql = "INSERT INTO tb_chinapnr_account_detail(create_time, \ serial_number, usr_id, user_name, acct_type,debit_or_credit_mark,tran_amount,free_amount,acct_amount,in_usr_id,buss_type,des_note) \ VALUES ('%s', '%s', '%s', '...
insert
identifier_name
chinpnr_account_pull.py
#!/usr/bin/python # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait import pymysql db = py...
if i != 1: next = browser.find_element_by_xpath('//p[@class="page"]/a[@title="Next"]') next.click() wait.until(EC.presence_of_element_located( (By.XPATH, '//p[@class="page"]/a[@class="current" and @title="' + str(i) + '"]'))) ...
conditional_block
chinpnr_account_pull.py
#!/usr/bin/python # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait import pymysql db = py...
453923', '6000060269456948', '6000060269455093', '6000060269455994', '6000060269459071', '6000060269455869', '6000060269456118', '6000060269456261', '6000060269457616', '6000060269462708', '6000060269461736', '6000060269463618', '6000060269652085', '6000060269469033', '6000060269480234'...
# SQL 插入语句 sql = "INSERT INTO tb_chinapnr_account_detail(create_time, \ serial_number, usr_id, user_name, acct_type,debit_or_credit_mark,tran_amount,free_amount,acct_amount,in_usr_id,buss_type,des_note) \ VALUES ('%s', '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s')" % \ ...
identifier_body
viewer.js
"use strict"; var Viewer = { // The arguments received args: {}, // Registered game loaders supportedGames: {}, // Current loaded game game: null, speed: 3.0, // Turns per second // msPerFrame: 16, // Milliseconds between updates lastTick: 0, lastRender: 0, nextTick: null, playing: ...
else game = this.args.game; if (!game) { $("File").addEventListener("change", function(ev) { if (ev.target.files.length > 0) { Viewer.loadFromFile(ev.target.files[0]); } }, false); this.showOverlay("Upload"); } else this.loadFromURL(game); }, show...
{ // Arguments passed by Jutge if (location.host) game = location.protocol + "//" + location.host + "/"; else game = "https://battle-royale-eda.jutge.org/"; if (this.args.nbr) { game += "?cmd=lliuraments&sub="+this.args.sub+"&nbr="+this.args.nbr+"&download=partida"; } else game += ...
conditional_block
viewer.js
"use strict"; var Viewer = { // The arguments received args: {}, // Registered game loaders supportedGames: {}, // Current loaded game game: null, speed: 3.0, // Turns per second // msPerFrame: 16, // Milliseconds between updates lastTick: 0, lastRender: 0, nextTick: null, playing: ...
this.music = new Audio(); this.music.loop = true; this.music.addEventListener("canplay", function() { Viewer.loaded(); }, false); this.music.src = url; }, stopMusic: function() { if (this.music != null) { this.music.pause(); this.music = null; } }, showHelp: function() ...
loadMusic: function(url) { ++this.loading; this.stopMusic();
random_line_split
keyboard.rs
// Copyright 2020 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...
0x004D => Code::NumLock, 0x004E => Code::ScrollLock, 0x004F => Code::Numpad7, 0x0050 => Code::Numpad8, 0x0051 => Code::Numpad9, 0x0052 => Code::NumpadSubtract, 0x0053 => Code::Numpad4, 0x0054 => Code::Numpad5, 0x0055 => Code::Numpad6, 0x005...
0x0049 => Code::F7, 0x004A => Code::F8, 0x004B => Code::F9, 0x004C => Code::F10,
random_line_split
keyboard.rs
// Copyright 2020 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...
(code: Code, m: Modifiers) -> Key { fn a(s: &str) -> Key { Key::Character(s.into()) } fn s(mods: Modifiers, base: &str, shifted: &str) -> Key { if mods.contains(Modifiers::SHIFT) { Key::Character(shifted.into()) } else { Key::Character(base.into()) } ...
code_to_key
identifier_name
keyboard.rs
// Copyright 2020 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 n(mods: Modifiers, base: Key, num: &str) -> Key { if mods.contains(Modifiers::NUM_LOCK) != mods.contains(Modifiers::SHIFT) { Key::Character(num.into()) } else { base } } match code { Code::KeyA => s(m, "a", "A"), Code::KeyB => s(m, "b", "B"...
{ if mods.contains(Modifiers::SHIFT) { Key::Character(shifted.into()) } else { Key::Character(base.into()) } }
identifier_body
motion-export-dialog.component.ts
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; import { MatButtonToggle, MatButtonToggleChange } from '@angular/material/button-toggle'; import { MatDialogRef } from '@angular/material/dialog'; import { auditTime, O...
/** * Function to change the state of the property `disabled` of a given button. * * Ensures, that the button exists. * * @param button The button whose state will change. * @param nextState The next state the button will assume. */ private changeStateOfButton(button: MatBut...
{ if (event.value.includes(MOTION_PDF_OPTIONS.ContinuousText)) { this.tocButton.checked = false; this.addBreaksButton.checked = false; } }
identifier_body
motion-export-dialog.component.ts
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; import { MatButtonToggle, MatButtonToggleChange } from '@angular/material/button-toggle'; import { MatDialogRef } from '@angular/material/dialog'; import { auditTime, O...
else { this.enableControl(`content`); this.changeStateOfButton(this.speakersButton, true); } if (format === ExportFileFormat.CSV || format === ExportFileFormat.XLSX) { this.disableControl(`lnMode`); this.disableControl(`crMode`); this.disable...
{ this.disableControl(`content`); this.changeStateOfButton(this.speakersButton, false); }
conditional_block
motion-export-dialog.component.ts
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; import { MatButtonToggle, MatButtonToggleChange } from '@angular/material/button-toggle'; import { MatDialogRef } from '@angular/material/dialog'; import { auditTime, O...
@Component({ selector: `os-motion-export-dialog`, templateUrl: `./motion-export-dialog.component.html`, styleUrls: [`./motion-export-dialog.component.scss`], encapsulation: ViewEncapsulation.None }) export class MotionExportDialogComponent extends BaseUiComponent implements OnInit { /** * impor...
random_line_split
motion-export-dialog.component.ts
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; import { MatButtonToggle, MatButtonToggleChange } from '@angular/material/button-toggle'; import { MatDialogRef } from '@angular/material/dialog'; import { auditTime, O...
(): void { this.dialogRef.close(); } /** * Gets the untranslated label for metaData */ public getLabelForMetadata(metaDataName: string): string { switch (metaDataName) { case `polls`: { return `Voting result`; } case `id`: { ...
onCloseClick
identifier_name
watched_bitfield.rs
use crate::{BitField8, Error}; use std::{ fmt::{self, Display}, str::FromStr, }; /// (De)Serializable field that tracks which videos have been watched /// and the latest one watched. /// /// This is a [`WatchedBitField`] compatible field, (de)serialized /// without the knowledge of `videos_ids`. /// /// `{anch...
} /// Module containing all the impls of the `serde` feature #[cfg(feature = "serde")] mod serde { use std::str::FromStr; use serde::{de, Serialize}; use super::WatchedField; impl<'de> serde::Deserialize<'de> for WatchedField { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> ...
{ watched.bitfield }
identifier_body
watched_bitfield.rs
use crate::{BitField8, Error}; use std::{ fmt::{self, Display}, str::FromStr, }; /// (De)Serializable field that tracks which videos have been watched /// and the latest one watched. /// /// This is a [`WatchedBitField`] compatible field, (de)serialized /// without the knowledge of `videos_ids`. /// /// `{anch...
() { let watched = WatchedBitField::construct_and_resize("undefined:1:eJwDAAAAAAE=", vec![]); assert_eq!( watched, Ok(WatchedBitField { bitfield: BitField8::new(0), video_ids: vec![] }) ); } }
deserialize_empty
identifier_name
watched_bitfield.rs
use crate::{BitField8, Error}; use std::{ fmt::{self, Display}, str::FromStr, }; /// (De)Serializable field that tracks which videos have been watched /// and the latest one watched. /// /// This is a [`WatchedBitField`] compatible field, (de)serialized /// without the knowledge of `videos_ids`. /// /// `{anch...
} pub fn set(&mut self, idx: usize, v: bool) { self.bitfield.set(idx, v); } pub fn set_video(&mut self, video_id: &str, v: bool) { if let Some(pos) = self.video_ids.iter().position(|s| *s == video_id) { self.bitfield.set(pos, v); } } } impl fmt::Display for Wa...
{ false }
conditional_block
watched_bitfield.rs
use crate::{BitField8, Error}; use std::{ fmt::{self, Display}, str::FromStr, }; /// (De)Serializable field that tracks which videos have been watched /// and the latest one watched. /// /// This is a [`WatchedBitField`] compatible field, (de)serialized /// without the knowledge of `videos_ids`. /// /// `{anch...
for i in 0..video_ids.len() { // TODO: Check what will happen if we change it to `usize` let id_in_prev = i as i32 + offset; if id_in_prev >= 0 && (id_in_prev as usize) < bitfield.length { resized_wbf.set(i, bitfield.get...
bitfield: BitField8::new(video_ids.len()), video_ids: video_ids.clone(), }; // rewrite the old buf into the new one, applying the offset
random_line_split
pisco_redsequence.py
import sys import os import pandas as pd import numpy as np import subprocess import shlex from astropy.coordinates import SkyCoord from astropy import units as u from astropy.table import Table import matplotlib.pyplot as plt from matplotlib import image import matplotlib import extra_program as ex import ezgal fr...
# adding the slope for different color set that we are interested in (01_rsz_test,fit_gr_ri01.ipyn) def blue_model(color,mags,redshift,red_mag): #g-r if color=='sloan_g-sloan_r': blue_mag=(0.787302458781+2.9352*redshift)+red_mag elif color=='sloan_r-sloan_i': if redshift <= 0.36: ...
if color=='sloan_r-sloan_z': slope_r_m_i=-0.0192138872893 slope_r_m_z=(1.584 * slope_r_m_i) slope_fit=[slope_r_m_z, 0] i_band0=-20. elif color=='sloan_g-sloan_i': slope_v_m_i=-0.029 slope_g_m_i=(1.481 * slope_v_m_i) slope_fit=[slope_g_m_i, 0] i_band0=-...
identifier_body
pisco_redsequence.py
import sys import os import pandas as pd import numpy as np import subprocess import shlex from astropy.coordinates import SkyCoord from astropy import units as u from astropy.table import Table import matplotlib.pyplot as plt from matplotlib import image import matplotlib import extra_program as ex import ezgal fr...
(fname): with open(fname) as f: content = f.readlines() content = [x.strip() for x in content] band=[x.split(' ')[0][-1] for x in content[5:-1]] corr=[float(x.split(' ')[1]) for x in content[5:-1]] ecorr=[float(x.split(' ')[3]) for x in content[5:-1]] return zip(band,corr,ecorr), corr d...
find_offset
identifier_name
pisco_redsequence.py
import sys import os import pandas as pd import numpy as np import subprocess import shlex from astropy.coordinates import SkyCoord from astropy import units as u from astropy.table import Table import matplotlib.pyplot as plt from matplotlib import image import matplotlib import extra_program as ex import ezgal fr...
elif color=='sloan_r-sloan_i': if redshift <= 0.36: blue_mag=(0.348871987852+0.75340856*redshift)+red_mag else: blue_mag=(-0.210727367027+2.2836974*redshift)+red_mag else: print 'This color has not been implemented.' return blue_mag def histogram_plot(xranf,...
blue_mag=(0.787302458781+2.9352*redshift)+red_mag
conditional_block
pisco_redsequence.py
import sys import os import pandas as pd import numpy as np import subprocess import shlex from astropy.coordinates import SkyCoord from astropy import units as u from astropy.table import Table import matplotlib.pyplot as plt from matplotlib import image import matplotlib import extra_program as ex import ezgal fr...
print 'This color has not been implemented.' return blue_mag def histogram_plot(xranf,numberf,df,ax=None,line=False,cbar=False): l2=6 ax.set_xlim(0,0.8) ic2,ic3=0,0 numbers=numberf[:6] numbers2=numberf[l2:] ax.bar(xranf[:6],numbers,width=0.05,color='red',alpha=0.5,align='center') ...
else: blue_mag=(-0.210727367027+2.2836974*redshift)+red_mag else:
random_line_split
main.rs
use std::{fmt::Display, ops::Index, str::FromStr}; use anyhow::{bail, Error}; use intcode::Computer; static INPUT: &str = include_str!("input.txt"); struct View { view: Vec<u8>, width: usize, height: usize, } impl FromStr for View { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Er...
o = n.0; break; } } if !found_turn { break; } } let route = Route(route); Ok(route) } } fn part_01(input: &str) -> Result<usize, Error> { let mut aligment_parameters = 0; l...
found_turn = true; route.append(&mut o.orient(n.0));
random_line_split
main.rs
use std::{fmt::Display, ops::Index, str::FromStr}; use anyhow::{bail, Error}; use intcode::Computer; static INPUT: &str = include_str!("input.txt"); struct View { view: Vec<u8>, width: usize, height: usize, } impl FromStr for View { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Er...
fn forward(&self, pos: (usize, usize), o: Orientation) -> Option<(usize, usize)> { let width = self.width; let height = self.height; let d = o.delta(); pos.0 .checked_add_signed(d.0) .and_then(|x| pos.1.checked_add_signed(d.1).map(|y| (x, y))) .f...
{ let width = self.width; let height = self.height; [ Orientation::Up, Orientation::Down, Orientation::Left, Orientation::Right, ] .into_iter() .filter_map(move |o| { let d = o.delta(); pos.0 ...
identifier_body
main.rs
use std::{fmt::Display, ops::Index, str::FromStr}; use anyhow::{bail, Error}; use intcode::Computer; static INPUT: &str = include_str!("input.txt"); struct View { view: Vec<u8>, width: usize, height: usize, } impl FromStr for View { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Er...
(&self, pos: (usize, usize), o: Orientation) -> Option<(usize, usize)> { let width = self.width; let height = self.height; let d = o.delta(); pos.0 .checked_add_signed(d.0) .and_then(|x| pos.1.checked_add_signed(d.1).map(|y| (x, y))) .filter(move |(x, ...
forward
identifier_name
main.rs
use std::{fmt::Display, ops::Index, str::FromStr}; use anyhow::{bail, Error}; use intcode::Computer; static INPUT: &str = include_str!("input.txt"); struct View { view: Vec<u8>, width: usize, height: usize, } impl FromStr for View { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Er...
} else { view.push(o); } } let height = view.len() / width; Ok(View { view, width, height, }) } } impl Index<(usize, usize)> for View { type Output = u8; fn index(&self, (x, y): (usize, usize)) -> ...
{ width = view.len(); }
conditional_block
val.rs
//! A concrete implementation of `futures::Future`. It is similar in spirit as //! `futures::Promise`, but is better suited for use with Tokio. use futures::{Future, Poll, Task}; use std::mem; use std::cell::Cell; use std::sync::{Arc, Mutex}; use self::State::*; /// A future representing the completion of an asynchro...
(&mut self, task: &mut Task) -> Poll<bool, ()> { self.inner.poll(task) } fn schedule(&mut self, task: &mut Task) { self.inner.schedule(task) } } /* * * ===== Inner ===== * */ impl<T, E> Inner<T, E> { /// Complete the future with the given result fn complete(&self, res: Option<...
poll
identifier_name
val.rs
//! A concrete implementation of `futures::Future`. It is similar in spirit as //! `futures::Promise`, but is better suited for use with Tokio. use futures::{Future, Poll, Task}; use std::mem; use std::cell::Cell; use std::sync::{Arc, Mutex}; use self::State::*; /// A future representing the completion of an asynchro...
}).forget(); assert_eq!(123, rx.recv().unwrap()); } #[test] fn test_polling_aborted_future_panics() { use std::thread; let res = thread::spawn(|| { let (c, val) = pair::<u32, ()>(); val.then(move |res| { println!("WAT: {:?}", res); ...
val.then(move |res| { tx.send(res.unwrap()).unwrap(); res
random_line_split
val.rs
//! A concrete implementation of `futures::Future`. It is similar in spirit as //! `futures::Promise`, but is better suited for use with Tokio. use futures::{Future, Poll, Task}; use std::mem; use std::cell::Cell; use std::sync::{Arc, Mutex}; use self::State::*; /// A future representing the completion of an asynchro...
/// Abort the computation. This will cause the associated `Val` to panic on /// a call to `poll`. pub fn abort(self) { self.inner.complete(None, false); } /// Returns a `Future` representing the consuming end cancelling interest /// in the future. /// /// This function can onl...
{ self.inner.complete(Some(Err(err)), false); }
identifier_body
DissertationScript.py
from subprocess import call import os import pandas as pd from pandas import DataFrame import string import re from urllib.request import urlopen from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.se...
try: site = urlopen(el).read() text = open("CongressBLAHfolder/"+agen+str(num)+a+str(reg3.groups()[0])+".txt","wb") text.write(site) except Exception as e: print("This didn't work: "+s...
for el in reg2: print(el) #print(el) #li.append(el) reg3 = re.search('hrg(\d*?)\/',el)
random_line_split
DissertationScript.py
from subprocess import call import os import pandas as pd from pandas import DataFrame import string import re from urllib.request import urlopen from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.se...
(): ###Create files with each Senator and their full website, including PersonID #Load GPO Biographies - JSON and extract the key, which is names of all Congresspeople going back to 1997 names = json.load(open('GPO Biographies - JSON')) names = list(names.keys()) #This gets rid of middle names and m...
cspan_selenium_getsite
identifier_name