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 |
|---|---|---|---|---|
gardenView.js | import {fabric} from 'fabric';
import * as actions from './actions';
import * as cst from '../constants';
import {PlantView} from './plantView';
import {ScoreInput} from './scoring/input';
const DEFAULT_IMAGE_WIDTH = 28;
const DEFAULT_IMAGE_HEIGHT = 28;
const SCROLLBAR_WIDTH = 26;
const DEFAULT_USER_WIDTH = 6;
const... | /* Populate garden with plants from imported data */
load(data) {
// By default, if no user dimensions saved, we generate a 6mx4m garden
const {width, length} = (typeof(data.garden.userDimensions) !== 'undefined')
? data.garden.userDimensions
: {width: DEFAULT_USER_WIDTH, length: DEFAULT_USER_LE... | img.set({
width: width,
height: height,
left: position.x,
top: position.y,
hasRotatingPoint: false,
lockRotation: true,
lockScalingFlip : true,
lockScalingX: true,
lockScalingY: true
});
const plant = this.plantFactory.buildPlant(idPlant);
let plantV... | identifier_body |
gardenView.js | import {fabric} from 'fabric';
import * as actions from './actions';
import * as cst from '../constants';
import {PlantView} from './plantView';
import {ScoreInput} from './scoring/input';
const DEFAULT_IMAGE_WIDTH = 28;
const DEFAULT_IMAGE_HEIGHT = 28;
const SCROLLBAR_WIDTH = 26;
const DEFAULT_USER_WIDTH = 6;
const... | }
const scoreInput = new ScoreInput(plants, plantModels, {
sizeMeter: this.grid.sizeMeter
});
// Call score process by dispatching save event with plants data
this.actionDispatcher.dispatch({type: actions.SCORE, data: {
input: scoreInput,
}});
}
/*
Add a plant on grid, by put... | plantModels[plant.id] = plant;
}
| conditional_block |
csv_test.py | #!/usr/bin/env python
# Copyright (C) 2014, 2015 by Ali Baharev <ali.baharev@gmail.com>
# All rights reserved.
# BSD license.
# https://github.com/baharev/CSV_Test
from __future__ import print_function
from contextlib import closing
from cStringIO import StringIO
from itertools import izip, izip_longest
from math impor... | (passed, extra_msg):
with closing(StringIO()) as out:
out.write('Passed:\n')
for p in passed:
out.write(p)
out.write('\n')
out.write('=========================================================\n')
if extra_msg:
out.write( extra_msg + '\n' )
... | create_header | identifier_name |
csv_test.py | #!/usr/bin/env python
# Copyright (C) 2014, 2015 by Ali Baharev <ali.baharev@gmail.com>
# All rights reserved.
# BSD license.
# https://github.com/baharev/CSV_Test
from __future__ import print_function
from contextlib import closing
from cStringIO import StringIO
from itertools import izip, izip_longest
from math impor... |
def check_rowlength(lines, expected_len):
# Returns error message on error, None otherwise.
# The first row is the header, and error messages use base 1 indices
indices = [i for i, row in enumerate(lines, 2) if len(row)!=expected_len]
if indices:
return 'row length error in rows (header is row... | if len(header)==0:
return None, 'missing'
col_types = [ TO_TYPE.get(col[-1:], None) for col in header ]
for i, typ in enumerate(col_types):
if typ is None:
msg = 'unrecognized type in column {}: "{}"'.format(i+1, header[i])
return None, msg
assert len(col_types)==len(... | identifier_body |
csv_test.py | #!/usr/bin/env python
# Copyright (C) 2014, 2015 by Ali Baharev <ali.baharev@gmail.com>
# All rights reserved.
# BSD license.
# https://github.com/baharev/CSV_Test
from __future__ import print_function
from contextlib import closing
from cStringIO import StringIO
from itertools import izip, izip_longest
from math impor... |
mismatch = compare_values(etalon, tocomp)
if mismatch:
log_error(filename, 'mismatch, excel sheet written')
write_mismatch(filename, etalon, tocomp, mismatch)
return
return True
def log_error(filename, msg):
assert filename not in _errors, (filename, _errors[filename])
_err... | msg = 'number of rows: {}!={}'.format(etalon_len, tocomp_len)
log_error(filename, msg)
return | conditional_block |
csv_test.py | #!/usr/bin/env python
# Copyright (C) 2014, 2015 by Ali Baharev <ali.baharev@gmail.com>
# All rights reserved.
# BSD license.
# https://github.com/baharev/CSV_Test
from __future__ import print_function
from contextlib import closing
from cStringIO import StringIO
from itertools import izip, izip_longest
from math impor... | with open(filename, 'r') as f:
header = extract_first_line(f)
lines = [ split(line) for line in f ]
print('Read {} lines'.format( bool(header) + len(lines) ))
return header, lines
def extract_first_line(f):
header = next(f, None)
return split(header) if header else [ ]
def split(li... | return
return header, table
def read_csv(filename):
print('Trying to read file "{}"'.format(filename)) | random_line_split |
list_view.rs | use std::{
cmp::Ordering,
io::{stdout, Write},
};
use crossterm::{
cursor::MoveTo,
queue,
style::{Color, SetBackgroundColor},
terminal::{Clear, ClearType},
};
use crate::{
compute_scrollbar, errors::Result, gray, Alignment, Area, CompoundStyle, MadSkin, Spacing,
};
pub struct ListViewCell... | else {
self.area.height
}
}
/// return an option which when filled contains
/// a tupple with the top and bottom of the vertical
/// scrollbar. Return none when the content fits
/// the available space.
#[inline(always)]
pub fn scrollbar(&self) -> Option<(u16, u16)> {... | {
self.area.height - 2
} | conditional_block |
list_view.rs | use std::{
cmp::Ordering,
io::{stdout, Write},
};
use crossterm::{
cursor::MoveTo,
queue,
style::{Color, SetBackgroundColor},
terminal::{Clear, ClearType},
};
use crate::{
compute_scrollbar, errors::Result, gray, Alignment, Area, CompoundStyle, MadSkin, Spacing,
};
pub struct ListViewCell... | self.row_order = Some(sort);
}
/// return the height which is available for rows
#[inline(always)]
pub const fn tbody_height(&self) -> u16 {
if self.area.height > 2 {
self.area.height - 2
} else {
self.area.height
}
}
/// return an option w... | /// set a comparator for row sorting
#[allow(clippy::type_complexity)]
pub fn sort(&mut self, sort: Box<dyn Fn(&T, &T) -> Ordering>) { | random_line_split |
list_view.rs | use std::{
cmp::Ordering,
io::{stdout, Write},
};
use crossterm::{
cursor::MoveTo,
queue,
style::{Color, SetBackgroundColor},
terminal::{Clear, ClearType},
};
use crate::{
compute_scrollbar, errors::Result, gray, Alignment, Area, CompoundStyle, MadSkin, Spacing,
};
pub struct ListViewCell... | (&mut self, data: T) {
let stick_to_bottom = self.row_order.is_none() && self.do_scroll_show_bottom();
let displayed = match &self.filter {
Some(fun) => fun(&data),
None => true,
};
if displayed {
self.displayed_rows_count += 1;
}
if st... | add_row | identifier_name |
lib.rs |
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
// Import the macro. Don't forget to add `error-chain` in your
// `Cargo.toml`!
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
extern crate clap;
extern crate byteorder;
extern crate ansi_term;
extern crate pbr;
pub mod network... | (&self, index: u32) -> Result<&FileInfo> {
return self.files.get(&index)
.ok_or_else(|| ErrorKind::UnknownFile(index).into());
}
pub fn run(&self) -> Result<()> {
//@Expansion: Maybe don't use fixed ports
let listener = std::net::TcpListener::bind((self.interface.addr, 2222)... | get_file | identifier_name |
lib.rs |
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
// Import the macro. Don't forget to add `error-chain` in your
// `Cargo.toml`!
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
extern crate clap;
extern crate byteorder;
extern crate ansi_term;
extern crate pbr;
pub mod network... |
//TODO: Make some error wrapper
let mut file = std::fs::File::create(new_path)?;
let mut buffer = [0u8; 8192];
loop{
let read = message.file.read(&mut buffer)
.chain_err(|| ErrorKind::ReadContent)?;
if read == 0 {
break;
... | {
bail!(ErrorKind::FileExists(new_path));
} | conditional_block |
lib.rs | // `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
// Import the macro. Don't forget to add `error-chain` in your
// `Cargo.toml`!
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
extern crate clap;
extern crate byteorder;
extern crate ansi_term;
extern crate pbr;
pub mod network;... | };
}
pub fn present(&self, t: &Transport) -> Result<String> {
let parts = (t.max_state() as f64).log(self.dict_entries as f64).ceil() as u32;
let mut part_representation: Vec<&str> = Vec::with_capacity(parts as usize);
let mut remainder = t.state();
for _ in 0..parts {... | dictionary: dictionary,
dict_entries: dict_entries, | random_line_split |
lib.rs |
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
// Import the macro. Don't forget to add `error-chain` in your
// `Cargo.toml`!
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
extern crate clap;
extern crate byteorder;
extern crate ansi_term;
extern crate pbr;
pub mod network... |
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> {
return Ok(std::net::Ipv4Addr::from(t.state()));
}
}
#[derive(Clone)]
pub struct FileInfo{
path: PathBuf,
len: u64,
}
impl FileInfo {
fn new(path: PathBuf, len: u64) -> FileInfo {
return FileInfo {
path: pa... | {
return Ok(ServerTransport::new(u32::from(self.clone()), std::u32::MAX));
} | identifier_body |
bulk.rs | use bitcoincash::blockdata::block::Block;
use bitcoincash::consensus::encode::{deserialize, Decodable};
use bitcoincash::hash_types::BlockHash;
use std::collections::HashSet;
use std::fs;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::{
mpsc::{Receiver, SyncSender},
Arc, Mutex,
};
use std::... | (blob: Vec<u8>, magic: u32) -> Result<Vec<Block>> {
let mut cursor = Cursor::new(&blob);
let mut blocks = vec![];
let max_pos = blob.len() as u64;
while cursor.position() < max_pos {
let offset = cursor.position();
match u32::consensus_decode(&mut cursor) {
Ok(value) => {
... | parse_blocks | identifier_name |
bulk.rs | use bitcoincash::blockdata::block::Block;
use bitcoincash::consensus::encode::{deserialize, Decodable};
use bitcoincash::hash_types::BlockHash;
use std::collections::HashSet;
use std::fs;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::{
mpsc::{Receiver, SyncSender},
Arc, Mutex,
};
use std::... | let chan = SyncChannel::new(0);
let blobs = chan.sender();
let handle = spawn_thread("bulk_read", move || -> Result<()> {
for path in blk_files {
blobs
.send((parser.read_blkfile(&path)?, path))
.expect("failed to send blk*.dat contents");
}
... | type JoinHandle = thread::JoinHandle<Result<()>>;
type BlobReceiver = Arc<Mutex<Receiver<(Vec<u8>, PathBuf)>>>;
fn start_reader(blk_files: Vec<PathBuf>, parser: Arc<Parser>) -> (BlobReceiver, JoinHandle) { | random_line_split |
bulk.rs | use bitcoincash::blockdata::block::Block;
use bitcoincash::consensus::encode::{deserialize, Decodable};
use bitcoincash::hash_types::BlockHash;
use std::collections::HashSet;
use std::fs;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::{
mpsc::{Receiver, SyncSender},
Arc, Mutex,
};
use std::... |
fn last_indexed_row(&self) -> Row {
// TODO: use JSONRPC for missing blocks, and don't use 'L' row at all.
let indexed_blockhashes = self.indexed_blockhashes.lock().unwrap();
let last_header = self
.current_headers
.iter()
.take_while(|h| indexed_blockha... | {
Ok(Arc::new(Parser {
magic: daemon.disk_magic(),
current_headers: load_headers(daemon)?,
indexed_blockhashes: Mutex::new(indexed_blockhashes),
cashaccount_activation_height,
duration: metrics.histogram_vec(
prometheus::HistogramOpts::... | identifier_body |
chapter12.py | ##############################
## Case Study (section 12.2.3)
##############################
## DDQN + PER for trading/ Trader version
## states only contain tech index/ some positive results
##程序框架使用了网页(https://github.com/jaromiru/AI-blog)的DQN程序主体架构
#import random, numpy, math, gym, scipy
import random, n... | )
model.add(Dense(self.layer1_para, kernel_initializer='lecun_uniform', input_shape=(self.stateCnt,)))
model.add(Activation('relu'))
#model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try?
model.add(Dense(self.layer2_para, kernel_initializer='lecun_unifor... | Sequential( | identifier_name |
chapter12.py | ##############################
## Case Study (section 12.2.3)
##############################
## DDQN + PER for trading/ Trader version
## states only contain tech index/ some positive results
##程序框架使用了网页(https://github.com/jaromiru/AI-blog)的DQN程序主体架构
#import random, numpy, math, gym, scipy
import random, n... | f.VERSION) ## 1.14.0
print(tf.keras.__version__) ## 2.2.4-tf
from keras import backend as K
#import tensorflow.keras.backend as K
#from tensorflow.python.keras import backend as K
def hubert_loss(y_true, y_pred): # sqrt(1+a^2)-1
err = y_pred - y_true
return K.mean( K.sqrt(1+K.square(err))-1, axi... | dataIdx = idx - self.capacity + 1
return (idx, self.tree[idx], self.data[dataIdx])
import tensorflow as tf
print(t | identifier_body |
chapter12.py | ##############################
## Case Study (section 12.2.3)
##############################
## DDQN + PER for trading/ Trader version
## states only contain tech index/ some positive results
##程序框架使用了网页(https://github.com/jaromiru/AI-blog)的DQN程序主体架构
#import random, numpy, math, gym, scipy
import random, n... | n based on our eperience
self.steps += 1
self.epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp(-LAMBDA * self.steps)
def _getTargets(self, batch):
no_state = numpy.zeros(self.stateCnt)
states = numpy.array([ o[1][0] for o in batch ])
states_ = numpy.ar... | # slowly decrease Epsilo | conditional_block |
chapter12.py | ##############################
## Case Study (section 12.2.3)
##############################
## DDQN + PER for trading/ Trader version
## states only contain tech index/ some positive results
##程序框架使用了网页(https://github.com/jaromiru/AI-blog)的DQN程序主体架构
#import random, numpy, math, gym, scipy
import random, n... | ## out-of-sample test
####################################
start_day = '20150715'
end_day = '20151207'
nst = (datax['date']==start_day).nonzero()[0][0]
ned = (datax['date']==end_day).nonzero()[0][0]
featurest = np.float64(features[nst:ned,:])
close2t = closex[nst:ned]
Xtt = (featurest - mu1)/std1
X... | #plt.plot(u0,close20,'og')
####################################
| random_line_split |
userlist.js | (function ($) {
var hisArr = [];
var queryMap = {};
var account;
var rebateMode;
$.ajax({
url: $.toFullPath('/data/json/config.json'),
async: false,
dataType: 'json',
success: function (response) {
var systemConfig = response['system_config'];
for (var i = 0; i < systemConfig.leng... | 日期 填充0
function addzero(v) {
if (v < 10) {
return '0' + v;
}
return v.toString();
}
})(jQuery); | nth() + 1)
+ '-' + addzero(date.getDate() + 1);
return s;
}
//月份 | identifier_body |
userlist.js | (function ($) {
var hisArr = [];
var queryMap = {};
var account;
var rebateMode;
$.ajax({
url: $.toFullPath('/data/json/config.json'),
async: false,
dataType: 'json',
success: function (response) {
var systemConfig = response['system_config'];
for (var i = 0; i < systemConfig.leng... | } catch (e) {
}
if (responseText.code === 'UC/TOKEN_INVALID') {
alert('网络连接超时,请重新登陆!');
$.cookie('token', null, {path: '/'});
window.location.href = '/views/main.html';
}
});
return account;
}
function cleanQueryForm() {
$('#account').val(null);
$('#moneyF... | seText);
| identifier_name |
userlist.js | (function ($) {
var hisArr = [];
var queryMap = {};
var account;
var rebateMode;
$.ajax({
url: $.toFullPath('/data/json/config.json'),
async: false,
dataType: 'json',
success: function (response) {
var systemConfig = response['system_config'];
for (var i = 0; i < systemConfig.leng... | $('#startDatePicker').datepicker({el: 'startDate'}).children('#startDate');//.val(minusMonth(6));
$('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate');//.val($.dateformat(new Date(), 'yyyy-MM-dd'));
//查询按钮
$('#queryBtn').on('click', function (e) {
$('#page').val(1);
$('#rows').... |
account = loadCurrAccount();//初始隐藏currAccount值
//设置默认查询时间 最近半年
| conditional_block |
userlist.js | (function ($) {
var hisArr = [];
var queryMap = {};
var account;
var rebateMode;
$.ajax({
url: $.toFullPath('/data/json/config.json'),
async: false,
dataType: 'json',
success: function (response) {
var systemConfig = response['system_config'];
for (var i = 0; i < systemConfig.leng... |
function queryMapFormat(queryStr) {
return queryStr.replace("}", ']').replace("{", '[');
}
function queryMapResotre(queryStr) {
return queryStr.replace("]", '}').replace("[", '{');
}
function getProtocolPrefix() {
return (window.location.protocol || document.location.protocol) + '//';
}
fu... | return false;
}; | random_line_split |
gcm.go | // Original file obtained from https://raw.githubusercontent.com/golang/go/4e8badbbc2fe7854bb1c12a9ee42315b4d535051/src/crypto/cipher/gcm.go
//
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ubiq
im... | e) {
ciphertext := make([]byte, len(g.block))
g.counterCrypt(ciphertext, g.block, &g.counter)
g.block = nil
g.counter = [gcmBlockSize]byte{}
g.len.ct += len(ciphertext)
g.update(&g.tagaccum, ciphertext)
tag := make([]byte, g.tagSize)
g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask)
g.tagmask ... | yte, []byt | identifier_name |
gcm.go | // Original file obtained from https://raw.githubusercontent.com/golang/go/4e8badbbc2fe7854bb1c12a9ee42315b4d535051/src/crypto/cipher/gcm.go
//
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ubiq
im... | identifier_body | ||
gcm.go | // Original file obtained from https://raw.githubusercontent.com/golang/go/4e8badbbc2fe7854bb1c12a9ee42315b4d535051/src/crypto/cipher/gcm.go
//
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ubiq
im... | e final four bytes of counterBlock as a big-endian value
// and increments it.
func gcmInc32(counterBlock *[16]byte) {
ctr := counterBlock[len(counterBlock)-4:]
binary.BigEndian.PutUint32(ctr, binary.BigEndian.Uint32(ctr)+1)
}
// counterCrypt crypts in to out using g.cipher in counter mode.
func (g *gcm) counterCryp... | BlockSize]byte
copy(partialBlock[:], data[fullBlocks:])
g.updateBlocks(y, partialBlock[:])
}
}
// gcmInc32 treats th | conditional_block |
gcm.go | // Original file obtained from https://raw.githubusercontent.com/golang/go/4e8badbbc2fe7854bb1c12a9ee42315b4d535051/src/crypto/cipher/gcm.go
//
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ubiq
im... |
g.block = nil
g.counter = [gcmBlockSize]byte{}
tag := make([]byte, g.tagSize)
g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask)
g.tagmask = [gcmBlockSize]byte{}
g.tagaccum = gcmFieldElement{}
g.len.aad = 0
g.len.ct = 0
return plaintext, subtle.ConstantTimeCompare(tag, expectedTag) == 1
}
// re... | g.update(&g.tagaccum, g.block)
g.counterCrypt(plaintext, g.block, &g.counter) | random_line_split |
lib.rs | // SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! `cursive-markup` provides the [`MarkupView`][] for [`cursive`][] that can render HTML or other
//! markup.
//!
//! # Quickstart
//!
//! To render an HTML document, create a [`MarkupView`][] with the [`... | /// [`set_maximum_width`][] method.
///
/// [`RenderedDocument`]: struct.RenderedDocument.html
/// [`Renderer`]: trait.Renderer.html
/// [`render`]: trait.Renderer.html#method.render
/// [`on_link_select`]: #method.on_link_select
/// [`on_link_focus`]: #method.on_link_focus
/// [`set_maximum_width`]: #method.set_maximu... | ///
/// You can also limit the available width by setting a maximum line width with the | random_line_split |
lib.rs | // SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! `cursive-markup` provides the [`MarkupView`][] for [`cursive`][] that can render HTML or other
//! markup.
//!
//! # Quickstart
//!
//! To render an HTML document, create a [`MarkupView`][] with the [`... | fn layout(&mut self, constraint: cursive_core::XY<usize>) {
self.render(constraint);
}
fn required_size(&mut self, constraint: cursive_core::XY<usize>) -> cursive_core::XY<usize> {
self.render(constraint)
}
fn take_focus(&mut self, direction: cursive_core::direction::Direction) -> ... | let doc = &self.doc.as_ref().expect("layout not called before draw");
for (y, line) in doc.lines.iter().enumerate() {
let mut x = 0;
for element in line {
let mut style = element.style;
if let Some(link_idx) = element.link_idx {
... | identifier_body |
lib.rs | // SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! `cursive-markup` provides the [`MarkupView`][] for [`cursive`][] that can render HTML or other
//! markup.
//!
//! # Quickstart
//!
//! To render an HTML document, create a [`MarkupView`][] with the [`... |
text: String,
style: theme::Style,
link_target: Option<String>,
}
#[derive(Clone, Debug, Default)]
struct RenderedElement {
text: String,
style: theme::Style,
link_idx: Option<usize>,
}
#[derive(Clone, Debug, Default)]
struct LinkHandler {
links: Vec<Link>,
focus: usize,
}
#[derive(C... | ement { | identifier_name |
ed_glob.py | ###############################################################################
# Name: ed_glob.py #
# Purpose: Global IDs/objects used throughout Editra #
# Author: Cody Precord <cprecord@editra.org> #
... | ():
"""Get the eol mode map"""
# Maintenance Note: ints must be kept in sync with EDSTC_EOL_* in edstc
return { EOL_MODE_CR : _("Old Machintosh (\\r)"),
EOL_MODE_LF : _("Unix (\\n)"),
EOL_MODE_CRLF : _("Windows (\\r\\n)")}
# Default Plugins
DEFAULT_PLUGINS = ("generator.Html", "ge... | EOLModeMap | identifier_name |
ed_glob.py | ###############################################################################
# Name: ed_glob.py #
# Purpose: Global IDs/objects used throughout Editra #
# Author: Cody Precord <cprecord@editra.org> #
... | # Code Elements (ids for art provider)
ID_CLASS_TYPE = wx.NewId()
ID_FUNCT_TYPE = wx.NewId()
ID_ELEM_TYPE = wx.NewId()
ID_VARIABLE_TYPE = wx.NewId()
ID_ATTR_TYPE = wx.NewId()
ID_PROPERTY_TYPE = wx.NewId()
ID_METHOD_TYPE = wx.NewId()
# Statusbar IDs
SB_INFO = 0
SB_BUFF = 1
SB_LEXER = 2
SB_ENCO... | ID_READONLY = wx.NewId()
ID_NEW_FOLDER = wx.NewId()
| random_line_split |
ed_glob.py | ###############################################################################
# Name: ed_glob.py #
# Purpose: Global IDs/objects used throughout Editra #
# Author: Cody Precord <cprecord@editra.org> #
... |
# Default Plugins
DEFAULT_PLUGINS = ("generator.Html", "generator.LaTeX", "generator.Rtf",
"iface.Shelf", "ed_theme.TangoTheme", "ed_log.EdLogViewer",
"ed_search.EdFindResults", "ed_bookmark.EdBookmarks")
| """Get the eol mode map"""
# Maintenance Note: ints must be kept in sync with EDSTC_EOL_* in edstc
return { EOL_MODE_CR : _("Old Machintosh (\\r)"),
EOL_MODE_LF : _("Unix (\\n)"),
EOL_MODE_CRLF : _("Windows (\\r\\n)")} | identifier_body |
ed_glob.py | ###############################################################################
# Name: ed_glob.py #
# Purpose: Global IDs/objects used throughout Editra #
# Author: Cody Precord <cprecord@editra.org> #
... |
ID_QUICK_FIND = wx.NewId()
ID_PREF = wx.ID_PREFERENCES
# Preference Dlg Ids
ID_PREF_LANG = wx.NewId()
ID_PREF_AALIAS = wx.NewId()
ID_PREF_AUTOBKUP = wx.NewId()
ID_PREF_AUTO_RELOAD = wx.NewId()
ID_PREF_AUTOCOMPEX = wx.NewId()
ID_PREF_AUTOTRIM = wx.NewId()
ID_PREF_CHKMOD = wx.NewId()
ID_PREF_CHKUPDA... | ID_FIND = wx.NewId()
ID_FIND_REPLACE = wx.NewId() | conditional_block |
spec.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 yo... | else {
Machine::regular(params, builtins)
}
}
/// Convert engine spec into a arc'd Engine of the right underlying type.
/// TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead.
fn engine(
spec_params: SpecParams,
engine_spec: ethjson::spec::Engine,
params: CommonParams,
... | {
Machine::with_ethash_extensions(params, builtins, ethash.params.clone().into())
} | conditional_block |
spec.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 yo... | })
}
/// Loads spec from json file. Provide factories for executing contracts and ensuring
/// storage goes to the right place.
pub fn load<'a, T: Into<SpecParams<'a>>, R: Read>(params: T, reader: R) -> Result<Self, Error> {
ethjson::spec::Spec::load(reader)
.map_err(|e| Error::Msg(e.to_string()))
.and_... | let params = CommonParams::from(s.params);
Spec::machine(&s.engine, params, builtins) | random_line_split |
spec.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 yo... | (
spec_params: SpecParams,
engine_spec: ethjson::spec::Engine,
params: CommonParams,
builtins: BTreeMap<Address, Builtin>,
) -> Arc<dyn Engine> {
let machine = Self::machine(&engine_spec, params, builtins);
match engine_spec {
ethjson::spec::Engine::Null(null) => Arc::new(NullEngine::new(null.params.in... | engine | identifier_name |
spec.rs | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 yo... |
}
impl<'a, T: AsRef<Path>> From<&'a T> for SpecParams<'a> {
fn from(path: &'a T) -> Self {
Self::from_path(path.as_ref())
}
}
/// given a pre-constructor state, run all the given constructors and produce a new state and
/// state root.
fn run_constructors<T: Backend>(
genesis_state: &PodState,
constructors: &[... | {
SpecParams {
cache_dir: path,
optimization_setting: Some(optimization),
}
} | identifier_body |
language.go | package inclusion
import (
"fmt"
"regexp"
"strings"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
type InclusiveFilter struct {
Filter string // Supports regex
Reply string
regex *regexp.Regexp // do not fill. Just used for caching the regex once com... | d, ensure its bounded as it should.
if !strings.Contains(word.Filter, " ") {
word.Filter = fmt.Sprintf("(?:^|\\W)%s(?:$|[^\\w+])", word.Filter)
}
word.regex, _ = regexp.Compile(word.Filter)
}
if word.regex.MatchString(text) {
word.Reply += conductLinks
return &word
}
}
return nil
}
| conditional_block | |
language.go | package inclusion
import (
"fmt"
"regexp"
"strings"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
type InclusiveFilter struct {
Filter string // Supports regex
Reply string
regex *regexp.Regexp // do not fill. Just used for caching the regex once com... | := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
text, _, _ := transform.String(t, strings.ToLower(input))
filters := append(inclusiveFilters, extraFilters...)
for _, word := range filters {
if word.regex == nil {
// If it's just one word, ensure its bounded as it should.
if !strin... | identifier_body | |
language.go | package inclusion | "unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
type InclusiveFilter struct {
Filter string // Supports regex
Reply string
regex *regexp.Regexp // do not fill. Just used for caching the regex once compiled.
}
var conductLinks = "\nIn case of doubts please... |
import (
"fmt"
"regexp"
"strings" | random_line_split |
language.go | package inclusion
import (
"fmt"
"regexp"
"strings"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
type InclusiveFilter struct {
Filter string // Supports regex
Reply string
regex *regexp.Regexp // do not fill. Just used for caching the regex once com... | usiveFilter {
// Removing accents and others before matching
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
text, _, _ := transform.String(t, strings.ToLower(input))
filters := append(inclusiveFilters, extraFilters...)
for _, word := range filters {
if word.regex == nil {
// If ... | *Incl | identifier_name |
dynamic_scene.rs | use std::any::TypeId;
use crate::{DynamicSceneBuilder, Scene, SceneSpawnError};
use anyhow::Result;
use bevy_ecs::{
entity::Entity,
reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities},
world::World,
};
use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid};
use bevy_utils::HashMap;
... | use crate::dynamic_scene_builder::DynamicSceneBuilder;
#[test]
fn components_not_defined_in_scene_should_not_be_affected_by_scene_entity_map() {
// Testing that scene reloading applies EntityMap correctly to MapEntities components.
// First, we create a simple world with a parent and a chi... | use bevy_hierarchy::{AddChild, Parent};
use bevy_utils::HashMap;
| random_line_split |
dynamic_scene.rs | use std::any::TypeId;
use crate::{DynamicSceneBuilder, Scene, SceneSpawnError};
use anyhow::Result;
use bevy_ecs::{
entity::Entity,
reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities},
world::World,
};
use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid};
use bevy_utils::HashMap;
... |
}
Ok(())
}
/// Write the resources, the dynamic entities, and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// in the world's [`AppTypeRegistry`] resource, or doesn't reflect the
///... | {
map_entities_reflect.map_entities(world, entity_map, &entities);
} | conditional_block |
dynamic_scene.rs | use std::any::TypeId;
use crate::{DynamicSceneBuilder, Scene, SceneSpawnError};
use anyhow::Result;
use bevy_ecs::{
entity::Entity,
reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities},
world::World,
};
use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid};
use bevy_utils::HashMap;
... |
#[cfg(test)]
mod tests {
use bevy_ecs::{reflect::AppTypeRegistry, system::Command, world::World};
use bevy_hierarchy::{AddChild, Parent};
use bevy_utils::HashMap;
use crate::dynamic_scene_builder::DynamicSceneBuilder;
#[test]
fn components_not_defined_in_scene_should_not_be_affected_by_scene... | {
let pretty_config = ron::ser::PrettyConfig::default()
.indentor(" ".to_string())
.new_line("\n".to_string());
ron::ser::to_string_pretty(&serialize, pretty_config)
} | identifier_body |
dynamic_scene.rs | use std::any::TypeId;
use crate::{DynamicSceneBuilder, Scene, SceneSpawnError};
use anyhow::Result;
use bevy_ecs::{
entity::Entity,
reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities},
world::World,
};
use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid};
use bevy_utils::HashMap;
... | {
/// The identifier of the entity, unique within a scene (and the world it may have been generated from).
///
/// Components that reference this entity must consistently use this identifier.
pub entity: Entity,
/// A vector of boxed components that belong to the given entity and
/// implement ... | DynamicEntity | identifier_name |
bank.rs | #[macro_use]
extern crate clap;
extern crate rand;
extern crate distributary;
use std::sync;
use std::thread;
use std::time;
use std::collections::HashMap;
use distributary::{Blender, Base, Aggregation, JoinBuilder, Datas, DataType, Token, Mutator};
use rand::Rng;
extern crate hdrsample;
use hdrsample::Histogram... |
fn client(i: usize,
mut transfers_put: Box<Putter>,
balances_get: Box<Getter>,
naccounts: i64,
start: time::Instant,
runtime: time::Duration,
verbose: bool,
cdf: bool,
audit: bool,
transactions: &mut Vec<(i64, i64, i64)>)
... | {
// prepopulate non-transactionally (this is okay because we add no accounts while running the
// benchmark)
println!("Connected. Setting up {} accounts.", naccounts);
{
// let accounts_put = bank.accounts.as_ref().unwrap();
let mut money_put = transfers_put.transfer();
for i in... | identifier_body |
bank.rs | #[macro_use]
extern crate clap;
extern crate rand;
extern crate distributary;
use std::sync;
use std::thread;
use std::time;
use std::collections::HashMap;
use distributary::{Blender, Base, Aggregation, JoinBuilder, Datas, DataType, Token, Mutator};
use rand::Rng;
extern crate hdrsample;
use hdrsample::Histogram... | (naccounts: i64, transfers_put: &mut Box<Putter>) {
// prepopulate non-transactionally (this is okay because we add no accounts while running the
// benchmark)
println!("Connected. Setting up {} accounts.", naccounts);
{
// let accounts_put = bank.accounts.as_ref().unwrap();
let mut mone... | populate | identifier_name |
bank.rs | #[macro_use]
extern crate clap;
extern crate rand;
extern crate distributary;
use std::sync;
use std::thread;
use std::time;
use std::collections::HashMap;
use distributary::{Blender, Base, Aggregation, JoinBuilder, Datas, DataType, Token, Mutator};
use rand::Rng;
extern crate hdrsample;
use hdrsample::Histogram... |
let avg_put_throughput = |th: Vec<f64>| if avg {
let sum: f64 = th.iter().sum();
println!("avg PUT: {:.2}", sum / th.len() as f64);
};
if let Some(duration) = migrate_after {
thread::sleep(duration);
println!("----- starting migration -----");
let start = time::Inst... | })
})
.collect::<Vec<_>>(); | random_line_split |
HiddenEye.py | #!/usr/bin/python3
#-*- coding: utf-8 -*-
# HiddenEye v1.0
# By:- DARKSEC TEAM
#
###########################
from time import sleep
from sys import stdout, exit, argv
from os import system, path
from distutils.dir_util import copy_tree
import multiprocessing
from urllib.request import urlopen, quote, unquote
from... | (): #Question where user can input custom web-link
print("\n (Choose Wisely As Your Victim Will Redirect to This Link)".format(RED, DEFAULT))
print("\n (Leave Blank To Loop The Phishing Page)".format(RED, DEFAULT))
print("\n {0}Insert a custom redirect url:".format(CYAN, DEFAULT))
... | custom | identifier_name |
HiddenEye.py | #!/usr/bin/python3
#-*- coding: utf-8 -*-
# HiddenEye v1.0
# By:- DARKSEC TEAM
#
###########################
from time import sleep
from sys import stdout, exit, argv
from os import system, path
from distutils.dir_util import copy_tree
import multiprocessing
from urllib.request import urlopen, quote, unquote
from... |
checkNgrok()
def end(): #Message when HiddenEye exit
system('clear')
print ('''{1}THANK YOU FOR USING ! JOIN DARKSEC TEAM NOW (github.com/DarkSecDevelopers).{1}'''.format(RED, DEFAULT, CYAN))
print ('''{1}WAITING FOR YOUR CONTRIBUTION. GOOD BYE !.{1}'''.format(RED, DEFAULT, CYAN))
def loadModule(module):... | if path.isfile('Server/ngrok') == False:
print('[*] Downloading Ngrok...')
if 'Android' in str(check_output(('uname', '-a'))):
filename = 'ngrok-stable-linux-arm.zip'
else:
ostype = systemos().lower()
if architecture()[0] == '64bit':
filename =... | identifier_body |
HiddenEye.py | #!/usr/bin/python3
#-*- coding: utf-8 -*-
# HiddenEye v1.0
# By:- DARKSEC TEAM
#
###########################
from time import sleep
from sys import stdout, exit, argv
from os import system, path
from distutils.dir_util import copy_tree
import multiprocessing
from urllib.request import urlopen, quote, unquote
from... |
else:
matchObj = re.match('^(.*?),(.*)$', ipinfo['loc'])
latitude = matchObj.group(1)
longitude = matchObj.group(2)
log('======================================================================'.format(RED, DEFAULT))
... | log('======================================================================'.format(RED, DEFAULT))
log(' \n{0}[ VICTIM IP BONUS ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines) | conditional_block |
HiddenEye.py | #!/usr/bin/python3
#-*- coding: utf-8 -*-
# HiddenEye v1.0
# By:- DARKSEC TEAM
#
###########################
from time import sleep
from sys import stdout, exit, argv
from os import system, path
from distutils.dir_util import copy_tree
import multiprocessing
from urllib.request import urlopen, quote, unquote
from... |
if __name__ == "__main__":
try:
runPEnv()
def custom(): #Question where user can input custom web-link
print("\n (Choose Wisely As Your Victim Will Redirect to This Link)".format(RED, DEFAULT))
print("\n (Leave Blank To Loop The Phishing Page)".format(RED, DEFAULT))
... | random_line_split | |
lib.rs | use byteorder::{NativeEndian, ReadBytesExt};
use fftw::array::AlignedVec;
use fftw::plan::*;
use fftw::types::*;
use num_complex::Complex;
use ron::de::from_reader;
use serde::Deserialize;
use std::f64::consts::PI;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
/// A struct containing the configur... |
/// Calculates the cross power spectrum of the given 3D grids (note if the same
/// grid is given twice then this is the auto power spectrum).
///
/// # Examples
///
/// ```
/// let output: Output = correlate(&config, grid1, grid2).unwrap();
/// ```
pub fn correlate(
config: &Config,
out1: AlignedVec<c64>,
... | {
let mut out = AlignedVec::new(ngrid3);
match plan.c2c(&mut grid, &mut out) {
Ok(_) => (),
Err(_) => return Err("Failed to FFT grid."),
};
Ok(out)
} | identifier_body |
lib.rs | use byteorder::{NativeEndian, ReadBytesExt};
use fftw::array::AlignedVec;
use fftw::plan::*;
use fftw::types::*;
use num_complex::Complex;
use ron::de::from_reader;
use serde::Deserialize;
use std::f64::consts::PI;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
/// A struct containing the configur... | }
/// Performs FFT on grids
///
/// # Examples
///
/// ```
/// let output: Output = correlate(&config, grid1, grid2).unwrap();
/// ```
pub fn perform_fft(
config: &Config,
grid1: AlignedVec<c64>,
grid2: AlignedVec<c64>,
) -> Result<(AlignedVec<c64>, AlignedVec<c64>), &'static str> {
println!("\nPerform... | });
Ok(grid) | random_line_split |
lib.rs | use byteorder::{NativeEndian, ReadBytesExt};
use fftw::array::AlignedVec;
use fftw::plan::*;
use fftw::types::*;
use num_complex::Complex;
use ron::de::from_reader;
use serde::Deserialize;
use std::f64::consts::PI;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
/// A struct containing the configur... | (config: &Config, num: usize) -> Result<AlignedVec<c64>, &'static str> {
let filename = match num {
1 => &config.grid1_filename,
2 => &config.grid2_filename,
_ => return Err("Need to load either grid 1 or 2!"),
};
println!("\nOpening grid from file: {}", filename);
let ngrid: usi... | load_grid | identifier_name |
jwt.go | // Package token wraps jwt-go library and provides higher level abstraction to work with JWT.
package token
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt"
)
// Service wraps jwt operations
// supports both header and cookie tokens
type Service struct {
Opts
}
// Claims... | (opts Opts) *Service {
res := Service{Opts: opts}
setDefault := func(fld *string, def string) {
if *fld == "" {
*fld = def
}
}
setDefault(&res.JWTCookieName, defaultJWTCookieName)
setDefault(&res.JWTHeaderKey, defaultJWTHeaderKey)
setDefault(&res.XSRFCookieName, defaultXSRFCookieName)
setDefault(&res.XS... | NewService | identifier_name |
jwt.go | // Package token wraps jwt-go library and provides higher level abstraction to work with JWT.
package token
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt"
)
// Service wraps jwt operations
// supports both header and cookie tokens
type Service struct {
Opts
}
// Claims... |
// ClaimsUpdater defines interface adding extras to claims
type ClaimsUpdater interface {
Update(claims Claims) Claims
}
// ClaimsUpdFunc type is an adapter to allow the use of ordinary functions as ClaimsUpdater. If f is a function
// with the appropriate signature, ClaimsUpdFunc(f) is a Handler that calls f.
type... | {
return f(aud)
} | identifier_body |
jwt.go | // Package token wraps jwt-go library and provides higher level abstraction to work with JWT.
package token
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt"
)
// Service wraps jwt operations
// supports both header and cookie tokens
type Service struct { | type Claims struct {
jwt.StandardClaims
User *User `json:"user,omitempty"` // user info
SessionOnly bool `json:"sess_only,omitempty"`
Handshake *Handshake `json:"handshake,omitempty"` // used for oauth handshake
NoAva bool `json:"no-ava,omitempty"` // disable avatar, always use i... | Opts
}
// Claims stores user info for token and state & from from login | random_line_split |
jwt.go | // Package token wraps jwt-go library and provides higher level abstraction to work with JWT.
package token
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt"
)
// Service wraps jwt operations
// supports both header and cookie tokens
type Service struct {
Opts
}
// Claims... |
}
secret, err := j.SecretReader.Get(aud)
if err != nil {
return Claims{}, fmt.Errorf("can't get secret: %w", err)
}
token, err := parser.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("u... | {
return Claims{}, fmt.Errorf("can't retrieve audience from the token")
} | conditional_block |
helper.js | import * as R from 'ramda';
// error handling 없이 무조건 null return
export const checkTC = (fn) => {
try {
return fn();
} catch (e) {
return null;
}
};
export const isNull = (val) => {
return String(val) === 'NULL' ? null : val;
};
export const isBoolean = (val) => {
return String(val) === '0' ? false ... | f (appendText) rtnText = rtnText + appendText;
return rtnText;
}
return text;
};
// Blob -> String 변환
export const parseBlob = async (file) => {
const reader = new FileReader();
reader.readAsText(file);
return await new Promise((resolve, reject) => {
reader.onload = function (event) {
resolve(... | );
let rtnText = maskingArray.join('');
i | conditional_block |
helper.js | import * as R from 'ramda';
// error handling 없이 무조건 null return
export const checkTC = (fn) => {
try {
return fn();
} catch (e) {
return null;
}
};
export const isNull = (val) => {
return String(val) === 'NULL' ? null : val;
};
export const isBoolean = (val) => {
return String(val) === '0' ? false ... |
let p = point;
while (node) {
p = p + node.textContent.length;
text = isPre ? node.textContent + text : text + node.textContent;
node = getNode(parent, node, isPre, point);
}
// 문자열 앞뒤 공백 OR 문자열 확인
const firstWord = isPre ? text.substring(p - 1, p) : text.slice(0, 1);
const wordCheck = firstW... | random_line_split | |
api_op_CreateFileSystem.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package efs
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aw... |
func addIdempotencyToken_opCreateFileSystemMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateFileSystem{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateFileSystem(region string) *awsmid... | {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateFileSystemInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateFileSystemInput ")
}
if input.CreationToken == nil {
t, err := m.tokenProvider.GetIdempotencyT... | identifier_body |
api_op_CreateFileSystem.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package efs
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aw... |
if err = addCreateFileSystemResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = addIdempotencyToken_opCreateFileSystemMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateFileSystemValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initiali... | {
return err
} | conditional_block |
api_op_CreateFileSystem.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package efs
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aw... | () string {
return "ResolveEndpointV2"
}
func (m *opCreateFileSystemResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoin... | ID | identifier_name |
api_op_CreateFileSystem.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package efs
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aw... | ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
break
case *internalauth.AuthenticationSchemeV4A:
v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A)
if v4aScheme.SigningName == nil {
v4aScheme.SigningName = aws.String("elasticfilesystem")
}
if v4aScheme.DisableDoubleEnco... | // and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, signingName) | random_line_split |
lifa.py | from functools import reduce
from zhdate import ZhDate
import datetime
import openpyxl
import itertools
from django.db import connection
import os
# from admin_app.sys import public_db
from pypinyin import lazy_pinyin
def readxlsx():
filename = r'd:\测试excel1.xlsx'
inwb = openpyxl.load_workbook(filename)
s... |
# # for i in v:
# # sum_value += i[1]
# sum_value = sum(x[1] for x in v)
# lc[k] = sum_value
print(lc)
s = {}
for k, v in itertools.groupby(l1, lambda x: x[0]):
s[k] = sum(x[1] for x in v)
print(s)
class nation():
def __init__(self, key1, value1):
... | c = itertools.groupby(l1, lambda x: x[0])
lc = {}
for k, v in c:
print(list(v)[0])
# # sum_value = 0 | conditional_block |
lifa.py | from functools import reduce
from zhdate import ZhDate
import datetime
import openpyxl
import itertools
from django.db import connection
import os
# from admin_app.sys import public_db
from pypinyin import lazy_pinyin
def readxlsx():
filename = r'd:\测试excel1.xlsx'
inwb = openpyxl.load_workbook(filename)
s... | },
{
"key": 4,
"value": "4-陪产假"
},
{
"key": 5,
"value": "5-婚假"
},
{
"key": 6,
"value": "6-丧假"
}
],
"category": "",
"start_date": "",
"days": "",
"agent_name": "",
"end_date": "",
"reason": "",
"remark": "",
"status": "0",
"apply_state":... | "key": 3,
"value": "3-产假" | random_line_split |
lifa.py | from functools import reduce
from zhdate import ZhDate
import datetime
import openpyxl
import itertools
from django.db import connection
import os
# from admin_app.sys import public_db
from pypinyin import lazy_pinyin
def readxlsx():
filename = r'd:\测试excel1.xlsx'
inwb = openpyxl.load_workbook(filename)
s... | unit": "联桥科技有限公司",
"rec_unit": "",
"supply_address": "许昌市中原电气谷森尼瑞节能产业园四楼",
"rec_address": "",
"sp_contact": "",
"rec_contact": "",
"supply_phone": "",
"rec_phone": "",
"ERP_no": "",
"express_no": "",
"notice_date": "2021-04-16 14:36:55",
"send_date": "",
"order_detail": [... |
temp = form_var
# temp = eval(form_var)
for k in param:
if not temp.get(k):
respcode, respmsg = str(temp_code), param.get(k) + '不可为空'
# respinfo = HttpResponse(public.setrespinfo())
return respcode, respmsg
form_var = {
"supply_ | identifier_body |
lifa.py | from functools import reduce
from zhdate import ZhDate
import datetime
import openpyxl
import itertools
from django.db import connection
import os
# from admin_app.sys import public_db
from pypinyin import lazy_pinyin
def readxlsx():
filename = r'd:\测试excel1.xlsx'
inwb = openpyxl.load_workbook(filename)
s... | uments\a.json"
lx = []
with(open(file_path, encoding='utf-8')) as f:
for line in f:
# temp_row = 'key:'+line[:line.index(',')]
mz = nation(line[:line.index(',')], line[line.index(',') + 1:-1])
lx.append(mz.__dict__)
print(lx)
def auto_generate_sql(input):
te... | er\Doc | identifier_name |
jenkins-mod-main.rs | #[macro_use]
extern crate error_chain;
extern crate hyper;
extern crate log4rs;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate structopt;
#[macro_use]
extern crate structopt_derive;
extern crate toml;
use hyper::client::{Client, RedirectPolicy};
use serd... | // write the body here
let mut client = Client::new();
client.set_redirect_policy(RedirectPolicy::FollowAll);
let mut resp = client.get(&config.update_center_url).send().chain_err(|| {
format!(
"Unable to perform HTTP request with URL string '{}'",
config.update_center_u... | })?;
info!("Completed configuration initialization!");
| random_line_split |
jenkins-mod-main.rs | #[macro_use]
extern crate error_chain;
extern crate hyper;
extern crate log4rs;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate structopt;
#[macro_use]
extern crate structopt_derive;
extern crate toml;
use hyper::client::{Client, RedirectPolicy};
use serd... |
None => Ok(()),
}
};
create_parent_dir_if_present(config.modified_json_file_path.parent())?;
create_parent_dir_if_present(config.url_list_json_file_path.parent())?;
}
let mut json_file = File::create(&config.modified_json_file_path)
.chain_err(|| "... | {
info!("Creating directory chain: {:?}", dir);
fs::create_dir_all(dir)
.chain_err(|| format!("Unable to create directory chain: {:?}", dir))
} | conditional_block |
jenkins-mod-main.rs | #[macro_use]
extern crate error_chain;
extern crate hyper;
extern crate log4rs;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate structopt;
#[macro_use]
extern crate structopt_derive;
extern crate toml;
use hyper::client::{Client, RedirectPolicy};
use serd... | <S: Into<String>>(
resp_outer_map: &mut MapStrVal,
connection_check_url_change: S,
) -> Result<()> {
let connection_check_url = match resp_outer_map.get_mut(CONNECTION_CHECK_URL_KEY) {
Some(connection_check_url) => connection_check_url,
None => bail!(format!(
"Unable to find '{}'... | change_connection_check_url | identifier_name |
mod.rs | use core::iter::Iterator;
use super::*;
use crate::error_consts::*;
//#[test]
//mod test;
#[derive(Clone)]
pub struct Line {
tag: char,
matched: bool,
text: String,
}
pub struct VecBuffer {
saved: bool,
// Chars used for tagging. No tag equates to NULL in the char
buffer: Vec<Line>,
clipboard: Vec<Line... | ;
// If there is no newline at the end, join next line
if !after.ends_with('\n') {
if tail.len() > 0 {
after.push_str(&tail.remove(0).text);
}
else {
after.push('\n');
}
}
// Split on newlines and add all lines to the buffer
for line in after.lines() {
s... | {
regex.replace(&tmp.text, pattern.1).to_string()
} | conditional_block |
mod.rs | use core::iter::Iterator;
use super::*;
use crate::error_consts::*;
//#[test]
//mod test;
#[derive(Clone)]
pub struct Line {
tag: char,
matched: bool,
text: String,
}
pub struct VecBuffer {
saved: bool,
// Chars used for tagging. No tag equates to NULL in the char
buffer: Vec<Line>,
clipboard: Vec<Line... | (&mut self, selection: Option<(usize, usize)>, path: &str, append: bool)
-> Result<(), &'static str>
{
let data = match selection {
Some(sel) => self.get_selection(sel)?,
None => Box::new(self.buffer[..].iter().map(|line| &line.text[..])),
};
file::write_file(path, data, append)?;
if s... | write_to | identifier_name |
mod.rs | use core::iter::Iterator;
use super::*;
use crate::error_consts::*;
//#[test]
//mod test;
#[derive(Clone)]
pub struct Line {
tag: char,
matched: bool,
text: String,
}
pub struct VecBuffer {
saved: bool,
// Chars used for tagging. No tag equates to NULL in the char
buffer: Vec<Line>,
clipboard: Vec<Line... | buffer: Vec::new(),
clipboard: Vec::new(),
}
}
}
impl Buffer for VecBuffer {
// Index operations, get and verify
fn len(&self) -> usize {
self.buffer.len()
}
fn get_tag(&self, tag: char)
-> Result<usize, &'static str>
{
let mut index = 0;
for line in &self.buffer[..] {
... | saved: true, | random_line_split |
simple_xia2_to_shelxcde_new.py | #!/bin/env python3
import argparse
import fileinput
import sys
import shutil
import os
import procrunner
import gemmi
import re
from xia2_json_reader import xia2_json_reader
from mtz_data_object import MtzData
from seq_data_object import SeqData
from matth_coeff_function_object import MattCoeff, matt_coeff_factory
fro... | (name, cell, wavelengths, sg, find, ntry=1000):
print("SHELXC")
print("======")
cell_round = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, cell))
keywords = []
for w in wavelengths:
label = w['label']
sca = os.path.relpath(w['sca'])
keywords.append("{0} {1}\n".format(label, sca)... | simpleSHELXC | identifier_name |
simple_xia2_to_shelxcde_new.py | #!/bin/env python3
import argparse
import fileinput
import sys
import shutil
import os
import procrunner
import gemmi
import re
from xia2_json_reader import xia2_json_reader
from mtz_data_object import MtzData
from seq_data_object import SeqData
from matth_coeff_function_object import MattCoeff, matt_coeff_factory
fro... |
else:
if not os.path.exists(args.xia2dir):
raise RuntimeError('%s does not exist' % args.xia2dir)
if args.atom is None:
print("Defaulting to --atom Se")
args.atom = "Se"
if args.ntry is None:
print("Defaulting to --ntry 1000")
args.ntry = 1000
########################################... | raise RuntimeError('Need to specify the path to the xia2 processing directory') | conditional_block |
simple_xia2_to_shelxcde_new.py | #!/bin/env python3
import argparse
import fileinput
import sys
import shutil
import os
import procrunner
import gemmi
import re
from xia2_json_reader import xia2_json_reader
from mtz_data_object import MtzData
from seq_data_object import SeqData
from matth_coeff_function_object import MattCoeff, matt_coeff_factory
fro... |
# cmd = "/dls_sw/apps/shelx/64/2017-1/shelxe {0} {1} -s{2} -m200 -h{3} -z{3} -e1".format(name, fa, solvent_frac, find)
#below is original line which is not used for this run
#cmd = "/dls_sw/apps/shelx/64/2017-1/shelxe {0} {1} -s{2} -m -h{3} -z{3} -a5 -q".format(name, fa, solvent_frac, find)
#cmd = "shelxe {0} {... | fa = name + '_fa'
solvent = "-s{0}".format(round(solvent_frac), 4)
m_value = "-m"
h_value = "-h{0}".format(find)
z_value = "-z{0}".format(find)
msg = "SHELXE - {0} hand"
if not inverse_hand:
msg = msg.format("original")
print(msg)
print("=" * len(msg))
result = procrunner.run(["shelxe"... | identifier_body |
simple_xia2_to_shelxcde_new.py | #!/bin/env python3
import argparse
import fileinput
import sys
import shutil
import os
import procrunner
import gemmi
import re
from xia2_json_reader import xia2_json_reader
from mtz_data_object import MtzData
from seq_data_object import SeqData
from matth_coeff_function_object import MattCoeff, matt_coeff_factory
fro... | shutil.copy(w['sca'], '.')
w['sca'] = os.path.abspath(f)
return wavelengths
if __name__ == '__main__':
########################################################################
### receive command line arguments
########################################################################
parser = argparse.Arg... | def copy_sca_locally(wavelengths):
'''Copy .sca files locally to work around problem at DLS where SHELX fails
to find the files'''
for w in wavelengths:
f = os.path.basename(w['sca']) | random_line_split |
day24b.rs | #![feature(drain_filter)]
use clap::Parser;
use env_logger::Env;
use log::{debug, info};
use std::cell::Cell;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
/// Advent of Code 2022, Day 24
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Input fi... | }
fn main() {
env_logger::Builder::from_env(Env::default().default_filter_or("info"))
.format_timestamp(None)
.init();
let args = Args::parse();
let nways: usize = match args.part {
1 => 1, // start-exit
2 => 3, // start-exit-start-exit
part @ _ => panic!("Don't kno... | ))
.collect::<String>()
.trim_end()
)
} | random_line_split |
day24b.rs | #![feature(drain_filter)]
use clap::Parser;
use env_logger::Env;
use log::{debug, info};
use std::cell::Cell;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
/// Advent of Code 2022, Day 24
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Input fi... |
}
impl Map {
/// Create a new empty Map with the specified dimensions.
pub fn empty((nrows, ncols): (usize, usize)) -> Map {
let start = (1, 0);
let exit = (ncols - 2, nrows - 1);
Map {
grid: (0..nrows)
.map(|nrow| {
(0..ncols)
... | {
let nblizzards = self.blizzards.len();
match (self, nblizzards) {
(MapPos { wall: true, .. }, _) => '#',
(MapPos { wall: false, .. }, 0) => '.',
(MapPos { wall: false, .. }, 1) => self.blizzards[0],
(MapPos { wall: false, .. }, 2 | 3 | 4 | 5 | 6 | 7 | 8 ... | identifier_body |
day24b.rs | #![feature(drain_filter)]
use clap::Parser;
use env_logger::Env;
use log::{debug, info};
use std::cell::Cell;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
/// Advent of Code 2022, Day 24
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Input fi... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"\n{}",
self.grid
.iter()
.enumerate()
.map(|(rownum, row)| format!(
"{}\n",
row.iter()
.enumerate()... | fmt | identifier_name |
interface.rs | //! All the nitty gritty details regarding COM interface for the shell extension
//! are defined here.
//!
//! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers
use com::sys::HRESULT;
use guid_win::Guid;
use once_cell::sync::Lazy;
use std::cell::RefCell;
use std::... | }
winerror::CLASS_E_CLASSNOTAVAILABLE
}
/// Add in-process server keys into registry.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllregisterserver
#[no_mangle]
extern "system" fn DllRegisterServer() -> HRESULT {
let hinstance = unsafe { DLL_HANDLE };
let path = mat... | random_line_split | |
interface.rs | //! All the nitty gritty details regarding COM interface for the shell extension
//! are defined here.
//!
//! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers
use com::sys::HRESULT;
use guid_win::Guid;
use once_cell::sync::Lazy;
use std::cell::RefCell;
use std::... |
winerror::CLASS_E_CLASSNOTAVAILABLE
}
/// Add in-process server keys into registry.
///
/// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllregisterserver
#[no_mangle]
extern "system" fn DllRegisterServer() -> HRESULT {
let hinstance = unsafe { DLL_HANDLE };
let path = match ge... | {
log::warn!("Unsupported class: {}", class_guid);
} | conditional_block |
interface.rs | //! All the nitty gritty details regarding COM interface for the shell extension
//! are defined here.
//!
//! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers
use com::sys::HRESULT;
use guid_win::Guid;
use once_cell::sync::Lazy;
use std::cell::RefCell;
use std::... |
/// Convert Win32 GUID pointer to Guid struct.
const fn guid_from_ref(clsid: *const guiddef::GUID) -> Guid {
Guid {
0: unsafe { *clsid },
}
}
/// Get path to loaded DLL file.
fn get_module_path(hinstance: win::HINSTANCE) -> Result<PathBuf, Error> {
use std::ffi::OsString;
use std::os::windows... | {
match wslscript_common::registry::remove_server_from_registry() {
Ok(_) => (),
Err(e) => {
log::error!("Failed to unregister server: {}", e);
return winerror::E_UNEXPECTED;
}
}
winerror::S_OK
} | identifier_body |
interface.rs | //! All the nitty gritty details regarding COM interface for the shell extension
//! are defined here.
//!
//! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers
use com::sys::HRESULT;
use guid_win::Guid;
use once_cell::sync::Lazy;
use std::cell::RefCell;
use std::... | () -> HRESULT {
let hinstance = unsafe { DLL_HANDLE };
let path = match get_module_path(hinstance) {
Ok(p) => p,
Err(_) => return winerror::E_UNEXPECTED,
};
log::debug!("DllRegisterServer for {}", path.to_string_lossy());
match wslscript_common::registry::add_server_to_registry(&path... | DllRegisterServer | identifier_name |
gbc.go | package gbc
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/djhworld/gomeboycolor/apu"
"github.com/djhworld/gomeboycolor/cartridge"
"github.com/djhworld/gomeboycolor/config"
"github.com/djhworld/gomeboycolor/cpu"
"github.com/djhworld/gomeboycolor/dma"
"github.com/djhworld/gomeboycolor/gpu"
"github... |
func (gbc *GomeboyColor) doFrameWithDebug() {
for gbc.cpuClockAcc < FRAME_CYCLES {
if gbc.cpu.PC == gbc.debugOptions.breakWhen {
gbc.pause()
}
if gbc.config.DumpState && !gbc.cpu.Halted {
fmt.Println("\t ", gbc.cpu)
}
gbc.Step()
}
}
func (gbc *GomeboyColor) setupBoot() {
if gbc.config.SkipBoot {
... | {
for gbc.cpuClockAcc < FRAME_CYCLES {
gbc.Step()
}
} | identifier_body |
gbc.go | package gbc
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/djhworld/gomeboycolor/apu"
"github.com/djhworld/gomeboycolor/cartridge"
"github.com/djhworld/gomeboycolor/config"
"github.com/djhworld/gomeboycolor/cpu"
"github.com/djhworld/gomeboycolor/dma"
"github.com/djhworld/gomeboycolor/gpu"
"github... | else {
frameRunnerWrapper(gbc.doFrameWithDebug)
}
gbc.cpuClockAcc = 0
}
}
func (gbc *GomeboyColor) RunIO() {
gbc.io.Run()
}
func (gbc *GomeboyColor) Step() {
cycles := 0x00
if gbc.hDMA.IsRunning() {
gbc.hDMA.Step()
} else {
cycles = gbc.cpu.Step()
}
//GPU is unaffected by CPU speed changes
gbc.gp... | {
frameRunnerWrapper(gbc.doFrame)
} | conditional_block |
gbc.go | package gbc
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/djhworld/gomeboycolor/apu"
"github.com/djhworld/gomeboycolor/cartridge"
"github.com/djhworld/gomeboycolor/config"
"github.com/djhworld/gomeboycolor/cpu"
"github.com/djhworld/gomeboycolor/dma"
"github.com/djhworld/gomeboycolor/gpu"
"github... | //Determine if ColorGB hardware should be enabled
func (gbc *GomeboyColor) setHardwareMode(isColor bool) {
if isColor {
gbc.cpu.R.A = 0x11
gbc.gpu.RunningColorGBHardware = gbc.mmu.IsCartridgeColor()
gbc.mmu.RunningColorGBHardware = true
} else {
gbc.cpu.R.A = 0x01
gbc.gpu.RunningColorGBHardware = false
gb... | }
}
}
| random_line_split |
gbc.go | package gbc
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/djhworld/gomeboycolor/apu"
"github.com/djhworld/gomeboycolor/cartridge"
"github.com/djhworld/gomeboycolor/config"
"github.com/djhworld/gomeboycolor/cpu"
"github.com/djhworld/gomeboycolor/dma"
"github.com/djhworld/gomeboycolor/gpu"
"github... | () {
gbc.inBootMode = true
gbc.mmu.WriteByte(0xFF50, 0x00)
}
func (gbc *GomeboyColor) checkBootModeStatus() {
//value in FF50 means gameboy has finished booting
if gbc.inBootMode {
if gbc.mmu.ReadByte(0xFF50) != 0x00 {
gbc.cpu.PC = 0x0100
gbc.mmu.SetInBootMode(false)
gbc.inBootMode = false
//put the... | setupWithBoot | identifier_name |
server.rs | // Copyright 2020 Oxide Computer Company
/*!
* Generic server-wide state and facilities
*/
use super::api_description::ApiDescription;
use super::config::ConfigDropshot;
use super::error::HttpError;
use super::handler::RequestContext;
use super::http_util::HEADER_REQUEST_ID;
use super::probes;
use super::router::Htt... |
}
/**
* Return the result of registering the server's DTrace USDT probes.
*
* See [`ProbeRegistration`] for details.
*/
pub fn probe_registration(&self) -> &ProbeRegistration {
&self.probe_registration
}
}
/*
* For graceful termination, the `close()` function is preferred... | {
Ok(())
} | conditional_block |
server.rs | // Copyright 2020 Oxide Computer Company
/*!
* Generic server-wide state and facilities
*/
use super::api_description::ApiDescription;
use super::config::ConfigDropshot;
use super::error::HttpError;
use super::handler::RequestContext;
use super::http_util::HEADER_REQUEST_ID;
use super::probes;
use super::router::Htt... | self.app_state.log,
"failed to register DTrace USDT probes: {}", msg
);
ProbeRegistration::Failed(msg)
}
}
} else {
debug!(
self.app_state.log,
"DTrace ... | }
Err(e) => {
let msg = e.to_string();
error!( | random_line_split |
server.rs | // Copyright 2020 Oxide Computer Company
/*!
* Generic server-wide state and facilities
*/
use super::api_description::ApiDescription;
use super::config::ConfigDropshot;
use super::error::HttpError;
use super::handler::RequestContext;
use super::http_util::HEADER_REQUEST_ID;
use super::probes;
use super::router::Htt... | (
_rqctx: Arc<RequestContext<i32>>,
) -> Result<HttpResponseOk<u64>, HttpError> {
Ok(HttpResponseOk(3))
}
struct TestConfig {
log_context: LogContext,
}
impl TestConfig {
fn log(&self) -> &slog::Logger {
&self.log_context.log
}
}
fn crea... | handler | identifier_name |
kflash.rs | //! Kendryte K210 UART ISP, based on [`kflash.py`]
//! (https://github.com/sipeed/kflash.py)
use anyhow::Result;
use crc::{crc32, Hasher32};
use std::{future::Future, marker::Unpin, path::Path, pin::Pin, sync::Mutex, time::Duration};
use tokio::{
io::{AsyncBufRead, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt... | (
reader: &mut (impl AsyncRead + Unpin),
) -> std::io::Result<std::convert::Infallible> {
let mut buf = [0u8; 256];
loop {
let num_bytes = reader.read(&mut buf).await?;
log::trace!("Discarding {} byte(s)", num_bytes);
}
}
#[derive(thiserror::Error, Debug)]
enum ProcessElfError {
#[e... | read_to_end_and_discard | identifier_name |
kflash.rs | //! Kendryte K210 UART ISP, based on [`kflash.py`]
//! (https://github.com/sipeed/kflash.py)
use anyhow::Result;
use crc::{crc32, Hasher32};
use std::{future::Future, marker::Unpin, path::Path, pin::Pin, sync::Mutex, time::Duration};
use tokio::{
io::{AsyncBufRead, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt... | BadInitialization,
BadExec,
Unknown(u8),
}
impl From<u8> for IspReasonCode {
fn from(x: u8) -> Self {
match x {
0x00 => Self::Default,
0xe0 => Self::Ok,
0xe1 => Self::BadDataLen,
0xe2 => Self::BadDataChecksum,
0xe3 => Self::InvalidComm... | BadDataChecksum,
InvalidCommand, | random_line_split |
modes.go | /*
Copyright 2021 Sonobuoy Contributors
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 writing, so... |
return s[0:count] + "... (truncated) ..."
}
| {
return s
} | conditional_block |
modes.go | /*
Copyright 2021 Sonobuoy Contributors
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 writing, so... | () *cobra.Command {
f := modesOptions{}
var modesCmd = &cobra.Command{
Use: "modes",
Short: "Display the various modes in which to run the e2e plugin",
Run: func(cmd *cobra.Command, args []string) {
showModes(f)
},
Args: cobra.ExactArgs(0),
}
modesCmd.Flags().BoolVar(&f.verbose, "verbose", false, "D... | NewCmdModes | identifier_name |
modes.go | /*
Copyright 2021 Sonobuoy Contributors
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 writing, so... |
func validE2eModes() []string {
keys := []string{}
for key := range validModes {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
type modesOptions struct {
verbose bool
}
func NewCmdModes() *cobra.Command {
f := modesOptions{}
var modesCmd = &cobra.Command{
Use: "modes",
Short: "Display ... | {
quoted := make([]string, len(liteSkips))
for i, v := range liteSkips {
quoted[i] = regexp.QuoteMeta(v)
// Quotes will cause the regexp to explode; easy to just change them to wildcards without an issue.
quoted[i] = strings.ReplaceAll(quoted[i], `"`, ".")
}
return strings.Join(quoted, "|")
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.