file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
cartesian.rs | // Copyright 2017 Nico Madysa.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You may
// obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wri... | 1 + self
.iterators
.iter()
.enumerate()
.map(|(i, iterator)| {
iterator.len()
* self.collections[i + 1..]
.iter()
.map(|c| c.into_iter().len())
.product::<usize>(... | return 0;
}
| conditional_block |
cartesian.rs | // Copyright 2017 Nico Madysa.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You may
// obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wri... | ::std::iter::Sum for SizeHint {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(SizeHint(0, Some(0)), |acc, x| acc + x)
}
}
impl ::std::iter::Product for SizeHint {
fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(SizeHint(1, Some(1)), |acc, x| acc * x)
}... | let lower = self.0 * other.0;
let upper = match (self.1, other.1) {
(Some(left), Some(right)) => Some(left * right),
_ => None,
};
SizeHint(lower, upper)
}
}
impl | identifier_body |
cartesian.rs | // Copyright 2017 Nico Madysa.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You may
// obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wri... | (Some(left), Some(right)) => Some(left * right),
_ => None,
};
SizeHint(lower, upper)
}
}
impl ::std::iter::Sum for SizeHint {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(SizeHint(0, Some(0)), |acc, x| acc + x)
}
}
impl ::std::iter::Product... | type Output = Self;
fn mul(self, other: Self) -> Self {
let lower = self.0 * other.0;
let upper = match (self.1, other.1) { | random_line_split |
dnn1.py | # Pose estimation and object detection: OpenCV DNN, ImageAI, YOLO, mpi, caffemodel, tensorflow
# Authors:
# Tutorial by: https://learnopencv.com/deep-learning-based-human-pose-estimation-using-opencv-cpp-python/
# Model file links collection (replace .sh script): Twenkid
# http://posefs1.perception.cs.cmu.edu/OpenPose/... | (image): #inWidth, Height ... - global, set as params later
frameHeight, frameWidth, ch = image.shape
# Prepare the image to be fed to the network
inpBlob = cv2.dnn.blobFromImage(image, 1.0 / 255, (inWidth, inHeight), (0, 0, 0), swapRB=False, crop=False)
#cv2.imshow("G", inpBlob) #unsupported
... | Detect | identifier_name |
dnn1.py | # Pose estimation and object detection: OpenCV DNN, ImageAI, YOLO, mpi, caffemodel, tensorflow
# Authors:
# Tutorial by: https://learnopencv.com/deep-learning-based-human-pose-estimation-using-opencv-cpp-python/
# Model file links collection (replace .sh script): Twenkid
# http://posefs1.perception.cs.cmu.edu/OpenPose/... | # My experiments results: disappointingly bad pose estimation on the images I tested. Sometimes good, sometimes terrible.
import cv2
import tensorflow.compat.v1 as tf
from imageai.Detection import ObjectDetection
import os
boxes = []
def yolo():
#name = "k.jpg"
root = "Z:\\"
name = "23367640.png" #t.jpg"... | # I tried with yolo-tiny, but the accuracy of the bounding boxes didn't seem acceptable.
#tf 1.15 for older versions of ImageAI - but tf doesn't support Py 3.8
#ImageAI: older versions require tf 1.x
#tf 2.4 - required by ImageAI 2.1.6 -- no GPU supported on Win 7, tf requires CUDA 11.0 (Win10). Win7: CUDA 10.x. CPU: w... | random_line_split |
dnn1.py | # Pose estimation and object detection: OpenCV DNN, ImageAI, YOLO, mpi, caffemodel, tensorflow
# Authors:
# Tutorial by: https://learnopencv.com/deep-learning-based-human-pose-estimation-using-opencv-cpp-python/
# Model file links collection (replace .sh script): Twenkid
# http://posefs1.perception.cs.cmu.edu/OpenPose/... |
for i in collected: Detect(i)
cv2.waitKey(0)
cv2.destroyAllWindows()
| frameHeight, frameWidth, ch = image.shape
# Prepare the image to be fed to the network
inpBlob = cv2.dnn.blobFromImage(image, 1.0 / 255, (inWidth, inHeight), (0, 0, 0), swapRB=False, crop=False)
#cv2.imshow("G", inpBlob) #unsupported
#cv2.waitKey(0)
# Set the prepared object as the input blob of t... | identifier_body |
dnn1.py | # Pose estimation and object detection: OpenCV DNN, ImageAI, YOLO, mpi, caffemodel, tensorflow
# Authors:
# Tutorial by: https://learnopencv.com/deep-learning-based-human-pose-estimation-using-opencv-cpp-python/
# Model file links collection (replace .sh script): Twenkid
# http://posefs1.perception.cs.cmu.edu/OpenPose/... |
print(points)
cv2.imshow("Output-Keypoints",image)
cv2.waitKey()
for i in collected: Detect(i)
cv2.waitKey(0)
cv2.destroyAllWindows()
| probMap = output[0, i, :, :]
# Find global maxima of the probMap.
minVal, prob, minLoc, point = cv2.minMaxLoc(probMap)
# Scale the point to fit on the original image
x = (frameWidth * point[0]) / W
y = (frameHeight * point[1]) / H
if prob > threshold :
cv2.... | conditional_block |
manifest.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... | e actual state with the desired, and attempts to
// converge the two. It then updates the Status block of the Manifest resource
// with the current status of the resource.
func (c *Controller) syncHandler(key string) error {
// If an error occurs during handling, we'll requeue the item so we can
// attempt processing... | eue.Get()
if shutdown {
return false
}
// We wrap this block in a func so we can defer c.workqueue.Done.
err := func(obj interface{}) error {
// We call Done here so the workqueue knows we have finished
// processing this item. We also must remember to call Forget if we
// do not want this work item being... | identifier_body |
manifest.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... | // workqueue.
func (c *Controller) runWorker() {
for c.processNextWorkItem() {
}
}
// processNextWorkItem will read a single work item off the workqueue and
// attempt to process it, by calling the syncHandler.
func (c *Controller) processNextWorkItem() bool {
obj, shutdown := c.workqueue.Get()
if shutdown {
re... | random_line_split | |
manifest.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... | (workers int, stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer c.workqueue.ShutDown()
klog.Info("starting manifest controller...")
defer klog.Info("shutting down manifest controller")
// Wait for the caches to be synced before starting workers
if !cache.WaitForNamedCacheSync("manifest-controller"... | Run | identifier_name |
manifest.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... |
//过滤没有annotation的
annotations := utd.GetAnnotations()
if ok := util.MatchAnnotationsKeyPrefix(annotations); !ok {
klog.V(5).Infof("addManifest but manifest %s:%s does not find match annotation", manifest.Namespace, manifest.Name)
return
}
c.enqueue(manifest)
}
func (c *Controller) updateManifest(old, cur int... | {
klog.Errorf("unmarshal error, %q, err=%v", klog.KObj(manifest), err)
return
} | conditional_block |
rsqf.rs | use block;
use logical;
use murmur::Murmur3Hash;
#[allow(dead_code)] // for now
pub struct RSQF {
meta: Metadata,
logical: logical::LogicalData,
}
#[allow(dead_code)] // for now | struct Metadata {
n: usize,
qbits: usize,
rbits: usize,
nblocks: usize,
nelements: usize,
ndistinct_elements: usize,
nslots: usize,
noccupied_slots: usize,
max_slots: usize,
}
/// Standard filter result type, on success returns a count on error returns a message
/// This should prob... | #[derive(Default, PartialEq)] | random_line_split |
rsqf.rs | use block;
use logical;
use murmur::Murmur3Hash;
#[allow(dead_code)] // for now
pub struct RSQF {
meta: Metadata,
logical: logical::LogicalData,
}
#[allow(dead_code)] // for now
#[derive(Default, PartialEq)]
struct Metadata {
n: usize,
qbits: usize,
rbits: usize,
nblocks: usize,
nelements:... | () {
RSQF::new(10000, 8);
}
#[test]
fn computes_valid_metadata() {
let filter = RSQF::new(10000, 9);
assert_eq!(filter.meta.n, 10000);
assert_eq!(filter.meta.rbits, 9);
assert_eq!(filter.meta.qbits, 14);
assert_eq!(filter.meta.nslots, 1usize << 14);
... | panics_on_invalid_r | identifier_name |
rsqf.rs | use block;
use logical;
use murmur::Murmur3Hash;
#[allow(dead_code)] // for now
pub struct RSQF {
meta: Metadata,
logical: logical::LogicalData,
}
#[allow(dead_code)] // for now
#[derive(Default, PartialEq)]
struct Metadata {
n: usize,
qbits: usize,
rbits: usize,
nblocks: usize,
nelements:... |
#[test]
fn computes_valid_metadata_for_n_and_r() {
let test_data = [
// (n, r, expected_qbits, expected_nslots)
(10_000_usize, 9_usize, 14, 1usize << 14),
];
for (n, r, expected_qbits, expected_nslots) in test_data.into_iter() {
let meta = Metadata:... | {
// Test data data values were computed from a Google Sheet using formulae from the RSQF
// paper
let test_data = [
// (n, r, expected_q)
(100_000_usize, 6_usize, 17),
(1_000_000_usize, 6_usize, 20),
(10_000_000_usize, 6_usize, 24),
(1... | identifier_body |
chekcPermission.go | /***********************************************************************
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//******
// Filename:
// Description:
// Author:
// CreateTime:
/*******************************************... | ogicexp)
if err != nil {
return false, err
}
//step 2. get all token value
for token, value := range args {
tokens[token] = value
}
for token, _ := range tokens {
switch token {
case "alluser":
tokens["alluser"] = true
case "inneruser":
inneruser, err := EnvIsInnerUser(user)
if err != nil {
... | = append(roleids, node.Id.Id)
cached[node.Id.Id] = node.Id.Id
}
}
}
return
}
func CheckPrivilege(logicexp string, user t_user.User, args map[string]interface{}) (ok bool, err error) {
if len(logicexp) == 0 {
return true, nil
}
//Step 1. get need tokens
tokens, expression, err := GetLogicexpTokensAndE... | identifier_body |
chekcPermission.go | /***********************************************************************
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//******
// Filename:
// Description:
// Author:
// CreateTime:
/*******************************************... | 获取用户角色树
roletree, err := GetUserRoleTreeFromDb(c.Mysql(), input.Userid)
if err != nil {
return c.RESULT_ERROR(ERR_PERMISSION_DENIED, "获取用户角色树错误")
}
log.PrintPreety("roletree", roletree)
//Step 5. 获取所有权限
privilegeids := GetPrivilegeIds(roletree)
if len(privilegeids) == 0 {
return c.RESULT_ERROR(ERR_PERMISSI... | bugf("args input is querystring")
for k, varray := range values {
if varray != nil {
args[k] = varray[0]
}
}
}
//Step 4. | conditional_block |
chekcPermission.go | /***********************************************************************
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//******
// Filename:
// Description:
// Author:
// CreateTime:
/*******************************************... | log.Panicf("CheckScenePrivilege NewEvaluableExpression(%s) failed:%s",
logicexp, err.Error())
return nil, nil, err
}
for _, tk := range expression.Tokens() {
if tk.Kind == govaluate.VARIABLE {
tokens[tk.Value.(string)] = 1
}
}
return tokens, expression, nil
}
func EnvIsInnerUser(user t_user.User) (inne... | (logicexp)
if err != nil {
| identifier_name |
chekcPermission.go | /***********************************************************************
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//******
// Filename:
// Description:
// Author:
// CreateTime:
/*******************************************... | //子节点不存在,新建添加
roletree[cnid] = &NodeInfo{
Id: cnid,
Name: getName(db, cnid),
Children: RoleTree{},
Parents: RoleTree{},
}
roletree[pnid].Children[cnid] = roletree[cnid]
roletree[cnid].Parents[pnid] = roletree[pnid]
}
//获取下一层级的节点信息
if rolemap.F_target_type == ... | } else { | random_line_split |
myds_retrain.py | #! /usr/bin/env python
import argparse
import io
import os
import matplotlib
matplotlib.use('agg')
import h5py
import matplotlib.pyplot as plt
import numpy as np
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import Model, load_model
f... |
def boxprocessing(box_data):
#function assumes that there are a maximum of 4 bbox in an image
processed_box_data = []
processed_box_data = np.array(processed_box_data)
for i in range(len(box_data)):
z = np.zeros([1,20]) #change here, multiple of 5 - for more bbox
y = np.append(... | '''
function to preprocess hdf5 data
borrowed code from train_overfit and retrain_yolo and modified to suit my input dataset type (hdf5)
'''
image_list = []
boxes_list = []
image_data_list = []
processed_box_data = []
# boxes processing
box_dataset = data['train/boxes']
proc... | identifier_body |
myds_retrain.py | #! /usr/bin/env python
import argparse
import io
import os
import matplotlib
matplotlib.use('agg')
import h5py
import matplotlib.pyplot as plt
import numpy as np
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import Model, load_model
f... | for image in image_data])
else:
ValueError("draw argument image_set must be 'train', 'val', or 'all'")
# model.load_weights(weights_name)
model_body.load_weights(weights_name)
# Create output variables for prediction.
yolo_outputs = yolo_head(model_body.output, anchors,... | for image in image_data[int(len(image_data)*.9):]])
elif image_set == 'all':
image_data = np.array([np.expand_dims(image, axis=0) | random_line_split |
myds_retrain.py | #! /usr/bin/env python
import argparse
import io
import os
import matplotlib
matplotlib.use('agg')
import h5py
import matplotlib.pyplot as plt
import numpy as np
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import Model, load_model
f... |
# model.load_weights(weights_name)
model_body.load_weights(weights_name)
# Create output variables for prediction.
yolo_outputs = yolo_head(model_body.output, anchors, len(class_names))
input_image_shape = K.placeholder(shape=(2, ))
boxes, scores, classes = yolo_eval(
yolo_out... | ValueError("draw argument image_set must be 'train', 'val', or 'all'") | conditional_block |
myds_retrain.py | #! /usr/bin/env python
import argparse
import io
import os
import matplotlib
matplotlib.use('agg')
import h5py
import matplotlib.pyplot as plt
import numpy as np
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import Model, load_model
f... | (boxes_list, anchors):
'''
Precompute detectors_mask and matching_true_boxes for training.
Detectors mask is 1 for each spatial position in the final conv layer and
anchor that should be active for the given boxes and 0 otherwise.
Matching true boxes gives the regression targets for the ground truth... | get_detector_mask | identifier_name |
server.ts | import { Injectable, NgZone } from '@angular/core';
import { Device } from '@ionic-native/device';
import { Zeroconf } from '@ionic-native/zeroconf';
import { Alert, AlertController, Platform, Events, } from 'ionic-angular';
import { Observable, Subject, Subscription } from 'rxjs';
import { discoveryResultModel } from... |
private isTransitioningState() {
return this.webSocket && (this.webSocket.readyState == WebSocket.CLOSING || this.webSocket.readyState == WebSocket.CONNECTING);
}
private wsConnect(server: ServerModel, skipQueue: boolean = false) {
//console.log('[S]: wsConnect(' + server.address + ')', new Date())
... | {
console.log('[S]: wsDisconnect(reconnect=' + reconnect + ')', this.webSocket);
if (this.webSocket) {
if (this.everConnected && !this.reconnecting) {
this.lastToast.present('Connection lost');
this.connected = false;
this.wsEventObservable.next({ name: wsEvent.EVENT_ERROR, ws: th... | identifier_body |
server.ts | import { Injectable, NgZone } from '@angular/core';
import { Device } from '@ionic-native/device';
import { Zeroconf } from '@ionic-native/zeroconf';
import { Alert, AlertController, Platform, Events, } from 'ionic-angular';
import { Observable, Subject, Subscription } from 'rxjs';
import { discoveryResultModel } from... | //console.log('[S]: queue: ', this.serverQueue);
}
disconnect() {
this.wsDisconnect(false);
}
isConnected() {
return this.connected;
}
isReconnecting() {
return this.reconnecting;
}
private wsDisconnect(reconnect = false) {
console.log('[S]: wsDisconnect(reconnect=' + reconnect +... | random_line_split | |
server.ts | import { Injectable, NgZone } from '@angular/core';
import { Device } from '@ionic-native/device';
import { Zeroconf } from '@ionic-native/zeroconf';
import { Alert, AlertController, Platform, Events, } from 'ionic-angular';
import { Observable, Subject, Subscription } from 'rxjs';
import { discoveryResultModel } from... | continuoslyWatchForServers: boolean) {
this.continuoslyWatchForServers = continuoslyWatchForServers;
if (!continuoslyWatchForServers) {
this.unwatch();
}
}
private clearReconnectInterval() {
if (this.reconnectInterval) {
clearInterval(this.reconnectInterval);
this.reconnectInterva... | etContinuoslyWatchForServers( | identifier_name |
server.ts | import { Injectable, NgZone } from '@angular/core';
import { Device } from '@ionic-native/device';
import { Zeroconf } from '@ionic-native/zeroconf';
import { Alert, AlertController, Platform, Events, } from 'ionic-angular';
import { Observable, Subject, Subscription } from 'rxjs';
import { discoveryResultModel } from... | else {
//console.log('[S]: WS: the server is already in the connections queue');
}
setTimeout(() => {
if (this.isTransitioningState()/* && this.webSocket.url.indexOf(server.address) != -1*/) {
//console.log('[S]: the server ' + server.address + ' is still in transitiong state aft... | {
this.serverQueue.push(server);
//console.log('[S]: WS: the server has been added to the connections list')
} | conditional_block |
ash-v3_8h.js | var ash_v3_8h =
[
[ "AshTxDmaBuffer", "struct_ash_tx_dma_buffer.html", "struct_ash_tx_dma_buffer" ],
[ "AshTxState", "struct_ash_tx_state.html", "struct_ash_tx_state" ],
[ "AshRxState", "struct_ash_rx_state.html", "struct_ash_rx_state" ],
[ "ASH_ACK_TIMEOUT", "ash-v3_8h.html#a3aa3f8d4315d93d748e471860fd... | [ "ASH_FLAG", "ash-v3_8h.html#a35d6a5603fa48cc59eb18417e4376ace", null ],
[ "ASH_FRAME_COUNTER_ROLLOVER", "ash-v3_8h.html#a3898f887b8d025d7b9b58ed70ca31a9c", null ],
[ "ASH_PAYLOAD_LENGTH_BYTE_ESCAPED", "ash-v3_8h.html#acdbd78ad666c177bb3111175b6b20c97", null ],
[ "ASH_STATE_STRINGS", "ash-v3_8h.html#aa... | random_line_split | |
lpc55_flash.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use anyhow::{bail, Context, Result};
use byteorder::ByteOrder;
use clap::Parser;
use lpc55_isp::cmd::*;
use lpc55_is... | (prop: BootloaderProperty, params: Vec<u32>) {
match prop {
BootloaderProperty::BootloaderVersion => {
println!("Version {:x}", params[1]);
}
BootloaderProperty::AvailablePeripherals => {
println!("Bitmask of peripherals {:x}", params[1]);
}
Bootloader... | pretty_print_bootloader_prop | identifier_name |
lpc55_flash.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use anyhow::{bail, Context, Result};
use byteorder::ByteOrder;
use clap::Parser;
use lpc55_isp::cmd::*;
use lpc55_is... |
fn pretty_print_error(params: Vec<u32>) {
let reason = params[1] & 0xfffffff0;
if reason == 0 {
println!("No errors reported");
} else if reason == 0x0602f300 {
println!("Passive boot failed, reason:");
let specific_reason = params[2] & 0xfffffff0;
match specific_reason {
... | {
match prop {
BootloaderProperty::BootloaderVersion => {
println!("Version {:x}", params[1]);
}
BootloaderProperty::AvailablePeripherals => {
println!("Bitmask of peripherals {:x}", params[1]);
}
BootloaderProperty::FlashStart => {
println... | identifier_body |
lpc55_flash.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use anyhow::{bail, Context, Result};
use byteorder::ByteOrder;
use clap::Parser;
use lpc55_isp::cmd::*;
use lpc55_is... |
0x0b38f300 => {
println!("DICE failure. Check:");
println!("- Key store is set up properly (UDS)");
}
0x0d70f300 => {
println!("Trying to boot a TZ image on a device that doesn't have TZ!");
}
0x0d71f300 => {
... | {
println!("Application entry point and/or stack is invalid");
} | conditional_block |
lpc55_flash.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use anyhow::{bail, Context, Result};
use byteorder::ByteOrder;
use clap::Parser;
use lpc55_isp::cmd::*;
use lpc55_is... | file: PathBuf,
},
/// Erase the CMPA region (use to boot non-secure binaries again)
#[clap(name = "erase-cmpa")]
EraseCMPA,
/// Save the CMPA region to a file
ReadCMPA {
/// Write to FILE, or stdout if omitted
file: Option<PathBuf>,
},
/// Save the CFPA region to ... | },
/// Write a file to the CMPA region
#[clap(name = "write-cmpa")]
WriteCMPA { | random_line_split |
main.js |
var controlStatus = 0; //global variable for controlling if user has the control of DOris or not
var message_websocket_recibed ; //global variable which stores messages recibed from Doris
var filesadded = ""; //list of files already added for controlling no to add a script two times
... |
function onRTPMessage(evt) {
var cad = evt.data;
var message = cad.slice(1, cad.length);
messageSplitted = message.split("|");
if (messageSplitted[0] === "$POSE_VEL") {
showPositionVel(messageSplitted[1]);
if(svg_first_sector_load){
drawDorisPosition(messageSplitte... |
var obj = JSON.parse(message);
var errorStatus = parseInt(obj.streaming.error);
if (errorStatus === 0) {
var port = obj.streaming.port;
var rtpURL = 'ws://192.168.1.101:' + port;
rtPackages = new WebSocket(rtpURL);
rtPackages.onmessage = function (evt) { onRTPMessag... | identifier_body |
main.js | var controlStatus = 0; //global variable for controlling if user has the control of DOris or not
var message_websocket_recibed ; //global variable which stores messages recibed from Doris
var filesadded = ""; //list of files already added for controlling no to add a script two times
var rt... | /*case 27:
siteAdded(message);
break;*/
case 34:
// MakeMenuRooms();
loadMenuMap(0);
break;
case 124:
notifyMe(message);
break;
case 125:
changeControlStatus(message);
... | random_line_split | |
main.js |
var controlStatus = 0; //global variable for controlling if user has the control of DOris or not
var message_websocket_recibed ; //global variable which stores messages recibed from Doris
var filesadded = ""; //list of files already added for controlling no to add a script two times
... | evt){
console.log("2 websocket se ha cerrado");
}
function onRTPError(evt){
console.log("2 websocket ha tenido un error");
}
/*
function siteAdded(message){
var obj = JSON.parse(message);
alert("Added at index: " + obj.robot.index);
}
*/
function requestReleaseControl() {
... | nRTPClose( | identifier_name |
main.js |
var controlStatus = 0; //global variable for controlling if user has the control of DOris or not
var message_websocket_recibed ; //global variable which stores messages recibed from Doris
var filesadded = ""; //list of files already added for controlling no to add a script two times
... |
else if (obj.robot.error === "None.") {
alert(selected_map.nameSector.concat(" cargado con éxito."));
}
/// Cargar o no cargar todos las caracteristicas del mapa dependiendo de si tenemos el control ///
///Si es positivo llamamos a features/... | {
alert("Tiene que tener el control.");
var room_number = parseInt(room_selected, 10); //Cogemos la escala aqui tambien aunque no tengamos el control, para asi dibujar donde se encuentra DOris
scaleSVG.x = document.getElementById("mySVG").getBBox().width / parseInt(ro... | conditional_block |
handler.go | package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/atotto/clipboard"
"github.com/otiai10/copy"
)
const (
NoBackupFlag = "nobackup"
DefaultBackupSuffix = "_bk"
DefaultOutputSuffix = "_new"
MarkdownSuffix = ".md"
)
// markdown... | Path), os.PathSeparator,
strings.TrimSuffix(fstat.Name(), MarkdownSuffix),
DefaultBackupSuffix, MarkdownSuffix)
return nil
}
// 要求不备份
if *backupPath == NoBackupFlag {
*noBackup = true
*backupPath = "--"
return nil
}
// 非 .md 结尾,默认备份路径为目录
if !strings.HasSuffix(*backupPath, MarkdownSuffix) {
// 判断目录... | filepath.Dir(in | identifier_name |
handler.go | package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/atotto/clipboard"
"github.com/otiai10/copy"
)
const (
NoBackupFlag = "nobackup"
DefaultBackupSuffix = "_bk"
DefaultOutputSuffix = "_new"
MarkdownSuffix = ".md"
)
// markdown... | 块中,连续多个空行只保留一个
if strings.TrimSpace(newLine) == "" {
if emptyLineFlag {
continue
}
outputLines = append(outputLines, "")
emptyLineFlag = true
} else {
emptyLineFlag = false
outputLines = append(outputLines, newLine)
}
}
return strings.Join(outputLines, "\n")
}
func formatLine(line strin... | neFlag = false
outputLines = append(outputLines, newLine)
continue
}
// 位于非代码 | conditional_block |
handler.go | package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/atotto/clipboard"
"github.com/otiai10/copy"
)
const (
NoBackupFlag = "nobackup"
DefaultBackupSuffix = "_bk"
DefaultOutputSuffix = "_new"
MarkdownSuffix = ".md"
)
// markdown... | ackupPath = fmt.Sprintf("%s%c%s%s%s", filepath.Dir(inPath), os.PathSeparator,
strings.TrimSuffix(fstat.Name(), MarkdownSuffix),
DefaultBackupSuffix, MarkdownSuffix)
return nil
}
// 要求不备份
if *backupPath == NoBackupFlag {
*noBackup = true
*backupPath = "--"
return nil
}
// 非 .md 结尾,默认备份路径为目录
if !strin... | OutputSuffix, MarkdownSuffix)
}
// 其他情况 outPath 不处理
}
bf, err := os.Open(inPath)
if err != nil {
return err
}
// 内容处理
inContentBytes, err := ioutil.ReadAll(bf)
if err != nil {
return err
}
inContent := string(inContentBytes)
// 手动关闭输入文件(因为可能后面是覆盖该文件,要写入)
bf.Close()
// 备份
if !noBackup {
os.Rena... | identifier_body |
handler.go | package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/atotto/clipboard"
"github.com/otiai10/copy"
)
const (
NoBackupFlag = "nobackup"
DefaultBackupSuffix = "_bk"
DefaultOutputSuffix = "_new"
MarkdownSuffix = ".md"
)
// markdown... | log.Println("开始处理目录中的 Markdown 文件...")
filepath.Walk(inPath, func(path string, info os.FileInfo, err error) error {
// 忽略目录
if info.IsDir() {
return nil
}
if strings.HasSuffix(info.Name(), MarkdownSuffix) {
if err := handleFileInput(path, "", NoBackupFlag); err != nil {
allSuccess = false
... | // step2. 遍历 inPath,逐个替换文件 | random_line_split |
manage-hospital.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpServiceService } from 'src/app/services/http-service.service';
import { CookieService } from 'ngx-cookie-service';
import { MatSnackBar } from '@angular/material'
import... | else {
this.manageHospitalForm.value.mpimage = false;
}
if (this.manageHospitalForm.invalid) {
return;
}
else {
this.manageHospitalForm.value.contactemails = this.collect_email_array;
this.manageHospitalForm.value.contactphones = this.collect_phone_array;
... | {
if (this.configData.files.length > 1) { this.ErrCode = true; return; }
this.manageHospitalForm.value.mpimage =
{
"basepath": this.configData.files[0].upload.data.basepath + '/' + this.configData.path + '/',
"image": this.configData.files[0].upload.data.data.fileservernam... | conditional_block |
manage-hospital.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpServiceService } from 'src/app/services/http-service.service';
import { CookieService } from 'ngx-cookie-service';
import { MatSnackBar } from '@angular/material'
import... |
ngOnInit() {
/** generating the form **/
this.generateForm();
/** calling all state **/
this.allStateCityData();
/** switch case **/
switch (this.action) {
case 'add':
/* Button text */
this.btn_text = "SUBMIT";
//Generating the form on ... | /** fetching the current date **/
if (this.action == 'add')
this.date = moment(this.myDate).format('MM/DD/YYYY');
}
| random_line_split |
manage-hospital.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpServiceService } from 'src/app/services/http-service.service';
import { CookieService } from 'ngx-cookie-service';
import { MatSnackBar } from '@angular/material'
import... | (index) {
this.collect_email_array.splice(index, 1);
}
/** collecting the phone numbers **/
collect_phones(event: any) {
if (event.keyCode == 32 || event.keyCode == 13) {
this.collect_phone_array.push(event.target.value);
this.manageHospitalForm.controls['contactphones'].patchValue(""... | clearEmail | identifier_name |
manage-hospital.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpServiceService } from 'src/app/services/http-service.service';
import { CookieService } from 'ngx-cookie-service';
import { MatSnackBar } from '@angular/material'
import... |
/** clearing the phones **/
clearPhones(index) {
this.collect_phone_array.splice(index, 1);
}
/** --------------------------submit------------------------**/
onSubmit() {
this.manageHospitalForm.value.user_id = this.manageHospitalForm.controls['user_id'].value;
this.manageHospit... | {
if (event.keyCode == 32 || event.keyCode == 13) {
this.collect_phone_array.push(event.target.value);
this.manageHospitalForm.controls['contactphones'].patchValue("");
return;
}
} | identifier_body |
option_definition.py |
"""--------------------------------------------------------------------
* $Id: option_definition.py 3112 2015-05-19 13:17:35Z robert.buras $
*
* This file is part of libRadtran.
* Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer,
* Claudia Emde, Robert Buras
*
* ######### Cont... | (self):
self.valid_range = ["1d","3d"]
def get_valid_range(self):
return self.valid_range
class ProfileType():
"""
Options which can take several profile files as argument (e.g. 1D, 3D, moments, ipa_files)
"""
def __init__(self):
self.valid_range = ["1d","3d","ipa_files","moments"]
def get_valid_range(self... | __init__ | identifier_name |
option_definition.py |
"""--------------------------------------------------------------------
* $Id: option_definition.py 3112 2015-05-19 13:17:35Z robert.buras $
*
* This file is part of libRadtran.
* Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer,
* Claudia Emde, Robert Buras
*
* ######### Cont... |
if extra_dependencies:
self.isMandatory = self._isMandatoryMixedOption
# Pretend to be a dictionary to avoid breaking old code
def __getitem__(self, *args, **kwargs):
return self.dict.__getitem__(*args, **kwargs)
def __setitem__(self, *args, **kwargs):
return self.dict.__setitem__(*args, **kwargs)
def... | self._speaker = speaker
assert not isinstance(enable_values, basestring), "Missing comma in one-item-tuple?"
self._enable_values = enable_values
self.canEnable = self._canEnableContinousOption | conditional_block |
option_definition.py |
"""--------------------------------------------------------------------
* $Id: option_definition.py 3112 2015-05-19 13:17:35Z robert.buras $
*
* This file is part of libRadtran.
* Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer,
* Claudia Emde, Robert Buras
*
* ######### Cont... |
def _addBooleanToGuiInput(self,gui_inputs):
if not self.showInGui:
return ()
for inp in gui_inputs:
if not inp.optional or inp.__class__ == BooleanInput:
return gui_inputs
return ( BooleanInput(name=''), ).__add__(gui_inputs)
class Dimension():
"""
Options which can take dimensions (number+word) ... | if not self.showInGui:
return gui_inputs
for inp in tokens:
try:
name = inp.gui_name
except KeyError:
pass
if not name: name = inp.get('name')
try:
vr = inp.get('valid_range')
except KeyError:
vr = None
if isinstance(inp, addSetting):
continue
elif isinstance(inp, addLogic... | identifier_body |
option_definition.py | """--------------------------------------------------------------------
* $Id: option_definition.py 3112 2015-05-19 13:17:35Z robert.buras $
*
* This file is part of libRadtran.
* Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer,
* Claudia Emde, Robert Buras
*
* ######### Conta... | if not vr: vr = (-1e99, 1e99)
gui_inp = (FloatInput(name=name,optional=inp.get('optional'),valid_range=vr,default=inp.get('default')),)
elif dtype == int:
if not vr: vr = (-1e99, 1e99)
gui_inp = (IntegerInput(name=name,valid_range=vr,optional=inp.get('optional'),default=inp.get('default')),)
... | if dtype == float or dtype==Double: | random_line_split |
mod.rs | pub mod lru_cache;
use fs::File;
use fs_err as fs;
use std::borrow::Borrow;
use std::boxed::Box;
use std::collections::hash_map::RandomState;
use std::error::Error as StdError;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::hash::BuildHasher;
use std::io;
use std::io::prelude::*;
use std::path::{Path, PathBuf... |
fn insert_by<K: AsRef<OsStr>, F: FnOnce(&Path) -> io::Result<()>>(
&mut self,
key: K,
size: Option<u64>,
by: F,
) -> Result<()> {
if let Some(size) = size {
if !self.can_store(size) {
return Err(Error::FileTooLarge);
}
}
... | {
if !self.can_store(size) {
return Err(Error::FileTooLarge);
}
let rel_path = match addfile_path {
AddFile::AbsPath(ref p) => p.strip_prefix(&self.root).expect("Bad path?").as_os_str(),
AddFile::RelPath(p) => p,
};
//TODO: ideally LRUCache::in... | identifier_body |
mod.rs | pub mod lru_cache;
use fs::File;
use fs_err as fs;
use std::borrow::Borrow;
use std::boxed::Box;
use std::collections::hash_map::RandomState;
use std::error::Error as StdError;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::hash::BuildHasher;
use std::io;
use std::io::prelude::*;
use std::path::{Path, PathBuf... | <Q: ?Sized>(&self, _: &Q, v: &u64) -> usize
where
K: Borrow<Q>,
{
*v as usize
}
}
/// Return an iterator of `(path, size)` of files under `path` sorted by ascending last-modified
/// time, such that the oldest modified file is returned first.
fn get_all_files<P: AsRef<Path>>(path: P) -> Box... | measure | identifier_name |
mod.rs | pub mod lru_cache;
use fs::File;
use fs_err as fs;
use std::borrow::Borrow;
use std::boxed::Box;
use std::collections::hash_map::RandomState;
use std::error::Error as StdError;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::hash::BuildHasher;
use std::io;
use std::io::prelude::*;
use std::path::{Path, PathBuf... | set_mtime_back(f.create_file("file1", 10), 5);
set_mtime_back(f.create_file("file2", 10), 10);
let mut c = LruDiskCache::new(f.tmp(), 25).unwrap();
assert_eq!(c.size(), 20);
c.insert_bytes("file3", &[0; 10]).unwrap();
assert_eq!(c.size(), 20);
// The oldest file o... | let f = TestFixture::new();
// Create files explicitly in the past. | random_line_split |
utils.py | # /usr/bin/env python
# coding=utf-8
"""utils"""
import logging
import os
import shutil
import json
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.init as init
MAP_DICT = {'C': 0, 'III': 1, 'V': 2, 'XXXVIII': 3, 'XXIX': 4, 'LV': 5, 'XXXIX': 6, 'XIV': 7,
'IV': 8, 'XIX': 9, 'I':... |
Args:
state: (dict) contains model's state_dict, may contain other keys such as epoch, optimizer state_dict
is_best: (bool) True if it is the best model seen till now
checkpoint: (string) folder where parameters are to be saved
"""
filepath = os.path.join(checkpoint, 'last.pth.tar')... | 'best.pth.tar'
| identifier_name |
utils.py | # /usr/bin/env python
# coding=utf-8
"""utils"""
import logging
import os
import shutil
import json
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.init as init
MAP_DICT = {'C': 0, 'III': 1, 'V': 2, 'XXXVIII': 3, 'XXIX': 4, 'LV': 5, 'XXXIX': 6, 'XIV': 7,
'IV': 8, 'XIX': 9, 'I':... | in self.model.named_parameters():
if param.requires_grad and emb_name in name and 'LayerNorm' not in name:
# 保存原始参数
self.backup[name] = param.data.clone()
# scale
norm = torch.norm(param.grad)
if norm != 0 and not torch.isnan(no... | """
#
for name, param | identifier_body |
utils.py | # /usr/bin/env python
# coding=utf-8
"""utils"""
import logging
import os
import shutil
import json
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.init as init
MAP_DICT = {'C': 0, 'III': 1, 'V': 2, 'XXXVIII': 3, 'XXIX': 4, 'LV': 5, 'XXXIX': 6, 'XIV': 7,
'IV': 8, 'XIX': 9, 'I':... | self.data_cache = True
self.train_batch_size = 256
self.dev_batch_size = 128
self.test_batch_size = 128
# 最小训练次数
self.min_epoch_num = 5
# 容纳的提高量(f1-score)
self.patience = 0.001
# 容纳多少次未提高
self.patience_num = 5
self.seed = 2020
... | self.tags = list(MAP_DICT.values())
self.n_gpu = torch.cuda.device_count()
# 读取保存的data | random_line_split |
utils.py | # /usr/bin/env python
# coding=utf-8
"""utils"""
import logging
import os
import shutil
import json
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.init as init
MAP_DICT = {'C': 0, 'III': 1, 'V': 2, 'XXXVIII': 3, 'XXIX': 4, 'LV': 5, 'XXXIX': 6, 'XIV': 7,
'IV': 8, 'XIX': 9, 'I':... | init.normal_(w.data) # bias
elif m is not None and hasattr(m, 'weight') and \
hasattr(m.weight, "requires_grad"):
if len(m.weight.size()) > 1:
init_method(m.weight.data)
else:
init.normal_(m.weight.data)
else:
... | isinstance(m, nn.LSTM):
for w in m.parameters():
if len(w.data.size()) > 1:
init_method(w.data) # weight
else:
| conditional_block |
Unity_K144.py | """Synchronize settings between FSW/SMW K144 5GNR personality"""
###############################################################################
### Code Import
### pylint: disable=bad-whitespace,invalid-name,line-too-long,unused-argument
### pylint: disable=bare-except,no-member
#######################################... |
if 'DMRS Config'in K144Data[0][i]:
K144Data[1][i] = K144Data[1][i].replace('T','')
if 'L_PTRS' in K144Data[0][i]:
K144Data[1][i] = K144Data[1][i].replace('TD','')
if 'K_PTRS' in K144Data[0][i]:
K144Data[1][i] = K144Data[1][i].r... | K144Data[1][i] = K144Data[1][i].replace('N','')
K144Data[2][i] = K144Data[2][i].replace('SS','') | conditional_block |
Unity_K144.py | """Synchronize settings between FSW/SMW K144 5GNR personality"""
###############################################################################
### Code Import
### pylint: disable=bad-whitespace,invalid-name,line-too-long,unused-argument
### pylint: disable=bare-except,no-member
#######################################... | except:
botWind.writeN("DataLoad: Default")
def dataSave():
"""Save GUIT --> setting file """
# NR5G = gui_reader()
try: #Python3
f = open(__file__ + ".csv",'wt', encoding='utf-8')
except:
f = open(__file__ + ".csv",'wb')
f.write('%s,'%(entryCol.entry0.get()))
f.writ... | entryCol.entry3.delete(0,END)
entryCol.entry3.insert(0,data[3])
botWind.writeN("DataLoad: File") | random_line_split |
Unity_K144.py | """Synchronize settings between FSW/SMW K144 5GNR personality"""
###############################################################################
### Code Import
### pylint: disable=bad-whitespace,invalid-name,line-too-long,unused-argument
### pylint: disable=bare-except,no-member
#######################################... |
def clearTopWind(tkEvent):
"""Clear Top Window"""
topWind.clear()
topWind.writeH("===Please Click Buttons Below===")
RSVar = GUIData()
for item in RSVar.List1:
topWind.writeN(item)
def dataLoad():
"""Read setting file --> GUI"""
try:
try: #Python3
f =... | """Set RB Offset"""
botWind.writeN('FSW:Signal Description-->RadioFrame-->BWP Config-->RB Offset')
botWind.writeN('SMW:User/BWP-->UL BWP-->RB Offset') | identifier_body |
Unity_K144.py | """Synchronize settings between FSW/SMW K144 5GNR personality"""
###############################################################################
### Code Import
### pylint: disable=bad-whitespace,invalid-name,line-too-long,unused-argument
### pylint: disable=bare-except,no-member
#######################################... | (self):
self.List1 = ['- Utility does not validate settings against 3GPP 5G',
'- Click *IDN? to validate IP Addresses',
'- Frequency & SMW Power labels are clickable',
'']
def gui_reader():
"""Read values from GUI"""
SMW_IP = en... | __init__ | identifier_name |
lab1e.py | import math
import operator
import random
import re
import numpy as np
#STEP 1
import nltk
from nltk.corpus import brown
from sklearn.metrics.pairwise import cosine_similarity
from scipy.stats import pearsonr
#STEP 6. Table RG65 with lists P and S as defined in the lab.
P = [
('cord', 'smile'),
('rooster', 'voyage'... |
print('LSA semantic analogy accuracy: ', cnt, '/', 90)
#The below code will perform the analogy test for Word2Vec on the 90 semantic analogy tuples
Mw2 = np.zeros(shape=(5031,300))
for index, (i, j) in enumerate(uni, start=0):
try:
Mw2[index] = model[i]
except:
pass
cnt = 0
for ww in rel_wo... | Mw3[len(Mw3)-1] = M2_100[unigram[ww[0].lower()]] - M2_100[unigram[ww[1].lower()]] + M2_100[unigram[ww[3].lower()]]
SMw3 = cosine_similarity(Mw3)
max = -10
maxind = -1
for index, i in enumerate(SMw3[len(Mw3)-1], start=0):
if i > max and index < 5030 and uni[index][0] != ww[3].lower():
... | conditional_block |
lab1e.py | import math
import operator
import random
import re
import numpy as np
#STEP 1
import nltk
from nltk.corpus import brown
from sklearn.metrics.pairwise import cosine_similarity
from scipy.stats import pearsonr
#STEP 6. Table RG65 with lists P and S as defined in the lab.
P = [
('cord', 'smile'),
('rooster', 'voyage'... |
for index, (i, j) in enumerate(uni, start=0):
try:
Mw3[index] = M2_100[unigram[i]]
except:
pass
cnt = 0
for ww in rel_words[0:89]:
Mw3[len(Mw3)-1] = M2_100[unigram[ww[0].lower()]] - M2_100[unigram[ww[1].lower()]] + M2_100[unigram[ww[3].lower()]]
SMw3 = cosine_similarity(Mw3)
max =... | #instances in rel_words. It counts how many times LSA pick the right word for the analogy.
#(Note: picks the word from the pool of 5030 whose vector is closest in cosine distance to the
#added vectors)
Mw3 = np.zeros(shape=(5031,100)) | random_line_split |
serializers.py | from rest_framework import serializers
from rest_framework.fields import empty
from rest_framework.settings import api_settings
from .models import CitizenInfo, ImportId
from datetime import datetime
class TrueIntegerField(serializers.IntegerField):
"""
В DRF стандартный сериализатор IntegerField, какого-то... | if birth_date > current_date:
raise serializers.ValidationError("Birth_date can't be "
"after current date")
return value
def to_representation(self, instance):
"""
Корректируем отображение данных из БД.
m2m отображен... | """
birth_date = value
current_date = datetime.now().date() | random_line_split |
serializers.py | from rest_framework import serializers
from rest_framework.fields import empty
from rest_framework.settings import api_settings
from .models import CitizenInfo, ImportId
from datetime import datetime
class TrueIntegerField(serializers.IntegerField):
"""
В DRF стандартный сериализатор IntegerField, какого-то... |
def save_citizens(citizen_data, new_import):
"""Логика полного сохранения гражданина"""
new_citizen = CitizenInfo(import_id=new_import,
citizen_id=citizen_data.get('citizen_id'),
town=citizen_data.get('town'),
street=ci... | "name": instance.name,
"birth_date": JSON_birth_date,
"gender": instance.gender,
"relatives": relatives_id_list
} | conditional_block |
serializers.py | from rest_framework import serializers
from rest_framework.fields import empty
from rest_framework.settings import api_settings
from .models import CitizenInfo, ImportId
from datetime import datetime
class TrueIntegerField(serializers.IntegerField):
"""
В DRF стандартный сериализатор IntegerField, какого-то... | elatives_id_list.sort()
# Нужный формат дня рождения
JSON_birth_date = datetime.strptime(str(instance.birth_date),
'%Y-%m-%d').strftime('%d.%m.%Y')
# Составляем ответ вручную
return {
"citizen_id": instance.citizen_id,
"... | ражении
r | identifier_name |
serializers.py | from rest_framework import serializers
from rest_framework.fields import empty
from rest_framework.settings import api_settings
from .models import CitizenInfo, ImportId
from datetime import datetime
class TrueIntegerField(serializers.IntegerField):
"""
В DRF стандартный сериализатор IntegerField, какого-то... | relatives_pk_list = []
for citizen_id in value:
# Проверяем, существует ли родственник с таким id
try:
citizen_pk = CitizenInfo.objects.get(import_id=import_id,
citizen_id=citizen_id).pk
except:
... | твенников" его родственника,
# Что бы не проверять по два раза. Сохранению не помешает.
relatives_dict[relative_id].remove(citizen_id)
# Если находим несовпадение, то сразу отдаем 400 BAD_REQUEST
elif citizen_id not in relatives_dict[relative_id]:
... | identifier_body |
server.go | package apiserver
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"sync/atomic"
"github.com/felixge/httpsnoop"
"github.com/gorilla/mux"
"github.com/openaustralia/yinyo/pkg/commands"
"github.com/openaustralia/yinyo/pkg/integrationclient"
"github.com/openaustralia/yinyo/pkg/protoc... | if !created {
err = newHTTPError(err, http.StatusNotFound, fmt.Sprintf("run %v: not found", runID))
logAndReturnError(err, w)
return
}
next.ServeHTTP(w, r)
})
}
func logAndReturnError(err error, w http.ResponseWriter) {
log.Println(err)
err2, ok := err.(clientError)
if !ok {
// TODO: Factor out c... | logAndReturnError(err, w)
return
} | random_line_split |
server.go | package apiserver
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"sync/atomic"
"github.com/felixge/httpsnoop"
"github.com/gorilla/mux"
"github.com/openaustralia/yinyo/pkg/commands"
"github.com/openaustralia/yinyo/pkg/integrationclient"
"github.com/openaustralia/yinyo/pkg/protoc... | (w http.ResponseWriter, r *http.Request) error {
createResult, err := server.app.CreateRun(protocol.CreateRunOptions{APIKey: r.URL.Query().Get("api_key")})
if err != nil {
if errors.Is(err, integrationclient.ErrNotAllowed) {
return newHTTPError(err, http.StatusUnauthorized, err.Error())
}
return err
}
w.H... | createRun | identifier_name |
server.go | package apiserver
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"sync/atomic"
"github.com/felixge/httpsnoop"
"github.com/gorilla/mux"
"github.com/openaustralia/yinyo/pkg/commands"
"github.com/openaustralia/yinyo/pkg/integrationclient"
"github.com/openaustralia/yinyo/pkg/protoc... |
func (server *Server) getCache(w http.ResponseWriter, r *http.Request) error {
runID := mux.Vars(r)["id"]
reader, err := server.app.GetCache(runID)
if err != nil {
// Returns 404 if there is no cache
if errors.Is(err, commands.ErrNotFound) {
return newHTTPError(err, http.StatusNotFound, err.Error())
}
r... | {
runID := mux.Vars(r)["id"]
err := server.app.PutApp(runID, r.Body, r.ContentLength)
if errors.Is(err, commands.ErrArchiveFormat) {
return newHTTPError(err, http.StatusBadRequest, err.Error())
}
return err
} | identifier_body |
server.go | package apiserver
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"sync/atomic"
"github.com/felixge/httpsnoop"
"github.com/gorilla/mux"
"github.com/openaustralia/yinyo/pkg/commands"
"github.com/openaustralia/yinyo/pkg/integrationclient"
"github.com/openaustralia/yinyo/pkg/protoc... |
}
})
}
// Middleware function, which will be called for each request
// TODO: Refactor checkRunCreated method to return an error
func (server *Server) checkRunCreated(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
runID := mux.Vars(r)["id"]
created, e... | {
// TODO: Will this actually work here
logAndReturnError(err, w)
return
} | conditional_block |
saga.ts | import {
generateKeys,
invalidMnemonicWords,
normalizeMnemonic,
suggestMnemonicCorrections,
validateMnemonic,
} from '@celo/utils/lib/account'
import { privateKeyToAddress } from '@celo/utils/lib/address'
import * as bip39 from 'react-native-bip39'
import {
call,
cancel,
delay,
fork,
join,
put,
... |
// If the given mnemonic phrase is invalid, spend up to 5 seconds trying to correct it.
// A balance check happens before the phrase is returned, so if the phrase was autocorrected,
// we do not need to check the balance again later in this method.
// If useEmptyWallet is true, skip this step. It only... | {
ValoraAnalytics.track(OnboardingEvents.wallet_import_phrase_invalid, {
wordCount: countMnemonicWords(normalizedPhrase),
invalidWordCount: invalidWords?.length,
})
} | conditional_block |
saga.ts | import {
generateKeys,
invalidMnemonicWords,
normalizeMnemonic,
suggestMnemonicCorrections,
validateMnemonic,
} from '@celo/utils/lib/account'
import { privateKeyToAddress } from '@celo/utils/lib/address'
import * as bip39 from 'react-native-bip39'
import {
call,
cancel,
delay,
fork,
join,
put,
... | mnemonic = correctedPhrase
checkedBalance = true
} else {
Logger.info(
TAG + '@importBackupPhraseSaga',
`Backup phrase autocorrection ${timeout ? 'timed out' : 'failed'}`
)
ValoraAnalytics.track(OnboardingEvents.wallet_import_phrase_corre... | correctedPhrase: call(attemptBackupPhraseCorrection, normalizedPhrase),
timeout: delay(MNEMONIC_AUTOCORRECT_TIMEOUT),
})
if (correctedPhrase) {
Logger.info(TAG + '@importBackupPhraseSaga', 'Using suggested mnemonic autocorrection') | random_line_split |
agent.py | import os
import time
from datetime import datetime
import math
import glob
import gym
import tensorflow as tf
import numpy as np
import config as c
import deepdrive
from gym_deepdrive.envs.deepdrive_gym_env import Action
from tensorflow_agent.net import Net
from utils import save_hdf5, download
import logs
log = lo... | (self, obz, y):
log.debug('getting next action')
if y is None:
log.debug('net out is None')
return self.previous_action or Action()
desired_spin, desired_direction, desired_speed, desired_speed_change, desired_steering, desired_throttle = y[0]
desired_spin = des... | get_next_action | identifier_name |
agent.py | import os
import time
from datetime import datetime
import math
import glob
import gym
import tensorflow as tf
import numpy as np
import config as c
import deepdrive
from gym_deepdrive.envs.deepdrive_gym_env import Action
from tensorflow_agent.net import Net
from utils import save_hdf5, download
import logs
log = lo... |
elif 0.67 <= rand < 0.85:
self.random_action_count = 4
self.non_random_action_count = 5
elif 0.85 <= rand < 0.95:
self.random_action_count = 8
self.non_random_action_count = 10
else:
self.random_action_c... | self.random_action_count = 0
self.non_random_action_count = 10 | conditional_block |
agent.py | import os | import glob
import gym
import tensorflow as tf
import numpy as np
import config as c
import deepdrive
from gym_deepdrive.envs.deepdrive_gym_env import Action
from tensorflow_agent.net import Net
from utils import save_hdf5, download
import logs
log = logs.get_log(__name__)
class Agent(object):
def __init__(sel... | import time
from datetime import datetime
import math | random_line_split |
agent.py | import os
import time
from datetime import datetime
import math
import glob
import gym
import tensorflow as tf
import numpy as np
import config as c
import deepdrive
from gym_deepdrive.envs.deepdrive_gym_env import Action
from tensorflow_agent.net import Net
from utils import save_hdf5, download
import logs
log = lo... |
session_done = False
episode = 0
try:
while not session_done:
if episode_done:
obz = gym_env.reset()
episode_done = False
else:
obz = None
while not episode_done:
action = agent.act(obz, reward, epi... | gym_env.close()
agent.close() | identifier_body |
AddSlotModal.js | import React from 'react';
import {Modal, Text, TextInput, TouchableOpacity,StyleSheet,ScrollView,View,ActivityIndicator} from 'react-native';
import Icon from 'react-native-vector-icons/dist/Feather';
import ModalDropdown from 'react-native-modal-dropdown';
import DateTimePickerModal from "react-native-modal-datetime... | onBackdropPress={this.props.closeModal}>
<ScrollView style={styles.scrollView}>
<View style={styles.container}>
<View style={styles.sectionHeader}>
<View style={styles.sectionHeading}>
<Text style={styles.sectio... | onSwipe={this.props.closeModal} | random_line_split |
AddSlotModal.js | import React from 'react';
import {Modal, Text, TextInput, TouchableOpacity,StyleSheet,ScrollView,View,ActivityIndicator} from 'react-native';
import Icon from 'react-native-vector-icons/dist/Feather';
import ModalDropdown from 'react-native-modal-dropdown';
import DateTimePickerModal from "react-native-modal-datetime... | extends React.Component {
state = {
datePickerMode:'',
isDatePickerVisible:false,
startTime:'',
endTime:'',
weekDay: '',
isLoading:false,
errors:[]
};
weekDays = ['Mon', 'Tues','Wed','Thur','Fri', 'Sat', 'Sun'];
getCurrentTime = (date) => {
let hours = date.getHour... | AddSlotModal | identifier_name |
Home.js | import React, { Component } from 'react';
import { connect } from 'react-redux'
import EpisodeItem from '../EpisodeItem/EpisodeItem';
import Compile from '../Compile/Compile';
import { getHomeList, clearHomeData } from '../../actions/home';
import { showCompile } from '../../actions/compileStatus';
import { getClassif... | // import Storage from '../../tools/storage'
import Storage from '../../libs/storage';
import VTouch from '../Live/Refresh';
import Tracker from '../../tracker';
import { browserHistory, hashHistory} from 'react-router';
const history = window.config.hashHistory ? hashHistory : browserHistory
import './home.css';
c... | import { getChannels } from '../../actions/compile';
import Immutable from 'immutable';
import ToolKit from '../../tools/tools' | random_line_split |
Home.js | import React, { Component } from 'react';
import { connect } from 'react-redux'
import EpisodeItem from '../EpisodeItem/EpisodeItem';
import Compile from '../Compile/Compile';
import { getHomeList, clearHomeData } from '../../actions/home';
import { showCompile } from '../../actions/compileStatus';
import { getClassif... | his.context.store.dispatch(getHomeList(this.state.index, this.firstUpKey, this.lastUpKey, this.handle))
Tracker.track('send', 'event', 'app', 'pull', 'up', 1);
}
}
render () {
let style, childStyle, spinner = '';
if (this.state.firstLoading) {
style = {
position: 'fixed',
... | 'up';
t | identifier_name |
Home.js | import React, { Component } from 'react';
import { connect } from 'react-redux'
import EpisodeItem from '../EpisodeItem/EpisodeItem';
import Compile from '../Compile/Compile';
import { getHomeList, clearHomeData } from '../../actions/home';
import { showCompile } from '../../actions/compileStatus';
import { getClassif... | ore.dispatch(clearHomeData());
this.fromScroll = false;
this.setState({
index: Number(i),
firstLoading: true,
isUpLoading: true
})
//设置页面返回定义key
Storage.s_set(Storage.KEYS.BACK_KEY, Number(i))
Storage.s_set(Storage.KEYS.BACK_POSITION_KEY, Number(index))
let active = document.querySelector('.a... | his.lastDownKey : this.end;
this.context.store.dispatch(getHomeList(this.state.index, firstDownKey, lastDownKey, this.handle));
Tracker.track('send', 'event', 'app', 'pull', 'down', 1);
console.log('=========下拉刷新==========');
}
}
navHandleClick(i, index) {
//index表示当前元素在nav中的index位数
let linkageKey;
... | identifier_body |
Home.js | import React, { Component } from 'react';
import { connect } from 'react-redux'
import EpisodeItem from '../EpisodeItem/EpisodeItem';
import Compile from '../Compile/Compile';
import { getHomeList, clearHomeData } from '../../actions/home';
import { showCompile } from '../../actions/compileStatus';
import { getClassif... | .s_remove(Storage.KEYS.HOME_SCROLL_KEY);
}
if ( nextProps.getHomeData.data && nextProps.getHomeData.data.data.length > 0) {
this.refreshKey = false;
let newPropsObj = nextProps.getHomeData.data;
let newPropsData = newPropsObj.data;
this.handle === 'up' ? this.isUpLoading = newPropsObj.loadMore : this.i... | = Storage.s_get(Storage.KEYS.HOME_SCROLL_KEY)
this.Touch.init();
Storage | conditional_block |
word_module_trials07.py | import math
from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.shared import RGBColor
document = Document()
#the following variable is to know i... |
str1 = question_header[x]
#for choices:
choices = question_choices[x].split(',,__,,')
choices_lines_count = 0
for choice in choices:
#89 is the max number of charcters written in a line of choices
choices_lines_count += math.ceil(len(choice)/89)*11 + 9 #10
#check if end of page or not
curre... | #write the multiple choice questions
myAddPageBreak()
for x in range(len(question_header)):
| random_line_split |
word_module_trials07.py | import math
from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.shared import RGBColor
document = Document()
#the following variable is to know i... |
row = table_merge.rows[3].cells
row[0].text = '\nID: '
paragraphs = row[0].paragraphs
for paragraph in paragraphs:
for run in paragraph.runs:
font = run.font
font.size= Pt(14)
a = table_merge.cell(0, 0)
b = table_merge.cell(5, 1)
A = a.merge(b)
#add notes
my_add_paragraph("\n\n\t\t\t\tImpor... | font = run.font
font.size= Pt(14) | conditional_block |
word_module_trials07.py | import math
from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.shared import RGBColor
document = Document()
#the following variable is to know i... | ():
#we get the following list from DB test ----------------------------------------------
question_header = ["there is very little .... from the factory, so it's nor bad for the environment", \
"here is your ticket for the museum , the ticket is ....... for two days." , \
... | get_mcq | identifier_name |
word_module_trials07.py | import math
from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.shared import RGBColor
document = Document()
#the following variable is to know i... |
def get_choices():
#we get the following list from DB test ----------------------------------------------
#split choices using ",,__,,"
question_choices = ["waste,,__,,wave,,__,,wildlife,,__,,weight" , "virtual,,__,,valid,,__,,vinegar,,__,,vapour" , \
"child,,__,,childhood,,__,,ch... | question_header = ["there is very little .... from the factory, so it's nor bad for the environment", \
"here is your ticket for the museum , the ticket is ....... for two days." , \
"ola spent most of her ..... living on a farm , but she moved to cairo when she was sixteen",\
... | identifier_body |
displayTopology.js | define(function(require, exports, module){
require('jquery');
var DATA = {};
var Tips = require('Tips');
var Translate = require('Translate');
var dicArr = ['common','doSoftMgnt','doEqMgmt'];
function T(_str){
return Translate.getValue(_str, dicArr);
}
function tall(dom){
return Tran... | 'left' :'308px'
})
aparr.push($noap);
}
*/
return aparr;
}
function getAPDom(index,ip,ssid,ssid5,cnl,cnl5,serial,apstatus,clienCt,mac){
var $ap = $('<div class="ap_signle_cover_div"></div>');
$ap.css({
// 'opacity':'0.2',
'transition':'all 0.3s',
'color' :'#000000'... | random_line_split | |
displayTopology.js | define(function(require, exports, module){
require('jquery');
var DATA = {};
var Tips = require('Tips');
var Translate = require('Translate');
var dicArr = ['common','doSoftMgnt','doEqMgmt'];
function T(_str){
return Translate.getValue(_str, dicArr);
}
function tall(dom){
return Tran... | r Modal = require('Modal');
var modalObj = Modal.getModalObj(modallist);
var TableContainer = require('P_template/common/TableContainer');
var conhtml = TableContainer.getHTML({}),
$tableCon = $(conhtml);
modalObj.insert($tableCon);
var headData = {
"btns" : []
};
/... |
};
va | identifier_name |
displayTopology.js | define(function(require, exports, module){
require('jquery');
var DATA = {};
var Tips = require('Tips');
var Translate = require('Translate');
var dicArr = ['common','doSoftMgnt','doEqMgmt'];
function T(_str){
return Translate.getValue(_str, dicArr);
}
function tall(dom){
return Tran... | lse if(apsdata.apcount == 3){
aparr[0].css({
top:'250px',
left:'45px'
});
aparr[1].css({
top:'250px',
left:'300px'
});
aparr[2].css({
top:'250px',
left:'565px'
});
}else if(apsdata.apcount == 2){
aparr[0].css({
top:'250px',
left:'100px'
});
... | .css({
top:'250px',
left:'10px'
});
aparr[1].css({
top:'250px',
left:'215px'
});
aparr[2].css({
top:'250px',
left:'420px'
});
aparr[3].css({
top:'250px',
left:'630px'
});
}e | conditional_block |
displayTopology.js | define(function(require, exports, module){
require('jquery');
var DATA = {};
var Tips = require('Tips');
var Translate = require('Translate');
var dicArr = ['common','doSoftMgnt','doEqMgmt'];
function T(_str){
return Translate.getValue(_str, dicArr);
}
function tall(dom){
return Tran... | require('Modal');
var modalObj = Modal.getModalObj(modallist);
var TableContainer = require('P_template/common/TableContainer');
var conhtml = TableContainer.getHTML({}),
$tableCon = $(conhtml);
modalObj.insert($tableCon);
var headData = {
"btns" : []
};
// 表格配置数据
... | identifier_body | |
step3-twist.py | import os
import pandas as pd
import time
import sys
from tqdm import tqdm
sys.path.append(os.path.join(os.environ['HOME'],'Working/interaction/'))
from src.make import exec_gjf
from src.vdw import vdw_R, get_c_vec_vdw
from src.utils import get_E
import argparse
import numpy as np
from scipy import signal
i... | nit_params.csvとstep3-twist.csvがauto_dirの下にある
"""
init_params_csv=os.path.join(auto_dir, 'step3-twist_init_params.csv')
df_init_params = pd.read_csv(init_params_csv)
df_cur = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))
df_init_params_inprogress = df_init_params[df_init_params['status'... | (df_E, params_dict)
df_E_filtered = df_E_filtered.reset_index(drop=True)
try:
status = get_values_from_df(df_E_filtered,0,'status')
return status=='Done'
except KeyError:
return False
def get_params_dict(auto_dir, num_nodes, fixed_param_keys, opt_param_keys, monomer_name):
... | identifier_body |
step3-twist.py | import os
import pandas as pd
import time
import sys
from tqdm import tqdm
sys.path.append(os.path.join(os.environ['HOME'],'Working/interaction/'))
from src.make import exec_gjf
from src.vdw import vdw_R, get_c_vec_vdw
from src.utils import get_E
import argparse
import numpy as np
from scipy import signal
i... | param_keys].to_dict()
fixed_params_dict = df_init_params.loc[index,fixed_param_keys].to_dict()
isDone, opt_params_dict = get_opt_params_dict(df_cur, init_params_dict,fixed_params_dict, monomer_name)
if isDone:
# df_init_paramsのstatusをupdate
df_init_params = update_va... | n_df(df_init_params,index,'status','InProgress')
df_init_params.to_csv(init_params_csv,index=False)
params_dict = df_init_params.loc[index,fixed_param_keys+opt_param_keys].to_dict()
return params_dict
for index in df_init_params.index:
df_init_params = pd.read_csv(in... | conditional_block |
step3-twist.py | import os
import pandas as pd
import time
import sys
from tqdm import tqdm
sys.path.append(os.path.join(os.environ['HOME'],'Working/interaction/'))
from src.make import exec_gjf
from src.vdw import vdw_R, get_c_vec_vdw
from src.utils import get_E
import argparse
import numpy as np
from scipy import signal
i... | ==str:
query.append('{} == "{}"'.format(k,v))
else:
query.append('{} == {}'.format(k,v))
df_filtered = df.query(' and '.join(query))
return df_filtered
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--init',action='store... | if type(v) | identifier_name |
step3-twist.py | import os
import pandas as pd
import time
import sys
from tqdm import tqdm
sys.path.append(os.path.join(os.environ['HOME'],'Working/interaction/'))
from src.make import exec_gjf
from src.vdw import vdw_R, get_c_vec_vdw
from src.utils import get_E
import argparse
import numpy as np
from scipy import signal
i... | for index in df_init_params.index:
df_init_params = pd.read_csv(init_params_csv)
init_params_dict = df_init_params.loc[index,fixed_param_keys+opt_param_keys].to_dict()
fixed_params_dict = df_init_params.loc[index,fixed_param_keys].to_dict()
isDone, opt_params_dict = get_opt_param... | df_init_params = update_value_in_df(df_init_params,index,'status','InProgress')
df_init_params.to_csv(init_params_csv,index=False)
params_dict = df_init_params.loc[index,fixed_param_keys+opt_param_keys].to_dict()
return params_dict
| random_line_split |
lib.rs | use bevy::{
prelude::*,
render::camera::Camera,
render::color::Color,
render::mesh::{VertexAttribute, VertexAttributeValues},
render::pipeline::PrimitiveTopology,
window::CursorMoved,
};
pub struct PickingPlugin;
impl Plugin for PickingPlugin {
fn build(&self, app: &mut AppBuilder) {
... |
}
impl Default for PickState {
fn default() -> Self {
PickState {
cursor_event_reader: EventReader::default(),
ordered_pick_list: Vec::new(),
topmost_pick: None,
}
}
}
/// Holds the entity associated with a mesh as well as it's computed intersection from a ... | {
&self.topmost_pick
} | identifier_body |
lib.rs | use bevy::{
prelude::*,
render::camera::Camera,
render::color::Color,
render::mesh::{VertexAttribute, VertexAttributeValues},
render::pipeline::PrimitiveTopology,
window::CursorMoved,
};
pub struct PickingPlugin;
impl Plugin for PickingPlugin {
fn build(&self, app: &mut AppBuilder) {
... | // Find the maximum signed z value
let max_z = triangle
.iter()
.fold(-1.0, |max, x| if x.z() > max { x.z() } else { max });
// If the maximum z value is less than zero, all vertices are behind the camera
max_z < 0.0
} | fn triangle_behind_cam(triangle: [Vec3; 3]) -> bool { | random_line_split |
lib.rs | use bevy::{
prelude::*,
render::camera::Camera,
render::color::Color,
render::mesh::{VertexAttribute, VertexAttributeValues},
render::pipeline::PrimitiveTopology,
window::CursorMoved,
};
pub struct PickingPlugin;
impl Plugin for PickingPlugin {
fn build(&self, app: &mut AppBuilder) {
... | (&self) -> &Vec<PickIntersection> {
&self.ordered_pick_list
}
pub fn top(&self) -> &Option<PickIntersection> {
&self.topmost_pick
}
}
impl Default for PickState {
fn default() -> Self {
PickState {
cursor_event_reader: EventReader::default(),
ordered_pick... | list | identifier_name |
lib.rs | use bevy::{
prelude::*,
render::camera::Camera,
render::color::Color,
render::mesh::{VertexAttribute, VertexAttributeValues},
render::pipeline::PrimitiveTopology,
window::CursorMoved,
};
pub struct PickingPlugin;
impl Plugin for PickingPlugin {
fn build(&self, app: &mut AppBuilder) {
... | else {
*current_color = initial_color;
}
}
// Query highlightable entities that have changed
for (mut highlightable, _pickable, material_handle, entity) in &mut query_picked.iter() {
let current_color = &mut materials.get_mut(material_handle).unwrap().albedo;
let initia... | {
*current_color = highlight_params.selection_color;
} | conditional_block |
lib.rs | // Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any late... |
}
/// A per-relay-parent job for the provisioning subsystem.
pub struct ProvisioningJob {
relay_parent: Hash,
receiver: mpsc::Receiver<ProvisionerMessage>,
backed_candidates: Vec<CandidateReceipt>,
signed_bitfields: Vec<SignedAvailabilityBitfield>,
metrics: Metrics,
inherent_after: InherentAfter,
awaiting_inhe... | {
match *self {
InherentAfter::Ready => {
// Make sure we never end the returned future.
// This is required because the `select!` that calls this future will end in a busy loop.
futures::pending!()
},
InherentAfter::Wait(ref mut d) => {
d.await;
*self = InherentAfter::Ready;
},
}
} | identifier_body |
lib.rs | // Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any late... | for bitfield in bitfields {
let validator_idx = bitfield.validator_index().0 as usize;
match availability.get_mut(validator_idx) {
None => {
// in principle, this function might return a `Result<bool, Error>` so that we can more clearly express this error condition
// however, in practice, that would ju... | ) -> bool {
let mut availability = availability.clone();
let availability_len = availability.len();
| random_line_split |
lib.rs | // Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any late... | (
relay_parent: Hash,
metrics: Metrics,
receiver: mpsc::Receiver<ProvisionerMessage>,
) -> Self {
Self {
relay_parent,
receiver,
backed_candidates: Vec::new(),
signed_bitfields: Vec::new(),
metrics,
inherent_after: InherentAfter::new_from_now(),
awaiting_inherent: Vec::new(),
}
}
asyn... | new | identifier_name |
lib.rs | // Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any late... |
}
#[tracing::instrument(level = "trace", skip(self), fields(subsystem = LOG_TARGET))]
fn note_provisionable_data(&mut self, span: &jaeger::Span, provisionable_data: ProvisionableData) {
match provisionable_data {
ProvisionableData::Bitfield(_, signed_bitfield) => {
self.signed_bitfields.push(signed_bitfie... | {
self.metrics.on_inherent_data_request(Ok(()));
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.