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 |
|---|---|---|---|---|
lib.rs | //! # Mime
//!
//! Mime is now Media Type, technically, but `Mime` is more immediately
//! understandable, so the main type here is `Mime`.
//!
//! ## What is Mime?
//!
//! Example mime string: `text/plain;charset=utf-8`
//!
//! ```rust
//! # #[macro_use] extern crate mime;
//! # fn main() {
//! let plain_text: mime::M... | mime!(Multipart/FormData; Boundary=("ABCDEFG")));
assert_eq!(Mime::from_str("multipart/form-data; charset=BASE64; boundary=ABCDEFG").unwrap(),
mime!(Multipart/FormData; Charset=("base64"), Boundary=("ABCDEFG")));
}
#[test]
fn test_get_param() {
let mime... | #[test]
fn test_case_sensitive_values() {
assert_eq!(Mime::from_str("multipart/form-data; boundary=ABCDEFG").unwrap(), | random_line_split |
lib.rs | //! # Mime
//!
//! Mime is now Media Type, technically, but `Mime` is more immediately
//! understandable, so the main type here is `Mime`.
//!
//! ## What is Mime?
//!
//! Example mime string: `text/plain;charset=utf-8`
//!
//! ```rust
//! # #[macro_use] extern crate mime;
//! # fn main() {
//! let plain_text: mime::M... | else if let TopLevel::Star = self.0 {
if let SubLevel::Star = self.1 {
let attrs = self.2.as_ref();
if attrs.len() == 0 {
return f.write_str("*/*");
}
}
}
// slower general purpose fmt
try!(fmt::Display... | {
if let SubLevel::Json = self.1 {
let attrs = self.2.as_ref();
if attrs.len() == 0 {
return f.write_str("application/json");
}
}
} | conditional_block |
lib.rs | //! # Mime
//!
//! Mime is now Media Type, technically, but `Mime` is more immediately
//! understandable, so the main type here is `Mime`.
//!
//! ## What is Mime?
//!
//! Example mime string: `text/plain;charset=utf-8`
//!
//! ```rust
//! # #[macro_use] extern crate mime;
//! # fn main() {
//! let plain_text: mime::M... | (c: char) -> bool {
if is_restricted_name_first_char(c) {
true
} else {
match c {
'!' |
'#' |
'$' |
'&' |
'-' |
'^' |
'.' |
'+' |
'_' => true,
_ => false
}
}
}
#[c... | is_restricted_name_char | identifier_name |
lib.rs | //! # Mime
//!
//! Mime is now Media Type, technically, but `Mime` is more immediately
//! understandable, so the main type here is `Mime`.
//!
//! ## What is Mime?
//!
//! Example mime string: `text/plain;charset=utf-8`
//!
//! ```rust
//! # #[macro_use] extern crate mime;
//! # fn main() {
//! let plain_text: mime::M... |
}
impl<P: AsRef<[Param]>> Mime<P> {
pub fn get_param<A: PartialEq<Attr>>(&self, attr: A) -> Option<&Value> {
self.2.as_ref().iter().find(|&&(ref name, _)| attr == *name).map(|&(_, ref value)| value)
}
}
impl FromStr for Mime {
type Err = ();
fn from_str(raw: &str) -> Result<Mime, ()> {
... | {
// It's much faster to write a single string, as opposed to push
// several parts through f.write_str(). So, check for the most common
// mime types, and fast track them.
if let TopLevel::Text = self.0 {
if let SubLevel::Plain = self.1 {
let attrs = self.2.a... | identifier_body |
utils.py | from __future__ import division
from time import sleep
import numpy as np
import pandas as pd
import numpy.ma as ma
import os
import h5py
"""
Module to define some useful util functions
"""
def removeIncompleteSamples(data):
""" Method to remove samples with missing views
PARAMETERS
----------
dat... | # QC checks
assert model.trained == True, "Model is not trained yet"
assert len(np.unique(view_names)) == len(view_names), 'View names must be unique'
assert len(np.unique(sample_names)) == len(sample_names), 'Sample names must be unique'
# Create output directory
if not os.path.isdir(os.path.d... | """
| random_line_split |
utils.py | from __future__ import division
from time import sleep
import numpy as np
import pandas as pd
import numpy.ma as ma
import os
import h5py
"""
Module to define some useful util functions
"""
def removeIncompleteSamples(data):
""" Method to remove samples with missing views
PARAMETERS
----------
dat... | (A,B):
""" Method to efficiently compute correlation coefficients between two matrices
PARMETERS
---------
A: np array
B: np array
"""
# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - A.mean(1)[:,None]
B_mB = B - B.mean(1)[:,None]
# Sum o... | corr | identifier_name |
utils.py | from __future__ import division
from time import sleep
import numpy as np
import pandas as pd
import numpy.ma as ma
import os
import h5py
"""
Module to define some useful util functions
"""
def removeIncompleteSamples(data):
""" Method to remove samples with missing views
PARAMETERS
----------
dat... |
def dotd(A, B, out=None):
"""Diagonal of :math:`\mathrm A\mathrm B^\intercal`.
If ``A`` is :math:`n\times p` and ``B`` is :math:`p\times n`, it is done in :math:`O(pn)`.
Args:
A (array_like): Left matrix.
B (array_like): Right matrix.
out (:class:`numpy.ndarray`, optional): copy re... | """ Method to load the data
PARAMETERS
----------
data_opts: dic
verbose: boolean
"""
print ("\n")
print ("#"*18)
print ("## Loading data ##")
print ("#"*18)
print ("\n")
sleep(1)
M = len(data_opts['input_files'])
Y = [None]*M
for m in range(M):
... | identifier_body |
utils.py | from __future__ import division
from time import sleep
import numpy as np
import pandas as pd
import numpy.ma as ma
import os
import h5py
"""
Module to define some useful util functions
"""
def removeIncompleteSamples(data):
""" Method to remove samples with missing views
PARAMETERS
----------
dat... |
data_filt = [None]*M
samples_to_keep = np.setdiff1d(range(N),samples_to_remove)
for m in range(M):
data_filt[m] = data[m].iloc[samples_to_keep]
return data_filt
def maskData(data, data_opts):
""" Method to mask values of the data,
It is mainly to test missing values and to evaluat... | print("A total of " + str(len(samples_to_remove)) + " sample(s) have at least a missing view and will be removed") | conditional_block |
list.js | //https://developers.google.com/places/javascript/
//https://developers.google.com/maps/documentation/javascript/places#placeid
// Link to google api-key for the MapP5 project
// https://console.developers.google.com/apis/credentials?project=mapp5-1232
// https://maps.googleapis.com/maps/api/place/radarsearch/json?l... | (geocoderSearchResult) {
return new Promise(function(resolve, reject) {
if (geocoderSearchResult.geometry.location) {
map.setCenter(geocoderSearchResult.geometry.location);
// Create a list and display all the results.
var cll = geocoderSearchResult.geometry.location.lat... | getBookstores | identifier_name |
list.js | //https://developers.google.com/places/javascript/
//https://developers.google.com/maps/documentation/javascript/places#placeid
// Link to google api-key for the MapP5 project
// https://console.developers.google.com/apis/credentials?project=mapp5-1232
// https://maps.googleapis.com/maps/api/place/radarsearch/json?l... |
var Venue = function() {
this.tips = '';
this.name = '';
this.venueUrl = '';
this.venuePhotoUrl = '';
this.rating = 0.0;
this.lat = 0;
this.lng = 0;
this.index = '';
this.marker = {};
this.displaySelection = function() {
if(!infowindow.isOpen){
//The infowind... | random_line_split | |
list.js | //https://developers.google.com/places/javascript/
//https://developers.google.com/maps/documentation/javascript/places#placeid
// Link to google api-key for the MapP5 project
// https://console.developers.google.com/apis/credentials?project=mapp5-1232
// https://maps.googleapis.com/maps/api/place/radarsearch/json?l... |
});
return marker;
}
var stopAnimation = function(marker) {
setTimeout(function() {
marker.setAnimation(null);
}, 1400);
};
// code attribution: https://github.com/mdn/promises-test/blob/gh-pages/index.html
/*
This function takes the result from the geocoder request and subit... | {
infowindow.close();
infowindow.setContent(self.content);
infowindow.open(self.map, this);
infowindow.isOpen = true;
} | conditional_block |
list.js | //https://developers.google.com/places/javascript/
//https://developers.google.com/maps/documentation/javascript/places#placeid
// Link to google api-key for the MapP5 project
// https://console.developers.google.com/apis/credentials?project=mapp5-1232
// https://maps.googleapis.com/maps/api/place/radarsearch/json?l... |
// This function sets up markes for points of interest and adds click handlers to all the markers.
function createMarker(frsqrItem) {
var content = "";
// The marker object ,
// - animation property set to DROP.
// - icon property is set to an icon from Templatic
var marker = new google.ma... | {
if (getBooksRequest.readyState === XMLHttpRequest.DONE) {
if (getBooksRequest.status === 200) {
var jsonResponse = JSON.parse(getBooksRequest.responseText);
var bkstr = []; // array, holds the frsqrItem object literal that is defined inside the loop below.
var frsqrBoo... | identifier_body |
shuf.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) cmdline evec seps rvec fdata
use clap::{crate_version, Arg, ArgAction, Command};
use memchr::memchr_ite... |
pub fn uu_app() -> Command {
Command::new(uucore::util_name())
.about(ABOUT)
.version(crate_version!())
.override_usage(format_usage(USAGE))
.infer_long_args(true)
.args_override_self(true)
.arg(
Arg::new(options::ECHO)
.short('e')
... | {
let args = args.collect_lossy();
let matches = uu_app().try_get_matches_from(args)?;
let mode = if let Some(args) = matches.get_many::<String>(options::ECHO) {
Mode::Echo(args.map(String::from).collect())
} else if let Some(range) = matches.get_one::<String>(options::INPUT_RANGE) {
m... | identifier_body |
shuf.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) cmdline evec seps rvec fdata
use clap::{crate_version, Arg, ArgAction, Command};
use memchr::memchr_ite... | (args: impl uucore::Args) -> UResult<()> {
let args = args.collect_lossy();
let matches = uu_app().try_get_matches_from(args)?;
let mode = if let Some(args) = matches.get_many::<String>(options::ECHO) {
Mode::Echo(args.map(String::from).collect())
} else if let Some(range) = matches.get_one::<... | uumain | identifier_name |
shuf.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) cmdline evec seps rvec fdata
use clap::{crate_version, Arg, ArgAction, Command};
use memchr::memchr_ite... | .override_usage(format_usage(USAGE))
.infer_long_args(true)
.args_override_self(true)
.arg(
Arg::new(options::ECHO)
.short('e')
.long(options::ECHO)
.value_name("ARG")
.help("treat each ARG as an input line")
... | .version(crate_version!()) | random_line_split |
eda.py | # To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %% [markdown]
# # Predicting Scooter Users
# April 2020
#
# Part 2. Exploratory Data Analysis
#
# Submitted by: XU Yuting
# %% [markdown]
# ## Section 1. Import Data
# %%
# import relevant libraries
import sys
import pandas as pd... | df['psi'].describe()
# %% [markdown]
# #### Task 4: Column 'date' - transform to numeric data e.g. year, month, date, day of week
# %%
# first we convert the date column to date object
dt=df['date']
df['date']=pd.to_datetime(dt)
# %%
type(df['date'].values[0])
# %% [markdown]
# Now we need to create new columns an... | # %%
df['psi'].replace(0,np.nan,inplace=True) | random_line_split |
form-field-config.type.ts | /**
* This file is part of OpenMediaVault.
*
* @license http://www.gnu.org/licenses/gpl.html GPL Version 3
* @author Volker Theile <volker.theile@openmediavault.org>
* @copyright Copyright (c) 2009-2021 Volker Theile
*
* OpenMediaVault is free software: you can redistribute it and/or modify
* it under the ... | // --- numberInput | password | textInput ---
autocomplete?: string;
// Note, this button is only visible if the browser supports
// that. The following requirements must be met:
// - The HTTPS protocol is used. localhost is also supported.
// - The site is not embedded in an iFrame.
hasCopyToClipboardBut... | random_line_split | |
lib.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
impl Sub for Indent {
type Output = Indent;
fn sub(self, rhs: Indent) -> Indent {
Indent::new(self.block_indent - rhs.block_indent,
self.alignment - rhs.alignment)
}
}
impl Add<usize> for Indent {
type Output = Indent;
fn add(self, rhs: usize) -> Indent {
In... | alignment: self.alignment + rhs.alignment,
}
} | random_line_split |
lib.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> Span {
self.span
}
}
impl Spanned for ast::Pat {
fn span(&self) -> Span {
self.span
}
}
impl Spanned for ast::Ty {
fn span(&self) -> Span {
self.span
}
}
impl Spanned for ast::Arg {
fn span(&self) -> Span {
if items::is_named_arg(self) {
... | span | identifier_name |
trajectory_tracking.py | #!/usr/bin/env python3
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import *
from rospy.core import rospyinfo
from std_msgs import msg
from tf.transformations import euler_from_quaternion
from gazebo_msgs.msg import ModelStates
import yaml
import matplotlib.pyplot as plt
from sensor_msgs.msg i... |
def unicicle_Linear_control(self,traj,zeta,a):
rospy.sleep(0.1) # need small time to setup q in callback
max_t = self.t[len(self.t) - 1]
len_t = len(self.t)
self.trajectory=traj
if(self.trajectory == "parallel_parking" ):
for i in np.arange(0, len_t):
... | if(self.trajectory == "parallel_parking" ):
(x, y, theta) = self.get_pose() #NB: i punti x e y sono sull'asse posteriore, non è il centro della macchina
else:
(a, b, theta) = self.get_pose() #prendo solo theta
x=self.data_pose[0]
y=self.data_pose[1]
#compu... | identifier_body |
trajectory_tracking.py | #!/usr/bin/env python3
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import *
from rospy.core import rospyinfo
from std_msgs import msg
from tf.transformations import euler_from_quaternion
from gazebo_msgs.msg import ModelStates
import yaml
import matplotlib.pyplot as plt
from sensor_msgs.msg i... | f):
toltheta=0.2
tol=0.05
vel=2
q_i = self.get_pose()
if np.pi/2-toltheta<=q_i[2]<=toltheta+np.pi/2 or -np.pi/2-toltheta<=q_i[2]<=toltheta-np.pi/2:
while q_i[0]<=self.A_park[0][0]-tol or q_i[0]>=self.A_park[0][0]+tol:
q_i = self.get_pose()
... | oint(sel | identifier_name |
trajectory_tracking.py | #!/usr/bin/env python3
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import *
from rospy.core import rospyinfo
from std_msgs import msg
from tf.transformations import euler_from_quaternion
from gazebo_msgs.msg import ModelStates
import yaml
import matplotlib.pyplot as plt
from sensor_msgs.msg i... | y = round(posizione[1],1)
tg = Trajectory_generation()
q_i = self.get_pose()
self.trajectory=traj
if(self.trajectory == "parallel_parking" ):
(self.x_d, self.y_d,self.dotx_d,self.doty_d,self.v_d, self.w_d , self.theta_d , self.psi, self.A_park) =t... |
data = rospy.wait_for_message("/gazebo/model_states", ModelStates, timeout=5)
posizione = self.callback(data)
x = round(posizione[0],1) | random_line_split |
trajectory_tracking.py | #!/usr/bin/env python3
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import *
from rospy.core import rospyinfo
from std_msgs import msg
from tf.transformations import euler_from_quaternion
from gazebo_msgs.msg import ModelStates
import yaml
import matplotlib.pyplot as plt
from sensor_msgs.msg i... | else:
a=tt.data_pose[0] #estraggo x odometria
# SEZIONE AVANZAMENTO
while tt.get_laser()[0]==0 and abs(a)<=13: # 13 fine strada parcheggi
if tt.get_laser()[0]==1:
print("Park Found")
else:
print("Park not Found")
tt.send_velocities(3,0,0)
if... | .data_pose[1] #estraggo y odometria
| conditional_block |
srvcenter.go | /*
* Copyright 2013 Nan Deng
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in ... | (maxNrConns, maxNrConnsPerUser, maxNrUsers int) {
connMap := newTreeBasedConnMap()
nrConns := 0
for {
select {
case connInEvt := <-self.connIn:
if maxNrConns > 0 && nrConns >= maxNrConns {
if connInEvt.errChan != nil {
connInEvt.errChan <- ErrTooManyConns
}
continue
}
err := connMap.Add... | process | identifier_name |
srvcenter.go | /*
* Copyright 2013 Nan Deng
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in ... |
func getPushInfo(msg *proto.Message, extra map[string]string, fwd bool) map[string]string {
if extra == nil {
extra = make(map[string]string, len(msg.Header)+3)
}
if fwd {
for k, v := range msg.Header {
if strings.HasPrefix(k, "notif.") {
if strings.HasPrefix(k, "notif.uniqush.") {
// forward messa... | {
shouldFwd := false
if self.config != nil {
if self.config.ForwardRequestHandler != nil {
shouldFwd = self.config.ForwardRequestHandler.ShouldForward(fwdreq)
maxttl := self.config.ForwardRequestHandler.MaxTTL()
if fwdreq.TTL < 1*time.Second || fwdreq.TTL > maxttl {
fwdreq.TTL = maxttl
}
}
}
if ... | identifier_body |
srvcenter.go | /*
* Copyright 2013 Nan Deng
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in ... |
if wreq.resChan != nil {
wreq.resChan <- res
}
// close all connections with error:
go func() {
for _, e := range errConns {
fmt.Printf("Need to remove connection %v\n", e.conn.UniqId())
self.connLeave <- &eventConnLeave{conn: e.conn, err: e.err}
}
}()
}
}
}
func (self *servic... | {
msg := wreq.msg
extra := wreq.extra
username := wreq.user
service := self.serviceName
fwd := false
if len(msg.Sender) > 0 && len(msg.SenderService) > 0 {
if msg.Sender != username || msg.SenderService != service {
fwd = true
}
}
go func() {
should := self.shouldPus... | conditional_block |
srvcenter.go | /*
* Copyright 2013 Nan Deng
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in ... | usr := conn.Username()
if len(usr) == 0 || strings.Contains(usr, ":") || strings.Contains(usr, "\n") {
return fmt.Errorf("[Username=%v] Invalid Username")
}
evt := new(eventConnIn)
ch := make(chan error)
conn.SetMessageCache(self.config.MsgCache)
evt.conn = conn
evt.errChan = ch
self.connIn <- evt
err := <... | }
}
func (self *serviceCenter) NewConn(conn server.Conn) error { | random_line_split |
wireguard.go | package cmd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"strings"
"text/template"
"github.com/AlecAivazis/survey/v2"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/cmdctx"
"github.com/superfly/fl... |
fmt.Printf(`
!!!! WARNING: Output includes credential information. Credentials cannot !!!!
!!!! be recovered after creation; if you lose the token, you'll need to !!!!
!!!! remove and and re-add it. !!!!
To use a token to create a WireGuard connection, you can use curl:
curl -v --request... | {
return err
} | conditional_block |
wireguard.go | package cmd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"strings"
"text/template"
"github.com/AlecAivazis/survey/v2"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/cmdctx"
"github.com/superfly/fl... | (ctx *cmdctx.CmdContext, idx int, prompt string) (w io.WriteCloser, mustClose bool, err error) {
var (
f *os.File
filename string
)
for {
filename, err = argOrPromptLoop(ctx, idx, prompt, filename)
if err != nil {
return nil, false, err
}
if filename == "" {
fmt.Println("Provide a filename... | resolveOutputWriter | identifier_name |
wireguard.go | package cmd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"strings"
"text/template"
"github.com/AlecAivazis/survey/v2"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/cmdctx"
"github.com/superfly/fl... | }
func runWireGuardStat(cmdCtx *cmdctx.CmdContext) error {
ctx := cmdCtx.Command.Context()
client := cmdCtx.Client.API()
org, err := orgByArg(cmdCtx)
if err != nil {
return err
}
var name string
if len(cmdCtx.Args) >= 2 {
name = cmdCtx.Args[1]
} else {
name, err = selectWireGuardPeer(ctx, cmdCtx.Clien... | fmt.Println("Removed peer.")
return wireguard.PruneInvalidPeers(ctx, cmdCtx.Client.API()) | random_line_split |
wireguard.go | package cmd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"strings"
"text/template"
"github.com/AlecAivazis/survey/v2"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/cmdctx"
"github.com/superfly/fl... |
func runWireGuardTokenStartPeer(ctx *cmdctx.CmdContext) error {
token := os.Getenv("FLY_WIREGUARD_TOKEN")
if token == "" {
return fmt.Errorf("set FLY_WIREGUARD_TOKEN env")
}
name, err := argOrPrompt(ctx, 0, "Name (DNS-compatible) for peer: ")
if err != nil {
return err
}
group, err := argOrPrompt(ctx, 1,... | {
fmt.Printf(`
!!!! WARNING: Output includes private key. Private keys cannot be recovered !!!!
!!!! after creating the peer; if you lose the key, you'll need to rekey !!!!
!!!! the peering connection. !!!!
`)
w, shouldClose, err := resolveOutputWriter(ctx, idx, "Fi... | identifier_body |
nba-game-list.ts | import { Component, OnInit } from '@angular/core';
import { Refresher, AlertController, NavController, Platform } from 'ionic-angular';
import { DatePicker, DatePickerOptions } from 'ionic-native';
import { NBATeamDataType } from '../../base-data-type/nba-team-datatype';
import { NBATeamMap } from '../../services/nba-t... |
})
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
} | {
this.gameCount = 0;
let alert = this.GamealertCtrl.create({
title: 'Oops!',
subTitle: 'There are not any game today or the day you select.',
buttons: ['OK']
});
alert... | conditional_block |
nba-game-list.ts | import { Component, OnInit } from '@angular/core';
import { Refresher, AlertController, NavController, Platform } from 'ionic-angular';
import { DatePicker, DatePickerOptions } from 'ionic-native';
import { NBATeamDataType } from '../../base-data-type/nba-team-datatype';
import { NBATeamMap } from '../../services/nba-t... | (event, GameItem) {
this.navCtrl.push(NBAGameDetailPage, {
GameItem: GameItem,
SelectedYear: this.selectedYear
});
}
/**
* @Param: nowDateTime, UTC
* @Example: UTC => +8: "Asia/Shanghai", -4: "America/New_York", -7: "America/Los_Angeles"
* @Remark: "Asia/S... | GameItemTapped | identifier_name |
nba-game-list.ts | import { Component, OnInit } from '@angular/core';
import { Refresher, AlertController, NavController, Platform } from 'ionic-angular';
import { DatePicker, DatePickerOptions } from 'ionic-native';
import { NBATeamDataType } from '../../base-data-type/nba-team-datatype';
import { NBATeamMap } from '../../services/nba-t... |
doRefresh(refresher: Refresher) {
this.GetNBAGameList(this.ChangedDate).then(() => refresher.complete()).catch(this.handleError);
}
OpenDatePicker(): void {
let options: DatePickerOptions;
if (this.platform.is('android')) {
options = {
... | {
let nowLocalTime: Date = new Date();
//we use America/Los_Angeles time zone because L.A. game start at last in one day.
let SpecificDateTimeArray: any[] = this.GetSpecificTimeZoneFormat(nowLocalTime, -7);
this.ChangedDate = SpecificDateTimeArray[0] + SpecificDat... | identifier_body |
nba-game-list.ts | import { Component, OnInit } from '@angular/core';
import { Refresher, AlertController, NavController, Platform } from 'ionic-angular';
import { DatePicker, DatePickerOptions } from 'ionic-native';
import { NBATeamDataType } from '../../base-data-type/nba-team-datatype';
import { NBATeamMap } from '../../services/nba-t... | GameProcess = EachGameitem['GameDate'].replace(/\s*ET\s*/, '');
break;
case 'live':
GameProcess = EachGameitem['process']['Quarter'] + ' ';
GameProcess += EachGamei... | random_line_split | |
ddglCtrl.js | require([ 'jquery', 'app', 'common', 'validate','pagination', 'bootstrap', 'timepicker', 'dateZh' ], function($, app, common,validate) {
$('title').text('订单管理');
var deliverytype = ['','上门提货','自送网点'];
var iscreditapply = ['否','是'];
//日期控件
$('#date-start, #date-end').datetimepicker({
format : "yyyy-mm-dd hh:ii:s... | ', function() {
$("input[name='orderid-query']").val('');
$("input[name='sender-query']").val('');
$("input[name='receiver-query']").val('');
$("input[name='username-query']").val('');
$("select[name='state-query']").val('');
$("select[name='iscreditapply-query']").val('');
$('.setTableLength').val(... | );
}
//placeholder兼容ie end
//清除按钮
$('.clearBtn').on('click | identifier_body |
ddglCtrl.js | require([ 'jquery', 'app', 'common', 'validate','pagination', 'bootstrap', 'timepicker', 'dateZh' ], function($, app, common,validate) {
$('title').text('订单管理');
var deliverytype = ['','上门提货','自送网点'];
var iscreditapply = ['否','是'];
//日期控件
$('#date-start, #date-end').datetimepicker({
format : "yyyy-mm-dd hh:ii:s... | );
$(".modal-edityd").find("select[name='dispatchtype']").val(data.dispatchtype);
$(".modal-edityd").find("input[name='agencyfund']").val(data.agencyfund);
$(".modal-edityd").find("input[name='receiptnum']").val(data.receiptnum);
$(".modal-edityd").find("input[name='receiptno']").val(data.receiptno);
$("... | conditional_block | |
ddglCtrl.js | require([ 'jquery', 'app', 'common', 'validate','pagination', 'bootstrap', 'timepicker', 'dateZh' ], function($, app, common,validate) {
$('title').text('订单管理');
var deliverytype = ['','上门提货','自送网点'];
var iscreditapply = ['否','是'];
//日期控件
$('#date-start, #date-end').datetimepicker({
format : "yyyy-mm-dd hh:ii:s... | }
var sumnum = 0;
var sumweight = 0.0;
var sumvalume = 0.0;
var sumorderfee = 0.0;
var sumagencyfund = 0.0;
var result = data.result;
if(result!=null && result=="noauthority") {
common.alert1('你无此权限!');
return;
}
if(data.result!=null && data.result=="againLogin") {
... | $('.loading').remove(); | random_line_split |
ddglCtrl.js | require([ 'jquery', 'app', 'common', 'validate','pagination', 'bootstrap', 'timepicker', 'dateZh' ], function($, app, common,validate) {
$('title').text('订单管理');
var deliverytype = ['','上门提货','自送网点'];
var iscreditapply = ['否','是'];
//日期控件
$('#date-start, #date-end').datetimepicker({
format : "yyyy-mm-dd hh:ii:s... | ut');
}
//placeholder兼容ie end
//清除按钮
$('.clearBtn').on('click', function() {
$("input[name='orderid-query']").val('');
$("input[name='sender-query']").val('');
$("input[name='receiver-query']").val('');
$("input[name='username-query']").val('');
$("select[name='state-query']").val('');
$("select[nam... | createElement('inp | identifier_name |
SiteInfoDialog.py | # -*- coding: utf-8 -*-
# Copyright (c) 2011 - 2019 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing a dialog to show some information about a site.
"""
from PyQt5.QtCore import pyqtSlot, QUrl, Qt
from PyQt5.QtGui import QPixmap, QImage, QPainter, QColor, QBrush
from PyQt5.QtNetwork import QNet... |
@pyqtSlot(QTreeWidgetItem, QTreeWidgetItem)
def on_imagesTree_currentItemChanged(self, current, previous):
"""
Private slot to show a preview of the selected image.
@param current current image entry (QTreeWidgetItem)
@param previous old current entry (QTreeWidgetI... | self.tagsTree.resizeColumnToContents(col) | conditional_block |
SiteInfoDialog.py | # -*- coding: utf-8 -*-
# Copyright (c) 2011 - 2019 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing a dialog to show some information about a site.
"""
from PyQt5.QtCore import pyqtSlot, QUrl, Qt
from PyQt5.QtGui import QPixmap, QImage, QPainter, QColor, QBrush
from PyQt5.QtNetwork import QNet... |
@pyqtSlot()
def __imageReplyFinished(self):
"""
Private slot handling the loading of an image.
"""
if self.__imageReply.error() != QNetworkReply.NoError:
return
data = self.__imageReply.readAll()
self.__showPixmap(QPixmap.fromImage(QImag... | """
Private slot to show a preview of the selected image.
@param current current image entry (QTreeWidgetItem)
@param previous old current entry (QTreeWidgetItem)
"""
if current is None:
return
imageUrl = QUrl(current.text(1))
if imag... | identifier_body |
SiteInfoDialog.py | # -*- coding: utf-8 -*-
# Copyright (c) 2011 - 2019 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing a dialog to show some information about a site.
"""
from PyQt5.QtCore import pyqtSlot, QUrl, Qt
from PyQt5.QtGui import QPixmap, QImage, QPainter, QColor, QBrush
from PyQt5.QtNetwork import QNet... | (self):
"""
Private method to show some text while loading an image.
"""
self.imagePreview.setBackgroundBrush(
self.__imagePreviewStandardBackground)
scene = QGraphicsScene(self.imagePreview)
scene.addText(self.tr("Loading..."))
self.imagePreview.setSc... | __showLoadingText | identifier_name |
SiteInfoDialog.py | # -*- coding: utf-8 -*-
# Copyright (c) 2011 - 2019 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing a dialog to show some information about a site.
"""
from PyQt5.QtCore import pyqtSlot, QUrl, Qt
from PyQt5.QtGui import QPixmap, QImage, QPainter, QColor, QBrush
from PyQt5.QtNetwork import QNet... |
pixmapItem = self.imagePreview.scene().items()[0]
if not isinstance(pixmapItem, QGraphicsPixmapItem):
return
if pixmapItem.pixmap().isNull():
E5MessageBox.warning(
self,
self.tr("Save Image"),
self.tr(
... | return | random_line_split |
kNN.py | # -*- coding:UTF-8 -*-
import numpy as np
import operator
def createDataSet():
dataMat = np.array([[1.0,1.1], [1.0,1.0], [0.0,1.0], [0.0,1.1]])
labelVec = ['love', 'love', 'hate', 'hate']
return dataMat, labelVec
def classify0(inX, dataMat, labelVec, k):
# 训练集的个数
dataSize = dataMat.shape[0]
... |
return returnVec
def handwritingClassTest():
from os import listdir
from sklearn.neighbors import KNeighborsClassifier as kNN
hwLabels = []
# 目录下文件名
trainingFileList = listdir('trainingDigits')
m = len(trainingFileList)
trainingMat = np.zeros((m, 1024))
# 获取训练数据和标签
for i in ran... | ineStr[i]) | identifier_name |
kNN.py | # -*- coding:UTF-8 -*-
import numpy as np
import operator
def createDataSet():
dataMat = np.array([[1.0,1.1], [1.0,1.0], [0.0,1.0], [0.0,1.1]])
labelVec = ['love', 'love', 'hate', 'hate']
return dataMat, labelVec
def classify0(inX, dataMat, labelVec, k):
# 训练集的个数
dataSize = dataMat.shape[0]
... | ate(product(range(1, 4), repeat=2)):
ax = plt.Subplot(fig, inner_grid[j])
ax.plot(*squiggle_xy(a, b, c, d))
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
all_axes = fig.get_axes()
#show only the outside spines
for ax in all_axes:
... | idSpec(4, 4, wspace=0.0, hspace=0.0)
for i in range(16):
inner_grid = gridspec.GridSpecFromSubplotSpec(3, 3,
subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0)
a, b = int(i/4)+1,i%4+1
for j, (c, d) in enumer | identifier_body |
kNN.py | # -*- coding:UTF-8 -*-
import numpy as np
import operator
def createDataSet():
dataMat = np.array([[1.0,1.1], [1.0,1.0], [0.0,1.0], [0.0,1.1]])
labelVec = ['love', 'love', 'hate', 'hate']
return dataMat, labelVec
def classify0(inX, dataMat, labelVec, k):
# 训练集的个数
dataSize = dataMat.shape[0]
... | outer_grid = gridspec.GridSpec(4, 4, wspace=0.0, hspace=0.0)
for i in range(16):
inner_grid = gridspec.GridSpecFromSubplotSpec(3, 3,
subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0)
a, b = int(i/4)+1,i%4+1
for j, (c, d) in enumerate(product(range(1, 4), repeat=2)):
... |
fig = plt.figure(figsize=(8, 8))
# gridspec inside gridspec | random_line_split |
kNN.py | # -*- coding:UTF-8 -*-
import numpy as np
import operator
def createDataSet():
dataMat = np.array([[1.0,1.1], [1.0,1.0], [0.0,1.0], [0.0,1.1]])
labelVec = ['love', 'love', 'hate', 'hate']
return dataMat, labelVec
def classify0(inX, dataMat, labelVec, k):
# 训练集的个数
dataSize = dataMat.shape[0]
... | lineStr = fr.readline()
for j in range(32):
returnVec[0, i * 32 + j] = int(lineStr[i])
return returnVec
def handwritingClassTest():
from os import listdir
from sklearn.neighbors import KNeighborsClassifier as kNN
hwLabels = []
# 目录下文件名
trainingFileList = listdir('trainin... | ec[i])
if (classifierResult != datingLabelVec[i]):
errorCount += 1.0
print "the total error rate is:%f" % (errorCount/float(numTestVecs))
print errorCount
def img2vector(filename):
returnVec = np.zeros((1, 1024))
fr = open(filename)
for i in range(32):
| conditional_block |
chat-ui.js | /**
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
*
* 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 require... | {
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
var char = str.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return ((hash + 2147483647 + 1) % 6) + 1;
} | identifier_body | |
chat-ui.js | /**
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
*
* 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 require... | this.maxUserSearchResults = 100;
this.urlPattern = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;
this.pseudoUrlPattern = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
var self = this;
// Initialize the UI
this.UIbindElements();
this.UIScrollToInput();
// Initi... | this.maxLengthUsername = 15;
this.maxLengthUsernameDisplay = 13;
this.maxLengthRoomName = 15;
this.maxLengthMessage = 120; | random_line_split |
chat-ui.js | /**
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
*
* 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 require... |
}
if (!rawMessage.isDigitalAssistant) {
message.message = _.map(message.message.split(' '), function(token) {
if (self.urlPattern.test(token) || self.pseudoUrlPattern.test(token)) {
return _linkify(encodeURI(token));
} else {
... | {
var s = "0" + _hashCode(message.name);
message.avatar = s.substr(s.length - 2);
} | conditional_block |
chat-ui.js | /**
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
*
* 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 require... | (str) {
return str
.replace(self.urlPattern, '<a target="_blank" href="$&">$&</a>')
.replace(self.pseudoUrlPattern, '$1<a target="_blank" href="http://$2">$2</a>');
};
function _hashCode(str){
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
... | _linkify | identifier_name |
main.py | # -*- coding: utf8 -*-
# import os
# import pygame
from modules.create_window import *
# from modules.key_control_move import *
from modules.color_name import *
from pics import *
import copy
# The first and the second number are the start position (x,y).
# r,l,u,d = right,left,up,down
# The number after english wo... | gameDisplay.blit(text_line_2, (240, 370))
gameDisplay.blit(text_line_1, (506, 370))
gameDisplay.blit(text_line_2, (506, 340))
gameDisplay.blit(play, (300, 350))
if pygame.Rect(300, 350, play_size[0], play_size[1]).collidepoint(mouse_pos):
gameDisplay.blit(text_line, (290, 270))
gameDispla... | gameDisplay.blit(text_line_1, (240, 340)) | random_line_split |
main.py | # -*- coding: utf8 -*-
# import os
# import pygame
from modules.create_window import *
# from modules.key_control_move import *
from modules.color_name import *
from pics import *
import copy
# The first and the second number are the start position (x,y).
# r,l,u,d = right,left,up,down
# The number after english wo... |
def showMonsterWalkPath(data_list):
"""
showMonsterWalkPath(data_list)
The data_list should be a 2D list.
"""
pos = [0,0]
for i in range(len(data_list)):
if i == 0:
pos = copy.copy(data_list[i])
gameDisplay.blit(monster_walk, pos)
else:
monster_move = False
num_cal = [1,0,0]
dx = (data_list[... | """
Translate the monster_walk_path to a list and return it.
"""
path = []
pos = [0,0]
for i in range(len(data)):
if i == 0:
pos[0] = 50*(int(data[i])-1)
elif i == 1:
pos[1] = 50*(int(data[i])-1)
path.append(copy.copy(pos))
else:
move = [0,0]
if data[i] == "l":
move = [-50,0]
elif data[... | identifier_body |
main.py | # -*- coding: utf8 -*-
# import os
# import pygame
from modules.create_window import *
# from modules.key_control_move import *
from modules.color_name import *
from pics import *
import copy
# The first and the second number are the start position (x,y).
# r,l,u,d = right,left,up,down
# The number after english wo... |
elif not stop and not drop_it:
stop = True
if stop:
pass
else:
if event.type == pygame.MOUSEBUTTONUP:
if playing:
#-- Right frame:
# Tools
if pygame.Rect((676, 135), sell_0_size).collidepoint(mouse_pos):
money_temp = int(money_now) + sell_price
if money_... | drop_it = False | conditional_block |
main.py | # -*- coding: utf8 -*-
# import os
# import pygame
from modules.create_window import *
# from modules.key_control_move import *
from modules.color_name import *
from pics import *
import copy
# The first and the second number are the start position (x,y).
# r,l,u,d = right,left,up,down
# The number after english wo... | (data_list, init_pos):
"""
createMonsterWalkPath(data_list, init_pos)
"""
path = []
pos = copy.copy(init_pos)
path.append(copy.copy(pos))
monster_size = 20
side_d = (50-monster_size)/2
for i in data_list:
pos_temp = [0,0]
pos_temp[0] = pos[0]-side_d
pos_temp[1] = pos[1]-side_d
dx = i[0] - pos_temp[0]... | createMonsterWalkPath | identifier_name |
Clout.js | /*!
* clout-js
* Copyright(c) 2015 - 2016 Muhammad Dadu
* MIT Licensed
*/
/**
* Clout
* @module clout-js/lib/Clout
*/
const path = require('path');
const fs = require('fs-extra');
const { EventEmitter } = require('events');
const debug = require('debug')('clout:core');
const async = require('async');
const _ = ... |
}
debug('push hook (lowest priority yet)');
this.hooks[event].push(fn);
}
/**
* Loads hooks from directory
* @param {Path} dir directory
* @return {Promise} promise
*/
loadHooksFromDir(dir) {
const glob = path.join(dir, '/hooks/**/*.js');
const files = utils.getGlobbedFiles(gl... | {
debug('push hook at index %s', String(i));
this.hooks[event].splice(i, 0, fn);
return;
} | conditional_block |
Clout.js | /*!
* clout-js
* Copyright(c) 2015 - 2016 Muhammad Dadu
* MIT Licensed
*/
/**
* Clout
* @module clout-js/lib/Clout
*/
const path = require('path');
const fs = require('fs-extra');
const { EventEmitter } = require('events');
const debug = require('debug')('clout:core');
const async = require('async');
const _ = ... | * @param {Path} dir directory
* @return {Promise} promise
*/
loadHooksFromDir(dir) {
const glob = path.join(dir, '/hooks/**/*.js');
const files = utils.getGlobbedFiles(glob);
debug('loadHooksFromDir: %s', dir);
return new Promise((resolve, reject) => {
async.each(files, (file, next)... | }
/**
* Loads hooks from directory | random_line_split |
Clout.js | /*!
* clout-js
* Copyright(c) 2015 - 2016 Muhammad Dadu
* MIT Licensed
*/
/**
* Clout
* @module clout-js/lib/Clout
*/
const path = require('path');
const fs = require('fs-extra');
const { EventEmitter } = require('events');
const debug = require('debug')('clout:core');
const async = require('async');
const _ = ... |
/**
* Load clout-js node module
* @param {string} moduleName clout node module name
*/
addModule(moduleName) {
if (this.moduleCache.includes(moduleName)) {
debug('module: %s already loaded', moduleName);
return;
}
this.logger.debug('loading module: %s', moduleName);
this.modu... | {
debug('loading modules', JSON.stringify(modules));
modules.forEach(moduleName => this.addModule(moduleName));
} | identifier_body |
Clout.js | /*!
* clout-js
* Copyright(c) 2015 - 2016 Muhammad Dadu
* MIT Licensed
*/
/**
* Clout
* @module clout-js/lib/Clout
*/
const path = require('path');
const fs = require('fs-extra');
const { EventEmitter } = require('events');
const debug = require('debug')('clout:core');
const async = require('async');
const _ = ... | (dir) {
const glob = path.join(dir, '/hooks/**/*.js');
const files = utils.getGlobbedFiles(glob);
debug('loadHooksFromDir: %s', dir);
return new Promise((resolve, reject) => {
async.each(files, (file, next) => {
debug('loading hooks from file: %s', String(file));
const hooks = r... | loadHooksFromDir | identifier_name |
htp1.py | import json
import logging
from typing import Optional, List
import semver
from autobahn.exception import Disconnected
from autobahn.twisted.websocket import WebSocketClientFactory, connectWS, WebSocketClientProtocol
from twisted.internet.protocol import ReconnectingClientFactory
from ezbeq.apis.ws import WsServer
fr... | self.sendMessage('getmso'.encode('utf-8'), isBinary=False)
def onOpen(self):
logger.info("Connected to HTP1")
self.factory.register(self)
def onClose(self, was_clean, code, reason):
if was_clean:
logger.info(f"Disconnected code: {code} reason: {reason}")
els... | random_line_split | |
htp1.py | import json
import logging
from typing import Optional, List
import semver
from autobahn.exception import Disconnected
from autobahn.twisted.websocket import WebSocketClientFactory, connectWS, WebSocketClientProtocol
from twisted.internet.protocol import ReconnectingClientFactory
from ezbeq.apis.ws import WsServer
fr... |
ops = [peq.as_ops(c, use_shelf=self.__supports_shelf) for peq in to_load for c in self.__peq.keys()]
ops = [op for slot_ops in ops for op in slot_ops if op]
if ops:
self.__client.send('changemso [{"op":"replace","path":"/peq/peqsw","value":true}]')
self.__client.send(f"c... | peq = PEQ(len(to_load), fc=100, q=1, gain=0, filter_type_name='PeakingEQ')
to_load.append(peq) | conditional_block |
htp1.py | import json
import logging
from typing import Optional, List
import semver
from autobahn.exception import Disconnected
from autobahn.twisted.websocket import WebSocketClientFactory, connectWS, WebSocketClientProtocol
from twisted.internet.protocol import ReconnectingClientFactory
from ezbeq.apis.ws import WsServer
fr... |
def clientConnectionFailed(self, connector, reason):
logger.warning(f"Client connection failed {reason} .. retrying ..")
super().clientConnectionFailed(connector, reason)
def clientConnectionLost(self, connector, reason):
logger.warning(f"Client connection failed {reason} .. retrying ... | super(Htp1ClientFactory, self).__init__(*args, **kwargs)
self.__clients: List[Htp1Protocol] = []
self.listener = listener
self.setProtocolOptions(version=13) | identifier_body |
htp1.py | import json
import logging
from typing import Optional, List
import semver
from autobahn.exception import Disconnected
from autobahn.twisted.websocket import WebSocketClientFactory, connectWS, WebSocketClientProtocol
from twisted.internet.protocol import ReconnectingClientFactory
from ezbeq.apis.ws import WsServer
fr... | (self, client: Htp1Protocol):
if client in self.__clients:
logger.info(f"Unregistering device {client.peer}")
self.__clients.remove(client)
else:
logger.info(f"Ignoring unregistered device {client.peer}")
def broadcast(self, msg):
if self.__clients:
... | unregister | identifier_name |
Final of the Electromagnet Project.py | # coding: utf-8
# # INTRODUCTION
# This project is related to designing a junk-yard magnet, which is an electromagnet type. Throughout this project, electromagnet operating principles and design techniques in terms of different load values and electromagnet types are covered. The electromagnet should be capable of... | tt = float(raw_input("Enter the thickness of the load in mm :"))
llcm = ll * float(2.54)
wwcm = ww * float(2.54)
ttcm = tt / float(10)
VV = float(llcm * wwcm * ttcm)
density = float(7.81)
mgg = VV * density
mg = mgg / float(1000)
elif material == 2:
ll = float(raw_input("Enter the le... | material = float(raw_input("The load material: "))
if material == 1:
ll = float(raw_input("Enter the length of the load in inches :"))
ww = float(raw_input("Enter the width of the load in inches :")) | random_line_split |
Final of the Electromagnet Project.py |
# coding: utf-8
# # INTRODUCTION
# This project is related to designing a junk-yard magnet, which is an electromagnet type. Throughout this project, electromagnet operating principles and design techniques in terms of different load values and electromagnet types are covered. The electromagnet should be capable o... |
g = float(raw_input("Enter the length of Air gap in mm ")) # 0.1 mm for Contacted Lifting
t = 0 # the width between the track poles
from math import pi, exp, sqrt, atan
uo = float(4 * pi * 10**-7)
print " Permeability : For Iron (99.8% pure) is 6.3 * 10^-3 H/m"
print " Permeability : For Electrical steel is 5... | loat(raw_input("Enter the length of Electromagnet in mm "))
w = float(raw_input("Enter the Width between the electromagnet pole pieces in mm "))
h = float(raw_input("Enter the Height of the pole pieces above the yoke in mm "))
p = float(raw_input("Enter the Width of the pole pieces in mm "))
if l >= (2 ... | conditional_block |
aa_changes.rs | use crate::alphabet::aa::Aa;
use crate::alphabet::letter::Letter;
use crate::alphabet::letter::{serde_deserialize_seq, serde_serialize_seq};
use crate::alphabet::nuc::Nuc;
use crate::analyze::aa_del::AaDel;
use crate::analyze::aa_sub::AaSub;
use crate::analyze::nuc_del::NucDelRange;
use crate::analyze::nuc_sub::NucSub;... |
/// Finds aminoacid substitutions and deletions in query peptides relative to reference peptides, in one gene
///
/// ## Precondition
/// Nucleotide sequences and peptides are required to be stripped from insertions
///
///
/// ## Implementation details
/// We compare reference and query peptides (extracted by the pr... | {
let mut changes = qry_translation
.iter_cdses()
.map(|(qry_name, qry_cds_tr)| {
let ref_cds_tr = ref_translation.get_cds(qry_name)?;
let cds = gene_map.get_cds(&qry_cds_tr.name)?;
Ok(find_aa_changes_for_cds(
cds, qry_seq, ref_seq, ref_cds_tr, qry_cds_tr, nuc_subs, nuc_dels,
)... | identifier_body |
aa_changes.rs | use crate::alphabet::aa::Aa;
use crate::alphabet::letter::Letter;
use crate::alphabet::letter::{serde_deserialize_seq, serde_serialize_seq};
use crate::alphabet::nuc::Nuc;
use crate::analyze::aa_del::AaDel;
use crate::analyze::aa_sub::AaSub;
use crate::analyze::nuc_del::NucDelRange;
use crate::analyze::nuc_sub::NucSub;... | // then append to the group.
if codon <= prev.pos + 2 {
// If previous codon in the group is not exactly adjacent, there is 1 item in between,
// then cover the hole by inserting previous codon.
if codon == prev.pos + 2 && is_codon_sequenced(aa_alignment_ranges, c... | random_line_split | |
aa_changes.rs | use crate::alphabet::aa::Aa;
use crate::alphabet::letter::Letter;
use crate::alphabet::letter::{serde_deserialize_seq, serde_serialize_seq};
use crate::alphabet::nuc::Nuc;
use crate::analyze::aa_del::AaDel;
use crate::analyze::aa_sub::AaSub;
use crate::analyze::nuc_del::NucDelRange;
use crate::analyze::nuc_sub::NucSub;... |
// Current group is not empty
Some(prev) => {
// If previous codon in the group is adjacent or almost adjacent (there is 1 item in between),
// then append to the group.
if codon <= prev.pos + 2 {
// If previous codon in the group is not exactly adjacent, there... | {
if codon > 0 && is_codon_sequenced(aa_alignment_ranges, codon - 1) {
// Also prepend one codon to the left, for additional context, to start the group
curr_group.push(AaChangeWithContext::new(
cds,
codon - 1,
qry_seq,
ref_seq,
... | conditional_block |
aa_changes.rs | use crate::alphabet::aa::Aa;
use crate::alphabet::letter::Letter;
use crate::alphabet::letter::{serde_deserialize_seq, serde_serialize_seq};
use crate::alphabet::nuc::Nuc;
use crate::analyze::aa_del::AaDel;
use crate::analyze::aa_sub::AaSub;
use crate::analyze::nuc_del::NucDelRange;
use crate::analyze::nuc_sub::NucSub;... | {
pub cds_name: String,
pub pos: AaRefPosition,
pub ref_aa: Aa,
pub qry_aa: Aa,
pub nuc_pos: NucRefGlobalPosition,
#[schemars(with = "String")]
#[serde(serialize_with = "serde_serialize_seq")]
#[serde(deserialize_with = "serde_deserialize_seq")]
pub ref_triplet: Vec<Nuc>,
#[schemars(with = "Strin... | AaChangeWithContext | identifier_name |
lib.rs | #![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))]
#![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))]
#![deny(warnings)]
extern crate bytes;
extern crate conduit_proxy_controller_grpc;
extern crate env_logger;
extern crate deflate;
#[macro_use]
extern crate futures;
extern crate fut... |
RouteError::NotRecognized => {
error!("turning route not recognized error into 500");
http::StatusCode::INTERNAL_SERVER_ERROR
}
RouteError::NoCapacity(capacity) => {
// TODO For H2 streams, we should probably si... | {
error!("turning {} into 500", i);
http::StatusCode::INTERNAL_SERVER_ERROR
} | conditional_block |
lib.rs | #![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))]
#![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))]
#![deny(warnings)]
extern crate bytes;
extern crate conduit_proxy_controller_grpc;
extern crate env_logger;
extern crate deflate;
#[macro_use]
extern crate futures;
extern crate fut... |
/// Can cancel a future by setting a flag.
///
/// Used to 'watch' the accept futures, and close the listeners
/// as soon as the shutdown signal starts.
struct Cancelable<F> {
future: F,
canceled: bool,
}
impl<F> Future for Cancelable<F>
where
F: Future<Item=()>,
{
type Item = ();
type Error = F... | {
let stack = Arc::new(NewServiceFn::new(move || {
// Clone the router handle
let router = router.clone();
// Map errors to appropriate response error codes.
let map_err = MapErr::new(router, |e| {
match e {
RouteError::Route(r) => {
e... | identifier_body |
lib.rs | #![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))]
#![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))]
#![deny(warnings)]
extern crate bytes;
extern crate conduit_proxy_controller_grpc;
extern crate env_logger;
extern crate deflate;
#[macro_use]
extern crate futures;
extern crate fut... | pub mod ctx;
mod dns;
mod drain;
pub mod fs_watch;
mod inbound;
mod logging;
mod map_err;
mod outbound;
pub mod stream;
pub mod task;
pub mod telemetry;
mod transparency;
mod transport;
pub mod timeout;
mod tower_fn; // TODO: move to tower-fn
mod watch_service; // TODO: move to tower
use bind::Bind;
use conditional::C... | pub mod control;
pub mod convert; | random_line_split |
lib.rs | #![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))]
#![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))]
#![deny(warnings)]
extern crate bytes;
extern crate conduit_proxy_controller_grpc;
extern crate env_logger;
extern crate deflate;
#[macro_use]
extern crate futures;
extern crate fut... | (&self) -> SocketAddr {
self.inbound_listener.local_addr()
}
pub fn outbound_addr(&self) -> SocketAddr {
self.outbound_listener.local_addr()
}
pub fn metrics_addr(&self) -> SocketAddr {
self.metrics_listener.local_addr()
}
pub fn run_until<F>(self, shutdown_signal: F)
... | inbound_addr | identifier_name |
auto_aliasing.go | // Copyright 2016-2023, Pulumi Corporation.
//
// 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... |
func aliasResource(
p *ProviderInfo, res shim.Resource,
applyResourceAliases *[]func(),
hist map[string]*tokenHistory[tokens.Type], computed *ResourceInfo,
tfToken string, version int,
) {
prev, hasPrev := hist[tfToken]
if !hasPrev {
// It's not in the history, so it must be new. Stick it in the history for
... | {
hist, ok, err := md.Get[aliasHistory](artifact, aliasMetadataKey)
if err != nil {
return aliasHistory{}, err
}
if !ok {
hist = aliasHistory{
Resources: map[string]*tokenHistory[tokens.Type]{},
DataSources: map[string]*tokenHistory[tokens.ModuleMember]{},
}
}
return hist, nil
} | identifier_body |
auto_aliasing.go | // Copyright 2016-2023, Pulumi Corporation.
//
// 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... | (schema shim.Schema, h *fieldHistory, info *SchemaInfo) (hasH bool, hasI bool) {
//revive:disable-next-line:empty-block
if schema == nil || (schema.Type() != shim.TypeList && schema.Type() != shim.TypeSet) {
// MaxItemsOne does not apply, so do nothing
} else if info.MaxItemsOne != nil {
// The user has overwrit... | applyMaxItemsOneAliasing | identifier_name |
auto_aliasing.go | // Copyright 2016-2023, Pulumi Corporation.
//
// 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... |
return hist, nil
}
func aliasResource(
p *ProviderInfo, res shim.Resource,
applyResourceAliases *[]func(),
hist map[string]*tokenHistory[tokens.Type], computed *ResourceInfo,
tfToken string, version int,
) {
prev, hasPrev := hist[tfToken]
if !hasPrev {
// It's not in the history, so it must be new. Stick it ... | {
hist = aliasHistory{
Resources: map[string]*tokenHistory[tokens.Type]{},
DataSources: map[string]*tokenHistory[tokens.ModuleMember]{},
}
} | conditional_block |
auto_aliasing.go | // Copyright 2016-2023, Pulumi Corporation.
//
// 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... | // the compilation of programs as the type changes from `T to List[T]` or vice versa. To
// avoid these breaking changes, this method undoes any upstream changes to MaxItems using
// [SchemaInfo.MaxItemsOne] overrides. This happens until a major version change is
// detected, and then overrides are cleared. Effectively... | // [SchemaInfo.MaxItemsOne] changes are also important because they involve flattening and
// pluralizing names. Collections (lists or sets) marked with MaxItems=1 are projected as
// scalar types in Pulumi SDKs. Therefore changes to the MaxItems property may be breaking | random_line_split |
cht.rs | // This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the F... | <N>(cht_size: N, block_num: N) -> Option<N>
where
N: Clone + AtLeast32Bit,
{
let block_cht_num = block_to_cht_number(cht_size.clone(), block_num.clone())?;
let two = N::one() + N::one();
if block_cht_num < two {
return None
}
let cht_start = start_number(cht_size, block_cht_num.clone());
if cht_start != block_... | is_build_required | identifier_name |
cht.rs | // This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the F... |
/// Returns Some(cht_number) if CHT is need to be built when the block with given number is
/// canonized.
pub fn is_build_required<N>(cht_size: N, block_num: N) -> Option<N>
where
N: Clone + AtLeast32Bit,
{
let block_cht_num = block_to_cht_number(cht_size.clone(), block_num.clone())?;
let two = N::one() + N::one(... | {
SIZE.into()
} | identifier_body |
cht.rs | // This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the F... |
let cht_start = start_number(cht_size, block_cht_num.clone());
if cht_start != block_num {
return None
}
Some(block_cht_num - two)
}
/// Returns Some(max_cht_number) if CHT has ever been built given maximal canonical block number.
pub fn max_cht_number<N>(cht_size: N, max_canonical_block: N) -> Option<N>
where... | {
return None
} | conditional_block |
cht.rs | // This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the F... | /// SIZE items. The items are assumed to proceed sequentially from `start_number(cht_num)`.
/// Discards the trie's nodes.
pub fn compute_root<Header, Hasher, I>(
cht_size: Header::Number,
cht_num: Header::Number,
hashes: I,
) -> ClientResult<Hasher::Out>
where
Header: HeaderT,
Hasher: hash_db::Hasher,
Hasher::Ou... | /// Compute a CHT root from an iterator of block hashes. Fails if shorter than | random_line_split |
utils.go | package mysql
import (
"database/sql"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"time"
"unsafe"
"github.com/pingcap/errors"
"github.com/amyangfei/data-dam/pkg/models"
)
const (
queryMaxRetry = 3
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterIdxBits = 6 ... |
defer rows.Close()
rowColumns, err := rows.Columns()
if err != nil {
return errors.Trace(err)
}
// Show an example.
/*
mysql> show index from test.t;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
... | {
return errors.Trace(err)
} | conditional_block |
utils.go | package mysql
import (
"database/sql"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"time"
"unsafe"
"github.com/pingcap/errors"
"github.com/amyangfei/data-dam/pkg/models"
)
const (
queryMaxRetry = 3
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterIdxBits = 6 ... |
func querySQL(db *sql.DB, query string, maxRetry int) (*sql.Rows, error) {
// TODO: add retry mechanism
rows, err := db.Query(query)
if err != nil {
return nil, errors.Trace(err)
}
return rows, nil
}
func getTableFromDB(db *sql.DB, schema string, name string) (*models.Table, error) {
table := &models.Table{}... | {
return strings.Replace(name, "`", "``", -1)
} | identifier_body |
utils.go | package mysql
import (
"database/sql"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"time"
"unsafe"
"github.com/pingcap/errors"
"github.com/amyangfei/data-dam/pkg/models"
)
const (
queryMaxRetry = 3
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterIdxBits = 6 ... | (name string) string {
return strings.Replace(name, "`", "``", -1)
}
func querySQL(db *sql.DB, query string, maxRetry int) (*sql.Rows, error) {
// TODO: add retry mechanism
rows, err := db.Query(query)
if err != nil {
return nil, errors.Trace(err)
}
return rows, nil
}
func getTableFromDB(db *sql.DB, schema st... | escapeName | identifier_name |
utils.go | package mysql
import (
"database/sql"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"time"
"unsafe"
"github.com/pingcap/errors"
"github.com/amyangfei/data-dam/pkg/models"
)
const (
queryMaxRetry = 3
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterIdxBits = 6 ... | if err != nil {
return errors.Trace(err)
}
// Show an example.
/*
mysql> show columns from test.t;
+-------+---------+------+-----+---------+-------------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------------------+
| a ... | defer rows.Close()
rowColumns, err := rows.Columns() | random_line_split |
stimuli_LSL.py | from __future__ import division
import cv2
import numpy as np
# import freenect # only use for debugging
from psychopy import *
import sys, os
from socket import *
from eeg_cnn import *
'''take image segmented by model, pick the right contours (not too small or too big) and calculate theur distance from the camera,... |
sample_tot = np.asarray(sample_tot[:1500]).reshape(1500,len(sample_tot[0]))
sample_tot = np.array([sample_tot]) # format needed for CNN (classification)
chosen_target = classification(sample_tot[0,:,:],0) # runs CNN on sample_tot, returns 0, 1 or 2, second parameter is not used
target_coords = center_coords[c... | sample = s.recv(104)
if len(sample) == 104:
sample = np.fromstring(sample) # recieve array of 13 elements (last 5 are metadata)
sample = sample[:-5]
sample_tot.append(sample)
if len(sample) == 0:
break | conditional_block |
stimuli_LSL.py | from __future__ import division
import cv2
import numpy as np
# import freenect # only use for debugging
from psychopy import *
import sys, os
from socket import *
from eeg_cnn import *
'''take image segmented by model, pick the right contours (not too small or too big) and calculate theur distance from the camera,... | # show targets for 2 second without flickering, to allow user to choose
if rec == 'startstimuli':
# # method 1
# for frameN in range(60):
# img.draw()
# event.clearEvents()
# mywin.flip()
# # draw the stimuli and update the window
# stream = s.recv(10)
# print stream
# for frameN in range(... | rec = s.recv(12)
| random_line_split |
descriptor.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: github.com/containerd/containerd/api/types/descriptor.proto
/*
Package types is a generated protocol buffer package.
It is generated from these files:
github.com/containerd/containerd/api/types/descriptor.proto
github.com/containerd/containerd/api/ty... |
func sovDescriptor(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozDescriptor(x uint64) (n int) {
return sovDescriptor(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *Descriptor) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{... | {
var l int
_ = l
l = len(m.MediaType)
if l > 0 {
n += 1 + l + sovDescriptor(uint64(l))
}
l = len(m.Digest)
if l > 0 {
n += 1 + l + sovDescriptor(uint64(l))
}
if m.Size_ != 0 {
n += 1 + sovDescriptor(uint64(m.Size_))
}
return n
} | identifier_body |
descriptor.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: github.com/containerd/containerd/api/types/descriptor.proto
/*
Package types is a generated protocol buffer package.
It is generated from these files:
github.com/containerd/containerd/api/types/descriptor.proto
github.com/containerd/containerd/api/ty... |
return dAtA[:n], nil
}
func (m *Descriptor) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.MediaType) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintDescriptor(dAtA, i, uint64(len(m.MediaType)))
i += copy(dAtA[i:], m.MediaType)
}
if len(m.Digest) > 0 {
dAtA[i] = 0x12
i++
... | {
return nil, err
} | conditional_block |
descriptor.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: github.com/containerd/containerd/api/types/descriptor.proto
/*
Package types is a generated protocol buffer package.
It is generated from these files:
github.com/containerd/containerd/api/types/descriptor.proto
github.com/containerd/containerd/api/ty... | if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Size_", wireType)
}
m.Size_ = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowDescriptor
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m... | m.Digest = github_com_opencontainers_go_digest.Digest(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3: | random_line_split |
descriptor.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: github.com/containerd/containerd/api/types/descriptor.proto
/*
Package types is a generated protocol buffer package.
It is generated from these files:
github.com/containerd/containerd/api/types/descriptor.proto
github.com/containerd/containerd/api/ty... | (dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowDescriptor
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) ... | skipDescriptor | identifier_name |
main.rs | #![deny(warnings)]
#![deny(missing_docs)]
//! Command line tool for modifying hosts file on Linux/UNIX to change static hostname-IP mappings.
//!
//! Intended to be run with the suid bit set, so unprivileged users may update the hosts file. This
//! allow easy integration for jobs like updating entries after launching ... |
}
panic!("found_post != found_pre");
}
}
if opts.dry_run || opts.verbose {
println!("generated:\n>>>\n{}<<<", &buf_generate);
}
if opts.dry_run {
println!("DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN");... | {
eprintln!("Difference: {:?}", DONT_TOUCH[i])
} | conditional_block |
main.rs | #![deny(warnings)]
#![deny(missing_docs)]
//! Command line tool for modifying hosts file on Linux/UNIX to change static hostname-IP mappings.
//!
//! Intended to be run with the suid bit set, so unprivileged users may update the hosts file. This
//! allow easy integration for jobs like updating entries after launching ... |
fn generate_hosts_file(len_content: usize, parsed: &Vec<HostsPart>) -> String {
let mut buf_generate = String::with_capacity(len_content);
// eprintln!("rendering: {:?}", parsed);
fn render_entry<'a>(
buf_generate: &mut String,
ip: &IpAddr,
hosts: &Vec<Cow<'a, str>>,
opt_... | {
'loop_actions: for action in &opts.actions {
match action {
Action::Define(ip, host) => {
if !config.whitelist.contains(host) {
return Err(format!("HOST {:?} not whitelisted!", host));
}
// eprintln!("defining additionally...:... | identifier_body |
main.rs | #![deny(warnings)]
#![deny(missing_docs)]
//! Command line tool for modifying hosts file on Linux/UNIX to change static hostname-IP mappings.
//!
//! Intended to be run with the suid bit set, so unprivileged users may update the hosts file. This
//! allow easy integration for jobs like updating entries after launching ... | // eprintln!("matching entry: {:?}", part);
let matches_hostname = part.matches_hostname(host);
if part.matches_ip(ip) && matches_hostname {
// eprintln!("already defined, NOP");
//opt_insert = None;
... | .enumerate()
.filter(|(_i, p)| p.matches_ip(ip) || p.matches_hostname(host))
{ | random_line_split |
main.rs | #![deny(warnings)]
#![deny(missing_docs)]
//! Command line tool for modifying hosts file on Linux/UNIX to change static hostname-IP mappings.
//!
//! Intended to be run with the suid bit set, so unprivileged users may update the hosts file. This
//! allow easy integration for jobs like updating entries after launching ... | <'a>(
buf_generate: &mut String,
ip: &IpAddr,
hosts: &Vec<Cow<'a, str>>,
opt_comment: &Option<Cow<'a, str>>,
) {
use std::fmt::Write;
write!(buf_generate, "{:20}\t", ip).expect("unable to format entry IP address");
let max = hosts.iter().count() - 1;
... | render_entry | identifier_name |
game.rs | use world::World;
use piston_window::*;
use camera::Camera;
use cgmath::{Vector2, vec3};
use cgmath::prelude::*;
use color::*;
use car::*;
use piston_window::Ellipse;
use bot::BoxRules;
use std::cell::RefCell;
use std::ops::DerefMut;
use std::time::Instant;
// `Game` contains every things to run the game
pub struct Ga... |
fn draw(&mut self, e: &Input) {
// Return a horizontal bar
macro_rules! bar {
($curr: expr, $full: expr) => {
[0.,
15.0,
self.config.screen_size.w as f64/2.*$curr/$full,
20.0,]
};
}
let jump_bar ... | {
match key {
Button::Keyboard(Key::A) => if let Turn::Left = self.state.turn {
self.state.turn = Turn::None;
},
Button::Keyboard(Key::D) => if let Turn::Right = self.state.turn {
self.state.turn = Turn::None;
},
Button:... | identifier_body |
game.rs | use world::World;
use piston_window::*;
use camera::Camera;
use cgmath::{Vector2, vec3};
use cgmath::prelude::*;
use color::*;
use car::*;
use piston_window::Ellipse;
use bot::BoxRules;
use std::cell::RefCell;
use std::ops::DerefMut;
use std::time::Instant;
// `Game` contains every things to run the game
pub struct Ga... | <T: Car>(config: &GameConfig, player: &T) -> Camera {
Camera::new(
config.screen_size.clone(),
vec3(0., config.camera_height, -config.camera_distance) + player.pos()
)
}
// Re-calculate fps
fn update_fps(&mut self) {
let d = self.state.last_frame.elapsed();
... | new_camera | identifier_name |
game.rs | use world::World;
use piston_window::*;
use camera::Camera;
use cgmath::{Vector2, vec3};
use cgmath::prelude::*;
use color::*;
use car::*;
use piston_window::Ellipse;
use bot::BoxRules;
use std::cell::RefCell;
use std::ops::DerefMut;
use std::time::Instant;
// `Game` contains every things to run the game
pub struct Ga... | self.world.player.speed += dt*self.config.sprint_factor;
}
} else if self.world.player.speed > self.config.player_speed.0 {
self.world.player.speed -= dt*self.config.sprint_factor;
}
self.state.spawn -= dt;
if self.state.spawn < 0. {
se... | }
if self.state.sprint {
if self.world.player.speed < self.config.player_speed.1 { | random_line_split |
graph.rs | use crate::{CommandEncoder, CommandEncoderOutput};
use generational_arena::Arena;
use moonwave_resources::{BindGroup, Buffer, ResourceRc, SampledTexture, TextureView};
use multimap::MultiMap;
use parking_lot::{RwLock, RwLockReadGuard};
use rayon::{prelude::*, ThreadPool};
use std::{
collections::HashMap,
fmt::{Debu... | optick::tag!("level", level as u32);
// Get rid of duplicated nodes.
let mut nodes_in_level = self.levels_map.get_vec_mut(&level).unwrap().clone();
nodes_in_level.sort_unstable_by_key(|x| x.index);
nodes_in_level.dedup_by_key(|x| x.index);
// Build cache for this level
... | optick::event!("FrameGraph::execute_level"); | random_line_split |
graph.rs | use crate::{CommandEncoder, CommandEncoderOutput};
use generational_arena::Arena;
use moonwave_resources::{BindGroup, Buffer, ResourceRc, SampledTexture, TextureView};
use multimap::MultiMap;
use parking_lot::{RwLock, RwLockReadGuard};
use rayon::{prelude::*, ThreadPool};
use std::{
collections::HashMap,
fmt::{Debu... | {
node_arena: RwLock<Arena<ConnectedNode>>,
edges_arena: RwLock<Arena<ConnectedEdges>>,
end_node: Index,
output_map: Vec<Vec<Option<FrameNodeValue>>>,
levels_map: MultiMap<usize, TraversedGraphNode>,
traversed_node_cache: HashMap<Index, usize>,
}
impl FrameGraph {
/// Creates a new empty graph.
pub fn... | FrameGraph | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.