file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
storage_service.go | /*
* @Description:
* @version:
* @Company: iwhalecloud
* @Author: ddh
* @Date: 2021-02-07 16:32:07
* @LastEditors: ddh
* @LastEditTime: 2021-02-07 16:32:07
*/
package service
import (
"DBaas/models"
"DBaas/utils"
"DBaas/x/response"
"encoding/json"
"errors"
"fmt"
"github.com/go-xorm/xorm"
"github.com/k... | = ss.Engine.NewSession()
defer session.Close()
if err := session.Begin(); err != nil {
return err
}
scUser := models.ScUser{UserId: userId}
_, err := session.Delete(&scUser)
if err != nil {
return err
}
if len(scList) > 0 {
for _, scInfo := range scList {
if scInfo["type"] == "ready" {
scId := int(... | rror {
session : | identifier_name |
storage_service.go | /*
* @Description:
* @version:
* @Company: iwhalecloud
* @Author: ddh
* @Date: 2021-02-07 16:32:07
* @LastEditors: ddh
* @LastEditTime: 2021-02-07 16:32:07
*/
package service
import (
"DBaas/models"
"DBaas/utils"
"DBaas/x/response"
"encoding/json"
"errors"
"fmt"
"github.com/go-xorm/xorm"
"github.com/k... | ageService) CreateMysqlByPV(pvId int, storageMap map[string]interface{}, remark string, userId int, mysqlName string, qos *models.Qos) (err error) {
nameExist, _ := ss.Engine.Where("is_deploy = true").Exist(&models.ClusterInstance{Name: mysqlName})
if nameExist {
return errors.New("This name already exists ")
}
e... | {
list = make([]models.PersistentVolume, 0)
where := "name like ?"
args := []interface{}{"%" + key + "%"}
// AAAA为root用户可查看所有PV
if userTag != "AAAA" {
where += " AND user_tag = ?"
args = append(args, userTag)
}
err = ss.Engine.Where(where, args...).Limit(pageSize, pageSize*(page-1)).Desc("id").Find(&list)
i... | identifier_body |
storage_service.go | /*
* @Description:
* @version:
* @Company: iwhalecloud
* @Author: ddh
* @Date: 2021-02-07 16:32:07
* @LastEditors: ddh
* @LastEditTime: 2021-02-07 16:32:07
*/
package service
import (
"DBaas/models"
"DBaas/utils"
"DBaas/x/response"
"encoding/json"
"errors"
"fmt"
"github.com/go-xorm/xorm"
"github.com/k... | and cannot be deleted", "此存储被集群占用,无法删除!")
}
if sc.ScType == models.ScTypeUnique {
pvCount, err := ss.Engine.Where("sc_id = ?", id).Count(new(models.PersistentVolume))
if err != nil {
return err
}
if pvCount > 0 {
return response.NewMsg("This store has pv and cannot be deleted", "请先删除此存储下的pv!")
}
er... | d by the cluster | conditional_block |
lib.rs | //! # Lattice Client
//!
//! This library provides a client that communicates with a waSCC lattice using
//! the lattice protocol over the NATS message broker. All waSCC hosts compiled
//! in lattice mode have the ability to automatically form self-healing, self-managing
//! infrastructure-agnostic clusters called [lat... |
/// Retrieves the list of all capabilities within the lattice (discovery limited by the client timeout period)
pub fn get_capabilities(
&self,
) -> std::result::Result<HashMap<String, Vec<HostedCapability>>, Box<dyn std::error::Error>>
{
let mut host_caps = HashMap::new();
let ... | {
let mut host_actors = HashMap::new();
let sub = self
.nc
.request_multi(self.gen_subject(INVENTORY_ACTORS).as_ref(), &[])?;
for msg in sub.timeout_iter(self.timeout) {
let ir: InventoryResponse = serde_json::from_slice(&msg.data)?;
if let Invent... | identifier_body |
lib.rs | //! # Lattice Client
//!
//! This library provides a client that communicates with a waSCC lattice using
//! the lattice protocol over the NATS message broker. All waSCC hosts compiled
//! in lattice mode have the ability to automatically form self-healing, self-managing
//! infrastructure-agnostic clusters called [lat... | (&self, subject: &str) -> String {
match self.namespace.as_ref() {
Some(s) => format!("{}.wasmbus.{}", s, subject),
None => format!("wasmbus.{}", subject),
}
}
}
fn get_connection(host: &str, credsfile: Option<PathBuf>) -> nats::Connection {
let mut opts = if let Some(cr... | gen_subject | identifier_name |
lib.rs | //! # Lattice Client
//!
//! This library provides a client that communicates with a waSCC lattice using
//! the lattice protocol over the NATS message broker. All waSCC hosts compiled
//! in lattice mode have the ability to automatically form self-healing, self-managing
//! infrastructure-agnostic clusters called [lat... | pub const INVENTORY_CAPABILITIES: &str = "inventory.capabilities";
pub const EVENTS: &str = "events";
const AUCTION_TIMEOUT_SECONDS: u64 = 5;
/// A response to a lattice probe for inventory. Note that these responses are returned
/// through regular (non-queue) subscriptions via a scatter-gather like pattern, so the
/... |
pub const INVENTORY_ACTORS: &str = "inventory.actors";
pub const INVENTORY_HOSTS: &str = "inventory.hosts";
pub const INVENTORY_BINDINGS: &str = "inventory.bindings"; | random_line_split |
mod.rs | pub mod cut_detector;
pub mod ring;
pub mod view;
use crate::{
common::{ConfigId, Endpoint, NodeId, Scheduler, SchedulerEvents},
consensus::FastPaxos,
error::Result,
event::{Event, NodeStatusChange},
monitor::Monitor,
transport::{
proto::{
self, Alert, BatchedAlertMessage, E... | ,
metadata: Metadata::default(),
})
.collect()
}
// Filter for removing invalid edge update messages. These include messages
// that were for a configuration that the current node is not a part of, and messages
// that violate teh semantics of being a part of a c... | {
EdgeStatus::Up
} | conditional_block |
mod.rs | pub mod cut_detector;
pub mod ring;
pub mod view;
use crate::{
common::{ConfigId, Endpoint, NodeId, Scheduler, SchedulerEvents},
consensus::FastPaxos,
error::Result,
event::{Event, NodeStatusChange},
monitor::Monitor,
transport::{
proto::{
self, Alert, BatchedAlertMessage, E... | cluster_metadata: HashMap::new(),
}
};
self.messages
.push_back((from, proto::ResponseKind::Join(response).into()));
}
}
// Invoked by observers of a node for failure detection
fn handle_probe_message(&self) -> Response {
... | sender: self.host_addr.clone(),
status: JoinStatus::ConfigChanged,
config_id: self.view.get_current_config_id(),
endpoints: vec![],
identifiers: vec![], | random_line_split |
mod.rs | pub mod cut_detector;
pub mod ring;
pub mod view;
use crate::{
common::{ConfigId, Endpoint, NodeId, Scheduler, SchedulerEvents},
consensus::FastPaxos,
error::Result,
event::{Event, NodeStatusChange},
monitor::Monitor,
transport::{
proto::{
self, Alert, BatchedAlertMessage, E... | (&mut self) {
for signal in self.monitor_cancellers.drain(..) {
let _ = signal.send(());
}
}
fn respond_to_joiners(&mut self, proposal: Vec<Endpoint>) {
let configuration = self.view.get_config();
let join_res = JoinResponse {
sender: self.host_addr.clon... | cancel_failure_detectors | identifier_name |
mod.rs | pub mod cut_detector;
pub mod ring;
pub mod view;
use crate::{
common::{ConfigId, Endpoint, NodeId, Scheduler, SchedulerEvents},
consensus::FastPaxos,
error::Result,
event::{Event, NodeStatusChange},
monitor::Monitor,
transport::{
proto::{
self, Alert, BatchedAlertMessage, E... |
pub fn view(&self) -> Vec<&Endpoint> {
self.view
.get_ring(0)
.expect("There is always a ring!")
.iter()
.collect()
}
pub fn step(&mut self, from: Endpoint, msg: proto::RequestKind) {
use proto::RequestKind::*;
match msg {
... | {
let nodes = self.view.get_ring(0);
nodes
.iter()
.map(|_| NodeStatusChange {
endpoint: self.host_addr.clone(),
status: EdgeStatus::Up,
metadata: Metadata::default(),
})
.collect()
} | identifier_body |
font.rs | use prelude::*;
use core::{self, Layer, Context, Color, Point2, Rect};
use core::builder::*;
use rusttype;
use backends::backend;
use font_loader::system_fonts;
static FONT_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
/// A font used for writing on a [`Layer`](struct.Layer.html).
///
/// Use [`Font::builder()`](#method.... | (context: &Context, font_data: Vec<u8>, size: f32) -> Font {
Font {
data : font_data,
font_id : FONT_COUNTER.fetch_add(1, Ordering::Relaxed),
size : size,
context : context.clone(),
}
}
/// Write text to given layer using given font
fn w... | create | identifier_name |
font.rs | use prelude::*;
use core::{self, Layer, Context, Color, Point2, Rect};
use core::builder::*;
use rusttype;
use backends::backend;
use font_loader::system_fonts;
static FONT_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
/// A font used for writing on a [`Layer`](struct.Layer.html).
///
/// Use [`Font::builder()`](#method.... |
/// Creates a new unique font
fn create(context: &Context, font_data: Vec<u8>, size: f32) -> Font {
Font {
data : font_data,
font_id : FONT_COUNTER.fetch_add(1, Ordering::Relaxed),
size : size,
context : context.clone(),
}
}
/// Wr... | {
if let Some((font_data, _)) = system_fonts::get(&Self::build_property(&info)) {
Ok(Self::create(context, font_data, info.size))
} else {
Err(core::Error::FontError("Failed to get system font".to_string()))
}
} | identifier_body |
font.rs | use prelude::*;
use core::{self, Layer, Context, Color, Point2, Rect};
use core::builder::*;
use rusttype;
use backends::backend;
use font_loader::system_fonts;
static FONT_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
/// A font used for writing on a [`Layer`](struct.Layer.html).
///
/// Use [`Font::builder()`](#method.... | .finish()
}
}
impl Font {
/// Returns a [font builder](support/struct.FontBuilder.html) for font construction.
///
/// # Examples
///
/// ```rust
/// # use radiant_rs::*;
/// # let display = Display::builder().hidden().build().unwrap();
/// # let renderer = Renderer::ne... | .field("size", &self.size) | random_line_split |
font.rs | use prelude::*;
use core::{self, Layer, Context, Color, Point2, Rect};
use core::builder::*;
use rusttype;
use backends::backend;
use font_loader::system_fonts;
static FONT_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
/// A font used for writing on a [`Layer`](struct.Layer.html).
///
/// Use [`Font::builder()`](#method.... |
if info.monospace {
property = property.monospace();
}
property.build()
}
}
/// A wrapper around rusttype's font cache.
pub struct FontCache {
cache : Mutex<rusttype::gpu_cache::Cache<'static>>,
queue : Mutex<Vec<(Rect<u32>, Vec<u8>)>>,
dirty : AtomicBool,
}
... | {
property = property.bold();
} | conditional_block |
app.js | console.log('sanity check, app.js is connected')
//Declare global variables here
var map,
template,
$reviewsList,
allReviews = [],
classes,
batwichSmack = [
'Wanna know my secret identity?',
'Stick it in your food hole!',
'For whom the BLT tolls.',
'A hotdog is no sandwich.'... | (user){
console.log(user)
activeUser = user
}
| saveUser | identifier_name |
app.js | console.log('sanity check, app.js is connected')
//Declare global variables here
var map,
template,
$reviewsList,
allReviews = [],
classes,
batwichSmack = [
'Wanna know my secret identity?',
'Stick it in your food hole!',
'For whom the BLT tolls.',
'A hotdog is no sandwich.'... | // listener for find hero button. hides button to search again until map is moved.
$('.map-section').on('click', '#map-button', function(){
console.log('map button pressed');
$('#hero-map').show();
$('.find-hero-button').hide();
// set default location as Hell Mi
var defaultLocation = {
... | //hide map area when page loads
$('#hero-map').hide();
| random_line_split |
app.js | console.log('sanity check, app.js is connected')
//Declare global variables here
var map,
template,
$reviewsList,
allReviews = [],
classes,
batwichSmack = [
'Wanna know my secret identity?',
'Stick it in your food hole!',
'For whom the BLT tolls.',
'A hotdog is no sandwich.'... | else {
activeUser.location = data.location;
console.log(activeUser);
$.ajax({
method: 'POST',
url: '/api/locations',
data: activeUser,
success: appendRestaurants,
error: noRestaurants
})
}
}
function noLocation(data){
... | {
map = new google.maps.Map(document.getElementById('mapPlacement'), {
center: {lat: data.location.lat, lng: data.location.lng},
zoom: 15
})
$.ajax({
method: 'POST',
url: '/api/locations',
data: data,
success: showRestaurants,
err... | conditional_block |
app.js | console.log('sanity check, app.js is connected')
//Declare global variables here
var map,
template,
$reviewsList,
allReviews = [],
classes,
batwichSmack = [
'Wanna know my secret identity?',
'Stick it in your food hole!',
'For whom the BLT tolls.',
'A hotdog is no sandwich.'... |
function heroChat() {
smackTalk = setInterval(function(){
$('.batwich-chat').empty();
$('.hero-chat').empty();
var chance = Math.round(Math.random());
if (chance) {
$('.hero-chat').hide();
$('.batwich-chat').show(400);
$('.batwich-chat').html(batwichSmack[Math.ro... | {
console.log('Trying to edit the review below', data);
templateReview({
reviewContent: data.reviewContent2
})
console.log('The review was edited', data);
return templateReview;
window.location.href="../"
} | identifier_body |
type_checker.rs | use scopeguard::{guard, ScopeGuard};
use super::model::Model;
use super::cwf::*;
use super::lang::ast::*;
pub struct TypeChecker<T: Model> {
model: T,
ctxs : Vec<CtxInfo>,
}
struct CtxInfo {
syntax: Ctx,
// morphism from previous (if any) context to current
weakening: Option<Morph>,
defs: Vec<... | (&mut self, expr: &Expr) -> Result<(Tm, Ty), String> {
let (tm, _) = self.check_tm(expr)?;
let eq_ty = self.model.eq_ty(&tm, &tm);
let refl_tm = self.model.refl(&tm);
Ok((refl_tm, eq_ty))
}
fn true_tm(&mut self) -> (Tm, Ty) {
let cur_ctx_syn = &self.ctxs.last().unwrap().... | refl | identifier_name |
type_checker.rs | use scopeguard::{guard, ScopeGuard};
use super::model::Model;
use super::cwf::*;
use super::lang::ast::*;
pub struct TypeChecker<T: Model> {
model: T,
ctxs : Vec<CtxInfo>,
}
struct CtxInfo {
syntax: Ctx,
// morphism from previous (if any) context to current
weakening: Option<Morph>,
defs: Vec<... | if let Some(name) = name {
s.ctxs.last_mut().unwrap().defs.push((name.clone(), val, ty));
};
check_body(&mut s, body)
}
pub fn check_ty(&mut self, expr: &Expr) -> Result<Ty, String> {
let cur_ctx_syn = &self.ctxs.last().unwrap().syntax;
match expr {
... | random_line_split | |
type_checker.rs | use scopeguard::{guard, ScopeGuard};
use super::model::Model;
use super::cwf::*;
use super::lang::ast::*;
pub struct TypeChecker<T: Model> {
model: T,
ctxs : Vec<CtxInfo>,
}
struct CtxInfo {
syntax: Ctx,
// morphism from previous (if any) context to current
weakening: Option<Morph>,
defs: Vec<... |
fn true_tm(&mut self) -> (Tm, Ty) {
let cur_ctx_syn = &self.ctxs.last().unwrap().syntax;
let bool_ty = self.model.bool_ty(cur_ctx_syn);
let tm = self.model.true_tm(cur_ctx_syn);
(tm, bool_ty)
}
fn false_tm(&mut self) -> (Tm, Ty) {
let cur_ctx_syn = &self.ctxs.last(... | {
let (tm, _) = self.check_tm(expr)?;
let eq_ty = self.model.eq_ty(&tm, &tm);
let refl_tm = self.model.refl(&tm);
Ok((refl_tm, eq_ty))
} | identifier_body |
app.component.local.ts | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
i... | {
commonResponseHandler(res, query);
insertHeadersIntoResponseViewer(res.headers);
let errorText;
try {
errorText = res.json();
handleJsonResponse(errorText);
return;
} catch(e) {
errorText = res.text();
}
if (errorText.indexOf("<!DOCTYPE html>") != -1) {
handleHtmlResponse(errorTe... | identifier_body | |
app.component.local.ts | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
i... | (query:GraphApiCall) {
let text = "";
if (isSuccessful(query)) {
text += getString(AppComponent.Options, "Success");
} else {
text += getString(AppComponent.Options, "Failure");
}
text += ` - ${getString(AppComponent.Options, "Status Code")} ${query.statu... | createTextSummary | identifier_name |
app.component.local.ts | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
i... |
`]
})
export class AppComponent extends GraphExplorerComponent implements OnInit, AfterViewInit {
ngAfterViewInit(): void {
// Headers aren't updated when that tab is hidden, so when clicking on any tab reinsert the headers
if (typeof $ !== "undefined") {
$("#response-viewer-labels .ms-Pivot-li... | padding: 0px;
} | random_line_split |
__init__.py | """
Deployment management for KnightLab web application projects.
Read the README.
"""
import os
from os.path import abspath, dirname
import sys
from datetime import datetime
import zipfile
import zlib
from fabric.api import env, put, local, settings, hide
from fabric.context_managers import lcd
from fabric.decorators ... |
bucket = _config['deploy'][env_type]['bucket']
warn('YOU ARE ABOUT TO DELETE EVERYTHING IN %s' % bucket)
if not do(prompt("Are you ABSOLUTELY sure you want to do this? (y/n): ").strip()):
abort('Aborting.')
with lcd(env.sites_path):
local('fablib/bin/s3cmd --c... | abort('Could not find "bucket" in deploy.%s" in config file' % env_type) | conditional_block |
__init__.py | """
Deployment management for KnightLab web application projects.
Read the README.
"""
import os
from os.path import abspath, dirname
import sys
from datetime import datetime
import zipfile
import zlib
from fabric.api import env, put, local, settings, hide
from fabric.context_managers import lcd
from fabric.decorators ... |
@task
def stage():
"""Build/commit/tag/push lib version, copy to local cdn repo"""
_setup_env()
if not 'stage' in _config:
abort('Could not find "stage" in config file')
# Make sure cdn exists
exists(dirname(env.cdn_path), required=True)
# Ask us... | """Build lib version"""
_setup_env()
# Get build config
if not 'build' in _config:
abort('Could not find "build" in config file')
# Check version
if not 'version' in _config:
_config['version'] = datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S')
... | identifier_body |
__init__.py | """
Deployment management for KnightLab web application projects.
Read the README.
"""
import os
from os.path import abspath, dirname
import sys
from datetime import datetime
import zipfile
import zlib
from fabric.api import env, put, local, settings, hide
from fabric.context_managers import lcd
from fabric.decorators ... | (env_type):
"""Delete website from S3 bucket. Specify stg|prd as argument."""
_setup_env()
# Activate local virtual environment (for render_templates+flask?)
local('. %s' % env.activate_path)
if not os.path.exists(env.s3cmd_cfg):
abort("Could not find 's3cmd.cfg' r... | undeploy | identifier_name |
__init__.py | """
Deployment management for KnightLab web application projects.
Read the README.
"""
import os
from os.path import abspath, dirname
import sys
from datetime import datetime
import zipfile
import zlib
from fabric.api import env, put, local, settings, hide
from fabric.context_managers import lcd
from fabric.decorators ... | ############################################################
# Static websites deployed to S3
############################################################
if _config and 'deploy' in _config:
@task
def undeploy(env_type):
"""Delete website from S3 bucket. Specify stg|prd as argument."""
_setup_... | random_line_split | |
secp256k1_recover.rs | //! Public key recovery from [secp256k1] ECDSA signatures.
//!
//! [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
//!
//! _This module provides low-level cryptographic building blocks that must be
//! used carefully to ensure proper security. Read this documentation and
//! accompanying links thoroughly._
//!
//! Th... | /// client.send_and_confirm_transaction(&tx)?;
///
/// Ok(())
/// }
/// ```
pub fn secp256k1_recover(
hash: &[u8],
recovery_id: u8,
signature: &[u8],
) -> Result<Secp256k1Pubkey, Secp256k1RecoverError> {
#[cfg(target_os = "solana")]
{
let mut pubkey_buffer = [0u8; SECP256K1_PUBLIC_KE... | /// | random_line_split |
secp256k1_recover.rs | //! Public key recovery from [secp256k1] ECDSA signatures.
//!
//! [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
//!
//! _This module provides low-level cryptographic building blocks that must be
//! used carefully to ensure proper security. Read this documentation and
//! accompanying links thoroughly._
//!
//! Th... | (
hash: &[u8],
recovery_id: u8,
signature: &[u8],
) -> Result<Secp256k1Pubkey, Secp256k1RecoverError> {
#[cfg(target_os = "solana")]
{
let mut pubkey_buffer = [0u8; SECP256K1_PUBLIC_KEY_LENGTH];
let result = unsafe {
crate::syscalls::sol_secp256k1_recover(
... | secp256k1_recover | identifier_name |
secp256k1_recover.rs | //! Public key recovery from [secp256k1] ECDSA signatures.
//!
//! [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
//!
//! _This module provides low-level cryptographic building blocks that must be
//! used carefully to ensure proper security. Read this documentation and
//! accompanying links thoroughly._
//!
//! Th... |
pub fn to_bytes(self) -> [u8; 64] {
self.0
}
}
/// Recover the public key from a [secp256k1] ECDSA signature and
/// cryptographically-hashed message.
///
/// [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
///
/// This function is specifically intended for efficiently implementing
/// Ethereum's [... | {
Self(
<[u8; SECP256K1_PUBLIC_KEY_LENGTH]>::try_from(<&[u8]>::clone(&pubkey_vec))
.expect("Slice must be the same length as a Pubkey"),
)
} | identifier_body |
VismoController.js | /*requires VismoShapes
Adds controls such as panning and zooming to a given dom element.
Mousewheel zooming currently not working as should - should center on location where mousewheel occurs
Will be changed to take a handler parameter rather then a targetjs
*/
var VismoController = function(elem,options){ //elem m... |
var el = e.target;
//var el = e.srcElement;
if(!el) return;
while(el != element){
if(el == element) {
onmousewheel(e);
... | var element = this.wrapper;
if(VismoUtils.browser.isIE) {
document.onmousewheel = function(e){
if(!e)e = window.event; | random_line_split |
VismoController.js | /*requires VismoShapes
Adds controls such as panning and zooming to a given dom element.
Mousewheel zooming currently not working as should - should center on location where mousewheel occurs
Will be changed to take a handler parameter rather then a targetjs
*/
var VismoController = function(elem,options){ //elem m... |
if(!VismoUtils.browser.isIE && !jQuery(that.wrapper).hasClass("panning")){
jQuery(that.wrapper).addClass("panning")
}
if(!that.goodToTransform(e)) {return;}
var pos = VismoClickingUtils.getMouseFromEventRelativeToElement(e,panning_status.clickpos.x,panning_status.clickpos.y,panning_status.elem);
... | {
return;
} | conditional_block |
model.py | """
Model is a wrapper over a set of KERAS models!
implements interface for learning over a generator + dataset or statically generated data
and for prediction (for all classes)
"""
import os
import cv2
import json
import keras
import rasterio
import numpy as np
from keras.utils import generic_utils
from keras.model... |
def _find_weights(weights_dir, mode='last'):
"""Find weights path if not provided manually during model initialization"""
if mode == 'last':
file_name = sorted(os.listdir(weights_dir))[-1]
weights_path = os.path.join(weights_dir, file_name)
elif mode == 'best':
raise NotImplemen... | path = os.path.join(*args)
if not os.path.exists(path):
os.makedirs(path)
return path | identifier_body |
model.py | """
Model is a wrapper over a set of KERAS models!
implements interface for learning over a generator + dataset or statically generated data
and for prediction (for all classes)
"""
import os
import cv2
import json
import keras
import rasterio
import numpy as np
from keras.utils import generic_utils
from keras.model... | (self, image, path, save_postfix='pred', geotransform=None, trg_crs='epsg:3857',
threshold=170):
image, shape = self._to_binary_masks(image, geotransform)
path = os.path.normpath(path) # delete '\' or '//' in the end of filepath
if not os.path.exists(path):
... | _save_vector_masks | identifier_name |
model.py | """
Model is a wrapper over a set of KERAS models!
implements interface for learning over a generator + dataset or statically generated data
and for prediction (for all classes)
"""
import os
import cv2
import json
import keras
import rasterio
import numpy as np
from keras.utils import generic_utils
from keras.model... | from .standardizer import Standardizer
def _create_dir(*args):
path = os.path.join(*args)
if not os.path.exists(path):
os.makedirs(path)
return path
def _find_weights(weights_dir, mode='last'):
"""Find weights path if not provided manually during model initialization"""
if mode == 'last... | from .config import OrthoSegmModelConfig | random_line_split |
model.py | """
Model is a wrapper over a set of KERAS models!
implements interface for learning over a generator + dataset or statically generated data
and for prediction (for all classes)
"""
import os
import cv2
import json
import keras
import rasterio
import numpy as np
from keras.utils import generic_utils
from keras.model... |
if mode == 'inference':
try:
model = keras.models.load_model(model_path, custom_objects=custom_objects, compile=False)
except:
model = keras.models.model_from_json(json.dumps(graph))
model.load_weights(weights_path)
segmentation_model = SegmentationModel(mod... | model = keras.models.load_model(model_path, custom_objects=custom_objects, compile=True) | conditional_block |
run_ERDCA.py | import sys,os
import data_processing as dp
import ecc_tools as tools
import timeit
# import pydca-ER module
import matplotlib
#matplotlib.use('agg')
import matplotlib.pyplot as plt
from pydca.erdca import erdca
from pydca.sequence_backmapper import sequence_backmapper
from pydca.msa_trimmer import msa_trimmer
from pyd... |
with open('DI/ER/er_DI_%s.pickle'%(pfam_id), 'wb') as f:
pickle.dump(erdca_DI, f)
f.close()
#---------------------------------------------------------------------------------------------------------------------#
plotting = False
if plotting:
# Print Details of protein PDB structure Info for co... | print(site_pair, score) | conditional_block |
run_ERDCA.py | import sys,os
import data_processing as dp
import ecc_tools as tools
import timeit
# import pydca-ER module
import matplotlib
#matplotlib.use('agg')
import matplotlib.pyplot as plt
from pydca.erdca import erdca
from pydca.sequence_backmapper import sequence_backmapper
from pydca.msa_trimmer import msa_trimmer
from pyd... | print(preprocessed_data_outfile)
print('\n\nPre-Processing MSA with Range PP Seq\n\n')
trimmer = msa_trimmer.MSATrimmer(
erdca_msa_file, biomolecule='PROTEIN',
refseq_file = erdca_ref_file
)
pfam_dict['ref_file'] = erdca_ref_file
try:
preprocessed_data,s_index, cols_removed,s_ipdb,s = trimmer.get_preprocess... | #---------------------------------- PreProcess FASTA Alignment -------------------------------------------------------#
#---------------------------------------------------------------------------------------------------------------------#
preprocessed_data_outfile = preprocess_path+'MSA_%s_PreP... | random_line_split |
buffer.rs | //! Buffer implementation like Bytes / BytesMut.
//!
//! It is simpler and contains less unsafe code.
use std::default::Default;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::slice;
use std::task::{Context, Poll};
use t... |
/// Add a string to the buffer.
#[inline]
pub fn put_str(&mut self, s: impl AsRef<str>) {
self.extend_from_slice(s.as_ref().as_bytes());
}
/// Return a reference to this Buffer as an UTF-8 string.
#[inline]
pub fn as_utf8_str(&self) -> Result<&str, std::str::Utf8Error> {
s... | {
self.extend_from_slice(s.as_bytes());
} | identifier_body |
buffer.rs | //! Buffer implementation like Bytes / BytesMut.
//!
//! It is simpler and contains less unsafe code.
use std::default::Default;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::slice;
use std::task::{Context, Poll};
use t... |
#[test]
fn test_buffer() {
let mut b = Buffer::new();
b.reserve(4096);
b.start_offset = 23;
b.data.resize(b.start_offset, 0);
for _ in 0..50000 {
b.put_str("xyzzyxyzzy");
}
assert!(b.len() == 500000);
assert!(&b[1000..1010] == &b"xyzzy... | #[cfg(test)]
mod tests {
use super::*; | random_line_split |
buffer.rs | //! Buffer implementation like Bytes / BytesMut.
//!
//! It is simpler and contains less unsafe code.
use std::default::Default;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::slice;
use std::task::{Context, Poll};
use t... | (&mut self, size: usize) {
if size == 0 {
self.clear();
return;
}
if size > self.len() {
panic!("Buffer::truncate(size): size > self.len()");
}
if self.rd_pos > size {
self.rd_pos = size;
}
self.data.truncate(size + ... | truncate | identifier_name |
buffer.rs | //! Buffer implementation like Bytes / BytesMut.
//!
//! It is simpler and contains less unsafe code.
use std::default::Default;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::slice;
use std::task::{Context, Poll};
use t... |
}
#[inline]
fn chunk(&self) -> &[u8] {
self.bytes()
}
#[inline]
fn remaining(&self) -> usize {
self.len() - self.rd_pos
}
}
impl Deref for Buffer {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
self.bytes()
}
}
impl DerefMut for Buffer... | {
// "It is recommended for implementations of advance to
// panic if cnt > self.remaining()"
panic!("read position advanced beyond end of buffer");
} | conditional_block |
udp.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{fastboot::InterfaceFactory, target::Target},
anyhow::{anyhow, bail, Context as _, Result},
async_io::Async,
async_net::UdpSoc... |
if let Some(ref mut task) = self.write_task {
match task.as_mut().poll(cx) {
Poll::Ready(Ok(s)) => {
self.write_task = None;
for _i in 0..s {
self.sequence += Wrapping(1u16);
}
P... | {
// TODO(fxb/78975): unfortunately the Task requires the 'static lifetime so we have to
// copy the bytes and move them into the async block.
let packets = self.create_fastboot_packets(buf).map_err(|e| {
std::io::Error::new(
ErrorKind::Other,
... | conditional_block |
udp.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{fastboot::InterfaceFactory, target::Target},
anyhow::{anyhow, bail, Context as _, Result},
async_io::Async,
async_net::UdpSoc... | format!("Could not create fastboot packets: {}", e),
)
})?;
let socket = self.socket.clone();
self.write_task.replace(Box::pin(async move {
for packet in &packets {
let (out_buf, sz) = send_to_device(&packet, &so... | // TODO(fxb/78975): unfortunately the Task requires the 'static lifetime so we have to
// copy the bytes and move them into the async block.
let packets = self.create_fastboot_packets(buf).map_err(|e| {
std::io::Error::new(
ErrorKind::Other, | random_line_split |
udp.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{fastboot::InterfaceFactory, target::Target},
anyhow::{anyhow, bail, Context as _, Result},
async_io::Async,
async_net::UdpSoc... | (sequence: u16) -> [u8; 8] {
let mut packet = [0u8; 8];
packet[0] = 0x02;
packet[1] = 0x00;
BigEndian::write_u16(&mut packet[2..4], sequence);
BigEndian::write_u16(&mut packet[4..6], 1);
BigEndian::write_u16(&mut packet[6..8], MAX_SIZE);
packet
}
fn make_empty_fastboot_packet(sequence: u16)... | make_init_packet | identifier_name |
udp.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{fastboot::InterfaceFactory, target::Target},
anyhow::{anyhow, bail, Context as _, Result},
async_io::Async,
async_net::UdpSoc... |
async fn make_sender_socket(addr: SocketAddr) -> Result<UdpSocket> {
let socket: std::net::UdpSocket = match addr {
SocketAddr::V4(ref _saddr) => socket2::Socket::new(
socket2::Domain::IPV4,
socket2::Type::DGRAM,
Some(socket2::Protocol::UDP),
)
.context(... | {
let mut buf = [0u8; 1500]; // Responses should never get this big.
timeout(REPLY_TIMEOUT, Box::pin(socket.recv(&mut buf[..])))
.await
.map_err(|_| anyhow!("Timed out waiting for reply"))?
.map_err(|e| anyhow!("Recv error: {}", e))
.map(|size| (buf, size))
} | identifier_body |
plate.ts | import * as THREE from "three";
import getGrid from "./grid";
import config from "../config";
import PlateBase from "./plate-base";
import Subplate, { ISerializedSubplate } from "./subplate";
import Field, { IFieldOptions, ISerializedField } from "./field";
import { IMatrix3Array, IQuaternionArray, IVec3Array } from ".... |
addFieldAt(props: Omit<IFieldOptions, "id" | "plate">, absolutePos: THREE.Vector3) {
const localPos = this.localPosition(absolutePos);
const id = getGrid().nearestFieldId(localPos);
if (!this.fields.has(id)) {
return this.addField({ ...props, id });
}
}
addExistingField(field: Field) {
... | {
const field = new Field({ ...props, plate: this });
this.addExistingField(field);
return field;
} | identifier_body |
plate.ts | import * as THREE from "three";
import getGrid from "./grid";
import config from "../config";
import PlateBase from "./plate-base";
import Subplate, { ISerializedSubplate } from "./subplate";
import Field, { IFieldOptions, ISerializedField } from "./field";
import { IMatrix3Array, IQuaternionArray, IVec3Array } from ".... | }
setHotSpot(position: THREE.Vector3, force: THREE.Vector3) {
this.hotSpot = { position, force };
}
setDensity(density: number) {
this.density = density;
}
removeUnnecessaryFields() {
this.fields.forEach((f: Field) => {
if (!f.alive) {
this.deleteField(f.id);
}
});
}... | const len = this.hotSpot.force.length();
if (len > 0) {
this.hotSpot.force.setLength(Math.max(0, len - timestep * HOT_SPOT_TORQUE_DECREASE));
} | random_line_split |
plate.ts | import * as THREE from "three";
import getGrid from "./grid";
import config from "../config";
import PlateBase from "./plate-base";
import Subplate, { ISerializedSubplate } from "./subplate";
import Field, { IFieldOptions, ISerializedField } from "./field";
import { IMatrix3Array, IQuaternionArray, IVec3Array } from ".... | (id: number) {
const field = this.fields.get(id);
if (!field) {
return;
}
this.fields.delete(id);
this.subplate.deleteField(id);
this.addAdjacentField(id);
field.adjacentFields.forEach((adjFieldId: number) => {
let adjField = this.adjacentFields.get(adjFieldId);
if (adjFiel... | deleteField | identifier_name |
plate.ts | import * as THREE from "three";
import getGrid from "./grid";
import config from "../config";
import PlateBase from "./plate-base";
import Subplate, { ISerializedSubplate } from "./subplate";
import Field, { IFieldOptions, ISerializedField } from "./field";
import { IMatrix3Array, IQuaternionArray, IVec3Array } from ".... |
});
}
});
while (queue.length > 0) {
const field = queue.shift() as Field;
field.isContinentBuffer = true;
const newDist = getDist(field) + grid.fieldDiameterInKm;
if (newDist < config.continentBufferWidth) {
field.forEachNeighbor((adjField: Field) => {
i... | {
dist[adjField.id] = grid.fieldDiameterInKm;
queue.push(adjField);
} | conditional_block |
utils.py | """Utilities. Mostly periodic checks. Everything that is neither core nor gui
contents (for use):
- run() -- call once on startup. takes care of all automatic tasks
- send_email() -- send an email
- get_name() -- get a pretty name
- get_book_data() -- attempt to get data about a book based on the ISBN ... |
def get_book_data(isbn: int):
"""Attempt to get book data via the ISBN from the DB, if that fails,
try the DNB (https://portal.dnb.de)"""
try:
book = next(iter(core.Book.search(('isbn', 'eq', isbn))))
except StopIteration:
pass # actually, I could put the whole rest of the functio... | random_line_split | |
utils.py | """Utilities. Mostly periodic checks. Everything that is neither core nor gui
contents (for use):
- run() -- call once on startup. takes care of all automatic tasks
- send_email() -- send an email
- get_name() -- get a pretty name
- get_book_data() -- attempt to get data about a book based on the ISBN ... | ():
"""get the encrypted contents of the database file"""
if fernet is None:
raise RuntimeError('encryption requested, but no cryptography available')
with open(config.core.database_name, 'rb') as f:
plain = f.read()
key = base64.urlsafe_b64encode(config.utils.tasks.secret_key)
ciphe... | get_encrypted_database | identifier_name |
utils.py | """Utilities. Mostly periodic checks. Everything that is neither core nor gui
contents (for use):
- run() -- call once on startup. takes care of all automatic tasks
- send_email() -- send an email
- get_name() -- get a pretty name
- get_book_data() -- attempt to get data about a book based on the ISBN ... |
def late_books():
"""Check for late and nearly late books.
Call the functions in late_handlers with arguments (late, warn).
late and warn are sequences of core.Borrow instances.
"""
late = []
warn = []
today = date.today()
for b in core.Borrow.search((
('is_back', 'eq', F... | """Run stuff to do as specified by times set in config"""
while True:
if datetime.now() > core.misc_data.check_date+timedelta(minutes=45):
for stuff in stuff_to_do:
threading.Thread(target=stuff).start()
core.misc_data.check_date = datetime.now() + config.utils.tasks.... | identifier_body |
utils.py | """Utilities. Mostly periodic checks. Everything that is neither core nor gui
contents (for use):
- run() -- call once on startup. takes care of all automatic tasks
- send_email() -- send an email
- get_name() -- get a pretty name
- get_book_data() -- attempt to get data about a book based on the ISBN ... |
elif td[0] == 'Verlag':
results['publisher'] = td[1].split(':')[1].strip()
elif td[0] == 'Zeitliche Einordnung':
results['year'] = td[1].split(':')[1].strip()
elif td[0] == 'Sprache(n)':
results['language'] = td[1].split(',')[0].split(... | for p in td[1].split('\n'):
g = person_re.search(p)
if g is None:
continue
g = g.groups()
if g[1] == 'Verfasser':
results['author'] = g[0]
else:
res... | conditional_block |
peer_connection.rs | // Copyright 2019, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... |
#[cfg(feature = "rpc")]
#[tracing::instrument("peer_connection::connect_rpc", level="trace", skip(self), fields(peer_node_id = self.peer_node_id.to_string().as_str()))]
pub async fn connect_rpc<T>(&mut self) -> Result<T, RpcError>
where T: From<RpcClient> + NamedProtocolService {
self.connect_... | {
let substream = self.open_substream(protocol_id).await?;
Ok(framing::canonical(substream.stream, max_frame_size))
} | identifier_body |
peer_connection.rs | // Copyright 2019, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... | ,
Disconnect(silent, reply_tx) => {
debug!(
target: LOG_TARGET,
"[{}] Disconnect{}requested for {} connection to peer '{}'",
self,
if silent { " (silent) " } else { " " },
self.direction,
... | {
let tracing_id = tracing::Span::current().id();
let span = span!(Level::TRACE, "handle_request");
span.follows_from(tracing_id);
let result = self.open_negotiated_protocol_stream(protocol_id).instrument(span).await;
log_if_error_fmt!(
... | conditional_block |
peer_connection.rs | // Copyright 2019, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... | (&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
f,
"Id: {}, Node ID: {}, Direction: {}, Peer Address: {}, Age: {:.0?}, #Substreams: {}, #Refs: {}",
self.id,
self.peer_node_id.short_str(),
self.direction,
self.address... | fmt | identifier_name |
peer_connection.rs | // Copyright 2019, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... | address: Arc<Multiaddr>,
direction: ConnectionDirection,
started_at: Instant,
substream_counter: AtomicRefCounter,
handle_counter: Arc<()>,
peer_identity_claim: Option<PeerIdentityClaim>,
}
impl PeerConnection {
pub(crate) fn new(
id: ConnectionId,
request_tx: mpsc::Sender<P... | peer_features: PeerFeatures,
request_tx: mpsc::Sender<PeerConnectionRequest>, | random_line_split |
web.js | //preload images
// $.ajaxSetup({
// timeout:200
// });
var vod = window.vod = {
selectedMedia:{},
mediaDisplayType:"popover",
searchXHR:null,
displayMedia:function(el, html){
//TODO: destroy any existing media
var media = $(".media");
var data = el.attr("media-data");
var type = el.attr("media-type").toLo... | });
$('body').on('click', '#search-more', function(){
var last = $("#search-content .media:last");
var id = last.attr('media-id');
vod.searchSince = id;
vod.filterSearch();
})
$('body').on('click', '#filter-container-elements li', function(){
var self = $(this);
var props = self.attr('filter-subprops');... | self.addClass("active"); | random_line_split |
web.js | //preload images
// $.ajaxSetup({
// timeout:200
// });
var vod = window.vod = {
selectedMedia:{},
mediaDisplayType:"popover",
searchXHR:null,
displayMedia:function(el, html){
//TODO: destroy any existing media
var media = $(".media");
var data = el.attr("media-data");
var type = el.attr("media-type").toLo... | else{
$("#listings-subpropfilter").html('');
}
setTimeout(window.vod.filterSearch,0);
})
$("body").on('keyup', '#finder', function(){
var t = window.vod.searchTime;
if(t){
window.clearTimeout(window.vod.searchTime);
}
window.vod.searchTime = setTimeout(function(){
var val = $("#finder").val();
... | {
props = JSON.parse(props);
var html = jade.render("listings-subpropfilter",{props:props});
var subprop = $("#listings-subpropfilter");
if(subprop.length){
subprop.html(html);
}else{
$("#sub-contents").prepend("<section id='listings-subpropfilter'>" + html + "</section>");
}
$("#listings-s... | conditional_block |
web.js | //preload images
// $.ajaxSetup({
// timeout:200
// });
var vod = window.vod = {
selectedMedia:{},
mediaDisplayType:"popover",
searchXHR:null,
displayMedia:function(el, html){
//TODO: destroy any existing media
var media = $(".media");
var data = el.attr("media-data");
var type = el.attr("media-type").toLo... | (){
$("#file-container").html('');
files_container.forEach(function(file, index){
var html = jade.render('file-container',{index:index, file:file.name||file.fileName, size:prettyBytes(file.size||file.fileSize)});
$("#file-container").append(html);
})
}
enquire.register("screen and (max-width:768px)", {
matc... | renderFiles | identifier_name |
web.js | //preload images
// $.ajaxSetup({
// timeout:200
// });
var vod = window.vod = {
selectedMedia:{},
mediaDisplayType:"popover",
searchXHR:null,
displayMedia:function(el, html){
//TODO: destroy any existing media
var media = $(".media");
var data = el.attr("media-data");
var type = el.attr("media-type").toLo... |
enquire.register("screen and (max-width:768px)", {
match:function(){
vod.mediaDisplayType = "tabpop";
console.log(vod)
},
unmatch:function(){
vod.mediaDisplayType = "popover";
console.log(vod)
}
});
var socket = window.socket = io.connect();
| {
$("#file-container").html('');
files_container.forEach(function(file, index){
var html = jade.render('file-container',{index:index, file:file.name||file.fileName, size:prettyBytes(file.size||file.fileSize)});
$("#file-container").append(html);
})
} | identifier_body |
db_explorer.go | package main
import (
"net/http"
"net/url"
"database/sql"
"encoding/json"
"fmt"
"regexp"
"strings"
"strconv"
"io/ioutil"
"sort"
)
type Handler struct {
DB *sql.DB
tables map[string]Table
}
var (
entriesPattern = regexp.MustCompile(`^\/[^\/]+\/?$`)
entryPattern = regexp.MustCompile(`^\/[^\/]+\/.+`)
... | // skip unknown fields
fields = append(fields, field.Name)
invalidTypeMessage := "field " + field.Name + " have invalid type"
// update auto increment field does not allowed
if field.AutoIncrement {
errorResponse(http.StatusBadRequest, invalidTypeMessage, w)
return
}
switch {
case value == nil && ... | { continue } | conditional_block |
db_explorer.go | package main
import (
"net/http"
"net/url"
"database/sql"
"encoding/json"
"fmt"
"regexp"
"strings"
"strconv"
"io/ioutil"
"sort"
)
type Handler struct {
DB *sql.DB
tables map[string]Table
}
var (
entriesPattern = regexp.MustCompile(`^\/[^\/]+\/?$`)
entryPattern = regexp.MustCompile(`^\/[^\/]+\/.+`)
... |
func (h *Handler) Edit(w http.ResponseWriter, r *http.Request) {
table, err := getTable(r, h)
if err != nil {
errorResponse(http.StatusBadRequest, err.Error(), w)
return
}
key, err := getKey(r)
if err != nil {
errorResponse(http.StatusBadRequest, err.Error(), w)
return
}
body, err := ioutil.ReadAll(r.... | {
table, err := getTable(r, h)
if err != nil {
errorResponse(http.StatusBadRequest, err.Error(), w)
return
}
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
errorResponse(http.StatusBadRequest, err.Error(), w)
return
}
var params map[string]interface{}
err = json.Unmarshal(... | identifier_body |
db_explorer.go | package main
import (
"net/http"
"net/url"
"database/sql"
"encoding/json"
"fmt"
"regexp"
"strings"
"strconv"
"io/ioutil"
"sort"
)
type Handler struct {
DB *sql.DB
tables map[string]Table
}
var (
entriesPattern = regexp.MustCompile(`^\/[^\/]+\/?$`)
entryPattern = regexp.MustCompile(`^\/[^\/]+\/.+`)
... | return
}
defer rows.Close()
result, err := parseResponse(rows, table)
if err != nil {
InternalServerError(err, w)
return
}
if len(result) == 0 {
errorResponse(http.StatusNotFound, "record not found", w)
return
}
successResponse(http.StatusOK, map[string]interface{}{"record": result[0]}, w)
}
f... | random_line_split | |
db_explorer.go | package main
import (
"net/http"
"net/url"
"database/sql"
"encoding/json"
"fmt"
"regexp"
"strings"
"strconv"
"io/ioutil"
"sort"
)
type Handler struct {
DB *sql.DB
tables map[string]Table
}
var (
entriesPattern = regexp.MustCompile(`^\/[^\/]+\/?$`)
entryPattern = regexp.MustCompile(`^\/[^\/]+\/.+`)
... | (w http.ResponseWriter, r *http.Request) {
table, err := getTable(r, h)
if err != nil {
errorResponse(http.StatusBadRequest, err.Error(), w)
return
}
id, err := getKey(r)
if err != nil {
errorResponse(http.StatusBadRequest, err.Error(), w)
return
}
res, err := h.DB.Exec("DELETE FROM " + table.Name + "... | Delete | identifier_name |
DQN_1.py | import numpy as np
import pandas as pd
import time
import tkinter as tk
import tensorflow.compat.v1 as tf
'''
4*4 的迷宫:
---------------------------
| 入口 | | | |
---------------------------
| | | 陷阱 | |
---------------------------
| | 陷阱 | 终点 | |
---------------------------
| ... | leep(0.01)
self.update()
np.random.seed(1)
tf.set_random_seed(1)
class DeepQNetwork:
# 建立神经网络
def _build_net(self):
# -------------- 创建 eval 神经网络, 及时提升参数 --------------
tf.compat.v1.disable_eager_execution()
self.s = tf.placeholder(tf.float32, [None, self.n_features], name='s... | time.s | identifier_name |
DQN_1.py | import numpy as np
import pandas as pd
import time
import tkinter as tk
import tensorflow.compat.v1 as tf
'''
4*4 的迷宫:
---------------------------
| 入口 | | | |
---------------------------
| | | 陷阱 | |
---------------------------
| | 陷阱 | 终点 | |
---------------------------
| ... | ve(self.rect, base_action[0], base_action[1]) # move agent
next_coords = self.canvas.coords(self.rect) # next state
# reward function
if next_coords == self.canvas.coords(self.oval):
reward = 1
done = True
elif next_coords in [self.canvas.coords(self.hell1)]:
... | self.canvas.mo | conditional_block |
DQN_1.py | import numpy as np
import pandas as pd
import time
import tkinter as tk
import tensorflow.compat.v1 as tf
'''
4*4 的迷宫:
---------------------------
| 入口 | | | |
---------------------------
| | | 陷阱 | |
---------------------------
| | 陷阱 | 终点 | |
---------------------------
| ... | lf):
self.canvas = tk.Canvas(self, bg='white',
height=MAZE_H * UNIT,
width=MAZE_W * UNIT)
# create grids
for c in range(0, MAZE_W * UNIT, UNIT):
x0, y0, x1, y1 = c, 0, c, MAZE_H * UNIT
self.canvas.create_lin... | __()
self.action_space = ['u', 'd', 'l', 'r']
self.n_actions = len(self.action_space)
self.n_features = 2
self.title('maze')
self.geometry('{0}x{1}'.format(MAZE_H * UNIT, MAZE_H * UNIT))
self._build_maze()
def _build_maze(se | identifier_body |
DQN_1.py | import numpy as np
import pandas as pd
import time
import tkinter as tk
import tensorflow.compat.v1 as tf
'''
4*4 的迷宫:
---------------------------
| 入口 | | | |
---------------------------
| | | 陷阱 | |
---------------------------
| | 陷阱 | 终点 | |
---------------------------
| ... | plt.plot(np.arange(len(self.cost_his)), self.cost_his)
plt.ylabel('Cost')
plt.xlabel('training steps')
plt.show()
def run_maze():
step = 0 # 用来控制什么时候学习
for episode in range(300):
# 初始化环境
observation = env.reset()
while True:
# 刷新环境
... | self.learn_step_counter += 1
def plot_cost(self):
import matplotlib.pyplot as plt | random_line_split |
utils.py | import datetime
import time
import logging
import dropbox
import json
import StringIO
import hashlib
import os
import re
import cProfile
from jose import jws
from dropbox.rest import ErrorResponse
from django.contrib import messages
from django.conf import settings
from django.core.exceptions import ImproperlyConfigu... |
class NoBasesFound(Exception):
pass
logger = logging.getLogger(__name__)
class Connection(object):
def __init__(self, dropbox_access_token):
self.client = dropbox.client.DropboxClient(dropbox_access_token)
super(Connection, self).__init__()
def info(self):
account_info = sel... | pass | identifier_body |
utils.py | import datetime
import time
import logging
import dropbox
import json
import StringIO
import hashlib
import os
import re
import cProfile
from jose import jws
from dropbox.rest import ErrorResponse
from django.contrib import messages
from django.conf import settings
from django.core.exceptions import ImproperlyConfigu... | (code, name):
errors = []
class CustomMessage(object):
pass
reporter = modReporter._makeDefaultReporter()
try:
tree = compile(code, name, "exec", _ast.PyCF_ONLY_AST)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = ... | check_code | identifier_name |
utils.py | import datetime
import time
import logging
import dropbox
import json
import StringIO
import hashlib
import os
import re
import cProfile
from jose import jws
from dropbox.rest import ErrorResponse
from django.contrib import messages
from django.conf import settings
from django.core.exceptions import ImproperlyConfigu... | logger.debug("Read JWT with secret %s" % secret)
logger.debug("Payload: %s" % payload)
decoded_dict = json.loads(jws.verify(payload, secret, algorithms=['HS256']))
logger.info("Identity: %s" % decoded_dict)
# print decoded_dict
# print type(decoded_dict)
username = decoded_dict.get('username... | return token
def read_jwt(payload, secret): | random_line_split |
utils.py | import datetime
import time
import logging
import dropbox
import json
import StringIO
import hashlib
import os
import re
import cProfile
from jose import jws
from dropbox.rest import ErrorResponse
from django.contrib import messages
from django.conf import settings
from django.core.exceptions import ImproperlyConfigu... |
if not os.path.exists(fq_file):
f = open(fq_file, 'w')
f.write(content)
f.close()
if sys.platform == "darwin":
os.popen4("echo $(cat %s) > %s" % (fq_file, fq_file))
else:
os.popen4("echo -e $(cat %s) > %s" % (fq_file, fq_file))
return fq_file
de... | os.mkdir(path) | conditional_block |
courses.py | """
quartzscrapers.scrapers.courses.courses
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains the classes for the worker threads, mangement of worker
threads, and scrapers for course data.
"""
import re
from queue import Queue
from threading import Thread
from collections import OrderedDict
# Adds chromed... | (func):
"""Execute Selenium task and retry upon failure."""
retries = 0
while retries < 3:
try:
return func()
except Exception as ex:
self.logger.error(
'Selenium error #%s: %s', retries ... | run_selenium_routine | identifier_name |
courses.py | """
quartzscrapers.scrapers.courses.courses
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains the classes for the worker threads, mangement of worker
threads, and scrapers for course data.
"""
import re
from queue import Queue
from threading import Thread
from collections import OrderedDict
# Adds chromed... |
def filter_description(soup):
"""Filter description for the course description text only."""
# TODO: Filter different text sections from description, such as
# 'NOTE', 'LEARNING HOURS', etc.
descr_raw = soup.find('span', id=regex_desc)
if not descr... | """Preprocess and reformat course name."""
course_title = soup.find('span', id=regex_title).text.strip()
name_idx = course_title.find('-')
dept_raw, course_code_raw = course_title[:name_idx - 1].split(' ')
course_name = course_title[name_idx + 1:].strip()
de... | identifier_body |
courses.py | """
quartzscrapers.scrapers.courses.courses
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains the classes for the worker threads, mangement of worker
threads, and scrapers for course data.
"""
import re
from queue import Queue
from threading import Thread
from collections import OrderedDict
# Adds chromed... | return descr_raw.text.encode('ascii', 'ignore').decode().strip()
def create_dict(rows, tag, tag_id=None, start=0, enroll=False):
"""Create dictionary out of BeautifulSoup objects.
Args:
rows: List of BeautifulSoup element tags.
tag: String of... | if descr_raw.find_all('br'):
return descr_raw.find_all('br')[0].previous_sibling
| random_line_split |
courses.py | """
quartzscrapers.scrapers.courses.courses
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains the classes for the worker threads, mangement of worker
threads, and scrapers for course data.
"""
import re
from queue import Queue
from threading import Thread
from collections import OrderedDict
# Adds chromed... |
self.logger.debug('Done course')
except Exception:
self.scraper.handle_error()
ic_action = {'ICAction': 'DERIVED_SAA_CRS_RETURN_PB$163$'}
self._request_page(ic_action)
def _login(self):
# Emulate a SOLUS login via a Selenium webdriver. Mainly used for... | try:
term_number = int(term['value'])
self.logger.debug('Starting term: %s (%s)',
term.text.strip(), term_number)
payload = {
'ICAction': 'DERIVED_SAA_CRS_SSR_PB_GO$3$',
... | conditional_block |
leetcodeFunc.go | package main
import (
"fmt"
"sort"
"strconv"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
445. 两数相加 II
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
nums := changeToNums(l1)
nums1 := changeToNums(l2)
fmt.Println(nums, nums1)
... | temp := nums[i] + jw
if jw > 0 {
jw--
}
if temp >= 10 {
temp = temp - 10
jw++
}
r = append(r, temp)
}
}
} else {
for i := 0; i < lg1; i++ {
if i < lg {
temp := nums[i] + nums1[i] + jw
if jw > 0 {
jw--
}
if temp >= 10 {
temp = temp - 10
j... | mp := nums[i] + nums1[i] + jw
if jw > 0 {
jw--
}
if temp >= 10 {
temp = temp - 10
jw++
}
r = append(r, temp)
} else {
| conditional_block |
leetcodeFunc.go | package main
import (
"fmt"
"sort"
"strconv"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
445. 两数相加 II
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
nums := changeToNums(l1)
nums1 := changeToNums(l2)
fmt.Println(nums, nums1)
... | 最大二叉树 II
*/
func insertIntoMaxTree(root *TreeNode, val int) *TreeNode {
//right 为空返回 新增又树
if root == nil {
return &TreeNode{
Val: val,
Left: nil,
Right: nil,
}
}
//节点大于树,原树入左侧 ,节点做根
if root.Val < val {
return &TreeNode{
Val: val,
Left: root,
Right: nil,
}
}
root.Right = insertInt... | }
/*
998. | identifier_name |
leetcodeFunc.go | package main
import (
"fmt"
"sort"
"strconv"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
445. 两数相加 II
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
nums := changeToNums(l1)
nums1 := changeToNums(l2)
fmt.Println(nums, nums1)
... | arget 的比较
d := presum + value*k - target
if d >= 0 {
//fmt.Println(d,value,endLen,index)
// c小于等于0.5那么取小 大于0.5 去取上值
c := value - (d+k/2)/k
return c
}
presum += value
}
return arr[length-1]
}
/**
1052. 爱生气的书店老板
*/
func maxSatisfied(customers []int, grumpy []int, X int) int {
count := 0
//默认的值
... | presum := 0
endLen := length
for index, value := range arr {
k := endLen - index
// 条件 未改变的和 + 当前 value*剩余的项 与 t | identifier_body |
leetcodeFunc.go | package main
import (
"fmt"
"sort"
"strconv"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
445. 两数相加 II
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
nums := changeToNums(l1)
nums1 := changeToNums(l2)
fmt.Println(nums, nums1)
... | 1330. 翻转子数组得到最大的数组值
使用数轴表示
a-----b
c------d
差值为 |c-b|*2 所以需要 b 最小 c 最大 才能获得最大的值
*/
func maxValueAfterReverse(nums []int) int {
sum := 0
length := len(nums)
a := -100000 //区间小值
b := 100000 //区间大值
for i := 0; i < length-1; i++ {
sum += IntAbs(nums[i] - nums[i+1])
a = IntMax(a, IntMin(nums[i], nums[i+1]))
... | }
return count
}
/** | random_line_split |
types.go | /*
Copyright 2018 The Kubernetes Authors.
Copyright 2020 Authors of Arktos - file modified.
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 re... | EndpointController EndpointControllerConfiguration
// GarbageCollectorControllerConfiguration holds configuration for
// GarbageCollectorController related features.
GarbageCollectorController GarbageCollectorControllerConfiguration
// NamespaceControllerConfiguration holds configuration for NamespaceController
/... | random_line_split | |
html_tools.py | import fnmatch
import io, os, re
import yaml
def rewrite_outdir(out_dir, chapter_dirs, static_host):
build_dir = os.path.dirname(out_dir)
if static_host and not static_host.endswith('/'):
static_host += '/'
for path in _walk(build_dir):
rewrite_file_links(path, out_dir, chapter_dirs, stat... |
def recursive_rewrite_links(data_dict, path, root, link_elements, other_elements,
static_host, chapter_dirs, chapter_append, yaml_append, rst_src_path,
lang_key=False, lang=None):
'''Rewrite links in the string values inside the data_dict.'''
# YAML file may have a list or a dictionary in the... | with io.open(file_path, 'w', encoding='utf-8') as f:
f.write(content) | identifier_body |
html_tools.py | import fnmatch
import io, os, re
import yaml
def rewrite_outdir(out_dir, chapter_dirs, static_host):
build_dir = os.path.dirname(out_dir)
if static_host and not static_host.endswith('/'):
static_host += '/'
for path in _walk(build_dir):
rewrite_file_links(path, out_dir, chapter_dirs, stat... | (content, path, root, link_elements, other_elements,
static_host, chapter_dirs, chapter_append, yaml_append,
rst_src_path=None):
q1 = re.compile(r'^(\w+:|//|#)') # Starts with "https:", "//" or "#".
q2 = re.compile(r'^(' + '|'.join(chapter_dirs) + r')(/|\\)') # Starts wit... | rewrite_links | identifier_name |
html_tools.py | import fnmatch
import io, os, re
import yaml
def rewrite_outdir(out_dir, chapter_dirs, static_host):
build_dir = os.path.dirname(out_dir)
if static_host and not static_host.endswith('/'):
static_host += '/'
for path in _walk(build_dir):
rewrite_file_links(path, out_dir, chapter_dirs, stat... |
out += content[i:]
return out
def _walk(html_dir):
files = []
for root, dirnames, filenames in os.walk(html_dir):
for filename in fnmatch.filter(filenames, '*.html'):
files.append(os.path.join(root, filename))
for filename in fnmatch.filter(filenames, '*.yaml'):
... | random_line_split | |
html_tools.py | import fnmatch
import io, os, re
import yaml
def rewrite_outdir(out_dir, chapter_dirs, static_host):
build_dir = os.path.dirname(out_dir)
if static_host and not static_host.endswith('/'):
static_host += '/'
for path in _walk(build_dir):
rewrite_file_links(path, out_dir, chapter_dirs, stat... |
elif isinstance(val, str):
if isinstance(rst_src_path, dict):
lang_rst_src_path = rst_src_path.get(lang if lang else 'en')
else:
lang_rst_src_path = rst_src_path
data_dict[key] = rewrite_links(val, path, root, link_elem... | recursive_rewrite_links(val, path, root, link_elements,
other_elements, static_host, chapter_dirs, chapter_append,
yaml_append, rst_src_path, key.endswith('|i18n'), lang)
# lang_key: if key is, e.g., "title|i18n", then the val dict
# contains keys ... | conditional_block |
common.js | $( function() {
$( "#slider" ).slider();
} );
$(document).ready(function() {
$("body").css({
"opacity": "1",
"transition": "opacity 1s ease-in-out"
});
// faq scroll
faqNav.init();
fixObj.init();
scrollTo();
$(window).on("backstretch.show", function (e, instance, index... | forms.makeerrfield(name);
$("#error_mes").html(msg);
$('[name="'+name+'"]').after( $("#error_mes") );
$("#error_mes").fadeIn("slow");
},
validate: function() {
forms.prevalidate();
if( !$('[name="name"]').val() ) {
forms.showError('name', forms.error... | },
showError: function( name, msg ) { | random_line_split |
common.js |
$( function() {
$( "#slider" ).slider();
} );
$(document).ready(function() {
$("body").css({
"opacity": "1",
"transition": "opacity 1s ease-in-out"
});
// faq scroll
faqNav.init();
fixObj.init();
scrollTo();
$(window).on("backstretch.show", function (e, instance, i... |
function initMap(){
// text overlay proto
function TxtOverlay(pos, txt, cls, map) {
this.pos = pos;
this.txt_ = txt;
this.cls_ = cls;
this.map_ = map;
this.div_ = null;
this.setMap(map);
}
TxtOverlay.prototype = new google.maps.OverlayView();
TxtOverlay.prototype.onAdd = function(... | {
var data, scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
... | identifier_body |
common.js |
$( function() {
$( "#slider" ).slider();
} );
$(document).ready(function() {
$("body").css({
"opacity": "1",
"transition": "opacity 1s ease-in-out"
});
// faq scroll
faqNav.init();
fixObj.init();
scrollTo();
$(window).on("backstretch.show", function (e, instance, i... | ed_top").addClass("fixed_bottom");
} else {
obj.removeClass("fixed_top fixed_bottom").css({"top": 0});
}
if (w != undefined) {
obj.css({"width": w});
}
}
},
init: function(){
var isiPad = navigator.userAgent.match(/iPad/i) != null;
if(!isiPad){
$(window).on(... | if ($(window).scrollTop() >= this.maxTop) {
obj.removeClass("fix | conditional_block |
common.js |
$( function() {
$( "#slider" ).slider();
} );
$(document).ready(function() {
$("body").css({
"opacity": "1",
"transition": "opacity 1s ease-in-out"
});
// faq scroll
faqNav.init();
fixObj.init();
scrollTo();
$(window).on("backstretch.show", function (e, instance, i... | () {
var $section = $('.faq');
if( !$section.length ) return false;
var $i = $('.faq .list');
var $pointer = $('.list-indicator');
var s = getScroll();
var is_top = ($section.offset().top - s.top);
var faq_height = ($section.height() - 100);
var faq_nav_height = $i.height() ;
var f... | listIndicate | identifier_name |
dsm2dtm.py | """
dsm2dtm - Generate DTM (Digital Terrain Model) from DSM (Digital Surface Model)
Author: Naman Jain
naman.jain@btech2015.iitgn.ac.in
www.namanji.wixsite.com/naman/
"""
import os
import numpy as np
import rasterio
import argparse
try:
import gdal
except:
from osgeo import gdal
def downsamp... |
def extract_dtm(dsm_path, ground_dem_path, non_ground_dem_path, radius, terrain_slope):
"""
Generates a ground DEM and non-ground DEM raster from the input DSM raster.
Input:
dsm_path: {string} path to the DSM raster
radius: {int} Search radius of kernel in cells.
terrain_slope: {... | np_raster = np.array(gdal.Open(raster_path).ReadAsArray())
return np_raster[np_raster != ignore_value].mean() | identifier_body |
dsm2dtm.py | """
dsm2dtm - Generate DTM (Digital Terrain Model) from DSM (Digital Surface Model)
Author: Naman Jain
naman.jain@btech2015.iitgn.ac.in
www.namanji.wixsite.com/naman/
"""
import os
import numpy as np
import rasterio
import argparse
try:
import gdal
except:
from osgeo import gdal
def downsamp... | (dsm_path, temp_dir):
# check DSM resolution. Downsample if DSM is of very high resolution to save processing time.
x_res, y_res = get_raster_resolution(dsm_path) # resolutions are in meters
dsm_name = dsm_path.split("/")[-1].split(".")[0]
dsm_crs = get_raster_crs(dsm_path)
if dsm_crs != 4326:
... | get_res_and_downsample | identifier_name |
dsm2dtm.py | """
dsm2dtm - Generate DTM (Digital Terrain Model) from DSM (Digital Surface Model)
Author: Naman Jain
naman.jain@btech2015.iitgn.ac.in
www.namanji.wixsite.com/naman/
"""
import os
import numpy as np
import rasterio
import argparse
try:
import gdal
except:
from osgeo import gdal
def downsamp... |
return np_raster
def get_raster_crs(raster_path):
"""
Returns the CRS (Coordinate Reference System) of the raster
Input:
raster_path: {string} path to the source tif image
"""
raster = rasterio.open(raster_path)
return raster.crs
def get_raster_resolution(raster_path):
raste... | try:
np_raster[i, j] = no_data_value
except:
pass | conditional_block |
dsm2dtm.py | """
dsm2dtm - Generate DTM (Digital Terrain Model) from DSM (Digital Surface Model)
Author: Naman Jain
naman.jain@btech2015.iitgn.ac.in
www.namanji.wixsite.com/naman/
"""
import os
import numpy as np
import rasterio
import argparse
try:
import gdal
except:
from osgeo import gdal
def downsamp... | if x_res < 0.3 or y_res < 0.3:
target_res = 0.3 # downsample to this resolution (in meters)
downsampling_factor = target_res / gdal.Open(dsm_path).GetGeoTransform()[1]
downsampled_dsm_path = os.path.join(temp_dir, dsm_name + "_ds.tif")
# Dowmsampling DSM
... | dsm_crs = get_raster_crs(dsm_path)
if dsm_crs != 4326: | random_line_split |
lib.rs | //! Usage
//! -----
//!
//! For simple applications, use one of the utility functions `listen` and `connect`:
//!
//! `listen` accpets a string that represents a socket address and a Factory, see
//! [Architecture](#architecture).
//!
//! ```no_run
//! // A WebSocket echo server
//!
//! use ws::listen;
//!
//! listen("... |
}
result.map(|_| self)
}
/// Queue an outgoing connection on this WebSocket. This method may be called multiple times,
/// but the actuall connections will not be established until after `run` is called.
pub fn connect(&mut self, url: url::Url) -> Result<&mut WebSocket<F>> {
l... | {
return self.run()
} | conditional_block |
lib.rs | //! Usage
//! -----
//!
//! For simple applications, use one of the utility functions `listen` and `connect`:
//!
//! `listen` accpets a string that represents a socket address and a Factory, see
//! [Architecture](#architecture).
//!
//! ```no_run
//! // A WebSocket echo server
//!
//! use ws::listen;
//!
//! listen("... | <U, F, H>(url: U, factory: F) -> Result<()>
where
U: Borrow<str>,
F: FnMut(Sender) -> H,
H: Handler
{
let mut ws = try!(WebSocket::new(factory));
let parsed = try!(
url::Url::parse(url.borrow())
.map_err(|err| Error::new(
ErrorKind::Internal,
... | connect | identifier_name |
lib.rs | //! Usage
//! -----
//!
//! For simple applications, use one of the utility functions `listen` and `connect`:
//!
//! `listen` accpets a string that represents a socket address and a Factory, see
//! [Architecture](#architecture).
//!
//! ```no_run
//! // A WebSocket echo server
//!
//! use ws::listen;
//!
//! listen("... | let mut config = EventLoopConfig::new();
config.notify_capacity(max + 1000);
WebSocket::with_config(factory, config)
}
/// Create a new WebSocket with a Factory and use the event loop config to provide settings for
/// the event loop.
pub fn with_config(factory: F, config: Event... | where F: Factory
{
/// Create a new WebSocket using the given Factory to create handlers.
pub fn new(mut factory: F) -> Result<WebSocket<F>> {
let max = factory.settings().max_connections; | random_line_split |
index.ts | import { assert } from '@0x/assert';
import { schemas } from '@0x/json-schemas';
import {
AbiEncoder,
abiUtils,
BigNumber,
decodeBytesAsRevertError,
decodeThrownErrorAsRevertError,
providerUtils,
RevertError,
StringRevertError,
} from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wr... |
const abiEncodedArguments = abiEncoder.encode(functionArguments);
return abiEncodedArguments;
}
/// @dev Constructs a contract wrapper.
/// @param contractName Name of contract.
/// @param abi of the contract.
/// @param address of the deployed contract.
/// @param supportedProv... | {
throw new Error(`Undefined Method Input ABI`);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.