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 |
|---|---|---|---|---|
binder.go | Type(models[0])
if pkgName == "" {
return nil, fmt.Errorf("missing package name for %s", name)
}
obj, err := b.FindObject(pkgName, typeName)
if err != nil {
return nil, err
}
return obj.Type(), nil
}
func (b *Binder) FindObject(pkgName string, typeName string) (types.Object, error) {
if pkgName == "" {
... | if model == "interface{}" {
if !isIntf(bindTarget) { | random_line_split | |
binder.go | ) (types.Type, error) {
models := b.cfg.Models[name].Model
if len(models) == 0 {
return nil, fmt.Errorf(name + " not found in typemap")
}
if models[0] == "map[string]interface{}" {
return MapType, nil
}
if models[0] == "interface{}" {
return InterfaceType, nil
}
pkgName, typeName := code.PkgAndType(mod... | named, ok := t.(*types.Named)
if !ok {
return t, false
}
if named.Origin().String() != "github.com/99designs/gqlgen/graphql.Omittable[T any]" {
return t, false
}
return named.TypeArgs().At(0), true
}
func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret *TypeReference, err error) {
... | return t, false
}
| conditional_block |
tools.py | )
import numpy as np
import copy
from senteval import utils
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader, SequentialSampler, RandomSampler
import torch.nn.functional as F
from tqdm import tqdm
class PyTorchClassifier(object):
def __init__(self, inputdim, nclas... |
"""
MLP with Pytorch (nhid=0 --> Logistic Regression)
"""
class MLP(PyTorchClassifier):
def __init__(self, params, inputdim, nclasses, l2reg=0., batch_size=64,
seed=1111, cudaEfficient=False):
super(self.__class__, self).__init__(inputdim, nclasses, l2reg,
... | probas = vals
else:
probas = np.concatenate(probas, vals, axis=0)
return probas
| random_line_split |
tools.py | )
import numpy as np
import copy
from senteval import utils
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader, SequentialSampler, RandomSampler
import torch.nn.functional as F
from tqdm import tqdm
class PyTorchClassifier(object):
def __init__(self, inputdim, nclas... |
def fit(self, args, model, tokenizer, train_x, train_y, dev_x, dev_y, validation_split=None,
early_stop=True):
self.nepoch = 0
bestaccuracy = -1
stop_train = False
early_stop_count = 0
# Preparing validation data
train_dataloader, train_sampler = self.prepare_data(args, ... | all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)
all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
all_segment_ids = torch.tensor([f.input_type_ids for f in featu... | identifier_body |
tools.py | )
import numpy as np
import copy
from senteval import utils
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader, SequentialSampler, RandomSampler
import torch.nn.functional as F
from tqdm import tqdm
class PyTorchClassifier(object):
def __init__(self, inputdim, nclas... |
self.nepoch += epoch_size
def score(self, args, model, tokenizer, dev_x):
dev_dataloader, dev_sampler = self.prepare_data(args, dev_x)
self.model.eval()
correct = 0
all = 0
with torch.no_grad():
for step, batch in enumerate(dev_dataloader):
batch = tuple(t.to(args.dev... | for step, batch in enumerate(train_dataloader):
batch = tuple(t.to(args.device) for t in batch)
inputs = {'input_ids': batch[0],
'attention_mask': batch[1],
'token_type_ids': batch[3]}
ybatch = batch[4]
with torch.no_grad():
... | conditional_block |
tools.py | )
import numpy as np
import copy
from senteval import utils
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader, SequentialSampler, RandomSampler
import torch.nn.functional as F
from tqdm import tqdm
class PyTorchClassifier(object):
def __init__(self, inputdim, nclas... | (self, args, features):
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)
all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
all_segment_ids = torch.tensor... | prepare_data | identifier_name |
google_drive_data.py | False:
status, done = downloader.next_chunk()
with io.open("." + "/" + name, 'wb') as f:
fh.seek(0)
f.write(fh.read())
def is_duplicate(img1,img2):
response=False
image1 = cv2.imread(img1)
image2 = cv2.imread(img2)
try:
difference = cv2.subt... |
def count_image(id):
imageList = []
service = get_gdrive_service()
results = service.files().list(pageSize=1000, q="'{}' in parents".format(id)).execute()
items = results.get('files', [])
for item in items:
mime_Type = item["mimeType"]
if mime_Type == "image/jpeg":
... | count=1
for item in items:
id = item["id"]
name = item["name"]
mime_type = item["mimeType"]
file = service.files().get(fileId=id).execute()
del file['id']
if "jpeg" in mime_type:
file['name'] = newName+str(count)+ ".jpg";
if "png" in mime_... | identifier_body |
google_drive_data.py | :
status, done = downloader.next_chunk()
with io.open("." + "/" + name, 'wb') as f:
fh.seek(0)
f.write(fh.read())
def is_duplicate(img1,img2):
response=False
image1 = cv2.imread(img1)
image2 = cv2.imread(img2)
try:
difference = cv2.subtract(i... |
for item in items:
id = item["id"]
name = item["name"]
mime_type = item["mimeType"]
if mime_type == "application/vnd.google-apps.folder":
folder_count = folder_count + 1
if mime_type == "image/jpeg":
# renameFile(item["id"],"rajj_img"+str(imag... | name = item["name"]
mime_type = item["mimeType"]
if name == 'Test Techm':
testtechm_id = item['parents'][0] | conditional_block |
google_drive_data.py | :
status, done = downloader.next_chunk()
with io.open("." + "/" + name, 'wb') as f:
fh.seek(0)
f.write(fh.read())
def is_duplicate(img1,img2):
response=False
image1 = cv2.imread(img1)
image2 = cv2.imread(img2)
try:
difference = cv2.subtract(i... |
def duplicate_image_list(imagelist):
#print(len(imagelist))
dup_list = []
if len(imagelist) >= 1:
for i in range(len(imagelist) - 1):
count=0
l=[]
for j in range(i + 1, len(imagelist)):
image1 = cv2.imread(imagelist[i])
i... | random_line_split | |
google_drive_data.py | (service):
file_metadata = {
'name': 'Test Techm',
'mimeType': 'application/vnd.google-apps.folder'
}
file = service.files().create(body=file_metadata,
fields='id').execute()
print('Folder ID: %s' % file.get('id'))
def get_gdrive_service():
... | create_folder | identifier_name | |
mod.rs | items: &[(&[u8], &[u8])], // &[(key, value)]
) -> Result<()> {
let checker = StorageProofChecker::<T::Hashing>::new(state_root, proof)?;
for (k, v) in items {
let actual_value = checker
.read_value(k)?
.ok_or_else(|| anyhow::Error::msg(Error::Stora... | proof: StorageProof, | random_line_split | |
mod.rs |
}
type BridgeId = u64;
pub trait Config: frame_system::Config<Hash = H256> {
type Block: BlockT<Hash = H256, Header = Self::Header>;
}
impl Config for chain::Runtime {
type Block = chain::Block;
}
#[derive(Encode, Decode, Clone, Serialize, Deserialize)]
pub struct LightValidation<T: Config> {
num_bridg... | {
BridgeInfo {
last_finalized_block_header: block_header,
current_set: validator_set,
}
} | identifier_body | |
mod.rs | (
&mut self,
block_header: T::Header,
validator_set: AuthoritySet,
proof: StorageProof,
) -> Result<BridgeId> {
let state_root = block_header.state_root();
Self::check_validator_set_proof(state_root, proof, &validator_set.list, validator_set.id)
.map_err(... | initialize_bridge | identifier_name | |
autodetect.js | ("Missing target type in SCConfig: " + filepath);
readConfig[opts.target] = opts;
},
});
vm.runInContext(scconfig,ctx,filepath);
return readConfig;
};
var testJSON = function(text){
var ret;
try {
ret = JSON.parse(text);
return ret;
}
catch(e){
return undefined;
}
};
var namedHa... | allConfigs.apps.push(data);
}
}
else {
util.log('app found with name ' + app + " but no config file detected.");
all | if(!data.name) data.name = app; | random_line_split |
product.ts | Client": this.values.customerName,
"productUi": this.product.product.id,
"productName": this.product.product.name,
"date": year+'/'+month+'/'+day,
"hour": this.hourInit,
"lat":this.lat,
"lng":this.long,
"onesignal":this.values.userId,
"location" : this.addressesCustomer
... | this.processDate = date
}
| identifier_body | |
product.ts | addressesCustomer: any;
constructor(
public alert:AlertController,
public translate: TranslateService,
public nav: NavController,
public service: ProductService,
public servi:Service,
public otherservice: Service,
params: NavParams,
public functions: Functions,
public values: Va... | customers: any;
addresses: any; | random_line_split | |
product.ts | : TranslateService,
public nav: NavController,
public service: ProductService,
public servi:Service,
public otherservice: Service,
params: NavParams,
public functions: Functions,
public values: Values,
private platform: Platform,
private geolocation: Geolocation,
private nativeGe... | this.daysConfig.push({
date: moment()
.add(index, 'days')
.toDate(),
marked: true,
})
}
//Por defecto iniciamos con el booking deshabilitado
this.disableSubmit = true
}
handleAddress(result){
this.addresses = result
this.addressesCustomer = this.... | this.daysConfig.push({
date: moment()
.add(index, 'days')
.toDate(),
disable: true,
})
}
| conditional_block |
product.ts | .availability.forEach(element => {
let day = Number((element.type as string).split(':')[1])
console.log({ day })
const index = this.disableWeekDays.indexOf(day)
if (index > -1) {
this.disableWeekDays.splice(index, 1)
}
})
console.log('this.daysConfig', this.daysConfig)
... | oseVariationOne(){ | identifier_name | |
codegen.rs | candidate_k_axes
.iter()
.filter(|a| input_facts[0].shape[a.inputs[0][0]] > 1.to_dim())
.collect::<TVec<_>>();
let k_axis = if non_trivial_k_axis.len() > 1 {
// TODO: handle case where multiple consecutive k in the same order in both input.
bail!("Multiple k-axis candidate ... | (
op: &EinSum,
model: &TypedModel,
node: &TypedNode,
(_, k_axis, _): (&Axis, &Axis, &Axis),
) -> TractResult<Option<TypedModelPatch>> {
let name = &node.name;
let mut patch = TypedModelPatch::new("Dequantizing einsum");
let taps = patch.taps(model, &node.inputs)?;
let [a, b, bias, mut a0... | dequant | identifier_name |
codegen.rs | candidate_k_axes
.iter()
.filter(|a| input_facts[0].shape[a.inputs[0][0]] > 1.to_dim())
.collect::<TVec<_>>();
let k_axis = if non_trivial_k_axis.len() > 1 | else {
non_trivial_k_axis.get(0).copied().or_else(|| candidate_k_axes.get(0)).copied()
};
let Some(k_axis) = k_axis else {
return Ok(AxesOrPatch::Patch(inject_k_axis(op, model, node)?));
};
let m_axis = op
.axes
.iter_all_axes()
.filter(|a| {
a.inputs... | {
// TODO: handle case where multiple consecutive k in the same order in both input.
bail!("Multiple k-axis candidate found");
} | conditional_block |
codegen.rs | // TODO: handle case where multiple consecutive k in the same order in both input.
bail!("Multiple k-axis candidate found");
} else {
non_trivial_k_axis.get(0).copied().or_else(|| candidate_k_axes.get(0)).copied()
};
let Some(k_axis) = k_axis else {
return Ok(AxesOrPatch::Pat... | {
let input_facts = model.node_input_facts(node.id)?;
let input_shapes: TVec<&[TDim]> = input_facts.iter().map(|f| &*f.shape).collect();
let output_shape = super::eval::output_shape(&op.axes, &input_shapes);
let candidate_k_axes: TVec<&Axis> = op
.axes
.iter_all_axes()
// Filter ... | identifier_body | |
codegen.rs | = candidate_k_axes
.iter()
.filter(|a| input_facts[0].shape[a.inputs[0][0]] > 1.to_dim())
.collect::<TVec<_>>();
let k_axis = if non_trivial_k_axis.len() > 1 {
// TODO: handle case where multiple consecutive k in the same order in both input.
bail!("Multiple k-axis candidat... | )?[0];
}
}
let a = wire_offset_u8_as_i8(&mut patch, &node.name, a, "a", &mut a0, "a0")?;
let b = wire_offset_u8_as_i8(&mut patch, &node.name, b, "b", &mut b0, "b0")?;
let mut output = patch.wire_node(
&node.name,
EinSum {
q_params: None,
axes... | for i in 1..(output_rank - q_axis_in_output) {
a_scale = patch.wire_node(
format!("{name}.a_scale_axis_fix_{i}"),
AxisOp::Add(i),
&[a_scale], | random_line_split |
interface.py | name})
}
r = requests.get(url, headers={
"X-Auth-Token": self.auth_token,
"Content-Type": "application/json"
})
if r.ok:
data = json.loads(r.text)
assert data
return data
else:
if r.status_code == 404:
... |
return self._tenancy
class Tenant(object):
def __init__(self, tenant, conn):
self.tenant = tenant
# Conn is the niceometer object we were instanced from
self.conn = conn
self._meters = set()
self._resources = None
self.invoice_type = None
# Invoice... | self._tenancy = {}
for tenant in self.auth.tenants.list():
t = Tenant(tenant, self)
self._tenancy[t["name"]] = t | conditional_block |
interface.py | invoice_type.split(":")
_package = __import__(module, globals(), locals(), [ call ])
funct = getattr(_package, call)
self.invoice_type = funct
config = self.conn.config["invoice_object"]
invoice = self.invoice_type(self, config)
return invoice
def resou... | Cumulative | identifier_name | |
interface.py | name})
}
r = requests.get(url, headers={
"X-Auth-Token": self.auth_token,
"Content-Type": "application/json"
})
if r.ok:
data = json.loads(r.text)
assert data
return data
else:
if r.status_code == 404:
... |
def __getattr__(self, attr):
if attr not in self.tenant:
return object.__getattribute__(self, attr)
# return super(Tenant, self).__getattr__(attr)
return self.tenant[attr]
def invoice(self, start, end):
"""
Creates a new Invoice.
Invoices are a... | def __init__(self, tenant, conn):
self.tenant = tenant
# Conn is the niceometer object we were instanced from
self.conn = conn
self._meters = set()
self._resources = None
self.invoice_type = None
# Invoice type needs to get set from the config, which is
#... | identifier_body |
interface.py | name})
}
r = requests.get(url, headers={
"X-Auth-Token": self.auth_token,
"Content-Type": "application/json" | data = json.loads(r.text)
assert data
return data
else:
if r.status_code == 404:
# couldn't find it
raise NotFound
class Artifice(object):
"""Produces billable artifacts"""
def __init__(self, config):
super(Artifice... | })
if r.ok: | random_line_split |
fint.py | , target):
# only return stories BY the user
user_token = 'id=%s' % target
links = re.findall('(/story.php\?story_fbid=[^"#]+)', html)
return [
'%s%s' % (BASE_URL, x.replace('&', '&')) for x in set(links)
if user_token in x
]
def get_photos_urls(target_id, html):
|
def get_all_photos(driver, target_id, limit=100):
url = 'https://mbasic.facebook.com/profile.php?id=%s&v=photos' % target_id
driver.get(url)
time.sleep(pause())
see_all = re.findall('<a href="([^"#]+)">See All</a>', driver.page_source)
photos = []
if not see_all:
return photos
e... | links = re.findall('(/photo\.php\?[^;]*;id=%s[^"]+)' % target_id, html)
return ['%s%s' % (BASE_URL, x.replace('&', '&')) for x in set(links)] | identifier_body |
fint.py | target):
# only return stories BY the user
user_token = 'id=%s' % target
links = re.findall('(/story.php\?story_fbid=[^"#]+)', html)
return [
'%s%s' % (BASE_URL, x.replace('&', '&')) for x in set(links)
if user_token in x
]
def get_photos_urls(target_id, html):
links = r... |
else:
break
return stories
def get_all_comments(driver, url, limit=200, cur_length=0):
if cur_length >= limit:
return []
driver.get(url)
html = driver.page_source.encode("utf-8",
errors='replace').decode("utf-8",
... | url = BASE_URL + see_more[0].replace('&', '&')
time.sleep(pause())
driver.get(url) | conditional_block |
fint.py | target):
# only return stories BY the user
user_token = 'id=%s' % target
links = re.findall('(/story.php\?story_fbid=[^"#]+)', html)
return [
'%s%s' % (BASE_URL, x.replace('&', '&')) for x in set(links)
if user_token in x
]
def get_photos_urls(target_id, html):
links = r... | (html):
return re.findall(
'<h3><a class="[^"]+" href="([^"]+)\?r[^"]*">([^<]*)</a>', html)
# Given a "reactions" page ufi/reaction/profile/browser/, returns a list of (url, display name)
def parse_likers(html):
return re.findall(
'<h3 class=".[^"]*"><a href="(.[^"]*)[^"]*">(.[^<]*)</a></h3>',... | parse_commenters | identifier_name |
fint.py | return []
driver.get(url)
html = driver.page_source.encode("utf-8",
errors='replace').decode("utf-8",
errors="replace")
reactions = parse_likers(html)
cur_length += len(reactions)
reaction_u... | print(msg, end='\r')
except (KeyboardInterrupt, SystemExit):
print('[!] KeyboardInterrupt received. %d users retrieved' %
len(users)) | random_line_split | |
headtail_resolution.py | (BaseResults):
def __init__(self, shuffled_results: ShuffledResults):
self.cur_partition = -1
self.partitions = ma.masked_all((len(shuffled_results),), dtype=int)
self._shuffled_results = shuffled_results
theta = _init_partitioned_series(shuffled_results.theta)
skeletons = ... |
return segments_alignment
def _calculate_smallest_gap_to_adjacent(segment_index, segments, segments_alignment):
# evaluate how far away this segment is from known values
score = np.nan
segment_offset = np.nan
if segment_index - 1 >= 0 and not segments_alignment.mask[segment_index - 1]:
g... | segment_skeletons = labelled_skeletons[segment]
non_nan_labelled = np.any(~np.isnan(segment_skeletons), axis=(1, 2))
labels_count = np.sum(non_nan_labelled)
non_masked = ~np.any(partitioned_skeletons[segment].mask, axis=(1, 2, 3))
to_compare = np.logical_and(non_nan_labelled, non_masked)... | conditional_block |
headtail_resolution.py | (partitioned_series, shuffled_series, frame_index: int, partition: int):
partitioned_series[frame_index][0] = shuffled_series[frame_index, partition]
partitioned_series[frame_index][1] = shuffled_series[frame_index, 1 - partition]
class _PartitionedResults(BaseResults):
def __init__(self, shuffled_results... | _set_partition | identifier_name | |
headtail_resolution.py | (BaseResults):
def __init__(self, shuffled_results: ShuffledResults):
self.cur_partition = -1
self.partitions = ma.masked_all((len(shuffled_results),), dtype=int)
self._shuffled_results = shuffled_results
theta = _init_partitioned_series(shuffled_results.theta)
skeletons = ... |
def mask(self, indices):
self.theta.mask[indices] = True
self.skeletons.mask[indices] = True
self.scores.mask[indices] = True
def num_valid(self):
return np.sum(~self.scores.mask)
class _FinalResults(BaseResults):
@classmethod
def from_resolved(cls, resolved_results:... | self.scores[segment] = self._partitioned_results.scores[segment][:, segment_alignment]
self.skeletons[segment] = self._partitioned_results.skeletons[segment][:, segment_alignment]
self.theta[segment] = self._partitioned_results.theta[segment][:, segment_alignment] | identifier_body |
headtail_resolution.py | (BaseResults):
def __init__(self, shuffled_results: ShuffledResults):
self.cur_partition = -1
self.partitions = ma.masked_all((len(shuffled_results),), dtype=int)
self._shuffled_results = shuffled_results
theta = _init_partitioned_series(shuffled_results.theta)
skeletons = ... | self.theta.mask[indices] = True
self.skeletons.mask[indices] = True
self.scores.mask[indices] = True
self.partitions.mask[indices] = True
def set_partition(self, frame_index: int, partition: int, new_partition: bool = False):
if new_partition:
self.cur_partition ... | random_line_split | |
game.rs | in which we will use the method
* get_entry which takes an Address(HashString) type then return ZomeApiResult<Option<Entry>>. We then unwrap it twice to
* retrieve the Entry itself. Then we use if let to match the move_entry with an Entry::App variant. This is because Entry
* enu... | let game = get_game_local_chain(local_chain, game_address)?; | random_line_split | |
game.rs | (game_address: &Address) -> ZomeApiResult<Vec<Move>> {
match hdk::get_links(game_address, LinkMatch::Any, LinkMatch::Any)?.addresses().into_iter().next() {
/* get links returns the ZomeApiResult<GetLinksResult>.
* This will get entries that are linked to the first argument.
* Since ZomeApi... | get_moves | identifier_name | |
game.rs | mut move_addresses = vec![first_move];
let mut more = true;
while more {
more = match hdk::get_links(move_addresses.last().unwrap(), LinkMatch::Any, LinkMatch::Any)?.addresses().into_iter().next() {
Some(addr) => {
move_addresses.push(... | else {
None
}
})
.next()
.ok_or(ZomeApiError::HashNotFound)
/* get_game_local_chain() gets all the Entry in the local_chain as well as the address of the game and will return ZomeApiResult<Game>.
* now we will call the iter() method on the local_chain so tha... | {
Some(Game::try_from(entry_data.clone()).unwrap())
} | conditional_block |
game.rs | None => {
false
},
}
}
/* In this match operator, we first cater to Some(first_move). The name is first_move because
* the Game entry is always linked to the first_move made by Player 2.
* S... | {
match hdk::get_links(game_address, LinkMatch::Any, LinkMatch::Any)?.addresses().into_iter().next() {
/* get links returns the ZomeApiResult<GetLinksResult>.
* This will get entries that are linked to the first argument.
* Since ZomeApiResult returns Result<T, ZomeApiError>(where T in thi... | identifier_body | |
server_rpc.py | self.rpc_config_set
self.rpc_handler_map['^/campaign/alerts/is_subscribed$'] = self.rpc_campaign_alerts_is_subscribed
self.rpc_handler_map['^/campaign/alerts/subscribe$'] = self.rpc_campaign_alerts_subscribe
self.rpc_handler_map['^/campaign/alerts/unsubscribe$'] = self.rpc_campaign_alerts_unsubscribe
self.rpc... |
# Tables with a message_id field
for table_name in db_models.get_tables_with_column_id('message_id'):
self.rpc_handler_map['^/message/' + table_name + '/count$'] = self.rpc_database_count_rows
self.rpc_handler_map['^/message/' + table_name + '/view$'] = self.rpc_database_get_rows
def rpc_ping(self):
"""... | self.rpc_handler_map['^/campaign/' + table_name + '/count$'] = self.rpc_database_count_rows
self.rpc_handler_map['^/campaign/' + table_name + '/view$'] = self.rpc_database_get_rows | conditional_block |
server_rpc.py | class KingPhisherRequestHandlerRPC(object):
"""
This superclass of :py:class:`.KingPhisherRequestHandler` maintains
all of the RPC call back functions.
:RPC API: :ref:`rpc-api-label`
"""
def install_handlers(self):
super(KingPhisherRequestHandlerRPC, self).install_handlers()
self.rpc_handler_map['^/ping$'] =... | DATABASE_TABLES = db_models.DATABASE_TABLES
DATABASE_TABLE_OBJECTS = db_models.DATABASE_TABLE_OBJECTS
| random_line_split | |
server_rpc.py | self.rpc_config_set
self.rpc_handler_map['^/campaign/alerts/is_subscribed$'] = self.rpc_campaign_alerts_is_subscribed
self.rpc_handler_map['^/campaign/alerts/subscribe$'] = self.rpc_campaign_alerts_subscribe
self.rpc_handler_map['^/campaign/alerts/unsubscribe$'] = self.rpc_campaign_alerts_unsubscribe
self.rpc... |
def rpc_campaign_message_new(self, campaign_id, email_id, target_email, company_name, first_name, last_name):
"""
Record a message that has been sent as part of a campaign. These
details can be retrieved later for value substitution in template
pages.
:param int campaign_id: The ID of the campaign.
:par... | """
Add a landing page for the specified campaign. Landing pages refer
to resources that when visited by a user should cause the visit
counter to be incremented.
:param int campaign_id: The ID of the campaign.
:param str hostname: The VHOST for the request.
:param str page: The request resource.
"""
pa... | identifier_body |
server_rpc.py | _version
return vinfo
def rpc_config_get(self, option_name):
"""
Retrieve a value from the server's configuration.
:param str option_name: The name of the configuration option.
:return: The option's value.
"""
if isinstance(option_name, (list, tuple)):
option_names = option_name
option_values = {... | rpc_database_insert_row | identifier_name | |
server.rs | server: bmrng::RequestSender<ServerEvent, Packet>,
// server: broadcast::Sender<ServerEvent>,
/// Event sender to Socket instances. cloned and passed over
client: mpsc::Sender<SocketEvent>,
}
#[derive(Debug)]
pub enum ServerState {
Unsubscribed {
socket_event_receiver: mpsc::Receiver<SocketEve... |
pub fn try_subscribe(
&self,
) -> Result<bmrng::RequestReceiver<ServerEvent, Packet>, AlreadySubscribedError> {
let mut state = self.state.lock().unwrap();
let old_state = std::mem::replace(&mut *state, ServerState::Subscribed);
match old_state {
ServerState::Subscr... | {
self.try_subscribe()
.expect("Already subscribed to engine_io_server::Server")
} | identifier_body |
server.rs | server: bmrng::RequestSender<ServerEvent, Packet>,
// server: broadcast::Sender<ServerEvent>,
/// Event sender to Socket instances. cloned and passed over
client: mpsc::Sender<SocketEvent>,
}
#[derive(Debug)]
pub enum ServerState {
Unsubscribed {
socket_event_receiver: mpsc::Receiver<SocketEve... | // TODO: or drop the whole thing. The server, the sockets, everything.
todo!();
// for socket in self.clients.iter() {
// socket.value().close(true);
// }
}
pub async fn close_socket(&self, connection_id: &str) {
if let Some((_key, socket)) = self.clients.rem... | // TODO: consider sending signals or dropping channels instead of closing them like this? | random_line_split |
server.rs | server: bmrng::RequestSender<ServerEvent, Packet>,
// server: broadcast::Sender<ServerEvent>,
/// Event sender to Socket instances. cloned and passed over
client: mpsc::Sender<SocketEvent>,
}
#[derive(Debug)]
pub enum ServerState {
Unsubscribed {
socket_event_receiver: mpsc::Receiver<SocketEve... | (
&self,
sid: Option<&String>,
upgrade: bool,
transport_kind: TransportKind,
http_method: HttpMethod,
) -> Result<(), ServerError> {
if let Some(sid) = sid {
let client = self.clients.get(sid);
if let Some(client) = client {
let... | verify_request | identifier_name |
dkg.go | .Int, [2]*big.Int, error) {
privateKey, publicKeyG1, err := cloudflare.RandomG1(rand.Reader)
publicKey := bn256.G1ToBigIntArray(publicKeyG1)
return privateKey, publicKey, err
}
// GenerateShares returns encrypted shares, private coefficients, commitments and potentially an error
func GenerateShares(transportPrivat... |
// convert public keys into G1 structs
publicKeyG1s := []*cloudflare.G1{}
for idx := 0; idx < len(participants); idx++ {
participant := participants[idx]
logger.Infof("participants[%v]: %v", idx, participant)
if participant != nil && participant.PublicKey[0] != nil && participant.PublicKey[1] != nil {
publ... | {
// create coefficients (private/public)
privateCoefficients, err := cloudflare.ConstructPrivatePolyCoefs(rand.Reader, threshold)
if err != nil {
return nil, nil, nil, err
}
publicCoefficients := cloudflare.GeneratePublicCoefs(privateCoefficients)
// create commitments
commitments := make([][2]*big.Int, len... | identifier_body |
dkg.go | .Int, [2]*big.Int, error) {
privateKey, publicKeyG1, err := cloudflare.RandomG1(rand.Reader)
publicKey := bn256.G1ToBigIntArray(publicKeyG1)
return privateKey, publicKey, err
}
// GenerateShares returns encrypted shares, private coefficients, commitments and potentially an error
func GenerateShares(transportPrivat... |
transportPublicKeyG1, err := bn256.BigIntArrayToG1(transportPublicKey)
if err != nil {
return nil, empty4Big, empty2Big, fmt.Errorf("error converting transport public key to g1: %v | {
publicKeyG1, err := bn256.BigIntArrayToG1(participants[idx].PublicKey)
if err != nil {
return nil, empty4Big, empty2Big, fmt.Errorf("error converting public key to g1: %v", err)
}
publicKeyG1s[idx] = publicKeyG1
} | conditional_block |
dkg.go | .Int, [2]*big.Int, error) {
privateKey, publicKeyG1, err := cloudflare.RandomG1(rand.Reader)
publicKey := bn256.G1ToBigIntArray(publicKeyG1)
return privateKey, publicKey, err
}
// GenerateShares returns encrypted shares, private coefficients, commitments and potentially an error
func GenerateShares(transportPrivat... | if err != nil {
return nil, empty4Big, empty2Big, fmt.Errorf("error converting transport public key to g1: %v", err | transportPublicKeyG1, err := bn256.BigIntArrayToG1(transportPublicKey) | random_line_split |
dkg.go | (i, j int) {
pl[i], pl[j] = pl[j], pl[i]
}
// ThresholdForUserCount returns the threshold user count and k for successful key generation
func ThresholdForUserCount(n int) (int, int) {
k := n / 3
threshold := 2 * k
if (n - 3*k) == 2 {
threshold = threshold + 1
}
return int(threshold), int(k)
}
// InverseArrayF... | Swap | identifier_name | |
id.rs |
pub fn art(name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_lowercase();
match ART.iter().position(|&other| other == name) {
Some(index) => index,
_ => panic!("art '{}' has no id yet", name),
}
}
pub fn villager(name: impl AsRef<str>) -> usize {
let name = name.as_ref().... | {
let name = name.as_ref().to_lowercase();
match FLOWERS.iter().position(|&other| other == name) {
Some(index) => index,
_ => panic!("flower '{}' has no id yet", name),
}
} | identifier_body | |
id.rs | (name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_lowercase();
match ART.iter().position(|&other| other == name) {
Some(index) => index,
_ => panic!("art '{}' has no id yet", name),
}
}
pub fn villager(name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_lowercase... | art | identifier_name | |
id.rs | ",
"earth-boring dung beetle",
"scarab beetle",
"drone beetle",
"goliath beetle",
"saw stag",
"miyama stag",
"giant stag",
"rainbow stag",
"cyclommatus stag",
"golden stag",
"giraffe stag",
"horned dynastid",
"horned atlas",
"horned elephant",
"horned hercules... | "black cosmos",
"white tulips",
"red tulips",
"yellow tulips",
"pink tulips",
"orange tulips",
"purple tulips",
"black tulips",
"yellow pansies",
"red pansies",
"white pansies",
"orange pansies",
"purple pansies",
"blue pansies",
"white roses",
"red roses"... | "white cosmos",
"yellow cosmos",
"pink cosmos",
"orange cosmos", | random_line_split |
main.rs | wing2up = rng.gen_bool(0.5);
for i in 0..count {
let xp = (i as f64 - (count - 1) as f64 * 0.5) / (count as f64);
let xbase = wingw * xp;
let wing1 = rng.gen_range(0.8, 1.1) * wing1m;
let wing2 =
rng.gen_range(0.8, 1.1) * wing2m * (if wing2up { -1.0 } else { 1.0 });
let route = shake(
... | if p.0 < pad || p.0 > width - pad || p.1 < pad || p.1 > height - pad {
break;
}
p = (p.0 + amp * a.cos(), p.1 + amp * a.sin());
positions.push(p); | random_line_split | |
main.rs |
fn eagle<R: Rng>(
origin: (f64, f64),
scale: f64,
rotation: f64,
xreverse: bool,
rng: &mut R,
) -> Vec<Vec<(f64, f64)>> {
let xmul = if xreverse { -1.0 } else { 1.0 };
let count = 2 + (scale * 3.0) as usize;
let mut routes: Vec<Vec<(f64, f64)>> = Vec::new();
let shaking = scale * 0.1;
// body
... | {
path
.iter()
.map(|&(x, y)| {
let dx = rng.gen_range(-scale, scale);
let dy = rng.gen_range(-scale, scale);
(x + dx, y + dy)
})
.collect()
} | identifier_body | |
main.rs | {
#[clap(short, long, default_value = "image.svg")]
file: String,
#[clap(short, long, default_value = "100.0")]
pub width: f64,
#[clap(short, long, default_value = "150.0")]
pub height: f64,
#[clap(short, long, default_value = "5.0")]
pub pad: f64,
#[clap(short, long, default_value = "0.0")]
pub se... | Opts | identifier_name | |
main.rs | .0, 1.0);
let dx2 = if rng.gen_bool(0.8) | else {
rng.gen_range(-3.0, 3.0)
};
let spread1 = 1.0 + rng.gen_range(0.0, 1.0) * rng.gen_range(0.0, 1.0);
let spread2 = 1.0 + rng.gen_range(0.0, 1.0) * rng.gen_range(0.0, 1.0);
let offset1 = rng.gen_range(-1.0, 0.6) * rng.gen_range(0.0, 1.0);
let offset2 = rng.gen_range(-1.0, 0.6) * rng.gen_range(0.0, 1.... | {
-dx1
} | conditional_block |
leetcode.rs | = (vec![], &self);
while let Some(n) = temp {
vec.push(n.val);
temp = &n.next;
}
vec
}
/// Build the vector of the node from the a list node.
fn to_node_vec(self) -> Vec<Option<Box<ListNode>>> {
let (mut vec, mut current) = (vec![], self);
while let Some(v) = current.as_mut() {
... | {
val: i32,
left: Option<Rc<RefCell<Self>>>,
right: Option<Rc<RefCell<Self>>>,
}
impl TreeNode {
#[inline]
fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
#[inline]
fn new_option(val: Option<i32>) -> Option<Rc<RefCell<Self>>> {
val.map(|v| Rc::new... | TreeNode | identifier_name |
leetcode.rs | = (vec![], &self);
while let Some(n) = temp {
vec.push(n.val);
temp = &n.next;
}
vec
}
/// Build the vector of the node from the a list node.
fn to_node_vec(self) -> Vec<Option<Box<ListNode>>> {
let (mut vec, mut current) = (vec![], self);
while let Some(v) = current.as_mut() {
... |
}
}
count == 1
}
/// Check element content equivalence without element order.
fn check_element_eq<T>(v1: T, v2: T) -> bool
where
T: IntoIterator,
T::Item: Eq + std::hash::Hash + std::fmt::Debug,
{
use std::collections::HashMap;
let (mut length1, mut length2) = (0, 0);
let (mut content1, mut conten... | {
return false;
} | conditional_block |
leetcode.rs | ), Some(2), Some(3), Some(4), None, Some(5), None, Some(6)]` will be transformed to:
```html
1
/ \
2 3
/ \ / \
4 N 5 N
/
6
```
`[Some(7), Some(5), Some(11), Some(4), None, Some(8), Some(13), Some(2), None, None, None, Some(12)]` will be transformed to:
```html
... | mod q84_largest_rectangle_in_histogram;
mod q85_maximal_rectangle;
mod q86_partition_list; | random_line_split | |
lib.rs | / noun when `n >= 1`, otherwise 0 names.
///
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Petnames<'a> {
pub adjectives: Words<'a>,
pub adverbs: Words<'a>,
pub names: Words<'a>,
}
#[cfg(feature = "default_dictionary")]
mod words {
include!(concat!(env!("OUT_DIR"), "/words.rs"));
}
impl<'a> Petna... | <RNG>(&'a self, rng: &'a mut RNG, words: u8, separator: &str) -> Names<'a, RNG>
where
RNG: rand::Rng,
{
Names { petnames: self, rng, words, separator: separator.to_string() }
}
/// Iterator yielding unique – i.e. non-repeating – petnames.
///
/// # Examples
///
/// ```ru... | iter | identifier_name |
lib.rs | name / noun when `n >= 1`, otherwise 0 names.
///
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Petnames<'a> {
pub adjectives: Words<'a>,
pub adverbs: Words<'a>,
pub names: Words<'a>,
}
#[cfg(feature = "default_dictionary")]
mod words {
include!(concat!(env!("OUT_DIR"), "/words.rs"));
}
impl<'a> ... | {
self.adjectives.to_mut().retain(|word| predicate(word));
self.adverbs.to_mut().retain(|word| predicate(word));
self.names.to_mut().retain(|word| predicate(word));
}
/// Calculate the cardinality of this `Petnames`.
///
/// If this is low, names may be repeated by the gener... | /// the adjectives, adverbs, and names lists.
///
pub fn retain<F>(&mut self, mut predicate: F)
where
F: FnMut(&str) -> bool, | random_line_split |
lib.rs | adjectives: Cow::from(&words::medium::ADJECTIVES[..]),
adverbs: Cow::from(&words::medium::ADVERBS[..]),
names: Cow::from(&words::medium::NAMES[..]),
}
}
/// Constructs a new `Petnames` from the large word lists.
#[cfg(feature = "default_dictionary")]
pub fn large() -> S... | let list = match self {
Self::Adjective => Some(List::Adjective),
Self::Adverb(_) => Some(List::Adverb),
Self::Name => Some(List::Name),
Self::Done => None,
};
self.advance();
list
}
fn | identifier_body | |
califa2_2.py | lcula a Concentracao de uma populacao, usando a definicao
de Conselice(2014) http://iopscience.iop.org/article/10.1086/375001/pdf
'''
a=1
radius=df.sort_values('raio')
r20=radius.iat[int(0.2*len(df)),-1]
r80=radius.iat[int(0.8*len(df)),-1]
Conc = 5*np.log((r80/r20))
return Conc
def Z(df... | as imagens fits'''
img = f_sdss[0].data
return img
def C(df):
'''funcao que ca | identifier_body | |
califa2_2.py | plt.axis([0,77,0,72])
plt.xlabel('X',fontweight='bold')
plt.ylabel('Y',fontweight='bold')
imgplot = plt.imshow(100*np.log10(img/255), cmap=cx)
titulo='Halpha Maps - Galaxy %s ' %halpha['num_gal'][i_gal]
plt.title(titulo)
#plt.colorbar()
figura = 'figures/imagens_Ha/galaxy_%s' %halpha['num_g... | print('excentricidade = %f' %exc)
print('inclinacao = %f' %(math.degrees(tetha)))
print('#%d' %i_gal) | random_line_split | |
califa2_2.py | 0,gal,Conc,ordem):
'''definindo uma funcao para ordenar a propridade de interesse
dividindo-o em bins de igual tamanho e calculando alguns parametros'''
df_Z = pd.DataFrame()
propr = []
err_prop = []
raio = []
err_raio = []
halpha = []
err_halpha = []
dens = []
err_dens = []
... | eitura do arquivo fits, criando um dataframe com os dados'''
df = pd.DataFrame()
nrows, ncols = img.shape
xx, yy = np.meshgrid( *np.ogrid[:ncols, :nrows] )
table = np.column_stack(( xx.flatten(), yy.flatten(), img.flatten() ))
temp = pd.DataFrame(table, columns=['x','y',param])
df = pd.concat([d... | função para l | identifier_name |
califa2_2.py | ,gal,Conc,ordem):
'''definindo uma funcao para ordenar a propridade de interesse
dividindo-o em bins de igual tamanho e calculando alguns parametros'''
df_Z = pd.DataFrame()
propr = []
err_prop = []
raio = []
err_raio = []
halpha = []
err_halpha = []
dens = []
err_dens = []
... |
#obtendo os dados de Halpha da imagem fits
df_ha = obtendo_dados(img,'halpha')
#obtendo os dados de densidade de massa da imagem fits
image_mass = fits.open('PatImages/PatImagesMcorSD__yx_%s.fits' %halpha['num_gal'][i_gal])
img = get_image(image_mass)
df_mass = obtendo_dados(img, 'mass')
... | DC)
print(bcolors.FAIL + '-'*33 + 'OBJETO: %s' %halpha['num_gal'][i_gal] + '-'*33 + bcolors.ENDC)
print(bcolors.FAIL +'-'*79+ bcolors.ENDC)
plt.close()
image_ha = fits.open('Hamaps/%s_%s_Ha.fits' %(halpha['num_gal'][i_gal],halpha['type'][i_gal]))
img = get_image(image_ha)
#plotando a imagem fit... | conditional_block |
modbase.py | url += '&' + i +'='+ search_options[i]
# the dataset
# if not 'dataset' in search_options.keys() and dataset:
if dataset:
url += '&dataset=' + dataset
# go get the results
print 'obtaining model results from:\n\t' + url
raw_stream = urllib2.urlopen( url + '&type=model' )
... |
# debug output
if len( matches ) > 1:
temp = 'multiple models are \"equally the best\":'
print temp
text += temp +'\n'
for i in matches:
temp = '\t'+ i['coordinates']
print temp
text += temp +'\n'
temp = 'copying the first on to be... | best_score = max( [i['target length'] for i in details] )
matches = [i for i in details if i['target length'] == best_score] | conditional_block |
modbase.py | ( dir_name , tagline = ' to sort the data' ):
"""
Creates the directory <dir_name>
WARNING: this will delete the directory and its contents if it already
exists!
Optionally output something special in <tagline>
"""
# check if it exists
print 'Creating a new directory ' + os.p... | create_directory | identifier_name | |
modbase.py | # url += '&' + i +'='+ search_options[i]
# the dataset
# if not 'dataset' in search_options.keys() and dataset:
if dataset:
url += '&dataset=' + dataset
# go get the results
print 'obtaining model results from:\n\t' + url
raw_stream = urllib2.urlopen( url + '&type=model' )
... | # as float
details['evalue'] = float( i.replace( 'EVALUE:' , '' ).strip() )
elif i[:13] == 'TEMPLATE PDB:':
details['template'] = str( i.replace( 'TEMPLATE PDB:' , '' ).strip | details['model score'] = float( i.replace( 'MODEL SCORE:' , '' ).strip() )
elif i[:7] == 'EVALUE:': | random_line_split |
modbase.py | _from_xml_tag( i , 'content' )[0] # just 1, always the first
# if out_directory is empty...this will just do as we want
filename = out_directory + root_filename + '_model_' + str( count ) + '_alignment.pir'
f = open( filename , 'w' )
f.write( i )
... | """
Displays a summary of the ModBase model <details>
Optionally <include_run_details>
Optionally <export> the summary text
"""
# check the input
if isinstance( details , str ):
# assume it just needs to be parsed out
details = extract_model_details_from_modbase_header( ... | identifier_body | |
dir.go | d.cache.NoteDir(now, name)
}
// Return everything we learned.
out = append(out, filteredSlice...)
return
}
////////////////////////////////////////////////////////////////////////
// Public interface
////////////////////////////////////////////////////////////////////////
func (d *dirInode) Lock() {
d.mu.Lock... | err = fmt.Errorf("DeleteObject: %v", err)
return
}
return | random_line_split | |
dir.go | gcs.Object
// Stat the placeholder.
o, err = statObjectMayNotExist(
ctx,
bucket,
NewDirName(dirName, name),
)
if err != nil {
err = fmt.Errorf("statObjectMayNotExist: %v", err)
return
}
// Should we pass on this name?
if o == nil {
continue
}
select {
case <-ctx.Done():
err =... | {
return
} | conditional_block | |
dir.go | (now, name) {
out = append(out, name)
} else {
tmp = append(tmp, name)
}
}
in = tmp
// Feed names into a channel.
unfiltered := make(chan string, 100)
b.Add(func(ctx context.Context) (err error) {
defer close(unfiltered)
for _, name := range in {
select {
case <-ctx.Done():
err = ctx.Err... | {
fn = NewFileName(d.Name(), name)
metadata := map[string]string{
SymlinkMetadataKey: target,
}
o, err = d.createNewObject(ctx, fn, metadata)
if err != nil {
return
}
d.cache.NoteFile(d.cacheClock.Now(), name)
return
} | identifier_body | |
dir.go | // exists in GCS.
// Return the full name of the child and the GCS object it backs up.
CreateChildSymlink(
ctx context.Context,
name string,
target string) (fn Name, o *gcs.Object, err error)
// Create a backing object for a child directory with the supplied (relative)
// name, failing with *gcs.Precondition... | (
ctx context.Context,
bucket gcs.Bucket,
name Name) (o *gcs.Object, err error) {
// Call the bucket.
req := &gcs.StatObjectRequest{
Name: name.GcsObjectName(),
}
o, err = bucket.StatObject(ctx, req)
// Suppress "not found" errors.
if _, ok := err.(*gcs.NotFoundError); ok {
err = nil
}
// Annotate oth... | statObjectMayNotExist | identifier_name |
forwarder_test.go | hmap := map[string]interface{}{
"/ping": func(ctx json.Context, ping *Ping) (*Pong, error) {
return &Pong{"Hello, world!", address, ctx.Headers()}, nil
},
"/error": func(ctx json.Context, ping *Ping) (*Pong, error) {
return nil, errors.New("remote error")
},
}
s.Require().NoError(json.Register(channel,... |
func (s *ForwarderTestSuite) TestForwardJSON() {
var ping Ping
var pong Pong
dest, err := s.sender.Lookup("reachable")
s.NoError(err)
headerBytes := []byte(`{"hdr1": "val1"}`)
res, err := s.forwarder.ForwardRequest(ping.Bytes(), dest, "test", "/ping", []string{"reachable"},
tchannel.JSON, &Options{Headers: ... | {
s.channel.Close()
s.peer.Close()
} | identifier_body |
forwarder_test.go | request to be forwarded")
var response pingpong.PingPongPingResult
err = DeserializeThrift(context.Background(), res, &response)
s.NoError(err)
s.Equal("correct pinging host", response.Success.Source)
}
func (s *ForwarderTestSuite) TestForwardThriftWithCtxOption() {
dest, err := s.sender.Lookup("reachable")
... | DeserializeThrift | identifier_name | |
forwarder_test.go | {
hmap := map[string]interface{}{
"/ping": func(ctx json.Context, ping *Ping) (*Pong, error) {
return &Pong{"Hello, world!", address, ctx.Headers()}, nil
},
"/error": func(ctx json.Context, ping *Ping) (*Pong, error) {
return nil, errors.New("remote error")
},
}
s.Require().NoError(json.Register(chann... | Key: "error",
},
}
bytes, err := SerializeThrift(context.Background(), request)
s.NoError(err, "expected ping to be serialized")
res, err := s.forwarder.ForwardRequest(bytes, dest, "test", "PingPong::Ping", []string{"reachable"},
tchannel.Thrift, nil)
s.NoError(err, "expected request to be forwarded")
v... |
request := &pingpong.PingPongPingArgs{
Request: &pingpong.Ping{ | random_line_split |
forwarder_test.go | (res, &pong))
s.Equal("correct pinging host", pong.From)
s.Equal("Hello, world!", pong.Message)
s.Equal(map[string]string{"hdr1": "val1"}, pong.Headers)
}
func (s *ForwarderTestSuite) TestForwardJSONErrorResponse() {
var ping Ping
dest, err := s.sender.Lookup("reachable")
s.NoError(err)
_, err = s.forwarder.F... | {
t.Errorf("ringpop claimed that the forwarded header was set before it was set")
} | conditional_block | |
myrule2.js | Date() {
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var cur... |
//问题:抓包显示有8个介绍界面,但只在historyHomePageList中获取到4个,原因是正则匹配时有问题??
//解决:列表中间的一个historyHomePageObj['list'][item]["app_msg_ext_info"]为undefined, 异常阻止了其他
// 介绍页面的获取!
for(var item in historyHomePageObj['list']){
console.l... | random_line_split | |
myrule2.js | () {
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var current... | }
next += 'setTimeout(function(){window.location.href="' + url + '";},' + delay + ');';
next += 'setTimeout(function(){window.location.href="' + url + '";},10000);';
next += '</script>';
return next;
},
getNotification: function () {
ret... | cript">';
} else {
var next = '<script type="text/javascript">';
| conditional_block |
myrule2.js | Date() {
var date = new | function(db, callback) {
//连接到表 site
var collection = db.collection('site');
//插入数据
data = articleLinkArr;
collection.insert(data, function(err, result) {
if(err)
{
console.log('Error:'+ err);
return;
}
callback(result);
});
};
module.e... | Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear... | identifier_body |
myrule2.js | Date() { | new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullY... |
var date = | identifier_name |
main.go | Config()
sessionConfig, _ := json.Marshal(globalsessionkeeper.ChompConfig.ManagerConfig)
dbConfig := globalsessionkeeper.ChompConfig.DbConfig
fmt.Printf("\n\n\nIn init, new manager\n")
fmt.Printf("In init, new manager\n")
fmt.Printf("In init, new manager\n\n\n\n")
globalsessionkeeper.GlobalSessions, err = session... |
func (ah AppHandler) ServerHttp(w http.ResponseWriter, r *http.Request) {
fmt.Printf("AH Context = %v\n", ah.appContext)
err := ah.h(ah.appContext, w, r)
if err != nil {
// log.Printf("HTTP %d: %q", status, err)
status := err.(globalsessionkeeper.ErrorResponse).Code
switch status {
case http.StatusNotFoun... | {
fmt.Printf("Going out as: %v\n", errorResponse)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(errorResponse.Code)
json.NewEncoder(w).Encode(errorResponse)
} | identifier_body |
main.go | Config()
sessionConfig, _ := json.Marshal(globalsessionkeeper.ChompConfig.ManagerConfig)
dbConfig := globalsessionkeeper.ChompConfig.DbConfig
fmt.Printf("\n\n\nIn init, new manager\n")
fmt.Printf("In init, new manager\n")
fmt.Printf("In init, new manager\n\n\n\n")
globalsessionkeeper.GlobalSessions, err = session... | status := err.(globalsessionkeeper.ErrorResponse).Code
switch status {
case http.StatusNotFound:
fmt.Printf("Error: Page not found\n")
HttpErrorResponder(w, err.(globalsessionkeeper.ErrorResponse))
case http.StatusInternalServerError:
fmt.Printf("Error: %v\n", http.StatusInternalServerError)
HttpErr... |
fmt.Printf("AH Context = %v\n", ah.appContext)
err := ah.h(ah.appContext, w, r)
if err != nil {
// log.Printf("HTTP %d: %q", status, err) | random_line_split |
main.go | Config()
sessionConfig, _ := json.Marshal(globalsessionkeeper.ChompConfig.ManagerConfig)
dbConfig := globalsessionkeeper.ChompConfig.DbConfig
fmt.Printf("\n\n\nIn init, new manager\n")
fmt.Printf("In init, new manager\n")
fmt.Printf("In init, new manager\n\n\n\n")
globalsessionkeeper.GlobalSessions, err = session... | else if auth[0] != "Basic" {
http.Error(w, "bad syntax", http.StatusBadRequest)
return
}
payload, _ := base64.StdEncoding.DecodeString(auth[1])
pair := strings.SplitN(string(payload), ":", 2)
if len(pair) != 2 || !Validate(pair[0], pair[1]) {
http.Error(w, "au... | {
http.Error(w, "bad syntax", http.StatusBadRequest)
return
} | conditional_block |
main.go | Config()
sessionConfig, _ := json.Marshal(globalsessionkeeper.ChompConfig.ManagerConfig)
dbConfig := globalsessionkeeper.ChompConfig.DbConfig
fmt.Printf("\n\n\nIn init, new manager\n")
fmt.Printf("In init, new manager\n")
fmt.Printf("In init, new manager\n\n\n\n")
globalsessionkeeper.GlobalSessions, err = session... | (pass handler) handler {
return func(w http.ResponseWriter, r *http.Request) {
cookie := globalsessionkeeper.GetCookie(r)
if cookie == "" {
//need logging here instead of print
fmt.Println("Session Auth Cookie = %v", cookie)
query := mux.Vars(r)
fmt.Printf("Query here.. %v\n", query)
if query["toke... | SessionAuth | identifier_name |
predicates.go | }
return ok, reasons, err
}
func getReasonsString(reasons []core.PredicateFailureReason) string {
if len(reasons) == 0 {
return ""
}
ss := make([]string, 0, len(reasons))
for _, reason := range reasons {
ss = append(ss, reason.GetReason())
}
return strings.Join(ss, ", ")
}
func NewPredicateHelper(pre core... |
func (m SchedtagInputResourcesMap) GetAvoidTags() []computeapi.SchedtagConfig {
return m.getAllTags(false)
}
type CandidateInputResourcesMap struct {
*sync.Map // map[string]SchedtagInputResourcesMap
}
type ISchedtagCandidateResource interface {
GetName() string
GetId() string
Keyword() string
GetSchedtags() ... | {
return m.getAllTags(true)
} | identifier_body |
predicates.go | () []computeapi.SchedtagConfig {
return m.getAllTags(false)
}
type CandidateInputResourcesMap struct {
*sync.Map // map[string]SchedtagInputResourcesMap
}
type ISchedtagCandidateResource interface {
GetName() string
GetId() string
Keyword() string
GetSchedtags() []models.SSchedtag
GetSchedtagJointManager() mod... | OnSelectEnd | identifier_name | |
predicates.go | ([]computeapi.SchedtagConfig, 0)
for _, ss := range m {
for _, s := range ss {
var tags []computeapi.SchedtagConfig
if isPrefer {
tags = s.PreferTags
} else {
tags = s.AvoidTags
}
ret = append(ret, tags...)
}
}
return ret
}
func (m SchedtagInputResourcesMap) GetPreferTags() []computeapi.S... | {
resTags = append(resTags, res.GetSchedtags()...)
} | conditional_block | |
predicates.go | }
}
return ret
}
func (m SchedtagInputResourcesMap) GetPreferTags() []computeapi.SchedtagConfig {
return m.getAllTags(true)
}
func (m SchedtagInputResourcesMap) GetAvoidTags() []computeapi.SchedtagConfig {
return m.getAllTags(false)
}
type CandidateInputResourcesMap struct {
*sync.Map // map[string]SchedtagInpu... | preferTags := inputRes.GetPreferTags()
avoidCountMap := GetSchedtagCount(avoidTags, resTags, api.AggregateStrategyAvoid)
preferCountMap := GetSchedtagCount(preferTags, resTags, api.AggregateStrategyPrefer)
| random_line_split | |
adminEventTitle.js | .png'
import { subscribe } from '../../../redux/middlweare/crud'
import AllEvents from '../../events/allEvents/allEvents'
import FooterEventsGallery from '../../footer/footerEventsGallery';
import UploadImageFromConfigurator from '../../Configurator/uploadImageFromConfigurator';
import uploadIcon from '../../../assets/... | site: state.site,
pagesettings: state.pageSettings.page,
headersettings: state.editHeader.header,
subscribesettings: state.editSubscription.subscribe,
// (לחלק לכמה רדיוסרים)
// text-align נתונים מהשרת................................
}
}
const mapDispatchToProps = (d... | return { | random_line_split |
adminEventTitle.js | '
import { subscribe } from '../../../redux/middlweare/crud'
import AllEvents from '../../events/allEvents/allEvents'
import FooterEventsGallery from '../../footer/footerEventsGallery';
import UploadImageFromConfigurator from '../../Configurator/uploadImageFromConfigurator';
import uploadIcon from '../../../assets/uplo... | gger
var height, len = headersettings.eventsPageTitle.length;
height = Math.ceil(len / 15) * 7;
if (height < 25) {
height += "vh";
console.log("-- ", height, " --");
document.documentElement.style.setProperty('--title-height', height);
}
let te... | loadImg)
}
function setFontsize() {
debu | identifier_body |
adminEventTitle.js | .png'
import { subscribe } from '../../../redux/middlweare/crud'
import AllEvents from '../../events/allEvents/allEvents'
import FooterEventsGallery from '../../footer/footerEventsGallery';
import UploadImageFromConfigurator from '../../Configurator/uploadImageFromConfigurator';
import uploadIcon from '../../../assets/... | }
return (
<>
<div className="container-fluid adminEventTitle" >
<div className="row adminTitleDiv" id='showHeader'>
<img className="myImg titleImgColor" src={img[pagesettings.eventsPageColor]} onClick={changeToPageSettingsComponent}></img>
... | textSize = textSize - 1
}
}
}
document.documentElement.style.setProperty('--font-size-title-admin', `${textSize}vw`);
| conditional_block |
adminEventTitle.js | .png'
import { subscribe } from '../../../redux/middlweare/crud'
import AllEvents from '../../events/allEvents/allEvents'
import FooterEventsGallery from '../../footer/footerEventsGallery';
import UploadImageFromConfigurator from '../../Configurator/uploadImageFromConfigurator';
import uploadIcon from '../../../assets/... | + myImg.width / myImg.height + "@@")
size = myImg.width / myImg.height < 1.5 ? myImg.width / myImg.height * 21 : myImg.width / myImg.height < 2 ? myImg.width / myImg.height * 17 : myImg.width / myImg.height * 12;
size += "vw";
var inputHeight = myImg.width / myImg.height < 1.5 ? 24 : myImg.width... | console.log("@@" | identifier_name |
index.go | c.x, c.y)
}
type Cmd int
const (
CMD_WAIT Cmd = 0
CMD_MOVE Cmd = 1
CMD_DIG Cmd = 2
CMD_RADAR Cmd = 3
CMD_TRAP Cmd = 4
)
type Item int
const (
ITEM_NONE Item = -1
ITEM_RADAR Item = 2
ITEM_TRAP Item = 3
ITEM_ORE Item = 4
)
type Object int
const (
OBJ_ME Object... | (p1, p2 Coord) int {
return int(math.Ceil(float64(digDist(p1, p2)) / MOVE_DIST))
}
/**********************************************************************************
* Serious business here
*********************************************************************************/
func calculateCellRadarValues(unknowns ... | digTurnDist | identifier_name |
index.go |
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func clamp(x, low, high int) int {
return min(max(x, low), high)
}
/**********************************************************************************
* D... | {
if n < 0 {
return -n
}
return n
} | identifier_body | |
index.go | )", c.x, c.y)
}
type Cmd int
const (
CMD_WAIT Cmd = 0
CMD_MOVE Cmd = 1
CMD_DIG Cmd = 2
CMD_RADAR Cmd = 3
CMD_TRAP Cmd = 4
)
type Item int
const (
ITEM_NONE Item = -1
ITEM_RADAR Item = 2
ITEM_TRAP Item = 3
ITEM_ORE Item = 4
)
type Object int
const (
OBJ_ME Obj... | robot := &(*robots)[myRobot_i]
robot.id = id
robot.pos | random_line_split | |
index.go | c.x, c.y)
}
type Cmd int
const (
CMD_WAIT Cmd = 0
CMD_MOVE Cmd = 1
CMD_DIG Cmd = 2
CMD_RADAR Cmd = 3
CMD_TRAP Cmd = 4
)
type Item int
const (
ITEM_NONE Item = -1
ITEM_RADAR Item = 2
ITEM_TRAP Item = 3
ITEM_ORE Item = 4
)
type Object int
const (
OBJ_ME Object... |
if r.cmd == CMD_DIG {
return fmt.Sprintf("DIG %d %d", r.targetPos.x, r.targetPos.y)
}
if r.cmd == CMD_RADAR {
return "REQUEST RADAR"
}
if r.cmd == CMD_TRAP {
return "REQUEST TRAP"
}
fmt.Fprintf(os.Stderr, "Unknown command type for robot! %d, id: %d", r.cmd, r.id)
... | {
return fmt.Sprintf("MOVE %d %d", r.targetPos.x, r.targetPos.y)
} | conditional_block |
main.rs | () {
let s: Vec<usize> = std::fs::read_to_string("src/e11.txt")
.unwrap()
.split_whitespace()
.map(|n| n.parse::<usize>().unwrap())
.collect();
//println!("{:?}", s);
// could just run with s, but let's build our 2d array.
let mut v = [[0; 20]; 20];
(0..400).for_each(... | e11 | identifier_name | |
main.rs | % 2 == 0 {
let counter = h.entry(2).or_insert(0);
*counter += 1;
n /= 2;
}
let mut i = 3;
while n > 1 {
while n % i == 0 {
let counter = h.entry(i).or_insert(0);
*counter += 1;
n /= i;
}
... |
let triangle: Vec<Vec<usize>> = std::fs::read_to_string("src/e18.txt")
.unwrap()
.lines()
.map(|l| {
l.split_whitespace()
.into_iter()
.map(|n| n.parse::<usize>().unwrap())
.collect::<Vec<usize>>()
})
.collect();
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.