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 |
|---|---|---|---|---|
sevencow.py | # -*- coding: utf-8 -*-
import os
import hmac
import time
import json
import mimetypes
import functools
from urlparse import urlparse
from urllib import urlencode
from base64 import urlsafe_b64encode
from hashlib import sha1
import requests
version_info = (0, 1, 2)
VERSION = __version__ = '.'.join( map(str, version_... |
self.stat = functools.partial(self._stat_rm_handler, 'stat')
self.delete = functools.partial(self._stat_rm_handler, 'delete')
self.copy = functools.partial(self._cp_mv_handler, 'copy')
self.move = functools.partial(self._cp_mv_handler, 'move')
def get_bucket(self, bucket):
... | self.upload_tokens = {} | random_line_split |
sevencow.py | # -*- coding: utf-8 -*-
import os
import hmac
import time
import json
import mimetypes
import functools
from urlparse import urlparse
from urllib import urlencode
from base64 import urlsafe_b64encode
from hashlib import sha1
import requests
version_info = (0, 1, 2)
VERSION = __version__ = '.'.join( map(str, version_... | ucket, args[0])
@transform_argument
def delete(self, *args):
return self.cow.delete(self.bucket, args[0])
@transform_argument
def copy(self, *args):
return self.cow.copy(self._build_cp_mv_args(args[0]))
@transform_argument
def move(self, *args):
return self.cow... | identifier_body | |
sevencow.py | # -*- coding: utf-8 -*-
import os
import hmac
import time
import json
import mimetypes
import functools
from urlparse import urlparse
from urllib import urlencode
from base64 import urlsafe_b64encode
from hashlib import sha1
import requests
version_info = (0, 1, 2)
VERSION = __version__ = '.'.join( map(str, version_... | = '%s/upload' % UP_HOST
token = self.generate_upload_token(scope)
names = names or {}
def _uploaded_name(filename):
return names.get(filename, None) or os.path.basename(filename)
def _put(filename):
files = {
'file': (filename, open(filen... | rl | identifier_name |
class_vertice_graph.py | """ The goal of this file is to have all the information on a graph. """
import sys, os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
import numpy as np
import matplotlib.pyplot as plt
import copy
i... | (self, edges_list):
""" An element of edges_list is an edge """
for e in edges_list:
exceptions.check_pertinent_edge(self, e)
self._edges_list = edges_list
def neighbours_list(self, list_tuple, id=0):
self._edges_list.clear()
"""interface with old constructor , t... | edges_list | identifier_name |
class_vertice_graph.py | """ The goal of this file is to have all the information on a graph. """
import sys, os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
import numpy as np
import matplotlib.pyplot as plt
import copy
i... | self.number_of_edges=0
def push_diplayable_edge(self,bidim_array):
self.connection_table_edge_and_diplayable_edge.append(copy.deepcopy(bidim_array))
self.number_of_disp_edges+=1
def push_edge(self,e):
self.number_of_edges+=1
self.list_of_edges.append(e)
def push_edg... | self.number_of_vertices = len(list_of_vertices)
self.connection_table_edge_and_diplayable_edge=[]
self.list_of_edges=[]
self.number_of_disp_edges=0 | random_line_split |
class_vertice_graph.py | """ The goal of this file is to have all the information on a graph. """
import sys, os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
import numpy as np
import matplotlib.pyplot as plt
import copy
i... |
if not non_oriented:
if (vertice, edge.linked[1]) not in pairs_of_vertices:
pairs_of_vertices.append((vertice, edge.linked[1]))
return pairs_of_vertices
def number_of_edges(self):
a=self.pairs_of_vertices()
assert self.number_of_e... | pairs_of_vertices.append((vertice, edge.linked[1])) | conditional_block |
class_vertice_graph.py | """ The goal of this file is to have all the information on a graph. """
import sys, os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
import numpy as np
import matplotlib.pyplot as plt
import copy
i... |
def is_vertice_in_graph_based_on_xy_with_tolerance(self, vertice, epsilon):
for i in range(self.number_of_vertices):
v = self.list_of_vertices[i]
if ((v.coordinates[0] - vertice.coordinates[0])**2) + ((v.coordinates[1] - vertice.coordinates[1])**2) < epsilon:
return... | for i in range(self.number_of_vertices):
v = self.list_of_vertices[i]
if v.coordinates[0] == vertice.coordinates[0] and v.coordinates[1] == vertice.coordinates[1]:
return True,i
return False,None | identifier_body |
build.rs | #[cfg(not(feature = "binary"))]
fn main() {}
#[cfg(feature = "binary")]
fn main() {
binary::main();
}
#[cfg(feature = "binary")]
mod binary {
use quote::quote;
use std::convert::TryInto;
pub fn main() {
use llvm_tools_build as llvm_tools;
use std::{
env,
fs::{s... |
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set"));
let kernel = PathBuf::from(match env::var("KERNEL") {
Ok(kernel) => kernel,
Err(_) => {
eprintln!(
"The KERNEL environment variable must be set for building the bootl... | {
panic!(
"The {} bootloader must be compiled for the `{}` target.",
firmware, expected_target,
);
} | conditional_block |
build.rs | #[cfg(not(feature = "binary"))]
fn main() {}
#[cfg(feature = "binary")]
fn main() {
binary::main();
}
#[cfg(feature = "binary")]
mod binary {
use quote::quote;
use std::convert::TryInto;
pub fn main() {
use llvm_tools_build as llvm_tools;
use std::{
env,
fs::{s... | ;
impl serde::de::Visitor<'_> for AlignedAddressVisitor {
type Value = AlignedAddress;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
formatter,
"a page-aligned memory address, either as integer or as decimal or he... | AlignedAddressVisitor | identifier_name |
build.rs | #[cfg(not(feature = "binary"))]
fn main() {}
#[cfg(feature = "binary")]
fn main() {
binary::main();
}
#[cfg(feature = "binary")]
mod binary {
use quote::quote;
use std::convert::TryInto;
pub fn main() {
use llvm_tools_build as llvm_tools;
use std::{
env,
fs::{s... | // Parse configuration from the kernel's Cargo.toml
let config = match env::var("KERNEL_MANIFEST") {
Err(env::VarError::NotPresent) => {
panic!("The KERNEL_MANIFEST environment variable must be set for building the bootloader.\n\n\
Please use `cargo builder` ... | kernel_file_name
);
}
| random_line_split |
state.rs | use std::collections::HashMap;
use num_traits::{AsPrimitive, Float};
use sdl2::{
keyboard::Keycode,
pixels::Color,
rect::{Point, Rect},
render::Canvas,
video::Window,
};
use crate::{
ext::ColorExt, key_state_handler::KeyStateHandler, map::Map, math::vector::Vec2D,
WINDOW_HEIGHT, WINDOW_WID... |
pub fn mouse_motion(&mut self, dx: i32) {
self.angle += MOUSE_SENSITIVITY * dx as f64;
}
fn calculate_collisions(&mut self) {
let mut current_angle = self.angle - (self.fov.to_radians() / 2.);
let end_angle = current_angle + (self.radian_per_column * self.resolution as f64);
... | {
self.wall_colors.get(index).copied().unwrap_or(Color::WHITE)
} | identifier_body |
state.rs | use std::collections::HashMap;
use num_traits::{AsPrimitive, Float};
use sdl2::{
keyboard::Keycode,
pixels::Color,
rect::{Point, Rect},
render::Canvas,
video::Window,
};
use crate::{
ext::ColorExt, key_state_handler::KeyStateHandler, map::Map, math::vector::Vec2D,
WINDOW_HEIGHT, WINDOW_WID... | pub fn update(&mut self) {
self.update_camera();
self.calculate_collisions();
}
pub fn draw_minimap(
&self,
canvas: &mut Canvas<Window>,
dims: (f64, f64),
) -> Result<(), String> {
let minimap_offset = (dims.0.max(dims.1) / 4.);
let minimap_base =... |
self.position.add_x_y_raw(delta.x_y());
self.position.clamp(self.map.dims, PLAYER_WALL_PADDING);
}
| random_line_split |
state.rs | use std::collections::HashMap;
use num_traits::{AsPrimitive, Float};
use sdl2::{
keyboard::Keycode,
pixels::Color,
rect::{Point, Rect},
render::Canvas,
video::Window,
};
use crate::{
ext::ColorExt, key_state_handler::KeyStateHandler, map::Map, math::vector::Vec2D,
WINDOW_HEIGHT, WINDOW_WID... |
}
if max_height.is_infinite() {
self.columns.push((0, 0));
} else {
self.columns
.push((wall_color_index, max_height.round() as u32));
}
current_angle += self.radian_per_column;
}
}
fn upda... | {
let raw_distance = ray.dist(&intersection_vector);
let delta = current_angle - self.angle;
let corrected_distance = raw_distance * (delta.cos() as f64);
let projected_height = self.projection_factor / corrected_distance;
... | conditional_block |
state.rs | use std::collections::HashMap;
use num_traits::{AsPrimitive, Float};
use sdl2::{
keyboard::Keycode,
pixels::Color,
rect::{Point, Rect},
render::Canvas,
video::Window,
};
use crate::{
ext::ColorExt, key_state_handler::KeyStateHandler, map::Map, math::vector::Vec2D,
WINDOW_HEIGHT, WINDOW_WID... | (&self, canvas: &mut Canvas<Window>) -> Result<(), String> {
self.render_frame(canvas)?;
self.draw_minimap(canvas, (WINDOW_WIDTH as f64 / 5., WINDOW_WIDTH as f64 / 5.))?;
Ok(())
}
}
| draw | identifier_name |
opdb.rs | /*
@author: xiao cai niao
@datetime: 2019/11/6
*/
use actix_web::{web};
use crate::webroute::route::{HostInfo, PostUserInfo, EditInfo, EditMainTain};
use crate::storage::rocks::{DbInfo, KeyValue, CfNameTypeCode, PrefixTypeCode};
use crate::ha::procotol::{DownNodeCheck, RecoveryInfo, ReplicationState, MysqlMonitorStatus... | pub cluster_name: String,
pub delay: usize
}
impl SlaveBehindSetting{
pub fn new(cluster_name: &String) -> SlaveBehindSetting {
SlaveBehindSetting{ cluster_name: cluster_name.clone(), delay: 100 }
}
pub fn save(&self, db: &web::Data<DbInfo>) -> Result<(), Box<dyn Error>>{
db.prefix_put... | eCode::NodesState.get())?;
Ok(())
}
}
///
///
/// slave behind 配置结构体
#[derive(Serialize, Deserialize, Debug)]
pub struct SlaveBehindSetting{
| conditional_block |
opdb.rs | /*
@author: xiao cai niao
@datetime: 2019/11/6
*/
use actix_web::{web};
use crate::webroute::route::{HostInfo, PostUserInfo, EditInfo, EditMainTain};
use crate::storage::rocks::{DbInfo, KeyValue, CfNameTypeCode, PrefixTypeCode};
use crate::ha::procotol::{DownNodeCheck, RecoveryInfo, ReplicationState, MysqlMonitorStatus... | ata: web::Data<DbInfo>, info: &web::Json<HostInfo>) -> Result<(), Box<dyn Error>> {
let check_unique = data.get(&info.host, &CfNameTypeCode::HaNodesInfo.get());
match check_unique {
Ok(v) => {
if v.value.len() > 0 {
let a = format!("this key: ({}) already exists in the databa... | sert_mysql_host_info(d | identifier_name |
opdb.rs | /*
@author: xiao cai niao
@datetime: 2019/11/6
*/
use actix_web::{web};
use crate::webroute::route::{HostInfo, PostUserInfo, EditInfo, EditMainTain};
use crate::storage::rocks::{DbInfo, KeyValue, CfNameTypeCode, PrefixTypeCode};
use crate::ha::procotol::{DownNodeCheck, RecoveryInfo, ReplicationState, MysqlMonitorStatus... | }
self.update_time = crate::timestamp();
}
///
/// 获取当前节点在db中保存的状态信息
pub fn get_state(&self, db: &web::Data<DbInfo>) -> Result<MysqlState, Box<dyn Error>> {
let kv = db.get(&self.host, &CfNameTypeCode::NodesState.get())?;
if kv.value.len() > 0 {
let state: My... | if info.maintain == "true".to_string() {
self.maintain = false;
}else {
self.maintain = true; | random_line_split |
opdb.rs | /*
@author: xiao cai niao
@datetime: 2019/11/6
*/
use actix_web::{web};
use crate::webroute::route::{HostInfo, PostUserInfo, EditInfo, EditMainTain};
use crate::storage::rocks::{DbInfo, KeyValue, CfNameTypeCode, PrefixTypeCode};
use crate::ha::procotol::{DownNodeCheck, RecoveryInfo, ReplicationState, MysqlMonitorStatus... | ult 3306
pub rtype: String, //db、route
pub cluster_name: String, //集群名称,route类型默认default
pub online: bool, //db是否在线, true、false
pub insert_time: i64,
pub update_time: i64,
pub maintain: bool, //是否处于维护模式,true、false
}
impl HostInfoValue {
pub fn new(info: &HostInfo) -> Result<HostInfoVal... | o.password.clone(),
hook_id: rand_string(),
create_time,
update_time
}
}
}
///
///
///
/// 节点基础信息, host做为key
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HostInfoValue {
pub host: String, //127.0.0.1:3306
pub dbport: usize, //defa | identifier_body |
server_impl.go | // Contains the implementation of a LSP server.
package lsp
import "errors"
import "strconv"
import "github.com/cmu440/lspnet"
import "container/list"
import "encoding/json"
import "fmt"
import "time"
type msgPackage struct {
msg *Message
addr *lspnet.UDPAddr
}
type abstractClient struct {
addr *lspnet.... |
func (s *server) sendData(dataMsg *Message) {
s.writeToClientChan <- dataMsg
}
func (s *server) addEpochNum() {
for connId, c := range s.clients {
c.epochNum += 1
if c.epochNum >= s.epochLimit {
c.lostConn = true
s.sendDeadMsg(connId)
}
}
}
func (s *server) sendDeadMsg(connId int) {
dataMsg := NewDa... | {
//////fmt.Println(connID)
client := s.clients[connID]
dataMsg := NewData(connID, client.nextSN, payload, payload)
////fmt.Println("Server: 197 write ", dataMsg)
go s.sendData(dataMsg)
client.nextSN += 1
return nil
} | identifier_body |
server_impl.go | // Contains the implementation of a LSP server.
package lsp
import "errors"
import "strconv"
import "github.com/cmu440/lspnet"
import "container/list"
import "encoding/json"
import "fmt"
import "time"
type msgPackage struct {
msg *Message
addr *lspnet.UDPAddr
}
type abstractClient struct {
addr *lspnet.... |
// create ack message
connID := msg.ConnID
seqNum := msg.SeqNum
ack := NewAck(connID, seqNum)
// check the receive variables in client
// delete the message in mapreceived
if msg.SeqNum == c.nextSmallestData {
c.nextSmallestData += 1
for c.mapReceived[c.nextSmallestData] != nil {
delete(c.mapReceived,... | {
s.readList.PushBack(msg)
} | conditional_block |
server_impl.go | // Contains the implementation of a LSP server.
package lsp
import "errors"
import "strconv"
import "github.com/cmu440/lspnet"
import "container/list"
import "encoding/json"
import "fmt"
import "time"
type msgPackage struct {
msg *Message
addr *lspnet.UDPAddr
}
type abstractClient struct {
addr *lspnet.... | () error {
return errors.New("text")
//fmt.Println("server: server close !!!!!!!!!!!!!!!!!!!!!!!!!!!!")
s.writeFinished <- 0
//fmt.Println("Server: finish wirte1")
<-s.writeFinished
//fmt.Println("Server: finish wirte")
/*s.ackFinished <- 0
<-s.ackFinished*/
//fmt.Println("Server: finish ack")
s.closeEpoch <... | Close | identifier_name |
server_impl.go | // Contains the implementation of a LSP server.
package lsp
import "errors"
import "strconv"
import "github.com/cmu440/lspnet"
import "container/list"
import "encoding/json"
import "fmt"
import "time"
type msgPackage struct {
msg *Message
addr *lspnet.UDPAddr
}
type abstractClient struct {
addr *lspnet.... | if s.waitToWriteFinish && s.writeList.Len() == 0 {
s.writeFinished <- 1
s.waitToWriteFinish = false
}
case <-s.readRequest.ask:
s.handleReadRequest()
case payload := <-s.writeRequest.ask:
connId := <-s.writeRequest.connId
var response = s.handleWriteRequest(connId, payload)
s.writeRequest.... | // ack/conn type: don't need to consider order
s.writeToClient(msg)
}
| random_line_split |
simulation.py | """Assignment 1 - Simulation
=== CSC148 Fall 2017 ===
Diane Horton and David Liu
Department of Computer Science,
University of Toronto
=== Module Description ===
This file contains the Simulation class, which is the main class for your
bike-share simulation.
At the bottom of the file, there is a sample_simulation ... |
def _update_active_rides_fast(self, time: datetime) -> None:
"""Update this simulation's list of active rides for the given time.
REQUIRED IMPLEMENTATION NOTES:
- see Task 5 of the assignment handout
"""
pass
def create_stations(stations_file: str) -> Dict[str, 'Statio... | """Return a dictionary containing statistics for this simulation.
The returned dictionary has exactly four keys, corresponding
to the four statistics tracked for each station:
- 'max_start'
- 'max_end'
- 'max_time_low_availability'
- 'max_time_low_unoccupied'
... | identifier_body |
simulation.py | """Assignment 1 - Simulation
=== CSC148 Fall 2017 ===
Diane Horton and David Liu
Department of Computer Science,
University of Toronto
=== Module Description ===
This file contains the Simulation class, which is the main class for your
bike-share simulation.
At the bottom of the file, there is a sample_simulation ... | :
"""Runs the core of the simulation through time.
=== Attributes ===
all_rides:
A list of all the rides in this simulation.
Note that not all rides might be used, depending on the timeframe
when the simulation is run.
all_stations:
A dictionary containing all the statio... | Simulation | identifier_name |
simulation.py | """Assignment 1 - Simulation
=== CSC148 Fall 2017 ===
Diane Horton and David Liu
Department of Computer Science,
University of Toronto
=== Module Description ===
This file contains the Simulation class, which is the main class for your
bike-share simulation.
At the bottom of the file, there is a sample_simulation ... | 'max_end': ('', -1),
'max_time_low_availability': ('', -1),
'max_time_low_unoccupied': ('', -1)
}
def _update_active_rides_fast(self, time: datetime) -> None:
"""Update this simulation's list of active rides for the given time.
REQUIRED IMPLEMENTATION NO... | 'max_start': ('', -1), | random_line_split |
simulation.py | """Assignment 1 - Simulation
=== CSC148 Fall 2017 ===
Diane Horton and David Liu
Department of Computer Science,
University of Toronto
=== Module Description ===
This file contains the Simulation class, which is the main class for your
bike-share simulation.
At the bottom of the file, there is a sample_simulation ... |
def _update_active_rides(self, time: datetime) -> None:
"""Update this simulation's list of active rides for the given time.
REQUIRED IMPLEMENTATION NOTES:
- Loop through `self.all_rides` and compare each Ride's start and
end times with <time>.
If <time> is betw... | if self.visualizer.handle_window_events():
return # Stop the simulation | conditional_block |
conn.rs | // Copyright 2016 The Grin Developers
//
// 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 agree... | <W: ser::Writeable>(&self, t: Type, body: &W) -> Result<(), Error> {
let mut body_data = vec![];
try!(ser::serialize(&mut body_data, body));
let mut data = vec![];
try!(ser::serialize(
&mut data,
&MsgHeader::new(t, body_data.len() as u64),
));
data.append(&mut body_data);
self.outbound_chan
.unb... | send_msg | identifier_name |
conn.rs | // Copyright 2016 The Grin Developers
//
// 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 agree... | let (conn, fut) = Connection::listen(conn, move |sender, header: MsgHeader, data| {
let msg_type = header.msg_type;
let recv_h = try!(handler.handle(sender, header, data));
let mut expects = exp.lock().unwrap();
let filtered = expects
.iter()
.filter(|&&(typ, h, _): &&(Type, Option<Hash>, Instant... | // Decorates the handler to remove the "subscription" from the expected
// responses. We got our replies, so no timeout should occur.
let exp = expects.clone(); | random_line_split |
conn.rs | // Copyright 2016 The Grin Developers
//
// 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 agree... |
}
/// A higher level connection wrapping the TcpStream. Maintains the amount of
/// data transmitted and deals with the low-level task of sending and
/// receiving data, parsing message headers and timeouts.
#[allow(dead_code)]
pub struct Connection {
// Channel to push bytes to the remote peer
outbound_chan: Unbou... | {
self(sender, header, body)
} | identifier_body |
conn.rs | // Copyright 2016 The Grin Developers
//
// 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 agree... |
Ok(reader)
})
});
Box::new(read_msg)
}
/// Utility function to send any Writeable. Handles adding the header and
/// serialization.
pub fn send_msg<W: ser::Writeable>(&self, t: Type, body: &W) -> Result<(), Error> {
let mut body_data = vec![];
try!(ser::serialize(&mut body_data, body));
let mu... | {
debug!(LOGGER, "Invalid {:?} message: {}", msg_type, e);
return Err(Error::Serialization(e));
} | conditional_block |
dpkg_install.go | package main
import (
"archive/tar"
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/blakesmith/ar"
"github.com/julien-sobczak/deb822"
)
func main() {
// This program expects one or more package files to install.
if len(os.Args) < 2 {
log.Fatalf("Missing package archive(s)... | (filename string) string {
return filepath.Join("/var/lib/dpkg", p.Name()+"."+filename)
}
// We now add a method to change the package status
// and make sure the section in the status file is updated too.
// This method will be used several times at the different steps
// of the installation process.
func (p *Packa... | InfoPath | identifier_name |
dpkg_install.go | package main
import (
"archive/tar"
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/blakesmith/ar"
"github.com/julien-sobczak/deb822"
)
func main() {
// This program expects one or more package files to install.
if len(os.Args) < 2 {
log.Fatalf("Missing package archive(s)... |
/* Utility functions */
func ReadLines(path string) ([]string, error) {
if _, err := os.Stat(path); !os.IsNotExist(err) {
content, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return SplitLines(string(content)), nil
}
return nil, nil
}
func SplitLines(content string) []string {
var line... | {
// This function synchronizes the files under /var/lib/dpkg/info
// for a single package.
// Write <package>.list
if err := os.WriteFile(p.InfoPath("list"),
[]byte(MergeLines(p.Files)), 0644); err != nil {
return err
}
// Write <package>.conffiles
if err := os.WriteFile(p.InfoPath("conffiles"),
[]byte(... | identifier_body |
dpkg_install.go | package main
import (
"archive/tar"
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/blakesmith/ar"
"github.com/julien-sobczak/deb822"
)
func main() {
// This program expects one or more package files to install.
if len(os.Args) < 2 {
log.Fatalf("Missing package archive(s)... | var bufControl bytes.Buffer
io.Copy(&bufControl, reader)
pkg, err := parseControl(db, bufControl)
if err != nil {
return err
}
// Add the new package in the database
db.Packages = append(db.Packages, pkg)
db.Sync()
// data.tar
reader.Next()
var bufData bytes.Buffer
io.Copy(&bufData, reader)
fmt.Print... |
// control.tar
reader.Next() | random_line_split |
dpkg_install.go | package main
import (
"archive/tar"
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/blakesmith/ar"
"github.com/julien-sobczak/deb822"
)
func main() {
// This program expects one or more package files to install.
if len(os.Args) < 2 {
log.Fatalf("Missing package archive(s)... |
// Add the new package in the database
db.Packages = append(db.Packages, pkg)
db.Sync()
// data.tar
reader.Next()
var bufData bytes.Buffer
io.Copy(&bufData, reader)
fmt.Printf("Preparing to unpack %s ...\n", filepath.Base(archivePath))
if err := pkg.Unpack(bufData); err != nil {
return err
}
if err :=... | {
return err
} | conditional_block |
clarans.py | """!
@brief Cluster analysis algorithm: CLARANS.
@details Implementation based on paper @cite article::clarans::1.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2019
@copyright GNU Public License
@cond GNU_PUBLIC_LICENSE
PyClustering is free software: you can redistribute it and/or modify... |
def __calculate_estimation(self):
"""!
@brief Calculates estimation (cost) of the current clusters. The lower the estimation,
the more optimally configuration of clusters.
@return (double) estimation of current clusters.
"""
estimation = 0.0
... | """!
@brief Finds the another nearest medoid for the specified point that is different from the specified medoid.
@param[in] point_index: index of point in dataspace for that searching of medoid in current list of medoids is perfomed.
@param[in] current_medoid_index: index of medoid that sh... | identifier_body |
clarans.py | """!
@brief Cluster analysis algorithm: CLARANS.
@details Implementation based on paper @cite article::clarans::1.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2019
@copyright GNU Public License
@cond GNU_PUBLIC_LICENSE
PyClustering is free software: you can redistribute it and/or modify... |
# case 2:
else:
candidate_cost += distance_candidate - distance_current
elif (point_cluster_index == other_medoid_cluster_index):
# case 3 ('nearest medoid' is the representative object of t... | candidate_cost += distance_nearest - distance_current | conditional_block |
clarans.py | """!
@brief Cluster analysis algorithm: CLARANS.
@details Implementation based on paper @cite article::clarans::1.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2019
@copyright GNU Public License
@cond GNU_PUBLIC_LICENSE
PyClustering is free software: you can redistribute it and/or modify... | (self):
"""!
@brief Returns allocated clusters by the algorithm.
@remark Allocated clusters can be returned only after data processing (use method process()), otherwise empty list is returned.
@return (list) List of allocated clusters, each cluster contains indexes of objects in ... | get_clusters | identifier_name |
clarans.py | """!
@brief Cluster analysis algorithm: CLARANS.
@details Implementation based on paper @cite article::clarans::1.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2019
@copyright GNU Public License
@cond GNU_PUBLIC_LICENSE
PyClustering is free software: you can redistribute it and/or modify... |
@see get_clusters()
@see get_medoids()
"""
random.seed()
# loop for a numlocal number of times
for _ in range(0, self.__numlocal):
print("numlocal: ", _)
# set (current) random medoids
self.__current = random.sample(ra... | def process(self, plotting=False):
"""!
@brief Performs cluster analysis in line with rules of CLARANS algorithm.
@return (clarans) Returns itself (CLARANS instance).
| random_line_split |
client.rs | use std::thread;
use std::net::SocketAddr;
use std::net::ToSocketAddrs;
use std::sync::mpsc;
use std::sync::Arc;
use futures;
use futures::Future;
use futures::stream::Stream;
use tokio_core;
use tokio_core::reactor;
use solicit::http::HttpScheme;
use solicit::http::HttpError;
use solicit::http::Header;
use solicit:... |
fn data_frame(&mut self, chunk: Vec<u8>) -> bool {
self.tr.data_frame(chunk)
}
fn trailers(&mut self, headers: Vec<StaticHeader>) -> bool {
self.tr.trailers(headers)
}
fn end(&mut self) {
self.tr.end()
}
}
// Data sent from event loop to GrpcClient
struct LoopToClien... | } | random_line_split |
client.rs | use std::thread;
use std::net::SocketAddr;
use std::net::ToSocketAddrs;
use std::sync::mpsc;
use std::sync::Arc;
use futures;
use futures::Future;
use futures::stream::Stream;
use tokio_core;
use tokio_core::reactor;
use solicit::http::HttpScheme;
use solicit::http::HttpError;
use solicit::http::Header;
use solicit:... | <Req : Send + 'static, Resp : Send + 'static>(&self, req: GrpcStreamSend<Req>, method: Arc<MethodDescriptor<Req, Resp>>)
-> GrpcFutureSend<Resp>
{
stream_single_send(self.call_impl(req, method))
}
pub fn call_bidi<Req : Send + 'static, Resp : Send + 'static>(&self, req: GrpcStreamSend<Req>,... | call_client_streaming | identifier_name |
client.rs | use std::thread;
use std::net::SocketAddr;
use std::net::ToSocketAddrs;
use std::sync::mpsc;
use std::sync::Arc;
use futures;
use futures::Future;
use futures::stream::Stream;
use tokio_core;
use tokio_core::reactor;
use solicit::http::HttpScheme;
use solicit::http::HttpError;
use solicit::http::Header;
use solicit:... |
}
// Event loop entry point
fn run_client_event_loop(
socket_addr: SocketAddr,
send_to_back: mpsc::Sender<LoopToClient>)
{
// Create an event loop.
let mut lp = reactor::Core::new().unwrap();
// Create a channel to receive shutdown signal.
let (shutdown_tx, shutdown_rx) = tokio_core::channel... | {
// ignore error because even loop may be already dead
self.loop_to_client.shutdown_tx.send(()).ok();
// do not ignore errors because we own event loop thread
self.thread_join_handle.take().expect("handle.take")
.join().expect("join thread");
} | identifier_body |
fixed.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | <T>(_col: &PrimitiveArray<T>) -> usize
where
T: ArrowPrimitiveType,
T::Native: FixedLengthEncoding,
{
T::Native::ENCODED_LEN
}
/// Fixed width types are encoded as
///
/// - 1 byte `0` if null or `1` if valid
/// - bytes of [`FixedLengthEncoding`]
pub fn encode<T: FixedLengthEncoding, I: IntoIterator<Item ... | encoded_len | identifier_name |
fixed.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
fn encode(self) -> [u8; 8] {
// https://github.com/rust-lang/rust/blob/9c20b2a8cc7588decb6de25ac6a7912dcef24d65/library/core/src/num/f32.rs#L1176-L1260
let s = self.to_bits() as i64;
let val = s ^ (((s >> 63) as u64) >> 1) as i64;
val.encode()
}
fn decode(encoded: Self::Enc... | impl FixedLengthEncoding for f64 {
type Encoded = [u8; 8]; | random_line_split |
fixed.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
to_write[1..].copy_from_slice(encoded.as_ref())
} else {
data[*offset] = null_sentinel(opts);
}
*offset = end_offset;
}
}
pub fn encode_fixed_size_binary(
data: &mut [u8],
offsets: &mut [usize],
array: &FixedSizeBinaryArray,
opts: SortOptions,
) {
... | {
// Flip bits to reverse order
encoded.as_mut().iter_mut().for_each(|v| *v = !*v)
} | conditional_block |
fixed.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
fn decode(encoded: Self::Encoded) -> Self {
encoded[0] != 0
}
}
macro_rules! encode_signed {
($n:expr, $t:ty) => {
impl FixedLengthEncoding for $t {
type Encoded = [u8; $n];
fn encode(self) -> [u8; $n] {
let mut b = self.to_be_bytes();
... | {
[self as u8]
} | identifier_body |
pop.py | import math
from historia.utils import unique_id, position_in_range
from historia.pops.models.inventory import Inventory
from historia.economy.enums.resource import Good, NaturalResource
from historia.economy.enums.order_type import OrderType
from historia.economy.models.price_range import PriceRange
from historia.econ... | (self, province, pop_job, population):
"""
Creates a new Pop.
manager (Historia)
province (SecondaryDivision)
culture (Culture)
religion (Religion)
language (Language)
job (Job)
"""
self.bankrupt_times = 0
self.home = provinc... | __init__ | identifier_name |
pop.py | import math
from historia.utils import unique_id, position_in_range
from historia.pops.models.inventory import Inventory
from historia.economy.enums.resource import Good, NaturalResource
from historia.economy.enums.order_type import OrderType
from historia.economy.models.price_range import PriceRange
from historia.econ... |
def generate_orders(self, good):
"""
If the Pop needs a Good to perform production, buy it
If the Pop has surplus Resources, sell them
"""
surplus = self.inventory.surplus(good)
if surplus >= 1: # sell inventory
# the original only old one item here
... | "Determine how much goods to buy based on market conditions"
mean = self.market.avg_historial_price(good, 15)
trading_range = self.trading_range_extremes(good)
favoribility = 1 - position_in_range(mean, trading_range.low, trading_range.high)
amount_to_buy = round(favoribility * self.inv... | identifier_body |
pop.py | import math
from historia.utils import unique_id, position_in_range
from historia.pops.models.inventory import Inventory
from historia.economy.enums.resource import Good, NaturalResource
from historia.economy.enums.order_type import OrderType
from historia.economy.models.price_range import PriceRange
from historia.econ... |
neighboring_markets = [p.market for p in self.location.owned_neighbors]
neighboring_markets = [m for m in neighboring_markets if m.supply_for(good) > self.trade_amount]
neighboring_markets.sort(key=lambda m: m.supply_for(good), reverse=True)
if len(neigh... | print("Good: {}, Demand: {}, Price: ${}".format(good.title, demand, price_at_home)) | conditional_block |
pop.py | import math
from historia.utils import unique_id, position_in_range
from historia.pops.models.inventory import Inventory
from historia.economy.enums.resource import Good, NaturalResource
from historia.economy.enums.order_type import OrderType
from historia.economy.models.price_range import PriceRange
from historia.econ... | self.price_belief = {}
# a dictionary of Goods to price list
# represents the prices of the good that the Pop has observed
# during the time they have been trading
self.observed_trading_range = {}
self.successful_trades = 0
self.failed_trades = 0
# make... | # represents the price range the agent considers valid for each Good | random_line_split |
server.go | package reflector
import (
"bufio"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"io"
"net"
"time"
"github.com/lbryio/reflector.go/internal/metrics"
"github.com/lbryio/reflector.go/store"
"github.com/lbryio/lbry.go/v2/extras/errors"
"github.com/lbryio/lbry.go/v2/extras/stop"
"github.com/lbryio/lbry.go/v... | else if handshake.Version == nil {
return errors.Err("handshake is missing protocol version")
} else if *handshake.Version != protocolVersion1 && *handshake.Version != protocolVersion2 {
return errors.Err("protocol version not supported")
}
resp, err := json.Marshal(handshakeRequestResponse{Version: handshake.... | {
return err
} | conditional_block |
server.go | package reflector
import (
"bufio"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"io"
"net"
"time"
"github.com/lbryio/reflector.go/internal/metrics"
"github.com/lbryio/reflector.go/store"
"github.com/lbryio/lbry.go/v2/extras/errors"
"github.com/lbryio/lbry.go/v2/extras/stop"
"github.com/lbryio/lbry.go/v... |
func (s *Server) handleConn(conn net.Conn) {
// all this stuff is to close the connections correctly when we're shutting down the server
connNeedsClosing := make(chan struct{})
defer func() {
close(connNeedsClosing)
}()
s.grp.Add(1)
metrics.RoutinesQueue.WithLabelValues("reflector", "server-handleconn").Inc()... | {
for {
conn, err := listener.Accept()
if err != nil {
if s.quitting() {
return
}
log.Error(err)
} else {
s.grp.Add(1)
metrics.RoutinesQueue.WithLabelValues("reflector", "server-listenandserve").Inc()
go func() {
defer metrics.RoutinesQueue.WithLabelValues("reflector", "server-listenand... | identifier_body |
server.go | package reflector
import (
"bufio"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"io"
"net"
"time"
"github.com/lbryio/reflector.go/internal/metrics"
"github.com/lbryio/reflector.go/store"
"github.com/lbryio/lbry.go/v2/extras/errors"
"github.com/lbryio/lbry.go/v2/extras/stop"
"github.com/lbryio/lbry.go/v... | func (s *Server) readRawBlob(conn net.Conn, blobSize int) ([]byte, error) {
err := conn.SetReadDeadline(time.Now().Add(s.Timeout))
if err != nil {
return nil, errors.Err(err)
}
blob := make([]byte, blobSize)
_, err = io.ReadFull(bufio.NewReader(conn), blob)
return blob, errors.Err(err)
}
func (s *Server) writ... | }
| random_line_split |
server.go | package reflector
import (
"bufio"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"io"
"net"
"time"
"github.com/lbryio/reflector.go/internal/metrics"
"github.com/lbryio/reflector.go/store"
"github.com/lbryio/lbry.go/v2/extras/errors"
"github.com/lbryio/lbry.go/v2/extras/stop"
"github.com/lbryio/lbry.go/v... | (conn net.Conn) error {
var handshake handshakeRequestResponse
err := s.read(conn, &handshake)
if err != nil {
return err
} else if handshake.Version == nil {
return errors.Err("handshake is missing protocol version")
} else if *handshake.Version != protocolVersion1 && *handshake.Version != protocolVersion2 {
... | doHandshake | identifier_name |
mod.rs | // Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_address::AccountAddress,
account_config::stc_type_tag,
block_metadata::BlockMetadata,
contract_event::Contract... | (
sender: AccountAddress,
sequence_number: u64,
script: Script,
max_gas_amount: u64,
gas_unit_price: u64,
expiration_time: Duration,
) -> Self {
RawUserTransaction {
sender,
sequence_number,
payload: TransactionPayload::Scri... | new_script | identifier_name |
mod.rs | // Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_address::AccountAddress,
account_config::stc_type_tag,
block_metadata::BlockMetadata,
contract_event::Contract... | expiration_time: Duration,
}
// TODO(#1307)
fn serialize_duration<S>(d: &Duration, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
serializer.serialize_u64(d.as_secs())
}
fn deserialize_duration<'de, D>(deserializer: D) -> std::result::Result<Duration, D::Error>
where
... | // A transaction that doesn't expire is represented by a very large value like
// u64::max_value().
#[serde(serialize_with = "serialize_duration")]
#[serde(deserialize_with = "deserialize_duration")] | random_line_split |
mod.rs | // Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_address::AccountAddress,
account_config::stc_type_tag,
block_metadata::BlockMetadata,
contract_event::Contract... |
pub fn sender(&self) -> AccountAddress {
self.raw_txn.sender
}
pub fn into_raw_transaction(self) -> RawUserTransaction {
self.raw_txn
}
pub fn sequence_number(&self) -> u64 {
self.raw_txn.sequence_number
}
pub fn payload(&self) -> &TransactionPayload {
&s... | {
&self.raw_txn
} | identifier_body |
sorting.go | package rivescript
// Data sorting functions
import (
"errors"
"sort"
"strconv"
"strings"
)
// Sort buffer data, for RiveScript.SortReplies()
type sortBuffer struct {
topics map[string][]sortedTriggerEntry // Topic name -> array of triggers
thats map[string][]sortedTriggerEntry
sub []string // Substitutio... | (dict map[string]string) []string {
output := []string{}
// Track by number of words.
track := map[int][]string{}
// Loop through each item.
for item := range dict {
cnt := wordCount(item, true)
if _, ok := track[cnt]; !ok {
track[cnt] = []string{}
}
track[cnt] = append(track[cnt], item)
}
// Sort ... | sortList | identifier_name |
sorting.go | package rivescript
// Data sorting functions
import (
"errors"
"sort"
"strconv"
"strings"
)
// Sort buffer data, for RiveScript.SortReplies()
type sortBuffer struct {
topics map[string][]sortedTriggerEntry // Topic name -> array of triggers
thats map[string][]sortedTriggerEntry
sub []string // Substitutio... | {
return &sortTrack{
atomic: map[int][]sortedTriggerEntry{},
option: map[int][]sortedTriggerEntry{},
alpha: map[int][]sortedTriggerEntry{},
number: map[int][]sortedTriggerEntry{},
wild: map[int][]sortedTriggerEntry{},
pound: []sortedTriggerEntry{},
under: []sortedTriggerEntry{},
star: []sortedTr... | identifier_body | |
sorting.go | package rivescript
// Data sorting functions
import (
"errors"
"sort"
"strconv"
"strings"
)
// Sort buffer data, for RiveScript.SortReplies()
type sortBuffer struct {
topics map[string][]sortedTriggerEntry // Topic name -> array of triggers
thats map[string][]sortedTriggerEntry
sub []string // Substitutio... | track[inherits].atomic[cnt] = append(track[inherits].atomic[cnt], trig)
}
}
// Move the no-{inherits} triggers to the bottom of the stack.
track[highestInherits+1] = track[-1]
delete(track, -1)
// Sort the track from the lowest to the highest.
var trackSorted []int
for k := range track {
track... | rs.say("Totally atomic trigger with %d words", cnt)
if _, ok := track[inherits].atomic[cnt]; !ok {
track[inherits].atomic[cnt] = []sortedTriggerEntry{}
} | random_line_split |
sorting.go | package rivescript
// Data sorting functions
import (
"errors"
"sort"
"strconv"
"strings"
)
// Sort buffer data, for RiveScript.SortReplies()
type sortBuffer struct {
topics map[string][]sortedTriggerEntry // Topic name -> array of triggers
thats map[string][]sortedTriggerEntry
sub []string // Substitutio... |
patternSet[pattern] = true
running = append(running, patternMap[pattern]...)
}
return running
}
// initSortTrack initializes a new, empty sortTrack object.
func initSortTrack() *sortTrack {
return &sortTrack{
atomic: map[int][]sortedTriggerEntry{},
option: map[int][]sortedTriggerEntry{},
alpha: map[int... | {
continue
} | conditional_block |
app.js | var SECONDS = 59;
var MINUTES = 3;
var SCORE = [0,0];
var VALUE1;
var VALUE2;
var sliceCount = 0;
var p1data = [];
var p2data = [];
var p1trend = "0";
var p2trend = "0";
var multiplierA;
var multiplierB;
var makePointsFlag = true;
var P1NAME;
var P2NAME;
var P1EMAIL;
var P2EMAIL;
var COMBONAME = null;
function add... |
else {
trendValue2 = 1;
}
trendValue1 ? SCORE[0] += Math.round(trendValue1) : null;
trendValue2 ? SCORE[1] += Math.round(trendValue2) : null;
scoreRender();
}
}
function scoreRender () {
document.getElementById("player-1-score").innerHTML = SCORE[0] ? SCOR... | {
trendValue2 = 5;
} | conditional_block |
app.js | var SECONDS = 59;
var MINUTES = 3;
var SCORE = [0,0];
var VALUE1;
var VALUE2;
var sliceCount = 0;
var p1data = [];
var p2data = [];
var p1trend = "0";
var p2trend = "0";
var multiplierA;
var multiplierB;
var makePointsFlag = true;
var P1NAME;
var P2NAME;
var P1EMAIL;
var P2EMAIL;
var COMBONAME = null;
function add... |
function initialization () {//initializes the persistant dashboard metrics for the first time
//add all of the local storage variables
//localStorage.setItem("highScore", 0);
//localStorage.setItem("totalparticipants", 0);
//localStorage.setItem("average", 0);
//localStorage.s... | {//checks if any of the present SCOREs are higher than the all time high SCORE
var tempSCORE = parseInt(localStorage.getItem("highScore"));
if (SCORE[0] > tempSCORE) {
localStorage.setItem("highScore", SCORE[0]);
}
if (SCORE[1] > tempSCORE) {
localStorage.setItem("highScore", SCORE[1])... | identifier_body |
app.js | var SECONDS = 59;
var MINUTES = 3;
var SCORE = [0,0];
var VALUE1;
var VALUE2;
var sliceCount = 0;
var p1data = [];
var p2data = [];
var p1trend = "0";
var p2trend = "0";
var multiplierA;
var multiplierB;
var makePointsFlag = true;
var P1NAME;
var P2NAME;
var P1EMAIL;
var P2EMAIL;
var COMBONAME = null;
function add... |
function highScore () {//checks if any of the present SCOREs are higher than the all time high SCORE
var tempSCORE = parseInt(localStorage.getItem("highScore"));
if (SCORE[0] > tempSCORE) {
localStorage.setItem("highScore", SCORE[0]);
}
if (SCORE[1] > tempSCORE) {
localStorage.setIte... | };
localStorage.setItem("finalobjects", JSON.stringify(totalFinalObjects));
} | random_line_split |
app.js | var SECONDS = 59;
var MINUTES = 3;
var SCORE = [0,0];
var VALUE1;
var VALUE2;
var sliceCount = 0;
var p1data = [];
var p2data = [];
var p1trend = "0";
var p2trend = "0";
var multiplierA;
var multiplierB;
var makePointsFlag = true;
var P1NAME;
var P2NAME;
var P1EMAIL;
var P2EMAIL;
var COMBONAME = null;
function add... | () {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
function pointGenerator () {//this function computes the points
//TODO: Make a funtion to check directional trends and integrate the result into this function
if (makePoint... | overlay | identifier_name |
XYRepresentation.py | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 5 15:06:34 2018
@author: lawrence
"""
import numpy as np
import random as rd
import matplotlib.pyplot as plt
import matplotlib.path as mplpath
import matplotlib.patches as patches
from matplotlib.collections import PatchCollection
from matplotlib import collections as ... |
def sample(self):
samp=self.mp.sample()
self.addVertex(samp)
return samp
class Map():
points=[] #PRM points
edges=[] #PRM edges
lines=[]
buff_lines=[]
obstacles=[]
buff=0
vis_graph=None
visibility=False
def __init__(self,lx=0,hx=0,ly=0,hy=0):
self... | if self.can_connect(a,q):
if (a,q) not in self.edges and (q,a) not in self.edges:
self.edges.append((a,q)) | identifier_body |
XYRepresentation.py | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 5 15:06:34 2018
@author: lawrence
"""
import numpy as np
import random as rd
import matplotlib.pyplot as plt
import matplotlib.path as mplpath
import matplotlib.patches as patches
from matplotlib.collections import PatchCollection
from matplotlib import collections as ... |
return False
def clear(self):
self.lines=[]
self.buff_lines=[]
self.obstacles=[]
"""vertices are of format [(a,b),(c,d)]"""
def add_Poly(self,vertices=[]):
if self.visibility:
init_poly=shapely.Polygon(vertices)
buff_poly=ini... | if obs[1].intersects(path) and not path.touches(obs[1]):
return True | conditional_block |
XYRepresentation.py | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 5 15:06:34 2018
@author: lawrence
"""
import numpy as np
import random as rd
import matplotlib.pyplot as plt
import matplotlib.path as mplpath
import matplotlib.patches as patches
from matplotlib.collections import PatchCollection
from matplotlib import collections as ... | (self,a,q):
if self.can_connect(a,q):
if (a,q) not in self.edges and (q,a) not in self.edges:
self.edges.append((a,q))
def sample(self):
samp=self.mp.sample()
self.addVertex(samp)
return samp
class Map():
points=[] #PRM points
edges=[] #PRM edges
... | connect | identifier_name |
XYRepresentation.py | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 5 15:06:34 2018
@author: lawrence
"""
import numpy as np
import random as rd
import matplotlib.pyplot as plt
import matplotlib.path as mplpath
import matplotlib.patches as patches
from matplotlib.collections import PatchCollection
from matplotlib import collections as ... | graph=Graph(mp)
"""Create graph for PRM"""
# PRM.prm_cc(graph,100,start,goal)
# PRM.prm_k(graph,100,3,start,goal)
PRM.prm_star(graph,5)
"""Add graph and tree to display and print out what it looks"""
mp.points=graph.vertices
mp.edges=graph.edges
mp.display()
"""Run A... | mp.add_Poly([(-1,-1), (-6,-2), (-5,2), (-3,2), (-4,0)])
mp.add_Poly([(6,5), (4,1), (5,-2), (2,-4), (1,2)])
mp.add_Poly([(0,-3) ,(0,-4) ,(1,-5) ,(-5,-5) ,(-5,-4) ])
mp.add_Poly([(6,6), (0,4) ,(-5,6) ,(0,6), (4,7)])
# mp.add_Poly([(-2,0),(-2,-1),(2,-1),(2,0)]) | random_line_split |
loadout-builder-reducer.ts | import {
defaultLoadoutParameters,
LoadoutParameters,
UpgradeSpendTier,
} from '@destinyitemmanager/dim-api-types';
import { D2ManifestDefinitions } from 'app/destiny2/d2-definitions';
import { t } from 'app/i18next-t';
import { DimItem, PluggableInventoryItemDefinition } from 'app/inventory/item-types';
import {... | body: t('LoadoutBuilder.MissingClassDescription'),
});
}
const lbStateInit = ({
stores,
preloadedLoadout,
initialLoadoutParameters,
classType,
defs,
}: {
stores: DimStore[];
preloadedLoadout?: Loadout;
initialLoadoutParameters: LoadoutParameters;
classType: DestinyClass | undefined;
defs: D2M... |
showNotification({
type: 'error',
title: t('LoadoutBuilder.MissingClass', { className: missingClassName }), | random_line_split |
loadout-builder-reducer.ts | import {
defaultLoadoutParameters,
LoadoutParameters,
UpgradeSpendTier,
} from '@destinyitemmanager/dim-api-types';
import { D2ManifestDefinitions } from 'app/destiny2/d2-definitions';
import { t } from 'app/i18next-t';
import { DimItem, PluggableInventoryItemDefinition } from 'app/inventory/item-types';
import {... | (classType: DestinyClass, defs: D2ManifestDefinitions) {
const missingClassName = Object.values(defs.Class).find((c) => c.classType === classType)!
.displayProperties.name;
showNotification({
type: 'error',
title: t('LoadoutBuilder.MissingClass', { className: missingClassName }),
body: t('LoadoutBu... | warnMissingClass | identifier_name |
loadout-builder-reducer.ts | import {
defaultLoadoutParameters,
LoadoutParameters,
UpgradeSpendTier,
} from '@destinyitemmanager/dim-api-types';
import { D2ManifestDefinitions } from 'app/destiny2/d2-definitions';
import { t } from 'app/i18next-t';
import { DimItem, PluggableInventoryItemDefinition } from 'app/inventory/item-types';
import {... |
export function useLbState(
stores: DimStore[],
preloadedLoadout: Loadout | undefined,
classType: DestinyClass | undefined,
initialLoadoutParameters: LoadoutParameters,
defs: D2ManifestDefinitions
) {
return useReducer(
lbStateReducer,
{ stores, preloadedLoadout, initialLoadoutParameters, defs, cl... | {
switch (action.type) {
case 'changeCharacter':
return {
...state,
selectedStoreId: action.storeId,
pinnedItems: {},
excludedItems: {},
lockedExoticHash: undefined,
};
case 'statFiltersChanged':
return { ...state, statFilters: action.statFilters };
... | identifier_body |
loadout-builder-reducer.ts | import {
defaultLoadoutParameters,
LoadoutParameters,
UpgradeSpendTier,
} from '@destinyitemmanager/dim-api-types';
import { D2ManifestDefinitions } from 'app/destiny2/d2-definitions';
import { t } from 'app/i18next-t';
import { DimItem, PluggableInventoryItemDefinition } from 'app/inventory/item-types';
import {... |
const statOrder = statOrderFromLoadoutParameters(loadoutParams);
const statFilters = statFiltersFromLoadoutParamaters(loadoutParams);
const lockedMods = lockedModsFromLoadoutParameters(loadoutParams, defs);
const lockItemEnergyType = Boolean(loadoutParams?.lockItemEnergyType);
// We need to handle the depre... | {
const loadoutStore = stores.find((store) => store.classType === preloadedLoadout.classType);
if (!loadoutStore) {
warnMissingClass(preloadedLoadout.classType, defs);
} else {
selectedStoreId = loadoutStore.id;
// TODO: instead of locking items, show the loadout fixed at the top to compar... | conditional_block |
config.rs | // Copyright 2019 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
use crate::common::*;
use clap::{App, Arg, ArgMatches};
use logger::*;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::net::SocketAddr... | (&self, pkey: &str) -> bool {
self.data.get(pkey).is_some()
}
/// Remove a `pkey`+`lkey`
pub fn remove(&mut self, pkey: &str, lkey: &str) {
if let Some(entry) = self.data.get_mut(pkey) {
entry.remove(lkey);
}
}
/// Remove the `pkey` and all `lkey`s under it
... | contains_pkey | identifier_name |
config.rs | // Copyright 2019 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
use crate::common::*;
use clap::{App, Arg, ArgMatches};
use logger::*;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::net::SocketAddr... |
/// the timeout for sampler execution
pub fn sampler_timeout(&self) -> Duration {
self.sampler_timeout
}
/// maximum consecutive sampler timeouts
pub fn max_sampler_timeouts(&self) -> usize {
self.max_sampler_timeouts
}
/// get listen address
pub fn listen(&self) -> S... | {
self.sample_rate
} | identifier_body |
config.rs | // Copyright 2019 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
use crate::common::*;
use clap::{App, Arg, ArgMatches};
use logger::*;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::net::SocketAddr... | else {
None
};
let sample_rate =
parse_float_arg(&matches, "sample-rate").unwrap_or(DEFAULT_SAMPLE_RATE_HZ);
let sampler_timeout = Duration::from_millis(
parse_numeric_arg(&matches, "sampler-timeout")
.unwrap_or(DEFAULT_SAMPLER_TIMEOUT_MILLIS... | {
let socket = sock.parse().unwrap_or_else(|_| {
println!("ERROR: memcache address is malformed");
process::exit(1);
});
Some(socket)
} | conditional_block |
config.rs | // Copyright 2019 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
use crate::common::*;
use clap::{App, Arg, ArgMatches};
use logger::*;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::net::SocketAddr... | }
/// helper function to discover the number of hardware threads
pub fn hardware_threads() -> Result<usize, ()> {
let path = "/sys/devices/system/cpu/present";
let f = File::open(path).map_err(|e| error!("failed to open file ({:?}): {}", path, e))?;
let mut f = BufReader::new(f);
let mut line = String... | })
}) | random_line_split |
tag.rs | //! Utilities and constants for OpenType tags.
//!
//! See also the [`tag!`](../macro.tag.html) macro for creating tags from a byte string.
use crate::error::ParseError;
use std::{fmt, str};
/// Generate a 4-byte OpenType tag from byte string
///
/// Example:
///
/// ```
/// use allsorts::tag;
/// assert_eq!(tag!(b"g... |
#[test]
fn test_three_chars() {
let tag = from_string("BEN").expect("invalid tag");
assert_eq!(tag, 1111838240);
}
}
mod display_tag {
use crate::tag::{DisplayTag, NAME};
#[test]
fn test_simple_ascii() {
assert_eq!(DisplayT... | {
let tag = from_string("beng").expect("invalid tag");
assert_eq!(tag, 1650814567);
} | identifier_body |
tag.rs | //! Utilities and constants for OpenType tags.
//!
//! See also the [`tag!`](../macro.tag.html) macro for creating tags from a byte string.
use crate::error::ParseError;
use std::{fmt, str};
/// Generate a 4-byte OpenType tag from byte string
///
/// Example:
///
/// ```
/// use allsorts::tag;
/// assert_eq!(tag!(b"g... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let tag = self.0;
let bytes = tag.to_be_bytes();
if bytes.iter().all(|c| c.is_ascii() && !c.is_ascii_control()) {
let s = str::from_utf8(&bytes).unwrap(); // unwrap safe due to above check
s.fmt(f)
} else {
... | fmt | identifier_name |
tag.rs | //! Utilities and constants for OpenType tags.
//!
//! See also the [`tag!`](../macro.tag.html) macro for creating tags from a byte string.
use crate::error::ParseError;
use std::{fmt, str};
/// Generate a 4-byte OpenType tag from byte string
///
/// Example:
///
/// ```
/// use allsorts::tag;
/// assert_eq!(tag!(b"g... | pub const MKMK: u32 = tag!(b"mkmk");
/// `mlm2`
pub const MLM2: u32 = tag!(b"mlm2");
/// `mlym`
pub const MLYM: u32 = tag!(b"mlym");
/// `mort`
pub const MORT: u32 = tag!(b"mort");
/// `morx`
pub const MORX: u32 = tag!(b"morx");
/// `mset`
pub const MSET: u32 = tag!(b"mset");
/// `name`
pub const NAME: u32 = tag!(b"nam... | pub const MEDI: u32 = tag!(b"medi");
/// `mkmk` | random_line_split |
tag.rs | //! Utilities and constants for OpenType tags.
//!
//! See also the [`tag!`](../macro.tag.html) macro for creating tags from a byte string.
use crate::error::ParseError;
use std::{fmt, str};
/// Generate a 4-byte OpenType tag from byte string
///
/// Example:
///
/// ```
/// use allsorts::tag;
/// assert_eq!(tag!(b"g... |
tag = (tag << 8) | (c as u32);
count += 1;
}
while count < 4 {
tag = (tag << 8) | (' ' as u32);
count += 1;
}
Ok(tag)
}
impl fmt::Display for DisplayTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let tag = self.0;
let bytes = tag... | {
return Err(ParseError::BadValue);
} | conditional_block |
lib.rs | /*!
* This library provides an API client for Diffbot.
*
* Making API requests
* -------------------
*
* There are a handful of different ways to make API calls:
*
* 1. The most basic way to make a request is with the ``call()`` function.
* Everything must be specified for each request.
*
* 2. Use the ``D... | (&self, url: &Url, api: &str, fields: &[&str])
-> Result<json::Object, Error> {
call(url, self.token, api, fields, self.version)
}
/// Prepare a request to any Diffbot API with the stored token and API version.
///
/// See the ``call()`` function for an explanation of the paramet... | call | identifier_name |
lib.rs | /*!
* This library provides an API client for Diffbot.
*
* Making API requests
* -------------------
*
* There are a handful of different ways to make API calls:
*
* 1. The most basic way to make a request is with the ``call()`` function.
* Everything must be specified for each request.
*
* 2. Use the ``D... | let num = num as uint;
let msg = match o.pop(&~"error")
.expect("JSON had errorCode but not error") {
json::String(s) => s,
uh_oh => fail!("error was {} instead of a string", uh_oh.to_s... | match json {
json::Object(~mut o) => {
match o.pop(&~"errorCode") {
Some(json::Number(num)) => { | random_line_split |
lib.rs | /*!
* This library provides an API client for Diffbot.
*
* Making API requests
* -------------------
*
* There are a handful of different ways to make API calls:
*
* 1. The most basic way to make a request is with the ``call()`` function.
* Everything must be specified for each request.
*
* 2. Use the ``D... |
}
/// An in-progress Diffbot API call.
pub struct Request {
priv request: RequestWriter<TcpStream>,
}
impl Request {
/// Set the value for Diffbot to send as the ``User-Agent`` header when
/// making your request.
pub fn user_agent(&mut self, user_agent: ~str) {
self.request.headers.extension... | {
prepare_request(url, self.token, api, fields, self.version)
} | identifier_body |
main.rs | use std::time;
use vulkano::instance::Instance;
use vulkano::instance::PhysicalDevice;
use vulkano::pipeline::GraphicsPipeline;
use vulkano::pipeline::viewport::Viewport;
use vulkano::device::Device;
use vulkano::device::Features;
use vulkano::device::RawDeviceExtensions;
use vulkano::framebuffer::{
Framebu... | () {
let img = match image::open("./media/autumn.png") {
Ok(image) => image,
Err(err) => panic!("{:?}", err)
};
{ // stdout image info
println!("color {:?}", img.color());
println!("dimensions {:?}", img.dimensions());
// println!("first pixel {:?}", img.pixels(... | main | identifier_name |
main.rs | use std::time;
use vulkano::instance::Instance;
use vulkano::instance::PhysicalDevice;
use vulkano::pipeline::GraphicsPipeline;
use vulkano::pipeline::viewport::Viewport;
use vulkano::device::Device;
use vulkano::device::Features;
use vulkano::device::RawDeviceExtensions;
use vulkano::framebuffer::{
Framebu... |
swapchain = new_swapchain;
framebuffers = window_size_dependent_setup(&new_images, render_pass.clone(), &mut dynamic_state);
recreate_swapchain = false;
}
let (image_num, acquire_future) = match swapchain::acquire_next_image(swapchain.clone(), None){
... | Err(err) => panic!("{:?}", err)
}; | random_line_split |
main.rs | use std::time;
use vulkano::instance::Instance;
use vulkano::instance::PhysicalDevice;
use vulkano::pipeline::GraphicsPipeline;
use vulkano::pipeline::viewport::Viewport;
use vulkano::device::Device;
use vulkano::device::Features;
use vulkano::device::RawDeviceExtensions;
use vulkano::framebuffer::{
Framebu... |
// fn init_particles_buffer() -> [Particle; PARTICLE_COUNT] {
// let mut rng = thread_rng();
// let mut particles = [Particle {
// pos: [0.0, 0.0],
// tail: [0.0, 0.0],
// speed: [0.0, 0.0],
// prev_pos: [0.0, 0.0],
// prev_tail: [0.0, 0.0],
// }; PARTICLE_COUNT];
/... | {
let img = match image::open("./media/autumn.png") {
Ok(image) => image,
Err(err) => panic!("{:?}", err)
};
{ // stdout image info
println!("color {:?}", img.color());
println!("dimensions {:?}", img.dimensions());
// println!("first pixel {:?}", img.pixels().n... | identifier_body |
main.rs | use std::time;
use vulkano::instance::Instance;
use vulkano::instance::PhysicalDevice;
use vulkano::pipeline::GraphicsPipeline;
use vulkano::pipeline::viewport::Viewport;
use vulkano::device::Device;
use vulkano::device::Features;
use vulkano::device::RawDeviceExtensions;
use vulkano::framebuffer::{
Framebu... | else {
return ;
};
let (new_swapchain, new_images) = match swapchain.recreate_with_dimension(dimensions) {
Ok(r) => r,
Err(SwapchainCreationError::UnsupportedDimensions) => continue,
Err(err) => panic!("{:?}", err)
}... | {
let dimensions: (u32, u32) = dimensions.to_physical(window.get_hidpi_factor()).into();
[dimensions.0, dimensions.1]
} | conditional_block |
body.rs | #![allow(dead_code)]
#![allow(unused_doc_comments)]
/**
* body.rs contains the Body struct and implements methods for it. A body struct contains only the
* position and velocity vectors of the body, other parameters are calculated using methods. A body
* is instantiated using using the Body::new() method, which als... | (&self, angle: f64) -> (Vector3<f64>, Vector3<f64>) {
let r = self.position_at_angle(angle);
let v = self.velocity_at_angle(angle);
let tht = angle - self.true_anomaly();
let trans = Matrix3::from_rows(&[
Vector3::new(tht.cos(), -tht.sin(), 0.0).transpose(),
Vecto... | position_and_velocity | identifier_name |
body.rs | #![allow(dead_code)]
#![allow(unused_doc_comments)]
/**
* body.rs contains the Body struct and implements methods for it. A body struct contains only the
* position and velocity vectors of the body, other parameters are calculated using methods. A body
* is instantiated using using the Body::new() method, which als... |
}
/* points from focus to perigee if I'm not mistaken */
pub fn eccentricity_vector(&self) -> Vector3<f64> {
let veloc = self.velocity;
let posit = self.position;
let h = self.angular_momentum();
(veloc.cross(&h) / SOLARGM) - posit.normalize()
}
pub fn angular_mome... | {
return val.acos();
} | conditional_block |
body.rs | #![allow(dead_code)]
#![allow(unused_doc_comments)]
/**
* body.rs contains the Body struct and implements methods for it. A body struct contains only the
* position and velocity vectors of the body, other parameters are calculated using methods. A body
* is instantiated using using the Body::new() method, which als... | impl Body {
pub fn new(position: Vector3<f64>, velocity: Vector3<f64>) -> Body {
// h and e are used for determining what kind of orbit the body is currently in
let h = position.cross(&velocity);
let e = ((velocity.cross(&h) / SOLARGM) - position.normalize()).norm();
Body {
... | pub velocity: Vector3<f64>,
pub orbit_type: OrbitType,
}
/* Adds methods to Body struct */ | random_line_split |
body.rs | #![allow(dead_code)]
#![allow(unused_doc_comments)]
/**
* body.rs contains the Body struct and implements methods for it. A body struct contains only the
* position and velocity vectors of the body, other parameters are calculated using methods. A body
* is instantiated using using the Body::new() method, which als... |
pub fn true_anomaly(&self) -> f64 {
let e_vec = self.eccentricity_vector();
let posit = self.position.normalize();
let val = e_vec.dot(&posit) / (e_vec.norm() * posit.norm());
if posit.dot(&self.velocity.normalize()) < 0.0 {
return 2.0 * PI - val.acos();
} else ... | {
self.omega().cross(&self.position)
} | identifier_body |
thermald.py | #!/usr/bin/env python3.7
import os
import json
import copy
import datetime
from smbus2 import SMBus
from cereal import log
from common.basedir import BASEDIR
from common.params import Params
from common.realtime import sec_since_boot, DT_TRML
from common.numpy_fast import clip
from common.filter_simple import FirstOrde... |
# temp thresholds to control fan speed - high hysteresis
_TEMP_THRS_H = [50., 65., 80., 10000]
# temp thresholds to control fan speed - low hysteresis
_TEMP_THRS_L = [42.5, 57.5, 72.5, 10000]
# fan speed options
_FAN_SPEEDS = [0, 16384, 32768, 65535]
# max fan speed only allowed if battery is hot
_BAT_TEMP_THERSHOLD ... | global LEON, last_eon_fan_val
if last_eon_fan_val is None or last_eon_fan_val != val:
bus = SMBus(7, force=True)
if LEON:
try:
i = [0x1, 0x3 | 0, 0x3 | 0x08, 0x3 | 0x10][val]
bus.write_i2c_block_data(0x3d, 0, [i])
except IOError:
# tusb320
if val == 0:
bu... | identifier_body |
thermald.py | #!/usr/bin/env python3.7
import os
import json
import copy
import datetime
from smbus2 import SMBus
from cereal import log
from common.basedir import BASEDIR
from common.params import Params
from common.realtime import sec_since_boot, DT_TRML
from common.numpy_fast import clip
from common.filter_simple import FirstOrde... | ignition = health is not None and health.health.started
do_uninstall = params.get("DoUninstall") == b"1"
accepted_terms = params.get("HasAcceptedTerms") == terms_version
completed_training = params.get("CompletedTrainingVersion") == training_version
should_start = ignition
# have we seen a pa... | params.delete("Offroad_ConnectivityNeededPrompt")
# start constellation of processes when the car starts | random_line_split |
thermald.py | #!/usr/bin/env python3.7
import os
import json
import copy
import datetime
from smbus2 import SMBus
from cereal import log
from common.basedir import BASEDIR
from common.params import Params
from common.realtime import sec_since_boot, DT_TRML
from common.numpy_fast import clip
from common.filter_simple import FirstOrde... | (val):
global LEON, last_eon_fan_val
if last_eon_fan_val is None or last_eon_fan_val != val:
bus = SMBus(7, force=True)
if LEON:
try:
i = [0x1, 0x3 | 0, 0x3 | 0x08, 0x3 | 0x10][val]
bus.write_i2c_block_data(0x3d, 0, [i])
except IOError:
# tusb320
if val == 0:
... | set_eon_fan | identifier_name |
thermald.py | #!/usr/bin/env python3.7
import os
import json
import copy
import datetime
from smbus2 import SMBus
from cereal import log
from common.basedir import BASEDIR
from common.params import Params
from common.realtime import sec_since_boot, DT_TRML
from common.numpy_fast import clip
from common.filter_simple import FirstOrde... |
def main(gctx=None):
thermald_thread()
if __name__ == "__main__":
main()
| health = messaging.recv_sock(health_sock, wait=True)
location = messaging.recv_sock(location_sock)
location = location.gpsLocation if location else None
msg = read_thermal()
# clear car params when panda gets disconnected
if health is None and health_prev is not None:
params.panda_disconnect(... | conditional_block |
falcon.py | """
Python implementation of Falcon:
https://falcon-sign.info/.
"""
from .common import q
from numpy import set_printoptions
from math import sqrt
from .fft import fft, ifft, sub, neg, add_fft, mul_fft
from .ntt import sub_zq, mul_zq, div_zq
from .ffsampling import gram, ffldl_fft, ffsampling_fft
from .ntruge... | s0 = sub_zq(hashed, mul_zq(s1, self.h))
s0 = [(coef + (q >> 1)) % q - (q >> 1) for coef in s0]
# Check that the (s0, s1) is short
norm_sign = sum(coef ** 2 for coef in s0)
norm_sign += sum(coef ** 2 for coef in s1)
if norm_sign > self.signature_bound:
... | random_line_split | |
falcon.py | """
Python implementation of Falcon:
https://falcon-sign.info/.
"""
from .common import q
from numpy import set_printoptions
from math import sqrt
from .fft import fft, ifft, sub, neg, add_fft, mul_fft
from .ntt import sub_zq, mul_zq, div_zq
from .ffsampling import gram, ffldl_fft, ffsampling_fft
from .ntruge... |
'''
else:
print("-------------INVALID encoding---------------")
else:
print("-------------NOT within signature bound---------------")
'''
def verify(self, message, signature):
"""
Verify a signature... | return header + salt + enc_s | conditional_block |
falcon.py | """
Python implementation of Falcon:
https://falcon-sign.info/.
"""
from .common import q
from numpy import set_printoptions
from math import sqrt
from .fft import fft, ifft, sub, neg, add_fft, mul_fft
from .ntt import sub_zq, mul_zq, div_zq
from .ffsampling import gram, ffldl_fft, ffsampling_fft
from .ntruge... | (self, message, signature):
"""
Verify a signature.
"""
# Unpack the salt and the short polynomial s1
salt = signature[HEAD_LEN:HEAD_LEN + SALT_LEN]
enc_s = signature[HEAD_LEN + SALT_LEN:]
s1 = decompress(enc_s, self.sig_bytelen - HEAD_LEN - SALT_LEN, self.... | verify | identifier_name |
falcon.py | """
Python implementation of Falcon:
https://falcon-sign.info/.
"""
from .common import q
from numpy import set_printoptions
from math import sqrt
from .fft import fft, ifft, sub, neg, add_fft, mul_fft
from .ntt import sub_zq, mul_zq, div_zq
from .ffsampling import gram, ffldl_fft, ffsampling_fft
from .ntruge... |
class SecretKey:
"""
This class contains methods for performing
secret key operations (and also public key operations) in Falcon.
One can:
- initialize a secret key for:
- n = 128, 256, 512, 1024,
- phi = x ** n + 1,
- q = 12 * 1024 + 1
- find a preimage ... | """
This class contains methods for performing public key operations in Falcon.
"""
def __init__(self, sk=None, n=None, h=None):
"""Initialize a public key."""
if sk:
self.n = sk.n
self.h = sk.h
elif n and h:
self.n = n
self... | identifier_body |
cluster_feeder.go | /*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
for _, checkpoint := range checkpointList.Items {
klog.V(3).Infof("Loading VPA %s/%s checkpoint for %s", checkpoint.ObjectMeta.Namespace, checkpoint.Spec.VPAObjectName, checkpoint.Spec.ContainerName)
err = feeder.setVpaCheckpoint(&checkpoint)
if err != nil {
klog.Errorf("Error while loading checkpoint.... | {
klog.Errorf("Cannot list VPA checkpoints from namespace %v. Reason: %+v", namespace, err)
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.