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 |
|---|---|---|---|---|
did.rs | #[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::string::ToString as _;
use core::cmp::Ordering;
use core::convert::TryFrom;
use core::fmt::Debug;
use core::fmt::Display;
use core::fmt::Formatter;
use core::fmt::Result as FmtResult;
use core::hash::Hash;
use core::hash::Hasher;
... | (path: &str) -> Cow<str> {
fn next_segment(input: impl AsRef<[u8]>) -> Option<usize> {
match input.as_ref() {
[b'/', input @ ..] => next_segment(input).map(|index| index + 1),
input => input.iter().position(|byte| *byte == b'/'),
}
}
let mut output: Path = Path::new();
let m... | remove_dot_segments | identifier_name |
cfg_simulator.py | """
CAR CONFIG
This file is read by your car application's manage.py script to change the car
performance.
EXMAPLE
-----------
import dk
cfg = dk.load_config(config_path='~/mycar/config.py')
print(cfg.CAMERA_RESOLUTION)
"""
import os
#PATHS
CAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))
DAT... | PID_P = -10.0 # proportional mult for PID path follower
PID_I = 0.000 # integral mult for PID path follower
PID_D = -0.2 # differential mult for PID path follower
PID_THROTTLE = 0.2 # constant throttle value during path following
USE_CO... | #Path following
PATH_FILENAME = "donkey_path.pkl" # the path will be saved to this filename
PATH_SCALE = 5.0 # the path display will be scaled by this factor in the web page
PATH_OFFSET = (0, 0) # 255, 255 is the center of the map. This offset controls where the origin is displayed.
... | random_line_split |
index.js | const Long = require('long');
const csv = require('csvtojson');
const fs = require('fs');
let imgSrcPath = '/mnt/dyk/Documents/Default Documents/项目-活动-竞赛/天涯明月刀/00.各种助手/94.SFC解包重打包/PySFCExtractor/output/ImageSetsMixed/';
let imgDesPath = './img_output/';
let files = [
'FashionTable.csv', 'FashionSetTable.csv', 'Equi... | typeIcon: 'Icons/Achieve/ach_xinwang.png', // 看需求,就是花花Icon
meili: 50,
logic: 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行
// 通用成就完成表
achiIdList: [24749, 24750, 24750, 24750], // 需求Id
}
};
// 遍历魅力表时,特殊的:万色、一染、丰彩染料累计、瑶光颜料累计、点染××累计
// 万色、一染。读描述的冒号前的内容,找对应套装,加到染色成就表里
// 染色魅力,todo 这里假设各个时装男女需求一样
let example... | data[1];
itemTable = data[2];
achiReqTable = data[3];
achiTable = data[4];
// 新增坐骑
itemTable = itemTable.concat(data[5]);
// todo 是否可以染色
let partRes = {};
let setRes = {};
let glamourRes = {};
let dyeRes = {};
let dyesumRes = {};
// 以主表开始遍历
fashionTable.forEach(part => {
// 查item表提数据
... | identifier_body |
index.js | const Long = require('long');
const csv = require('csvtojson');
const fs = require('fs');
let imgSrcPath = '/mnt/dyk/Documents/Default Documents/项目-活动-竞赛/天涯明月刀/00.各种助手/94.SFC解包重打包/PySFCExtractor/output/ImageSetsMixed/';
let imgDesPath = './img_output/';
let files = [
'FashionTable.csv', 'FashionSetTable.csv', 'Equi... | Table = data[1];
itemTable = data[2];
achiReqTable = data[3];
achiTable = data[4];
// 新增坐骑
itemTable = itemTable.concat(data[5]);
// todo 是否可以染色
let partRes = {};
let setRes = {};
let glamourRes = {};
let dyeRes = {};
let dyesumRes = {};
// 以主表开始遍历
fashionTable.forEach(part => {
// 查it... | set | identifier_name |
index.js | const Long = require('long');
const csv = require('csvtojson');
const fs = require('fs');
let imgSrcPath = '/mnt/dyk/Documents/Default Documents/项目-活动-竞赛/天涯明月刀/00.各种助手/94.SFC解包重打包/PySFCExtractor/output/ImageSetsMixed/';
let imgDesPath = './img_output/';
let files = [
'FashionTable.csv', 'FashionSetTable.csv', 'Equi... |
// 构造套装表
setTable.forEach(set => {
// todo 保存三体型卡片
[set.iconM, set.iconF, set.iconZ, set.cardM, set.cardF, set.cardZ].forEach(filename => {
let hash = getHash(`DATA\\IMAGESETS\\ICONS\\FASHION\\${filename}.TGA`);
let fullPath = `${imgSrcPath}${hash}.tga`;
if(fs.existsSync(fullPath)) {
... | random_line_split | |
index.js | const Long = require('long');
const csv = require('csvtojson');
const fs = require('fs');
let imgSrcPath = '/mnt/dyk/Documents/Default Documents/项目-活动-竞赛/天涯明月刀/00.各种助手/94.SFC解包重打包/PySFCExtractor/output/ImageSetsMixed/';
let imgDesPath = './img_output/';
let files = [
'FashionTable.csv', 'FashionSetTable.csv', 'Equi... | origin: 'shop', // 在表最右边
originDes: '商城购买获得',
card: ['ICON_64_equip_coat_M_M_TY_3103', 'ICON_64_equip_coat_F_F_TY_3103', 'ICON_64_equip_coat_Z_Z_TY_3103'],
weight: 309, // 排序权重,最右边
// dyeAchievements: {
//
// }, // 染色成就表
}
};
// // 染色 todo
// let exampleDye = {
//
// };
// 魅力对应
let ex... | menpai: -1,
// 身份、盟会职务不关键,全部显示
explain: '使用后获得“心王·影冠”外装外形',
des: '露凝香,玉笼烟。\\n谁共我,醉明月?',
icon: 'ICON_60_equip_Head_M_M_TY_3103', // icon是只有男的
type: '外装',
},
achiId: 24749, // 反查achievement request表,收集了该物品可以达成的成就小Id
}
};
// 全部套装
let exampleSets = {
328: { // 心王影套装id
name:... | conditional_block |
main.rs | use ash::extensions::{DebugReport, Surface, Swapchain};
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
use ash::extensions::{WaylandSurface, XlibSurface};
use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0, V1_0};
use ash::vk::Image;
use ash::vk::PhysicalDevice;
use ash::vk::Semaphore;
use ... | (
entry: &Entry<V1_0>,
instance: &Instance<V1_0>,
window: &winit::Window,
physical_device: PhysicalDevice,
device: &Device<V1_0>,
) -> Result<(Swapchain, SwapchainKHR), vk::Result> {
let surface = create_surface(entry, instance, window).unwrap();
let surface_loader =
Surface::new(ent... | create_swapchain | identifier_name |
main.rs | use ash::extensions::{DebugReport, Surface, Swapchain};
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
use ash::extensions::{WaylandSurface, XlibSurface};
use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0, V1_0};
use ash::vk::Image;
use ash::vk::PhysicalDevice;
use ash::vk::Semaphore;
use ... | let semaphore_create_info = vk::SemaphoreCreateInfo {
s_type: vk::StructureType::SemaphoreCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
};
device.create_semaphore(&semaphore_create_info, None)
}
unsafe extern "system" fn vulkan_debug_callback(
_: vk::DebugReportFla... | random_line_split | |
main.rs | use ash::extensions::{DebugReport, Surface, Swapchain};
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
use ash::extensions::{WaylandSurface, XlibSurface};
use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0, V1_0};
use ash::vk::Image;
use ash::vk::PhysicalDevice;
use ash::vk::Semaphore;
use ... |
fn create_instance(entry: &Entry<V1_0>) -> Instance<V1_0> {
let app_name = CString::new("Niagara-rs").unwrap();
let raw_name = app_name.as_ptr();
let appinfo = vk::ApplicationInfo {
s_type: vk::StructureType::ApplicationInfo,
api_version: vk_make_version!(1, 0, 36),
p_application_n... | {
Entry::new().unwrap()
} | identifier_body |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
p... | (a: &mut Self, b: &mut Self, choice: Choice) {
// what TweetNacl originally does
// let mask: i64 = !(b - 1);
// TweetNacl translated to Choice language
// let mask: i64 = !(choice.unwrap_u8() as i64) - 1);
// `subtle` definition, which is equivalent
// let mask: i64 = -(... | conditional_swap | identifier_name |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
p... | assert!(bool::from(maybe_one.ct_eq(&FieldElement::ONE)));
assert_eq!(maybe_one, FieldElement::ONE);
}
#[test]
fn test_imaginary() {
let minus_one = -&FieldElement::ONE;
let i_squared = &FieldElement::I * &FieldElement::I;
assert_eq!(minus_one, i_squared);
}
... | assert_eq!(maybe_one.to_bytes(), FieldElement::ONE.to_bytes()); | random_line_split |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
p... |
}
sqrt
}
}
impl ConstantTimeEq for FieldElement {
fn ct_eq(&self, other: &Self) -> Choice {
let canonical_self = self.to_bytes();
let canonical_other = other.to_bytes();
canonical_self.ct_eq(&canonical_other)
}
}
impl PartialEq for FieldElement {
fn eq(&self,... | {
sqrt = &sqrt * self;
} | conditional_block |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
p... |
}
impl<'a, 'b> Mul<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
fn mul(self, other: &'b FieldElement) -> FieldElement {
// start with so-called "schoolbook multiplication"
// TODO: nicer way to do this with iterators?
let mut pre_product: [i64; 31] = Default::d... | {
for (x, y) in self.0.iter_mut().zip(other.0.iter()) {
*x -= y;
}
} | identifier_body |
control.rs | use crossbeam_utils::thread::scope;
use cursive::{
backend::Backend as CursiveBackend,
backends::crossterm,
event::Key,
traits::Nameable,
view::ViewWrapper,
views::{LayerPosition, NamedView},
View,
};
use cursive::{traits::Resizable, views::ResizedView, Cursive};
use cursive_buffered_backend... | } | random_line_split | |
control.rs | use crossbeam_utils::thread::scope;
use cursive::{
backend::Backend as CursiveBackend,
backends::crossterm,
event::Key,
traits::Nameable,
view::ViewWrapper,
views::{LayerPosition, NamedView},
View,
};
use cursive::{traits::Resizable, views::ResizedView, Cursive};
use cursive_buffered_backend... |
}
}
}
/// This enum is used for delegating actions to higher level event loops.
enum DelegateEvent {
Quit,
SwitchToAlign,
SwitchToUnalign,
OpenDialog(CursiveCallback),
}
/// Converts an event to a delegation
fn delegate_action(action: Action) -> Option<DelegateEvent> {
match action {
... | {
sink.send(Box::new(|siv: &mut Cursive| {
siv.call_on_name("aligned", |view: &mut Aligned| {
view.process_action(&mut Dummy, otherwise);
})
.expect("Could not send new data to view");
}))
... | conditional_block |
control.rs | use crossbeam_utils::thread::scope;
use cursive::{
backend::Backend as CursiveBackend,
backends::crossterm,
event::Key,
traits::Nameable,
view::ViewWrapper,
views::{LayerPosition, NamedView},
View,
};
use cursive::{traits::Resizable, views::ResizedView, Cursive};
use cursive_buffered_backend... | () -> cursive::theme::Theme {
use cursive::theme::{BaseColor::*, Color::*, PaletteColor::*};
let mut cursiv_theme = cursive::theme::load_default();
cursiv_theme.palette[Background] = Dark(Black);
cursiv_theme
}
/// Forwards `AlignedMessage`s from the alignment thread into callbacks for the cursive inst... | cursiv_theme | identifier_name |
print_test.py | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 17:26:44 2018
@author: dell
"""
import tensorflow as tf
import numpy as np
from PIL import Image
"""
im = Image.open('D://Deeplearning_Demo//Data_original//Data_im//train_im//IMG_1_B.jpg')
im.show()
im_array = np.array(im)
print(im_array.shape)
"""
from ... | DRN_5=residual_block(DRN_4,128,dilation=1,stride=1,first_block=False)
with tf.variable_scope('DRN_5_2'):
DRN_5=residual_block(DRN_5,128,dilation=1,stride=1,first_block=False)
# [3,3,256]+[3,3,256]的残差网络的设,stride设计为2相当于进行了降采样的操作
with tf.variable_scope('DRN_6_1'):
DRN_6 = residua... | DRN_3 = residual_block(DRN_2, 32, dilation=1, stride=1, first_block=False)
with tf.variable_scope('DRN_4_2'):
DRN_4 = residual_block(DRN_3, 64, dilation=1, stride=1, first_block=False)
with tf.variable_scope('DRN_5_1'):
| random_line_split |
print_test.py | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 17:26:44 2018
@author: dell
"""
import tensorflow as tf
import numpy as np
from PIL import Image
"""
im = Image.open('D://Deeplearning_Demo//Data_original//Data_im//train_im//IMG_1_B.jpg')
im.show()
im_array = np.array(im)
print(im_array.shape)
"""
from ... | 240×320×3
# label = tf.cast(label, tf.float32).eval()
# print("label.dtype:", label.dtype) # uint8
# 开始转换一下生成结果
# 显示原始数据的分布是什么
i0 = Image.fromarray(label)
# plt.figure(i+1)
result = i0.show()
# 显示一下训练出来的数据是什么样子的
re... | conditional_block | |
print_test.py | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 17:26:44 2018
@author: dell
"""
import tensorflow as tf
import numpy as np
from PIL import Image
"""
im = Image.open('D://Deeplearning_Demo//Data_original//Data_im//train_im//IMG_1_B.jpg')
im.show()
im_array = np.array(im)
print(im_array.shape)
"""
from ... | ,tensor
image = tf.image.resize_images(image, [240, 240])
image = tf.image.per_image_standardization(image)
"""
标签数据
"""
label = tf.read_file(file_queue[1]) # reader读取序列
# 读出的 value 是 string,现在转换为 uint8 型的向量
record_bytes = tf.decode_raw(label, tf.float32)
depth_major = tf.reshape(tf.slice(record_bytes... | # 解码 | identifier_name |
print_test.py | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 17:26:44 2018
@author: dell
"""
import tensorflow as tf
import numpy as np
from PIL import Image
"""
im = Image.open('D://Deeplearning_Demo//Data_original//Data_im//train_im//IMG_1_B.jpg')
im.show()
im_array = np.array(im)
print(im_array.shape)
"""
from ... | 7,input_channel,16])
DRN_1=tf.nn.conv2d(input_layer,filter,strides=[1,1,1,1],padding='SAME')
DRN_1=tf.nn.relu(DRN_1)
with tf.variable_scope('DRN_2'):
DRN_2=residual_block(DRN_1,16,dilation=1,stride=1,first_block=False)
# [3,3,32]+[3,3,32]的残差网络的设,stride设计为2相当于进行了降采样的操作
w... | etwork
:return: 4D tensor.
'''
input_channel = input_layer.get_shape().as_list()[-1]
# 按照正常的网络结构
# 我们选择先bath 然后进行卷积和relu的操作
# Y = conv(Relu(batch_normalize(X)))
# bn_relu_conv_layer(input_layer,filter_shape,stride,dilation=1)
'''
设置残差网络的模板的第一层
'''
# 这里进行查看输入输出维度以... | identifier_body |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a st... |
}
impl PushActiveSetEntry {
const BLOOM_FALSE_RATE: f64 = 0.1;
const BLOOM_MAX_BITS: usize = 1024 * 8 * 4;
fn get_nodes<'a>(
&'a self,
origin: &'a Pubkey,
// If true forces gossip push even if the node has pruned the origin.
mut should_force_push: impl FnMut(&Pubkey) -> bo... | {
&self.0[get_stake_bucket(stake)]
} | identifier_body |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a st... | (
&self,
node: &Pubkey, // Gossip node.
origin: &Pubkey, // CRDS value owner
) {
if let Some(bloom_filter) = self.0.get(node) {
bloom_filter.add(origin);
}
}
fn rotate<R: Rng>(
&mut self,
rng: &mut R,
size: usize, // Number of no... | prune | identifier_name |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a st... | #[test]
fn test_push_active_set_entry() {
const NUM_BLOOM_FILTER_ITEMS: usize = 100;
let mut rng = ChaChaRng::from_seed([147u8; 32]);
let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect();
let weights: Vec<_> = repeat_with(|| rng.gen_range(1..1000)).take(20).coll... | random_line_split | |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a st... | else {
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry
.get_nodes(origin, |_| false)
.eq(keys.into_iter().filter(|&key| key != origin)));
}
}
// Assert that each filter already prunes the key.
... | {
assert!(entry.get_nodes(origin, |_| false).eq(keys));
} | conditional_block |
tag_tweets_py2.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import sys
import re
import os
import multiprocessing
import nltk.tokenize.casual as NLTK
from nltk.corpus import stopwords
import string
PUNCTUATION = list(string.punctuation)
STOP = stopwords.words('english') + ['rt', 'via']
################################... |
# Fix HTML character entities:
text = NLTK._replace_html_entities(text)
# Shorten problematic sequences of characters
safe_text = NLTK.HANG_RE.sub(r'\1\1\1', text)
# Tokenize:
words = WORD_RE.findall(safe_text)
clean_text = text
# # Possibly alter the cas... | tknzr = NLTK.TweetTokenizer()
return tknzr.tokenize(text) | conditional_block |
tag_tweets_py2.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import sys
import re
import os
import multiprocessing
import nltk.tokenize.casual as NLTK
from nltk.corpus import stopwords
import string
PUNCTUATION = list(string.punctuation)
STOP = stopwords.words('english') + ['rt', 'via']
################################... | f run(data_dir):
files = [os.path.join(data_dir, f) for f in os.listdir(data_dir)]
start = time.time()
pool = multiprocessing.Pool(4)
results = pool.map_async(read_tweets, files)
pool.close()
pool.join()
print(time.time()-start)
if __name__ == '__main__':
run("/home/p8shi/tweets_english... | return
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
de | identifier_body |
tag_tweets_py2.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import sys
import re
import os
import multiprocessing
import nltk.tokenize.casual as NLTK
from nltk.corpus import stopwords
import string
PUNCTUATION = list(string.punctuation)
STOP = stopwords.words('english') + ['rt', 'via']
################################... | # WORD_RE performs poorly on these patterns:
HANG_RE = re.compile(r"""([^a-zA-Z0-9])\1{3,}""")
# The emoticon string gets its own regex so that we can preserve case for
# them as needed:
EMOTICON_RE = re.compile(EMOTICONS, re.VERBOSE | re.I | re.UNICODE)
# These regex are added
EMOJI_RE = re.compile(EMOJIS, re.UNICOD... | WORD_RE = re.compile(r"""(%s)""" % "|".join(REGEXPS), re.VERBOSE | re.I
| re.UNICODE)
| random_line_split |
tag_tweets_py2.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import sys
import re
import os
import multiprocessing
import nltk.tokenize.casual as NLTK
from nltk.corpus import stopwords
import string
PUNCTUATION = list(string.punctuation)
STOP = stopwords.words('english') + ['rt', 'via']
################################... | xt = emoji_pattern.sub(r'', text).encode('utf8')
return
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
def run(data_dir):
files = [os.path.join(data_dir, f) for f in os.listdir(data_dir)]
start = time.time()
pool = multiprocessi... | icode
te | identifier_name |
Conv_layer.py | __author__='Pabi'
import numpy as np
import pandas as pd
class Data(object):
"""
This class is used for all data storage purposes
Data is stored as 3D volumes. This includes wieghts and input data
"""
def __init__(self, width, height, depth, weight_init='undefined'):
self.width = width
... | def im2col(self, X):
"""
:param X: filter_dim X filter_dim area of current image to be converted to 1 X filter_dim^2 vector
:param filter_dim:
:return: vector of dimension 1 by filter_dim^2
"""
flat_vect = np.reshape(X, -1)
return flat_vect
def convolutio... | random_line_split | |
Conv_layer.py | __author__='Pabi'
import numpy as np
import pandas as pd
class Data(object):
"""
This class is used for all data storage purposes
Data is stored as 3D volumes. This includes wieghts and input data
"""
def __init__(self, width, height, depth, weight_init='undefined'):
self.width = width
... |
def set_data_mtx(self,input_mtx):
self.data_mtx = input_mtx
self.depth , self.width,self.height = input_mtx.shape
self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width))
def get_gradient(self, x, y, depth):
... | self.padded_mtx = input_mtx
self.depth , self.width,self.height = input_mtx.shape
self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width)) | identifier_body |
Conv_layer.py | __author__='Pabi'
import numpy as np
import pandas as pd
class Data(object):
"""
This class is used for all data storage purposes
Data is stored as 3D volumes. This includes wieghts and input data
"""
def __init__(self, width, height, depth, weight_init='undefined'):
self.width = width
... |
self.input_vol.set_padded_mtx(np.asarray(input_img_list))
def set_weights(self,input_vol):
for j in range(len(self.filter_map)):
self.filter_map[j].set_data_mtx(input_vol[j,:,:,:])
def Naive_forwardpass(self):
"""
Forward pass of conv net implementing output map ge... | if (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 == 0.0 :
for j in range(0,input_img.shape[0]):
input_img_list[j] = self.zero_pad(input_img_list[j])
print(input_img_list)
padded = True
else:
... | conditional_block |
Conv_layer.py | __author__='Pabi'
import numpy as np
import pandas as pd
class Data(object):
"""
This class is used for all data storage purposes
Data is stored as 3D volumes. This includes wieghts and input data
"""
def __init__(self, width, height, depth, weight_init='undefined'):
self.width = width
... | (self, image_col, filter_col):
conv_result = np.sum(np.dot(image_col, filter_col))
return conv_result
def zero_pad(self,x):
return np.pad(x,pad_width=(1,1),mode='constant',constant_values=0)
def zero_pad_image(self):
input_img =self.input_vol.data_mtx.copy()
input_img_l... | convolution_op | identifier_name |
forms.py | # Copyright 2010 Jose Maria Zambrana Arze <contact@josezambrana.com>
#
# 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 appl... | (self, **kwargs):
if self.name == 'deleted_at' or self.auto_now or self.auto_now_add:
return None
defaults = {'form_class': SelectDateTimeField}
defaults.update(kwargs)
return super(DateTimeProperty, self).get_form_field(**defaults)
class StringListProperty(djangoforms.StringListProperty):
__me... | get_form_field | identifier_name |
forms.py | # Copyright 2010 Jose Maria Zambrana Arze <contact@josezambrana.com>
#
# 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 appl... |
from django import forms
from django.conf import settings
from django.core.validators import validate_email
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from common.models import Block, MenuItem, Theme, ConfigD... |
import logging | random_line_split |
forms.py | # Copyright 2010 Jose Maria Zambrana Arze <contact@josezambrana.com>
#
# 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 appl... |
class UnloggedCommentForm(CommentForm):
class Meta(CommentForm.Meta):
pass
captcha = ReCaptchaField()
class BlockNewForm(BaseForm):
class Meta:
model = Block
exclude = ['uuid', 'slug', 'args', 'deleted_at', 'params']
def __init__(self, *args, **kwargs):
super(BlockNewForm, self).__init_... | class Meta:
model = Comment
exclude = ModelForm.Meta.exclude + ['author', 'owner', 'content', 'content_type']
def __init__(self, *args, **kwargs):
self.extra_params = {}
if "extra_params" in kwargs:
self.extra_params = kwargs.pop("extra_params")
super(CommentForm, self).__init__(*args, **kw... | identifier_body |
forms.py | # Copyright 2010 Jose Maria Zambrana Arze <contact@josezambrana.com>
#
# 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 appl... |
if isinstance(value, basestring):
value = util.get_tags(value.lower())
return value
class MultiEmailField(forms.Field):
def to_python(self, value):
if not value:
return []
return util.get_tags(value.lower())
def validate(self, value):
super(MultiEmailField, self).validate(value)
... | return [] | conditional_block |
mod.rs | mod boundingbox;
mod material;
mod shape;
use crate::config::SimulationConfig;
use crate::fields::ScalarField;
use crate::greenfunctions::cosinebasis::{CosineBasis, Direction};
use crate::world::boundingbox::BoundingBox;
use crate::world::shape::Shape;
use nalgebra::*;
use pbr::ProgressBar;
use rayon::iter::*;
use ser... |
/// This function validates the geometry of the world. The function should be called, because it
/// guarantees overflows later on in the simulation.
///
/// # Errors
/// - If any of the shapes is too close to the world border, the simulation can't be run and a
/// `WorldError::ShapeTooCloseTo... | {
println!("Geometry:");
println!(
"\tWorld size: ({}, {}, {})",
self.size.x, self.size.y, self.size.z
);
for (i, bbox) in self.objects.iter().enumerate() {
println!("\t{}: {}", i, bbox);
}
println!("{}", self.simulation_config);
... | identifier_body |
mod.rs | mod boundingbox;
mod material;
mod shape;
use crate::config::SimulationConfig;
use crate::fields::ScalarField;
use crate::greenfunctions::cosinebasis::{CosineBasis, Direction};
use crate::world::boundingbox::BoundingBox;
use crate::world::shape::Shape;
use nalgebra::*;
use pbr::ProgressBar;
use rayon::iter::*;
use ser... | (&self, i: usize, frequency: f32) -> Vector3<f32> {
// Progress bar
let bbox = &self.objects[i].bbox();
let dx = bbox.x1 - bbox.x0 + 4;
let dy = bbox.y1 - bbox.y0 + 4;
let dz = bbox.z1 - bbox.z0 + 4;
let count = 2 * (dx * dy + dy * dz + dz * dx) * (1 + self.objects.len())... | force_on_for_freq | identifier_name |
mod.rs | mod boundingbox;
mod material;
mod shape;
use crate::config::SimulationConfig;
use crate::fields::ScalarField;
use crate::greenfunctions::cosinebasis::{CosineBasis, Direction};
use crate::world::boundingbox::BoundingBox;
use crate::world::shape::Shape;
use nalgebra::*;
use pbr::ProgressBar;
use rayon::iter::*;
use ser... | // Check for intersection with other objects
for (j, bbox_2) in expanded_boxes.iter().enumerate() {
if i < j && bbox_1.intersects(&bbox_2) {
return Err(WorldError::ShapesIntersect {
index_1: i,
index_2: j,
... | random_line_split | |
algorithm.rs | #![allow(unknown_lints)]
#![warn(clippy::all)]
extern crate ndarray;
extern crate petgraph;
extern crate rand;
extern crate sprs;
use crate::protocol_traits::graph::{Graph, GraphObject, Id, Metadata};
use crate::protocol_traits::ledger::LedgerView;
use crate::types::walk::{RandomWalk, RandomWalks, SeedSet};
use crate... | ledger_view: &L,
) -> Osrank
where
L: LedgerView,
G: Graph,
<G::Node as GraphObject>::Id: Eq + Clone + Hash,
{
let total_walks = random_walks.len();
let node_visits = random_walks.count_visits(&node_id);
Fraction::from(1.0 - ledger_view.get_damping_factors().project)
* Osrank::new(no... | node_id: Id<G::Node>, | random_line_split |
algorithm.rs | #![allow(unknown_lints)]
#![warn(clippy::all)]
extern crate ndarray;
extern crate petgraph;
extern crate rand;
extern crate sprs;
use crate::protocol_traits::graph::{Graph, GraphObject, Id, Metadata};
use crate::protocol_traits::ledger::LedgerView;
use crate::types::walk::{RandomWalk, RandomWalks, SeedSet};
use crate... | <G, I>
where
I: Eq + Hash,
{
network_view: G,
pub walks: RandomWalks<I>,
}
fn walks<'a, L, G: 'a, RNG>(
starting_nodes: impl Iterator<Item = &'a Id<G::Node>>,
network: &G,
ledger_view: &L,
mut rng: RNG,
get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64,
) -> RandomWalks<Id... | WalkResult | identifier_name |
channel.rs | use std::any::Any;
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
use futures::sync::oneshot;
use futures::Future;
use base::types::{ArcType, Type};
use api::generic::A;
use api::{
primitive, AsyncPushable, Function, FunctionRef, FutureResult, Generic, Getable, OpaqueValue,
OwnedF... | {
ExternModule::new(
vm,
record!{
resume => primitive::<fn(&'vm Thread) -> Result<(), String>>("std.thread.prim.resume", resume),
(yield_ "yield") => primitive::<fn(())>("std.thread.prim.yield", yield_),
spawn => primitive!(1 std::thread::prim::spawn),
... | identifier_body | |
channel.rs | use std::any::Any;
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
use futures::sync::oneshot;
use futures::Future;
use base::types::{ArcType, Type};
use api::generic::A;
use api::{
primitive, AsyncPushable, Function, FunctionRef, FutureResult, Generic, Getable, OpaqueValue,
OwnedF... | thread: RootedThread,
action: WithVM<'vm, FunctionRef<Action>>,
) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> {
struct SpawnFuture<F>(Mutex<Option<F>>);
impl<F> fmt::Debug for SpawnFuture<F> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Future")
}
... |
#[cfg(not(target_arch = "wasm32"))]
fn spawn_on<'vm>( | random_line_split |
channel.rs | use std::any::Any;
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
use futures::sync::oneshot;
use futures::Future;
use base::types::{ArcType, Type};
use api::generic::A;
use api::{
primitive, AsyncPushable, Function, FunctionRef, FutureResult, Generic, Getable, OpaqueValue,
OwnedF... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self.queue.lock().unwrap())
}
}
impl<T> Traverseable for Sender<T> {
fn traverse(&self, _gc: &mut Gc) {
// No need to traverse in Sender as values can only be accessed through Receiver
}
}
impl<T> Sender<T> {
fn send(&... | fmt | identifier_name |
devices.js | const express = require('express')
const router = express.Router()
const axios = require('axios')
const {checkAuth} = require('../middlewares/authentication.js')
import Device from '../models/device.js'
import AlarmRule from '../models/emqx_alarm_rule.js'
import SaverRule from '../models/emqx_saver_rule.js'
import Tem... | (userId) {
try {
const rules = await AlarmRule.find({userId})
return rules
} catch (error) {
return "error"
}
}
async function selectDevice(userId, dId){
try {
const result = await Device.updateMany({userId: userId}, {selected: false})
const result2 = await ... | getAlarmRules | identifier_name |
devices.js | const express = require('express')
const router = express.Router()
const axios = require('axios')
const {checkAuth} = require('../middlewares/authentication.js')
import Device from '../models/device.js'
import AlarmRule from '../models/emqx_alarm_rule.js'
import SaverRule from '../models/emqx_saver_rule.js'
import Tem... |
// We can solve this by creating our own asyncForEach() method:
// thanks to Sebastien Chopin - Nuxt Creator :)
// https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[... | {
try {
const rules = await AlarmRule.find({ userId: userId, dId: dId });
if (rules.length > 0) {
asyncForEach(rules, async rule => {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + rule.emqxRuleId;
const res = await axios.delete(url, auth);
... | identifier_body |
devices.js | const express = require('express')
const router = express.Router()
const axios = require('axios')
const {checkAuth} = require('../middlewares/authentication.js')
import Device from '../models/device.js'
import AlarmRule from '../models/emqx_alarm_rule.js'
import SaverRule from '../models/emqx_saver_rule.js'
import Tem... | }
const res = await axios.put(url, newRule, auth)
if (res.status === 200 && res.data.data) {
await SaverRule.updateOne({ emqxRuleId: emqxRuleId}, {status: status})
console.log("Saver Rule Status Update...".green)
return {
status: "success",
action: "update"
... |
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId
const newRule = {
enabled: status | random_line_split |
devices.js | const express = require('express')
const router = express.Router()
const axios = require('axios')
const {checkAuth} = require('../middlewares/authentication.js')
import Device from '../models/device.js'
import AlarmRule from '../models/emqx_alarm_rule.js'
import SaverRule from '../models/emqx_saver_rule.js'
import Tem... |
return result
}
module.exports = router | {
result += characters.charAt (
Math.floor(Math.random() * charactersLength)
)
} | conditional_block |
compare-table.ts | /* Copyright 2016-2017 TensorHub, Inc.
*
* 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 t... | else if (type == "sort") {
return "sort";
} else if (type == "filter") {
return "label";
} else {
return item.value;
}
}
}
}
function headerTitle(title) {
return "<span class='header-title'>" + title + "</span>";
}
fu... | {
return runLink(item.value, row.run);
} | conditional_block |
compare-table.ts | /* Copyright 2016-2017 TensorHub, Inc.
*
* 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 t... |
function addOrUpdateRows(dt, items) {
var added = false;
items.forEach(function(item, index) {
var curRow = findRow(dt, item);
if (curRow != null) {
updateRow(dt, curRow, item);
} else {
addRow(dt, item);
added = true;
}
});
if (added... | {
var ids = items.map(function(item) { return item.run.id; });
return new Set(ids);
} | identifier_body |
compare-table.ts | /* Copyright 2016-2017 TensorHub, Inc.
*
* 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 t... | return new Set(ids);
}
function addOrUpdateRows(dt, items) {
var added = false;
items.forEach(function(item, index) {
var curRow = findRow(dt, item);
if (curRow != null) {
updateRow(dt, curRow, item);
} else {
addRow(dt, item);
added = true;
... | random_line_split | |
compare-table.ts | /* Copyright 2016-2017 TensorHub, Inc.
*
* 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 t... | (dt, target) {
var row = dt.row("#" + target.run.id);
return row.data() != undefined ? row : null;
}
function updateRow(dt, row, newItem) {
var curItem = row.data();
dt.columns().every(function(colIndex) {
var property = dt.column(colIndex).dataSrc();
var curVal = curItem[property];
... | findRow | identifier_name |
tree.go | package web
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/VectorsOrigin/utils"
)
/*
tree 负责路由树的解析,排序,匹配
实现前面加类型
'/web/content/<string:xmlid>',
'/web/content/<string:xmlid>/<string:filename>',
'/web/content/<int:id>',
'/web/content/<int:id>/<string:filename>',
'/web/content/<int:id>-<string:unique>... | elf.Root)
// 获得对应方法[POST,GET...]
cn := self.Root[aMethod]
if cn == nil {
// 初始化Root node
cn = &TNode{
Children: TSubNodes{},
}
self.Root[aMethod] = cn
}
var p *TNode = cn // 复制方法对应的Root
// 层级插入Nodes的Node到Root
for idx, _ := range aNodes {
p = cn.addnode(p, aNodes, idx, aIsHook)
}
}
func printNod... | oot", s | identifier_name |
tree.go | package web
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/VectorsOrigin/utils"
)
/*
tree 负责路由树的解析,排序,匹配
实现前面加类型
'/web/content/<string:xmlid>',
'/web/content/<string:xmlid>/<string:filename>',
'/web/content/<int:id>',
'/web/content/<int:id>/<string:filename>',
'/web/content/<int:id>-<string:unique>... | // two static route, content longer is first.
func (self TSubNodes) Less(i, j int) bool {
if self[i].Type == StaticNode {
if self[j].Type == StaticNode {
return len(self[i].Text) > len(self[j].Text)
}
return true
}
if self[j].Type == StaticNode {
return false
} else {
return self[i].Level > self[j].Le... | // static route will be put the first, so it will be match first. | random_line_split |
tree.go | package web
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/VectorsOrigin/utils"
)
/*
tree 负责路由树的解析,排序,匹配
实现前面加类型
'/web/content/<string:xmlid>',
'/web/content/<string:xmlid>/<string:filename>',
'/web/content/<int:id>',
'/web/content/<int:id>/<string:filename>',
'/web/content/<int:id>-<string:unique>... | self[i], self[j] = self[j], self[i]
}
// static route will be put the first, so it will be match first.
// two static route, content longer is first.
func (self TSubNodes) Less(i, j int) bool {
if self[i].Type == StaticNode {
if self[j].Type == StaticNode {
return len(self[i].Text) > len(self[j].Text)
}
ret... | wap(i, j int) {
| identifier_body |
tree.go | package web
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/VectorsOrigin/utils"
)
/*
tree 负责路由树的解析,排序,匹配
实现前面加类型
'/web/content/<string:xmlid>',
'/web/content/<string:xmlid>/<string:filename>',
'/web/content/<int:id>',
'/web/content/<int:id>/<string:filename>',
'/web/content/<int:id>-<string:unique>... | conditional_block | ||
builder.py | # -*- coding: utf-8 -*-
"""
Convenience IR builder.
"""
from __future__ import print_function, division, absolute_import
from contextlib import contextmanager
from pykit import error
from pykit import types, config
from pykit.ir import Value, Op, Block, Const, Undef, ops, findop, FuncArg
from pykit.ir.verification i... |
# Allow splitting only after leaders and before terminator
# TODO: error check
# -------------------------------------------------
# Split
oldblock = self._curblock
newblock = self.func.new_block(name or 'block', after=self._curblock)
op = self._lastop
... | """Split the current block, returning (old_block, new_block)"""
# -------------------------------------------------
# Sanity check | random_line_split |
builder.py | # -*- coding: utf-8 -*-
"""
Convenience IR builder.
"""
from __future__ import print_function, division, absolute_import
from contextlib import contextmanager
from pykit import error
from pykit import types, config
from pykit.ir import Value, Op, Block, Const, Undef, ops, findop, FuncArg
from pykit.ir.verification i... |
self._insert_op(result)
return result
def _process_void(self, *args, **kwds):
result = kwds.pop('result', None)
op = _process(self, types.Void, list(args), result)
if kwds:
op.add_metadata(kwds)
return op
if ops.i... | result.add_metadata(metadata) | conditional_block |
builder.py | # -*- coding: utf-8 -*-
"""
Convenience IR builder.
"""
from __future__ import print_function, division, absolute_import
from contextlib import contextmanager
from pykit import error
from pykit import types, config
from pykit.ir import Value, Op, Block, Const, Undef, ops, findop, FuncArg
from pykit.ir.verification i... |
class Builder(OpBuilder):
"""
I build Operations and emit them into the function.
Also provides convenience operations, such as loops, guards, etc.
"""
def __init__(self, func):
self.func = func
self.module = func.module
self._curblock = None
self._lastop = None
... | if type == args[0].type:
return args[0]
return buildop(self, type, args, result) | identifier_body |
builder.py | # -*- coding: utf-8 -*-
"""
Convenience IR builder.
"""
from __future__ import print_function, division, absolute_import
from contextlib import contextmanager
from pykit import error
from pykit import types, config
from pykit.ir import Value, Op, Block, Const, Undef, ops, findop, FuncArg
from pykit.ir.verification i... | (self, type, args, result=None, buildop=convert):
if type == args[0].type:
return args[0]
return buildop(self, type, args, result)
class Builder(OpBuilder):
"""
I build Operations and emit them into the function.
Also provides convenience operations, such as loops, guards, etc... | convert | identifier_name |
gdbstub.rs | use std::io::{self, Read, Write};
use std::ops::{Add, AddAssign};
use std::str;
use std::thread;
use std::time::Duration;
use mio;
use mio::tcp::{TcpListener, TcpStream};
use cpu::BreakReason;
use dbgcore::{self, ActiveCpu::Arm9};
use hwcore::Message;
use msgs;
use utils;
#[derive(Debug, Error)]
pub enum ErrorKind {... | poll: poll,
socket: None,
};
let mut events = Events::with_capacity(1024);
info!("Starting GDB stub on port 4567...");
let mut last_halt = BreakData::new(BreakReason::Trapped, &mut debugger.ctx(Arm9));
't: loop {
... | let mut connection = Connection {
listener: &listener, | random_line_split |
gdbstub.rs | use std::io::{self, Read, Write};
use std::ops::{Add, AddAssign};
use std::str;
use std::thread;
use std::time::Duration;
use mio;
use mio::tcp::{TcpListener, TcpStream};
use cpu::BreakReason;
use dbgcore::{self, ActiveCpu::Arm9};
use hwcore::Message;
use msgs;
use utils;
#[derive(Debug, Error)]
pub enum ErrorKind {... | <'a, 'b: 'a> {
dbg: &'a mut dbgcore::DbgContext<'b>,
last_halt: &'a mut BreakData,
}
const TOKEN_LISTENER: mio::Token = mio::Token(1024);
const TOKEN_CLIENT: mio::Token = mio::Token(1025);
pub struct GdbStub {
debugger: dbgcore::DbgCore,
gdb_thread: Option<thread::JoinHandle<msgs::Client<Message>>>
}
... | GdbCtx | identifier_name |
gdbstub.rs | use std::io::{self, Read, Write};
use std::ops::{Add, AddAssign};
use std::str;
use std::thread;
use std::time::Duration;
use mio;
use mio::tcp::{TcpListener, TcpStream};
use cpu::BreakReason;
use dbgcore::{self, ActiveCpu::Arm9};
use hwcore::Message;
use msgs;
use utils;
#[derive(Debug, Error)]
pub enum ErrorKind {... |
}
fn handle_gdb_cmd_q(cmd: &str, _ctx: &mut GdbCtx) -> Result<String> {
let mut s = cmd.splitn(2, ':');
let ty = parse_next(&mut s)?;
let mut out = String::new();
match ty {
"fThreadInfo" => out += "m0000000000000001",
"sThreadInfo" => out += "l",
"C" => out += "QC0000000000000... | {
let reason_str = match self.reason {
BreakReason::Breakpoint => format!(";{}:", "swbreak"),
_ => String::new(),
};
format!("T05{:02X}:{:08X};{:02X}:{:08X}{};", 15, self.r15.swap_bytes(),
13, self.r13.swap_bytes(),
... | identifier_body |
spinning_square.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::{Context as _, Error};
use carnelian::{
app::{Config, ViewCreationParameters},
color::Color,
derive_handle_message_with_default,
... |
Ok(())
}
}
fn make_app_assistant_fut(
app_sender: &AppSender,
) -> LocalBoxFuture<'_, Result<AppAssistantPtr, Error>> {
let f = async move {
let assistant = Box::new(SpinningSquareAppAssistant::new(app_sender.clone()));
Ok::<AppAssistantPtr, Error>(assistant)
};
Box::pin(f)... | {
if keyboard_event.phase == input::keyboard::Phase::Pressed
|| keyboard_event.phase == input::keyboard::Phase::Repeat
{
match code_point {
SPACE => self.toggle_rounded(),
B => self.move_backward(),
F => ... | conditional_block |
spinning_square.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::{Context as _, Error};
use carnelian::{
app::{Config, ViewCreationParameters},
color::Color,
derive_handle_message_with_default,
... | }
#[derive(Debug)]
pub struct ToggleRoundedMessage {}
#[derive(Debug)]
pub struct ToggleDirectionMessage {}
struct SpinningSquareFacet {
direction: Direction,
square_color: Color,
rounded: bool,
start: Time,
square_path: Option<Path>,
size: Size,
}
impl SpinningSquareFacet {
fn new(squar... | match self {
Self::Clockwise => Self::CounterClockwise,
Self::CounterClockwise => Self::Clockwise,
}
} | random_line_split |
spinning_square.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::{Context as _, Error};
use carnelian::{
app::{Config, ViewCreationParameters},
color::Color,
derive_handle_message_with_default,
... | (&mut self, new_size: &Size) -> Result<(), Error> {
self.scene_details = None;
self.ensure_scene_built(*new_size);
Ok(())
}
fn get_scene(&mut self, size: Size) -> Option<&mut Scene> {
self.ensure_scene_built(size);
Some(&mut self.scene_details.as_mut().unwrap().scene)
... | resize | identifier_name |
aup2rpp.py | import struct
import xml.etree.ElementTree as ET
import uuid
import math
import pprint
import os
import html
import argparse
AU_SAMPLE_FORMAT_16 = 3
AU_SAMPLE_FORMAT_24 = 4
AU_SAMPLE_FORMAT_FLOAT = 6
def load_au_file(au_fpath):
with open(au_fpath, 'rb') as f:
# See https://github.com/audacity/audacity/blob/mast... |
elif btype == 'pcmaliasblockfile':
# We don't do anything special regarding stereo, the source file should be fine already
if not is_last:
next_block = blocks[block_index + 1]
if next_block['type'] == 'pcmaliasblockfile':
if next_block['filename'] != block['filename']:
is_nex... | assert block['filename'].endswith('.au')
block2 = None
if is_stereo_track and clip2 is not None:
for b in clip2['sequence']['blocks']:
if b['start'] == block['start'] and b['len'] == block['len']:
block2 = b
break
if block2 is not None:
src_fpath = indexed_files[block... | conditional_block |
aup2rpp.py | import struct
import xml.etree.ElementTree as ET
import uuid
import math
import pprint
import os
import html
import argparse
AU_SAMPLE_FORMAT_16 = 3
AU_SAMPLE_FORMAT_24 = 4
AU_SAMPLE_FORMAT_FLOAT = 6
def load_au_file(au_fpath):
with open(au_fpath, 'rb') as f:
# See https://github.com/audacity/audacity/blob/mast... |
output = {
'rate': rate,
'name': unescape(name),
'data_dir': data_dir,
'tracks': []
}
for project_item in root:
tag = project_item.tag.split('}')[1]
if tag == 'wavetrack':
o_track = {
'name': unescape(project_item.attrib['name']),
'channel': int(project_item.attrib['channel']),
'linke... | return html.unescape(s) | identifier_body |
aup2rpp.py | import struct
import xml.etree.ElementTree as ET
import uuid
import math
import pprint
import os
import html
import argparse
AU_SAMPLE_FORMAT_16 = 3
AU_SAMPLE_FORMAT_24 = 4
AU_SAMPLE_FORMAT_FLOAT = 6
def load_au_file(au_fpath):
with open(au_fpath, 'rb') as f:
# See https://github.com/audacity/audacity/blob/mast... | samples_by_channel.append(samples)
w.append_multichannel_samples(samples_by_channel)
w.finalize()
return 0 if w is None else w.samples_count
def load_audacity_project(fpath):
root = ET.parse(fpath).getroot()
rate = int(float(root.attrib["rate"]))
name = root.attrib['projname']
ns = { 'ns': 'http://... | random_line_split | |
aup2rpp.py | import struct
import xml.etree.ElementTree as ET
import uuid
import math
import pprint
import os
import html
import argparse
AU_SAMPLE_FORMAT_16 = 3
AU_SAMPLE_FORMAT_24 = 4
AU_SAMPLE_FORMAT_FLOAT = 6
def load_au_file(au_fpath):
with open(au_fpath, 'rb') as f:
# See https://github.com/audacity/audacity/blob/mast... | :
def __init__(self, f, sample_rate, channels, bits_per_sample):
self.f = f
self.sample_rate = sample_rate
self.channels = channels
self.bits_per_sample = bits_per_sample
self.finalized = False
self.samples_count = 0
self.fmt_chunk_size = 2 + 2 + 4 + 4 + 2 + 2
self.initial_fpos = f.tell()
# Leave... | WavWriter | identifier_name |
ipfs.go | package ipfs
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
config "github.com/ipfs/go-ipfs-config"
files "github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/coreapi"
"github.com/ipfs/go-ipfs/core/no... |
return err
}
// StorageInterface impl
// Get retrieves object at path and returns as a os.File instance
// path should be ipfs cid. Caller should close file when done
func (fs *Ipfs) Get(path string) (f *os.File, err error) {
// Create output filename from the CID path string
var fname string
fname, err = fs.ma... | {
// Try to make 0700
if err = os.MkdirAll(path, os.ModePerm); err != nil {
return fmt.Errorf("failed to create root dir: %s", path)
}
} | conditional_block |
ipfs.go | package ipfs
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
config "github.com/ipfs/go-ipfs-config"
files "github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/coreapi"
"github.com/ipfs/go-ipfs/core/no... | }
// Check temp dir path
if err := ensureDir(cfg.TempDir); err != nil {
return nil, err
}
// Create ipfs node base on configuration
if err := ipfs.setupPlugins(cfg.RootPath); err != nil {
return nil, err
}
// Initialize the default ipfs config
// Create a config with default options and a 2048 bit key
... | // Check root path
if err := ensureDir(cfg.RootPath); err != nil {
return nil, err | random_line_split |
ipfs.go | package ipfs
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
config "github.com/ipfs/go-ipfs-config"
files "github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/coreapi"
"github.com/ipfs/go-ipfs/core/no... |
// TODO fix this, change default configuration values.
// Will need to add config options.
func (fs *Ipfs) createRepo(ctx context.Context, repoPath string, defaultCfg *config.Config) (err error) {
// Provide specific config modifications from default init.
if fs.config.DataStore != nil {
// Parse any overrides fo... | {
// Load any external plugins if available
plugins, err := loader.NewPluginLoader(path)
if err != nil {
return fmt.Errorf("error loading plugins: %s", err)
}
// Load preloaded and external plugins
if err := plugins.Initialize(); err != nil {
return fmt.Errorf("error initializing plugins: %s", err)
}
if e... | identifier_body |
ipfs.go | package ipfs
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
config "github.com/ipfs/go-ipfs-config"
files "github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/coreapi"
"github.com/ipfs/go-ipfs/core/no... | (path string) (string, error) {
return path, nil
}
// GetEndpoint no-op
func (fs *Ipfs) GetEndpoint() string {
return "/ipfs"
}
// Creates an IPFS node and returns its coreAPI
func (fs *Ipfs) createNode(ctx context.Context, repoPath string) (icore.CoreAPI, error) {
// Open the repo
repo, err := fsrepo.Open(repoPa... | GetURL | identifier_name |
tree.py | from typing import List, Tuple, Union, Dict, Any
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from manual_ml.base import BaseModel
from manual_ml.helpers.metrics import accuracy
class Tree(BaseModel):
"""
Binary classification tree
"""
def __init__(self,
mi... | (self,
nodes: List[str]=None,
root: bool=True):
if nodes is None:
nodes = []
if root:
nodes = self.tree
Tree.print_node(nodes)
if nodes['class'] == -1:
self._print(nodes=nodes['l_node'],
root=Fa... | _print | identifier_name |
tree.py | from typing import List, Tuple, Union, Dict, Any
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from manual_ml.base import BaseModel
from manual_ml.helpers.metrics import accuracy
class Tree(BaseModel):
"""
Binary classification tree
"""
def __init__(self,
mi... |
def fit(self, x, y, debug=False):
"""
Convert data to matrix if dataframe
Recursively create nodes using tree.buildNodes()
"""
# Set feature names
self.set_names(x)
# Convert to mats if not
x = self.strip_df(x)
y = self.strip_df(y)
... | bs =' ' * node['depth'] * 2
bs2 = '-' * 2
print(bs+'|'+bs2+'*' * 50)
print(bs+'|'+bs+node['node_str'])
print(bs+'|'+bs+'Depth:', node['depth'])
print(bs+'|'+bs+'n samples:', node['n'])
if not node['terminal']:
print(bs+'|'+bs+'Name: '+node['name'])
... | identifier_body |
tree.py | from typing import List, Tuple, Union, Dict, Any
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from manual_ml.base import BaseModel
from manual_ml.helpers.metrics import accuracy
class Tree(BaseModel):
"""
Binary classification tree
"""
def __init__(self,
mi... | 'note': f'One class at depth, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
else:
# Not terminal. Build next node.
# First find best split to run
col_idx, best_x, gini = Tre... | cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth, | random_line_split |
tree.py | from typing import List, Tuple, Union, Dict, Any
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from manual_ml.base import BaseModel
from manual_ml.helpers.metrics import accuracy
class Tree(BaseModel):
"""
Binary classification tree
"""
def __init__(self,
mi... |
else:
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'Too few data points, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
... | cla = nom_class | conditional_block |
opt.rs | //! CLI argument handling
use anyhow::Result;
use cargo::core::resolver::CliFeatures;
use cargo::ops::Packages;
use std::fmt;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub(crate) enum Cli {
/// Profile a binary with Xcode Instruments.
///
/// B... | (&self) -> Package {
if let Some(ref package) = self.package {
Package::Package(package.clone())
} else {
Package::Default
}
}
// valid target: --example, --bin, --bench
fn get_target(&self) -> Target {
if let Some(ref example) = self.example {
... | get_package | identifier_name |
opt.rs | //! CLI argument handling
use anyhow::Result;
use cargo::core::resolver::CliFeatures;
use cargo::ops::Packages;
use std::fmt;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub(crate) enum Cli {
/// Profile a binary with Xcode Instruments.
///
/// B... |
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Package::Default => {
write!(f, "Default: search all packages for example/bin/bench")
}
Package::Package(s) => write!(f, "{}", s),
}
}
}
im... | {
match p {
Package::Default => Packages::Default,
Package::Package(s) => Packages::Packages(vec![s]),
}
} | identifier_body |
opt.rs | //! CLI argument handling
use anyhow::Result;
use cargo::core::resolver::CliFeatures;
use cargo::ops::Packages;
use std::fmt;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub(crate) enum Cli {
/// Profile a binary with Xcode Instruments.
///
/// B... |
#[derive(Debug, StructOpt)]
#[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)]
pub(crate) struct AppConfig {
/// List available templates
#[structopt(short = "l", long)]
pub(crate) list_templates: bool,
/// Specify the instruments template to run
///
/// To see available temp... | )]
Instruments(AppConfig),
} | random_line_split |
quotes.py | # quotes.py
# http://sites.google.com/site/pocketsense/
#
# Original Version: TFB (http://thefinancebuff.com)
#
# This script retrieves price quotes for a list of stock and mutual fund ticker symbols from Yahoo! Finance.
# It creates a dummy OFX file and then imports the file to the default application associated with ... | :
"""
Create an OFX file based on a list of stocks and mutual funds.
"""
def __init__(self, currency, account, shares, stockList, mfList):
self.currency = currency
self.account = account
self.shares = shares
self.stockList = stockList
self.mfList = mfList
... | OfxWriter | identifier_name |
quotes.py | # quotes.py
# http://sites.google.com/site/pocketsense/
#
# Original Version: TFB (http://thefinancebuff.com)
#
# This script retrieves price quotes for a list of stock and mutual fund ticker symbols from Yahoo! Finance.
# It creates a dummy OFX file and then imports the file to the default application associated with ... |
self.status=False
self.source='Y'
#note: each try for a quote sets self.status=true if successful
if eYahoo:
csvtxt = self.getYahooQuote()
quote = self.csvparse(csvtxt)
if self.status: self.source='Y'
if not s... | print "Getting quote for:", self.ticker | conditional_block |
quotes.py | # quotes.py
# http://sites.google.com/site/pocketsense/
#
# Original Version: TFB (http://thefinancebuff.com)
#
# This script retrieves price quotes for a list of stock and mutual fund ticker symbols from Yahoo! Finance.
# It creates a dummy OFX file and then imports the file to the default application associated with ... |
#----------------------------------------------------------------------------
def getQuotes():
global YahooURL, eYahoo, GoogleURL, eGoogle, YahooTimeZone
status = True #overall status flag across all operations (true == no errors getting data)
#get site and other user-defined data
userdat = s... | """
Create an OFX file based on a list of stocks and mutual funds.
"""
def __init__(self, currency, account, shares, stockList, mfList):
self.currency = currency
self.account = account
self.shares = shares
self.stockList = stockList
self.mfList = mfList
s... | identifier_body |
quotes.py | # quotes.py
# http://sites.google.com/site/pocketsense/
#
# Original Version: TFB (http://thefinancebuff.com)
#
# This script retrieves price quotes for a list of stock and mutual fund ticker symbols from Yahoo! Finance.
# It creates a dummy OFX file and then imports the file to the default application associated with ... | join("", posstock), #str.join("",StrList) = "str(0)+str(1)+str(2)..."
join("", posmf))
def _pos(self, type, symbol, price, quoteTime):
return OfxTag("POS" + type.upper(),
OfxTag("INVPOS",
OfxTag("SECID",
... | for mf in self.mfList:
posmf.append(self._pos("mf", mf.symbol, mf.price, mf.quoteTime))
return OfxTag("INVPOSLIST", | random_line_split |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::ch... |
command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?;
capabilities::reset_effective(command)?;
if let Some(caps) = &proc.capabilities {
capabilities::drop_privileges(caps, command)?;
}
// Take care of LISTEN_FDS used for systemd-active-socket. If the value is
//... | {
rootfs::prepare_rootfs(
spec,
rootfs,
namespaces
.clone_flags
.contains(sched::CloneFlags::CLONE_NEWUSER),
)
.with_context(|| "Failed to prepare rootfs")?;
// change the root of filesystem of the process to the rootfs... | conditional_block |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::ch... | "LISTEN_FDS entered is malformed: {:?}. Ignore the value.",
&value
);
args.preserve_fds
}
};
// clean up and handle perserved fds.
cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?;
// notify parents ... | log::warn!( | random_line_split |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::ch... | () -> Result<()> {
// Open a fd without the CLOEXEC flag. Rust automatically adds the flag,
// so we use fcntl::open here for more control.
let fd = fcntl::open("/dev/null", fcntl::OFlag::O_RDWR, sys::stat::Mode::empty())?;
cleanup_file_descriptors(fd - 1).with_context(|| "Failed to clea... | test_cleanup_file_descriptors | identifier_name |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::ch... |
// Cleanup any extra file descriptors, so the new container process will not
// leak a file descriptor from before execve gets executed. The first 3 fd will
// stay open: stdio, stdout, and stderr. We would further preserve the next
// "preserve_fds" number of fds. Set the rest of fd with CLOEXEC flag, so they
// wil... | {
const PROCFS_FD_PATH: &str = "/proc/self/fd";
ensure_procfs(Path::new(PROCFS_FD_PATH))
.with_context(|| format!("{} is not the actual procfs", PROCFS_FD_PATH))?;
let fds: Vec<i32> = fs::read_dir(PROCFS_FD_PATH)?
.filter_map(|entry| match entry {
Ok(entry) => Some(entry.path())... | identifier_body |
batch-rotate.go | // Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (... |
// Empty indicates if kv is not set
func (kv BatchKeyRotateKV) Empty() bool {
return kv.Key == "" && kv.Value == ""
}
// Match matches input kv with kv, value will be wildcard matched depending on the user input
func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool {
if kv.Empty() {
return true
}
if stri... | {
if kv.Key == "" {
return errInvalidArgument
}
return nil
} | identifier_body |
batch-rotate.go | // Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (... | () error {
if r.Attempts < 0 {
return errInvalidArgument
}
if r.Delay < 0 {
return errInvalidArgument
}
return nil
}
// BatchKeyRotationType defines key rotation type
type BatchKeyRotationType string
const (
sses3 BatchKeyRotationType = "sse-s3"
ssekms BatchKeyRotationType = "sse-kms"
)
// BatchJobKeyR... | Validate | identifier_name |
batch-rotate.go | // Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (... | }
}
return nil
}
// BatchKeyRotateFilter holds all the filters currently supported for batch replication
type BatchKeyRotateFilter struct {
NewerThan time.Duration `yaml:"newerThan,omitempty" json:"newerThan"`
OlderThan time.Duration `yaml:"olderThan,omitempty" json:"olderThan"`
CreatedAfter ... | }
ctx["MinIO batch API"] = "batchrotate" // Context for a test key operation
if _, err := GlobalKMS.GenerateKey(GlobalContext, e.Key, ctx); err != nil {
return err | random_line_split |
batch-rotate.go | // Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (... |
}()
}
wk.Wait()
ri.Complete = ri.ObjectsFailed == 0
ri.Failed = ri.ObjectsFailed > 0
globalBatchJobsMetrics.save(job.ID, ri)
// persist in-memory state to disk.
logger.LogIf(ctx, ri.updateAfter(ctx, api, 0, job))
buf, _ := json.Marshal(ri)
if err := r.Notify(ctx, bytes.NewReader(buf)); err != nil {
logg... | {
attempts := attempts
stopFn := globalBatchJobsMetrics.trace(batchKeyRotationMetricObject, job.ID, attempts, result)
success := true
if err := r.KeyRotate(ctx, api, result); err != nil {
stopFn(err)
logger.LogIf(ctx, err)
success = false
} else {
stopFn(nil)
}
ri.trackCu... | conditional_block |
lib.rs | // まとめ
// - あらゆるところでパターンは使用されている
// - ちゃんと,あり得る可能性をカバーしよう
//
// python 3.10あたりで,pythonにも導入されるかも?
// (rustのsubprocessはpythonから影響を受けていたりなど,インスパイアされあっているような雰囲気)
//
//
// この章は辞書的な感じで,いろんなパターンとそのマッチング方法を列挙している感じ
// まずは6章の軽い復習+α
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
pub fn simple_matching() {
l... | identifier_name | ||
lib.rs | // まとめ
// - あらゆるところでパターンは使用されている
// - ちゃんと,あり得る可能性をカバーしよう
//
// python 3.10あたりで,pythonにも導入されるかも?
// (rustのsubprocessはpythonから影響を受けていたりなど,インスパイアされあっているような雰囲気)
//
//
// この章は辞書的な感じで,いろんなパターンとそのマッチング方法を列挙している感じ
// まずは6章の軽い復習+α
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
pub fn simple_matching() {
l... | 実はいつもつかうlet文もパターンの考え方を使っている
pub fn let_statement_uses_pattern() {
// let PATTERN = EXPRESSION;
// ここでマッチしたものを変数_xに束縛することを意味するパターン
// なんでもいいよと言っている
let _x = 5;
// mismatched type
// expected a tuple with 3 elements, found one with 2 elements
// let (_x, _y) = (1, 2, 3);
// こうすると_x, _yのみ... | _as_long_as_vector_has_values() {
let mut stack = Vec::new();
stack.push(1);
stack.push(2);
stack.push(3);
while let Some(top) = stack.pop() {
println!("vector has {} on the top", top);
}
// vector has 3 on the top
// vector has 2 on the top
// vector has 1 on the top
}
// ... | identifier_body |
lib.rs | // まとめ
// - あらゆるところでパターンは使用されている
// - ちゃんと,あり得る可能性をカバーしよう
//
// python 3.10あたりで,pythonにも導入されるかも?
// (rustのsubprocessはpythonから影響を受けていたりなど,インスパイアされあっているような雰囲気)
//
//
// この章は辞書的な感じで,いろんなパターンとそのマッチング方法を列挙している感じ
// まずは6章の軽い復習+α
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
pub fn simple_matching() {
l... | Message::Quit,
Message::Move { x: 3, y: 4 },
Message::Write("Hello!".to_string()),
Message::ChangeColor(Color::Rgb(0, 255, 128)),
Message::ChangeColor(Color::Hsv(0, 0, 0)),
];
for msg in msgs.iter() {
match msg {
Message::Quit => {
pri... | let msgs = vec![ | random_line_split |
vggish_input.py | # Copyright (c) 2017-2019 Carnegie Mellon University. All rights reserved.
# Use of this source code is governed by BSD 3-clause license and the following
# license from the original code.
# This code is modified from Ubicoustics codebase. LICENSE infomation:
# SOFTWARE LICENSE AGREEMENT
# ACADEMIC OR NON-PROFIT... | ata, sample_rate):
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
# Compute log mel spectrogr... | veform_to_examples(d | identifier_name |
vggish_input.py | # Copyright (c) 2017-2019 Carnegie Mellon University. All rights reserved.
# Use of this source code is governed by BSD 3-clause license and the following
# license from the original code.
# This code is modified from Ubicoustics codebase. LICENSE infomation:
# SOFTWARE LICENSE AGREEMENT
# ACADEMIC OR NON-PROFIT... |
def waveform_to_examples(data, sample_rate):
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
... | random_line_split | |
vggish_input.py | # Copyright (c) 2017-2019 Carnegie Mellon University. All rights reserved.
# Use of this source code is governed by BSD 3-clause license and the following
# license from the original code.
# This code is modified from Ubicoustics codebase. LICENSE infomation:
# SOFTWARE LICENSE AGREEMENT
# ACADEMIC OR NON-PROFIT... |
def waveform_to_examples_subtract_bg(data, sample_rate, bg):
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params... | len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_s... | identifier_body |
vggish_input.py | # Copyright (c) 2017-2019 Carnegie Mellon University. All rights reserved.
# Use of this source code is governed by BSD 3-clause license and the following
# license from the original code.
# This code is modified from Ubicoustics codebase. LICENSE infomation:
# SOFTWARE LICENSE AGREEMENT
# ACADEMIC OR NON-PROFIT... |
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_spectrogram(
data,
audio_sample_rate=vggish_params.SAMPLE_RATE,
log_offset=vggish_params.LOG_OFFSET,
window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS,
hop_length_secs=vggish_params.S... | ta = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
| conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.