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 |
|---|---|---|---|---|
lib.rs | : usize, width: usize) -> Option<Bitmap> {
if width > (std::mem::size_of::<usize>() * 8) || width == 0 {
None
} else {
entries.checked_mul(width)
.and_then(|bits| bits.checked_add(8 - (bits % 8)))
.and_then(|rbits| rbits.checked_div(8))
.and_th... |
while bits_left > 0 {
let can_set = std::cmp::min(8 - in_byte_offset, bits_left);
// pull out the highest can_set bits from value
let mut to_set: usize = value >> (usize - can_set);
// move them into where they will live
to_se... | let mut bits_left = self.width; | random_line_split |
lib.rs | : usize, width: usize) -> Option<Bitmap> {
if width > (std::mem::size_of::<usize>() * 8) || width == 0 {
None
} else {
entries.checked_mul(width)
.and_then(|bits| bits.checked_add(8 - (bits % 8)))
.and_then(|rbits| rbits.checked_div(8))
.and_th... |
pub fn iter(&self) -> Slices {
Slices { idx: 0, bm: self }
}
/// Get the raw pointer to this Bitmap's data.
pub unsafe fn get_ptr(&self) -> *mut u8 {
self.data
}
/// Set the raw pointer to this Bitmap's data, returning the old one. It needs to be free'd
/// with `Vec`'s d... | {
// can't overflow, since creation asserts that it doesn't.
let w = self.entries * self.width;
let r = w % 8;
(w + r) / 8
} | identifier_body |
message.go | interface implementation here).
******************************************************************************/
/*
Interface type: For messages sent to the application server.
*/
type MessageServer interface {
tcp(l *Lobby)
socketio(l *Lobby)
}
/*
An application specific message from a User.
*/
type MsgServer st... |
(*l.tcpConn).Write(jsonMsg)
}
func (n NewSession) socketio(l *Lobby) {
(*l.socket).Emit("in", n)
}
/*
Sends an event from the Host User to inform the Application server that
it has loaded the Application and is ready to communicate.
Also implements Command (multiple interface implementation)
*/
type Launch str... | {
log.Print(err)
return
} | conditional_block |
message.go | new interface implementation here).
******************************************************************************/
/*
Interface type: For messages sent to the application server.
*/
type MessageServer interface {
tcp(l *Lobby)
socketio(l *Lobby)
}
/*
An application specific message from a User.
*/
type MsgServe... | }
/*
Interface type: Commands received by the lobby for accessing/changing
the lobby data structure.
*/
type Command interface {
execute(l *Lobby)
}
/*
Contains all potential fields in the three specified events received from
Application servers: "created", "msgplayer" and "msgall"
Using omitempty, only requi... | (*l.tcpConn).Write(jsonMsg)
}
func (e End) socketio(l *Lobby) {
(*l.socket).Emit("in", e) | random_line_split |
message.go | new interface implementation here).
******************************************************************************/
/*
Interface type: For messages sent to the application server.
*/
type MessageServer interface {
tcp(l *Lobby)
socketio(l *Lobby)
}
/*
An application specific message from a User.
*/
type MsgServe... | (l *Lobby) {
if len(l.users) != 0 {
(*h.Socket).Emit("hostlobby", false)
log.Print("manager.desktopSetup: lobby id entered already has a host user.")
return
}
err := l.addNewUser(h.Username, h.Socket)
if err != nil {
(*h.Socket).Emit("hostlobby", false)
log.Print(err)
return
}
(*h.Socket).Emit("hostlo... | execute | identifier_name |
message.go | interface implementation here).
******************************************************************************/
/*
Interface type: For messages sent to the application server.
*/
type MessageServer interface {
tcp(l *Lobby)
socketio(l *Lobby)
}
/*
An application specific message from a User.
*/
type MsgServer st... |
/*
An event to force emit update for the list of users in the lobby.
*/
type Update struct {}
func (u Update) execute(l *Lobby) {
l.updateLobby()
}
/*
An event to attempt to prepare the Application server to begin the Application.
*/
type Start struct {}
func (s Start) execute(l *Lobby) {
room := l.lobbyId
va... | {
if len(l.users) == 0 {
(*j.Socket).Emit("joinlobby", false)
log.Print("manager.desktopSetup: lobby id entered does not have a host user.")
return
}
err := l.addNewUser(j.Username, j.Socket)
if err != nil {
(*j.Socket).Emit("joinlobby", false)
log.Print(err)
return
}
(*j.Socket).Emit("joinlobby", tru... | identifier_body |
ja-jp.ts | PlaylistOverviewDesignMessage: "使用中、この領域には、表示されている再生リスト内の他の資産が表示されます。",
PlaylistOverviewHeading: "再生リストのすべての手順",
BurgerButton: "バーガー",
LinkButton: "リンク",
SearchButton: "検索",
AdministerPlaylist: "再生リストの管理",
NoSearchResults: "検索結果がクエリと一致しません。",
DefaultCDNLabel: "学習ソースを選択する",
DefaultCDN... | LinkPanelCopyLabel: "コピー",
HeaderPlaylistPanelCurrentPlaylistLabel: "現在の再生リスト:",
HeaderPlaylistPanelAdminHeader: "管理", | random_line_split | |
torrent.go | != 0 {
if err := os.MkdirAll(path, 0700); err != nil {
return err
}
}
length := v["length"].(int64)
file, err := os.OpenFile(fullPath, os.O_RDWR, 0600)
if err == nil {
torrent.findCompletedPieces(file, begin, length, k)
file.Close()
}
torrent.files = append(torrent.files, File... | {
if res := torrent.totalSize % torrent.pieceLength; res != 0 {
return res
}
return torrent.pieceLength
} | identifier_body | |
torrent.go | announce"].(string))
}
if comment, ok := data["comment"]; ok {
torrent.comment = comment.(string)
}
info := data["info"].(map[string]interface{})
torrent.name = info["name"].(string)
torrent.pieceLength = info["piece length"].(int64)
infoHash := sha1.Sum(bencode.Encode(info))
// Set handshake
var buffer ... | } else {
if n, err := handle.ReadAt(buf[:bufPos], f.length-bufPos); err != nil || int64(n) != bufPos {
return
}
break
}
}
if torrent.checkPieceHash(buf[:pieceLength], pieceIndex) {
torrent.pieces[pieceIndex].done = true
torrent.completedPieces++
}
pos += pieceLength
pieceIndex++
... | }
bufPos -= f.length | random_line_split |
torrent.go | 4)
}
// Multiple files
var begin int64
for k, v := range files.([]interface{}) {
v := v.(map[string]interface{})
// Set up directory structure
pathList := v["path"].([]interface{})
pathElements := []string{dirName}
for i := 0; i < len(pathList)-1; i++ {
pathElements = append(pathElements, p... | {
select {
case trackerID := <-torrent.stoppedTrackerChannel:
for k, v := range torrent.activeTrackers {
if v == trackerID {
torrent.activeTrackers = append(torrent.activeTrackers[:k], torrent.activeTrackers[k+1:]...)
break
}
}
// Handle other messages that a Tracker may send
c... | conditional_block | |
torrent.go | )-1].(string))
if err := torrent.validatePath(base, fullPath); err != nil {
return err
}
if len(path) != 0 {
if err := os.MkdirAll(path, 0700); err != nil {
return err
}
}
length := v["length"].(int64)
file, err := os.OpenFile(fullPath, os.O_RDWR, 0600)
if err == nil {
torre... | getLastPieceLength | identifier_name | |
project_config.py | 1[0:len(LINKFLAG1) - 1]
HighTecDirNOW = self.HithTecDir.text()
DebugNameNOW = self.ProjectName.text()
inn = self.includeList.count()
inpathNOW = []
exn = self.excludeList.count()
expathNOW = []
Ln = self.Llist.count()
LnNOW = []
ln = self.llist.co... | conditional_block | ||
project_config.py |
class BackendTread1(QThread):
startcompile1 = pyqtSignal(str)
endSig = pyqtSignal()
def __init__(self, parent=None):
super(BackendTread1, self).__init__(parent)
def startCom(self):
self.process = subprocess.Popen(cmd1)
def run(self):
#cmd1 = r'''%s\bin\make -j8 all >consol... | pyqtSignal(int)
def __init__(self, parent=None):
super(BackendTread, self).__init__(parent)
self.working=True
def stopSig(self):
self.working=False
def run(self):
#cmd1 = r'''%s\bin\make -j8 all >console.log 2>&1''' % Hdir
'''os.chdir(self.ProjectName_2.text() + '/De... | identifier_body | |
project_config.py | self.working=False
def run(self):
#cmd1 = r'''%s\bin\make -j8 all >console.log 2>&1''' % Hdir
'''os.chdir(self.ProjectName_2.text() + '/Default')
self.process = subprocess.call(cmd1)'''
while VAL<NUM and self.working:
num=0
for path,dir,files in os.walk(... | lf):
| identifier_name | |
project_config.py | .connect(self.DelLibraryPath)
self.lWUI = Enterlibraries.Ui_LSelect()
self.lWin = QWidget()
self.lWin.setWindowModality(Qt.ApplicationModal)
self.lWUI.setupUi(self.lWin)
self.LWUI.LibraryP.setText("")
self.add2.clicked.connect(self.lWin.show)
self.lWUI.l_OK.clic... | ln = self.llist.count()
lnNOW = []
try: | random_line_split | |
feature.pb.go | int) { return fileDescriptor0, []int{3} }
type isFeature_Kind interface {
isFeature_Kind()
}
type Feature_BytesList struct {
BytesList *BytesList `protobuf:"bytes,1,opt,name=bytes_list,json=bytesList,oneof"`
}
type Feature_FloatList struct {
FloatList *FloatList `protobuf:"bytes,2,opt,name=float_list,json=floatLis... | () string { return proto.CompactTextString(m) }
func (*FeatureList) ProtoMessage() {}
func (*FeatureList) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
func (m *FeatureList) GetFeature() []*Feature {
if m != nil {
return m.Feature
}
return nil
}
type FeatureLists stru... | String | identifier_name |
feature.pb.go | ) { return fileDescriptor0, []int{3} }
type isFeature_Kind interface {
isFeature_Kind()
}
type Feature_BytesList struct {
BytesList *BytesList `protobuf:"bytes,1,opt,name=bytes_list,json=bytesList,oneof"`
}
type Feature_FloatList struct {
FloatList *FloatList `protobuf:"bytes,2,opt,name=float_list,json=floatList,o... |
func init() { proto.RegisterFile("tensorflow/core/example/feature.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 371 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xdf, 0x4a, 0xc3, 0x30,
0x14, 0xc6, 0x4d, 0xab, 0x9b, 0x3d, 0x9d, 0x30, 0... | {
proto.RegisterType((*BytesList)(nil), "tensorflow.BytesList")
proto.RegisterType((*FloatList)(nil), "tensorflow.FloatList")
proto.RegisterType((*Int64List)(nil), "tensorflow.Int64List")
proto.RegisterType((*Feature)(nil), "tensorflow.Feature")
proto.RegisterType((*Features)(nil), "tensorflow.Features")
proto.Re... | identifier_body |
feature.pb.go | ) { return fileDescriptor0, []int{3} }
type isFeature_Kind interface {
isFeature_Kind()
}
type Feature_BytesList struct {
BytesList *BytesList `protobuf:"bytes,1,opt,name=bytes_list,json=bytesList,oneof"`
}
type Feature_FloatList struct {
FloatList *FloatList `protobuf:"bytes,2,opt,name=float_list,json=floatList,o... |
msg := new(BytesList)
err := b.DecodeMessage(msg)
m.Kind = &Feature_BytesList{msg}
return true, err
case 2: // kind.float_list
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(FloatList)
err := b.DecodeMessage(msg)
m.Kind = &Feature_FloatList{msg}
return true,... | {
return true, proto.ErrInternalBadWireType
} | conditional_block |
feature.pb.go | type Int64List struct {
Value []int64 `protobuf:"varint,1,rep,packed,name=value" json:"value,omitempty"`
}
func (m *Int64List) Reset() { *m = Int64List{} }
func (m *Int64List) String() string { return proto.CompactTextString(m) }
func (*Int64List) ProtoMessage() {}
func (*I... | return nil
}
| random_line_split | |
GridSave.py | .
dpix = (referencevalue - crval2)/cdelt2
crpix2 = crpix2 + dpix
# change x axis
header['CRVAL2'] = referencevalue
header['CRPIX2'] = crpix2
header['EQUINOX'] = 2.000000000000E+03 # Equinox of equatorial coordinates
header['BMAJ'] = 18.1 # Beam major axis in degrees: 80cm horn at 21.1cm
hea... | print("Reading Observing parameters from: %s" % (coldfile)) | random_line_split | |
GridSave.py | 2 dimensinoal
array of image data and writes a FITS image
This program produces two images. It expects an grid that is in cartisian format.
The second format described by the input: projection
"""
# print("Image: ", imageData)
imageData = grid.image
size = imageData.shape
imageCop... | ( grid1, grid2):
"""
gridratio computes the ratio of two grids when the values in both grids are non-zero
This function is used to compute gain ratios
The average and rms of the ratios are provided along as the grid of ratios
"""
nx1 = grid1.img_width
ny1 = grid1.img_height
nx2 = grid2.... | gridratio | identifier_name |
GridSave.py |
array of image data and writes a FITS image
This program produces two images. It expects an grid that is in cartisian format.
The second format described by the input: projection
"""
# print("Image: ", imageData)
imageData = grid.image
size = imageData.shape
imageCopy = copy.deep... | """
Main executable for gridding astronomical data
"""
dpi = 1
dpi = 2
width = int(360)
height = int(130)
mywidth = int(width*dpi)
myheight = int(height*dpi)
FWHM = 7.5 # degrees
FWHM = 10.0 # degrees
FWHM = 5.0 # degrees
FWHM = 3.0 # degrees
FWHM = 1.0 # degrees... | identifier_body | |
GridSave.py |
# now for output image check all pixel values
for jjj in range (ny):
for iii in range (nx):
# if this image pixal has no value
pixout[0] = (iii,jjj)
oworld = wout.wcs_pix2world(pixout, 0)
xy = oworld[0]
if np.isnan(xy[0]):
continue
# ... | for iii in range (nx):
imageCopy[jjj][iii] = nan | conditional_block | |
prec_climber.rs | (non_camel_case_types)]
/// # #[allow(dead_code)]
/// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// # enum Rule {
/// # plus,
/// # minus,
/// # times,
/// # divide,
/// # power
/// # }
/// static CLIMBER: PrecClimber<Rule> = prec_climber![
/// L plus | minus,
/// ... | ///
/// # Examples
///
/// ```
/// # use pest::prec_climber::{Assoc, Operator};
/// # #[allow(non_camel_case_types)]
/// # #[allow(dead_code)]
/// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// # enum Rule {
/// # plus,
/// # minus
/// #... | random_line_split | |
prec_climber.rs | (non_camel_case_types)]
/// # #[allow(dead_code)]
/// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// # enum Rule {
/// # plus,
/// # minus,
/// # times,
/// # divide,
/// # power
/// # }
/// static CLIMBER: PrecClimber<Rule> = prec_climber![
/// L plus | minus,
/// ... | }
/// List of operators and precedences, which can perform [precedence climbing][1] on infix
/// expressions contained in a [`Pairs`]. The token pairs contained in the `Pairs` should start
/// with a *primary* pair and then alternate between an *operator* and a *primary*.
///
/// [1]: https://en.wikipedia.org/wiki/Ope... |
fn assign_next<R: RuleType>(op: &mut Operator<R>, next: Operator<R>) {
if let Some(ref mut child) = op.next {
assign_next(child, next);
} else {
op.next = Some(Box::new(next));
}
}
assign_next(&mut self, rhs);
self
... | identifier_body |
prec_climber.rs | Rule> = prec_climber![
/// L plus | minus,
/// L times | divide,
/// R power,
/// ];
/// ```
#[cfg(feature = "const_prec_climber")]
#[macro_export]
macro_rules! prec_climber {
(
$( $assoc:ident $rule:ident $( | $rules:ident )* ),+ $(,)?
) => {{
prec_climber!(
@prece... | limb< | identifier_name | |
prec_climber.rs | ,
}
/// Infix operator used in [`PrecClimber`].
///
/// [`PrecClimber`]: struct.PrecClimber.html
#[derive(Debug)]
pub struct Operator<R: RuleType> {
rule: R,
assoc: Assoc,
next: Option<Box<Operator<R>>>,
}
impl<R: RuleType> Operator<R> {
/// Creates a new `Operator` from a `Rule` and `Assoc`.
///
... |
break;
}
| conditional_block | |
subscriber.rs | (Sender<MessageInfo>, Receiver<MessageInfo>) = bounded(8);
// Ends when subscriber or publisher sender is destroyed, which happens at Subscriber destruction
loop {
select! {
recv(data_rx) -> msg => {
match msg {
Err(_) => break,
Ok(v)... | {
let input = [7, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 4, 0, 0, 0, 11, 12, 13, 14];
let mut cursor = std::io::Cursor::new(input);
let data = package_to_vector(&mut cursor).expect(FAILED_TO_READ_WRITE_VECTOR);
assert_eq!(data, [7, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7]);
let data = package_to_vec... | identifier_body | |
subscriber.rs | <usize, Sub> = BTreeMap::new();
let mut existing_headers: Vec<HashMap<String, String>> = Vec::new();
let (data_tx, data_rx): (Sender<MessageInfo>, Receiver<MessageInfo>) = bounded(8);
// Ends when subscriber or publisher sender is destroyed, which happens at Subscriber destruction
loop {
selec... | let data = package_to_vector(&mut cursor).expect(FAILED_TO_READ_WRITE_VECTOR);
assert_eq!(data, [7, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7]);
let data = package_to_vector(&mut cursor).expect(FAILED_TO_READ_WRITE_VECTOR); | random_line_split | |
subscriber.rs | SubscriberRosConnection {
next_data_stream_id: 1,
data_stream_tx,
publishers_stream: pub_tx,
topic,
connected_ids: BTreeSet::new(),
connected_publishers: BTreeSet::new(),
}
}
// TODO: allow synchronous handling for subscribers
... | (&self) -> Vec<String> {
self.connected_publishers.iter().cloned().collect()
}
#[allow(clippy::useless_conversion)]
pub fn connect_to<U: ToSocketAddrs>(
&mut self,
publisher: &str,
addresses: U,
) -> std::io::Result<()> {
for address in addresses.to_socket_addrs(... | publisher_uris | identifier_name |
subscriber.rs | SubscriberRosConnection {
next_data_stream_id: 1,
data_stream_tx,
publishers_stream: pub_tx,
topic,
connected_ids: BTreeSet::new(),
connected_publishers: BTreeSet::new(),
}
}
// TODO: allow synchronous handling for subscribers
... |
}
});
Ok(headers)
}
fn write_request<U: std::io::Write>(
mut stream: &mut U,
caller_id: &str,
topic: &str,
msg_definition: &str,
md5sum: &str,
msg_type: &str,
) -> Result<()> {
let mut fields = HashMap::<String, String>::new();
fields.insert(String::from("message_defini... | {
// Data receiver has been destroyed after
// Subscriber destructor's kill signal
break;
} | conditional_block |
snva.py | _logger_fn,
args=(log_queue, child_log_queue))
child_logger_thread.start()
child_logger_thread_map[video_file_path] = child_logger_thread
if 'signalstate' == args.processormode:
child_process = Process(
target=process_video_signalstate,
name=path.spl... | except socket.gaierror:
# log something
logging.info('gaierror') | random_line_split | |
snva.py |
# Logger thread: listens for updates to log queue and writes them as they arrive
# Terminates after we add None to the queue
def child_logger_fn(main_log_queue, child_log_queue):
while True:
try:
message = child_log_queue.get()
if message is None:
break
main_log_queue.put(message)
... | while True:
try:
message = log_queue.get()
if message is None:
break
logger = logging.getLogger(__name__)
logger.handle(message)
except Exception as e:
logging.error(e)
break | identifier_body | |
snva.py |
logging.debug('FFPROBE path set to: {}'.format(ffprobe_path))
# # TODO validate all video file paths in the provided text file if args.inputpath is a text file
# if path.isdir(args.inputpath):
# video_file_names = set(IO.read_video_file_names(args.inputpath))
# video_file_paths = [path.join(args.inputp... | ffprobe_path = '/usr/bin/ffprobe' | conditional_block | |
snva.py | .protobuffilename)
#
# if not path.isfile(model_file_path):
# raise ValueError('The model specified at the path {} could not be '
# 'found.'.format(model_file_path))
#
# logging.debug('model_file_path set to {}'.format(model_file_path))
model_input_size_file_path = path.join(models_d... | (video_file_path):
# Before popping the next video off of the list and creating a process to
# scan it, check to see if fewer than logical_device_count + 1 processes are
# active. If not, Wait for a child process to release its semaphore
# acquisition. If so, acquire the semaphore, pop the next video na... | start_video_processor | identifier_name |
selectionmenu.js | }
}
// EN: Publish addEvent as a static method
// EN: (attach it to the constructor object)
// DE: Mache addEvent als statische Methode öffentlich
// DE: (hefte die Methode an den Konstruktor, der zurückgegeben wird)
SelectionMenu.addEvent = addEvent;
function getSelection () {
// EN: Feature dection HTML5 ... | // DE: Füge das span-Element in die neue Range ein
newRange.insertNode(span);
// EN: Adjust the selection by removing and adding the range.
// EN: This prevents the selection of the menu text. | random_line_split | |
selectionmenu.js | : (hefte die Methode an den Konstruktor, der zurückgegeben wird)
SelectionMenu.addEvent = addEvent;
function getSelection () {
// EN: Feature dection HTML5 / Microsoft
// DE: Fähigkeitenweiche HTML5 / Microsoft
if (window.getSelection) {
return window.getSelection();
} else if (document.selection && docum... | } else {
selection.removeAllRanges() | conditional_block | |
selectionmenu.js | fn) {
// EN: Feature dection DOM Events / Microsoft
// DE: Fähigkeitenweiche DOM Events / Microsoft
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else if (obj.attachEvent) {
obj.attachEvent('on' + type, function () {
return fn.call(obj, window.event);
});
}
}
// EN: Pub... | .prototype = {
create : function () {
var instance = this;
// EN: Create the menu container if necessary
// DE: Erzeuge den Menü-Container, sofern noch nicht passiert
if (span) {
return;
}
span = document.createElement('span');
span.id = instance.id;
},
setupEvents : function () {
... | e = this;
// EN: Copy members from the options object to the instance
// DE: Kopiere Einstellungen aus dem options-Objekt herüber zur Instanz
instance.id = options.id || 'selection-menu';
instance.menuHTML = options.menuHTML;
instance.minimalSelection = options.minimalSelection || 5;
instance.container = o... | identifier_body |
selectionmenu.js | , fn) {
// EN: Feature dection DOM Events / Microsoft
// DE: Fähigkeitenweiche DOM Events / Microsoft
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else if (obj.attachEvent) {
obj.attachEvent('on' + type, function () {
return fn.call(obj, window.event);
});
}
}
// EN: Pu... | ) {
// EN: Feature detection HTML5 / Microsoft
// DE: Fähigkeitenweiche HTML5 / Microsoft
return selection.toString ? selection.toString() : selection.text;
}
function contains (a, b) {
// EN: Feature detection DOM Core / Microsoft
// DE: Fähigkeitenweiche DOM Core / Microsoft
return a.compareDocumentPo... | Text (selection | identifier_name |
lib.rs | map>,
}
/// IoUring build params
#[derive(Clone, Default)]
pub struct Builder {
dontfork: bool,
params: sys::io_uring_params,
}
#[derive(Clone)]
pub struct Parameters(sys::io_uring_params);
unsafe impl Send for IoUring {}
unsafe impl Sync for IoUring {}
impl IoUring {
/// Create a IoUring instance
/... | }
#[inline]
pub fn params(&self) -> &Parameters {
&self.params
}
pub fn start_enter_syscall_thread(&self) {
sys::start_enter_syscall_thread(self.fd.as_raw_fd());
}
/// Initiate and/or complete asynchronous I/O
///
/// # Safety
///
/// This provides a ra... | #[inline]
pub fn submitter(&self) -> Submitter<'_> {
Submitter::new(&self.fd, self.params.0.flags, &self.sq) | random_line_split |
lib.rs | map, &sqe_mmap, p);
let cq = CompletionQueue::new(&cq_mmap, p);
let mm = MemoryMap {
cq_mmap: Some(cq_mmap),
sq_mmap,
sqe_mmap,
};
Ok((mm, sq, cq))
}
}
let fd: Fd = u... | self.0.features & sys::IORING_FEAT_FAST_POLL != 0
}
| identifier_body | |
lib.rs | params
#[derive(Clone, Default)]
pub struct Builder {
dontfork: bool,
params: sys::io_uring_params,
}
#[derive(Clone)]
pub struct Parameters(sys::io_uring_params);
unsafe impl Send for IoUring {}
unsafe impl Sync for IoUring {}
impl IoUring {
/// Create a IoUring instance
///
/// The `entries` s... | is_feature_single_mmap | identifier_name | |
lib.rs | map>,
}
/// IoUring build params
#[derive(Clone, Default)]
pub struct Builder {
dontfork: bool,
params: sys::io_uring_params,
}
#[derive(Clone)]
pub struct Parameters(sys::io_uring_params);
unsafe impl Send for IoUring {}
unsafe impl Sync for IoUring {}
impl IoUring {
/// Create a IoUring instance
/... | else {
let sq_mmap = Mmap::new(fd, sys::IORING_OFF_SQ_RING as _, sq_len)?;
let cq_mmap = Mmap::new(fd, sys::IORING_OFF_CQ_RING as _, cq_len)?;
let sq = SubmissionQueue::new(&sq_mmap, &sqe_mmap, p);
let cq = CompletionQueue::new(&cq_mmap, p);
... | {
let scq_mmap =
Mmap::new(fd, sys::IORING_OFF_SQ_RING as _, cmp::max(sq_len, cq_len))?;
let sq = SubmissionQueue::new(&scq_mmap, &sqe_mmap, p);
let cq = CompletionQueue::new(&scq_mmap, p);
let mm = MemoryMap {
sq_m... | conditional_block |
seq2seq.py | .Variable(
tf.truncated_normal(dtype=dtype, shape=(self.input_dimensions, self.hidden_size), mean=0, stddev=0.01),
name='Wz' + self.name)
self.Wh = tf.Variable(
tf.truncated_normal(dtype=dtype, shape=(self.input_dimensions, self.hidden_size), mean=0, stddev=0.01),
... |
# Perform the scan operator (hacky as fac diud)
self.h_t_transposed = tf.scan(self.forward_pass, self.x_t, self.h_0, name='h_t_transposed')
# Transpose the result back
self.h_t = tf.transpose(self.h_t_transposed, [1, 0], name='h_t')
return self.h_t
def predict_sequence(s... | self.h_0 = h_0 | conditional_block |
seq2seq.py | .Variable(
tf.truncated_normal(dtype=dtype, shape=(self.input_dimensions, self.hidden_size), mean=0, stddev=0.01),
name='Wz' + self.name)
self.Wh = tf.Variable(
tf.truncated_normal(dtype=dtype, shape=(self.input_dimensions, self.hidden_size), mean=0, stddev=0.01),
... | h_tm1 = tf.reshape(h_tm1, shape=[1, -1])
# Definitions of z_t and r_t
z_t = tf.sigmoid(tf.matmul(x_t, self.Wz) + tf.matmul(h_tm1, self.Uz) + self.bz)
r_t = tf.sigmoid(tf.matmul(x_t, self.Wr) + tf.matmul(h_tm1, self.Ur) + self.br)
# Definition of h~_t
h_proposal = tf.tan... | :return:
"""
# Convert vector-tensor form into matrix-tensor form
x_t = tf.reshape(x_t, shape=[1, -1]) | random_line_split |
seq2seq.py | .Variable(
tf.truncated_normal(dtype=dtype, shape=(self.input_dimensions, self.hidden_size), mean=0, stddev=0.01),
name='Wz' + self.name)
self.Wh = tf.Variable(
tf.truncated_normal(dtype=dtype, shape=(self.input_dimensions, self.hidden_size), mean=0, stddev=0.01),
... |
return tf.squeeze(h_t)
def process_sequence(self, sequence, h_0=None):
# Put the time-dimension upfront for the scan operator
self.x_t = tf.transpose(sequence, [1, 0], name='x_t') # [n_words, embedding_dim]
if h_0 is None:
# A little hack (to obtain the same shape a... | """Perform a forward pass.
:param h_tm1: np.matrix. The hidden state at the previous timestep (h_{t-1}).
:param x_t: np.matrix. The input vector.
:return:
"""
# Convert vector-tensor form into matrix-tensor form
x_t = tf.reshape(x_t, shape=[1, -1])
h_tm1 = tf.r... | identifier_body |
seq2seq.py | .Variable(
tf.truncated_normal(dtype=dtype, shape=(self.input_dimensions, self.hidden_size), mean=0, stddev=0.01),
name='Wz' + self.name)
self.Wh = tf.Variable(
tf.truncated_normal(dtype=dtype, shape=(self.input_dimensions, self.hidden_size), mean=0, stddev=0.01),
... | (self, h_tm1, x_t): # Function though to be used by tf.scan
"""Perform a forward pass.
:param h_tm1: np.matrix. The hidden state at the previous timestep (h_{t-1}).
:param x_t: np.matrix. The input vector.
:return:
"""
# Convert vector-tensor form into matrix-tensor ... | forward_pass | identifier_name |
error.rs | pub fn new_service_specific_error(err: i32, message: Option<&CStr>) -> Status {
let ptr = if let Some(message) = message {
unsafe {
// Safety: Any i32 is a valid service specific error for the
// error code parameter. We construct a valid, null-terminated
... | {
self.0
} | identifier_body | |
error.rs | as i32 => StatusCode::DEAD_OBJECT,
e if e == StatusCode::FAILED_TRANSACTION as i32 => StatusCode::FAILED_TRANSACTION,
e if e == StatusCode::BAD_INDEX as i32 => StatusCode::BAD_INDEX,
e if e == StatusCode::NOT_ENOUGH_DATA as i32 => StatusCode::NOT_ENOUGH_DATA,
e if e == StatusCode::WOULD... | fmt | identifier_name | |
error.rs | 32 => StatusCode::FAILED_TRANSACTION,
e if e == StatusCode::BAD_INDEX as i32 => StatusCode::BAD_INDEX,
e if e == StatusCode::NOT_ENOUGH_DATA as i32 => StatusCode::NOT_ENOUGH_DATA,
e if e == StatusCode::WOULD_BLOCK as i32 => StatusCode::WOULD_BLOCK,
e if e == StatusCode::TIMED_OUT as i32 ... | impl Display for Status {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_str(&self.get_description()) | random_line_split | |
setup.rs | <'a, I, D: Dimensions, S> {
/// ID of this ship.
id: I,
/// Grid that the ship may occupy.
grid: &'a Grid<I, D>,
/// Placement info for the ship.
ship: &'a ShipPlacementInfo<S, D::Coordinate>,
}
impl<'a, I: ShipId, D: Dimensions, S: ShipShape<D>> ShipEntry<'a, I, D, S> {
/// If the ship is ... | get_ship | identifier_name | |
setup.rs | setup phase of the board.
use std::collections::{hash_map::Entry, HashMap};
use crate::{
board::{AddShipError, Board, CannotPlaceReason, Dimensions, Grid, PlaceError},
ships::{ProjectIter, ShapeProjection, ShipId, ShipShape},
};
/// Reference to a particular ship's placement info as well as the grid, providi... | placement,
));
}
_ => {}
}
}
// Already ensured that every position is valid and not occupied.
for coord in placement.iter() {
self.grid[coord].ship = Some(self... | ));
}
Some(cell) if cell.ship.is_some() => {
return Err(PlaceError::new(
CannotPlaceReason::AlreadyOccupied, | random_line_split |
ingredientsScraper.py | (fooddish):
#dictionary for ingredients
I = {}
#dictionary for food recipes
R = {}
website = 'http://allrecipes.com'
for food in fooddish:
R[food] = {}
#search for food
print food
#for page in xrange(2):
resultspage = urllib2.urlopen("http://allrecipes.com/sear... | IngredientScraper2 | identifier_name | |
ingredientsScraper.py | .float32)
#ingsorted = sorted(I.keys())[1:]
#for i in xrange(len(trainlabels)):
##thresh = np.random.uniform(0,RecipeMax[trainlabels[i]],n)
#dish = fooddish[trainlabels[i]]
#X[i,:] = [1 if x != 0 else 0 for x in Recipes[dish][1:]]
##if len(R[dish].keys()) != 0:
###randomly pick recipe
##recipe = rnd.c... | #topfeatures = [None]*svm_weights.shape[0] #topfeatures for each class
#for i in xrange(svm_weights.shape[0]):
#featureIdx=np.argsort(abs(svm_weights[i,:]))
#topfeatures[i] = featureIdx[::-1][0:30] #get top 30 | random_line_split | |
ingredientsScraper.py |
#normalize values
m = sum(R[food][recipename].values())
R[food][recipename]={ingid: R[food][recipename][ingid]/m for ingid in R[food][recipename].keys()}
#Recipes = {}
#ingsorted = sorted(I.keys())
#for food in R.keys():
##m = sum(R[food].values())
##normalize values
... | ingid = ing.attrs['data-ingredientid']
ingname = ing.find(id='lblIngName').text
if ingid not in I:
I[ingid] = ingname
amt=float(ing.attrs['data-grams'])
R[food][recipename][ingid] = amt | conditional_block | |
ingredientsScraper.py | if recipename not in R[food]:
#print "Recipe: ", recipename
#ingredients for this recipe
ingredients = recipe.find_all('li', id='liIngredient')
R[food][recipename] = {}
for ing in ingredients:
ingid = ing.attrs['data-ingredientid']
ingname = ing.find(id='lblIngName').text
if ingid not ... | I = {}
#dictionary for food recipes
R = {}
website = 'http://allrecipes.com'
for food in fooddish:
R[food] = {}
#search for food
print food
#for page in xrange(2):
resultspage = urllib2.urlopen("http://allrecipes.com/search/default.aspx?qt=k&wt="+food)
results = bs(re... | identifier_body | |
buffered.rs | is
/// in memory, like a `Vec<u8>`.
///
/// It is critical to call [`flush`] before `BufWriter<W>` is dropped. Though
/// dropping will attempt to flush the the contents of the buffer, any errors
/// that happen in the process of dropping will be ignored. Calling [`flush`]
/// ensures that the buffer is empty and thus... | t_ref(& | identifier_name | |
buffered.rs | of our internal buffer then we need to fetch
// some more data from the underlying reader.
// Branch using `>=` instead of the more correct `==`
// to tell the compiler that the pos..cap slice is always valid.
if self.pos >= self.cap {
debug_assert!(self.pos == self.cap);
... | {
self.flush_buf()?;
} | conditional_block | |
buffered.rs | Writer<W: Write> {
inner: Option<W>,
buf: Vec<u8>,
// #30888: If the inner writer panics in a call to write, we don't want to
// write the buffered data a second time in BufWriter's destructor. This
// flag tells the Drop impl if it should skip the flush.
panicked: bool,
}
/// An error returned... | self.inner.into_inner().map_err(|IntoInnerError(buf, e)| {
IntoInnerError(LineWriter { inner: buf, need_flush: false }, e)
})
}
} | identifier_body | |
buffered.rs | output.
///
/// It can be excessively inefficient to work directly with something that
/// implements [`Write`]. For example, every call to
/// [`write`][`TcpStream::write`] on [`TcpStream`] results in a system call. A
/// `BufWriter<W>` keeps an in-memory buffer of data and writes it to an underlying
/// writer in la... | pub struct LineWriter<W: Write> {
inner: BufWriter<W>,
need_flush: bool, | random_line_split | |
util.ts | uncapitalize = (str: string) => str.replace(/(?:^|\s)\S/g, (a) => a.toLowerCase())
return uncapitalize(mode.replace(/^Showdown$/, 'Solo Showdown').split(' ').join(''))
}
export const formatList = (l: string[], joiner = 'or') => l.slice(0, l.length - 1).join(', ') + ' ' + joiner + ' ' + l[l.length - 1]
export const ... | */
/**
* Encode tag string into 64bit unsigned integer string.
* TODO: Use BigInt if tags are >2^53 at some point.
*/
export function tagToId(tag: string) {
if (!tagPattern.test(tag)) {
throw new Error('Cannot encode tag ' + tag)
}
if (tag.startsWith('#')) {
tag = tag.substring(1)
}
const result ... | arraySum((c, i) -> (position('0289PYLQGRJCUV', c)-1)*pow(14, length(player_club_tag)-i-1-1), arraySlice(splitByString('', player_club_tag), 2), range(if(player_club_tag <> '', toUInt64(length(player_club_tag)-1), 0))) as player_club_id, | random_line_split |
util.ts |
export const formatList = (l: string[], joiner = 'or') => l.slice(0, l.length - 1).join(', ') + ' ' + joiner + ' ' + l[l.length - 1]
export const clamp = (min: number, max: number, n: number) => Math.min(max, Math.max(min, n))
export const minMaxScale = (fromMin: number, fromMax: number, n: number) => (n - fromMin) /... | {
const uncapitalize = (str: string) => str.replace(/(?:^|\s)\S/g, (a) => a.toLowerCase())
return uncapitalize(mode.replace(/^Showdown$/, 'Solo Showdown').split(' ').join(''))
} | identifier_body | |
util.ts | .min(max, Math.max(min, n))
export const minMaxScale = (fromMin: number, fromMax: number, n: number) => (n - fromMin) / (fromMax - fromMin)
export const scaleInto = (fromMin: number, fromMax: number, toMax: number, n: number) => clamp(0, toMax, Math.floor(minMaxScale(fromMin, fromMax, n) * toMax))
export function xpTo... | getMonthSeasonEnd | identifier_name | |
util.ts | uncapitalize = (str: string) => str.replace(/(?:^|\s)\S/g, (a) => a.toLowerCase())
return uncapitalize(mode.replace(/^Showdown$/, 'Solo Showdown').split(' ').join(''))
}
export const formatList = (l: string[], joiner = 'or') => l.slice(0, l.length - 1).join(', ') + ' ' + joiner + ' ' + l[l.length - 1]
export const ... |
}
return Math.round(num / si[i].value)
.toFixed(digits)
.replace(rx, '$1') + si[i].symbol
}
const propPriority = ['winRateAdj', 'winRate', 'wins', 'rank1', 'duration', 'useRate', 'pickRate']
/**
* Get brawlers by event: {
* [eventId]: [
* brawler id,
* brawler name,
* brawler stats,
* ... | {
break
} | conditional_block |
parameter_noise.py | return self.sub_exploration.get_exploration_action(
action_distribution=action_distribution, timestep=timestep, explore=explore
)
@override(Exploration)
def on_episode_start(
self,
policy: "Policy",
*,
environment: BaseEnv = None,
episode: int... | return {"cur_stddev": self.stddev_val} | identifier_body | |
parameter_noise.py | ()
self.tf_add_stored_noise_op = self._tf_add_stored_noise_op()
self.tf_remove_noise_op = self._tf_remove_noise_op()
# Create convenience sample+add op for tf.
with tf1.control_dependencies([self.tf_sample_new_noise_op]):
add_op = self._tf_add_stored_noise... | _add_stored_noise | identifier_name | |
parameter_noise.py | [1]).
sub_exploration: Optional sub-exploration config.
None for auto-detection/setup.
"""
assert framework is not None
super().__init__(
action_space,
policy_config=policy_config,
model=model,
framework=framework,
... |
elif isinstance(self.action_space, Box):
sub_exploration = {
"type": "OrnsteinUhlenbeckNoise",
"random_timesteps": random_timesteps,
}
# TODO(sven): Implement for any action space.
else:
raise No... | sub_exploration = {
"type": "EpsilonGreedy",
"epsilon_schedule": {
"type": "PiecewiseSchedule",
# Step function (see [2]).
"endpoints": [
(0, 1.0),
(ran... | conditional_block |
parameter_noise.py | see [1]).
sub_exploration: Optional sub-exploration config.
None for auto-detection/setup.
"""
assert framework is not None
super().__init__(
action_space,
policy_config=policy_config,
model=model,
framework=framework,
... | # a special schedule.
if isinstance(self.action_space, Discrete):
sub_exploration = {
"type": "EpsilonGreedy",
"epsilon_schedule": {
"type": "PiecewiseSchedule",
# Step function (see [2]).
... | random_line_split | |
hazard2.py | (instr):
return Cat(C(0, 12), instr[12:])
def imm_j(instr):
return Cat(C(0, 1), instr[21:31], instr[20], instr[12:20], Repl(instr[-1], 12))
class Hazard2Shifter(Elaboratable):
def __init__(self):
self.i = Signal(XLEN)
self.shamt = Signal(range(XLEN))
self.right = Signal()
self.arith = Signal()
self.... | imm_u | identifier_name | |
hazard2.py | .shifter = shifter = Hazard2Shifter()
# Add/subtract i0 and i1, then subtract 4 if take4 is true. Use of 3-input adder
# encourages tools to implement as carry-save.
adder = sum((
self.i0,
self.i1 ^ Repl(self.op != ALUOp.ADD, XLEN),
Cat(self.op != ALUOp.ADD, C(0, 1), Repl(self.take4, XLEN - 2))
))[:XL... | ### Stage F ###
i_dph_active = Signal()
d_dph_active = Signal()
d_dph_write = Signal()
d_dph_addr = Signal(2)
d_dph_size = Signal(2)
d_dph_signed = Signal()
cir = Signal(32)
cir_valid = Signal()
load_rdata = Signal(XLEN)
with m.If(i_dph_active & ~stall):
m.d.sync += cir.eq(self.hrdata)
... | m = Module()
stall = ~self.hready
| random_line_split |
hazard2.py |
m.d.comb += self.o.eq(Mux(self.right, accum, accum[::-1]))
return m
class Hazard2ALU(Elaboratable):
def __init__(self):
self.i0 = Signal(XLEN)
self.i1 = Signal(XLEN)
self.op = Signal(Shape.cast(ALUOp))
self.take4 = Signal()
self.cmp = Signal()
self.o = Signal(XLEN)
def elaborate(se... | accum_next = Signal(XLEN, name=f"shift_accum{i}")
m.d.comb += accum_next.eq(Mux(self.shamt[i],
Cat(accum[1 << i:], Repl(accum[-1] & self.arith, 1 << i)),
accum
))
accum = accum_next | conditional_block | |
hazard2.py |
class Hazard2ALU(Elaboratable):
def __init__(self):
self.i0 = Signal(XLEN)
self.i1 = Signal(XLEN)
self.op = Signal(Shape.cast(ALUOp))
self.take4 = Signal()
self.cmp = Signal()
self.o = Signal(XLEN)
def elaborate(self, platform):
m = Module()
m.submodules.shifter = shifter = Hazard2S... | m = Module()
accum = Signal(XLEN, name="shift_pre_reverse")
m.d.comb += accum.eq(Mux(self.right, self.i, self.i[::-1]))
for i in range(self.shamt.width):
accum_next = Signal(XLEN, name=f"shift_accum{i}")
m.d.comb += accum_next.eq(Mux(self.shamt[i],
Cat(accum[1 << i:], Repl(accum[-1] & self.arith, 1 << ... | identifier_body | |
server.go | , error) {
// check message and boradcast to clients when necessary
checkMessage(in.Topic, in.Payload)
go func(a string, b []byte) {
web.PayloadMap.Store(a, b)
web.PayloadChan <- b
}(in.Topic, []byte(in.Payload))
// check whether should capture or not
buscfg := sys.GetBusManagerCfg()
for _, cap := range bu... | if err := sys.SaveBusManagerCfg(cfg); err != nil {
buslog.LOG.Warningf("save bus config failed, errmsg {%v}", err)
}
| random_line_split | |
server.go | : -1,
// Timestamp: public.UTCTimeStamp(),// 此值因与服务器发生了冲突,估不上报
Cov: true,
State: 0,
}
willpayload, _ := json.Marshal(payload)
payload.Value = 0
connpayload, _ := json.Marshal(payload)
s.MqttClient = NewMQTTClient(SubMessageHandler, willtopic, string(willpayload), conntopic, string(conn... | fs := ifl[cfg.Cache.MaxFile:]
// remove files
for _, f := range rfs {
os.Remove(filepath.Join(cfg.Cache.Directory, strconv.Itoa(f)))
}
}
var nf int
if l == 0 {
nf = 0
} else {
nf = ifl[0] + 1
}
filepath := filepath.Join(cfg.Cache.Directory, strconv.Itoa(nf))
f, err := os.Create(filepath)
if err ... | tSlice(ifl)))
log.Println(ifl)
l := len(ifl)
if l > cfg.Cache.MaxFile {
r | conditional_block |
server.go | y
downloadDependentDeviceLibrary()
if err := web.ReadVideoConfig(); err != nil {
log.Printf("open video config file failed, errmsg {%v}", err)
}
s.enableCache = true
// check directory exist or not
_, err := os.Stat(sys.GetBusManagerCfg().Cache.Directory)
if err != nil {
if os.IsNotExist(err) {
// do n... | brar | identifier_name | |
server.go | fg := sys.GetBusManagerCfg()
// download element library
downloadDependentDeviceLibrary()
if err := web.ReadVideoConfig(); err != nil {
log.Printf("open video config file failed, errmsg {%v}", err)
}
s.enableCache = true
// check directory exist or not
_, err := os.Stat(sys.GetBusManagerCfg().Cache.Directo... | atusSync.Unlock()
if networkStatus == Online && !mqtt {
// 当mqtt在线时,只能由mqtt处理
return
}
networkStatus = status
}
// Init do some init operation
func (s *BusServer) Init() {
c | identifier_body | |
TempTaker_old.py |
#ControlActionThreshold = [1,1,1,1,1,1,1,1]; # idea is to reduce wear on control elements by doing adjustments only when large changes occur, SRC,SRH,BRC,BRH,LRC,LRH
ControlActionThreshold = [2,2,4,3,2,2,2,2]; # idea is to reduce wear on control elements by doing adjustments only when large changes occur, SRC,SRH,BRC,... |
def saveIntegralError(self,integError):
#print integError
self.INTEGFILE.seek(0) #moves position to the beginning of the file
pickle.dump(integError, self.INTEGFILE)
self.INTEGFILE.truncate()
def finderrorSig(self, CurTemp): #takes array with current temperatures and finds the error signal array
err... | random_line_split | |
TempTaker_old.py | IFILE)
pickle.dump(self.D.tolist(),self.PIFILE)
self.PIFILE.close()
self.PImodtime = os.path.getmtime(pifile) #time when pifile is last modified
def updateExternalPIDParams(self):
if(os.path.getmtime(pifile) != self.PImodtime): #if PI parmeters have been modified externally, update them
self.PIFILE = open... | __del__ | identifier_name | |
TempTaker_old.py | SmallRoom]
propArr[laserroomctrl] = PSup[laserroomctrl]*curErrArr[SupplyLaserRoom-1]#0 + PTab[laserroomctrl]*curErrArr[Table4-1]#0 + PCoolingWater[laserroomctrl]*curErrArr[ColdWaterLaserRoom]
propArr[officectrl] = 0 #no control in office
propArr = propArr - clip(propArr, -PropActionThreshold,PropActionThreshold)
... | print '\n' + 'Filling up history for ' + str(self.RunningAvgNum) +' seconds \n' | identifier_body | |
TempTaker_old.py | 1]
integArr[laserroomctrl] = IntErrArr[Table4-1]
integArr[officectrl] = 0 #no control in office
integrespArr = (I * integArr) # when used with arrays, * is component by component multiplcation or dot product for 1D arrays
#print integArr
if((lastErrArr == zeros(Ch)).any()): #when the lastErrArr is the zero... | average = sum(self.historyArr[0:(self.historyCounter+1),:],axis=0)/(self.historyCounter) | conditional_block | |
Decryption.py | ()
#encrypt message
C = encryptor.update(message) + encryptor.finalize()
return C, IV
def MyFileEncrypt(filepath):
#generating key
key = os.urandom(KEY_LENGTH)
#Exclude private key, public key, and executable from encrypt
#getting file name and extension
filename_ext = os.path.bas... | encryptedFilepath = os.path.splittext(file)[0] + ".encrypted" + ".json"
with open( encryptedFilepath, 'w')as jsonfile:
json.dump(data, jsonfile, indent=3)
except:
print("Error:Json file didnt create")
... | try:
key = CheckRSAKeys()
except:
print("Error: keys has issue")
return
try:
for root, dirs, filres in os.walk(directory):
for file in filres:
try:
RSACipher, C, IV, tag, ext = MyRSAEncrypt(os.path.join(root,file),key[0])
... | identifier_body |
Decryption.py | ()
#encrypt message
C = encryptor.update(message) + encryptor.finalize()
return C, IV
def MyFileEncrypt(filepath):
#generating key
key = os.urandom(KEY_LENGTH)
#Exclude private key, public key, and executable from encrypt
#getting file name and extension
filename_ext = os.path.bas... | with open(jsonFile) as decryptFile:
data = json.load(decryptFile)
decryptFile.close()
#getting data from dictionary
C = (data['C']).encode('cp437')
IV = (data['IV']).encode('cp4 |
jsonFile = filename + ".json"
#open file to decrypt | random_line_split |
Decryption.py | RSACipher.decode('cp437'),"C": C.decode('cp437'), "IV": IV.decode('cp437'), "ext": ext, "tag": tag.decode('cp437')}
#create and write to json
filenameJSON = filename + ".json"
#write json data to file
with open(filenameJSON, "w") as outfile:
json.dump(encData, outfile)
outfil... | main | identifier_name | |
Decryption.py | ()
#encrypt message
C = encryptor.update(message) + encryptor.finalize()
return C, IV
def MyFileEncrypt(filepath):
#generating key
key = os.urandom(KEY_LENGTH)
#Exclude private key, public key, and executable from encrypt
#getting file name and extension
filename_ext = os.path.bas... |
#open and read file to encrypt
file = open(filepath, "rb")
m = file.read()
file.close()
#getting file name and extension
filename_ext = os.path.basename(filepath) #gets file name with extension from path
filename, ext = os.path.splitext(filename_ext) #separates file name and exten... | raise Exception("HMACKey less than 32 bytes!") | conditional_block |
skim.rs | BONUS_MATCHED: i64 = 4;
const BONUS_CASE_MATCH: i64 = 4;
const BONUS_UPPER_MATCH: i64 = 6;
const BONUS_ADJACENCY: i64 = 10;
const BONUS_SEPARATOR: i64 = 8;
const BONUS_CAMEL: i64 = 8;
const PENALTY_CASE_UNMATCHED: i64 = -1;
const PENALTY_LEADING: i64 = -6; // penalty applied for every letter before the first match
con... |
pub fn fuzzy_indices(choice: &str, pattern: &str) -> Option<(i64, Vec<usize>)> {
if pattern.is_empty() {
return Some((0, Vec::new()));
}
let mut picked = vec![];
let scores = build_graph(choice, pattern)?;
let last_row = &scores[scores.len() - 1];
let (mut next_col, &MatchingStatus {... | {
if pattern.is_empty() {
return Some(0);
}
let scores = build_graph(choice, pattern)?;
let last_row = &scores[scores.len() - 1];
let (_, &MatchingStatus { final_score, .. }) = last_row
.iter()
.enumerate()
.max_by_key(|&(_, x)| x.final_score)
.expect("fuzzy... | identifier_body |
skim.rs | (_, x)| x.final_score)
.expect("fuzzy_indices failed to iterate over last_row");
Some(final_score)
}
pub fn fuzzy_indices(choice: &str, pattern: &str) -> Option<(i64, Vec<usize>)> {
if pattern.is_empty() {
return Some((0, Vec::new()));
}
let mut picked = vec![];
let scores = build_... | random_line_split | ||
skim.rs | BONUS_MATCHED: i64 = 4;
const BONUS_CASE_MATCH: i64 = 4;
const BONUS_UPPER_MATCH: i64 = 6;
const BONUS_ADJACENCY: i64 = 10;
const BONUS_SEPARATOR: i64 = 8;
const BONUS_CAMEL: i64 = 8;
const PENALTY_CASE_UNMATCHED: i64 = -1;
const PENALTY_LEADING: i64 = -6; // penalty applied for every letter before the first match
con... | else {
score += PENALTY_CASE_UNMATCHED;
}
// apply bonus for camelCases
if choice_role == CharRole::Head {
score += BONUS_CAMEL;
}
// apply bonus for matches after a separator
if choice_prev_ch_type == CharType::Separ {
score += BONUS_SEPARATOR;
}
if pat_idx =... | {
if pat_ch.is_uppercase() {
score += BONUS_UPPER_MATCH;
} else {
score += BONUS_CASE_MATCH;
}
} | conditional_block |
skim.rs | BONUS_MATCHED: i64 = 4;
const BONUS_CASE_MATCH: i64 = 4;
const BONUS_UPPER_MATCH: i64 = 6;
const BONUS_ADJACENCY: i64 = 10;
const BONUS_SEPARATOR: i64 = 8;
const BONUS_CAMEL: i64 = 8;
const PENALTY_CASE_UNMATCHED: i64 = -1;
const PENALTY_LEADING: i64 = -6; // penalty applied for every letter before the first match
con... | (line: &str, pattern: &str) -> Option<String> {
let (_score, indices) = fuzzy_indices(line, pattern)?;
Some(wrap_matches(line, &indices))
}
fn assert_order(pattern: &str, choices: &[&'static str]) {
let result = filter_and_sort(pattern, choices);
if result != choices {
... | wrap_fuzzy_match | identifier_name |
ex1a_sim_vanillaSEIR_model_old.py | computed?
contact_rate = 10 # number of contacts an individual has per day
E0 = (contact_rate - 1)*I0 # Estimated exposed based on contact rate and inital infected
# Derived Model parameters and
beta = r0 / gamma_inv
sigma = 1.0 / sigma_inv
gamma ... | (x):
return np.log(x) + r0_test*(1-x)
###################################################
######## SEIR Model simulation Simulation ########
###################################################
if sim_num == 0:
''' Compartment structure of armed forces SEIR model
N = S + E + I + R
''' ... | epi_size | identifier_name |
ex1a_sim_vanillaSEIR_model_old.py | they computed?
contact_rate = 10 # number of contacts an individual has per day
E0 = (contact_rate - 1)*I0 # Estimated exposed based on contact rate and inital infected
# Derived Model parameters and
beta = r0 / gamma_inv
sigma = 1.0 / sigma_inv
gamma... | # Unpack timseries
if sim_num == 0:
t = sol_ode_timeseries[0]
S = sol_ode_timeseries[1]
E = sol_ode_timeseries[2]
I = sol_ode_timeseries[3]
R = sol_ode_timeseries[4]
else:
t = sol_ode_timeseries[0]
S = sol_ode_timeseries[1]
E = sol_ode_timeseries[2]
... | SEIRparams = N, beta, gamma, sigma
sol_ode_timeseries = simulate_seirModel(seir_type, SEIRparams, solver_type, y0, N, days, 1)
| random_line_split |
ex1a_sim_vanillaSEIR_model_old.py | computed?
contact_rate = 10 # number of contacts an individual has per day
E0 = (contact_rate - 1)*I0 # Estimated exposed based on contact rate and inital infected
# Derived Model parameters and
beta = r0 / gamma_inv
sigma = 1.0 / sigma_inv
gamma ... |
ax1.text(peak_inf_idx+10, peak_inf/N, txt_title.format(peak_inf=peak_inf, peak_days= peak_inf_idx), fontsize=12, color="r")
ax1.text(peak_inf_idx+10, peak_total_inf/N, txt_title2.format(peak_total=peak_total_inf, peak_days= peak_inf_idx), fontsize=12, color="r")
# Making things beautiful
ax1.set_xlabel('Time /days'... | txt_title = r"Peak infected: {peak_inf:5.0f} by day {peak_days:2.0f} from March 21"
txt_title2 = r"Total Cases: {peak_total:5.0f} by day {peak_days:2.0f} from March 21" | conditional_block |
ex1a_sim_vanillaSEIR_model_old.py | computed?
contact_rate = 10 # number of contacts an individual has per day
E0 = (contact_rate - 1)*I0 # Estimated exposed based on contact rate and inital infected
# Derived Model parameters and
beta = r0 / gamma_inv
sigma = 1.0 / sigma_inv
gamma ... |
###################################################
######## SEIR Model simulation Simulation ########
###################################################
if sim_num == 0:
''' Compartment structure of armed forces SEIR model
N = S + E + I + R
'''
# Initial conditions vect... | return np.log(x) + r0_test*(1-x) | identifier_body |
clustering.py | # list of all maneuvers
maneuvers = ['Obstacles15', 'Obstacles35', 'RampA', 'StraightF', 'Turn90FR', 'Turn90FL', 'Turn180L', 'Turn180R']
# choose the feature subsets for clustering
featureSet_list = ['ALL', 'ALL_TORQUE', '2D_TORQUE', 'LR_TORQUE', 'LR_TORQUE_MEAN', '2D_TORQUE_MEAN']
dataset_to_import = 'featured_data... |
# DEFINITIONS
USER = 'Mahsa' # ['Mahsa', 'Jaimie'] # participant name
WIN_SIZE = 32 # window size
| random_line_split | |
clustering.py | def import_func(path_):
""" function to import featured datasets"""
datasets_dic = {}
for dataset_path in path_:
# Parse labels from filenames
dataset_label = os.path.split(dataset_path)[1].split('.')[0]
# Read from csv to Pandas
dataset = pd.read_csv(dataset_path)
... | (df_clus):
""" add all cluster labels to the original dataframe """
df_all_labeled = df_all_columns.copy()
df_all_labeled['Clus_label'] = df_clus['Clus_label'].copy()
df_all_labeled['Clus_label']= df_all_labeled['Clus_label'].astype(int)
for i in range(0, clus_params['n_components']):
df_al... | labeling_func | identifier_name |
clustering.py | in df_all.columns.tolist() if 'Torque' in col] # all torque data
# all torque features except for roc (mean/std/... & left/right/sum/diff)
columns_2d_torque = [col for col in df_all.columns.tolist()
if 'Torque_sum' in col or 'Torque_diff' in col and 'roc' not in col]
# all torq... | """
input: input original dataframe (with maneuver columns), clustered dataframe, number of clusteres,
and selected features to plot
output: plotting clustered time series data with different colors
"""
clusterNum = clus_params['n_components']
color_dict = {i: cmap(i) for i in range(clus... | identifier_body | |
clustering.py | def import_func(path_):
""" function to import featured datasets"""
datasets_dic = {}
for dataset_path in path_:
# Parse labels from filenames
dataset_label = os.path.split(dataset_path)[1].split('.')[0]
# Read from csv to Pandas
dataset = pd.read_csv(dataset_path)
... |
if not np.any(Y_ == i):
continue
if "MEAN" in clus_params['feat_list']:
plt.scatter(XX[Y_ == i, 0], XX[Y_ == i, 1], color=color, s=60)
else:
plt.scatter(XX[Y_ == i, 0], XX[Y_ == i, 5], color=color, s=60)
# Plot an ellipse to show the Gaussian compo... | subset = [0, 5] # mean torque L & R
v, w = linalg.eigh(cov[np.ix_(subset, subset)])
mean = np.array([mean[0], mean[5]]) | conditional_block |
dataflows.rs | self.index_imports.insert(
id,
IndexImport {
desc,
typ,
monotonic,
usage_types: None,
},
);
}
/// Imports a source and makes it available as `id`.
pub fn import_source(&mut self, id: GlobalId... | (&self) -> impl Iterator<Item = GlobalId> + '_ {
self.index_exports
.keys()
.chain(self.sink_exports.keys())
.cloned()
}
/// Identifiers of exported subscribe sinks.
pub fn subscribe_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
self.sink_exports
... | export_ids | identifier_name |
dataflows.rs | self.index_imports.insert(
id,
IndexImport {
desc,
typ,
monotonic,
usage_types: None,
},
);
}
/// Imports a source and makes it available as `id`.
pub fn import_source(&mut self, id: GlobalId... |
/// Calls r and s on any sub-members of those types in self. Halts at the first error return.
pub fn visit_children<R, S, E>(&mut self, r: R, s: S) -> Result<(), E>
where
R: Fn(&mut OptimizedMirRelationExpr) -> Result<(), E>,
S: Fn(&mut MirScalarExpr) -> Result<(), E>,
{
for Bu... | {
for (source_id, (source, _monotonic)) in self.source_imports.iter() {
if source_id == id {
return source.typ.arity();
}
}
for IndexImport { desc, typ, .. } in self.index_imports.values() {
if &desc.on_id == id {
return typ.ari... | identifier_body |
dataflows.rs | {
self.index_imports.insert(
id,
IndexImport {
desc,
typ,
monotonic,
usage_types: None,
},
);
}
/// Imports a source and makes it available as `id`.
pub fn import_source(&mut self, id: Globa... | /// Returns true iff `id` is already imported.
pub fn is_imported(&self, id: &GlobalId) -> bool {
self.objects_to_build.iter().any(|bd| &bd.id == id)
|| self.source_imports.keys().any(|i| i == id)
}
/// Assigns the `as_of` frontier to the supplied argument.
///
/// This meth... | random_line_split | |
rpc.rs | >,
stop_flag: Arc<Notify>,
) -> crate::Result<(
(WorkerId, WorkerConfiguration),
impl Future<Output = crate::Result<()>>,
)> {
let (_listener, port) = start_listener().await?;
configuration.listen_address = format!("{}:{}", configuration.hostname, port);
let ConnectionDescriptor {
mut se... | {
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
interval.tick().await;
let state = state_ref.get();
if !state.has_tasks() && !state.reservation {
let elapsed = state.last_task_finish_time.elapsed();
if elapsed > idle_timeout {
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.