lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
C++
treap_vis_multiset.cc
varqox/benchmarks
7713013f1a6af368da4cf634a72ae69ca6d17334
#include <bits/stdc++.h> using namespace std; #define FOR(i,a,n) for (decltype(a) i = (a), i##__ = (n); i <= i##__; ++i) #define REP(i,n) FOR(i,0,(n)-1) #define FORD(i,a,n) for (decltype(n) i = (a), i##__ = (n); i >= i##__; --i) #define ALL(x) x.begin(), x.end() #define EB emplace_back #define ST first #define ND sec...
#include <bits/stdc++.h> using namespace std; #define FOR(i,a,n) for (decltype(a) i = (a), i##__ = (n); i <= i##__; ++i) #define REP(i,n) FOR(i,0,(n)-1) #define FORD(i,a,n) for (decltype(n) i = (a), i##__ = (n); i >= i##__; --i) #define ALL(x) x.begin(), x.end() #define EB emplace_back #define ST first #define ND sec...
template<class... T> void __e(T&&... a) { int t[] = {(cerr << forward<T>(a), 0)...}; (void)t; cerr << endl; } template<class A, class B> inline void mini(A& a, B&& b) { if (b < a) a = b; } template<class A, class B> inline void maxi(A& a, B&& b) { if (b > a) a = b; } inline int ceil2(int x) { return (x < 2 ? 1 : 1...
ostream& __d(ostream& os, I a, I b) { os << "{\n"; for (I c = a; a != b; ++a) os << " " << distance(c, a) << ": " << *a << endl; return os << "}"; }
function_block-function_prefix_line
[ { "content": "class Cstring {\n\nprivate:\n\n\tsize_t len_, real_len_;\n\npublic:\n\n\tchar *p;\n\n\n\n\texplicit Cstring(size_t len = 0, char c = '\\0'): len_(len),\n\n\t\t\treal_len_(len + 1), p((char*)malloc(real_len_)) {\n\n\t\tif (p == NULL)\n\n\t\t\tthrow std::bad_alloc();\n\n\n\n\t\tmemset(p, c, len);\n\...
C++
src/lib/drishti/eye/EyeModelEyelids.cpp
ZJCRT/drishti
7c0da7e71cd4cff838b0b8ef195855cb68951839
#include "drishti/eye/EyeModelEstimatorImpl.h" #include "drishti/core/drishti_stdlib_string.h" #include "drishti/eye/EyeIO.h" #define DRISHTI_EYE_DEBUG_INITS 0 #if DRISHTI_EYE_DEBUG_INITS # include <opencv2/highgui.hpp> #endif DRISHTI_EYE_NAMESPACE_BEGIN using PointVec = std::vector<cv::Point2f>; static void ji...
#include "drishti/eye/EyeModelEstimatorImpl.h" #include "drishti/core/drishti_stdlib_string.h" #include "drishti/eye/EyeIO.h" #define DRISHTI_EYE_DEBUG_INITS 0 #if DRISHTI_EYE_DEBUG_INITS # include <opencv2/highgui.hpp> #endif DRISHTI_EYE_NAMESPACE_BEGIN using PointVec = std::vector<cv::Point2f>; static void ji...
static PointVec getMedianOfPoses(const std::vector<PointVec>& poses) { std::vector<std::vector<float>> params[2]; params[0].resize(poses[0].size()); params[1].resize(poses[0].size()); for (const auto & pose : poses) { for (int j = 0; j < pose.size(); j++) { params[0][j]...
static void jitter(const EyeModel& eye, const geometry::UniformSimilarityParams& params, std::vector<EyeModel>& poses, int n) { cv::Point2f center = drishti::core::centroid(eye.eyelids); const geometry::UniformSimilarityParams& params_ = params; for (int i = 0; i < n; i++) { cv::Matx33f H =...
function_block-full_function
[]
C++
Development/OrignalDev/Util/EventTimeLine.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
#include "Jack/EventTimeLine.hh" #include "Ravl/GUI/Manager.hh" #include "Ravl/Image/Font.hh" #include <gdk/gdk.h> #define DODEBUG 0 #if DODEBUG #define ONDEBUG(x) x #else #define ONDEBUG(x) #endif namespace RavlGUIN { using namespace RavlAudioN; EventTimeLineBodyC::EventTimeLineBodyC() : RawCanvasBody...
#include "Jack/EventTimeLine.hh" #include "Ravl/GUI/Manager.hh" #include "Ravl/Image/Font.hh" #include <gdk/gdk.h> #define DODEBUG 0 #if DODEBUG #define ONDEBUG(x) x #else #define ONDEBUG(x) #endif namespace RavlGUIN { using namespace RavlAudioN; EventTimeLineBodyC::EventTimeLineBodyC() : RawCanvasBody...
#endif #if 1 if(markerGcR != 0) { IndexRange2dC markRange(displayArea.Range1(), IndexRangeC((markerRight - displayRange.Min()) * scale, ((markerRight+1) - displayRange.Min()) * scale)); if(markRange.Range2().Size() < 3) { markRange.Range2().Expand((3 - markRange.Range2(...
if(markerGcL != 0) { IndexRange2dC markRange(displayArea.Range1(), IndexRangeC((markerLeft - displayRange.Min()) * scale, ((markerLeft+1) - displayRange.Min()) * scale)); if(markRange.Range2().Size() < 3) { markRange.Range2().Expand((3 - markRange.Range2().Size())/2); } ...
if_condition
[ { "content": "\n\n#include \"../.././GUI/Util/EventTimeLine.hh\"\n\n\n", "file_path": "RAVL2/MSVC/include/Ravl/GUI/EventTimeLine.hh", "rank": 0, "score": 176136.96804029416 }, { "content": " class EventTimeLineC;\n\n \n\n //! userlevel=Develop\n\n //: Event time line.\n\n \n", "file...
C++
printscan/print/drivers/usermode/tools/uni/minidev.new/tips.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
#include "StdAfx.H" #include "Resource.H" #include <WinReg.H> #include <Sys\Stat.H> #include <Sys\Types.H> #include "tips.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define MAX_BUFLEN 1000 static const TCHAR szSection[] =...
#include "StdAfx.H" #include "Resource.H" #include <WinReg.H> #include <Sys\Stat.H> #include <Sys\Types.H> #include "tips.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define MAX_BUFLEN 1000 static const TCHAR szSection[] =...
} } void CTipOfTheDay::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Check(pDX, IDC_STARTUP, m_bStartup); DDX_Text(pDX, IDC_TIPSTRING, m_strTip); } BEGIN_MESSAGE_MAP(CTipOfTheDay, CDialog) ON_BN_CLICKED(IDC_NEXTTIP, OnNextTip) ON_WM_CTLCOLOR() ON_WM_PAINT() ...
if (m_pStream != NULL) { CWinApp* pApp = AfxGetApp(); pApp->WriteProfileInt(szSection, szIntFilePos, ftell(m_pStream)); fclose(m_pStream);
function_block-random_span
[]
C++
src/kdtree.cpp
pillowsofwind/mini_renderer
a02b16c4a96d21fc5920479ea496b31f462a6407
#include "kdtree.hpp" #include <climits> #include <iostream> #include <algorithm> using namespace std; void KDTree::load(int _size, HitPoint *_data) { m_nNode = 0; m_size = _size; m_data = _data; m_index = new int[m_size]; m_memory = new Node[m_size]; for (int i = 0; i < m_size; +...
#include "kdtree.hpp" #include <climits> #include <iostream> #include <algorithm> using namespace std; void KDTree::load(int _size, HitPoint *_data) { m_nNode = 0; m_size = _size; m_data = _data; m_index = new int[m_size]; m_memory = new Node[m_size]; for (int i = 0; i < m_size; +...
e->left) update(node->left); if (node->right) update(node->right); m_data[node->value].maxRadius2 = m_data[node->value].radius2; if (node->left && m_data[node->left->value].maxRadius2 > m_data[node->value].maxRadius2) m_data[node->value].maxRadius2 = m_data[node->left->value].maxRadius2; ...
ax[i] = LONG_MIN; for (int i = 0; i < m_size; ++i) { Vector3f temp = m_data[i].position;; for (int j = 0; j < K; ++j) { if (m_data[i].position[j] < min[j]) min[j] = m_data[i].position[j]; if (m_data[i].position[j] > max[j]) max[j] = m_data[i].position[j]; } ...
random
[ { "content": "struct OctNode {\n\n OctNode *child[8];\n\n\n\n OctNode() {\n\n child[0] = 0;\n\n }\n\n\n\n bool isTerm() { return child[0] == 0; }\n\n\n\n std::vector<int> obj;\n\n};\n\n\n", "file_path": "include/octree.hpp", "rank": 0, "score": 62447.16502680025 }, { "c...
C++
src/WebInterface/CController.hpp
Fabio3rs/cppapiframework
14f1b1b42b77edbbf72d9d7f949ea6c9fcfa06a5
#pragma once #ifndef CController_hpp #define CController_hpp #include "../stdafx.hpp" #include "pistache.hpp" struct httpStreamPack { const Pistache::Rest::Request &request; Pistache::Http::ResponseWriter &response; httpStreamPack(const Pistache::Rest::Request &req, Pistache::Http::Re...
#pragma once #ifndef CController_hpp #define CController_hpp #include "../stdafx.hpp" #include "pistache.hpp" struct httpStreamPack { const Pistache::Rest::Request &request; Pistache::Http::ResponseWriter &response; httpStreamPack(const Pistache::Rest::Request &req, Pistache::Http::Re...
); inputstream.seekg(0, std::ios::beg); response.setMime(Pistache::Http::Mime::MediaType( Pistache::Http::Mime::Type::Application, Pistache::Http::Mime::Subtype::Ext, Pistache::Http::Mime::Suffix::Zip)); auto stream = response.stream(Pistache::Http::Code::Ok...
on_return(bool success, const std::string &msg) -> Poco::JSON::Object::Ptr; static auto default_json_return(bool success, const std::string &msg, const Poco::UUID &uuid) -> Poco::JSON::Object::Ptr; static auto default_json_return_as_str(bool success, const s...
random
[ { "content": "class JsonResponse : public ResponseViaReturn {\n\n\n\n public:\n\n JsonResponse(const JsonResponse &) = default;\n\n JsonResponse(JsonResponse &&) = default;\n\n\n\n auto operator=(const JsonResponse &) -> JsonResponse & = default;\n\n auto operator=(JsonResponse &&) -> JsonResponse ...
C++
src/main.cpp
Laakeri/pace2020-treedepth-exact
1049abbe6fb4012f027c2fcfce15fff5fa8c169f
#include <iostream> #include <vector> #include <memory> #include <fstream> #include <iomanip> #include <set> #include <cassert> #include <random> #include <sys/resource.h> #include "graph.hpp" #include "io.hpp" #include "utils.hpp" #include "mcs.hpp" #include "staticset.hpp" #include "bitset.hpp" #include "chordalsolv...
#include <iostream> #include <vector> #include <memory> #include <fstream> #include <iomanip> #include <set> #include <cassert> #include <random> #include <sys/resource.h> #include "graph.hpp" #include "io.hpp" #include "utils.hpp" #include "mcs.hpp" #include "staticset.hpp" #include "bitset.hpp" #include "chordalsolv...
template<size_t chunks> int HeurComp(const FGraph<chunks>& graph, int best, double time, const Preprocessor& pp) { Timer timer; timer.start(); int it=0; std::set<uint64_t> gs; int vari = 0; int upd_cnt = 0; int last_add = 0; while (timer.get() < time) { double dupls = 0; if (it > 0) { du...
void SetStackSize(int64_t sz) { struct rlimit rl; assert(getrlimit(RLIMIT_STACK, &rl) == 0); Log::Write(3, "Cur stack size ", rl.rlim_cur); if (rl.rlim_cur < sz) { rl.rlim_cur = sz; Log::Write(3, "Setting stack size ", sz); assert(setrlimit(RLIMIT_STACK, &rl) == 0); } }
function_block-full_function
[ { "content": "class FBitsetSet {\n\n public:\n\n FBitsetSet() {}\n\n FBitsetSet(size_t capacity, double load_factor) {\n\n load_factor_ = load_factor;\n\n assert(chunks > 0);\n\n assert(load_factor_ >= 1.1);\n\n capacity_ = NextPrime((capacity + 1) * load_factor_);\n\n assert((size_t)(capacity_...
C++
video/src/window/message_box_common.cpp
vinders/pandora_toolbox
f32e301ebaa2b281a1ffc3d6d0c556091420520a
#if !defined(_WINDOWS) # include <mutex> # include <thread/spin_lock.h> # include "video/_private/_message_box_common.h" using namespace pandora::video; static pandora::thread::SpinLock __lastErrorLock; static pandora::memory::LightString __lastError; void pandora::video::__MessageBox::setLastError(con...
#if !defined(_WINDOWS) # include <mutex> # include <thread/spin_lock.h> # include "video/_private/_message_box_common.h" using namespace pandora::video; static pandora::thread::SpinLock __lastErrorLock; static pandora::memory::LightString __lastError; void pandora::video::__MessageBox::setLastError(con...
uint32_t pandora::video::__MessageBox::toActionLabels(const char* action1, const char* action2, const char* action3, const char** outLabels) noexcept { if (action3) { outLabels[__index(0,2)] = __setActionLabel(action1, __getLabelOK()); outLabels[__index(1,2)] = __setActionLabel(act...
return 2; case MessageBox::ActionType::yesNoCancel: outLabels[__index(0,2)] = __getLabelYes(); outLabels[__index(1,2)] = __getLabelNo(); outLabels[__index(2,2)] = __getLabelCancel(); return 3; case MessageBox::ActionType::abortRetryIgnore: outLabels[__index(0,2)] = __...
function_block-function_prefix_line
[ { "content": " __x11_XSync Sync_ = nullptr;\n", "file_path": "hardware/include/hardware/_private/_libraries_x11.h", "rank": 0, "score": 120923.27754309989 }, { "content": " constexpr inline bool isHyperThreadingCapable() const noexcept { return (logicalCores > ph...
C++
attitude_control/src/attitude_controller.cpp
archipela-go/attitude_control
7124366f405efd5eabeaf93f82dcd5ccc6ccf2e8
#include <ros/ros.h> #include <Eigen/Geometry> #include <mavros_msgs/AttitudeTarget.h> #include <mavros_msgs/ActuatorControl.h> #include <kingfisher_msgs/Drive.h> #include <sensor_msgs/Imu.h> #include <tf/transform_datatypes.h> #include <math.h> using namespace std; namespace attitude_controller { class Node { publ...
#include <ros/ros.h> #include <Eigen/Geometry> #include <mavros_msgs/AttitudeTarget.h> #include <mavros_msgs/ActuatorControl.h> #include <kingfisher_msgs/Drive.h> #include <sensor_msgs/Imu.h> #include <tf/transform_datatypes.h> #include <math.h> using namespace std; namespace attitude_co
ix3x3(setpoint_tf).getRPY(setpoint_roll, setpoint_pitch, setpoint_yaw); ROS_INFO_STREAM("imu yaw: " << imu_yaw); ROS_INFO_STREAM("setpoint yaw: " << setpoint_yaw); double error = asin(sin(setpoint_yaw - imu_yaw)); double d_error = (error - last_error_)/(ros::Time::now() - last_error_time_).toSec()...
ntroller { class Node { public: explicit Node(const ros::NodeHandle& pnh); void setpoint_cb(const mavros_msgs::AttitudeTarget::ConstPtr& msg); void imu_cb(const sensor_msgs::Imu::ConstPtr& msg); private: ros::NodeHandle pnh_; ros::Subscriber setpoint_sub_; ros::Time last_setpoint_time_; mavros_msgs::...
random
[ { "content": "# pixhawk_emulator\n\nCollection of packages that emulate various Pixhawk modules.\n\n\n\n## Installation Instructions\n\nRun the following command before trying to build the code.\n\n``` bash\n\nsudo ln -s /usr/include/eigen3/Eigen /usr/local/include/Eigen\n\n```\n", "file_path": "README.md",...
C++
source/D2Common/src/Drlg/DrlgDrlgGrid.cpp
eezstreet/D2MOO
28a30aecc69bf43c80e6757a94d533fb37634b68
#include <Drlg/D2DrlgDrlg.h> #include <Drlg/D2DrlgDrlgGrid.h> #include <Drlg/D2DrlgDrlgRoom.h> void(__fastcall* gpfFlagOperations[])(int*, int) = { DRGLGRID_OrFlag, DRGLGRID_AndFlag, DRGLGRID_XorFlag, DRGLGRID_OverwriteFlag, DRGLGRID_OverwriteFlagIfZero, DRGLGRID_AndNegatedFlag }; void __fastcall DRGLGRID_Overw...
#include <Drlg/D2DrlgDrlg.h> #include <Drlg/D2DrlgDrlgGrid.h> #include <Drlg/D2DrlgDrlgRoom.h> void(__fastcall* gpfFlagOperations[])(int*, int) = { DRGLGRID_OrFlag, DRGLGRID_AndFlag, DRGLGRID_XorFlag, DRGLGRID_OverwriteFlag, DRGLGRID_OverwriteFlagIfZero, DRGLGRID_AndNegatedFlag }; void __fastcall DRGLGRID_Overw...
void __fastcall DRLGGRID_FillNewCellFlags(void* pMemPool, D2DrlgGridStrc* pDrlgGrid, int* pCellPos, D2DrlgCoordStrc* pDrlgCoord, int nWidth) { pDrlgGrid->nWidth = pDrlgCoord->nWidth; pDrlgGrid->nHeight = pDrlgCoord->nHeight; pDrlgGrid->pCellsFlags = &pCellPos[pDrlgCoord->nPosX + nWidth * pDrlgCoord->nPosY]; pD...
void __fastcall DRLGGRID_FillGrid(D2DrlgGridStrc* pDrlgGrid, int nWidth, int nHeight, int* pCellPos, int* pCellRowOffsets) { pDrlgGrid->nWidth = nWidth; pDrlgGrid->nHeight = nHeight; pDrlgGrid->pCellsFlags = pCellPos; memset(pCellPos, 0x00, sizeof(int) * nHeight * nWidth); pDrlgGrid->pCellsRowOffsets = pCellRow...
function_block-full_function
[ { "content": "\tuint8_t nInt;\t\t\t\t\t\t\t//0x32\n", "file_path": "source/D2Common/include/D2DataTbls.h", "rank": 0, "score": 99807.58277220109 }, { "content": "\tBOOL bReturn;\t\t\t\t\t\t\t//0x18\n", "file_path": "source/D2CommonDefinitions/include/D2Structs.h", "rank": 1, "sco...
Rust
rust/tests/integration_test.rs
dandyvica/rbf
449a99a30854ad8ca35032dbecfeb3af465a77aa
use rbf::reader::{Reader, ReaderLazyness}; use rbf::record::{AsciiMode, UTF8Mode}; use rbf::vector_of; pub mod setup { use rbf::layout::Layout; use rbf::record::{AsciiMode, UTF8Mode}; pub fn layout_load_layout_ascii() -> Layout<AsciiMode> { Layout::<AsciiMode>::new("./tests/test.xml").u...
use rbf::reader::{Reader, ReaderLazyness}; use rbf::record::{AsciiMode, UTF8Mode}; use rbf::vector_of; pub mod setup { use rbf::layout::Layout; use rbf::record::{AsciiMode, UTF8Mode}; pub fn layout_load_layout_ascii() -> Layout<AsciiMode> { Layout::<AsciiMode>::new("./tests/test.xml").u...
panic!( "record name <{}> not found in file <{}>", rec.name, "./tests/test.data" ), } } }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let mut nb_lines: usize = 0;\n\n let mut nb_records: HashMap<String, usize> = HashMap::new();\n\n\n\n // get arguments\n\n let args: Vec<String> = env::args().collect();\n\n\n\n if args.len() == 1 {\n\n println!(\"Usage: {} layout_file data_file\", args[0]);\n...
Rust
query/src/pipelines/new/processors/transforms/hash_join/chaining_hash_table.rs
lichuang/databend
e6a76e22e4d30683a152bdd29b5d5b60c96a9c8f
use std::sync::Arc; use std::sync::Mutex; use std::sync::RwLock; use common_datablocks::DataBlock; use common_datavalues::Column; use common_datavalues::ColumnRef; use common_datavalues::ConstColumn; use common_datavalues::DataSchemaRef; use common_exception::Result; use common_planners::Expression; use crate::comm...
use std::sync::Arc; use std::sync::Mutex; use std::sync::RwLock; use common_datablocks::DataBlock; use common_datavalues::Column; use common_datavalues::ColumnRef; use common_datavalues::ConstColumn; use common_datavalues::DataSchemaRef; use common_exception::Result; use common_planners::Expression; use crate::comm...
k(HashUtil::combine_hashes(&hash_values, row_count)) } fn apply_bitmask(hash_vector: &HashVector, mask: u64) -> HashVector { let mut result = HashVector::with_capacity(hash_vector.len()); for hash in hash_vector { result.push(*hash & mask); } result } fn com...
], row_count: usize) -> Result<HashVector> { let hash_values = columns .iter() .map(HashUtil::compute_hash) .collect::<Result<Vec<HashVector>>>()?; O
function_block-random_span
[ { "content": "// No logical type is specified\n\n// Use Default options\n\npub fn default_column_cast(column: &ColumnRef, data_type: &DataTypeImpl) -> Result<ColumnRef> {\n\n let func_ctx = FunctionContext::default();\n\n cast_with_type(\n\n column,\n\n &column.data_type(),\n\n data_t...
Rust
src/crawler.rs
Ayush1325/webcrawler-woc
086941224ead6f814bd02442021db8f742e5c874
/*! Module Containing the Crawler functions. */ use crate::extractors::links; use futures::{stream, StreamExt}; use links::Link; use reqwest::Url; use std::time::Duration; use std::{collections::HashSet, sync::Arc}; use tokio::sync::mpsc; fn init_reqwest_client(timeout: u64) -> Result<reqwest::Client, String> { le...
/*! Module Containing the Crawler functions. */ use crate::extractors::links; use futures::{stream, StreamExt}; use links::Link; use reqwest::Url; use std::time::Duration; use std::{collections::HashSet, sync::Arc}; use tokio::sync::mpsc; fn init_reqwest_client(timeout: u64) -> Result<reqwest::Client, String> { le...
async fn crawl_page( url: Url, client: reqwest::Client, tx: mpsc::Sender<Link>, tx_selenium: mpsc::Sender<String>, limit: usize, resolver: trust_dns_resolver::TokioAsyncResolver, word_list: Arc<HashSet<String>>, ) { let mut link = links::Link::new_from_url(&url); let resp = match g...
pub async fn crawl_no_depth( origin_url: Link, whitelist: Option<HashSet<url::Host>>, blacklist: Option<HashSet<url::Host>>, word_list: HashSet<String>, tx_output: mpsc::Sender<Link>, tx_selenium: mpsc::Sender<String>, task_limit: usize, timeout: u64, ) -> Result<(), String> { let mu...
function_block-full_function
[ { "content": "/// Helper function to parse url in a page.\n\n/// Converts relative urls to full urls.\n\n/// Also removes javascript urls and other false urls.\n\npub fn normalize_url(url: &str, base_url: &str) -> Option<Link> {\n\n if url.starts_with(\"#\") {\n\n // Checks for internal links.\n\n ...
Rust
rust/src/storage/gcs/client.rs
Smurphy000/delta-rs
9196ff49bc147b36339b4901624229473092b024
use super::{util, GCSClientError, GCSObject}; use futures::Stream; use std::convert::{TryFrom, TryInto}; use std::path::PathBuf; use std::sync::Arc; use tame_gcs::objects::{self, Object}; use tame_oauth::gcp as oauth; use log::debug; pub struct GCSStorageBackend { pub client: reqwest::Client, pub c...
use super::{util, GCSClientError, GCSObject}; use futures::Stream; use std::convert::{TryFrom, TryInto}; use std::path::PathBuf; use std::sync::Arc; use tame_gcs::objects::{self, Object}; use tame_oauth::gcp as oauth; use log::debug; pub struct GCSStorageBackend { pub client: reqwest::Client, pub c...
..Default::default() }); let list_request = Object::list(&uri.bucket, list_request_opts)?; let list_response = util::execute::<_, objects::ListResponse>( self, list_request).await?; for object_meta in list_response.objects { ...
tAccess>, } impl std::fmt::Debug for GCSStorageBackend { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { f.debug_struct("GCSStorageBackend {...}").finish() } } impl TryFrom<PathBuf> for GCSStorageBackend { type Error = GCSClientError; fn try_from(cred_path: Path...
random
[ { "content": "pub fn check_object_not_found(err: GCSClientError) -> GCSClientError {\n\n match err {\n\n GCSClientError::GCSError {\n\n source: tame_gcs::error::Error::HttpStatus(HttpStatusError(StatusCode::NOT_FOUND)),\n\n } => GCSClientError::NotFound,\n\n err => err,\n\n ...
Rust
src/query.rs
m42e/zsh-histdb-skim
385c039f4338963e4cada1ab9c3035e1d969a552
use crate::location::Location; use crate::environment::*; pub fn build_query_string(theloc: &Location, grouped: bool) -> String { let mut query = String::from("select history.id as id, commands.argv as cmd,"); if !grouped { query.push_str(" start_time") } else { query.push_str(" max(start_t...
use crate::location::Location; use crate::environment::*; pub fn build_query_string(theloc: &Location, grouped: bool) -> String { let mut query = String::from("select history.id as id, commands.argv as cmd,"); if !grouped { query.push_str(" start_time") } else { query.push_str(" max(start_t...
#[test] fn contains_grouping() { let re_group = Regex::new(r"group by history.command_id, history.place_id").unwrap(); for l in vec![ Location::Session, Location::Directory, Location::Machine, Location::Everywhere, ] { let que...
fn contains_host() { let re_host = Regex::new(r"host == '.*'").unwrap(); for l in vec![Location::Session, Location::Directory, Location::Machine] { let query = build_query_string(&l, true); assert!(re_host.is_match(&query)); } let query = build_query_string(&Locat...
function_block-full_function
[ { "content": "/// Get the histdb session from the environment\n\npub fn get_current_session_id() -> String {\n\n let key = \"HISTDB_SESSION\";\n\n let session_id = env::var(key).unwrap_or(String::from(\"\"));\n\n return session_id.to_string();\n\n}\n\n\n", "file_path": "src/environment.rs", "ra...
Rust
src/routes/mod.rs
koto-bank/zeph
bfb154678e2881a9584e4ea19d90c4dc29e9455b
use {DB,CONFIG}; use iron::prelude::*; use iron::status; use iron::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use urlencoded::UrlEncodedQuery; use serde_json::to_value; pub mod image; pub mod user; pub mod admin; pub use image::*; pub use user::*; pub use admin::*; pub fn index_n_search(_req: &mut Request) ...
use {DB,CONFIG}; use iron::prelude::*; use iron::status; use iron::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use urlencoded::UrlEncodedQuery; use serde_json::to_value; pub mod image; pub mod user; pub mod admin; pub use image::*; pub use user::*; pub use admin::*; pub fn index_n_search(_req: &mut Request) ...
tr { td code "1girl format:jpg,gif" td "Search for GIF and JPEG images" } } } }; Ok(Response::with((status::Ok, page))) }
function_block-function_prefix_line
[ { "content": "pub fn login(req: &mut Request) -> IronResult<Response> {\n\n let mut response = Response::new();\n\n\n\n let body = match req.get::<UrlEncodedBody>() {\n\n Ok(data) => data,\n\n Err(_) => return Ok(Response::with(status::BadRequest))\n\n };\n\n\n\n if let (Some(login), ...
Rust
src/opus/imported_encode.rs
binast/range-encoding-rs
7dd51d3522a936b50b0ee02a351af5783d65e1e5
#![allow(dead_code, mutable_transmutes, non_camel_case_types, non_snake_case, non_upper_case_globals, unused_mut)] use std; use std::io::Write; pub type int32_t = std::os::raw::c_int; pub type uint32_t = std::os::raw::c_uint; pub type __uint16_t = std::os::raw::c_ushort;...
#![allow(dead_code, mutable_transmutes, non_camel_case_types, non_snake_case, non_upper_case_globals, unused_mut)] use std; use std::io::Write; pub type int32_t = std::os::raw::c_int; pub type uint32_t = std::os::raw::c_uint; pub type __uint16_t = std::os::raw::c_ushort;...
this: *mut ec_enc<W>, mut _value: std::os::raw::c_uint, ) -> Result<(), std::io::Error> { (*_this).out.write_all(&[_value as u8])?; Ok(()) } pub unsafe fn ec_encode_bin<W: Write>( mut _this: *mut ec_enc<W>, mut _fl: std::os::raw::c_uint, mut _fh: std::os::raw::c_uint, mut _bits: std::os::ra...
.wrapping_sub(1i32 as std::os::raw::c_uint) .wrapping_add(carry as std::os::raw::c_uint) & (1u32 << 8i32).wrapping_sub(1i32 as std::os::raw::c_uint); loop { ec_write_byte(_this, sym)?; (*_this).ext = (*_this).ext.wrapping_sub(1); ...
random
[ { "content": "#[test]\n\nfn widths() {\n\n let widths = [1, 30, 5, 20];\n\n let probabilities = CumulativeDistributionFrequency::new(widths.iter().cloned().collect());\n\n\n\n let widths2: Vec<_> = probabilities.widths().collect();\n\n assert_eq!(widths2, widths)\n\n}\n\n\n", "file_path": "tests...
Rust
src/database/tcn_dao.rs
Co-Epi/app-backend-rust
b332afe7e92caf2703334c00dabf72fb4f279869
use crate::{ byte_vec_to_16_byte_array, errors::{ServicesError}, expect_log, reports_interval, tcn_recording::observed_tcn_processor::ObservedTcn, }; use log::*; use reports_interval::UnixTime; use rusqlite::{params, Row, NO_PARAMS, types::Value}; use std::{ sync::Arc, rc::Rc, }; use tcn::Tempor...
use crate::{ byte_vec_to_16_byte_array, errors::{ServicesError}, expect_log, reports_interval, tcn_recording::observed_tcn_processor::ObservedTcn, }; use log::*; use reports_interval::UnixTime; use rusqlite::{params, Row, NO_PARAMS, types::Value}; use std::{ sync::Arc, rc::Rc, }; use tcn::Tempor...
stance: 2.0, avg_distance: 2.0, total_count: 1, }; let save_res = tcn_dao.overwrite(vec![stored_tcn1.clone(), stored_tcn2.clone()]); assert!(save_res.is_ok()); let tcn = ObservedTcn { tcn: TemporaryContactNumber([0; 16]), contact_start: Un...
e::new( Connection::open_in_memory().expect("Couldn't create database!"), )); let tcn_dao = TcnDaoImpl::new(database); let observed_tcn = ObservedTcn { tcn: TemporaryContactNumber([ 24, 229, 125, 245, 98, 86, 219, 221, 172, 25, 232, 150, 206, 66, 164, 173...
random
[ { "content": "fn record_tcn(env: &JNIEnv, tcn: JString, distance: jfloat) -> Result<(), ServicesError> {\n\n let tcn_java_str = env.get_string(tcn)?;\n\n let tcn_str = tcn_java_str.to_str()?;\n\n\n\n dependencies()\n\n .observed_tcn_processor\n\n .save(tcn_str, distance as f32)\n\n}\n\n\n...
Rust
src/bits/mask.rs
feb29/cwt
5e757ca672887b584c75871bc54875295759f825
use std::{ borrow::Cow, cmp::Ordering::{self, Equal, Greater, Less}, iter::{empty, Peekable}, }; pub trait Mask<'a>: Sized { type Block: 'a + ?Sized + ToOwned; type Steps: Iterator<Item = (usize, Cow<'a, Self::Block>)>; fn into_steps(self) -> Self::Steps; fn and<Rhs...
use std::{ borrow::Cow, cmp::Ordering::{self, Equal, Greater, Less}, iter::{empty, Peekable}, }; pub trait Mask<'a>: Sized { type Block: 'a + ?Sized + ToOwned; type Steps: Iterator<Item = (usize, Cow<'a, Self::Block>)>; fn into_steps(self) -> Self::Steps; fn and<Rhs...
pub fn and<A>(xs: impl IntoIterator<Item = A>) -> Self where A: Mask<'a, Block = T>, And<'a, Box<dyn Iterator<Item = (usize, Cow<'a, T>)> + 'a>, A>: 'a + Mask<'a, Block = T>, { Self::fold(xs, And::new) } pub fn or<A>(xs: impl IntoIterator<Item = A>) -> Self w...
pub(crate) fn fold<A, B, F>(xs: impl IntoIterator<Item = A>, mut f: F) -> Fold<'a, Cow<'a, T>> where A: 'a + Mask<'a, Block = T>, B: 'a + Mask<'a, Block = T>, F: FnMut(Box<dyn Iterator<Item = (usize, Cow<'a, T>)> + 'a>, A) -> B, { let mut xs = xs.into_iter(); if let Some(...
function_block-full_function
[ { "content": "#[inline]\n\npub fn blocks<T: FixedBits>(n: usize) -> usize {\n\n blocks_by(n, T::SIZE)\n\n}\n\n\n\n/// Computes the minimum length of the sequence to store `n` bits.\n\n#[inline]\n\npub const fn blocks_by(n: usize, block_size: usize) -> usize {\n\n // If we want 17 bits, dividing by 32 will...
Rust
src/module.rs
accup/cargo-expunch
58b24319545a2874a3a3fc0127f745c00ef3bd60
use std::collections::HashMap; use std::path::PathBuf; use syn::{self, UseTree}; pub fn concat_module_parts(prefix: &[String], suffix: &[String], crate_name: &str) -> Vec<String> { let mut full_parts = prefix.to_vec(); for part in suffix { match part { _ if part == "crate" || part == crate_...
use std::collections::HashMap; use std::path::PathBuf; use syn::{self, UseTree}; pub fn concat_module_parts(prefix: &[String], suffix: &[String], crate_name: &str) -> Vec<String> {
ne() } _ if module_part == "super" => self_path .parent() .ok_or_else(|| { format!( "Failed to get the parent directory of the {0} {1} より上の階層へ遡ろうとしました", self_path.to_str().unwrap_or("(undisplayabl...
let mut full_parts = prefix.to_vec(); for part in suffix { match part { _ if part == "crate" || part == crate_name => { full_parts.clear(); full_parts.push(part.clone()); } _ if part == "super" => { full_parts.pop(); ...
random
[ { "content": "/// Rustソースコードを解析して展開する\n\nfn expunch_file(source_code_path: &str) -> Result<(), String> {\n\n let source_code_path = PathBuf::from(source_code_path);\n\n let package_path = PathBuf::from(\".\");\n\n let metadata = MetadataCommand::new()\n\n .manifest_path(\"./Cargo.toml\")\n\n ...
Rust
src/resource.rs
pduval/rustic_hal
ca1651aaf2651d21d5268ba9b7edc016f4c4801f
use std::collections::btree_map::Entry; use std::collections::*; use std::vec::*; use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use super::link::HalLink; use super::{HalError, HalResult}; use serde_json::{from_value, to_value, Map, Value as JsonValue}; #[derive(Clone, Debug)] p...
use std::collections::btree_map::Entry; use std::collections::*; use std::vec::*; use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use super::link::HalLink; use super::{HalError, HalResult}; use serde_json::{from_value, to_value, Map, Value as JsonValue}; #[derive(Clone, Debug)] p...
h(&resource); } } } self } pub fn with_curie(self, name: &str, href: &str) -> Self { self.with_link("curies", HalLink::new(href).templated(true).with_name(name)) } pub fn with_extra_data<V>(mut self, name: &str, value: V) -> Self where V:...
e { pub fn new<T>(payload: T) -> HalResource where T: Serialize, { let val = match to_value(payload) { Ok(val) => match val { JsonValue::Object(_) => Some(val), _ => None, }, _ => None, }; HalResource { ...
random
[ { "content": "fn is_not(b: &bool) -> bool {\n\n !*b\n\n}\n\nmacro_rules! chainable_string {\n\n ($x: ident, $y: ident) => {\n\n pub fn $y(mut self, $x: &str) -> Self {\n\n self.$x = Some($x.to_string());\n\n self\n\n }\n\n\n\n pub fn $x(&self) -> Option<String> {...
Rust
src/poly/comp.rs
HColeman127/algeo
bf2ac1514041ff00a1e571732ac01647329ece72
use std::marker::PhantomData; use itertools::{EitherOrBoth, Itertools}; use crate::core::num::Field; use super::elts::*; use super::mdeg::MultiDegree; use super::ord::MonomialOrder; pub struct Computer<F: Field, O: MonomialOrder> { _marker: PhantomData<(F, O)>, } impl<F: Field, O: MonomialOrder> Computer<F, O>...
use std::marker::PhantomData; use itertools::{EitherOrBoth, Itertools}; use crate::core::num::Field; use super::elts::*; use super::mdeg::MultiDegree; use super::ord::MonomialOrder; pub struct Computer<F: Field, O: MonomialOrder> { _marker: PhantomData<(F, O)>, } impl<F: Field, O: MonomialOrder> Computer<F, O>...
; } }
print_buchberger(&[ x(2) + x(1) * y(5) + y(4), x(1) * y(6) - x(1) * y(3) + y(5) - y(2), x(1) * y(5) - x(1) * y(2), ])
call_expression
[ { "content": "pub fn mat_iterator<'a, F: Field>(n: usize, m: usize, values: &'a [F])-> impl 'a + Iterator<Item=Mat<F>>{\n\n\tMatIterator {\n\n\t\tvalues,\n\n\t\tn,\n\n\t\tm,\n\n\t\tnum: 0\n\n\t}\n\n}\n\n\n\npub struct MatIterator<'a, F: Field> {\n\n\tvalues: &'a [F],\n\n\tn: usize,\n\n\tm: usize,\n\n\tnum: usiz...
Rust
tests/auth_test.rs
nappa85/rust-etcd
9fd9f3c33687623772abfff3e5a43579ab9aa677
extern crate etcd; extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate native_tls; extern crate tokio_core; extern crate tokio_timer; use futures::future::Future; use tokio_core::reactor::Core; use etcd::{BasicAuth, Client}; use etcd::auth::{self, AuthChange, NewUser, Role, RoleUpdate, UserU...
extern crate etcd; extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate native_tls; extern crate tokio_core; extern crate tokio_timer; use futures::future::Future; use tokio_core::reactor::Core; use etcd::{BasicAuth, Client}; use etcd::auth::{self, AuthChange, NewUser, Role, RoleUpdate, UserU...
res.unwrap(); auth::delete_role(&authed_client, "rkt") }) .then(|res| { res.unwrap(); let mut update_guest = RoleUpdate::new("guest"); update_guest.grant_kv_write_permission("/*"); auth::update_role(&auth...
r.add_role("rkt"); auth::create_user(&authed_client, rkt_user) }) .then(|res| { let response = res.unwrap(); let rkt_user = response.data; assert_eq!(rkt_user.name(), "rkt"); let role_name = &rkt_user.role_names(...
random
[ { "content": "/// Attempts to enable the auth system.\n\npub fn enable<C>(client: &Client<C>) -> Box<Future<Item = Response<AuthChange>, Error = Vec<Error>>>\n\nwhere\n\n C: Clone + Connect + Sync + 'static,\n\n{\n\n let http_client = client.http_client().clone();\n\n\n\n let result = first_ok(client.e...
Rust
src/order_service.rs
alank976/restaurant-order
a623ebede260f11c324982d9831136f2a4e8254a
use std::collections::HashMap; use std::sync::{Arc, RwLock}; use crate::order_item::OrderItem; pub struct OrderService(Arc<RwLock<HashMap<u8, Vec<OrderItem>>>>); impl OrderService { pub fn new() -> Self { OrderService(Arc::new(RwLock::new(HashMap::new()))) } fn new_for_test(m: Arc<RwLock<HashMap...
use std::collections::HashMap; use std::sync::{Arc, RwLock}; use crate::order_item::OrderItem; pub struct OrderService(Arc<RwLock<HashMap<u8, Vec<OrderItem>>>>); impl OrderService { pub fn new() -> Self { OrderService(Arc::new(RwLock::new(HashMap::new()))) } fn new_for_test(m: Arc<RwLock<HashMap...
em::new("ramen".to_string())]); svc.cancel_item(1, "ramen".to_string()).unwrap(); assert!(rw_map .read() .unwrap() .get(&1) .unwrap() .is_empty()); } #[test] fn it_rejects_when_table_id_greater_100() { let (svc, _) = new_s...
vc, rw_map) = new_service_and_inner_map(); rw_map .write() .unwrap() .insert(1, vec![OrderIt
function_block-random_span
[ { "content": "#[cfg(test)]\n\nmod tests {\n\n use std::thread;\n\n use std::time::{Duration, Instant};\n\n\n\n use restaurant_order::*;\n\n use restaurant_order::clients::*;\n\n\n\n #[test]\n\n fn integration_test() {\n\n thread::spawn(move || WebServer::new().start(8001));\n\n\n\n ...
Rust
parser/src/lib.rs
codeanonorg/ULP
1412606cf2456a183a33f3ef5a5defe94675b41b
mod report; mod spanned; mod token; use crate::token::Token; use chumsky::{prelude::*, Stream}; use report::Report; use report::{report_of_char_error, report_of_token_error}; use token::lexer; #[derive(Clone, Debug, PartialEq)] pub enum Lit { Num(String), List(Vec<Self>), } #[derive(Clone, Debug, PartialEq)]...
mod report; mod spanned; mod token; use crate::token::Token; use chumsky::{prelude::*, Stream}; use report::Report; use report::{report_of_char_error, report_of_token_error}; use token::lexer; #[derive(Clone, Debug, PartialEq)] pub enum Lit { Num(String), List(Vec<Self>), } #[derive(Clone, Debug, PartialEq)]...
fn parser() -> impl Parser<Token, Option<Vec<Sym>>, Error = Simple<Token>> { use token::Dir::*; use Token::*; let var = filter_map(|span, tok| match tok { Var(i) => Ok(Sym::Var(i)), t => Err(Simple::expected_input_found(span, vec![], Some(t))), }); let lit = literal().map(Sym::Lite...
use token::Dir::*; let int = filter_map(|span, tok| match tok { Num(n) => Ok(Lit::Num(n)), t => Err(Simple::expected_input_found(span, vec![], Some(t))), }); recursive(|lit| lit.repeated().at_least(1).delimited_by(Bracket(L), Bracket(R)).map(Lit::List).or(int)) }
function_block-function_prefix_line
[ { "content": "/// Check that an ULP program is well formed and returns its associated\n\n/// computation tree\n\npub fn check(mut prog: Vec<Sym>) -> Result<ComputationTree, &'static str> {\n\n if prog.len() == 0 {\n\n Err(\"No symbols\")\n\n } else {\n\n prog.reverse();\n\n linear_che...
Rust
src/resolver/storage.rs
casper-ecosystem/caspiler
69874a86537fb6f1a138f03e382686f03e46751e
use num_bigint::BigInt; use num_traits::FromPrimitive; use num_traits::One; use num_traits::Zero; use super::cfg::{ControlFlowGraph, Instr, Vartable}; use super::expression::{cast, expression, Expression}; use output::Output; use parser::pt; use resolver; pub fn array_offset( loc: &pt::Loc, start: Expression,...
use num_bigint::BigInt; use num_traits::FromPrimitive; use num_traits::One; use num_traits::Zero; use super::cfg::{ControlFlowGraph, Instr, Vartable}; use super::expression::{cast, expression, Expression}; use output::Output; use parser::pt; use resolver; pub fn array_offset( loc: &pt::Loc, start: Expression,...
} pub fn bytes_pop( loc: &pt::Loc, var_expr: Expression, func: &pt::Identifier, args: &[pt::Expression], cfg: &mut ControlFlowGraph, errors: &mut Vec<Output>, ) -> Result<(Expression, resolver::Type), ()> { cfg.writes_contract_storage = true; if !args.is_empty() { errors.push(...
if args.is_empty() { Ok(( Expression::StorageBytesPush(*loc, Box::new(var_expr), Box::new(val)), resolver::Type::Bytes(1), )) } else { Ok(( Expression::StorageBytesPush(*loc, Box::new(var_expr), Box::new(val)), resolver::Type::Undef, ))...
if_condition
[ { "content": "/// Cast from one type to another, which also automatically derefs any Type::Ref() type.\n\n/// if the cast is explicit (e.g. bytes32(bar) then implicit should be set to false.\n\npub fn cast(\n\n loc: &pt::Loc,\n\n expr: Expression,\n\n from: &resolver::Type,\n\n to: &resolver::Type,\...
Rust
src/main.rs
drgmr/t8bar
eb0d8db31b5e7aba58ac439ae06cd6ca6dad01ca
#[macro_use] extern crate log; use std::env; use std::fs::File; use std::io::{copy, Read, Write}; use std::path::PathBuf; use std::process::{Command, Stdio}; use rubrail::ItemId; use rubrail::TTouchbar; use rubrail::Touchbar; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Target { hostname: String...
#[macro_use] extern crate log; use std::env; use std::fs::File; use std::io::{copy, Read, Write}; use std::path::PathBuf; use std::process::{Command, Stdio}; use rubrail::ItemId; use rubrail::TTouchbar; use rubrail::Touchbar; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Target { hostname: String...
p(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); let result: Vec<Target> = serde_json::from_str(&contents).unwrap(); info!("Configuration acquired: {:#?}", result); result }
function_block-function_prefixed
[ { "content": "# t8bar\n\n\n\nA Screen Sharing touch bar utility.\n\n\n\n![Example Image](/media/screenshot.png)\n\n\n\n## Current State\n\n\n\nRelatively simple but arguably bad code is working - this was mostly an\n\nexperiment of building something that's actually useful using Rust. Code\n\nimprovements and b...
Rust
logger/src/lib.rs
graham/trillium
eac4620156275b5eec41744bd2015c26208a3bab
#![forbid(unsafe_code)] #![warn( rustdoc::missing_crate_level_docs, missing_docs, nonstandard_style, unused_qualifications )] /*! Welcome to the trillium logger! */ pub use crate::formatters::{apache_combined, apache_common, dev_formatter}; use std::fmt::Display; use trillium::{async_trait, Conn, Handle...
#![forbid(unsafe_code)] #![warn( rustdoc::missing_crate_level_docs, missing_docs, nonstandard_style, unused_qualifications )] /*! Welcome to the trillium logger! */ pub use crate::formatters::{apache_combined, apache_common, dev_formatter}; use std::fmt::Display; use trillium::{async_trait, Conn, Handle...
Self { self.color_mode = color_mode; self } /** specify the logger target see [`Target`] for more details. note that this can be chained with [`Logger::with_color_mode`] and [`Logger::with_formatter`] ``` use trillium_logger::{Logger, Target}; Logger::new().with_target...
to [`ColorMode::On`] or [`ColorMode::Off`] **Note**: The actual colorization of output is determined by the log formatters, so it is possible for this to be correctly enabled but for the output to have no colored components. */ #[derive(Clone, Copy, Debug)] #[non_exhaustive] pub enum ColorMode { Auto, ...
random
[ { "content": "pub fn dev_formatter(conn: &Conn, color: bool) -> impl Display + Send + 'static {\n\n (method, \" \", url, \" \", response_time, \" \", status).format(conn, color)\n\n}\n\n\n\n/**\n\nformatter for the peer ip address of the connection\n\n\n\n**note**: this can be modified by handlers prior to l...
Rust
src/parser/record.rs
natir/needletail
3756d79cd3452f178a657387c26114bbbe7a5650
use std::borrow::Cow; use std::io::Write; use memchr::memchr; use crate::errors::ParseError; use crate::parser::fasta::BufferPosition as FastaBufferPosition; use crate::parser::fastq::BufferPosition as FastqBufferPosition; use crate::parser::utils::{Format, LineEnding, Position}; use crate::Sequence; #[derive(Debug,...
use std::borrow::Cow; use std::io::Write; use memchr::memchr; use crate::errors::ParseError; use crate::parser::fasta::BufferPosition as FastaBufferPosition; use crate::parser::fastq::BufferPosition as FastqBufferPosition; use crate::parser::utils::{Format, LineEnding, Position}; use crate::Sequence; #[derive(Debug,...
} pub fn start_line_number(&self) -> u64 { self.position.line } pub fn line_ending(&self) -> LineEnding { self.line_ending } pub fn write( &self, writer: &mut dyn Write, forced_line_ending: Option<LineEnding>, ) -> Result<(), Pa...
match self.buf_pos { BufferPositionKind::Fasta(bp) => bp.num_bases(&self.buffer), BufferPositionKind::Fastq(bp) => bp.num_bases(&self.buffer), }
if_condition
[ { "content": "/// Find the lexigraphically smallest substring of `seq` of length `length`\n\n///\n\n/// There's probably a faster algorithm for this somewhere...\n\npub fn minimizer(seq: &[u8], length: usize) -> Cow<[u8]> {\n\n let reverse_complement: Vec<u8> = seq.iter().rev().map(|n| complement(*n)).collec...
Rust
client/src/utils/hd.rs
huhn511/stronghold.rs
85920e55eb05e50520795a67c533ec52f08fd10b
use crypto::{ed25519::SecretKey, macs::hmac::HMAC_SHA512}; use std::convert::TryFrom; #[derive(Debug)] pub enum Error { NotSupported, InvalidLength(usize), CryptoError(crypto::Error), } pub struct Seed(Vec<u8>); impl Seed { pub fn from_bytes(bs: &[u8]) -> Self { Self(bs.to_vec()) } ...
use crypto::{ed25519::SecretKey, macs::hmac::HMAC_SHA512}; use std::convert::TryFrom; #[derive(Debug)] pub enum Error { NotSupported, InvalidLength(usize), CryptoError(crypto::Error), } pub struct Seed(Vec<u8>); impl Seed { pub fn from_bytes(bs: &[u8]) -> Self { Self(bs.to_vec()) } ...
}
private_key: "b1d0bad404bf35da785a64ca1ac54b2617211d2777696fbffaf208f746ae84f2", }, TestChain { chain: Chain::from_u32_hardened(vec![0, 1, 2]), chain_code: "2e69929e00b5ab250f49c3fb1c12f252de4fed2c1db88387094a0f8c4c9ccd6c", ...
function_block-function_prefix_line
[ { "content": "/// Read ciphertext from the input, decrypts it using the specified key and the associated data\n\n/// specified during encryption and returns the plaintext\n\npub fn read<I: Read>(input: &mut I, key: &Key, associated_data: &[u8]) -> crate::Result<Vec<u8>> {\n\n // check the header\n\n check...
Rust
src/binary_heap.rs
acodercat/rust-algorithms
06db2526fa8709886a2baf2467f720c62076720d
use std::fmt::Debug; use std::cmp::PartialOrd; #[derive(Debug)] pub struct BinaryHeap <T> { container: Vec<T>, } impl <T: Debug + PartialOrd> BinaryHeap <T> { pub fn new() -> Self { return BinaryHeap { container: Vec::new() }; } pub fn from(vec: Vec<T>) -> BinaryHeap...
use std::fmt::Debug; use std::cmp::PartialOrd; #[derive(Debug)] pub struct BinaryHeap <T> { container: Vec<T>, } impl <T: Debug + PartialOrd> BinaryHeap <T> { pub fn new() -> Self { return BinaryHeap { container: Vec::new() }; } pub fn from(vec: Vec<T>) -> BinaryHeap...
heap2.push(1); heap2.push(3); heap2.push(190); assert_eq!(heap2.peek(), Some(&190)); assert_eq!(heap2.extract(), Some(190)); assert_eq!(heap2.peek(), Some(&3)); }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let mut heap:BinaryHeap<i32> = BinaryHeap::from(vec![1, 2, 3, 4]);\n\n heap.push(-21);\n\n heap.push(1);\n\n heap.push(3);\n\n heap.push(190);\n\n heap.push(4);\n\n heap.push(90);\n\n heap.extract();\n\n heap.extract();\n\n println!(\"{}\", heap.peek()...
Rust
tests/issuer.rs
evannetwork/vade-evan
7d37225a4756c7595b03a4901a5e3805654f2f7d
/* Copyright (c) 2018-present evan GmbH. 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 i...
/* Copyright (c) 2018-present evan GmbH. 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 i...
ocalSigner::new()); let schema: CredentialSchema = Issuer::create_credential_schema( EXAMPLE_DID_1, ISSUER_DID, "test_schema", "Test description", test_properties, required_properties, false, &did_document["publicKey"][0]["id"].to_string(), &IS...
items: None, }, ); required_properties.push("test_property_string".to_owned()); let signer: Box<dyn Signer> = Box::new(L
function_block-random_span
[ { "content": "fn get_vade_evan(matches: &ArgMatches) -> Result<VadeEvan> {\n\n let target = get_argument_value(&matches, \"target\", Some(DEFAULT_TARGET));\n\n let signer = get_argument_value(&matches, \"signer\", Some(DEFAULT_SIGNER));\n\n return Ok(VadeEvan::new(VadeEvanConfig { target, signer })?);\...
Rust
src/identbimap/mod.rs
sozysozbot/wenyan-to-rust
2129edbb87116b899875b14fee2e0785f8a7d7b3
use crate::parse; use big_s::S; use bimap_plus_map::BiMapPlusMap; use std::collections::HashMap; type Table = HashMap<String, String>; fn to_pinyin(ident: parse::Identifier, conversion_table: &Table) -> String { let parse::Identifier(i) = ident; let vec = i .chars() .map(|c| match conversion_t...
use crate::parse; use big_s::S; use bimap_plus_map::BiMapPlusMap; use std::collections::HashMap; type Table = HashMap<String, String>; fn to_pinyin(ident: parse::Identifier, conversion_table: &Table) -> String {
type Hanzi = parse::Identifier; type Ascii = String; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Type { Mutable, } pub struct IdentBiMap(BiMapPlusMap<Hanzi, Ascii, Option<Type>>); impl IdentBiMap { pub fn translate_from_hanzi(&self, id: &parse::Identifier) -> Ascii { self.0.bimap_get_by_left(id...
let parse::Identifier(i) = ident; let vec = i .chars() .map(|c| match conversion_table.get(&format!("{:X}", c as u32)) { None => S("_"), Some(a) => a.split(' ').collect::<Vec<_>>()[0].to_string(), }) .collect::<Vec<_>>(); vec.join("") }
function_block-function_prefix_line
[ { "content": "pub fn compile(parsed: &[parse::Statement], conversion_table: &HashMap<String, String>) -> String {\n\n let mut ans = vec![(0, S(\"fn main() {\"))];\n\n let mut env = Env {\n\n ans_counter: 0,\n\n rand_counter: 0,\n\n indent_level: 1,\n\n variables_not_yet_named: ...
Rust
rust/leetcode/src/hash_table/valid_sudoku.rs
zayfen/LeetCode
8efdb380b79355e463f5a8b01105275ac699e08c
struct Solution (); impl Solution { pub fn is_valid_cell_in_row (board: &Vec<Vec<char>>, row: usize, col: usize) -> bool { let mut numbers = vec!('1', '2', '3', '4', '5', '6', '7', '8', '9'); for num in &board[row] { if *num == '.' { continue; } let number = num.to_digit(10).un...
struct Solution (); impl Solution { pub fn is_valid_cell_in_row (board: &Vec<Vec<char>>, row: usize, col: usize) -> bool { let mut numbers = vec!('1', '2', '3', '4', '5', '6', '7', '8', '9'); for num in &board[row] { if *num == '.' { continue; } let number = num.to_digit(10).un...
}
fn test_is_valid_sudoku () { let board = vec!( vec!('5','3','.','.','7','.','.','.','.'), vec!('6','.','.','1','9','5','.','.','.'), vec!('.','9','8','.','.','.','.','6','.'), vec!('8','.','.','.','6','.','.','.','3'), vec!('4','.','.','8','.','3','.','.','1'), vec!('7','.','.','...
function_block-full_function
[ { "content": "pub fn switch (nums: &mut Vec<i32>, left: usize, right: usize) {\n\n let tmp = nums[left];\n\n nums[left] = nums[right];\n\n nums[right] = tmp;\n\n}\n\n\n", "file_path": "rust/leetcode/src/heap/p215_largest_element_in_an_array.rs", "rank": 0, "score": 166054.35345015902 }, { ...
Rust
src/drive_operations.rs
EndaHallahan/Scrit
10431c049fef5f587b506f0e65b4f55443b3f91c
use map_operations::*; use push::ScritFile; use hyper; use hyper::net::HttpsConnector; use hyper::Client; use hyper_native_tls::NativeTlsClient; use yup_oauth2::{Authenticator, FlowType, ApplicationSecret, DiskTokenStorage, DefaultAuthenticatorDelegate, parse_application_secret}; use google_dri...
use map_operations::*; use push::ScritFile; use hyper; use hyper::net::HttpsConnector; use hyper::Client; use hyper_native_tls::NativeTlsClient; use yup_oauth2::{Authenticator, FlowType, ApplicationSecret, DiskTokenStorage, DefaultAuthenticatorDelegate, parse_application_secret}; use google_dri...
} None => { println!("Couldn't find file '{}' in project folder, creating new file...", file_name); false } } }, Err(_) => { println!("Couldn't find file '{}' in project folder, creating new file...", file_name); false } } } pub fn check_folder(folder_id : &String...
if !y.trashed.unwrap() && parents.contains(folder_id) { true } else { println!("Couldn't find file '{}' in project folder, creating new file...", file_name); false }
if_condition
[ { "content": "pub fn replace_file(ele: &mut Element, in_id: &str, in_title: &String) {\n\n\tele.set_attr(\"id\", in_id);\n\n\tele.set_attr(\"title\", in_title);\n\n\tele.delete_children();\n\n}\n\n\n", "file_path": "src/map_operations.rs", "rank": 3, "score": 224990.306815553 }, { "content":...
Rust
vk_tracer/src/render/renderer.rs
icanwalkonwater/rs-vk-tracer
424524af7e66de2b60137ec4aab80848e076efb5
use crate::{ command_recorder::QueueType, errors::{HandleType, Result}, render::{RenderablePipelineHandle, VkRecordable}, RenderPlanHandle, RenderTargetHandle, RendererHandle, VkTracerApp, }; use ash::{ version::{DeviceV1_0, DeviceV1_2}, vk, }; impl VkTracerApp { pub fn new_renderer_from_pl...
use crate::{ command_recorder::QueueType, errors::{HandleType, Result}, render::{RenderablePipelineHandle, VkRecordable}, RenderPlanHandle, RenderTargetHandle, RendererHandle, VkTracerApp, }; use ash::{ version::{DeviceV1_0, DeviceV1_2}, vk, }; impl VkTracerApp { pub fn new_renderer_from_pl...
} }
Ok(self.app.renderer_storage.insert(Renderer { main_commands: commands.0, secondary_commands: commands.1, render_fence, render_plan: self.render_plan, pipelines_by_subpass: self.pipelines_by_subpass, pipelines_amount: self.pipelines_amount, ...
call_expression
[ { "content": "pub fn dump_vma_stats(app: &VkTracerApp) {\n\n let stats = app.vma.build_stats_string(true).unwrap();\n\n let mut f = File::create(\"vma_stats.json\").unwrap();\n\n f.write_all(stats.as_bytes()).unwrap();\n\n}\n", "file_path": "vk_tracer/src/utils.rs", "rank": 1, "score": 1528...
Rust
src/main.rs
gourlaysama/girouette
c82e9f2b4eb8b684e46c54f0f11ab1bee6034141
use anyhow::{anyhow, Context, Result}; use env_logger::{Builder, Env}; use girouette::{ cli::ProgramOptions, config::ProgramConfig, show, Girouette, Location, WeatherClient, }; use log::*; use std::{env, time::Duration}; use structopt::StructOpt; use termcolor::*; use tokio::runtime; static DEFAULT_CONFIG: &str = ...
use anyhow::{anyhow, Context, Result}; use env_logger::{Builder, Env}; use girouette::{ cli::ProgramOptions, config::ProgramConfig, show, Girouette, Location, WeatherClient, }; use log::*; use std::{env, time::Duration}; use structopt::StructOpt; use termcolor::*; use tokio::runtime; static DEFAULT_CONFIG: &str = ...
#[cfg(feature = "geoclue")] async fn find_location(timeout: Duration) -> Result<Location> { info!("no location to query, trying geoclue"); girouette::geoclue::get_location(timeout) .await .map_err(|e| { e.context("geoclue couldn't report your location; use `-l/--location' argument`...
timeout).await?, }; let key = conf.key.clone().ok_or_else(|| { anyhow!( "no API key for OpenWeather was found you can get a key over at https://openweathermap.org/appid", ) })?; let lib = Girouette::new( conf.display_config, cache_length, time...
function_block-function_prefixed
[ { "content": "fn main() {\n\n let outdir = match env::var_os(\"OUT_DIR\") {\n\n None => return,\n\n Some(outdir) => outdir,\n\n };\n\n let mut app = ProgramOptions::clap();\n\n\n\n app.gen_completions(\"girouette\", Shell::Bash, &outdir);\n\n\n\n app.gen_completions(\"girouette\", S...
Rust
src/operator/helmert.rs
busstoptaktik/geodesy
2718c094001b0a2168deb4fbaaa09c4ab9f78a7c
#![allow(non_snake_case)] use crate::operator_construction::*; use crate::Context; use crate::CoordinateTuple; use crate::GeodesyError; #[derive(Debug)] pub struct Helmert { R: [[f64; 3]; 3], T0: [f64; 3], R0: [f64; 3], dR: [f64; 3], dT: [f64; 3], t_epoch: f64, t_obs: f64, scale: f64, ...
#![allow(non_snake_case)] use crate::operator_construction::*; use crate::Context; use crate::CoordinateTuple; use crate::GeodesyError; #[derive(Debug)] pub struct Helmert { R: [[f64; 3]; 3], T0: [f64; 3], R0: [f64; 3], dR: [f64; 3], dT: [f64; 3], t_epoch: f64, t_obs: f64, scale: f64, ...
scale += dt * self.dscale; } } let x = (c[0] - T[0]) / scale; let y = (c[1] - T[1]) / scale; let z = (c[2] - T[2]) / scale; if self.rotation { c[0] = x * R[0][0] + y * R[1][0] + z...
if self.rotation { R = rotation_matrix(rx, ry, rz, self.exact, self.position_vector); }
if_condition
[ { "content": "/// Handle instantiation of built-in operators.\n\nfn builtins(ctx: &mut Context, args: &mut OperatorArgs) -> Result<Operator, GeodesyError> {\n\n // Pipelines are not characterized by the name \"pipeline\", but simply by containing steps.\n\n if let Ok(steps) = args.numeric_value(\"_nsteps\...
Rust
ecap/src/common/name.rs
Mark-Simulacrum/ecap-rs
842f70a5bded587308c329ffbf7eacf3289a380c
use std::borrow::Cow; use std::cell::Cell; use std::sync::atomic::{AtomicUsize, Ordering}; static LAST_ID: AtomicUsize = AtomicUsize::new(0); #[derive(Debug, Clone)] pub struct Name<'a> { image: Option<Cow<'a, [u8]>>, id: Id, host_id: Cell<Option<u32>>, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub ...
use std::borrow::Cow; use std::cell::Cell; use std::sync::atomic::{AtomicUsize, Ordering}; static LAST_ID: AtomicUsize = AtomicUsize::new(0); #[derive(Debug, Clone)] pub struct Name<'a> { image: Option
elf.id { false } else { true } } pub fn image(&self) -> Option<&[u8]> { self.image.as_ref().map(|s| s.as_ref()) } pub fn host_id(&self) -> Option<u32> { self.host_id.get() } ...
<Cow<'a, [u8]>>, id: Id, host_id: Cell<Option<u32>>, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Id { Unknown, Unidentified, Id(u32), } impl<'a> Name<'a> { pub fn id(&self) -> Id { self.id } pub fn to_owned(self) -> Name<'static> { Name { ...
random
[ { "content": "/// Reading of `(Name, Area)` pairs across the adapter/host boundary.\n\n///\n\n/// This is used to share configuration information and transaction meta-information.\n\n///\n\n/// FIXME: \"Options objects and individual option values may be temporary. They must not\n\n/// be used beyond the method...
Rust
choseong-pullup/src/lib.rs
y15un/korean-stuff
e31c92ac364ca1cff88e3f5561fbbbc4cb9b7b49
use std::convert::TryFrom; use unicode_korean_multitool::{Choseong, Jongseong, Syllable}; const RULESET: [(Option<Jongseong>, Choseong, Jongseong, bool); 28] = [ (None, Choseong::Kiyeok, Jongseong::Kiyeok, false), (None, Choseong::SsangKiyeok, Jongseong::SsangKiyeok, false), (None, Choseong::Nieun, Jongseo...
use std::convert::TryFrom; use unicode_korean_multitool::{Choseong, Jongseong, Syllable}; const RULESET: [(Option<Jongseong>, Choseong, Jongseong, bool); 28] = [ (None, Choseong::Kiyeok, Jongseong::Kiyeok, false), (None, Choseong::SsangKiyeok, Jongseong::SsangKiyeok, false), (None, Choseong::Nieun, Jongseo...
#[cfg(test)] mod tests { #[test] fn test_pullup_choseong() { assert_eq!( super::pullup_choseong("초성 올려 쓰기"), "촛엉 올려 쓱이".to_owned() ); assert_eq!( super::pullup_choseong("이불 밖은 위험해!"), "입울 밖은 위험해!".to_owned() ); assert_eq!(...
pub fn pullup_choseong_config(source: &str, extended_flag: bool) -> String { let mut destination = String::with_capacity(source.len()); let mut characters = source.chars().peekable(); let mut choseong_pulled = false; while let Some(current) = characters.next() { if !Syllable::is_one_of_us(curr...
function_block-full_function
[ { "content": "pub fn pushdown_jongseong_config(source: &str, extended_flag: bool) -> String {\n\n let mut destination = String::with_capacity(source.len());\n\n\n\n let mut buffer: [u8; 4] = [0, 0, 0, 0];\n\n let mut characters = source.chars().peekable();\n\n let mut new_choseong = None;\n\n\n\n ...
Rust
gui/draw-cube/src/007-synchronization/main.rs
Shub1427/rustschool
fe45848a2101ac0cf48311e9926fe26f509059bd
use gfx_hal::{ command, format::{self as hal_format, Aspects, Swizzle}, image::{Layout, SubresourceRange, ViewKind}, pass::{Attachment, AttachmentOps, SubpassDesc}, pool::CommandPoolCreateFlags, prelude::*, window as hal_window, Backend, Features, Instance, }; use std::mem::ManuallyDrop; us...
use gfx_hal::{ command, format::{self as hal_format, Aspects, Swizzle}, image::{Layout, SubresourceRange, ViewKind}, pass::{Attachment, AttachmentOps, SubpassDesc}, pool::CommandPoolCreateFlags, prelude::*, window as hal_window, Backend, Features, Instance, }; use std::mem::ManuallyDrop; us...
} } impl<B: Backend> Drop for Renderer<B> { fn drop(&mut self) { unsafe { for image_available in self.image_available_semaphores.drain(..) { self.device.destroy_semaphore(image_available); } for render_complete in self.render_complete_semaphores.drai...
Ok(Renderer { instance, surface: ManuallyDrop::new(surface), device, command_pool: Some(command_pool), swapchain: Some(swapchain), image_views, render_pass: Some(render_pass), framebuffers, image_available_semaph...
call_expression
[ { "content": "// The &'static here means the return type has a static lifetime.\n\n// This is a Rust feature that you don't need to worry about now.\n\npub fn hello() -> &'static str {\n\n \"Hello, World!\"\n\n}\n", "file_path": "exercism/rust/hello-world/src/lib.rs", "rank": 0, "score": 250871.1...
Rust
rmqtt/src/settings/mod.rs
phial3/rmqtt
8c29529e273007178fd0af73dccb6b0bf6729339
use std::fmt; use std::net::SocketAddr; use std::ops::{Deref, DerefMut}; use std::sync::Arc; use std::time::Duration; use config::{Config, ConfigError, File}; use parking_lot::RwLock; use serde::de::{Deserialize, Deserializer}; use crate::{NodeId, Result}; use self::listener::Listeners; use self::log::Log; pub mod ...
use std::fmt; use std::net::SocketAddr; use std::ops::{Deref, DerefMut}; use std::sync::Arc; use std::time::Duration; use config::{Config, ConfigError, File}; use parking_lot::RwLock; use serde::de::{Deserialize, Deserializer}; use crate::{NodeId, Result}; use self::listener::Listeners; use self::log::Log; pub mod ...
}) .sum() } #[inline] pub fn deserialize_duration<'de, D>(deserializer: D) -> Result<Duration, D::Error> where D: Deserializer<'de>, { let v = String::deserialize(deserializer)?; Ok(to_duration(&v)) } #[inline] pub fn to_duration(text: &str) -> Duration { let text = text.to_lo...
match u { 'B' => v, 'K' => v * 1024, 'M' => v * 1048576, 'G' => v * 1073741824, _ => 0, }
if_condition
[ { "content": "fn open_file(filename: &str) -> Result<File> {\n\n OpenOptions::new()\n\n .create(true)\n\n .write(true)\n\n .append(true)\n\n .open(filename)\n\n .map_err(|e| MqttError::from(format!(\"logger file config error, filename: {}, {:?}\", filename, e)))\n\n}\n", ...
Rust
geo/src/algorithm/relate/geomgraph/topology_position.rs
phreeheeler/geo
ab0fe46cec04ebe358d66455a6b73415c925b18d
use super::{CoordPos, Direction}; use std::fmt; #[derive(Copy, Clone)] pub(crate) enum TopologyPosition { Area { on: Option<CoordPos>, left: Option<CoordPos>, right: Option<CoordPos>, }, LineOrPoint { on: Option<CoordPos>, }, } impl fmt::Debug for TopologyPosition { ...
use super::{CoordPos, Direction}; use std::fmt; #[derive(Copy, Clone)] pub(crate) enum TopologyPosition { Area { on: Option<CoordPos>, left: Option<CoordPos>, right: Option<CoordPos>, }, LineOrPoint { on: Option<CoordPos>, }, } impl fmt::Debug for TopologyPosition { ...
pub fn set_all_positions_if_empty(&mut self, position: CoordPos) { match self { Self::LineOrPoint { on } => { if on.is_none() { *on = Some(position); } } Self::Area { on, left, right } => { if on.is_non...
pub fn set_all_positions(&mut self, position: CoordPos) { match self { Self::LineOrPoint { on } => { *on = Some(position); } Self::Area { on, left, right } => { *on = Some(position); *left = Some(position); *righ...
function_block-full_function
[]
Rust
crates/tor-chanmgr/src/event.rs
Mohsen7s/arti
1dbb23982fa36d431f2dd2b501cfc043438d9de5
#![allow(dead_code, unreachable_pub)] use futures::{Stream, StreamExt}; use postage::watch; use std::{ fmt, time::{Duration, Instant}, }; #[derive(Default, Debug, Clone)] pub struct ConnStatus { online: Option<bool>, tls_works: Option<bool>,...
#![allow(dead_code, unreachable_pub)] use futures::{Stream, StreamExt}; use postage::watch; use std::{ fmt, time::{Duration, Instant}, }; #[derive(Default, Debug, Clone)] pub struct ConnStatus { online: Option<bool>, tls_works: Option<bool>,...
; ConnStatus { online, tls_works } } fn record_attempt(&mut self) { self.n_attempts += 1; } fn record_tcp_success(&mut self, now: Instant) { self.last_tcp_success = Some(now); } fn record_tls_finished(&mut self, now: Instant) { self.la...
match (self.last_chan_success.is_some(), early) { (true, _) => Some(true), (_, true) => None, (false, false) => Some(false), }
if_condition
[ { "content": "pub fn create_runtime() -> std::io::Result<impl Runtime> {\n\n PreferredRuntime::create()\n\n}\n\n\n\n/// Helpers for test_with_all_runtimes\n\npub mod testing__ {\n", "file_path": "crates/tor-rtcompat/src/lib.rs", "rank": 0, "score": 283516.07034823194 }, { "content": "/// ...
Rust
tornado-kernel/src/user/space.rs
HUST-OS/tornado-os
e086b451a0836c00bc13ab940f6a4fa55c1855c6
use crate::memory::{AddressSpaceId, PhysicalAddress, PhysicalPageNumber, PAGE_SIZE}; use alloc::boxed::Box; use async_mutex::AsyncMutex; use lazy_static::lazy_static; #[cfg(feature = "qemu")] const BASE: usize = 0x8400_0000; #[cfg(feature = "k210")] const BASE: usize = 0x8050_0000; lazy_static! { pub static ref ...
use crate::memory::{AddressSpaceId, PhysicalAddress, PhysicalPageNumber, PAGE_SIZE}; use alloc::boxed::Box; use async_mutex::AsyncMutex; use lazy_static::lazy_static; #[cfg(feature = "qemu")] const BASE: usize = 0x8400_0000; #[cfg(feature = "k210")] const BASE: usize = 0x8050_0000; lazy_static! { pub static ref ...
} #[allow(unused)] pub fn dealloc(&mut self, asid: AddressSpaceId) -> Option<(PhysicalPageNumber, usize)> { let mut prev = &mut self.used; loop { if prev.next.is_none() { break; } if prev.next.as_ref().unwrap().val == asid ...
if pages > N - self.len { None } else { let base = self.free.next.as_ref().unwrap().id * PAGE_SIZE + B; let base = PhysicalPageNumber::floor(PhysicalAddress(base)); for _ in 0..pages { let mut node = self.free.next.take().unwrap(); ...
if_condition
[ { "content": "pub fn bounded<T, const N: usize>() -> (Sender<T, N>, Receiver<T, N>) {\n\n let buf = Arc::new(AsyncMutex::new(ChannelBuf::new()));\n\n let tx_event = Arc::new(Event::new());\n\n let rx_event = Arc::new(Event::new());\n\n let sender = Sender {\n\n buf: Arc::clone(&buf),\n\n ...
Rust
src/spv/logical/parser/parser.rs
Trark/magmaflow
c5ebdbedfa576b63aa54f29b8bafcf46b5716b1c
use spv::op::*; use spv::types::*; use spv::raw::*; use spv::logical::*; use super::OpByBlock; #[derive(Clone, Debug, PartialEq)] pub enum ValidationError { MemoryModelMissing, ExpectedOpFunction(usize), ExpectedOpFunctionEnd(usize), ExpectedBranch(usize), UnexpectedInstruction(usize), } pub type...
use spv::op::*; use spv::types::*; use spv::raw::*; use spv::logical::*; use super::OpByBlock; #[derive(Clone, Debug, PartialEq)] pub enum ValidationError { MemoryModelMissing, ExpectedOpFunction(usize), ExpectedOpFunctionEnd(usize), ExpectedBranch(usize), UnexpectedInstruction(usize), } pub type...
locks, insts), Err(err) => return PhaseResult::Err(err), }; if let Some(&OpByBlock::OpFunctionEnd(_)) = insts.first() { let insts = insts.advance(); let def = FunctionDefinition { function: op.clone(), ...
, output) } PhaseResult::Next(next) => Ok((output, next)), PhaseResult::Err(err) => Err(err), } } read_rest(insts, f, Vec::new()) } fn read_capability(insts: OpSlice) -> PhaseResult<Capability> { if let Some(&OpByBlock::OpCapability(ref op)) = insts.first() { ...
random
[ { "content": "/// An instruction from an extended instruction set\n\n///\n\n/// This is expected to itself be an enum variant in the instruction set\n\npub trait ExtInst: Any + ExtInstClone + Debug + Display {\n\n /// Returns the op in the extended instruction\n\n fn get_op(&self) -> &Op;\n\n\n\n fn as...
Rust
examples/src/bin/smoltcp.rs
akiles/ppproto
b13f98d99b5afb2ffee18cebe6bef6ffdc340c84
#[path = "../serial_port.rs"] mod serial_port; use as_slice::{AsMutSlice, AsSlice}; use clap::Clap; use std::fmt::Write as _; use std::io::{Read, Write}; use std::marker::PhantomData; use std::ops::Range; use std::os::unix::io::AsRawFd; use std::path::Path; use std::str; use log::*; use smoltcp::iface::InterfaceBuild...
#[path = "../serial_port.rs"] mod serial_port; use as_slice::{AsMutSlice, AsSlice}; use clap::Clap; use std::fmt::Write as _; use std::io::{Read, Write}; use std::marker::PhantomData; use std::ops::Range; use std::os::unix::io::AsRawFd; use std::path::Path; use std::str; use log::*; use smoltcp::iface::InterfaceBuild...
w(vec![0; 65535]); let tcp4_tx_buffer = TcpSocketBuffer::new(vec![0; 65535]); let tcp4_socket = TcpSocket::new(tcp4_rx_buffer, tcp4_tx_buffer); let ip_addrs = [IpCidr::new(Ipv4Address::UNSPECIFIED.into(), 0)]; let mut iface = InterfaceBuilder::new(device).ip_addrs(ip_addrs).finalize(); let mu...
function_block-function_prefixed
[ { "content": "fn parse_options(mut pkt: &[u8], mut f: impl FnMut(u8, &[u8])) -> Result<(), MalformedError> {\n\n while pkt.len() != 0 {\n\n if pkt.len() < 2 {\n\n return Err(MalformedError);\n\n }\n\n\n\n let code = pkt[0];\n\n let len = pkt[1] as usize;\n\n\n\n ...
Rust
rav1e-worker/src/main.rs
rust-av/rav1e-by-gop
2fad32cd518dcf95e88fffbd2f3c8f66ab1ab41d
use std::{collections::BTreeMap, env, net::SocketAddrV4, path::PathBuf, time::Duration}; use clap::{App, Arg}; use lazy_static::lazy_static; use log::{debug, log_enabled}; use parking_lot::RwLock; use rand::Rng; use rav1e_by_gop::{EncodeOptions, EncodeState, VideoDetails}; use server::*; use tokio::time::sleep; use uu...
use std::{collections::BTreeMap, env, net::SocketAddrV4, path::PathBuf, time::Duration}; use clap::{App, Arg}; use lazy_static::lazy_static; use log::{debug, log_enabled}; use parking_lot::RwLock; use rand::Rng; use rav1e_by_gop::{EncodeOptions, EncodeState, VideoDetails}; use server::*; use tokio::time::sleep; use uu...
async fn main() { env::var("SERVER_PASSWORD").expect("SERVER_PASSWORD env var MUST be set!"); if env::var("RUST_LOG").is_err() { env::set_var("RUST_LOG", "rav1e_worker=info"); } env_logger::init(); let matches = App::new("rav1e-worker") .arg( Arg::with_name("LISTEN_IP")...
function_block-full_function
[ { "content": "pub fn encode_segment(\n\n opts: EncodeOptions,\n\n video_info: VideoDetails,\n\n data: SegmentData,\n\n thread_pool: &mut ThreadPool,\n\n rayon_pool: Arc<rayon::ThreadPool>,\n\n progress_sender: ProgressSender,\n\n segment_output_file: Output,\n\n) -> Result<()> {\n\n let ...
Rust
rust-runtime/aws-smithy-http-server/src/routing/tiny_map.rs
eduardomourar/smithy-rs
817bf68e69da1d1ef14f8e79a27ec39a6d92bbad
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ use std::{borrow::Borrow, collections::HashMap, hash::Hash}; #[derive(Clone, Debug)] pub struct TinyMap<K, V, const CUTOFF: usize> { inner: TinyMapInner<K, V, CUTOFF>, } #[derive(Clone, Debug)] enu...
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ use std::{borrow::Borrow, collections::HashMap, hash::Hash}; #[derive(Clone, Debug)] pub struct TinyMap<K, V, const CUTOFF: usize> { inner: TinyMapInner<K, V, CUTOFF>, } #[derive(Clone, Debug)] enu...
("c", 2), ("d", 3), ("e", 4)]; const LARGE_VALUES: [(&'static str, usize); 10] = [ ("a", 0), ("b", 1), ("c", 2), ("d", 3), ("e", 4), ("f", 5), ("g", 6), ("h", 7), ("i", 8), ("j", 9), ]; #[test] fn collect_small() { ...
TinyMap<K, V, CUTOFF> { type Item = (K, V); type IntoIter = IntoIter<K, V>; fn into_iter(self) -> Self::IntoIter { let inner = match self.inner { TinyMapInner::Vec(vec) => OrIterator::Left(vec.into_iter()), TinyMapInner::HashMap(hash_map) => OrIterator::Right(hash_map.into_...
random
[ { "content": "#[track_caller]\n\npub fn assert_uris_match(left: &Uri, right: &Uri) {\n\n if left == right {\n\n return;\n\n }\n\n assert_eq!(left.authority(), right.authority());\n\n assert_eq!(left.scheme(), right.scheme());\n\n assert_eq!(left.path(), right.path());\n\n assert_eq!(\n\...
Rust
src/util/test_helpers.rs
aimerib/nightrunner-lib
55d8a326a35e1f397fa9e8741d02bfe05359c2c8
use crate::config::{ determiners::AllowedDeterminers, directions::{AllowedDirections, Directions}, movements::AllowedMovements, prepositions::AllowedPrepositions, rooms::{Exits, Item, Room, Storage}, Config, Event, Narrative, State, Subject, Verb, VerbFunction, }; pub fn mock_config() -> Config...
use crate::config::{ determiners::AllowedDeterminers, directions::{AllowedDirections,
String::from("pick"), String::from("take"), String::from("grab"), String::from("pi"), String::from("tk"), String::from("gr"), String::from("get"), String::from("g"), ...
Directions}, movements::AllowedMovements, prepositions::AllowedPrepositions, rooms::{Exits, Item, Room, Storage}, Config, Event, Narrative, State, Subject, Verb, VerbFunction, }; pub fn mock_config() -> Config { Config { allowed_prepositions: AllowedPrepositions::init(), allowed_det...
random
[ { "content": "use std::cell::RefCell;\n\nuse std::collections::HashMap;\n\nuse std::fmt::{self, Display};\n\nuse std::iter::FromIterator;\n\n\n\nuse regex::Regex;\n\nuse serde::{Deserialize, Serialize};\n\n/// Module containing a few utility functions to\n\n/// make testing a little easier.\n\npub mod test_help...
Rust
src/lib.rs
w4/scoped-vec.rs
e8913a9c571a94d44e8c7f5a364ccca1fe034441
use std::sync::{Arc, RwLock, RwLockReadGuard}; use owning_ref::OwningHandle; #[derive(Clone)] pub struct ScopedVec<T: Clone> { inner: Arc<RwLock<Vec<T>>>, children: Arc<RwLock<Vec<ScopedVec<T>>>>, } impl<T: Clone> ScopedVec<T> { pub fn new() -> Self { Self { inner: Arc::new(RwLock::d...
use std::sync::{Arc, RwLock, RwLockReadGuard}; use owning_ref::OwningHandle; #[derive(Clone)] pub struct ScopedVec<T: Clone> { inner: Arc<RwLock<Vec<T>>>, children: Arc<RwLock<Vec<ScopedVec<T>>>>, } impl<T: Clone> ScopedVec<T> { pub fn new() -> Self { Self { inner: Arc::new(RwLock::d...
#[test] fn diverged_adjacent_scopes_cant_interact() { let mut root = ScopedVec::new(); root.push(3); let mut scoped1 = root.scope(); scoped1.push(4); let mut scoped2 = root.scope(); scoped2.push(5); let mut iter = scoped1.iter(); assert_eq!(it...
let mut root = ScopedVec::new(); root.push(3); let mut scoped = root.scope(); scoped.push(4); let mut nested_scoped1 = scoped.scope(); nested_scoped1.push(5); let mut nested_scoped2 = scoped.scope(); nested_scoped2.push(6); let mut iter = root.iter(); ...
function_block-function_prefix_line
[ { "content": "# scoped-vec.rs\n\n\n\n[![License: WTFPL](https://img.shields.io/badge/License-WTFPL-brightgreen.svg?style=flat-square&logo=appveyor)](http://www.wtfpl.net/about/) ![https://docs.rs/scoped-vec/](https://docs.rs/scoped-vec/badge.svg) [![Downloads](https://img.shields.io/crates/d/scoped-vec.svg?styl...
Rust
libranoc/src/syntax/parse/statement/expression/operator.rs
rano-lang/rano
fe047a40dd17e4b35457a375d7749ca881dac4dc
use crate::{ core::ast::*, syntax::{parse::*, Span, TokenKind}, }; pub struct OperatorBindingPowerPrefix { pub constructor: Box<dyn FnOnce(Box<Expression>) -> PrefixOperator>, pub right_binding_power: u8, } pub struct OperatorBindingPowerInfix { pub operator: Token, pub constructor: Box<dyn Fn...
use crate::{ core::ast::*, syntax::{parse::*, Span, TokenKind}, }; pub struct OperatorBindingPowerPrefix { pub constructor: Box<dyn FnOnce(Box<Expression>) -> PrefixOperator>, pub right_binding_power: u8, } pub struct OperatorBindingPowerInfix { pub operator: Token, pub constructor: Box<dyn Fn...
mainder(lhs, operator, rhs) }), left_binding_power: 11, right_binding_power: 12, } }), map(tag(TokenKind::PunctuationFullStop), |operator| { OperatorBindingPowerInfix { operator, constructor: Box::new...
|_| { OperatorBindingPowerPrefix { constructor: Box::new(|expr| PrefixOperator::UnaryPlus(UnaryPlus(expr))), right_binding_power: 13, } }), map(tag(TokenKind::PunctuationHyphenMinus), |_| { OperatorBindingPowerPrefix { ...
random
[ { "content": "pub fn parse(tokens: Vec<Token>) -> crate::core::Result<Module> {\n\n let i = ParseInput::new(tokens);\n\n let (_, nodes) = all_consuming(many0(parse_statement_node))(i)?;\n\n Ok(Module { nodes })\n\n}\n", "file_path": "libranoc/src/syntax/parse/mod.rs", "rank": 0, "score": 15...
Rust
coresimd/mod.rs
peterhj/stdsimd-nvptx
ee6e4c833e4cc76ab437e0f5d0c4899ad7138478
#[macro_use] mod macros; mod simd; #[stable(feature = "simd_arch", since = "1.27.0")] pub mod arch { #[cfg(any(target_arch = "x86", dox))] #[doc(cfg(target_arch = "x86"))] #[stable(feature = "simd_x86", since = "1.27.0")] pub mod x86 { #[stable(feature = "simd_x86", since = "1...
#[macro_use] mod macros; mod simd; #[stable(feature = "simd_arch", since = "1.27.0")] pub mod arch { #[cfg(any(target_arch = "x86", dox))] #[doc(cfg(target_arch = "x86"))] #[stable(feature = "simd_x86", since = "1.27.0")] pub mod x86 { #[stable(feature = "simd_x86", since = "1...
t_arch = "nvptx64")))] #[unstable(feature = "stdsimd", issue = "27731")] pub mod nvptx { pub use coresimd::nvptx::*; } } mod simd_llvm; #[cfg(any(target_arch = "x86", target_arch = "x86_64", dox))] #[doc(cfg(any(target_arch = "x86", target_arch = "x86_64")))] mod x86; #[cfg(any(target_arch = "x86_...
#[cfg(any(target_arch = "x86_64", dox))] #[doc(cfg(target_arch = "x86_64"))] #[stable(feature = "simd_x86", since = "1.27.0")] pub mod x86_64 { #[stable(feature = "simd_x86", since = "1.27.0")] pub use coresimd::x86::*; #[stable(feature = "simd_x86", since = "1.27.0")...
random
[ { "content": "#[proc_macro_attribute]\n\npub fn simd_test(\n\n attr: proc_macro::TokenStream,\n\n item: proc_macro::TokenStream,\n\n) -> proc_macro::TokenStream {\n\n let tokens = TokenStream::from(attr).into_iter().collect::<Vec<_>>();\n\n if tokens.len() != 3 {\n\n panic!(\"expected #[simd_...
Rust
nalgebra-sparse/src/ops/impl_std_ops.rs
ThatGeoGuy/nalgebra
10deb03b71793c5d98de04267a99d7af69a715d5
use super::serial::{scalar::*, spadd::*, spmm::*, spsub::*}; use crate::cs::{ CompressedColumnStorage, CompressedRowStorage, Compression, CsMatrix, CscMatrix, CsrMatrix, }; use nalgebra::{Dim, Matrix, RawStorage, RawStorageMut, Scalar}; use num_traits::Zero; use std::{ borrow::Borrow, ops::{Add, AddAssign...
use super::serial::{scalar::*, spadd::*, spmm::*, spsub::*}; use crate::cs::{ CompressedColumnStorage, CompressedRowStorage, Compression, CsMatrix, CscMatrix, CsrMatrix, }; use nalgebra::{Dim, Matrix, RawStorage, RawStorageMut, Scalar}; use num_traits::Zero; use std::{ borrow::Borrow, ops::{Add, AddAssign...
type Output = CsrMatrix<<T1 as Mul<T2>>::Output>; fn mul(self, rhs: CsMatrix<T2, MO2, MI2, D2, CompressedColumnStorage>) -> Self::Output { spmm_csc_csc(self, rhs).unwrap() } } impl<T1, T2, MO1, MO2, MI1, MI2, D1, D2> Mul<CsMatrix<T2, MO2, MI2, D2, CompressedRowStorage>> for CsMatrix<T1, MO1, MI1, ...
, MI1, MI2, D1, D2> Mul<CsMatrix<T2, MO2, MI2, D2, CompressedRowStorage>> for CsMatrix<T1, MO1, MI1, D1, CompressedColumnStorage> where T1: Scalar + Mul<T2>, <T1 as Mul<T2>>::Output: Scalar + AddAssign + Zero, T2: Scalar, MO1: Borrow<[usize]>, MO2: Borrow<[usize]>, MI1: Borrow<[usize]>, ...
random
[ { "content": "/// Sparse-sparse matrix subtraction.\n\n///\n\n/// This function takes two arguments, a CSC matrix and a CSR matrix, and performs sparse-matrix\n\n/// subtraction between the two.\n\n///\n\n/// # Errors\n\n///\n\n/// This function fails and produces an [`OperationError`] with kind\n\n/// [`Operat...
Rust
smart_contracts/interpreter/iflow/lib.rs
Liqum/rust-onchain-execution-engine
9db88f17283a320ac896b4431a7579384ae22f8f
#![feature(proc_macro_hygiene)] #![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; #[ink::contract(version = "0.1.0")] mod iflow { use ink_core::storage::{self, Flush}; use ink_prelude::vec::Vec; #[ink(storage)] struct Iflow { start_event: storage::Value<u128>, factory: s...
#![feature(proc_macro_hygiene)] #![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; #[ink::contract(version = "0.1.0")] mod iflow { use ink_core::storage::{self, Flush}; use ink_prelude::vec::Vec; #[ink(storage)] struct Iflow { start_event: storage::Value<u128>, factory: s...
33 { self.subprocesses.push(element_index); } } _ => { if type_info != _type_info { return; } } } self.cond_table ...
ble .get(&element_index) .map_or(0, |cond| cond[0]) } #[ink(message)] fn get_post_condition(&self, element_index: u128) -> u128 { self.cond_table .get(&element_index) .map_or(0, |cond| cond[1]) } #[ink(...
random
[ { "content": "/// Construct a `BpmnInterpreter::continue_execution` call\n\npub fn continue_execution(instance_id: u64, element_index: u128) -> Call {\n\n BpmnInterpreter::continue_execution(instance_id, element_index).into()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{calls, NodeRuntimeTypes}...
Rust
src/main.rs
jameslahm/convertio
a11f96b9af7e3ae9e6dad7d0b41b8cce2a4c07d1
use base64::{decode, encode}; use clap::{load_yaml, App}; use futures::future::try_join_all; use serde::{Deserialize, Deserializer}; use std::{ collections::HashMap, fs::File, io::{Read, Write}, path::PathBuf, time::Duration, u64, }; const API_BASE_URL: &str = "http://api.convertio.co/convert";...
use base64::{decode, encode}; use clap::{load_yaml, App}; use futures::future::try_join_all; use serde::{Deserialize, Deserializer}; use std::{ collections::HashMap, fs::File, io::{Read, Write}, path::PathBuf, time::Duration, u64, }; const API_BASE_URL: &str = "http://api.convertio.co/convert";...
async fn wait_for_status(task: &mut ConversionTask) -> Result<(), Box<dyn std::error::Error>> { let client = reqwest::Client::new(); let resp = client .get(format!("{}/{}/status", API_BASE_URL, task.conversion_id).as_str()) .send() .await? .json::<StatusConversionResp>() ...
async fn start_conversion( input_file_name: &str, output_format: &str, api_key: &str, ) -> Result<ConversionTask, Box<dyn std::error::Error>> { let mut map = HashMap::new(); map.insert("apikey", api_key); map.insert("input", "base64"); let mut file = File::open(input_file_name).expect(...
function_block-full_function
[ { "content": "## Convertio\n\nConvert anything from one format to another using [convertio.co](https://convertio.co/)\n\n\n\n### example\n\n```bash\n\ncargo run -- -f pdf \"Chp 2.pptx\" \"Chp 1.ppt\"\n\n```\n", "file_path": "README.md", "rank": 14, "score": 1.2168407813751934 } ]
Rust
ltn/src/select_boundary.rs
aclk/abstreet
611ab9fce155ae2ed37a224cbbd417fcebaa0536
use std::collections::BTreeSet; use anyhow::Result; use geom::Distance; use map_model::Block; use widgetry::mapspace::ToggleZoomed; use widgetry::mapspace::{World, WorldOutcome}; use widgetry::{ Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel, State, Text, TextExt, VerticalAlignment, W...
use std::collections::BTreeSet; use anyhow::Result; use geom::Distance; use map_model::Block; use widgetry::mapspace::ToggleZoomed; use widgetry::mapspace::{World, WorldOutcome}; use widgetry::{ Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel, State, Text, TextExt, VerticalAlignment, W...
fn currently_have_block(&self, app: &App, id: BlockID) -> bool { app.session.partitioning.block_to_neighborhood(id) == self.id } } impl State<App> for SelectBoundary { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition { if let Outcome::Clicked(x) = self.panel.event(ctx)...
d_owner = app.session.partitioning.block_to_neighborhood(id); app.session .partitioning .transfer_block(&app.map, id, old_owner, self.id)?; Ok(None) } }
function_block-function_prefixed
[ { "content": "pub fn stop(ctx: &mut EventCtx, app: &App, details: &mut Details, id: TransitStopID) -> Widget {\n\n let header = Widget::row(vec![\n\n Line(\"Bus stop\").small_heading().into_widget(ctx),\n\n header_btns(ctx),\n\n ]);\n\n\n\n Widget::custom_col(vec![header, stop_body(ctx, a...
Rust
src/lib/worker.rs
seb-odessa/workers-pool
dd093585771d86c6295123edc64c0b84a497d1f3
use std::sync::mpsc; use std::sync::mpsc::{Sender, Receiver}; use super::types::{Message, Processor, HasName, HasTarget}; pub struct WorkerHandler<T: HasName + HasTarget, W: HasName + Processor> { gate: Sender<Message<T>>, input: Receiver<Message<T>>, output: Sender<Message<T>>, received: usize, ...
use std::sync::mpsc; use std::sync::mpsc::{Sender, Receiver}; use super::types::{Message, Processor, HasName, HasTarget}; pub struct WorkerHandler<T: HasName + HasTarget, W: HasName + Processor> { gate: Sender<Message<T>>, input: Receiver<Message<T>>, output: Sender<Message<T>>, received: usize, ...
trace!("{} Has finished run()", self.worker.name()); } } #[cfg(test)] mod tests { use std::sync::mpsc; use std::sync::mpsc::{Sender, Receiver}; use std::thread; use types::{Message, Processor, HasName, HasTarget}; use super::WorkerHandler; #[derive(Debug, PartialEq)] struct EventFa...
impl<T: HasName + HasTarget, W: HasName + Processor> WorkerHandler<T, W> { pub fn new(worker: W, output: Sender<Message<T>>) -> Self { trace!("WorkerHandler::new({}, ...)", &worker.name()); let (tx, rx) = mpsc::channel(); WorkerHandler { gate: tx, input: rx, ...
random
[ { "content": "/// This trait guaranty that it's implementer has a process<T>() function\n\npub trait Processor {\n\n /// Takes arg of type <T>\n\n /// Returns result of the same type\n\n fn process<T>(&self, arg: T) -> T;\n\n}\n\n\n\n/// Message type used as container for all Supevisors/Workers communi...
Rust
dnscat/src/encryption/standard.rs
avitex/rust-dnscat2
151f889780ac4ebf65ecabe3a738f84a22965bb1
use std::borrow::Borrow; use bytes::BufMut; use constant_time_eq::constant_time_eq; use generic_array::typenum::{U32, U65}; use generic_array::{sequence::Lengthen, GenericArray}; use ring::agreement::{self, agree_ephemeral}; use ring::rand; use salsa20::cipher::{NewStreamCipher, StreamCipher}; use salsa20::Salsa20; us...
use std::borrow::Borrow; use bytes::BufMut; use constant_time_eq::constant_time_eq; use generic_array::typenum::{U32, U65}; use generic_array::{sequence::Lengthen, GenericArray}; use ring::agreement::{self, agree_ephemeral}; use ring::rand; use salsa20::cipher::{NewStreamCipher, StreamCipher}; use salsa20::Salsa20; us...
lt<(), EncryptionError> { let (cipher_key, mac_key) = self.stream_keys().get_write_keys(self.is_client); let nonce = self.next_nouce()?.to_be_bytes(); let mut cipher = Salsa20::new(&cipher_key, &calc_nonce(nonce)); cipher.encrypt(data); let sig = calc_signature(head, &nonce[..]...
= self .peer_authenticator .expect("peer authenticator consumed or not init"); if constant_time_eq(&valid[..], &peer[..]) { Ok(()) } else { Err(EncryptionError::Authentication) } } fn encrypt( &mut self, head: &SessionHead...
random
[ { "content": "pub fn decode_iter<I>(iter: I, skip_ignored: bool) -> impl Iterator<Item = Result<u8, DecodeError>>\n\nwhere\n\n I: Iterator<Item = u8>,\n\n{\n\n let mut iter = iter\n\n .fuse()\n\n .map(decode_nibble)\n\n .filter_map(move |res| match res {\n\n NibbleResult::I...
Rust
src/dnsimple/domains_signer_records.rs
dnsimple/dnsimple-rust
4f972d5e89b1cf76baea5b4df604359a39acfe5f
use crate::dnsimple::domains::Domains; use crate::dnsimple::{DNSimpleEmptyResponse, DNSimpleResponse, Endpoint, RequestOptions}; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct DelegationSignerRecord { pub id: u64, pub domain_id: u64, pub algorithm: S...
use crate::dnsimple::domains::Domains; use crate::dnsimple::{DNSimpleEmptyResponse, DNSimpleResponse, Endpoint, RequestOptions}; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct DelegationSignerRecord { pub id: u64, pub domain_id: u64, pub algorithm: S...
pub fn get_delegation_signer_record( &self, account_id: u64, domain: &str, ) -> Result<DNSimpleResponse<DelegationSignerRecord>, String> { let path = format!("/{}/domains/{}/ds_records", account_id, doma...
f, account_id: u64, domain: &str, payload: DelegationSignerRecordPayload, ) -> Result<DNSimpleResponse<DelegationSignerRecord>, String> { let path = format!("/{}/domains/{}/ds_records", account_id, domain); self.client .post::<SignerRecordEndpoint>(&*path, serde_...
function_block-function_prefixed
[ { "content": "/// Creates a mockserver and a client (changing the url of the client\n\n/// to that of the mockserver to capture the requests).\n\n///\n\n/// It builds a response struct for the mock server using the fixture.\n\n///\n\n/// # Arguments\n\n///\n\n/// `fixture`: the path to the fixture inside the `a...
Rust
src/lib.rs
dnaeon/rust-libzmq
6925d29555743e714864378c08eaeffaeed5e8f1
extern crate libc; const ZMQ_HAUSNUMERO: usize = 156384712; pub const EFSM: usize = ZMQ_HAUSNUMERO + 51; pub const ENOCOMPATPROTO: usize = ZMQ_HAUSNUMERO + 52; pub const ETERM: usize = ZMQ_HAUSNUMERO + 53; pub const EMTHREAD: usize = ZMQ_HAUSNUMERO + 54; pub const ZMQ_IO_THREADS: usize = 1; pub const ZMQ_MAX_SOCKETS...
extern crate libc; const ZMQ_HAUSNUMERO: usize = 156384712; pub const EFSM: usize = ZMQ_HAUSNUMERO + 51; pub const ENOCOMPATPROTO: usize = ZMQ_HAUSNUMERO + 52; pub const ETERM: usize = ZMQ_HAUSNUMERO + 53; pub const EMTHREAD: usize = ZMQ_HAUSNUMERO + 54; pub const ZMQ_IO_THREADS: usize = 1; pub const ZMQ_MAX_SOCKETS...
ibc::c_void, t: libc::c_int) -> *mut libc::c_void; pub fn zmq_close(s: *mut libc::c_void) -> libc::c_int; pub fn zmq_setsockopt(s: *mut libc::c_void, option: libc::c_int, optval: *const libc::c_void, optvallen: libc::size_t) -> libc::...
pub fn zmq_errno(); pub fn zmq_strerror(errnum: &i32) -> *const libc::c_char; pub fn zmq_version(major: &mut i32, minor: &mut i32, patch: &mut i32); pub fn zmq_ctx_new() -> *mut libc::c_void; pub fn zmq_ctx_term(context: *mut libc::c_void) -> libc::c_int...
random
[ { "content": "## rust-libzmq\n\n\n\nRust low-level bindings to [libzmq](https://github.com/zeromq/libzmq).\n\n\n\nCurrent version of `rust-libzmq` is built against libzmq version 4.2.0.\n\n\n\nIf you are looking for the high-level Rust ZeroMQ bindings, please\n\ncheck [rust-zmq](https://github.com/erickt/rust-z...
Rust
research/query_service/ir/runtime/src/process/operator/sort/sort.rs
lnfjpt/GraphScope
917146f86d8387302a2e1de6963115e7568bf3ee
use std::cmp::Ordering; use std::convert::{TryFrom, TryInto}; use ir_common::error::ParsePbError; use ir_common::generated::algebra as algebra_pb; use ir_common::generated::algebra::order_by::ordering_pair::Order; use crate::error::FnGenResult; use crate::process::functions::CompareFunction; use crate::process::ope...
use std::cmp::Ordering; use std::convert::{TryFrom, TryInto}; use ir_common::error::ParsePbError; use ir_common::generated::algebra as algebra_pb; use ir_common::generated::algebra::order_by::ordering_pair::Order; use crate::error::FnGenResult; use crate::process::functions::CompareFunction; use crate::process::ope...
#[test] fn sort_by_property_test() { let sort_opr = pb::OrderBy { pairs: vec![pb::order_by::OrderingPair { key: Some(common_pb::Variable::from("@.name".to_string())), order: 2, }], limit: None, }; let mut result ...
if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id()); } } let expected_ids = vec![2, 1]; assert_eq!(result_ids, expected_ids); }
function_block-function_prefix_line
[ { "content": "fn create_src(id: u32, source: &mut Source<i32>) -> Result<(Stream<i32>, Stream<i32>), BuildJobError> {\n\n let src1 = if id == 0 { source.input_from(1..5)? } else { source.input_from(8..10)? };\n\n let (src1, src2) = src1.copied()?;\n\n let src2 = src2.map(|x| Ok(x + 1))?;\n\n Ok((src...
Rust
src/parser/lexer/mod.rs
mitsuhiko/lol-html
2772fd0e9feb4a820bfc0cb460e9441b0d0c205d
#[macro_use] mod actions; mod conditions; mod lexeme; use crate::base::{Align, Range}; use crate::html::{LocalNameHash, Namespace, TextType}; use crate::parser::state_machine::{ ActionError, ActionResult, FeedbackDirective, StateMachine, StateResult, }; use crate::parser::{ ParserDirective, ParsingAmbiguityEr...
#[macro_use] mod actions; mod conditions; mod lexeme; use crate::base::{Align, Range}; use crate::html::{LocalNameHash, Namespace, TextType}; use crate::parser::state_machine::{ ActionError, ActionResult, FeedbackDirective, StateMachine, StateResult, }; use crate::parser::{ ParserDirective, ParsingAmbiguityEr...
#[inline] fn create_lexeme_with_raw<'i, T>( &mut self, input: &'i [u8], token: T, raw_end: usize, ) -> Lexeme<'i, T> { Lexeme::new( input.into(), token, Range { start: self.lexeme_start, end: raw_en...
e) -> Result<ParserDirective, RewritingError> { trace!(@output lexeme); self.lexeme_start = lexeme.raw_range().end; self.lexeme_sink.handle_tag(lexeme) }
function_block-function_prefixed
[ { "content": "type CapturerEventHandler<'h> = &'h mut dyn FnMut(TokenCapturerEvent) -> Result<(), RewritingError>;\n\n\n\npub struct TokenCapturer {\n\n encoding: &'static Encoding,\n\n text_decoder: TextDecoder,\n\n capture_flags: TokenCaptureFlags,\n\n}\n\n\n\nimpl TokenCapturer {\n\n pub fn new(c...
Rust
src/main.rs
matthias-t/workspace
2ff2562d55d2d92b007379fe5a283e3bb0d81582
#[macro_use] mod macros; mod app; mod exit; mod shell; mod tilde; mod workspace; use clap::ArgMatches; use colored::Colorize; use failure::Fail; use std::env; use std::fs; use std::io::Write; use std::path; use std::process; use crate::exit::Exit; use crate::tilde::Tilde; use crate::workspace::Workspace; pub static...
#[macro_use] mod macros; mod app; mod exit; mod shell; mod tilde; mod workspace; use clap::ArgMatches; use colored::Colorize; use failure::Fail; use std::env; use std::fs; use std::io::Write; use std::path; use std::process; use crate::exit::Exit; use crate::tilde::Tilde; use crate::workspace::Workspace; pub static...
fn path_to_binary_or_arg(matches: &ArgMatches) -> path::PathBuf { if let Some(path) = matches.value_of("PATH") { return path::Path::new(path) .with_file_name("ws") .with_extension("bat") .to_path_buf(); } else { let mut path = env::current_exe().unwrap_or_ex...
fn main() { let matches = app::cli().get_matches(); unsafe { VERBOSE = matches.is_present("verbose"); } if !matches.is_present("shell-wrapper") && matches.subcommand_matches("shell").is_none() { warn!("You are using the workspace binary, which is the backend for the `ws` function."); ...
function_block-full_function
[ { "content": "pub fn cli() -> App<'static, 'static> {\n\n App::new(\"workspace\")\n\n .version(crate_version!())\n\n .about(\"A command-line project manager\")\n\n .setting(AppSettings::SubcommandRequiredElseHelp)\n\n .global_setting(AppSettings::ColoredHelp)\n\n .global_se...
Rust
cli/src/forge.rs
Genysys/foundry
0527eb95ce9c17101b434a0626ba3861836c0a9e
use ethers::{ providers::Provider, solc::{remappings::Remapping, ArtifactOutput, Project}, }; use evm_adapters::{ sputnik::{vicinity, ForkMemoryBackend, PRECOMPILES_MAP}, FAUCET_ACCOUNT, }; use regex::Regex; use sputnik::backend::Backend; use structopt::StructOpt; use forge::MultiContractRunnerBuilder;...
use ethers::{ providers::Provider, solc::{remappings::Remapping, ArtifactOutput, Project}, }; use evm_adapters::{ sputnik::{vicinity, ForkMemoryBackend, PRECOMPILES_MAP}, FAUCET_ACCOUNT, }; use regex::Regex; use sputnik::backend::Backend; use structopt::StructOpt; use forge::MultiContractRunnerBuilder;...
fn install(root: impl AsRef<std::path::Path>, dependencies: Vec<Dependency>) -> eyre::Result<()> { let libs = std::path::Path::new("lib"); dependencies.iter().try_for_each(|dep| -> eyre::Result<_> { let path = libs.join(&dep.name); println!("Installing {} in {:?}, (url: {}, tag: {:?})", dep.n...
rexample ) } (None, Some(ref counterexample)) => { format!("[FAIL. Counterexample: {}]", counterexample) } (Some(ref reason), None) => { for...
function_block-function_prefixed
[ { "content": "/// Tries to extract the `Contract` in the `DAPP_JSON` file\n\npub fn find_dapp_json_contract(path: &str, name: &str) -> eyre::Result<Contract> {\n\n let dapp_json = dapp_json_path();\n\n let mut value: serde_json::Value = serde_json::from_reader(std::fs::File::open(&dapp_json)?)\n\n ...
Rust
graphannis/src/annis/db/token_helper.rs
corpus-tools/graphANNIS
6b1bf752a33f851f3fffe8e49e1e72cfc29b60f5
use crate::{ annis::{ db::{ aql::model::{AnnotationComponentType, TOKEN_KEY}, AnnotationStorage, }, errors::GraphAnnisError, }, errors::Result, graph::GraphStorage, AnnotationGraph, }; use graphannis_core::{ graph::ANNIS_NS, types::{Component, ...
use crate::{ annis::{ db::{ aql::model::{AnnotationComponentType, TOKEN_KEY}, AnnotationStorage, }, errors::GraphAnnisError, }, errors::Result, graph::GraphStorage, AnnotationGraph, }; use graphannis_core::{ graph::ANNIS_NS, types::{Component, ...
; Ok((out_left, out_right)) } } }
match self.right_edges.get_outgoing_edges(n).next() { Some(out) => Some(out?), None => None, }
if_condition
[ { "content": "pub fn compare_match_by_text_pos(\n\n m1: &Match,\n\n m2: &Match,\n\n node_annos: &dyn AnnotationStorage<NodeID>,\n\n token_helper: Option<&TokenHelper>,\n\n gs_order: Option<&dyn GraphStorage>,\n\n collation: CollationType,\n\n quirks_mode: bool,\n\n) -> Result<Ordering> {\n\...
Rust
packages/std/src/init_handle.rs
puneet2019/cosmwasm
8cf9c302e408ce175852ad6a2ab153d426b43bdd
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt; use crate::coins::Coin; use crate::encoding::Binary; use crate::errors::StdResult; use crate::types::{HumanAddr, Never}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum C...
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt; use crate::coins::Coin; use crate::encoding::Binary; use crate::errors::StdResult; use crate::types::{HumanAddr, Never}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum C...
=> assert_eq!(bank, msg), _ => panic!("must encode in Bank variant"), } } }
data: None, } } } #[cfg(test)] mod test { use super::*; use crate::errors::StdError; use crate::{coins, from_slice, to_vec, Uint128}; #[test] fn log_works_for_different_types() { let expeceted = LogAttribute { key: "foo".to_string(), value: "42".t...
random
[ { "content": "// coins is a shortcut constructor for a set of one denomination of coins\n\npub fn coins(amount: u128, denom: &str) -> Vec<Coin> {\n\n vec![coin(amount, denom)]\n\n}\n\n\n", "file_path": "packages/std/src/coins.rs", "rank": 1, "score": 333316.4643425882 }, { "content": "// ...
Rust
libllama/src/dbgcore.rs
HIDE810/llama
380326dd946cee1769711999b9c12aa09dfb1e99
use std::sync; use cpu::{self, v5, v6}; pub use cpu::irq::{IrqType9, IrqClient}; use cpu::caches::Ops; use hwcore; use io; #[derive(Clone)] pub struct DbgCore { hw: sync::Arc<sync::Mutex<hwcore::HwCore>> } impl DbgCore { pub fn bind(hw: hwcore::HwCore) -> DbgCore { DbgCore { hw: sync::Arc...
use std::sync; use cpu::{self, v5, v6}; pub use cpu::irq::{IrqType9, IrqClient}; use cpu::caches::Ops; use hwcore; use io; #[derive(Clone)] pub struct DbgCore { hw: sync::Arc<sync::Mutex<hwcore::HwCore>> } impl DbgCore { pub fn bind(hw: hwcore::HwCore) -> DbgCore { DbgCore { hw: sync::Arc...
de:block) => { match $self.cpu_ref() { CpuRef::v5($ident) => $code, CpuRef::v6($ident) => $code } }; } pub trait HwCtx { fn cpu_ref(&self) -> CpuRef; fn cpu_mut(&mut self) -> CpuMut; fn read_mem(&mut self, address: u32, bytes: &mut [u8]) -> Result<(), String> { ...
are11.lock().unwrap_or_else(print_regs) } } pub fn hw<'b>(&'b mut self) -> Box<dyn HwCtx + 'b> { match self.active_cpu { ActiveCpu::Arm9 => Box::new(self.hw9()), ActiveCpu::Arm11 => Box::new(self.hw11()) } } pub fn trigger_irq(&mut self, irq: IrqType9) {...
random
[ { "content": "/// Controls debugger behavior based on user-provided commands\n\n///\n\n/// `command`: Iterator over &str items\n\npub fn handle<'a, It>(active_cpu: &mut ActiveCpu, debugger: &mut dbgcore::DbgCore, mut command: It)\n\n where It: Iterator<Item=&'a str> {\n\n\n\n match command.next() {\n\n ...
Rust
rooms/tests/kdbush.rs
oniproject/tto
4336c525ac39b1706e7ded9b28e4c5d55929268f
/* mod data; fn sq_dist(a: [f32; 2], b: [f32; 2]) -> f32 { let dx = a[0] - b[0]; let dy = a[1] - b[1]; dx * dx + dy * dy } static IDS: &[u32] = &[ 97,74,95,30,77,38,76,27,80,55,72,90,88,48,43,46, 65,39,62,93, 9,96,47, 8, 3,12,15,14,21,41,36,40, 69,56,85,78,17,71,44,19,18,13,99,24,67,33,37,49, ...
/* mod data; fn sq_dist(a: [f32; 2], b: [f32; 2]) -> f32 { let dx = a[0] - b[0]; let dy = a[1] - b[1]; dx * dx + dy * dy } static IDS: &[u32] = &[ 97,74,95,30,77,38,76,27,80,55,72,90,88,48,43,46, 65,39,62,93, 9,96,47, 8, 3,12,15,14,21,41,36,40, 69,56,85,78,17,71,44,19,18,13,99,24,67,33,37,49, ...
fn within() { let mut index: KDBush<f32> = KDBush::new(10); index.fill(POINTS.iter().cloned().enumerate() .map(|(i, p)| (i as u32, p))); let mut result = Vec::new(); index.within(WITHIN_CENTER, WITHIN_RADIUS, |idx| { result.push(idx); let p = POINTS[idx as usize]; assert...
function_block-full_function
[ { "content": "pub fn test_within(p: [f32; 2]) -> bool {\n\n let dx = p[0] - WITHIN_CENTER[0];\n\n let dy = p[1] - WITHIN_CENTER[1];\n\n dx * dx + dy * dy <= WITHIN_RADIUS * WITHIN_RADIUS\n\n}\n\n\n", "file_path": "rooms/tests/data.rs", "rank": 0, "score": 279974.47262647696 }, { "co...
Rust
src/main.rs
arlicle/panda-api-install
4adefe942fe58770f617e8331475eebc38217cea
use std::fs::{self, DirEntry, File, OpenOptions}; use std::io::{self, BufReader, Read, Write, Error}; use std::path::Path; use std::process::Command; use fs_extra::dir::{self, copy}; use fs_extra::{copy_items, remove_items}; #[cfg(windows)] use winapi; #[cfg(windows)] use winreg::enums::*; #[cfg(windows)] use winreg:...
use std::fs::{self, DirEntry, File, OpenOptions}; use std::io::{self, BufReader, Read, Write, Error}; use std::path::Path; use std::process::Command; use fs_extra::dir::
; if panda_dir.exists() { let mut from_paths = vec![&panda_dir_string]; let _r = remove_items(&from_paths); } match std::fs::create_dir_all(&panda_dir_string) { Ok(_) => (), Err(e) => { println!("create folder failed {} {:?}", &panda_dir_st...
{self, copy}; use fs_extra::{copy_items, remove_items}; #[cfg(windows)] use winapi; #[cfg(windows)] use winreg::enums::*; #[cfg(windows)] use winreg::{self, RegKey}; fn main() { pretty_env_logger::init(); let current_exe = &std::env::current_exe().unwrap(); let current_exe = Path::new(current_exe); ...
random
[]
Rust
rust/src/bin/frontend.rs
emwalker/digraffe
0ea46c938155204739cae2ddc4c668b7d7d85acd
use actix_web::{guard, post, web, App, HttpRequest, HttpResponse, HttpServer}; use async_graphql::extensions; use async_graphql::http::{playground_source, GraphQLPlaygroundConfig}; use async_graphql::EmptySubscription; use async_graphql_actix_web::{GraphQLRequest, GraphQLResponse}; use std::env; use digraph::config::...
use actix_web::{guard, post, web, App, HttpRequest, HttpResponse, HttpServer}; use async_graphql::extensions; use async_graphql::http::{playground_source, GraphQLPlaygroundConfig}; use async_graphql::EmptySubscription; use async_graphql_actix_web::{GraphQLRequest, GraphQLResponse}; use std::env; use digraph::config::...
80"); HttpServer::new(move || { App::new() .app_data(web::Data::new(state.clone())) .service(index) .service( web::resource("/graphql") .guard(guard::Get()) .to(index_playground), ) .ser...
nsion(extensions::Logger) .finish(); let state = State::new(pool, schema, config.digraph_server_secret); let socket = env::var("LISTEN_ADDR").unwrap_or_else(|_| "0.0.0.0:8080".to_owned()); println!("Playground: http://localhost:80
function_block-random_span
[ { "content": "fn sha1_digest(normalized: &[u8]) -> String {\n\n let hash = Sha1::digest(normalized);\n\n format!(\"{:x}\", hash)\n\n}\n\n\n", "file_path": "rust/src/http/repo_url.rs", "rank": 0, "score": 157224.1471751658 }, { "content": "pub fn warning(text: String) -> Alert {\n\n ...
Rust
src/wayland/gamma_control.rs
EdwardBetts/way-cooler
9d0e5d8137dbe2b4e6c7c3c1b899ab3e87cb6da0
use wayland::gamma_control::generated ::server::gamma_control::GammaControl; use wayland::gamma_control::generated ::server::gamma_control_manager::GammaControlManager; use rustwlc::wayland; use rustwlc::handle::{wlc_handle_from_wl_output_resource, WlcOutput}; use rustwlc::render::{wlc_output_set_gamma, wlc_o...
use wayland::gamma_control::generated ::server::gamma_control::GammaControl; use wayland::gamma_control::generated ::server::gamma_control_manager::GammaControlManager; use rustwlc::wayland; use rustwlc::handle::{wlc_handle_from_wl_output_resource, WlcOutput}; use rustwlc::render::{wlc_output_set_gamma, wlc_o...
unsafe extern "C" fn get_gamma_control(client: *mut wl_client, _resource: *mut wl_resource, id: uint32_t, output: *mut wl_resource) { info!("Request received for control of the gamma ramps"); l...
resource: *mut wl_resource) { ffi_dispatch!( WAYLAND_SERVER_HANDLE, wl_resource_destroy, resource ); }
function_block-function_prefix_line
[ { "content": "pub fn lock_screen(client: *mut wl_client, output: WlcOutput) {\n\n let mut mode = write_current_mode();\n\n {\n\n match *mode {\n\n Modes::LockScreen(ref mut lock_mode) => {\n\n lock_mode.clients.push((client as _, output, None));\n\n return\n...
Rust
src/lib.rs
LaBatata101/grep_bin
89d41dfbcd4dc9b8d7e174bfe802971ab24eaebf
use clap::{values_t, App, AppSettings, Arg, ArgMatches}; use std::process; use std::{env, path::PathBuf}; use ansi_term::Colour; mod utils; use utils::{file, search}; use crate::utils::{print_hexdump_output, PatternType}; pub fn setup_args<'a>() -> ArgMatches<'a> { let integer_validator = |value: String| match ...
use clap::{values_t, App, AppSettings, Arg, ArgMatches}; use std::process; use std::{env, path::PathBuf}; use ansi_term::Colour; mod utils; use utils::{file, search}; use crate::utils::{print_hexdump_output, PatternType}; pub fn setup_args<'a>() -> ArgMatches<'a> { let integer_validator = |value: String| match ...
ne."), ) .arg( Arg::with_name("print_only") .short("p") .long("print-only") .help("Prints only the file name that contais the match."), ) .arg( Arg::with_name("skip_bytes") .short("s") ...
.empty_values(false) .help("The file path"), ) .arg( Arg::with_name("PATTERN") .index(2) .required(true) .empty_values(false) .long_help( "Can be a ascii string or a byte sequence. Asci...
random
[ { "content": "pub fn print_hexdump_output(matches: &Matches, bytes_per_line: usize) {\n\n let mut ascii_repr = Vec::new();\n\n\n\n for range in matches.context_bytes_indexes() {\n\n let offset = range.range().start;\n\n print!(\n\n \"{}: \",\n\n Colour::Green.paint(for...
Rust
examples/demo/main.rs
cohaereo/egui_glfw_gl
c2d244eaecffc06d6010d6aa6193c24757e31a23
use egui_glfw_gl as egui_backend; use std::time::Instant; use egui_backend::egui::{vec2, Color32, Image, Pos2, Rect}; use egui_glfw_gl::glfw::{Context, Key}; use glfw::Action; const SCREEN_WIDTH: u32 = 800; const SCREEN_HEIGHT: u32 = 600; const PIC_WIDTH: i32 = 320; const PIC_HEIGHT: i32 = 192; mod triangle; fn ma...
use egui_glfw_gl as egui_backend; use std::time::Instant; use egui_backend::egui::{vec2, Color32, Image, Pos2, Rect}; use egui_glfw_gl::glfw::{Context, Key}; use glfw::Action; const SCREEN_WIDTH: u32 = 800; const SCREEN_HEIGHT: u32 = 600; const PIC_WIDTH: i32 = 320; const PIC_HEIGHT: i32 = 192; mod triangle; fn ma...
, pixels_per_point: Some(native_pixels_per_point), ..Default::default() }); let start_time = Instant::now(); let mut srgba: Vec<Color32> = Vec::new(); for _ in 0..PIC_HEIGHT { for _ in 0..PIC_WIDTH { srgba.push(Color32::BLACK); } } ...
Some(Rect::from_min_size( Pos2::new(0f32, 0f32), vec2(width as f32, height as f32) / native_pixels_per_point, ))
call_expression
[ { "content": "pub fn handle_event(event: glfw::WindowEvent, state: &mut EguiInputState) {\n\n use glfw::WindowEvent::*;\n\n\n\n match event {\n\n FramebufferSize(width, height) => {\n\n state.input.screen_rect = Some(Rect::from_min_size(\n\n Pos2::new(0f32, 0f32),\n\n ...
Rust
day22/src/main.rs
obi1kenobi/advent-of-code-2021
f4df532edc67efcfaae7332e60483032afb3801a
#![feature(map_first_last)] use std::{ collections::{BTreeMap, BTreeSet}, env, fs, ops::RangeInclusive, fmt::Display, }; #[allow(unused_imports)] use itertools::Itertools; fn parse_range(range: &str) -> (i64, i64) { let (low, high) = range.split_once("..").unwrap(); (low.parse().unwrap(), high.par...
#![feature(map_first_last)] use std::{ collections::{BTreeMap, BTreeSet}, env, fs, ops::RangeInclusive, fmt::Display, }; #[allow(unused_imports)] use itertools::Itertools; fn parse_range(range: &str) -> (i64, i64) { let (low, high) = range.split_once("..").unwrap(); (low.parse().unwrap(), high.par...
e |(y_idx, z)| { z.iter() .enumerate() .filter_map(|(z_idx, is_on)| { if *is_on { Some(cell_volumes_ref[x_idx + 1][y_idx + 1][z_idx + 1]) } else { None ...
function_block-function_prefixed
[ { "content": "fn neighbors(data: &[Vec<i64>], x: i64, y: i64) -> impl Iterator<Item = (i64, i64)> + '_ {\n\n assert!(get_height(data, x, y).is_some());\n\n\n\n NEIGHBOR_OFFSETS\n\n .iter()\n\n .copied()\n\n .filter_map(move |(dx, dy)| {\n\n let new_x = x + dx;\n\n ...
Rust
src/upstream.rs
ZigzagAK/ws-platform
f00e25dd8bd08d5269cfbd689e18f707c9f8963f
/* * Copyright (C) 2020 Aleksei Konovkin (alkon2000@mail.ru) */ use std::net::SocketAddr; use std::sync::{ Arc, RwLock, atomic::{ AtomicUsize, Ordering } }; use std::collections::{ HashMap, hash_map::Iter }; use std::time::Duration; use std::cmp::min; use crate::connection_pool::*; use crate::error::CoreError; pub...
/* * Copyright (C) 2020 Aleksei Konovkin (alkon2000@mail.ru) */ use std::net::SocketAddr; use std::sync::{ Arc, RwLock, atomic::{ AtomicUsize, Ordering } }; use std::collections::{ HashMap, hash_map::Iter }; use std::time::Duration; use std::cmp::min; use crate::connection_pool::*; use crate::error::CoreError; pub...
g(), servers: RwLock::new([HashMap::new(), HashMap::new()]), active: Arc::new(0), balancer: balancer } } pub fn add_primary(&mut self, addr: SocketAddr, max_keepalive: usize, max_active: usize) { self.servers.write().unwrap()[0] .insert(addr, ...
n>, keepalive_requests: Option<u64> ) -> Upstream { Upstream { max_keepalive: max_keepalive, max_active: max_active, timeout: timeout, keepalive_timeout: keepalive_timeout, keepalive_requests: keepalive_requests, name: name.to_s...
random
[]
Rust
sui_core/src/transaction_input_checker.rs
velvia/sui
976b6bbc2573b375776995a6d3239cba5b73c26e
use std::collections::HashSet; use prometheus_exporter::prometheus::IntCounter; use serde::{Deserialize, Serialize}; use sui_types::{ base_types::{ObjectID, ObjectRef, SequenceNumber, SuiAddress}, error::{SuiError, SuiResult}, fp_ensure, gas::{self, SuiGasStatus}, messages::{InputObjectKind, Sing...
use std::collections::HashSet; use prometheus_exporter::prometheus::IntCounter; use serde::{Deserialize, Serialize}; use sui_types::{ base_types::{ObjectID, ObjectRef, SequenceNumber, SuiAddress}, error::{SuiError, SuiResult}, fp_ensure, gas::{self, SuiGasStatus}, messages::{InputObjectKind, Sing...
errors.push(object_kind.object_not_found_error()); continue; } }; if transfer_object_ids.contains(&object.id()) { object.is_transfer_eligible()?; } match check_one_lock( &transaction.signer(), ...
ions in a batch", object.id()), } ); } } let mut all_objects = Vec::with_capacity(input_objects.len()); let mut errors = Vec::new(); let transfer_object_ids: HashSet<_> = transaction .kind .single_transactions() .filter_map(|s| { ...
random
[ { "content": "/// Creates an object for use in the microbench\n\nfn create_gas_object(object_id: ObjectID, owner: SuiAddress) -> Object {\n\n Object::with_id_owner_gas_coin_object_for_testing(\n\n object_id,\n\n SequenceNumber::new(),\n\n owner,\n\n GAS_PER_TX,\n\n )\n\n}\n\n\n...
Rust
src/app/core/m3u8/m3u8.rs
PeterDing/aget-rs
ebf43a1a2ab9ae88efd66d2f298643c119021372
use std::{cell::Cell, path::PathBuf, rc::Rc, time::Duration}; use futures::{ channel::mpsc::{channel, Sender}, select, stream::StreamExt, SinkExt, }; use actix_rt::{ spawn, time::{delay_for, interval}, System, }; use crate::{ app::{ core::m3u8::common::{get_m3u8, M3u8Segment, ...
use std::{cell::Cell, path::PathBuf, rc::Rc, time::Duration}; use futures::{ channel::mpsc::{channel, Sender}, select, stream::StreamExt, SinkExt, }; use actix_rt::{ spawn, time::{delay_for, interval}, System, }; use crate::{ app::{ core::m3u8::common::{get_m3u8, M3u8Segment, ...
.await?; let index = segment.index; let mut buf: Vec<u8> = vec![]; let mut resp = resp.fuse(); let mut tick = interval(self.timeout).fuse(); let mut fire = false; loop { select! { item = resp.next() => { ...
request( &self.client, segment.method.clone(), segment.uri.clone(), segment.data.clone(), None, )
call_expression
[ { "content": "pub fn parse_header(raw: &str) -> Result<(&str, &str), Error> {\n\n if let Some(index) = raw.find(\": \") {\n\n return Ok((&raw[..index], &raw[index + 2..]));\n\n }\n\n if let Some(index) = raw.find(\":\") {\n\n return Ok((&raw[..index], &raw[index + 1..]));\n\n }\n\n ...
Rust
src/input_byte_stream.rs
sunfishcode/nameless
f5986c3f999db099c05214d6fe61bd04bf81bf93
use crate::open_input::{open_input, Input}; use crate::{MediaType, Pseudonym}; use clap::TryFromOsArg; use io_streams::StreamReader; use layered_io::{Bufferable, LayeredReader, ReadLayered, Status}; use std::ffi::OsStr; use std::fmt::{self, Debug, Formatter}; use std::io::{self, IoSliceMut, Read}; use terminal_io::Neve...
use crate::open_input::{open_input, Input}; use crate::{MediaType, Pseudonym}; use clap::TryFromOsArg; use io_streams::StreamReader; use layered_io::{Bufferable, LayeredReader, ReadLayered, Status}; use std::ffi::OsStr; use std::fmt::{self, Debug, Formatter}; use std::io::{self, IoSliceMut, Read}; use terminal_io::Neve...
#[test] fn data_url_base64() { let mut s = String::new(); InputByteStream::try_from_os_str_arg("data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==".as_ref()) .unwrap() .read_to_string(&mut s) .unwrap(); assert_eq!(s, "Hello, World!"); }
fn data_url_plain() { let mut s = String::new(); InputByteStream::try_from_os_str_arg("data:,Hello%2C%20World!".as_ref()) .unwrap() .read_to_string(&mut s) .unwrap(); assert_eq!(s, "Hello, World!"); }
function_block-full_function
[ { "content": "#[kommand::main]\n\nfn main(mut input: InputByteStream, mut output: OutputByteStream) -> anyhow::Result<()> {\n\n copy(&mut input, &mut output)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/copy.rs", "rank": 0, "score": 139863.88478210891 }, { "content": "#[kommand::ma...
Rust
plumber_vdf/src/parsers.rs
lasa01/plumber_core
056b42a7f0b29793407153cf8b52c6a0ca2e6076
use nom::{ branch::alt, bytes::complete::{escaped, is_a, is_not, tag, take_till, take_until}, character::complete::{anychar, char, multispace1, none_of, one_of, space0, space1}, combinator::{all_consuming, cut, eof, not, opt, peek, recognize, value}, error::{ErrorKind, ParseError}, sequence::{de...
use nom::{ branch::alt, bytes::complete::{escaped, is_a, is_not, tag, take_till, take_until}, character::complete::{anychar, char, multispace1, none_of, one_of, space0, space1}, combinator::{all_consuming, cut, eof, not, opt, peek, recognize, value}, error::{ErrorKind, ParseError}, sequence::{de...
)(i) } fn specific_token<'a: 'b, 'b, E: ParseError<&'a [u8]> + 'a>( key: &'b [u8], ) -> impl FnMut(&'a [u8]) -> IResult<&'a [u8], &'a [u8], E> + 'b { preceded( multispace_comment0, alt(( preceded(char('"'), cut(terminated(tag(key), char('"')))), tag(key), )), ...
ignore_many1(alt(( unit(unquoted_char_nonspace), unit(terminated(space1, unquoted_char_nonspace)), )))
call_expression
[ { "content": "fn read_animation_value(bytes: &mut &[u8]) -> Result<AnimationValue> {\n\n let value_bytes = bytes\n\n .get(..2)\n\n .ok_or_else(|| corrupted(\"animation values out of bounds\"))?\n\n .try_into()\n\n .expect(\"slice must have correct length\");\n\n\n\n *bytes = &b...
Rust
src/bin/day22/swiss_box.rs
mbikovitsky/aoc2021
0d952a7184edefcb6ab1859608daf74ed3fd4a43
use std::ops::{Sub, SubAssign}; use itertools::Itertools; use num::{CheckedAdd, CheckedMul, CheckedSub, Integer}; use petgraph::{ graph::NodeIndex, stable_graph::StableDiGraph, visit::{depth_first_search, Control, Dfs, DfsEvent, Reversed}, EdgeDirection::{Incoming, Outgoing}, }; use crate::r#box::Box;...
use std::ops::{Sub, SubAssign}; use itertools::Itertools; use num::{CheckedAdd, CheckedMul, CheckedSub, Integer}; use petgraph::{ graph::NodeIndex, stable_graph::StableDiGraph, visit::{depth_first_search, Control, Dfs, DfsEvent, Reversed}, EdgeDirection::{Incoming, Outgoing}, }; use crate::r#box::Box;...
} fn is_leaf(&self, node: NodeIndex) -> bool { self.tree .neighbors_directed(node, Outgoing) .next() .is_none() } } impl<T: Integer> Default for SwissBox<T> { fn default() -> Self { Self { tree: Default::default(), } } } imp...
Some( self.tree .externals(Incoming) .exactly_one() .map_err(|_| "More than one root in the tree") .unwrap(), )
call_expression
[ { "content": "pub fn input_file() -> Result<File> {\n\n let input_filename = match env::args_os().nth(1) {\n\n Some(filename) => filename,\n\n None => {\n\n let mut path: PathBuf = [\n\n OsStr::new(INPUTS_DIRECTORY),\n\n env::current_exe()\n\n ...
Rust
src/fs.rs
autokrator-uog/actix-web
8590eca7f83cf835b458c7e57d6f6ccffc8a58f4
use std::io; use std::io::Read; use std::fmt::Write; use std::fs::{File, DirEntry}; use std::path::{Path, PathBuf}; use std::ops::{Deref, DerefMut}; use mime_guess::get_mime_type; use param::FromParam; use handler::{Handler, Responder}; use headers::ContentEncoding; use httprequest::HttpRequest; use httpresponse::H...
use std::io; use std::io::Read; use std::fmt::Write; use std::fs::{File, DirEntry}; use std::path::{Path, PathBuf}; use std::ops::{Deref, DerefMut}; use mime_guess::get_mime_type; use param::FromParam; use handler::{Handler, Responder}; use headers::ContentEncoding; use httprequest::HttpRequest; use httpresponse::H...
}
let mut st = StaticFiles::new(".", false).index_file("index.html"); let mut req = HttpRequest::default(); req.match_info_mut().add("tail", "guide"); let resp = st.handle(req).respond_to(HttpRequest::default()).unwrap(); assert_eq!(resp.status(), StatusCode::FOUND); assert_eq!(re...
function_block-function_prefix_line
[ { "content": "fn index(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>>\n\n{\n\n println!(\"{:?}\", req);\n\n\n\n req.multipart() // <- get multipart stream for current request\n\n .from_err() // <- convert multipart errors\n\n .and_then(|item| { ...
Rust
src/simple_control.rs
magiclen/gitlab-deploy
9c8e0d0a765d2db598a618c719dcef3b9c837c86
use std::error::Error; use std::fmt::Write as FmtWrite; use execute::Execute; use clap::{ArgMatches, Values}; use crate::constants::*; use crate::functions::*; use crate::parse::*; #[inline] fn handle_command(values: Option<Values>) -> Result<Vec<&str>, &'static str> { match values { Some(values) => Ok(...
use std::error::Error; use std::fmt::Write as FmtWrite; use execute::Execute; use clap::{ArgMatches, Values}; use crate::constants::*; use crate::functions::*; use crate::parse::*; #[inline] fn handle_command(values: Option<Values>) -> Result<Vec<&str>, &'static str> { match values { Some(values) => Ok(...
rol failed!".into()); } } { let mut command = create_ssh_command(ssh_user_host, format!("cd {SSH_PROJECT:?} && echo \"{TIMESTAMP} {COMMAND:?} {REFERENCE_NAME}-{SHORT_SHA}\" >> {SSH_PROJECT:?}/../control.log", SSH_PROJECT = ssh_project, ...
; let project_name = parse_project_name(matches); let reference_name = parse_reference_name(matches); let phase = parse_phase(matches); let command = handle_command(matches.values_of("COMMAND"))?; let command_string: String = command.join(" "); let inject_project_directory = matches.is_pres...
random
[ { "content": "fn get_matches() -> ArgMatches {\n\n let app = Command::new(APP_NAME)\n\n .term_width(terminal_size().map(|(width, _)| width.0 as usize).unwrap_or(0))\n\n .version(CARGO_PKG_VERSION)\n\n .author(CARGO_PKG_AUTHORS)\n\n .about(concat!(\"GitLab Deploy is used for deploy...
Rust
src/bin/bevy_client.rs
qkniep/moonshot
e5b37cf15d6f31cb422a1954f86fc443dfb52063
use bevy::{ input::{keyboard::KeyboardInput, ElementState, Input}, log::{Level, LogSettings}, prelude::*, render::{camera::Camera, pass::ClearColor}, ui::camera::UI_CAMERA, }; use moonshot::building::*; use moonshot::combat::*; use moonshot::components::*; use moonshot::cursor_world_coords::*; us...
use bevy::{ input::{keyboard::KeyboardInput, ElementState, Input}, log::{Level, LogSettings}, prelude::*, render::{camera::Camera, pass::ClearColor}, ui::camera::UI_CAMERA, }; use moonshot::building::*; use moonshot::combat::*; use moonshot::components::*; use moonshot::cursor_world_coords::*; us...
y - 128.0 * trans.scale.y <= world_coords.y && trans.translation.y + 128.0 * trans.scale.y >= world_coords.y { state.current_planet = Some(entity); } } } }
function_block-function_prefixed
[ { "content": "pub fn update_simulation_time(mut sim_time: ResMut<NetworkSimulationTime>, time: Res<Time>) {\n\n sim_time.update_elapsed(time.delta_seconds);\n\n sim_time.reset_frame_lag();\n\n while sim_time.elapsed_duration() > sim_time.per_frame_duration() {\n\n sim_time.increment_frame_number...
Rust
src/day11.rs
jjcomer/advent2019
b6fa95f1ffb6ce56ed5ab47bacd3d0377322c69a
use crate::intcode; use crate::intcode::{run_program, IntCodeResult, Program}; use std::collections::HashMap; #[aoc_generator(day11)] pub fn input_generator(input: &str) -> Program { intcode::input_generator(input) } enum Direction { Up, Down, Left, Right, } fn change_direction(current_direction:...
use crate::intcode; use crate::intcode::{run_program, IntCodeResult, Program}; use std::collections::HashMap; #[aoc_generator(day11)] pub fn input_generator(input: &str) -> Program { intcode::input_generator(input) } enum Direction { Up, Down, Left, Right, } fn change_direction(current_direction:...
current_position = move_bot(&current_direction, &current_position); pointer = new_pointer; relative_index = new_relative_index; } }; } let max_x = map.keys().map(|x| x.0).max().unwrap(); let max_y = map.keys().map(|x| x.1).max().unwrap(); ...
on { Direction::Up => Direction::Left, Direction::Left => Direction::Down, Direction::Down => Direction::Right, Direction::Right => Direction::Up, }, 1 => match current_direction { Direction::Up => Direction::Right, Direction::Right...
random
[ { "content": "#[aoc_generator(day19)]\n\npub fn input_generator(input: &str) -> Program {\n\n intcode::input_generator(input)\n\n}\n\n\n\n#[cached(\n\n convert = r#\"{format!(\"{},{}\",x,y)}\"#,\n\n create = \"{UnboundCache::new()}\",\n\n type = \"UnboundCache<String,bool>\"\n\n)]\n", "file_path...
Rust
src/ecs/src/world.rs
lukebitts/Luck
aef25bc3442872789228e14989d203afe3cc8a52
use mopa::Any; use super::entity::Entities; use super::component::Components; use super::{Entity, System}; use std::any::TypeId; pub struct World { entities: Entities, components: Components, systems: Vec<Box<System>>, to_destroy: Vec<Entity>, } unsafe impl Send for World {} unsafe impl Sync for Worl...
use mopa::Any; use super::entity::Entities; use super::component::Components; use super::{Entity, System}; use std::any::TypeId; pub struct World { entities: Entities, components: Components, systems: Vec<Box<System>>, to_destroy: Vec<Entity>, } unsafe impl Send for World {} unsafe impl Sync for Worl...
fn destroy_scheduled_entities(&mut self) { let to_destroy = self.to_destroy.clone(); for entity in to_destroy { self.remove_all_components(entity); self.apply(entity); self.entities.destroy_entity(entity); } self.to_destroy.clear(); } } impl...
self.systems .par_iter() .map(|s| s.process(self)) .collect_into(&mut callbacks); for callback in &mut callbacks { (*callback)(self); } self.destroy_scheduled_entities(); }
function_block-function_prefix_line
[ { "content": "/// A trait that describes which components the system should process. It is split from the\n\n/// System trait to allow it to be implemented through the impl_signature macro.\n\npub trait Signature : mopa::Any + Send + Sync {\n\n /// Should return the components this system expects to process...
Rust
src/configuration/archive.rs
dandyvica/clf
0774f971a973d89688a72f7283e251c7a429e946
use std::{ fmt::Debug, path::{Path, PathBuf}, }; use serde::Deserialize; #[derive(Debug, Deserialize, Clone)] #[serde(deny_unknown_fields)] pub struct LogArchive { pub dir: Option<PathBuf>, pub extension: Option<String>, pub pattern: Option<String>, } impl LogArchive { ...
use std::{ fmt::Debug, path::{Path, PathBuf}, }; use serde::Deserialize; #[derive(Debug, Deserialize, Clone)] #[serde(deny_unknown_fields)] pub struct LogArchive { pub dir: Option<PathBuf>, pub extension: Option<String>, pub pattern: Option<String>, } impl LogArchive { ...
}
fn archived_path() { let p = PathBuf::from(r"C:\Windows\WindowsUpdate.log"); let archive = LogArchive { dir: None, extension: None, pattern: None, }; assert_eq!( archive.archived_path(&p), PathBuf::from(r"C:\Windows\WindowsUpda...
function_block-full_function
[ { "content": "fn read_file<R: BufRead>(mut reader: R) {\n\n // our read buffer\n\n let mut buffer = Vec::with_capacity(1024);\n\n\n\n loop {\n\n let ret = reader.read_until(b'\\n', &mut buffer);\n\n if let Ok(bytes_read) = ret {\n\n if bytes_read == 0 {\n\n break...
Rust
src/output.rs
tjbell/tcount
535a66463229d97845cfed29031ea2528a4c2f72
use crate::count::Counts; use crate::language::Language; use crate::query::{Query, QueryKind}; use prettytable::{format, Cell, Row, Table}; use regex::Regex; use std::fmt::Display; use std::format; use std::str::FromStr; #[derive(Debug)] pub enum Format { Table, CSV, } impl FromStr for Format { type Err =...
use crate::count::Counts; use crate::language::Language; use crate::query::{Query, QueryKind}; use prettytable::{format, Cell, Row, Table}; use regex::Regex; use std::fmt::Display; use std::format; use std::str::FromStr; #[derive(Debug)] pub enum Format { Table, CSV, } impl FromStr for Format { type Err =...
#[inline] fn title_cell(content: &str) -> Cell { Cell::new(content).style_spec("b") } #[inline] fn label_cell(label: &str) -> Cell { Cell::new(label).style_spec("li") } #[inline] fn count_cell(count: u64) -> Cell { Cell::new(&count.to_string()).style_spec("r") } #[inline] fn generic_cell(s: impl Display)...
pub fn format_builder() -> format::FormatBuilder { format::FormatBuilder::new() .separators( &[format::LinePosition::Top], format::LineSeparator::new('─', '─', '─', '─'), ) .separators( &[format::LinePosition::Title], format::LineSeparator::new...
function_block-full_function
[]
Rust
src/input/touch_controls.rs
khang06/doukutsu-rs
8e0fb80c8cdf59883c9e6ec1c6823b4f958949ed
use ggez::{Context, GameResult}; use winit::event::TouchPhase; use crate::common::Rect; use crate::engine_constants::EngineConstants; use crate::texture_set::TextureSet; #[derive(Copy, Clone, PartialEq, Eq)] pub enum TouchControlType { None, Dialog, Controls, } #[derive(Copy, Clone)] pub struct TouchPoin...
use ggez::{Context, GameResult}; use winit::event::TouchPhase; use crate::common::Rect; use crate::engine_constants::EngineConstants; use crate::texture_set::TextureSet; #[derive(Copy, Clone, PartialEq, Eq)] pub enum TouchControlType { None, Dialog, Controls, } #[derive(Copy, Clone)] pub struct TouchPoin...
} TouchPhase::Ended | TouchPhase::Cancelled => { self.points.retain(|p| p.id != touch.id); self.clicks.retain(|p| p.id != touch.id); } } } pub fn point_in(&self, bounds: Rect) -> Option<u64> { for point in self.points.iter() {...
if let Some(point) = self.points.iter_mut().find(|p| p.id == touch.id) { point.last_position = point.position; point.position = (touch.location.x / scale as f64, touch.location.y / scale as f64); } else { self.touch_id_counter = self.touch_id_c...
if_condition
[ { "content": "#[inline(always)]\n\npub fn fix9_scale(val: i32, scale: f32) -> f32 {\n\n (val as f64 * scale as f64 / 512.0).floor() as f32 / scale\n\n}\n\n\n", "file_path": "src/common.rs", "rank": 0, "score": 267354.8191958265 }, { "content": "pub fn interpolate_fix9_scale(old_val: i32, ...
Rust
src/util/encrypt.rs
MarcoPolo/rust-sssmc39
a3e9d53d295b249c0212d6f7ab9dc434c8210df2
use crate::error::Error; #[cfg(feature = "ring_pbkdf2")] use ring::pbkdf2; #[cfg(feature = "ring_pbkdf2")] use std::num::NonZeroU32; #[cfg(feature = "rust_crypto_pbkdf2")] use pbkdf2::pbkdf2; #[cfg(feature = "rust_crypto_pbkdf2")] use sha2::Sha256; #[cfg(feature = "rust_crypto_pbkdf2")] use hmac::Hmac; #[derive(Deb...
use crate::error::Error; #[cfg(feature = "ring_pbkdf2")] use ring::pbkdf2; #[cfg(feature = "ring_pbkdf2")] use std::num::NonZeroU32; #[cfg(feature = "rust_crypto_pbkdf2")] use pbkdf2::pbkdf2; #[cfg(feature = "rust_crypto_pbkdf2")] use sha2::Sha256; #[cfg(feature = "rust_crypto_pbkdf2")] use hmac::Hmac; #[derive(Deb...
fn xor(&self, a: &[u8], b: &[u8]) -> Vec<u8> { let mut retval = vec![0; b.len()]; for i in 0..b.len() { retval[i] = a[i] ^ b[i]; } retval } } #[cfg(test)] mod tests { use super::*; use rand::{thread_rng, Rng}; fn roundtrip_test(secret: Vec<u8>, passphrase: &str, identifier: u16, iteration_exponent...
df2::PBKDF2_HMAC_SHA256, NonZeroU32::new(iterations as u32).unwrap(), salt, password, &mut out, ); out }
function_block-function_prefixed
[ { "content": "pub fn verify_checksum(custom_string: &[u8], data: &[u32]) -> Result<(), Error> {\n\n\tlet mut values: Vec<u32> = custom_string.iter().map(|d| u32::from(*d)).collect();\n\n\tfor e in data {\n\n\t\tvalues.push(e.to_owned());\n\n\t}\n\n\tif polymod(&values) != 1 {\n\n\t\treturn Err(ErrorKind::Config...
Rust
runner-integration-tests/src/testkind/optimization.rs
comprakt/comprakt
2315e85972e63ea327c4d115ffe623253b520440
use crate::*; use optimization::{self, Optimization}; use serde_derive::Deserialize; use std::{ fs::File, io::{self, Write}, path::PathBuf, process::Stdio, }; #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "kebab-case")] pub enum AsmComparisonOutcome { Unchanged, ...
use crate::*; use optimization::{self, Optimization}; use serde_derive::Deserialize; use std::{ fs::File, io::{self, Write}, path::PathBuf, process::Stdio, }; #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "kebab-case")] pub enum AsmComparisonOutcome { Unchanged, ...
.into_optimizing_compiler_reference_data(&path_binary_optimized), &TestSpec { input: path_binary_optimized.clone(), references: path_binary_optimized.clone(), generate_tentatives: true, }, ); let reference_input = match test_data.reference.expect { ...
ompiler_call(callinfo_actual, &input_without_yaml_path); println!("Executing: {:?}", cmd_actual); let output_actual = cmd_actual .output() .expect("failed to call compiler under test for actual input"); assert_output( &output_actual, test_data .reference ...
random
[ { "content": "pub fn default_reference_exitcode(base: &PathBuf) -> ExpectedData {\n\n ExpectedData::InFile(add_extension(base, \"exitcode\"))\n\n}\n\n\n\nimpl OptionalReferenceData {\n\n pub fn all_from_own_file(base: &PathBuf) -> Self {\n\n Self {\n\n stderr: Some(default_reference_stde...
Rust
game_plugin/src/loading.rs
will-hart/cloud-surfer
4363e0bdf506c3049b77ee110cebc08fcd9e828c
mod paths; use crate::loading::paths::PATHS; use crate::GameState; use bevy::asset::LoadState; use bevy::prelude::*; use bevy_kira_audio::AudioSource; pub struct LoadingPlugin; impl Plugin for LoadingPlugin { fn build(&self, app: &mut AppBuilder) { app.add_system_set( SystemSet::on_enter(Game...
mod paths; use crate::loading::paths::PATHS; use crate::GameState; use bevy::asset::LoadState; use bevy::prelude::*; use bevy_kira_audio::AudioSource; pub struct LoadingPlugin; impl Plugin for LoadingPlugin { fn build(&self, app: &mut AppBuilder) { app.add_system_set( SystemSet::on_enter(Game...
fn check_state( mut commands: Commands, mut state: ResMut<State<GameState>>, asset_server: Res<AssetServer>, loading_state: Res<LoadingState>, mut loading_text: Query<&mut Text, With<LoadingText>>, loading_items: Query<Entity, With<LoadingItem>>, ) { if LoadState::Loaded != asset_ser...
function_block-full_function
[ { "content": "fn spawn_camera(mut commands: Commands) {\n\n commands.spawn_bundle(OrthographicCameraBundle::new_2d());\n\n}\n\n\n", "file_path": "game_plugin/src/player.rs", "rank": 0, "score": 112530.4475544525 }, { "content": "fn play_game_music(audio: Res<Audio>, channels: Res<AudioCha...
Rust
src/bin/client/gui.rs
CreativeWolfies/sharmat
c139a0adffee32fa6541b284d71934156a57099b
use super::style::SharmatStyleSheet; use super::settings::*; use sharmat::{game::*, player::PlayerColor}; use std::cell::RefCell; use std::collections::HashMap; use std::hash::Hash; use std::rc::Rc; use iced::{ executor, Application, Background, Color, Command, Container, Element, Length, Point, Row, Size, }; ...
use super::style::SharmatStyleSheet; use super::settings::*; use sharmat::{game::*, player::PlayerColor}; use std::cell::RefCell; use std::collections::HashMap; use std::hash::Hash; use std::rc::Rc; use iced::{ executor, Application, Background, Color, Command, Container, Element, Length, Point, Row, Size, }; ...
pub fn render_hints(&self) -> bool { self.settings.get_bool("render_hints").unwrap_or(true) } pub fn render_hints_opponent(&self) -> bool { self.settings.get_bool("render_hints_opponent").unwrap_or(false) } } impl<'a, Message> Widget<Message, Renderer> for GBoard { fn width(&self...
ize, usize) { if bounds.contains(mouse) { ( ((mouse.x - bounds.x) / tile_size).floor() as usize, ((mouse.y - bounds.y) / tile_size).floor() as usize, ) } else { (std::usize::MAX, std::usize::MAX) } }
function_block-function_prefixed
[ { "content": "type RawPiece = Option<(usize, PlayerColor)>;\n\n\n\n#[derive(Debug, PartialEq, Eq, Hash, Clone)]\n\npub struct Board {\n\n pub width: NonZeroUsize,\n\n pub height: NonZeroUsize,\n\n board: Vec<Vec<RawPiece>>,\n\n name: String,\n\n}\n\n\n\n#[derive(Debug, PartialEq, Eq)]\n\npub enum Bo...
Rust
src/auto/misc.rs
talklittle/gtk
b3af34228bef07e0c22829437d73144857fa44d7
use Buildable; use Widget; use ffi; use glib; use glib::StaticType; use glib::Value; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::mem; use std::mem::transmut...
use Buildable; use Widget; use ffi; use glib; use glib::StaticType; use glib::Value; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::mem; use std::mem::transmut...
fn connect_property_ypad_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::ypad", transmute(notify_ypad_trampoline::<Self> as usize), Bo...
d { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::yalign", transmute(notify_yalign_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } }
function_block-function_prefixed
[ { "content": "fn into_raw<F: FnMut() -> Continue + 'static>(func: F) -> gpointer {\n\n let func: Box<RefCell<Box<FnMut() -> Continue + 'static>>> =\n\n Box::new(RefCell::new(Box::new(func)));\n\n Box::into_raw(func) as gpointer\n\n}\n\n\n", "file_path": "src/signal.rs", "rank": 0, "scor...
Rust
src/arena/views/character_overlay.rs
chamons/ArenaGS
0d3c8d4ebc818198b21a8c99dc853286cc16b7c2
use sdl2::pixels::Color; use sdl2::rect::Point as SDLPoint; use sdl2::rect::Rect as SDLRect; use specs::prelude::*; use super::TILE_SIZE; use crate::after_image::prelude::*; use crate::atlas::prelude::*; use crate::clash::{ShortInfo, StatusInfo, StatusKind}; use crate::props::LifeBar; pub struct CharacterOverlay { ...
use sdl2::pixels::Color; use sdl2::rect::Point as SDLPoint; use sdl2::rect::Rect as SDLRect; use specs::prelude::*; use super::TILE_SIZE; use crate::after_image::prelude::*; use crate::atlas::prelude::*; use crate::clash::{ShortInfo, StatusInfo, StatusKind}; use crate::props::LifeBar; pub struct CharacterOverlay { ...
} fn get_overlay_statuses(&self, ecs: &World, entity: Entity) -> Vec<OverlayStatus> { let mut status = vec![]; let temperature = ecs.get_temperature(entity); if temperature.is_burning() { status.push(OverlayStatus::Burning); } if temperature.is_freezing() {...
Ok(CharacterOverlay { cache: IconCache::init_with_alpha( render_context, IconLoader::init_overlay_icons(), &[ "small_frame.png", "large_frame.png", "fire.png", "ice.png", ...
call_expression
[ { "content": "pub fn get_elemental_summon_to_use(ecs: &World) -> &'static str {\n\n let mut elements = vec![ElementalKind::Water, ElementalKind::Fire, ElementalKind::Wind, ElementalKind::Earth];\n\n\n\n for e in find_all_characters(ecs).iter().filter(|&&c| is_elemental(ecs, c)) {\n\n match get_elem...
Rust
tachyon-core/src/routers/api/object.rs
LGU-Web3-0/Project-Tachyon
156b5af1dc6e2c84c0818f38d81c42a4886510e1
use crate::session::UserInfo; use crate::{IntoAnyhow, State, StatusCode}; use actix_multipart::Multipart; use actix_session::Session; use actix_web::error::{ErrorBadRequest, ErrorInternalServerError}; use actix_web::http::header::{ContentDisposition, ContentType, DispositionParam, DispositionType}; use actix_web::web::...
use crate::session::UserInfo; use crate::{IntoAnyhow, State, StatusCode}; use actix_multipart::Multipart; use actix_session::Session; use actix_web::error::{ErrorBadRequest, ErrorInternalServerError}; use actix_web::http::header::{ContentDisposition, ContentType, DispositionParam, DispositionType}; use actix_web::web::...
) .insert_header(ContentDisposition { disposition: DispositionType::Attachment, parameters: vec![DispositionParam::Filename( metadata.name.as_str().to_string(), )], }) .streaming(stream)) } #[cfg(test)] mod test { #[cfg(all(not(miri), test...
ContentType( metadata .mimetype .parse() .map_err(error::ErrorInternalServerError)?, )
call_expression
[ { "content": "pub fn error_handler<B>(res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>>\n\nwhere\n\n B: MessageBody + 'static,\n\n{\n\n if res.request().method() != Method::GET\n\n || res\n\n .response()\n\n .headers()\n\n .get(\"content-type\")\n\n ...
Rust
metalmq-client/src/channel_api.rs
jonasrichard/metalmq
6196238344e95bfc0d76a4b1363ba4b7e2bc8157
use crate::client_api::{ClientRequest, ClientRequestSink, Param, WaitFor}; use crate::model::ChannelNumber; use crate::processor; use anyhow::Result; use metalmq_codec::frame; use std::collections::HashMap; #[derive(Debug)] pub struct Channel { pub(crate) channel: ChannelNumber, pub(crate) sink: ClientRequestS...
use crate::client_api::{ClientRequest, ClientRequestSink, Param, WaitFor}; use crate::model::ChannelNumber; use crate::processor; use anyhow::Result; use metalmq_codec::frame; use std::collections::HashMap; #[derive(Debug)] pub struct Channel { pub(crate) channel: ChannelNumber, pub(crate) sink: ClientRequestS...
pub async fn basic_publish( &self, exchange_name: &str, routing_key: &str, payload: String, mandatory: bool, immediate: bool, ) -> Result<()> { let mut flags = frame::BasicPublishFlags::empty(); flags.set(frame::BasicPublishFlags::MANDATORY, mand...
pub async fn queue_delete(&self, queue_name: &str, if_unused: bool, if_empty: bool) -> Result<()> { let mut flags = frame::QueueDeleteFlags::empty(); flags.set(frame::QueueDeleteFlags::IF_UNUSED, if_unused); flags.set(frame::QueueDeleteFlags::IF_EMPTY, if_empty); let frame = frame::queu...
function_block-full_function
[ { "content": "pub fn basic_consume_ok(channel: u16, consumer_tag: &str) -> AMQPFrame {\n\n AMQPFrame::Method(\n\n channel,\n\n BASIC_CONSUME_OK,\n\n MethodFrameArgs::BasicConsumeOk(BasicConsumeOkArgs {\n\n consumer_tag: consumer_tag.to_string(),\n\n }),\n\n )\n\n}\n\...
Rust
src/model/area/foundation.rs
nakidixon/klondike-rs
b017ed3cc4645df7e48f137e0197252feef44b09
use crate::{ model::{ card::{Card, Rank, Suit}, settings::GameSettings, stack::{Orientation, Stack, StackDetails, StackSelection}, }, utils::vec::SplitOffBounded, }; use super::{ Action, Area, AreaId, Held, InvalidCard, MoveResult, NotSupported, NothingToSelect, Result, Sele...
use crate::{ model::{ card::{Card, Rank, Suit}, settings::GameSettings, stack::{Orientation, Stack, StackDetails, StackSelection}, }, utils::vec::SplitOffBounded, }; use super::{ Action, Area, AreaId, Held, InvalidCard, MoveResult, NotSupported, NothingToSelect, Result, Sele...
p_or_else(|| self.id()); self.take_cards(len, source) } fn take_all_cards(&mut self) -> Held { let source = self.selection.held_from.take().unwrap_or_else(|| self.id()); self.take_cards(self.cards.len(), source) } fn peek_top_card(&self) -> Option<&Card> { self.cards.la...
} fn take_cards(&mut self, len: usize) -> Held { self.take_cards(len, self.id()) } fn take_all_cards(&mut self) -> Held { self.take_cards(self.cards.len(), self.id()) } fn peek_top_card(&self) -> Option<&Card> { self.cards.last() } fn as_stack(&self) -> Stack<'_>...
random
[ { "content": "pub trait SelectedArea: Area {\n\n fn deselect(self: Box<Self>) -> (Box<dyn UnselectedArea>, Option<Held>);\n\n\n\n fn activate(&mut self) -> Result<Option<Action>>;\n\n fn pick_up(&mut self) -> Result;\n\n fn put_down(&mut self) -> Result;\n\n fn select_more(&mut self) -> Result;\n...
Rust
benches/predict.rs
moisesmcardona/rav1e
5e9d1b0754879eba2f59192af9c0d016ef380eb5
use criterion::*; use rand::{ChaChaRng, Rng, SeedableRng}; use rav1e::partition::BlockSize; use rav1e::predict::{Block4x4, Intra}; pub const MAX_ITER: usize = 50000; pub const BLOCK_SIZE: BlockSize = BlockSize::BLOCK_32X32; pub fn generate_block(rng: &mut ChaChaRng) -> (Vec<u16>, Vec<u16>, Vec<u16>) { let block =...
use criterion::*; use rand::{ChaChaRng, Rng, SeedableRng}; use rav1e::partition::BlockSize; use rav1e::predict::{Block4x4, Intra}; pub const MAX_ITER: usize = 50000; pub const BLOCK_SIZE: BlockSize = BlockSize::BLOCK_32X32; pub fn generate_block(rng: &mut ChaChaRng) -> (Vec<u16>, Vec<u16>, Vec<u16>) { let block =...
pub fn intra_dc_4x4(b: &mut Bencher) { let mut ra = ChaChaRng::from_seed([0; 32]); let (mut block, above, left) = generate_block(&mut ra); b.iter(|| { for _ in 0..MAX_ITER { Block4x4::pred_dc( &mut block, BLOCK_SIZE.width(), &above[..4], &left[..4] ); } }) ...
pub fn pred_bench(c: &mut Criterion) { c.bench_function("intra_dc_4x4", |b| intra_dc_4x4(b)); c.bench_function("intra_dc_128_4x4_u8", |b| intra_dc_128_4x4_u8(b)); c.bench_function("intra_dc_left_4x4", |b| intra_dc_left_4x4(b)); c.bench_function("intra_dc_top_4x4", |b| intra_dc_top_4x4(b)); c.bench_function("i...
function_block-full_function
[ { "content": "pub fn intra_bench(c: &mut Criterion) {\n\n c.bench_functions(\n\n \"intra_dc_4x4\",\n\n vec![\n\n Fun::new(\"native\", |b, _: &Option<usize>| {\n\n predict_native::intra_dc_4x4(b)\n\n }),\n\n Fun::new(\"aom\", |b, _: &Option<usize>| {\n\n predict_intra_4x4_aom(...
Rust
src/config.rs
video-audio/va-tool
e97918d0aa936ace07dfd3df84758b6a7646a4d2
use std::env; use regex::Regex; use url::Url; use crate::error::{Error, Result}; use crate::opt::{Match as OptMatch, Matcher as OptMatcher, Opt, OptKind, Opts}; #[rustfmt::skip] const OPTS: Opts = &[ &Opt(&"vv", &["verbose"], OptKind::NoArg), &Opt(&"vvv", &["very-verbose"], OptKind::NoArg), &Opt(&"help",...
use std::env; use regex::Regex; use url::Url; use crate::error::{Error, Result}; use crate::opt::{Match as OptMatch, Matcher as OptMatcher, Opt, OptKind, Opts}; #[rustfmt::skip] const OPTS: Opts = &[ &Opt(&"vv", &["verbose"], OptKind::NoArg), &Opt(&"vvv", &["very-verbose"], OptKind::NoArg), &Opt(&"help",...
| <str/url> | Where to write to"); println!(); } pub(crate) fn print_version(&self) { println!("version: {}", env!("CARGO_PKG_VERSION")); } pub(crate) fn print_config(&self) { println!("log-level: {}", self.log_level.to_string().to_lowercase()); println!("inputs:"...
. is $(mpeg-ts-packer-size) * $(fifo-size)"); println!(" . mpeg-ts-packer-size is 188"); println!(" -o, --output, --out
random
[ { "content": "fn opts_get<'opt, 's>(opts: Opts<'opt>, key: &'s str) -> Option<&'opt Opt<'opt>> {\n\n for opt in opts {\n\n if opt.0 == key {\n\n return Some(opt);\n\n }\n\n\n\n for k in opt.1 {\n\n if *k == key {\n\n return Some(opt);\n\n }...