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 |
|---|---|---|---|---|
viewsets.py | Optional
import toml
from asciinema import asciicast
from asciinema.commands.cat import CatCommand
from django.conf import settings
from django.db.models import F, Q
from django.http import StreamingHttpResponse, Http404
from django.utils.functional import cached_property
from django.views.static import serve
from dj... | filterset_class = ActionFilter
ordering_fields = ('parent', 'parent', 'created_at', 'updated_at')
detail_serializer_class = DetailActionSerializer
pagination_class = StandardResultsSetPagination
def get_queryset(self):
queryset = super(ActionViewSet, self).get_queryset()
if self.act... | queryset = Action.objects.order_by('-pk')
serializer_class = ActionSerializer
filter_backends = (filters.OrderingFilter, filters.SearchFilter, DjangoFilterBackend)
search_fields = ('name',) | random_line_split |
viewsets.py | Optional
import toml
from asciinema import asciicast
from asciinema.commands.cat import CatCommand
from django.conf import settings
from django.db.models import F, Q
from django.http import StreamingHttpResponse, Http404
from django.utils.functional import cached_property
from django.views.static import serve
from dj... | @action(methods=['get'], detail=True)
def terminal_output(self, request, pk):
instance: Action = self.get_object()
file: str = instance.get_terminal_path()
if not os.path.lexists(file) or not os.path.getsize(file):
raise Http404
return StreamingHttpResponse(asciinema_... | stance: Action = self.get_object()
return serve_file(request, instance.get_terminal_path())
| identifier_body |
lib.rs | nalgebra_v0_32` | no | version 0.32 |
//! | `nalgebra_v0_32-serde` | no | version 0.32 + serde support |
//! | `nalgebra_v0_31` | no | version 0.31 |
//! | `nalgebra_v0_31-serde` | no | version 0.31 + serde support ... | fn add(&self, other: &T) -> U;
}
/// Subtract a `T` from `self` | random_line_split | |
main.rs | _offset = {} = ({} - {}) * {}/2/{} + {}/2/2 - {}/2", h_offset, sprite_dir, player.a, fb.w, player.fov, fb.w, sprite_screen_size);
for i in 0..sprite_screen_size {
if h_offset+i<0 || h_offset+i >= screen_size { continue; }
if depth_buffer[(h_offset+i) as usize] < sprite.player_dist { continue; }
... | .arg("out")
.output()
.expect("failed to create directory"); | random_line_split | |
main.rs | ;
let texid = map.get(i, j).expect("i, j not in map range");
fb.draw_rectangle(
rect_x,
rect_y,
rect_w,
rect_h,
tex_walls.get(0, 0, texid).expect("no texture at texid"),
)?;
}
}
let mut d... | {
let r = 2;
let g = 4;
let b = 8;
let a = 255;
let color = utils::pack_color_rgba(r, g, b, a);
let (rc, gc, bc, ac) = utils::unpack_color(color);
assert_eq!(vec![r, g, b, a], vec![rc, gc, bc, ac]);
} | identifier_body | |
main.rs | ::PI { sprite_dir += 2.0 * f32::consts::PI; }
//distance from player to sprite
// let sprite_dist =
// f32::sqrt(f32::powi(player.x - sprite.x, 2) + f32::powi(player.y - sprite.y, 2));
// let sprite_screen_size = f32::min(2000.0, fb.h as f32 / sprite_dist) as i32;
let sprite_screen_size = f32::... |
let rect_x = i as usize * rect_w;
let rect_y = j as usize * rect_h;
let texid = map.get(i, j).expect("i, j not in map range");
fb.draw_rectangle(
rect_x,
rect_y,
rect_w,
rect_h,
tex_walls.get... | {
continue; //skip empty spaces
} | conditional_block |
main.rs | : &mut Vec<Sprite>, // will change order of sprites according to distance from player
tex_walls: &Texture,
tex_monsters: &Texture,
) -> Result<(), FrameError> {
// fb.clear(utils::pack_color_rgb(249, 209, 152));
fb.clear(utils::pack_color_bgra(152, 209, 249, 255));
let rect_w = fb.w / (map.w as usiz... | unpacks_ints | identifier_name | |
metrics.pb.go |
const (
SimpleMetric_COUNTER SimpleMetric_Type = 0
SimpleMetric_GAUGE SimpleMetric_Type = 1
)
var SimpleMetric_Type_name = map[int32]string{
0: "COUNTER",
1: "GAUGE",
}
var SimpleMetric_Type_value = map[string]int32{
"COUNTER": 0,
"GAUGE": 1,
}
func (x SimpleMetric_Type) String() string {
return proto.En... | random_line_split | ||
metrics.pb.go | () SimpleMetric_Type {
if m != nil {
return m.Type
}
return SimpleMetric_COUNTER
}
func (m *SimpleMetric) GetValue() uint64 {
if m != nil {
return m.Value
}
return 0
}
func (m *SimpleMetric) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func init() {
proto.RegisterEnum("envoy.admin.v3.... | (dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SimpleMetric) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.XXX_unrecognized != nil {
i -= len(m.XXX_unrecognized)
copy(dAtA[i:], m.XXX_unrecognized)
}
if len(m.... | MarshalTo | identifier_name |
metrics.pb.go | x49, 0xcd, 0x2b, 0xcb,
0xaf, 0xd4, 0x4f, 0x4c, 0xc9, 0xcd, 0xcc, 0xd3, 0x2f, 0x33, 0xd6, 0xcf, 0x4d, 0x2d, 0x29, 0xca,
0x4c, 0x2e, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x03, 0xcb, 0xea, 0x81, 0x65, 0xf5,
0xca, 0x8c, 0xa5, 0x64, 0x4b, 0x53, 0x0a, 0x12, 0xf5, 0x13, 0xf3, 0xf2, 0xf2, 0x4b, 0x12, 0x4b,
0x32,... | {
n += 1 + l + sovMetrics(uint64(l))
} | conditional_block | |
metrics.pb.go | 6, 0x22, 0x8a, 0xed, 0x4e, 0x4e, 0x27,
0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0xae, 0x86, 0x13, 0x17,
0xd9, 0x98, 0x04, 0x18, 0xb9, 0x64, 0x32, 0xf3, 0x21, 0x6e, 0x2e, 0x28, 0xca, 0xaf, 0xa8, 0x44,
0x73, 0xbe, 0x13, 0x0f, 0x44, 0x6f, 0x71, 0x00, 0xc8, 0xf3, 0x01, 0x8c, 0x49, 0x6c, 0x... | {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowMetrics
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 ... | identifier_body | |
OceanFront_ViewshedNEW2.py |
if not os.path.exists(Final_Floor_Viewsheds) : os.makedirs(Final_Floor_Viewsheds)
if not os.path.exists(SummaryTables) : os.makedirs(SummaryTables)
if not os.path.exists(ElevAvgTables): os.makedirs(ElevAvgTables)
if not os.path.exists(ArcLengths): os.makedirs(ArcLengths)
def outName(input,post="_Output"):
"""Retu... | os.makedirs(IntermediateFiles) | conditional_block | |
OceanFront_ViewshedNEW2.py | ")
#Open error log file
infile = open(outputWorkspace+"\\Error_Log_"+Year+".txt","w")
#Perform field check for viewshed parameters within the observation point attribute table.
#Script will add field to the attribute table if the field does not already exist.
#Needed fields are SPOT - used to define the surface eleva... | ##
#Delete individual summary tables
arcpy.SetProgressorLabel("Deleting Summary Tables... ")
try: | random_line_split | |
OceanFront_ViewshedNEW2.py | maryTables) : os.makedirs(SummaryTables)
if not os.path.exists(ElevAvgTables): os.makedirs(ElevAvgTables)
if not os.path.exists(ArcLengths): os.makedirs(ArcLengths)
def | (input,post="_Output"):
"""Returns output name."""
outName=os.path.basename(input).split(".")[0]+post
return outName
def DegViewshed (FLOOR, HEIGHT):
"""Calculates a parcels viewshed, in degrees"""
#Select Record
arcpy.SelectLayerByAttribute_management(PointsFL,"NEW_SELECTION",SQL)
#S... | outName | identifier_name |
OceanFront_ViewshedNEW2.py | maryTables) : os.makedirs(SummaryTables)
if not os.path.exists(ElevAvgTables): os.makedirs(ElevAvgTables)
if not os.path.exists(ArcLengths): os.makedirs(ArcLengths)
def outName(input,post="_Output"):
|
def DegViewshed (FLOOR, HEIGHT):
"""Calculates a parcels viewshed, in degrees"""
#Select Record
arcpy.SelectLayerByAttribute_management(PointsFL,"NEW_SELECTION",SQL)
#Set Observer Height (OffSETA)
arcpy.CalculateField_management(PointsFL,"OFFSETA",HEIGHT,"PYTHON_9.3")
#perform views... | """Returns output name."""
outName=os.path.basename(input).split(".")[0]+post
return outName | identifier_body |
container.rs | )? {
kill(pid, signal)?;
}
}
// For cgroup v1, killing a process in a frozen cgroup does nothing until it's thawed.
// Only thaw the cgroup for SIGKILL.
// Ref: https://github.com/opencontainers/runc/pull/3217
if !is_cgroup2_unified_mode() && self.stat... |
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::test_utils::*; | random_line_split | |
container.rs | , Copy, Clone, PartialEq)]
pub enum ContainerAction {
Create,
Start,
Run,
}
#[derive(Debug)]
pub struct Container {
pub status: Status,
pub state: ContainerState,
pub cgroup: cgroups::Cgroup,
}
// Container represents a container that is created by the container runtime.
impl Container {
p... | (&self) -> Result<()> {
if self.state != ContainerState::Running && self.state != ContainerState::Created {
return Err(anyhow!(
"failed to pause container: current status is: {:?}",
self.state
));
}
freeze(&self.cgroup, FreezerState::Frozen... | pause | identifier_name |
container.rs | , Copy, Clone, PartialEq)]
pub enum ContainerAction {
Create,
Start,
Run,
}
#[derive(Debug)]
pub struct Container {
pub status: Status,
pub state: ContainerState,
pub cgroup: cgroups::Cgroup,
}
// Container represents a container that is created by the container runtime.
impl Container {
p... |
freeze(&self.cgroup, FreezerState::Thawed)?;
Ok(())
}
pub fn destroy(&self) -> Result<()> {
remove_cgroup_dir(&self.cgroup)?;
self.status.remove_dir()
}
}
/// Used to run a process. If init is set, it will create a container and run the process in it.
/// If init is not se... | {
return Err(anyhow!(
"failed to resume container: current status is: {:?}",
self.state
));
} | conditional_block |
InceptionResNet_Image_Captioning.py |
class RNN_Decoder(tf.keras.Model):
# def __init__(self, embedding_dim, units, vocab_size, embedding_matrix):
def __init__(self, embedding_dim, units, vocab_size):
super(RNN_Decoder, self).__init__()
self.units = units
# self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim,embe... | x = self.fc(x)
x = tf.nn.relu(x)
return x | identifier_body | |
InceptionResNet_Image_Captioning.py | finIm/im' + str(a) + ".png"
|
test_image_paths = []
for a in range(40504):
loc = testim_dir + 'im' + str(a) + ".png"
# loc = 'C:\\Users\\BARAN/Desktop/Dersler/EEE/EEE443/phtyon/finIm/im' + str(a) + ".png"
if (os.path.exists(loc)):
test_image_paths.append(loc)
# tot=0
# for a in range(40504):
# ... | loc = trainim_dir + 'im' + str(a) + ".png"
if (os.path.exists(loc)):
train_image_paths2.append(loc) | conditional_block |
InceptionResNet_Image_Captioning.py | tf.keras.applications.resnet_v2.preprocess_input(img)
img = tf.keras.applications.inception_resnet_v2.preprocess_input(img)
return img, image_path
# image_model2 = tf.keras.applications.ResNet50V2(include_top=False,weights='imagenet')
image_model2 = tf.keras.applications.InceptionResNetV2(include_top=Fa... | train_step | identifier_name | |
InceptionResNet_Image_Captioning.py | Im/im' + str(a) + ".png"
loc = trainim_dir + 'im' + str(a) + ".png"
if (os.path.exists(loc)):
train_image_paths2.append(loc)
test_image_paths = []
for a in range(40504):
loc = testim_dir + 'im' + str(a) + ".png"
# loc = 'C:\\Users\\BARAN/Desktop/Dersler/EEE/EEE443/phtyon/finIm/i... | print(i)
batch_features2 = image_features_extract_model2(img)
batch_features2 = tf.reshape(batch_features2,
(batch_features2.shape[0], -1, batch_features2.shape[3]))
for bf, p in zip(batch_features2, path):
path_of_feature = p.numpy().decode("utf-8")
n... | random_line_split | |
utils.go | USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package generator
import (
"bytes"
"fmt"
"log"
"regexp"
"strings"
"text/template"
"github.com/tcncloud/protoc-gen-persist/v5/persist"
descriptor "google.golang.org/protobuf/types/descriptorpb"
"golang.org/x/tools/imports"
)
var r... | () string { return t.tm.GetProtoTypeName() }
type HasLabelAndType interface {
GetLabel() descriptor.FieldDescriptorProto_Label
GetType() descriptor.FieldDescriptorProto_Type
GetTypeName() string
}
// usualy typ is a *descriptor.FieldDescriptorProto, but it also could be a *TmAsField
fun... | GetTypeName | identifier_name |
utils.go | USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package generator
import (
"bytes"
"fmt"
"log"
"regexp"
"strings"
"text/template"
"github.com/tcncloud/protoc-gen-persist/v5/persist"
descriptor "google.golang.org/protobuf/types/descriptorpb"
"golang.org/x/tools/imports"
)
var r... |
// TmAsField (TypeMappingAsField) Implements GetLabel and GetType, returning results from their GetProto equivalents
type TmAsField struct {
tm *persist.TypeMapping_TypeDescriptor
}
func (t TmAsField) GetLabel() descriptor.FieldDescriptorProto_Label { return t.tm.GetProtoLabel() }
func (t TmAsField) GetType() descr... | {
return f.GetGoTypeName(protoName)
} | identifier_body |
utils.go | // * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materia... | random_line_split | ||
utils.go | USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package generator
import (
"bytes"
"fmt"
"log"
"regexp"
"strings"
"text/template"
"github.com/tcncloud/protoc-gen-persist/v5/persist"
descriptor "google.golang.org/protobuf/types/descriptorpb"
"golang.org/x/tools/imports"
)
var r... | else {
return "[]byte", nil
}
case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
if typ.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED {
return "[]float64", nil
} else {
return "float64", nil
}
case descriptor.FieldDescriptorProto_TYPE_FIXED32:
if typ.GetLabel() == descriptor.FieldDes... | {
return "[][]byte", nil
} | conditional_block |
feature_tracking.py | x_curr = i
y_curr = j
else:
print("Please enter valid similarity poisson_mode")
return x_curr, y_curr
def find_points(prev_frame, curr_frame, prev_frame_points, detector, similarity_mode):
global curr_points, display_keypoints
curr_points = []
display_keypoints = ... | (frame, points, color, radius):
for (x, y) in points:
draw_point(frame, x, y, color, radius)
current_frame_gui = None
clicked_points = []
display_keypoints = []
class Modes:
MOVIE = 1
IMAGE = 2
OTHER = 3
# POINTS SHOULD BE ADDED IN THE FOLLOWING ORDER:
#
# TOP LEFT, TOP RIGHT, BOTTOM LEFT,... | draw_points | identifier_name |
feature_tracking.py | x_curr = i
y_curr = j
else:
print("Please enter valid similarity poisson_mode")
return x_curr, y_curr
def find_points(prev_frame, curr_frame, prev_frame_points, detector, similarity_mode):
| prev_frame_descriptor = custom_descriptor(prev_frame_intensities)
print("SHAPE",prev_frame_descriptor.shape)
# Define bounds of search area
top, bottom, left, right = get_bounds(x_prev, y_prev, descriptor_offset, search_offset)
# Adjust the bounds
# top, bottom, left, r... | global curr_points, display_keypoints
curr_points = []
display_keypoints = []
for idx, (x_prev, y_prev) in enumerate(prev_frame_points):
# Create block of image intensities
# using neighboring pixels around each
# previously identified corner point
#20 works for bed scene
... | identifier_body |
feature_tracking.py | x_curr = i
y_curr = j
else:
print("Please enter valid similarity poisson_mode")
return x_curr, y_curr
def find_points(prev_frame, curr_frame, prev_frame_points, detector, similarity_mode):
global curr_points, display_keypoints
curr_points = []
display_keypoints = ... | cv2.putText(overlay, line, (c_x, c_y + i * dy), fontFace, fontScale, thickness)
# alpha blend overlay with frame
alpha = 0.8
frame = alpha * overlay + (1-alpha) * frame
return frame
def create_warp_comosite(composite_image,curr_frame_points_offset,current_frame):
# Create point corresponde... | c_y += text_vertical_offset
for i, line in enumerate(text.split('\n')): | random_line_split |
feature_tracking.py | )
return harris_frame
def compute_orb(window):
detector = cv2.ORB_create(edgeThreshold=0)
keypoints_ = detector.detect(window, None) # list of keypoint objects, get raw indicies
keypoints = []
for kp in keypoints_:
x, y = kp.pt
keypoints.append([int(x), int(y)])
print("Number ... | composite_cap = cv2.VideoCapture("inputs/composite_videos/space.mp4") | conditional_block | |
upload.py | ext = os.path.splitext(os.path.basename(filename))
is_gz = False
if ext in {'.gz', '.gzip', '.bz', '.bz2', '.bzip'}:
is_gz = True
new_filename, ext = os.path.splitext(new_filename)
final_filename = new_filename + ext
if validate or is_gz:
final_filename = final_filename + '.gz'... | if file_uuid:
uploading_uuids.append(file_uuid)
except Exception as e:
# handle inside the thread to prevent the exception message from leaking out
wrapped_args[-1].value = '{}'.format(e)
raise System... | random_line_split | |
upload.py | = os.path.splitext(os.path.basename(filename))
is_gz = False
if ext in {'.gz', '.gzip', '.bz', '.bz2', '.bzip'}:
is_gz = True
new_filename, ext = os.path.splitext(new_filename)
final_filename = new_filename + ext
if validate or is_gz:
final_filename = final_filename + '.gz'
... |
except Exception as e:
# handle inside the thread to prevent the exception message from leaking out
wrapped_args[-1].value = '{}'.format(e)
raise SystemExit
semaphore.release()
# the thread error message must be th... | uploading_uuids.append(file_uuid) | conditional_block |
upload.py | ext = os.path.splitext(os.path.basename(filename))
is_gz = False
if ext in {'.gz', '.gzip', '.bz', '.bz2', '.bzip'}:
is_gz = True
new_filename, ext = os.path.splitext(new_filename)
final_filename = new_filename + ext
if validate or is_gz:
final_filename = final_filename + '.gz'... | config = TransferConfig(max_concurrency=threads)
try:
client.upload_fileobj(file_obj, upload_params['s3_bucket'], upload_params['file_id'],
ExtraArgs={'ServerSideEncryption': 'AES256'}, Config=config)
except S3UploadFailedError:
raise UploadException("Upload of ... | """
Uploads a file to the One Codex server via an intermediate S3 bucket (and handles files >5Gb)
"""
import boto3
from boto3.s3.transfer import TransferConfig
from boto3.exceptions import S3UploadFailedError
# first check with the one codex server to get upload parameters
try:
uplo... | identifier_body |
upload.py | ext = os.path.splitext(os.path.basename(filename))
is_gz = False
if ext in {'.gz', '.gzip', '.bz', '.bz2', '.bzip'}:
is_gz = True
new_filename, ext = os.path.splitext(new_filename)
final_filename = new_filename + ext
if validate or is_gz:
final_filename = final_filename + '.gz'... | (filename, logger=None, validate=True):
"""
A little helper to wrap a sequencing file (or join and wrap R1/R2 pairs)
and return a merged file_object
"""
if isinstance(filename, tuple):
if not validate:
raise UploadException('Validation is required in order to auto-interleave file... | _wrap_files | identifier_name |
event_queue.rs | queue
///
/// This handle gives you access to methods on an event queue
/// that are safe to do from within a callback.
///
/// They are also available on an `EventQueue` object via `Deref`.
pub struct EventQueueHandle {
state: State,
wlevq: Option<*mut wl_event_queue>,
}
impl EventQueueHandle {
/// Regis... | Some(evtq) => ffi_dispatch!(
WAYLAND_CLIENT_HANDLE,
wl_display_prepare_read_queue,
self.display,
evtq
),
None => ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_prepare_read, self.display),
... | match self.handle.wlevq { | random_line_split |
event_queue.rs | queue
///
/// This handle gives you access to methods on an event queue
/// that are safe to do from within a callback.
///
/// They are also available on an `EventQueue` object via `Deref`.
pub struct EventQueueHandle {
state: State,
wlevq: Option<*mut wl_event_queue>,
}
impl EventQueueHandle {
/// Regis... |
}
/// An event queue managing wayland events
///
/// Each wayland object can receive events from the server. To handle these events
/// you must associate to these objects an implementation: a struct defined in their
/// respective module, in which you provide a set of functions that will handle each event.
///
/// Y... | {
&mut self.state
} | identifier_body |
event_queue.rs | queue
///
/// This handle gives you access to methods on an event queue
/// that are safe to do from within a callback.
///
/// They are also available on an `EventQueue` object via `Deref`.
pub struct EventQueueHandle {
state: State,
wlevq: Option<*mut wl_event_queue>,
}
impl EventQueueHandle {
/// Regis... | (&mut self) -> &mut State {
&mut self.state
}
}
/// An event queue managing wayland events
///
/// Each wayland object can receive events from the server. To handle these events
/// you must associate to these objects an implementation: a struct defined in their
/// respective module, in which you provide ... | state | identifier_name |
horovod_patches.py | 32',
initializer=tf.constant_initializer(0), trainable=False)
#global_step = tf.train.get_or_create_global_step()
loss = tf.get_collection(tf.GraphKeys.LOSSES)
if len(loss) == 0:
raise RuntimeError("No losses found in losses collection")
loss = tf.add_n(loss, na... | is_train = tf.placeholder(tf.bool, ())
input_tensors = tf.cond(is_train, lambda: train_queue.dequeue(),
lambda: evaluator_runner.eval_queue.dequeue())
# tensorfow can't infer the shape for an unsized queue, so set it manually
for input_tensor, pl in zip(input_tensors, placeh... | """ Train while encoding batches on a seperate thread and storing them in a tensorflow Queue, can
be much faster then using the feed_dict approach """
train = data.get_train()
eval_datasets = data.get_eval()
loader = data.get_resource_loader()
print("Training on %d batches" % len(train))
prin... | identifier_body |
horovod_patches.py | 32',
initializer=tf.constant_initializer(0), trainable=False)
#global_step = tf.train.get_or_create_global_step()
loss = tf.get_collection(tf.GraphKeys.LOSSES)
if len(loss) == 0:
raise RuntimeError("No losses found in losses collection")
loss = tf.add_n(loss, na... | tf.get_default_graph().finalize()
if dry_run:
return
on_step = sess.run(global_step)
if save_start:
# summary_writer.add_graph(sess.graph, global_step=on_step)
if hvd.rank() == 0:
trainer.save_train_start(out.dir, data, sess.run(global_step), evaluators, train_para... | print("Initializing parameters...")
sess.run(tf.global_variables_initializer())
sess.run(bcast)
# Make sure no bugs occur that add to the graph in the train loop, that can cause (eventuall) OOMs | random_line_split |
horovod_patches.py | (train_params):
""" Bulid ops we should run during training, including learning, EMA, and summary ops"""
global_step = tf.get_variable('global_step', shape=[], dtype='int32',
initializer=tf.constant_initializer(0), trainable=False)
#global_step = tf.train.get_or_create_glob... | _build_train_ops | identifier_name | |
horovod_patches.py | (list(to_monitor.values())))
summary_tensor = tf.summary.merge(
[tf.summary.scalar(col, monitor_ema.average(v)) for col, v in to_monitor.items()] +
[summary_tensor])
# EMA for the loss and what we monitoring
if train_params.loss_ema is not None:
loss_ema = tf.train.Expon... | print("Save weights with current best weights (%s vs %.5f)" % (
"None" if cur_best is None else ("%.5f" % cur_best), val))
best_weight_saver.save(sess, join(out.best_weight_dir, "best"), global_step=global_step)
... | conditional_block | |
main.rs | Class {
Colony,
Scout,
Fighter
}
struct Ship {
class: ShipClass,
health: u32,
speed: u32,
damage: u32
}
impl Ship {
fn new(class: ShipClass) -> Ship {
match class {
ShipClass::Colony => Ship { class: class, health: 100, speed: 10, damage: 10},
ShipClass... | {
let (x1, y1) = self.first.borrow().center();
let (x2, y2) = self.second.borrow().center();
drawer.draw_line(
Point{x: x1, y: y1},
Point{x: x2, y: y2});
} | identifier_body | |
main.rs | Class {
Farm,
Laboratory,
GoldMine
}
#[derive(Debug, Clone)]
struct Building {
class: BuildingClass,
production: Resources
}
impl Building {
fn new(class: BuildingClass) -> Building {
let production = match class {
BuildingClass::Farm => Resources { food: 5, technolog... | }
self.ships.get_mut(&ship.class).unwrap().push(ship);
}
fn merge(&mut self, fleet: Box<Fleet>) {
for (ship_class, ships) in fleet.ships.into_iter() {
for ship in ships.into_iter() {
self.add(ship);
}
}
}
fn size(&self) -> u32 {
... |
fn add(&mut self, ship: Ship) {
match self.ships.get(&ship.class) {
None => { self.ships.insert(ship.class, Vec::new()); },
Some(_) => () | random_line_split |
main.rs | (self, other:Resources) -> Resources {
Resources {
food: self.food + other.food,
technology: self.technology + other.technology,
gold: self.gold + other.gold
}
}
}
impl Resources {
fn new() -> Resources {
Resources{food: 0, technology: 0, ... | add | identifier_name | |
class_loader_context.go | = android.InstallPathToOnDevicePath(ctx, installPath.(android.InstallPath))
}
// Nested class loader context shouldn't have conditional part (it is allowed only at the top level).
for ver, _ := range nestedClcMap {
if ver != AnySdkVersion {
clcStr, _ := ComputeClassLoaderContext(nestedClcMap)
return fmt.Er... | Context) (string, string, an | identifier_name | |
class_loader_context.go | Clcs := range otherClcMap {
for _, otherClc := range otherClcs {
alreadyHave := false
for _, clc := range clcMap[sdkVer] {
if clc.Name == otherClc.Name {
alreadyHave = true
break
}
}
if !alreadyHave {
clcMap[sdkVer] = append(clcMap[sdkVer], otherClc)
}
}
}
}
// Returns top-lev... | lcs))
for _, clc := range jClcs {
clcs = append(clcs, &ClassLoaderContext{
Name: clc.Name,
Host: constructPath(ctx, clc.Host),
Device: clc.Device,
Subcontexts: fromJsonClassLoaderContextRec(ctx, clc.Subcontexts),
})
}
return clcs
}
// Convert Soong CLC map to JSON representatio | identifier_body | |
class_loader_context.go | same thing, but computed in two different ways.
//
// It is important that build-time and run-time CLCs coincide, otherwise the AOT-compiled code
// created by dexpreopt will be rejected. In order to check the equality of build-time and
// run-time CLCs, the dex2oat compiler records build-time CLC in the *.odex files ... | AndroidHidlBase,
}
var OptionalCompatUsesLibs = append(android.CopyOf(OptionalCompatUsesLibs28), OptionalCompatUsesLibs30...)
var CompatUsesLibs = android.CopyOf(CompatUsesLibs29)
const UnknownInstallLibraryPath = "error"
// AnySdkVersion means that the class loader context is needed regardless of the targetSdkVersi... | AndroidHidlManager, | random_line_split |
class_loader_context.go | is a map from SDK version to CLC. There is a special entry with key
// AnySdkVersion that stores unconditional CLC that is added regardless of the target SDK version.
//
// Conditional CLC is for compatibility libraries which didn't exist prior to a certain SDK version
// (say, N), but classes in them were in the boot... |
fixedClcs := []*ClassLoaderContext{}
for _, clc := range clcs {
if android.InList(clc.Name, usesLibs) {
// skip compatibility libraries that are already included in unconditional context
} else if clc.Name == AndroidTestMock && !android.InList("android.test.runner", usesLibs) {
// android.test.mock i... | conditional_block | |
train_DQN_vs_overlap_rnn_no_perception_new.py | #hidden_state = model_out[1][0]
#cell_state = model_out[1][1]
hidden_state = model_out[1]
#return action, hidden_state, cell_state
return action, hidden_state
def update(self, batch_size, time_step=5):
print('batch_size = {... | ax.imshow(ft_new_overlapArea.reshape(16, 16))
plt.show()
'''
## collision done only stops continuing the sequence, but won't affect reward computing | random_line_split | |
train_DQN_vs_overlap_rnn_no_perception_new.py | goal_pose, start_pose)
next_states[i, j] = torch.tensor(elem[3], dtype=torch.float32)
rw.append(current_reward)
do.append(float(current_done))
#do.append(elem[4])
actions[i] = torch.tensor(ac, dtype=torch.long)
rewards[i] = torch.t... | agent.update(len(agent.memory), 3) | conditional_block | |
train_DQN_vs_overlap_rnn_no_perception_new.py | _heading, location_angle))
if pho_dist >= 0.05:
## alpha angle in goToPose is the difference between location angle and left_pose_heading
a1, b1 = cos(location_angle), sin(location_angle)
a2, b2 = cos(left_pose_heading), sin(left_pose_heading)
alpha_dist = math.sqrt((a1-a2)**2 + (b1-b2)**2)
## beta angle in ... | (self):
for target_param, param in zip(self.critic.parameters(), self.actor.parameters()):
target_param.data.copy_(param.data)
self.critic.eval()
## for collecting (state, action, next_state) tuples
#def select_action(self, state, hidden_state, cell_state, EPS_START=0.9, EPS_END... | update_critic | identifier_name |
train_DQN_vs_overlap_rnn_no_perception_new.py |
def close_to_goal(pose1, pose2, thresh=0.15):
L2_dist = math.sqrt((pose1[0] - pose2[0])**2 + (pose1[1] - pose2[1])**2)
thresh_L2_dist = thresh
theta_change = abs(pose1[2] - pose2[2])/math.pi * 180
return (L2_dist < thresh_L2_dist) and (theta_change <= 30)
def compute_distance_old(left_pose, right_pose, lamb=0.5)... | pos, orn = func_pose2posAndorn(current_pose, mapper_scene2z[scene_name])
env.robot.reset_new_pose(pos, orn)
obs, _, _, _ = env.step(4)
obs_rgb = obs['rgb_filled']
obs_depth = obs['depth']
#obs_normal = obs['normal']
return obs_rgb, obs_depth#, obs_normal | identifier_body | |
firebaseMap.js | ;
ulList.appendChild(li).Trailer;
fahrerOnChange();
};
//chat option buttons fahrer
$(document).ready( function (){
$('#mdb-select input').on('click', function(){
radioChanged += 1;
//alert($('input[name=group1]:checked', '#mdb-select').val());
selectedFahrer = $('input[name=group1]:checke... | unixtime) {
var timestamp = parseInt(data.Zeit);
var u = new Date(unixtime);
return ('0' + u.getUTCDate()).slice(-2) +
'.' + ('0' + u.getUTCMonth() + 11 ).slice(-2)+
'.' + u.getUTCFullYear() +
' ' + ('0' + u.getUTCHours()+13 ).slice(-2) +
':' + ('0' + u.getUTCMinutes()).slice(-2) +
'... | nixTime( | identifier_name |
firebaseMap.js | onto');
var textInput = document.querySelector('#fahrerChat');
var postButton = document.querySelector('#post');
postButton.addEventListener("click", function(snapshot) {
var msgUser = usernameInput.value;
var msgText = textInput.value;
var recieve = '"' + msgText + '"';
var postData = {
usernam... |
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 49.1833848,
lng: 9.17934696
},
zoom: 18,
styles: [{
featureType: 'poi',
stylers: [{
visibility: 'off'
}] ... | identifier_body | |
firebaseMap.js | //fahrer 1
const fahrer1OnOff = document.getElementById('fahrer1OnOff');
var fahrer1 = document.querySelector('fahrer1');
var mafiF1 = document.querySelector('mafiF1');
var trailerF1 = document.querySelector('trailerF1');
var zeitF1 = document.querySelector('zeitF1');
//fahrer 2
const fahrer2OnOff = document.get... | const liList = document.getElementById('listLi');
| random_line_split | |
value.rs | color value (and optionally, its source string).
Color(Color, Option<String>),
/// The null value.
Null,
/// The true boolean value.
True,
/// The false boolean value.
False,
/// A binary operation, two operands and an operator.
/// The booleans represents possible whitespace.
B... | random_line_split | ||
value.rs | <ListSeparator>, bool),
/// A Numeric value is a rational value with a Unit (which may be
/// Unit::None) and flags.
///
/// The boolean flag is true for calculated values and false for
/// literal values.
Numeric(Numeric, bool),
/// A color value (and optionally, its source string).
Col... | (&self, other: &Value) -> bool {
match (&self, other) {
(Value::Bang(a), Value::Bang(b)) => a == b,
(Value::Numeric(a, _), Value::Numeric(b, _)) => a == b,
(Value::Literal(a, aq), Value::Literal(b, bq)) => {
if aq == bq {
a == b
... | eq | identifier_name |
main.rs | mush, facet);
let questions = (1..facet_vals.len())
.flat_map(move |k| facet_vals.combination(k))
.map(move |combis| Question {
facet,
vals: combis.into_iter().cloned().collect(),
});
for question in questio... | () {
let q = Question {
facet: 0,
vals: ['a', 'b', 'c'].iter().cloned().collect(),
};
let mushs = [
Mush {
poison: 'p',
attrs: ['a'; 22],
},
Mush {
poison: 'p',
attrs: ['b'; 22],
},
Mush {
poi... | test_answer | identifier_name |
main.rs | mush, facet);
let questions = (1..facet_vals.len())
.flat_map(move |k| facet_vals.combination(k))
.map(move |combis| Question {
facet,
vals: combis.into_iter().cloned().collect(),
});
for question in questio... | ("gill-size" ,"broad=b,narrow=n"),
("gill-color" ,"black=k,brown=n,buff=b,chocolate=h,gray=g,green=r,orange=o,pink=p,purple=u,red=e,white=w,yellow=y"),
("stalk-shape" ,"enlarging=e,tapering=t"),... | ("cap-color" ,"brown=n,buff=b,cinnamon=c,gray=g,green=r,pink=p,purple=u,red=e,white=w,yellow=y"),
("bruises?" ,"bruises=t,no=f"),
("odor" ,"almond=a,anise=l,creosote=c,fishy=y,foul=f,mu... | random_line_split |
main.rs | mush, facet);
let questions = (1..facet_vals.len())
.flat_map(move |k| facet_vals.combination(k))
.map(move |combis| Question {
facet,
vals: combis.into_iter().cloned().collect(),
});
for question in questio... | else { None })
.cloned()
.collect::<Vec<_>>()
.join(", ");
write!(
f,
"Examine '{}'. Is it {}{}?",
facet_name,
if self.vals.len() > 1 { "one of " } else { "" },
choices
)
}
}
#[test]
fn test_question_f... | { Some(v) } | conditional_block |
main.rs | ush, facet);
let questions = (1..facet_vals.len())
.flat_map(move |k| facet_vals.combination(k))
.map(move |combis| Question {
facet,
vals: combis.into_iter().cloned().collect(),
});
for question in question... |
}
#[test]
fn test_question_fmt() {
use std::iter::FromIterator;
let q = Question {
facet: 0,
vals: BTreeSet::from_iter(['b', 'c', 'x'].iter().cloned()),
};
format!("{}", q);
}
lazy_static::lazy_static! {
static ref FACETS: Vec<(&'static str,HashMap<char,&'static str>)> = {
... | {
let (facet_name, facet_map) = &FACETS[self.facet];
let choices = facet_map
.iter()
.filter_map(|(k, v)| if self.vals.contains(k) { Some(v) } else { None })
.cloned()
.collect::<Vec<_>>()
.join(", ");
write!(
f,
... | identifier_body |
mod.rs | node.close();
}
}
cluster.set_nodes(vec![]);
}
fn tend(&self) -> Result<()> {
let mut nodes = self.nodes();
// All node additions/deletions are performed in tend thread.
// If active nodes don't exist, seed cluster.
if nodes.is_empty(... | {
let mut aliases = self.aliases.write();
node.add_alias(host.clone());
aliases.insert(host, node);
} | identifier_body | |
mod.rs | thread::spawn(move || Cluster::tend_thread(cluster_for_tend, rx));
debug!("New cluster initialized and ready to be used...");
Ok(cluster)
}
fn tend_thread(cluster: Arc<Cluster>, rx: Receiver<()>) {
let tend_interval = cluster.client_policy.tend_interval;
loop {
... | {
remove_list.push(tnode);
} | conditional_block | |
mod.rs | old_gen != node.partition_generation() {
self.update_partitions(node.clone())?;
}
}
Err(err) => {
node.increase_failures();
warn!("Node `{}` refresh failed: {}", node, err);
... | } | random_line_split | |
mod.rs | rx): (Sender<()>, Receiver<()>) = mpsc::channel();
let cluster = Arc::new(Cluster {
client_policy: policy,
seeds: Arc::new(RwLock::new(hosts.to_vec())),
aliases: Arc::new(RwLock::new(HashMap::new())),
nodes: Arc::new(RwLock::new(vec![])),
partition_... | (&self) -> bool {
let seed_array = self.seeds.read();
info!("Seeding the cluster. Seeds count: {}", seed_array.len());
let mut list: Vec<Arc<Node>> = vec![];
for seed in &*seed_array {
let mut seed_node_validator = NodeValidator::new(self);
if let Err(err) = see... | seed_nodes | identifier_name |
session.rs | )
}
}
/// State of game progression. Whether the game is on, over and what kind of over.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Progression {
PlayOn(LastAttack),
GameOverWinner(Player),
GameOverStalemate(Vec<Player>), // Easier to calculate than a draw...
}
/// The state of the session.
#[der... | choices,
);
};
Ok(state)
}
/// A game in progress. The `traversals` indicate how many turns have passed. Maintains
/// all state of the game.
///
/// ## Invariants
/// 1. The `Tree` will always be valid.
/// 2. The first `State` in the `turns` is the starting position sans any inital trave... | traversal.as_slice(),
current_board, | random_line_split |
session.rs | )
}
}
/// State of game progression. Whether the game is on, over and what kind of over.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Progression {
PlayOn(LastAttack),
GameOverWinner(Player),
GameOverStalemate(Vec<Player>), // Easier to calculate than a draw...
}
/// The state of the session.
#[der... | turns: vec![first_turn],
tree,
move_limit,
rand: rand::thread_rng(),
}
}
pub fn reset(self) -> Self {
let first = self.turns.first().unwrap().board.to_owned();
Session::new(
first.clone(),
game::start_tree_horizon_... | {
// The start may contain pass move. Cycle to get at the first true turn.
// This code is a copy of what's happening in `advance` below. TODO: Refactor me.
let mut tree = Some(tree);
let first_turn = loop {
match state_from_board(
start.clone(), tree... | identifier_body |
session.rs | (
attacker_dice: u8, attacker_rolled: usize, defender_dice: u8, defender_rolled: usize
) -> Self {
LastAttack { attacker_dice, attacker_rolled, defender_dice, defender_rolled }
}
}
impl fmt::Display for LastAttack {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.atta... | new | identifier_name | |
global.js | 时,跳转到此
*/
onIconError : function(img) {
// 记录原有路径
var originalSrc = img.getAttribute('originalSrc');
var gender = img.getAttribute('gender');
var src = img.getAttribute('src');
if (!originalSrc) {
img.setAttribute('orig... | }
} else {
for (var y | conditional_block | |
global.js | ").each(function() {
$(this).addClass("span-hover");
});
} else if (event.type == "mouseout") {
$(this).find("span").each(function() {
$(this).removeClass("span-hover");
});
... | exp.setTime(exp.getTime() + options.expires * 24 * 60 * 60 * 1000);
} else {
exp = options.expires;
}
expires = ';expires=' + exp.toUTCString();
}
path = options.path ? '; pa... | if (typeof options.expires == 'number') {
exp = new Date();
| random_line_split |
monitor.go | &MonitoringManager{
MonitorList: make([]*Monitor, 0),
LastMessageList: make(map[string]*[]byte),
Start: false,
}
}
// Return the global monitor manager object
func GetManager() *MonitoringManager {
if globalMonitor == nil {
fmt.Println("Monitor not initialized. Initializing")
Init() // Create monitor
}
... | CheckIPExistIndex | identifier_name | |
monitor.go | Message messagesocket.Message
// The start time of the monitor session
Start time.Time
// The end time of the monitor session
End time.Time
// The total duration the monitor session remain active
Interval time.Duration
// The facility the monitoring session is monitoring
Facility facility.Facility
... | }
// Monitor is the implementaion of a monitoring session
type Monitor struct {
// Store the client StartMonitoringMessage to identiy the client that initiate the monitoring session | random_line_split | |
monitor.go | time.Time
// The end time of the monitor session
End time.Time
// The total duration the monitor session remain active
Interval time.Duration
// The facility the monitoring session is monitoring
Facility facility.Facility
}
// Initialize the global monitor manager (Used by the server to manage monitorin... | else {
marshalled = byteArr
}
// Broadcast the message to the clients
mgmt.BroadcastUsingMsgList(marshalled, messageList)
// Check if the unacknowledged messages handler is started
// If it is not started, start it up
if !mgmt.Start {
fmt.Println("Starting resend loop")
go mgmt.goStartCheckingResend()
}... | {
fmt.Printf("%s\n", err.Error())
return // Don't send availability on error
} | conditional_block |
monitor.go | ())
// Resend message to client
v.Message.Reply(*value)
}
}
}
}
// Multithreaded Goroutine to handle checking for unacknowledged messages
// Unacknowledged messages will be resent in a loop until all messages are acknowledged
func (mgmt *MonitoringManager) goStartCheckingResend() {
// Defers setting res... | {
payload := make([]byte, 0)
// We place the action string in front first (length of string 1 byte, string x byte)
fmt.Println(len(actionString))
// We obtain the length of the action string
asLen, _ := hex.DecodeString(fmt.Sprintf("%02x", len(actionString)))
// We append the action string length to the beginnin... | identifier_body | |
scene.py | .models.get(parent).attachNewNode(actorNode)
# Attach the actor to the physics manager
self.app.physicsMgr.attachPhysicalNode(actorNode)
# reparent the model to the actor node
model.reparentTo(actorNodePath)
colliderNodePath = self.addColliderNode(parent)
if collider:
|
else:
# Parent the model to either the render tree or the parent
model.reparentTo(self.renderTree if parent is None else self.models.get(parent))
else:
# If the model is being instanced to an existing model
model = self.addInstance(pos, scale, instanceTo)
# Add the model to the scenes model dicti... | colliderNodePath.node().addSolid(collider) | conditional_block |
scene.py | self.models.get(parent).attachNewNode(actorNode)
# Attach the actor to the physics manager
self.app.physicsMgr.attachPhysicalNode(actorNode)
# reparent the model to the actor node
model.reparentTo(actorNodePath)
colliderNodePath = self.addColliderNode(parent) | model.reparentTo(self.renderTree if parent is None else self.models.get(parent))
else:
# If the model is being instanced to an existing model
model = self.addInstance(pos, scale, instanceTo)
# Add the model to the scenes model dictionary
self.models[key if key is not None else len(self.models)] = model... | if collider:
colliderNodePath.node().addSolid(collider)
else:
# Parent the model to either the render tree or the parent | random_line_split |
scene.py | .models.get(parent).attachNewNode(actorNode)
# Attach the actor to the physics manager
self.app.physicsMgr.attachPhysicalNode(actorNode)
# reparent the model to the actor node
model.reparentTo(actorNodePath)
colliderNodePath = self.addColliderNode(parent)
if collider:
colliderNodePath.node(... | (self, pos, scale, instanceTo):
'''
Adds an Instance of the chosen model to the scene.
'''
# Create a new empty node and attach it to the render tree
model = self.renderTree.attachNewNode("model_placeholder")
# Set the position and scale of the model
model.setPos(*pos)
model.setScale(*scale)
# Insta... | addInstance | identifier_name |
scene.py | self.models.get(parent).attachNewNode(actorNode)
# Attach the actor to the physics manager
self.app.physicsMgr.attachPhysicalNode(actorNode)
# reparent the model to the actor node
model.reparentTo(actorNodePath)
colliderNodePath = self.addColliderNode(parent)
if collider:
colliderNodePath.... |
def exitScene(self):
'''
An event hook method for running events as the scene is exited
'''
pass
class IntroClipScene(Scene):
'''
A subclass of the Scene class to handle the intro clip
and all of it's required tasks + events
'''
def __init__(self, app):
'''
Initialise and run any events BEFORE load... | '''
A event hook method for running events when the scene is first loaded
'''
pass | identifier_body |
villager_bot.py | _id: "lang"}
self.prefix_cache = dict[int, str]() # {guild_id: "prefix"}
self.disabled_commands = defaultdict[int, set[str]](
set
) # {guild_id: set({command, command,..})}
self.replies_cache = set[int]() # {guild_id, guild_id,..}
self.rcon_cache = dict[tuple[int, ... |
await self.karen.command_execution(
ctx.author.id, getattr(ctx.guild, "id", None), ctx.command.qualified_name, False
)
async def after_command_invoked(self, ctx: CustomContext):
try:
if ctx.command.qualified_name in self.d.concurrency_limited:
await... | await self.karen.lb_command_ran(ctx.author.id) | conditional_block |
villager_bot.py | _id: "lang"}
self.prefix_cache = dict[int, str]() # {guild_id: "prefix"}
self.disabled_commands = defaultdict[int, set[str]](
set
) # {guild_id: set({command, command,..})}
self.replies_cache = set[int]() # {guild_id, guild_id,..}
self.rcon_cache = dict[tuple[int, ... |
async def start(self):
self.font_files = await FontHandler(
font_urls=self.d.font_urls, output_directory="fonts"
).retrieve()
self.captcha_generator = captcha.image.ImageCaptcha(fonts=self.font_files)
self.karen = KarenClient(self.k.karen, self.get_packet_handlers(), s... | return getattr(discord.Color, self.d.embed_color)() | identifier_body |
villager_bot.py | _id: "lang"}
self.prefix_cache = dict[int, str]() # {guild_id: "prefix"}
self.disabled_commands = defaultdict[int, set[str]](
set
) # {guild_id: set({command, command,..})}
self.replies_cache = set[int]() # {guild_id, guild_id,..}
self.rcon_cache = dict[tuple[int, ... | ) -> None:
embed = discord.Embed(color=self.embed_color, description=message)
try:
await location.reply(embed=embed, mention_author=ping)
except discord.errors.HTTPException as e:
if (
e.code == 50035
): # invalid form body, happens somet... | raise
async def reply_embed(
self, location, message: str, ping: bool = False, *, ignore_exceptions: bool = False | random_line_split |
villager_bot.py | self.logger)
self.db = DatabaseProxy(self.karen)
await self.karen.connect()
cluster_info = await self.karen.fetch_cluster_init_info()
self.shard_count = cluster_info.shard_count
self.shard_ids = cluster_info.shard_ids
self.cluster_id = cluster_info.cluster_id
... | packet_fetch_guild_count | identifier_name | |
panel-page-manager.js | var LINKED_HASH_MAP = xutil.LinkedHashMap;
//------------------------------------------
// 类型声明
//------------------------------------------
var PANEL_PAGE_MANAGER = $namespace().PanelPageManager =
inheritsObject(
XDATASOURCE,
/**
* @param {Object}... | /**
* 得到当前页面实例
*
* @public
* @return {PanelPage} panelPage
*/
PANEL_PAGE_MANAGER_CLASS.getCurrentPage = function() {
return this._oCurrPageWrap ? this._oCurrPageWrap.page : null;
};
/**
* 得到当前页面ID
*
* @public
* @return {string} pageId
*/
PANEL... | n {PanelPage} panelPage
*/
PANEL_PAGE_MANAGER_CLASS.getPage = function(pageId) {
return (this._oPanelPageSet.get(pageId) || {}).page;
};
| conditional_block |
panel-page-manager.js | ;
var LINKED_HASH_MAP = xutil.LinkedHashMap;
//------------------------------------------
// 类型声明
//------------------------------------------
var PANEL_PAGE_MANAGER = $namespace().PanelPageManager =
inheritsObject(
XDATASOURCE,
/**
* @param {Objec... | }
// 选择激活
this.select(pageId, param);
return page;
};
/**
* 增加 panel pange
*
* @public
* @param {ecui.ui.PanelPage|Function} panelPage 要添加的panel page,
* 或者创建panel page的回调函数
* 如果为函数,则:
* @param {Object} options 参数
... | oncreate && oncreate(page); | random_line_split |
kvstore.go | (s, offset)
if nil == p {
return false
}
switch p.tt {
case proposal_lease:
this.rn.lease.update(this.rn, p.values[0].(int), p.values[1].(uint64))
case proposal_snapshot, proposal_update, proposal_kick:
unikey := p.values[0].(string)
if p.tt == proposal_kick {
logger.Debugln(unikey, "cache_... | qC * | identifier_name | |
kvstore.go | oseC.AddNoWait(&asynTaskKick{kv: kv}); nil == err {
return true, removeDirect
} else {
kv.setKicking(false)
return false, removeDirect
}
}
func splitUniKey(s string) (table string, key string) {
i := -1
for k, v := range s {
if v == 58 {
i = k
break
}
}
if i >= 0 {
table = s[:i]
key = s[i+1:... | = store.elements[uniKey]
if ok {
if !this.dbmeta.CheckMetaVersion(k.meta.Version()) {
newMeta := this.dbmeta.GetTableMeta(table)
if newMeta != nil {
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&k.meta)), unsafe.Pointer(newMeta))
} else {
//log error
err = errcode.ERR_INVAILD_TA... | identifier_body | |
kvstore.go |
func (this *kvstore) getRaftNode() *raftNode {
return this.rn
}
func (this *kvstore) removeKv(k *kv) {
processAgain := false
this.Lock()
k.Lock()
if !k.cmdQueue.empty() {
k.resetStatus()
processAgain = true
} else {
k.setStatus(cache_remove)
this.removeLRU(k)
delete(this.elements, k.uniKey)
}
k.... | return this.kvNode
} | random_line_split | |
kvstore.go | (this *kvstore) issueReadReq(task asynCmdTaskI) {
if err := this.readReqC.AddNoWait(task); nil != err {
task.onError(errcode.ERR_SERVER_STOPED)
}
}
func (this *kvstore) issueConfChange(task *asynTaskConfChange) {
this.confChangeC <- task
}
func (this *kvstore) updateLRU(kv *kv) {
if kv.nnext != nil || kv.ppre... | {
table, key := splitUniKey(unikey)
meta := this.storeMgr.dbmeta.GetTableMeta(table)
if nil == meta {
return false
}
kv = newkv(this, meta, key, unikey, false)
this.elements[unikey] = kv
}
if version == 0 {
kv.setStatus(cache_missing)
kv.fields = nil
logger.... | es[1].(int64)
if !ok | conditional_block |
shortid.go | s
// KpTvcui99k
// KFTGcuiQ9p
// KFmGeu-Q9O
// tFTvcu-QQt
// tpTveu-99u
//
// Life span
//
// The package guarantees the generation of unique Ids with zero collisions for 34 years
// (1/1/2016-1/1/2050) using the same worker Id within a single (although concurrent) application if
// application restarts take longe... |
// Epoch returns the value of epoch used as the beginning of millisecond counting (normally
// 2016-01-01 00:00:00 local time)
func (sid *Shortid) Epoch() time.Time {
return sid.epoch
}
// Worker returns the value of worker for this short Id generator.
func (sid *Shortid) Worker() uint {
return sid.worker
}
// Ne... | {
return sid.abc
} | identifier_body |
shortid.go | guarantees no collisions (due to guaranteed fixed size of Ids between milliseconds and because
// multiple requests within the same ms lead to longer Ids with the prefix unique to the ms);
// - supports 32 over 16 workers.
//
// The algorithm uses less randomness than the original node.js implementation, which per... |
// Encode encodes a given value into a slice of runes of length nsymbols. In case nsymbols==0, the
// length of the result is automatically computed from data. Even if fewer symbols is required to
// encode the data than nsymbols, all positions are used encoding 0 where required to guarantee | random_line_split | |
shortid.go | QQs
// KpTvcui99k
// KFTGcuiQ9p
// KFmGeu-Q9O
// tFTvcu-QQt
// tpTveu-99u
//
// Life span
//
// The package guarantees the generation of unique Ids with zero collisions for 34 years
// (1/1/2016-1/1/2050) using the same worker Id within a single (although concurrent) application if
// application restarts take lon... | (alphabet string, seed uint64) (Abc, error) {
runes := []rune(alphabet)
if len(runes) != len(DefaultABC) {
return Abc{}, fmt.Errorf("alphabet must contain %v unique characters", len(DefaultABC))
}
if nonUnique(runes) {
return Abc{}, errors.New("alphabet must contain unique characters only")
}
abc := Abc{alpha... | NewAbc | identifier_name |
shortid.go | }
// GetDefault retrieves the default short Id generator initialised with the default alphabet,
// worker=0 and seed=1. The default can be overwritten using SetDefault.
func GetDefault() *Shortid {
return (*Shortid)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&shortid))))
}
// SetDefault overwrites the defau... | {
ints[i] = int(b) & mask
} | conditional_block | |
circuit.rs | , thus PK is a point, sk is a scalar and derive(sk) = sk * B, for a predefined base pont B
// - VRF_INPUT and VRF_OUTPUT are elliptic curve points, and vrf(sk, VRF_INPUT) = sk * VRF_INPUT
// - set //TODO
// These are the values that are required to construct the circuit and populate all the wires.
// They are defined ... | {
::std::mem::swap(&mut lhs, &mut rhs);
} | conditional_block | |
circuit.rs | the given vrf_output is valid for the given vrf_input under
// a key from the predefined set. It formalizes the following language:
// {(VRF_INPUT, VRF_OUTPUT, set) | VRF_OUTPUT = vrf(sk, VRF_INPUT), PK = derive(sk) and PK is in set }, where:
// - sk, PK is an elliptic curve keypair, thus PK is a point, sk is a scala... | <'a, E: JubjubEngine> { // TODO: name
// Jubjub curve parameters.
pub params: &'a E::Params,
// The secret key, an element of Jubjub scalar field.
pub sk: Option<E::Fs>,
// The VRF input, a point in Jubjub prime order subgroup.
pub vrf_input: Option<edwards::Point<E, PrimeOrder>>,
// The... | Ring | identifier_name |
circuit.rs | the given vrf_output is valid for the given vrf_input under
// a key from the predefined set. It formalizes the following language:
// {(VRF_INPUT, VRF_OUTPUT, set) | VRF_OUTPUT = vrf(sk, VRF_INPUT), PK = derive(sk) and PK is in set }, where:
// - sk, PK is an elliptic curve keypair, thus PK is a point, sk is a scala... | use zcash_primitives::pedersen_hash;
use zcash_primitives::jubjub::{JubjubBls12, fs, edwards,};
use rand_core::{RngCore, SeedableRng,};
use rand_xorshift::XorShiftRng;
let params = &JubjubBls12::new();
let rng = &mut XorShiftRng::from_seed([
0x58, 0x62, 0xbe, 0x3d, 0x76, 0x3d, 0x31, 0x... |
#[test]
fn test_ring() {
use bellman::gadgets::test::TestConstraintSystem;
use pairing::bls12_381::{Bls12, Fr,}; | random_line_split |
blackjack.js | then(m => m.delete({ timeout: 8000 }));
}
if (bet < 1 || !Number.isInteger(Number(bet))) {
if (bet && bet.toLowerCase().includes('k')) {
const givenKay = bet.replace(/k/g, '');
if (!Number.isInteger(Number(givenKay * 1000)) || isNaN(givenKay * 1000)) {
... | function getValue (card) {
return { value: values[faces.indexOf(card.face)], card };
}
function addCards (type) {
return cards[type].sort((a, b) => getValue(b).value - getValue(a).value).reduce((p, c) => {
let newCard = getValue(c).value;
if (newCar... | {
switch (suit) {
case 'spades':
return '♠';
case 'hearts':
return '♥';
case 'diamonds':
return '♦';
case 'clubs':
return '♣';
}
}
| identifier_body |
blackjack.js | (message) {
const DB = require('djs-economy');
const user = message.author;
const cash = await DB.GetCash(message.author.id).cash;
const formatNumber = require('../../functions/regex');
const args = message.content.slice(prefix.length).trim().split(/ /g);
let be... | execute | identifier_name | |
blackjack.js | then(m => m.delete({ timeout: 8000 }));
}
if (bet < 1 || !Number.isInteger(Number(bet))) {
if (bet && bet.toLowerCase().includes('k')) {
const givenKay = bet.replace(/k/g, '');
if (!Number.isInteger(Number(givenKay * 1000)) || isNaN(givenKay * 1000)) {
... |
function getRespectiveIcon (suit) {
switch (suit) {
case 'spades':
return '♠';
case 'hearts':
return '♥';
case 'diamonds':
return '♦';
case 'clubs':
return '♣';
... | { // redraw
cards = {
bot: [deal(), deal()],
user: [deal(), deal()]
};
} | conditional_block |
blackjack.js | then(m => m.delete({ timeout: 8000 }));
}
if (bet < 1 || !Number.isInteger(Number(bet))) {
if (bet && bet.toLowerCase().includes('k')) {
const givenKay = bet.replace(/k/g, '');
if (!Number.isInteger(Number(givenKay * 1000)) || isNaN(givenKay * 1000)) {
... | }
if (cash === 0) {
return message.reply('You dont have any cash to bet');
}
if (bet > cash) {
return message.reply(`You only have ${formatNumber(cash)}. You cant bet more than that`);
}
if (bet > 5000000) {
return message.rep... | random_line_split | |
azure_logcollector.go | err
}
// Machine pool can be an AzureManagedMachinePool for AKS clusters.
_, err = getAzureManagedMachinePool(ctx, managementClusterClient, mp)
if err != nil {
return err
}
} else {
isWindows = isAzureMachinePoolWindows(am)
}
cluster, err := util.GetClusterFromMetadata(ctx, managementClusterClient, ... |
azManagedControlPlane := &infrav1.AzureManagedControlPlane{}
err := managementClusterClient.Get(ctx, key, azManagedControlPlane)
return azManagedControlPlane, err
}
func getAzureMachine(ctx context.Context, managementClusterClient client.Client, m *clusterv1.Machine) (*infrav1.AzureMachine, error) {
key := client... | key := client.ObjectKey{
Namespace: namespace,
Name: name,
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.