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 |
|---|---|---|---|---|
space_group.py | `Permutation` that represents a lattice permutation.
Stores translation lattice vector and generates a sensible name from it.
The product of two `Translation`s carries the appropriate displacement vector.
"""
def __init__(self, permutation: Array, displacement: Array):
r"""
Creates a ... |
return PermutationGroup(perms, degree=self.lattice.n_nodes)
@struct.property_cached
def rotation_group(self) -> PermutationGroup:
"""The group of rotations (i.e. point group symmetries with determinant +1)
as a `PermutationGroup` acting on the sites of `self.lattice`."""
perms ... | perm = self.lattice.id_from_position(p.preimage(self.lattice.positions))
perms.append(Permutation(perm, name=str(p))) | conditional_block |
space_group.py | `Permutation` that represents a lattice permutation.
Stores translation lattice vector and generates a sensible name from it.
The product of two `Translation`s carries the appropriate displacement vector.
"""
def __init__(self, permutation: Array, displacement: Array):
r"""
Creates a ... |
def translation_group(
self, axes: Optional[Union[int, Sequence[int]]] = None
) -> PermutationGroup:
"""
The group of valid translations of `self.lattice` as a `PermutationGroup`
acting on the sites of the same.
"""
if axes is None:
return self._full... | """
The group of valid translations of `self.lattice` as a `PermutationGroup`
acting on the sites of the same.
"""
return reduce(
PermutationGroup.__matmul__,
[self._translations_along_axis(i) for i in range(self.lattice.ndim)],
) | identifier_body |
space_group.py | `Permutation` that represents a lattice permutation.
Stores translation lattice vector and generates a sensible name from it.
The product of two `Translation`s carries the appropriate displacement vector.
"""
def | (self, permutation: Array, displacement: Array):
r"""
Creates a `Translation` from a permutation array and a displacement vector
Arguments:
permutation: a 1D array listing :math:`g^{-1}(x)` for all
:math:`0\le x < N` (i.e., `V[permutation]` permutes the
... | __init__ | identifier_name |
space_group.py | `Permutation` that represents a lattice permutation.
Stores translation lattice vector and generates a sensible name from it.
The product of two `Translation`s carries the appropriate displacement vector.
"""
def __init__(self, permutation: Array, displacement: Array):
r"""
Creates a ... | if isinstance(p, Identity):
perms.append(Identity())
else:
# note that we need the preimages in the permutation
perm = self.lattice.id_from_position(p.preimage(self.lattice.positions))
perms.append(Permutation(perm, name=str(p)))
... | """
perms = []
for p in self.point_group_: | random_line_split |
basic_model.py | # taken from the paper
MLP_HIDDEN_DIM = 100
EPOCHS = 150
WORD_EMBEDDING_DIM = 100
POS_EMBEDDING_DIM = 25
HIDDEN_DIM = 125
LEARNING_RATE = 0.01
EARLY_STOPPING = 10 # num epochs with no validation acc improvement to stop training
PATH = "./basic_model_best_params"
cross_entropy_loss = nn.CrossEntropyLoss(reduction='me... | import matplotlib.pyplot as plt
from chu_liu_edmonds import *
from os import path
| random_line_split | |
basic_model.py | # def forward(self, lstm_out):
# sentence_length = lstm_out.shape[0]
# scores = torch.zeros(size=(sentence_length, sentence_length)).to(device)
# for i, v_i in enumerate(lstm_out):
# for j, v_j in enumerate(lstm_out):
# if i == j:
# scores[i, j... | (self, lstm_dim, mlp_hidden_dim):
super(MLP, self).__init__()
self.first_mlp = SplittedMLP(lstm_dim, mlp_hidden_dim)
self.non_linearity = nn.Tanh()
self.second_mlp = nn.Linear(mlp_hidden_dim, 1, bias=True) # will output a score of a pair
def forward(self, lstm_out):
senten... | __init__ | identifier_name |
basic_model.py | [batch_size, seq_length, e_p]
embeds = torch.cat((e_w, e_p), dim=2).to(self.device) # [batch_size, seq_length, e_w + e_p]
# assert embeds.shape[0] == 1 and embeds.shape[2] == POS_EMBEDDING_DIM + WORD_EMBEDDING_DIM
lstm_out, _ = self.lstm(embeds.view(embeds.shape[1], 1, -1)... | hyper_parameter_tuning() | conditional_block | |
basic_model.py | # def forward(self, lstm_out):
# sentence_length = lstm_out.shape[0]
# scores = torch.zeros(size=(sentence_length, sentence_length)).to(device)
# for i, v_i in enumerate(lstm_out):
# for j, v_j in enumerate(lstm_out):
# if i == j:
# scores[i, j... |
class MLP(nn.Module):
def __init__(self, lstm_dim, mlp_hidden_dim):
super(MLP, self).__init__()
self.first_mlp = SplittedMLP(lstm_dim, mlp_hidden_dim)
self.non_linearity = nn.Tanh()
self.second_mlp = nn.Linear(mlp_hidden_dim, 1, bias=True) # will output a score of a pair
de... | heads_hidden = self.fc_h(lstm_out)
mods_hidden = self.fc_m(lstm_out)
return heads_hidden, mods_hidden | identifier_body |
main.go | .UserService.ReadSession(&t)
if err != nil {
respond(w, rsp, err)
return
}
readRsp, err := client.UserService.Read(&user.ReadRequest{
Id: rsp.Session.UserId,
})
respond(w, map[string]interface{}{
"session": rsp.Session,
"account": readRsp.Account,
}, err)
}
func post(w http.ResponseWriter, req *http.Re... | {
if err != nil {
w.WriteHeader(500)
fmt.Println(err)
}
if i == nil {
i = map[string]interface{}{}
}
if err != nil {
i = map[string]interface{}{
"error": err.Error(),
}
}
bs, _ := json.Marshal(i)
fmt.Fprintf(w, fmt.Sprintf("%v", string(bs)))
} | identifier_body | |
main.go | sub"`
}
// Endpoints
// upvote or downvote a post or a comment
func vote(w http.ResponseWriter, req *http.Request, upvote bool, isComment bool, t VoteRequest) error {
if t.Id == "" {
return fmt.Errorf("missing post id")
}
table := "posts"
if isComment {
table = "comments"
}
rsp, err := client.DbService.Read... |
func post(w http.ResponseWriter, req *http.Request) {
if cors(w, req) {
return
}
decoder := json.NewDecoder(req.Body)
var t PostRequest
err := decoder.Decode(&t)
if err != nil {
respond(w, nil, err)
return
}
if t.Post.Sub == "" || t.Post.Title == "" {
respond(w, nil, fmt.Errorf("both title and sub are... | }, err)
} | random_line_split |
main.go | sp.Session.UserId, mods)
if err == nil && (checkRsp != nil && len(checkRsp.Records) > 0) {
if !mod {
return fmt.Errorf("already voted")
}
}
val := float64(1)
if mod {
rand.Seed(time.Now().UnixNano())
val = float64(rand.Intn(17-4) + 4)
}
if !mod {
_, err = client.DbService.Create(&db.CreateRequest{
... | {
sign = -1
} | conditional_block | |
main.go | Password: t.Password,
})
respond(w, logRsp, err)
}
func readSession(w http.ResponseWriter, req *http.Request) {
if cors(w, req) {
return
}
decoder := json.NewDecoder(req.Body)
var t user.ReadSessionRequest
err := decoder.Decode(&t)
if err != nil {
fmt.Fprintf(w, fmt.Sprintf("%v", err.Error()))
}
rsp, er... | respond | identifier_name | |
tcp.rs | , waiting for reply (ACK or FIN)
FinWait2, // sent FIN acked, waiting for FIN from peer
Closing, // Waiting for ACK of FIN (FIN sent and recieved)
TimeWait, // Waiting for timeout after local close
ForceClose, // RST recieved, waiting for user close
CloseWait, // FIN recieved, waiting for user to close (error se... | ConnectionState::TimeWait => self.state,
| random_line_split | |
tcp.rs | : RST
/// 3: PSH
/// 4: ACK
/// 5: URG
/// 6: ECE
/// 7: CWR
flags: u8,
window_size: u16,
checksum: u16,
urgent_pointer: u16,
//options: [u8],
}
const FLAG_FIN: u8 = 1 << 0;
const FLAG_SYN: u8 = 1 << 1;
const FLAG_RST: u8 = 1 << 2;
const FLAG_PSH: u8 = 1 << 3;
const FLAG_ACK: u8 = 1 << 4;
impl PktHeader
{
... | {
// RST received, do an unclean close (reset by peer)
// TODO: Signal to user that the connection is closing (error)
ConnectionState::ForceClose
} | conditional_block | |
tcp.rs | drop
}
#[derive(Copy,Clone,PartialOrd,PartialEq,Ord,Eq)]
struct Quad
{
local_addr: Address,
local_port: u16,
remote_addr: Address,
remote_port: u16,
}
impl ::core::fmt::Debug for Quad
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "Quad({:?}:{} -> {:?}:{})", self.local_addr,... | (local_addr: Address, local_port: u16, remote_addr: Address, remote_port: u16) -> Quad
{
Quad {
local_addr, local_port, remote_addr, remote_port
}
}
fn send_packet(&self, seq: u32, ack: u32, flags: u8, window_size: u16, data: &[u8])
{
// Make a header
// TODO: Any options required?
let options_bytes =... | new | identifier_name |
tcp.rs | drop
}
#[derive(Copy,Clone,PartialOrd,PartialEq,Ord,Eq)]
struct Quad
{
local_addr: Address,
local_port: u16,
remote_addr: Address,
remote_port: u16,
}
impl ::core::fmt::Debug for Quad
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "Quad({:?}:{} -> {:?}:{})", self.local_addr,... |
fn send_packet(&self, seq: u32, ack: u32, flags: u8, window_size: u16, data: &[u8])
{
// Make a header
// TODO: Any options required?
let options_bytes = &[];
let opts_len_rounded = ((options_bytes.len() + 3) / 4) * 4;
let hdr = PktHeader {
source_port: self.local_port,
dest_port: self.remote_port,
... | {
Quad {
local_addr, local_port, remote_addr, remote_port
}
} | identifier_body |
kegweblib.py | ictures"] = picture_or_pictures
c["thumb_size"] = thumb_size
c["gallery_id"] = gallery_id
return c
@register.inclusion_tag("kegweb/badge.html")
def badge(amount, caption, style="", is_volume=False, do_pluralize=False):
if is_volume:
amount = mark_safe(VolumeNode.format(amount, "mL"))
if do... | (parser, token):
"""{% timeago <timestamp> %}"""
tokens = token.contents.split()
if len(tokens) != 2:
raise TemplateSyntaxError("%s requires 2 tokens" % tokens[0])
return TimeagoNode(tokens[1])
class TimeagoNode(Node):
def __init__(self, timestamp_varname):
self._timestamp_varname ... | timeago | identifier_name |
kegweblib.py | ictures"] = picture_or_pictures
c["thumb_size"] = thumb_size
c["gallery_id"] = gallery_id
return c
@register.inclusion_tag("kegweb/badge.html")
def badge(amount, caption, style="", is_volume=False, do_pluralize=False):
if is_volume:
amount = mark_safe(VolumeNode.format(amount, "mL"))
if do... |
@classmethod
def format(cls, amount, units, make_badge=False):
if amount < 0:
amount = 0
ctx = {
"units": units,
"amount": amount,
"title": "%s %s" % (amount, units),
"extra_css": "badge " if make_badge else "",
}
retu... | tv = Variable(self._volume_varname)
try:
num = float(tv.resolve(context))
except (VariableDoesNotExist, ValueError):
num = "unknown"
unit = "mL"
make_badge = "badge" in self._extra_args
return self.format(num, unit, make_badge) | identifier_body |
kegweblib.py | ictures"] = picture_or_pictures
c["thumb_size"] = thumb_size
c["gallery_id"] = gallery_id
return c
@register.inclusion_tag("kegweb/badge.html")
def badge(amount, caption, style="", is_volume=False, do_pluralize=False):
if is_volume:
amount = mark_safe(VolumeNode.format(amount, "mL"))
if do... |
return context["guest_info"]["name"]
# chart
@register.tag("chart")
def chart(parser, tokens):
"""{% chart <charttype> <obj> width height %}"""
tokens = tokens.contents.split()
if len(tokens) < 4:
raise TemplateSyntaxError("chart requires at least 4 arguments")
charttype = tokens[1]... | return '<a href="%s">%s</a>' % (
reverse("kb-drinker", args=[user.username]),
user.get_full_name(),
) | conditional_block |
kegweblib.py | c = {}
if not hasattr(picture_or_pictures, "__iter__"):
c["gallery_pictures"] = [picture_or_pictures]
else:
c["gallery_pictures"] = picture_or_pictures
c["thumb_size"] = thumb_size
c["gallery_id"] = gallery_id
return c
@register.inclusion_tag("kegweb/badge.html")
def badge(amou... | @register.inclusion_tag("kegweb/picture-gallery.html")
def gallery(picture_or_pictures, thumb_size="span2", gallery_id=""): | random_line_split | |
ddpg-per.py | kids
cr_idx = cl_idx + 1
if cl_idx >= len(self.tree): # reach bottom, end search
leaf_idx = parent_idx
break
else: # downward search, always search for a higher priority node
if v <= self.tree[cl_idx]:
... | able_scope(scope):
n_l1 = 30
w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], trainable=trainable)
w1_a = tf.get_variable('w1_a', [self.a_dim, n_l1], trainable=trainable)
b1 = tf.get_variable('b1', [1, n_l1], trainable=trainable)
net = tf.nn.relu(tf.matmul(s... | identifier_body | |
ddpg-per.py | _pointer = 0
def __init__(self, capacity):
self.capacity = capacity # for all priority values
self.tree = np.zeros(2 * capacity - 1)
# [--------------Parent nodes-------------][-------leaves to recode priority-------]
# size: capacity - 1 size: cap... | tion(self, s, a, | identifier_name | |
ddpg-per.py | transition):
max_p = np.max(self.tree.tree[-self.tree.capacity:])
if max_p == 0:
max_p = self.abs_err_upper
self.tree.add(max_p, transition) # set the max p for new p
def sample(self, n):
b_idx, b_memory, ISWeights = np.empty((n,), dtype=np.int32), \
... |
agent = DDPG(a_dim, s_dim, a_bound)
total_steps = 0
var = 3 | random_line_split | |
ddpg-per.py | + state, self.action_low, self.action_high)
class SumTree(object):
data_pointer = 0
def __init__(self, capacity):
self.capacity = capacity # for all priority values
self.tree = np.zeros(2 * capacity - 1)
# [--------------Parent nodes-------------][-------leaves to recode priority---... | tch_memory, ISWeights = self.memory.sample(self.per_batch_size) # sample for learning
batch_states = batch_memory[:,0:3]
batch_actions = batch_memory[:,3:4]
batch_rewards = [data[4] for data in batch_memory]
batch_states_ = batch_memory[:,5:8]
bs = np.array(b... | conditional_block | |
bot.js | client.join(client.CFG.JOIN_CHANNELS);
client.capReq(":twitch.tv/tags twitch.tv/commands twitch.tv/membership");
console.log("Bot: Ready!");
client.send("#supibot", "@Supinic I'm back MrDestructoid");
});
client.on("message", (evt) => {
const user = evt.user.getNick().toLowerCase();
const chan = evt.chan... | random_line_split | ||
bot.js | }
// Declare AFK people as non AFK - silently, if necessary
checkAFK(user, chan, evt);
// If it's a stealth channel, skip everything
if (client.CFG.STEALTH_CHANNELS.indexOf(chan) !== -1) {
return;
}
// Mirror messages to discord, if it's a linked channel
if (chan === client.CFG.CHAN.CEREBOT && clien... | t.reply(":z message too long.");
console.log("CMD REQUEST FAILED - MESSAGE TOO LONG", args.join(" ").length);
}
else | conditional_block | |
jpt_location.py | plot_grid
from pycram.plan_failures import PlanFailure
class JPTCostmapLocation(pycram.designators.location_designator.CostmapLocation):
"""Costmap Locations using Joint Probability Trees (JPTs).
JPT costmaps are trained to model the dependency with a robot position relative to the object, the robots type,
... | (self, sample: np.ndarray) -> Location:
"""
Convert a numpy array sampled from the JPT to a costmap-location
:param sample: The drawn sample
:return: The usable costmap-location
"""
sample_dict = {variable.name: value for variable, value in zip(self.model.variables, samp... | sample_to_location | identifier_name |
jpt_location.py | plot_grid
from pycram.plan_failures import PlanFailure
class JPTCostmapLocation(pycram.designators.location_designator.CostmapLocation):
"""Costmap Locations using Joint Probability Trees (JPTs).
JPT costmaps are trained to model the dependency with a robot position relative to the object, the robots type,
... |
# load model from path
if path:
self.model = jpt.trees.JPT.load(path)
# initialize member for visualized objects
self.visual_ids: List[int] = []
def evidence_from_occupancy_costmap(self) -> List[jpt.variables.LabelAssignment]:
"""
Create a list of boxe... | self.model = model | conditional_block |
jpt_location.py | plot_grid
from pycram.plan_failures import PlanFailure
class JPTCostmapLocation(pycram.designators.location_designator.CostmapLocation):
"""Costmap Locations using Joint Probability Trees (JPTs).
JPT costmaps are trained to model the dependency with a robot position relative to the object, the robots type,
... |
def sample(self, amount: int = 1) -> np.ndarray:
"""
Sample from the locations that fit the CostMap and are not occupied.
:param amount: The amount of samples to draw
:return: A numpy array containing the samples drawn from the tree.
"""
evidence = self.create_evid... | """
Create evidence usable for JPTs where type and status are set if wanted.
:param use_success: Rather to set success or not
:return: The usable label-assignment
"""
evidence = dict()
evidence["type"] = {self.target.type}
if use_success:
evidence["... | identifier_body |
jpt_location.py | import pycram.designators.location_designator
import pycram.task
from pycram.costmaps import OccupancyCostmap, plot_grid
from pycram.plan_failures import PlanFailure
class JPTCostmapLocation(pycram.designators.location_designator.CostmapLocation):
"""Costmap Locations using Joint Probability Trees (JPTs).
JPT... | import numpy as np
import pybullet
import tf
| random_line_split | |
main.go | BookService := orderbook.NewService(db, addressRepository, liquidityPoolRepository, contextLogger)
return &Extender{
Metrics: metrics.New(),
env: env,
nodeApi: nodeApi,
blockService: block.NewBlockService(blockRepository, validatorRepository, broadcastService),
... | {
if response.Height == 1 {
return
}
var links []*models.BlockValidator
for _, v := range response.Validators {
vId, err := ext.validatorRepository.FindIdByPk(helpers.RemovePrefix(v.PublicKey))
if err != nil {
ext.log.Error(err)
}
helpers.HandleError(err)
link := models.BlockValidator{
ValidatorID... | identifier_body | |
main.go | .Now()
return ctx, nil
}
func (eh eventHook) AfterQuery(ctx context.Context, event *pg.QueryEvent) error {
critical := time.Millisecond * 500
result := time.Duration(0)
if event.Stash != nil {
if v, ok := event.Stash["query_time"]; ok {
result = time.Now().Sub(v.(time.Time))
}
} | if result > critical {
bigQueryLog, err := os.OpenFile("big_query.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
eh.log.Error("error opening file: %v", err)
}
// don't forget to close it
defer bigQueryLog.Close()
eh.log.SetReportCaller(false)
eh.log.SetFormatter(&logrus.JSONFormatter{}... | random_line_split | |
main.go | //hookImpl := eventHook{
// log: logrus.New(),
// beforeTime: time.Now(),
//}
db := pg.Connect(pgOptions)
//db.AddQueryHook(hookImpl)
uploader := genesisUploader.New(genesisEnv.Config{
Debug: false,
PostgresHost: env.DbHost,
PostgresPort: env.DbPort,
PostgresDB: e... | handleBlockResponse | identifier_name | |
main.go | := address.NewRepository(db)
coinRepository := coin.NewRepository(db)
eventsRepository := events.NewRepository(db)
balanceRepository := balance.NewRepository(db)
liquidityPoolRepository := liquidity_pool.NewRepository(db)
orderbookRepository := orderbook.NewRepository(db)
coins.GlobalRepository = coins.NewRep... | {
start := ext.env.TxChunkSize * i
end := start + ext.env.TxChunkSize
if end > len(response.Transactions) {
end = len(response.Transactions)
}
layout := "2006-01-02T15:04:05Z"
blockTime, err := time.Parse(layout, response.Time)
if err != nil {
ext.log.Panic(err)
}
ext.saveTransactions(response... | conditional_block | |
utils.py | binary_img = gray_img.point(lambda x: 255 if x < otsu else 0, '1')
return binary_img
class Binary(object):
def __call__(self, img):
return binary(img)
def squeeze_weights(m):
m.weight.data = m.weight.data.sum(dim=1)[:, None]
m.in_channels = 1
def change_out_features(m, classes):
m.out... |
else:
s_h, s_w = stride
step = (s_h, s_w, n_colors)
extracted_patches = _extract_patches(image,
patch_shape=(p_h, p_w, n_colors),
extraction_step=step)
n_patches = _compute_n_patches(i_h, i_w, p_h, p_w, stri... | step = stride
s_h = stride
s_w = stride | conditional_block |
utils.py | binary_img = gray_img.point(lambda x: 255 if x < otsu else 0, '1')
return binary_img
class Binary(object):
def __call__(self, img):
return binary(img)
def squeeze_weights(m):
m.weight.data = m.weight.data.sum(dim=1)[:, None]
m.in_channels = 1
def change_out_features(m, classes):
m.out... | else:
raise ValueError("Invalid value for max_patches: %r" % max_patches)
else:
return all_patches
def clean_patches(patches, th=2000):
indices = []
for i, patch in enumerate(patches):
if patch.shape[-1] == 3:
patch = patch / 255
num_features = ... | if isinstance(stride, numbers.Number):
s_h = stride
s_w = stride
else:
s_h, s_w = stride
n_h = (i_h - p_h) // s_h + 1
n_w = (i_w - p_w) // s_w + 1
all_patches = n_h * n_w
if max_patches:
if (isinstance(max_patches, numbers.Integral)
and max_patches <... | identifier_body |
utils.py | binary_img = gray_img.point(lambda x: 255 if x < otsu else 0, '1')
return binary_img
class Binary(object):
def __call__(self, img):
return binary(img)
def squeeze_weights(m):
m.weight.data = m.weight.data.sum(dim=1)[:, None]
m.in_channels = 1
def change_out_features(m, classes):
m.out... | patches = extracted_patches
patches = patches.reshape(-1, p_h, p_w, n_colors)
# remove the color dimension if useless
if patches.shape[-1] == 1:
patches = patches.reshape((n_patches, p_h, p_w))
# return clean_patches(patches, th)
return patches
def _compute_n_patches(i_h, i_w, p_... | random_line_split | |
utils.py | binary_img = gray_img.point(lambda x: 255 if x < otsu else 0, '1')
return binary_img
class Binary(object):
def __call__(self, img):
return binary(img)
def squeeze_weights(m):
m.weight.data = m.weight.data.sum(dim=1)[:, None]
m.in_channels = 1
def change_out_features(m, classes):
m.out... | (Dataset):
def __init__(self, dataset, col_transform=None, bin_transform=None):
self.dataset = dataset
self.col_transform = col_transform
self.bin | BinColorDataset | identifier_name |
reaper-rush.rs | Greater => {
let local_minerals = mineral_fields
.iter()
.closer(11.0, base)
.map(|m| m.tag())
.collect::<Vec<u64>>();
idle_workers.extend(
self.units
.my
.workers
.filter(|u| {
u.target_tag().map_or(false, |target_tag| {
local_minerals.cont... | }
}
if self.counter().all().count(UnitTypeId::Barracks) < 4
&& self.can_afford(UnitTypeId::Barracks, false)
{
if let Some(location) = self.find_placement(
UnitTypeId::Barracks,
main_base,
PlacementOptions {
step: 4,
..Default::default()
},
) {
if let Some(builder) = self... | builder.build(UnitTypeId::SupplyDepot, location, false);
self.subtract_resources(UnitTypeId::SupplyDepot, false);
return;
} | random_line_split |
reaper-rush.rs | => {
let local_minerals = mineral_fields
.iter()
.closer(11.0, base)
.map(|m| m.tag())
.collect::<Vec<u64>>();
idle_workers.extend(
self.units
.my
.workers
.filter(|u| {
u.target_tag().map_or(false, |target_tag| {
local_minerals.contains(&t... | (&mut self) {
if self.minerals < 50 || self.supply_left == 0 {
return;
}
if self.supply_workers < 22 && self.can_afford(UnitTypeId::SCV, true) {
if let Some(cc) = self
.units
.my
.townhalls
.iter()
.find(|u| u.is_ready() && u.is_almost_idle())
{
cc.train(UnitTypeId::SCV, false);
... | train | identifier_name |
reaper-rush.rs | => {
let local_minerals = mineral_fields
.iter()
.closer(11.0, base)
.map(|m| m.tag())
.collect::<Vec<u64>>();
idle_workers.extend(
self.units
.my
.workers
.filter(|u| {
u.target_tag().map_or(false, |target_tag| {
local_minerals.contains(&t... | else {
None
};
for u in &idle_workers {
if let Some(closest) = deficit_geysers.closest(u) {
let tag = closest.tag();
deficit_geysers.remove(tag);
u.gather(tag, false);
} else if let Some(closest) = deficit_minings.closest(u) {
u.gather(
mineral_fields
.closer(11.0, closest)
... | {
let minerals = mineral_fields.filter(|m| bases.iter().any(|base| base.is_closer(11.0, *m)));
if minerals.is_empty() {
None
} else {
Some(minerals)
}
} | conditional_block |
reaper-rush.rs | Greater => {
let local_minerals = mineral_fields
.iter()
.closer(11.0, base)
.map(|m| m.tag())
.collect::<Vec<u64>>();
idle_workers.extend(
self.units
.my
.workers
.filter(|u| {
u.target_tag().map_or(false, |target_tag| {
local_minerals.cont... | .units
.my
.structures
.iter()
.find(|u| u.type_id() == UnitTypeId::Barracks && u.is_ready() && u.is_almost_idle())
{
barracks.train(UnitTypeId::Reaper, false);
self.subtract_resources(UnitTypeId::Reaper, true);
}
}
}
fn throw_mine(&self, reaper: &Unit, target: &Unit) -> bool {
... | {
if self.minerals < 50 || self.supply_left == 0 {
return;
}
if self.supply_workers < 22 && self.can_afford(UnitTypeId::SCV, true) {
if let Some(cc) = self
.units
.my
.townhalls
.iter()
.find(|u| u.is_ready() && u.is_almost_idle())
{
cc.train(UnitTypeId::SCV, false);
self.sub... | identifier_body |
p_test.go | 1"},
{test.Variable("function"), "function"},
}
for _, v := range variables {
if name := parser.identifierName(v.source); name != v.expected {
t.Errorf("'%s' expected, '%s' found.\n", v.expected, name)
}
}
nop := test.Nop()
if l := nodeList(nop); l[0] != nop {
t.Error("Nothing should happen to passed n... | tests := []struct {
source []byte
expected string
}{
// Sandbox
{
source: []byte(`<?php
function fc() {
$a = 1 + 2;
}
`),
expected: `func fc() {
a := 1 + 2
}`,
},
// examples/04.php
{
source: []byte(`<?php
function fc() {
$a = 2 + 3 + 4 * 2;
echo $a * $a | tt.Helper()
| random_line_split |
p_test.go | "},
{test.Variable("function"), "function"},
}
for _, v := range variables {
if name := parser.identifierName(v.source); name != v.expected {
t.Errorf("'%s' expected, '%s' found.\n", v.expected, name)
}
}
nop := test.Nop()
if l := nodeList(nop); l[0] != nop {
t.Error("Nothing should happen to passed no... |
}
func unaryOp(t *testing.T) {
t.Helper()
parent := lang.NewCode(nil)
parser := fileParser{parser: &parser{}}
for _, n := range []node.Node{
test.Plus(test.String(`"test"`)),
test.Plus(test.String(`""`)),
} {
e := parser.expression(parent, n)
if e.Parent() != parent {
t.Error("Parent not set.")
}
... | {
expr := parser.expression(nil, test.BinaryOp(left, c.op, right))
op, ok := expr.(*lang.BinaryOp)
if !ok {
t.Fatal("Expected binary operation, something else found.")
}
if op.Operation != c.op {
t.Errorf("'%s' expected, '%s' found.", c.op, op.Operation)
}
if !op.Type().Equal(c.ret) {
t.Errorf("'... | conditional_block |
p_test.go | 1"},
{test.Variable("function"), "function"},
}
for _, v := range variables {
if name := parser.identifierName(v.source); name != v.expected {
t.Errorf("'%s' expected, '%s' found.\n", v.expected, name)
}
}
nop := test.Nop()
if l := nodeList(nop); l[0] != nop {
t.Error("Nothing should happen to passed n... | (tt *testing.T) {
tt.Helper()
tests := []struct {
source []byte
expected string
}{
// Sandbox
{
source: []byte(`<?php
function fc() {
$a = 1 + 2;
}
`),
expected: `func fc() {
a := 1 + 2
}`,
},
// examples/04.php
{
source: []byte(`<?php
function fc() {
$a = 2 + 3 +... | testMain | identifier_name |
p_test.go | func testBinaryOp(t *testing.T) {
t.Helper()
left := test.Int("1")
right := test.Int("2")
cases := []struct {
op string
ret string
}{
{"+", lang.Int},
{"-", lang.Int},
{"*", lang.Int},
{"<", lang.Bool},
{"<=", lang.Bool},
{">=", lang.Bool},
{">", lang.Bool},
{"==", lang.Bool},
}
parser := ... | {
r := strings.Split(ref, "\n")
o := strings.Split(out, "\n")
i, j := 0, 0
for i < len(r) && j < len(o) {
c := true
s1 := strings.TrimLeft(r[i], "\t")
if s1 == "" {
i++
c = false
}
s2 := strings.TrimLeft(o[j], "\t")
if s2 == "" {
j++
c = false
}
if !c {
continue
}
if s1 != s2 { | identifier_body | |
repo_polling.go | )
continue
}
for _, p := range proj {
if RunningPollers.Workers[p.Key] == nil {
w := NewWorker(p.Key)
RunningPollers.mutex.Lock()
RunningPollers.Workers[p.Key] = w
RunningPollers.mutex.Unlock()
var pollerhasStop = func() {
RunningPollers.mutex.Lock()
delete(RunningPollers.Work... |
var quit chan bool
var atLeastOne bool
for i := range pollers {
p := &pollers[i]
b, _ := repositoriesmanager.CheckApplicationIsAttached(db, p.Name, w.ProjectKey, p.Application.Name)
if !b || p.Application.RepositoriesManager == nil || p.Application.RepositoryFullname == "" {
continue
}
if !p.Applicatio... | if err != nil {
return false, nil, err
} | random_line_split |
repo_polling.go | .Name, p.Pipeline.Name, p.Name)
//Get fro mcache to know if someone is polling the repo
cache.Get(k, &mayIWork)
//If nobody is polling it
if mayIWork == "" {
log.Info("Polling> Polling repository %s for %s/%s\n", p.Application.RepositoryFullname, w.ProjectKey, p.Application.Name)
cache.SetWithTTL(k, "true... | {
db := database.DB()
if db == nil {
time.Sleep(30 * time.Minute)
continue
}
execs, _ := LoadExecutions(db)
for i := range execs {
tenDaysAGo := time.Now().Add(-10 * 24 * time.Hour)
if execs[i].Execution.Before(tenDaysAGo) {
deleteExecution(db, &execs[i])
}
}
time.Sleep(1 * time.Hour)... | conditional_block | |
repo_polling.go | ID, pipID)
for RunningPollers.Workers[w.ProjectKey] != nil {
//Check database connection
db := database.DB()
if db == nil {
time.Sleep(60 * time.Second)
continue
}
//Loading poller from database
p, err := poller.LoadPollerByApplicationAndPipeline(db, appID, pipID)
if err != nil {
log.Warning("P... | {
query := `
update poller_execution set status = $2, data = $3 where id = $1
`
data, _ := json.Marshal(e.Events)
if _, err := db.Exec(query, e.ID, e.Status, data); err != nil {
return err
}
return nil
} | identifier_body | |
repo_polling.go | )
continue
}
for _, p := range proj {
if RunningPollers.Workers[p.Key] == nil {
w := NewWorker(p.Key)
RunningPollers.mutex.Lock()
RunningPollers.Workers[p.Key] = w
RunningPollers.mutex.Unlock()
var pollerhasStop = func() {
RunningPollers.mutex.Lock()
delete(RunningPollers.Work... | (tx *sql.Tx, rm *sdk.RepositoriesManager, poller *sdk.RepositoryPoller, e sdk.VCSPushEvent, projectData *sdk.Project) (bool, error) {
client, err := repositoriesmanager.AuthorizedClient(tx, projectData.Key, rm.Name)
if err != nil {
return false, err
}
// Create pipeline args
var args []sdk.Parameter
args = appe... | TriggerPipeline | identifier_name |
keycap.js | this.selectedKey.topView.viewbox = "0 0 " + this.selectedKey.topView.body.width + " " + this.selectedKey.topView.body.height
this.updateSnapPoints()
},
updateText: function(text) {
this.surfaces[this.currentView].text.value = text
surface = document.querySelector('.restrictRect').getBounding... | {
var surface = document.querySelector('.restrictRect').getBoundingClientRect()
interact('.moveableText')
.draggable({
onmove: window.dragMoveListener,
snap: {
targets: [{}],
range:20,
relativePoints: [
//{ x: 0 , y: 0 } // snap relative to the element's top... | identifier_body | |
keycap.js | .62 12.64 10.51C11.24 10.4 9.84 10.18 8.47 9.85C8.16 9.78 7.85 9.7 7.18 9.54C7 9.5 6.81 9.49 6.62 9.52C6.41 9.55 6.59 9.52 6.51 9.53C5.96 9.61 5.52 10.04 5.42 10.58C4.97 13.11 3.83 19.41 2 29.5L37 29.5Z", "restrict":{"height":17,"width":27,"x":6,"y":12}},
"leftView":{"path":"M2 29.89L37 30L30.75 10L3.77 14.33L2 29.... | () {
return {transform: 'translate(' + this.surfaces[this.currentView].img.x + 'px,' + this.surfaces[this.currentView].img.y + 'px)'}
}
},
mounted: function () {
var self = this;
fetch('https://us-central1-hotsguide-188315.cloudfunctions.net/function-1?board=keyboard-104&sides=true'... | transformImg | identifier_name |
keycap.js | -188315.cloudfunctions.net/function-1', //read comments in search.php for more information usage
// type: 'GET',
// data: {board: 'keyboard-61', sides:true},
// dataType: 'json',
// success: function(json) {
// self.keys = json.keys;
// self.sides = json.sides;
// }
// }); ... | var thisSurface = surface
img.onload = function () {
var svg_xml = (new XMLSerializer()).serializeToString(newSvg); | random_line_split | |
keycap.js | .62 12.64 10.51C11.24 10.4 9.84 10.18 8.47 9.85C8.16 9.78 7.85 9.7 7.18 9.54C7 9.5 6.81 9.49 6.62 9.52C6.41 9.55 6.59 9.52 6.51 9.53C5.96 9.61 5.52 10.04 5.42 10.58C4.97 13.11 3.83 19.41 2 29.5L37 29.5Z", "restrict":{"height":17,"width":27,"x":6,"y":12}},
"leftView":{"path":"M2 29.89L37 30L30.75 10L3.77 14.33L2 29.... | else {
itemsSpan = document.createElement('span')
itemsSpan.innerHTML = ' ('+cartItems.length+')'
itemsSpan.setAttribute('style','color:blue;')
cartLink.appendChild(itemsSpan)
}
})
},
setColor: function(color) {
document.querySelector('.key... | {
itemsSpan.innerHTML = ' ('+cartItems.length+')'
} | conditional_block |
replicator.go | bind_port", 6000))
r.driveRoot = cnf.GetDefault("app:object-server", "devices", "/srv/node")
r.rpcPort = int(cnf.GetInt("object-replicator", "rpc_port", 60000))
r.concurrency = int(cnf.GetInt("object-replicator", "concurrency", 1))
r.interval = int(cnf.GetInt("object-replicator", "interval", 60*60*24))
}
func (r ... | zap.String("url", url), zap.Error(err))
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusInsufficientStorage {
return nil, ErrRemoteDiskUnmounted
}
if resp.StatusCode != http.StatusOK {
return nil, ErrRemoteHash
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
r.l... | {
url := fmt.Sprintf("http://%s:%d/%s/%s",
node.Ip, node.Port, node.Device, partition)
if len(suffixes) > 0 {
url = fmt.Sprintf("%s/%s", url, strings.Join(suffixes, "-"))
}
req, err := http.NewRequest(common.REPLICATE, url, nil)
if err != nil {
r.logger.Error("unable to create diff request",
zap.String(... | identifier_body |
replicator.go | _port", 6000))
r.driveRoot = cnf.GetDefault("app:object-server", "devices", "/srv/node")
r.rpcPort = int(cnf.GetInt("object-replicator", "rpc_port", 60000))
r.concurrency = int(cnf.GetInt("object-replicator", "concurrency", 1))
r.interval = int(cnf.GetInt("object-replicator", "interval", 60*60*24))
}
func (r *Rep... | (
policy int, device *ring.Device, partition string, nodes *NodeChain) {
rehashed, localHash := r.getLocalHash(policy, device.Device, partition, nil)
r.stat.rehashed += rehashed
attempts := int(r.rings[policy].ReplicaCount()) - 1
for node := nodes.Next(); node != nil && attempts > 0; node = nodes.Next() {
attem... | replicateLocal | identifier_name |
replicator.go | ))
r.concurrency = int(cnf.GetInt("object-replicator", "concurrency", 1))
r.interval = int(cnf.GetInt("object-replicator", "interval", 60*60*24))
}
func (r *Replicator) collectDevices(policyFilter, deviceFilter string) {
pf := map[int]bool{}
for _, p := range strings.Split(policyFilter, ",") {
if p == "" {
co... | if remoteHash[s] != h {
suffixes = append(suffixes, s)
}
}
| random_line_split | |
replicator.go | _port", 6000))
r.driveRoot = cnf.GetDefault("app:object-server", "devices", "/srv/node")
r.rpcPort = int(cnf.GetInt("object-replicator", "rpc_port", 60000))
r.concurrency = int(cnf.GetInt("object-replicator", "concurrency", 1))
r.interval = int(cnf.GetInt("object-replicator", "interval", 60*60*24))
}
func (r *Rep... |
}
return hashes, nil
}
func (r *Replicator) replicateLocal(
policy int, device *ring.Device, partition string, nodes *NodeChain) {
rehashed, localHash := r.getLocalHash(policy, device.Device, partition, nil)
r.stat.rehashed += rehashed
attempts := int(r.rings[policy].ReplicaCount()) - 1
for node := nodes.Nex... | {
hashes[suff.(string)] = ""
} | conditional_block |
fleet.go | return err
}
if err := launchFleetUnitN(
i,
UNIT_NAME_SIDEKICK,
sidekickFleetUnitJson,
); err != nil {
return err
}
}
if err := c.WaitForFleetLaunch(); err != nil {
log.Printf("Error waiting for couchbase cluster launch: %v", err)
return err
}
return nil
}
// Call Fleet API and tell... | (allUnits bool) error {
ttlSeconds := uint64(300)
_, err := c.etcdClient.Set(KEY_REMOVE_REBALANCE_DISABLED, "true", ttlSeconds)
if err != nil {
return err
}
// call ManipulateUnits with a function that will stop them
unitDestroyer := func(unit *schema.Unit) error {
// stop the unit by updating desiredState... | DestroyUnits | identifier_name |
fleet.go | return err
}
if err := launchFleetUnitN(
i,
UNIT_NAME_SIDEKICK,
sidekickFleetUnitJson,
); err != nil {
return err
}
}
if err := c.WaitForFleetLaunch(); err != nil {
log.Printf("Error waiting for couchbase cluster launch: %v", err)
return err
}
return nil
}
// Call Fleet API and tell... | }
func (c CouchbaseFleet) GenerateUnits(outputDir string) error {
// generate node unit
nodeFleetUnit, err := c.generateNodeFleetUnitFile()
if err != nil {
return err
}
filename := fmt.Sprintf("%v@.service", UNIT_NAME_NODE)
path := filepath.Join(outputDir, filename)
if err := ioutil.WriteFile(path, []byte... | {
stringContainsAny := func(s string, filters []string) bool {
for _, filter := range filters {
if strings.Contains(s, filter) {
return true
}
}
return false
}
for _, unit := range units {
if stringContainsAny(unit.Name, filters) {
filteredUnits = append(filteredUnits, unit)
}
}
return f... | identifier_body |
fleet.go | return err
}
if err := launchFleetUnitN(
i,
UNIT_NAME_SIDEKICK,
sidekickFleetUnitJson,
); err != nil {
return err
}
}
if err := c.WaitForFleetLaunch(); err != nil {
log.Printf("Error waiting for couchbase cluster launch: %v", err)
return err
}
return nil
}
// Call Fleet API and tell i... |
// dirty hack to solve problem: the cluster might have
// 2 nodes which just finished rebalancing, and a third node
// that joins and triggers another rebalance. thus, it will briefly
// go into "no rebalances happening" state, followed by a rebalance.
// if we see the "no rebalances happening state", we'll be ... | {
return err
} | conditional_block |
fleet.go | return err
}
if err := launchFleetUnitN(
i,
UNIT_NAME_SIDEKICK,
sidekickFleetUnitJson,
); err != nil {
return err
}
}
if err := c.WaitForFleetLaunch(); err != nil {
log.Printf("Error waiting for couchbase cluster launch: %v", err)
return err
}
return nil
}
// Call Fleet API and tell... | // generate sidekick unit
sidekickFleetUnit, err := c.generateSidekickFleetUnitFile("%i")
if err != nil {
return err
}
filename = fmt.Sprintf("%v@.service", UNIT_NAME_SIDEKICK)
path = filepath.Join(outputDir, filename)
if err := ioutil.WriteFile(path, []byte(sidekickFleetUnit), 0644); err != nil {
return e... | random_line_split | |
aplicacao.py | :
# python -m serial.tools.list_ports
serialName = "/dev/ttyACM0" # Ubuntu (variacao de)
#serialName = "/dev/tty.usbmodem1411" # Mac (variacao de)
#serialName = "COM11" # Windows(variacao de)
class Client():
def __init__(self, serialName, debug=False):
self.com = enlace(s... |
while True:
# Faz a recepção dos dados
print("\n[LOG] Recebendo dados...")
keywordRecognized = False
receiveBuffer = bytearray()
# Espera até receber uma keyword.
while not keywordRecognized:
rxBuffer, nRx = com.getData(1)
re... | com.enable()
# LOG
print("[LOG] Comunicação inicializada.")
print("[LOG] Porta: {}".format(com.fisica.name)) | random_line_split |
aplicacao.py | # python -m serial.tools.list_ports
serialName = "/dev/ttyACM0" # Ubuntu (variacao de)
#serialName = "/dev/tty.usbmodem1411" # Mac (variacao de)
#serialName = "COM11" # Windows(variacao de)
class Cli |
def __init__(self, serialName, debug=False):
self.com = enlace(serialName)
self.com.enable()
self.debug = debug
self.fileName = None
self.results = []
if debug:
print("[LOG] Comunicação inicializada.")
print("[LOG] Porta: {}".format(self.com.... | ent(): | identifier_name |
aplicacao.py | # python -m serial.tools.list_ports
serialName = "/dev/ttyACM0" # Ubuntu (variacao de)
#serialName = "/dev/tty.usbmodem1411" # Mac (variacao de)
#serialName = "COM11" # Windows(variacao de)
class Client():
def __init__(self, serialName, debug=False):
self.com = enlace(seri... |
else:
print("\n[LOG] Arquivo fornecido como argumento.")
filePath = args.file
with open(filePath, "rb") as image:
print("[LOG] Arquivo encontrado. Lendo e transformando em bytearray.")
imageFile = image.read()
imageBy... | ame) # Repare que o metodo construtor recebe um string (nome)
# Ativa comunicacão
com.enable()
# LOG
print("[LOG] Comunicação inicializada.")
print("[LOG] Porta: {}".format(com.fisica.name))
shouldClose = False
while not shouldClose:
# Verifica se o arquivo a ser transferido foi pa... | identifier_body |
aplicacao.py | :
# python -m serial.tools.list_ports
serialName = "/dev/ttyACM0" # Ubuntu (variacao de)
#serialName = "/dev/tty.usbmodem1411" # Mac (variacao de)
#serialName = "COM11" # Windows(variacao de)
class Client():
def __init__(self, serialName, debug=False):
self.com = enlace(s... | ualiza dados da transmissão.
txSize = com.tx.getStatus()
print("[LOG] Transmitido...............{} bytes.".format(int(txSize)))
# Esperando pela resposta. Sabemos que ela deve ser o tamanho da arquivo.
print("[LOG] Esperando pela resposta do servidor com o tamanho do arquivo.")
... | # At | conditional_block |
lib.rs | 'c>(&'b mut self, slab_page: &'c mut ObjectPage<'a>) {
unsafe {
match slab_page.prev.resolve_mut() {
None => {
self.head = slab_page.next.resolve_mut();
}
Some(prev) => {
prev.next = match slab_page.next.resolve... | {
unsafe {
for (base_idx, b) in self.bitfield.iter().enumerate() {
let bitval = *b;
if bitval == u64::max_value() {
continue;
} else {
let negated = !bitval;
let first_free = negated.trailing_... | identifier_body | |
lib.rs | }
}
/// Return maximum size an object of size `current_size` can use.
///
/// Used to optimize `realloc`.
fn | (current_size: usize) -> Option<usize> {
match current_size {
0...8 => Some(8),
9...16 => Some(16),
17...32 => Some(32),
33...64 => Some(64),
65...128 => Some(128),
129...256 => Some(256),
257...512 => Some(512),
513... | get_max_size | identifier_name |
lib.rs | Allocator in slabs at `idx` with a ObjectPage.
///
/// # TODO
/// * Panics in case we're OOM (should probably return error).
fn refill_slab_allocator<'b>(&'b mut self, idx: usize) {
match self.pager.lock().allocate_page() {
Some(new_head) => self.slabs[idx].insert_slab(new_head),
... | {
continue;
} | conditional_block | |
lib.rs | SCAllocator::new(32, pager),
SCAllocator::new(64, pager),
SCAllocator::new(128, pager),
SCAllocator::new(256, pager),
SCAllocator::new(512, pager),
SCAllocator::new(1024, pager),
SCAllocator::new(2048, pager)... | ZoneAllocator {
pager: pager,
slabs: [
SCAllocator::new(8, pager),
SCAllocator::new(16, pager), | random_line_split | |
ip6.py | 6s16sxBH', self.src, self.dst, self.nxt, len(p))
s = dpkt.in_cksum_add(0, s)
s = dpkt.in_cksum_add(s, p)
try:
self.data.sum = dpkt.in_cksum_done(s)
except AttributeError:
pass
return self.pack_hdr() + self.headers_str() + bytes(self... | self.length = (self.len + 1) * 8
options = []
index = 0
while index < self.length - 2:
opt_type = compat_ord(self.data[index])
# PAD1 option
if opt_type == 0:
index += 1
continue
opt_length = compat_ord(s... | ('len', 'B', 0) # option data length in 8 octect units (ignoring first 8 octets) so, len 0 == 64bit header
)
def unpack(self, buf):
dpkt.Packet.unpack(self, buf) | random_line_split |
ip6.py |
next_ext_hdr = self.nxt
while next_ext_hdr in ext_hdrs:
ext = ext_hdrs_cls[next_ext_hdr](buf)
self.extension_hdrs[next_ext_hdr] = ext
self.all_extension_headers.append(ext)
buf = buf[ext.length:]
next_ext_hdr = getattr(ext, 'nxt', None)
... | buf = self.data | conditional_block | |
ip6.py | b''
@property
def frag_off(self):
return self.frag_off_resv_m >> 3
@frag_off.setter
def frag_off(self, v):
self.frag_off_resv_m = (self.frag_off_resv_m & ~0xfff8) | (v << 3)
@property
def m_flag(self):
return self.frag_off_resv_m & 1
@m_flag.setter
def m_flag... | s = (b'\x00\x00\x01\x00\x00\x00\x00\x44\xe2\x4f\x9e\x68\xf3\xcd\xb1\x5f\x61\x65\x42\x8b\x78\x0b'
b'\x4a\xfd\x13\xf0\x15\x98\xf5\x55\x16\xa8\x12\xb3\xb8\x4d\xbc\x16\xb2\x14\xbe\x3d\xf9\x96'
b'\xd4\xa0\x39\x1f\x85\x74\x25\x81\x83\xa6\x0d\x99\xb6\xba\xa3\xcc\xb6\xe0\x9a\x78\xee\xf2'
b'\xaf\x9a')... | identifier_body | |
ip6.py | (self):
return (self._v_fc_flow >> 20) & 0xff
@fc.setter
def fc(self, v):
self._v_fc_flow = (self._v_fc_flow & ~0xff00000) | (v << 20)
@property
def flow(self):
return self._v_fc_flow & 0xfffff
@flow.setter
def flow(self, v):
self._v_fc_flow = (self._v_fc_flow ... | fc | identifier_name | |
schema.go | t *TableSchema) GetColumnIfNonNilDefault() []bool {
nonNilDefaultByColumn := make([]bool, len(t.Schema.Columns))
for columnID, column := range t.Schema.Columns {
nonNilDefaultByColumn[columnID] = column.DefaultValue != nil
}
return nonNilDefaultByColumn
}
// GetArchivingSortColumns makes a copy of the Schema.Arc... | return
}
| random_line_split | |
schema.go | the specified column with the
// specified initial cases, and attaches it to TableSchema object.
// Caller should acquire the schema lock before calling this function.
func (t *TableSchema) createEnumDict(columnName string, enumCases []string) {
columnID := t.ColumnIDs[columnName]
dataType := t.ValueTypeByColumn[col... | {
enumCases = append(enumCases, *column.DefaultValue)
// default value is already appended, start watching from 1
startEnumID = 1
} | conditional_block | |
schema.go | (table *metaCom.Table) *TableSchema {
tableSchema := &TableSchema{
Schema: *table,
ColumnIDs: make(map[string]int),
EnumDicts: make(map[string]EnumDict),
ValueTypeByColumn: make([]memCom.DataType, len(table.Columns)),
PrimaryKeyColumnTypes: make([]memCom.DataType, l... | NewTableSchema | identifier_name | |
schema.go | )),
DefaultValues: make([]*memCom.DataValue, len(table.Columns)),
}
for id, column := range table.Columns {
if !column.Deleted {
tableSchema.ColumnIDs[column.Name] = id
}
tableSchema.ValueTypeByColumn[id] = memCom.DataTypeForColumn(column)
}
for i, columnID := range table.PrimaryKeyColumns {
... |
// GetArchivingSortColumns makes a copy of the Schema.ArchivingSortColumns so
// callers don't have to hold a read lock to access it.
func (t *TableSchema) GetArchivingSortColumns() []int {
t.RLock()
defer t.RUnlock()
return t.Schema.ArchivingSortColumns
}
// FetchSchema fetches schema from metaStore and updates ... | {
nonNilDefaultByColumn := make([]bool, len(t.Schema.Columns))
for columnID, column := range t.Schema.Columns {
nonNilDefaultByColumn[columnID] = column.DefaultValue != nil
}
return nonNilDefaultByColumn
} | identifier_body |
util.py | =CMAP_DEFAULT):
"""Converts a depth map to an RGB image."""
# Convert to disparity.
disp = 1.0 / (depth + 1e-6)
if normalizer is not None:
disp /= normalizer
else:
disp /= (np.percentile(disp, pc) + 1e-6)
disp = np.clip(disp, 0, 1)
disp = gray2rgb(disp, cmap=cmap)
keep_h... | """Pack depth predictions as a single .npy file"""
test_images = read_text_lines(test_file)
save_name = 'pred_depth.npy'
output_file = os.path.join(pred_dir, save_name)
img_height = 128
img_width = 416
all_pred = np.zeros((len(test_images), img_height, img_width))
for i, img_path in enum... | identifier_body | |
util.py | s %s: %s', v.op.name, shape,
format_number(shape.num_elements()))
total += shape.num_elements()
if also_print:
logging.info('Total: %s', format_number(total))
return total
def get_vars_to_save_and_restore(ckpt=None):
"""Returns list of variables that should be save... | read_calib_file | identifier_name | |
util.py | (im, cv2.COLOR_RGB2BGR)
_, im_data = cv2.imencode('.%s' % file_extension, im)
f.write(im_data.tostring())
def normalize_depth_for_display(depth, pc=95, crop_percent=0, normalizer=None,
cmap=CMAP_DEFAULT):
"""Converts a depth map to an RGB image."""
# Convert to ... |
else:
return 'Empty list.'
elif isinstance(obj, tuple):
if obj:
return 'Tuple of %d... %s' % (len(obj), info(obj[0]))
else:
return 'Empty tuple.'
else:
if is_a_numpy_array(obj):
return 'Array with shape: %s, dtype: %s' % (obj.shape... | return 'List of %d... %s' % (len(obj), info(obj[0])) | conditional_block |
util.py | sequence."""
half_offset = int((seq_length - 1) / 2)
return seq_length - 1 - half_offset
def info(obj):
"""Return info on shape and dtype of a numpy array or TensorFlow tensor."""
if obj is None:
return 'None.'
elif isinstance(obj, list):
if obj:
return 'List of %d... ... | def read_file_data(files, data_root): | random_line_split | |
gogo_fast_api.pb.go |
func (m *Http) GetFullyDecodeReservedExpansion() bool {
if m != nil {
return m.FullyDecodeReservedExpansion
}
return false
}
func (m *Http) GetAnyData() *types.Any {
if m != nil {
return m.AnyData
}
return nil
}
// HttpRule .
type HttpRule struct {
Selector string `protobuf:"bytes,1,opt,name=selector,pro... | {
if m != nil {
return m.Rules
}
return nil
} | identifier_body | |
gogo_fast_api.pb.go |
return nil
}
func (m *Http) GetFullyDecodeReservedExpansion() bool {
if m != nil {
return m.FullyDecodeReservedExpansion
}
return false
}
func (m *Http) GetAnyData() *types.Any {
if m != nil {
return m.AnyData
}
return nil
}
// HttpRule .
type HttpRule struct {
Selector string `protobuf:"bytes,1,opt,nam... | {
return m.Rules
} | conditional_block | |
gogo_fast_api.pb.go | _bindings,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HttpRule) Reset() { *m = HttpRule{} }
func (m *HttpRule) String() string { return proto.CompactTextString(m) }
func (*Http... | func (m *HttpRule) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HttpRule.Marshal(b, m, deterministic)
}
func (m *HttpRule) XXX_Merge(src proto.Message) {
xxx_messageInfo_HttpRule.Merge(m, src)
}
func (m *HttpRule) XXX_Size() int {
return xxx_messageInfo_HttpRule.Size(m)
}
func (... | return xxx_messageInfo_HttpRule.Unmarshal(m, b)
} | random_line_split |
gogo_fast_api.pb.go | ,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HttpRule) Reset() { *m = HttpRule{} }
func (m *HttpRule) String() string { return proto.CompactTextString(m) }
func (*HttpRule) Pro... | () string {
if m != nil {
return m.Selector
}
return ""
}
func (m *HttpRule) GetGet() string {
if x, ok := m.GetPattern().(*HttpRule_Get); ok {
return x.Get
}
return ""
}
func (m *HttpRule) GetPut() string {
if x, ok := m.GetPattern().(*HttpRule_Put); ok {
return x.Put
}
return ""
}
func (m *HttpRule)... | GetSelector | identifier_name |
app.js | if(type == void 0){
this.listeners = {}
return this
}
if(handler == void 0){
delete this.listeners[type]
return this
}
let handlers = this.listeners[type] || [];
let id = handlers.indexOf(handler);
if(id != -1){
... | (let i = 0; i < rows; i++) {
html += '<tr>';
for (let j = 0; j < cols; j++) {
html += '<td class="map-box" data-type="empty">';
}
html += '</tr>';
}
this.rows = rows;
this.cols = cols;
this.$el.innerHTML = html;
this... | for | identifier_name |
app.js | if(type == void 0){
this.listeners = {}
return this
}
if(handler == void 0){
delete this.listeners[type]
return this
}
let handlers = this.listeners[type] || [];
let id = handlers.indexOf(handler);
if(id != -1){
... |
this.$el.style.top = y * 20 + 'px';
}
getPos() {
return {x: this.x, y: this.y};
}
}
/**
* 玩家类
*/
class Player extends Character{
constructor(selector) {
super(selector)
}
/**
* 异步移动,实现动画效果
* @param pos
*/
goto(pos) {
this.x = pos.x;
t... | this.$el.style.left = x * 20 + 'px'; | conditional_block |
app.js | this.$el.getElementsByTagName('td');
}
clear() {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
this.type([i, j], 'empty');
}
}
}
type([x,y], type) {
if (type == void 0) {
return this.$boxes[y * t... | [next])
.catch(err =>{
console.error(err)
})
}
let target = this.target.getPos()
if(dst.x == target.x && dst.y == target.y) {
this.run_async(function(){
this.fire('gameover'); // 游戏结束加载下一关卡
});
}
... | identifier_body | |
app.js | if(type == void 0){
this.listeners = {}
return this
}
if(handler == void 0){
delete this.listeners[type]
return this
}
let handlers = this.listeners[type] || [];
let id = handlers.indexOf(handler);
if(id != -1){
... | throw new Error('map is full');
}
Utils.shuffle(positions);
let player = positions[0];
let target = positions[1];
this.player.setPos(player);
this.target.setPos(target);
}
setEnemy(){
}
/**
* 随机的修建障碍物 //todo 建筑迷宫算法
*/
randBuild()... | }
}
let len = positions.length;
if (len < 2) { | random_line_split |
parse_tweet_data.py | efficient import of other processes.
Inputs: *.csv file
Outputs: *.pkl file in the input directory
'''
# construct absolute path
filepath = os.path.join(path, infile)
# import *.csv file to data frame
df = pd.read_csv(filepath)
outfile = path_split[1] + '_' + path_split[3] + '_' ... |
df['stripped_tweet'] = edit_tweets
df['tweet_length'] = df['tweet_text'].str.len()
df['include_topic_model'] = include
df['stripped_tweet_length'] = df['include_topic_model'].str.len()
sub_df = df.loc[df['include_topic_model'] == '1']
outfile = path_split[1] + '_' + path_split[3] + '_sorted_... | include.append('0') | conditional_block |
parse_tweet_data.py | efficient import of other processes.
Inputs: *.csv file
Outputs: *.pkl file in the input directory
'''
# construct absolute path
filepath = os.path.join(path, infile)
# import *.csv file to data frame
df = pd.read_csv(filepath)
outfile = path_split[1] + '_' + path_split[3] + '_' ... | (df, num=30):
'''Takes an input data frame and creates inventories for that data frame, sorted by date. First automatically calls
the sort function to sort the data frame by the default (date).
Inputs: Pandas data frame imported from *.csv or *.pkl file
Number of inventories to split into. ... | split_df | identifier_name |
parse_tweet_data.py | efficient import of other processes.
Inputs: *.csv file
Outputs: *.pkl file in the input directory
'''
# construct absolute path
filepath = os.path.join(path, infile)
# import *.csv file to data frame
df = pd.read_csv(filepath)
outfile = path_split[1] + '_' + path_split[3] + '_' ... | outfile = path_split[1] + '_' + path_split[3] + '_sorted_strip_' + lang + '_' + today + '.pkl'
# save new data frame under *.pkl file
ext_path = os.path.join(path, '1_DataFrames')
sub_df.to_pickle(os.path.join(ext_path, outfile))
return sub_df
def extract_content(df, label='All_Languages'):
'... | df['stripped_tweet_length'] = df['include_topic_model'].str.len()
sub_df = df.loc[df['include_topic_model'] == '1']
| random_line_split |
parse_tweet_data.py | Pandas data frame imported from *.csv or *.pkl file
Field in data frame to be sorted (OPTIONAL: tweet_time, aka sort by date, is the default)
Outputs: *.pkl file in the input directory with "sorted" label sorted, containing additional column "unique_id_ida"
with 7-digit ID numbers begin... | '''Takes an input data frame and generates a histogram of number of tweets binned by month.
Inputs: Pandas data frame imported from *.csv or *.pkl file
Input parameter called "increment", which determined by what time interval the tweets are organized
Outputs: Histogram
'''
date_bounds = p... | identifier_body | |
09_XGBC_img.py | (data_dir+'\\std0_std45_sh0-arr_sh45-arr_bow-bool_train.npy')
################################################
# ADD COLUMN NAMES AND CONVERT TO PANDAS DF
################################################
c1=['std0','std45']
c2=['sh0_{0}'.format(str(i)) for i in range(64)]
c3=['sh45_{0}'.format(str(i)) for i in range... | y_train=train['bowties']
X_train=train.drop(columns='bowties')
y_test=test['bowties']
X_test=test.drop(columns='bowties')
y_val=train_val['bowties']
X_val=train_val.drop(columns='bowties')
pipeline=Pipeline([('Imputer',SimpleImputer(strategy='mean'))])
X_train_... | X=dp.numpy_to_pd(X_raw,column_names)
# =============================================================================
# SPLIT DATA INTO TEST AND TRAIN BOTH BALANCED
# WITH RESPECT TO (NON)BOWTIES
# =============================================================================
split=S... | conditional_block |
09_XGBC_img.py | (data_dir+'\\std0_std45_sh0-arr_sh45-arr_bow-bool_train.npy')
################################################
# ADD COLUMN NAMES AND CONVERT TO PANDAS DF
################################################
c1=['std0','std45']
c2=['sh0_{0}'.format(str(i)) for i in range(64)]
c3=['sh45_{0}'.format(str(i)) for i in range... |
seeking=True
if seeking:
X=dp.numpy_to_pd(X_raw,column_names)
# =============================================================================
# SPLIT DATA INTO TEST AND TRAIN BOTH BALANCED
# WITH RESPECT TO (NON)BOWTIES
# ==============================================================... | column_names=c1+c2+c3+c4
| random_line_split |
data_tensorboard.py | used in code after central_crop which squares the image
ration will be 1. So we take then random value between segmet form [1-dleta, 1+ dleta]
"""
def random_ratio_resize(img, prob=0.3, delta=0.1):
if np.random.rand() >= prob: # bigger do nothing
return img
ratio = img.shape[0] / img.shape[1] # in o... | self.on_epoch_end() # schuffle traing set
self.n = 0 # set to zero | conditional_block | |
data_tensorboard.py | (img, percent=0.15):
offset = int(img.shape[0] * percent) #cut the top portion of image
return img[offset:] # return image
"""
central_crop takes as an input img which is an array of shape (x, y, 3)
"""
def central_crop(img):
size = min(img.shape[0], img.shape[1]) # min of x and y
offset_h = int((img.s... | crop_top | identifier_name | |
data_tensorboard.py | As this function is used in code after central_crop which squares the image
ration will be 1. So we take then random value between segmet form [1-dleta, 1+ dleta]
"""
def random_ratio_resize(img, prob=0.3, delta=0.1):
if np.random.rand() >= prob: # bigger do nothing
return img
ratio = img.shape[0] /... |
"""
_process_csv_file take as an input a file in our case these are train_split.txt and test_split.txt (names may differ)
"""
def _process_csv_file(file):
with open(file, 'r') as fr: # open file
files = fr.readlines() # read lines
return files
class BalanceCovidDataset(keras.utils.Sequence):
'G... | img = random_ratio_resize(img) #defina above
img = _augmentation_transform.random_transform(img) # Applies a random transformation to an image.
return img | identifier_body |
data_tensorboard.py | As this function is used in code after central_crop which squares the image
ration will be 1. So we take then random value between segmet form [1-dleta, 1+ dleta]
"""
def random_ratio_resize(img, prob=0.3, delta=0.1):
if np.random.rand() >= prob: # bigger do nothing
return img
ratio = img.shape[0] /... | },
shuffle=True,
augmentation=apply_augmentation,
covid_percent=0.3,
class_weights=[1., 1., 6.], # default weight of classes. The less numbered class gets is more worthy than the others
# in this case COVID_19
... | mapping={
'normal': 0,
'pneumonia': 1,
'COVID-19': 2 | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.