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
laptop.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: laptop.proto package pc import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" timestamp "github.com/golang/protobuf/ptypes/timestamp" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/...
func (m *CreateLaptopRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_CreateLaptopRequest.Marshal(b, m, deterministic) } func (m *CreateLaptopRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_CreateLaptopRequest.Merge(m, src) } func (m *CreateLaptopRequest) XXX_Size()...
{ return xxx_messageInfo_CreateLaptopRequest.Unmarshal(m, b) }
identifier_body
renderer.rs
use gpukit::wgpu; use std::sync::Arc; pub struct Renderer { context: Arc<gpukit::Context>, pipeline: wgpu::RenderPipeline, vertex_buffer: gpukit::Buffer<Vertex>, index_buffer: gpukit::Buffer<u32>, bind_group: gpukit::BindGroup, screen_uniforms: UniformBuffer<ScreenUniforms>, texture_bind...
if index_count as usize > self.index_buffer.len() { self.index_buffer = Self::create_index_buffer(&self.context, index_count as usize); } // Write vertices/indices to their respective buffers for (egui::ClippedMesh(_, mesh), offset) in meshes.iter().zip(&offsets) { ...
{ self.vertex_buffer = Self::create_vertex_buffer(&self.context, vertex_count as usize); }
conditional_block
renderer.rs
use gpukit::wgpu; use std::sync::Arc; pub struct Renderer { context: Arc<gpukit::Context>, pipeline: wgpu::RenderPipeline, vertex_buffer: gpukit::Buffer<Vertex>, index_buffer: gpukit::Buffer<u32>, bind_group: gpukit::BindGroup, screen_uniforms: UniformBuffer<ScreenUniforms>, texture_bind...
color_targets: &[wgpu::ColorTargetState { format: target_format, blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::OneMinusSrcAlph...
2 => Uint32, ]], bind_group_layouts: &[&bind_group.layout, &texture_bind_group.layout],
random_line_split
renderer.rs
use gpukit::wgpu; use std::sync::Arc; pub struct Renderer { context: Arc<gpukit::Context>, pipeline: wgpu::RenderPipeline, vertex_buffer: gpukit::Buffer<Vertex>, index_buffer: gpukit::Buffer<u32>, bind_group: gpukit::BindGroup, screen_uniforms: UniformBuffer<ScreenUniforms>, texture_bind...
(context: &gpukit::Context, value: T) -> Self { let buffer = context .build_buffer() .with_usage(wgpu::BufferUsages::UNIFORM) .init_with_data(std::slice::from_ref(&value)); UniformBuffer { buffer, value } } fn update(&self, context: &gpukit::Context) { ...
new
identifier_name
exec.rs
use crate::guest; use crate::guest::{Crash, Guest}; use crate::utils::cli::{App, Arg, OptVal}; use crate::utils::free_ipv4_port; use crate::Config; use core::c::to_prog; use core::prog::Prog; use core::target::Target; use executor::transfer::{async_recv_result, async_send}; use executor::{ExecResult, Reason}; use std::...
(&mut self) { match self.inner { ExecutorImpl::Linux(ref mut e) => e.start().await, ExecutorImpl::Scripy(ref mut e) => e.start().await, } } pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> { match self.inner { Ex...
start
identifier_name
exec.rs
use crate::guest; use crate::guest::{Crash, Guest}; use crate::utils::cli::{App, Arg, OptVal}; use crate::utils::free_ipv4_port; use crate::Config; use core::c::to_prog; use core::prog::Prog; use core::target::Target; use executor::transfer::{async_recv_result, async_send}; use executor::{ExecResult, Reason}; use std::...
pub async fn start(&mut self) { // handle should be set to kill on drop self.exec_handle = None; self.guest.boot().await; self.start_executer().await } pub async fn start_executer(&mut self) { use tokio::io::ErrorKind::*; self.exec_handle = None; ...
{ let guest = Guest::new(cfg); let port = free_ipv4_port() .unwrap_or_else(|| exits!(exitcode::TEMPFAIL, "No Free port for executor driver")); let host_ip = cfg .executor .host_ip .as_ref() .map(String::from) .unwrap_or_else...
identifier_body
exec.rs
use crate::guest; use crate::guest::{Crash, Guest}; use crate::utils::cli::{App, Arg, OptVal}; use crate::utils::free_ipv4_port; use crate::Config; use core::c::to_prog; use core::prog::Prog; use core::target::Target; use executor::transfer::{async_recv_result, async_send}; use executor::{ExecResult, Reason}; use std::...
Ok(conn) => Some(conn.unwrap()), }; } pub async fn exec(&mut self, p: &Prog) -> Result<ExecResult, Option<Crash>> { // send must be success assert!(self.conn.is_some()); if let Err(e) = timeout( Duration::new(15, 0), async_send(p, self.conn.a...
{ self.exec_handle = None; eprintln!("Time out: wait executor connection {}", host_addr); exit(1) }
conditional_block
exec.rs
use crate::guest; use crate::guest::{Crash, Guest}; use crate::utils::cli::{App, Arg, OptVal}; use crate::utils::free_ipv4_port; use crate::Config; use core::c::to_prog; use core::prog::Prog; use core::target::Target; use executor::transfer::{async_recv_result, async_send}; use executor::{ExecResult, Reason}; use std::...
listener = match TcpListener::bind(&host_addr).await { Ok(l) => l, Err(e) => { if e.kind() == AddrInUse && retry != 5 { self.port = free_ipv4_port().unwrap(); retry += 1; continue; ...
let host_addr = format!("{}:{}", self.host_ip, self.port);
random_line_split
PoissonDiscSampleGenerator.py
"""Poisson Disc Sampling Generator This script uses a generator to create random points with a minimum distance of r from all other points within a defined space. This is often called Poisson Disc Sampling or blue noise. The script used is Bridson's Algorithm to generate the points. """ import numpy as np from Ut...
if seed < 0: raise ValueError("Seed must be non-negative.") self._seed = seed def _clear_previous_samples(self): """Clears grid and samples for generating new samples. """ del self._grid del self._samples # ------------------------------...
raise ValueError("Seed must be integer.")
conditional_block
PoissonDiscSampleGenerator.py
"""Poisson Disc Sampling Generator This script uses a generator to create random points with a minimum distance of r from all other points within a defined space. This is often called Poisson Disc Sampling or blue noise. The script used is Bridson's Algorithm to generate the points. """ import numpy as np from Ut...
@property def metric(self): """The distance function used to measure the distance between two points. Returns: (function) """ return self._metric @property def seed(self): """The random seed used for generating samples. Returns: ...
"""The number of attempts each active point to make a new point. Returns: (int) """ return self._k
identifier_body
PoissonDiscSampleGenerator.py
"""Poisson Disc Sampling Generator This script uses a generator to create random points with a minimum distance of r from all other points within a defined space. This is often called Poisson Disc Sampling or blue noise. The script used is Bridson's Algorithm to generate the points. """ import numpy as np from Ut...
(bool) If succeeds, returns True. Otherwise, returns False. """ # -------------------------------- # Check Bounds # -------------------------------- # Get grid point and confirm it is within range coord = self._get_grid_coord(point) if np.logical_or(np...
point (np.ndarray): An array of size (number_of_dimensions,). Returns:
random_line_split
PoissonDiscSampleGenerator.py
"""Poisson Disc Sampling Generator This script uses a generator to create random points with a minimum distance of r from all other points within a defined space. This is often called Poisson Disc Sampling or blue noise. The script used is Bridson's Algorithm to generate the points. """ import numpy as np from Ut...
(self, active_point): """ Attempts to make a random point in proximity of active_point. Attempts to make a random point around the active_point k times. If the new point is too close to another point, it will discard and try. If it fails k times, the function returns None. Args...
_make_point
identifier_name
Labupdown.py
import os from PIL import Image import torchvision.transforms as tvt import torch from sklearn import manifold import torchvision.utils as tvu import torch.nn.functional as F import cv2 import numpy as np from sklearn.cluster import SpectralClustering from sklearn.cluster import DBSCAN from sklearn.cluster import KMea...
project_mapdown1 = torch.zeros(features[:, :, s2:s3, s1:s4].size(0), features[:, :, s2:s3, s1:s4].size(2), features[:, :, s2:s3, s1:s4].size(3)).cuda() elif dr == 1: project_mapdown1 = torch.clamp( pca(features[:, :, s2:s3, s1:s4], allfeats=BIGfeat[...
if dr == 0:
random_line_split
Labupdown.py
import os from PIL import Image import torchvision.transforms as tvt import torch from sklearn import manifold import torchvision.utils as tvu import torch.nn.functional as F import cv2 import numpy as np from sklearn.cluster import SpectralClustering from sklearn.cluster import DBSCAN from sklearn.cluster import KMea...
def getPmap(features, first_compo): featuresChange=features.permute(1,0,2,3) reshaped_features=featuresChange.reshape(featuresChange.size(0),featuresChange.size(1)*featuresChange.size(2)*featuresChange.size(3)) projected_map = torch.matmul(first_compo.cuda().unsqueeze(0), reshaped_features.cuda()).view...
allfeaturesChange = allfeats.permute(1, 0, 2, 3) allreshaped_features = allfeaturesChange.reshape(allfeaturesChange.size(0), allfeaturesChange.size(1) * allfeaturesChange.size( 2) * allfeaturesChange.size(3...
identifier_body
Labupdown.py
import os from PIL import Image import torchvision.transforms as tvt import torch from sklearn import manifold import torchvision.utils as tvu import torch.nn.functional as F import cv2 import numpy as np from sklearn.cluster import SpectralClustering from sklearn.cluster import DBSCAN from sklearn.cluster import KMea...
p = F.interpolate(project_map.unsqueeze(1), size=(imgs.size(2), imgs.size(3)), mode='bilinear', align_corners=False) * 255. coordinate = np.array(coordinate) coordinate = np.squeeze(coordinate) feat = np.array(feat) # tsne2 = manifold.TSNE(n_components=3, init='pca', ran...
roject_map[i] Singlefeature = features[i, :, :, :] meanmaskvalue = Sproject_map.sum() / (Sproject_map.size(0) * Sproject_map.size(1)) Sproject_map[Sproject_map < theh] = 0 allcood = torch.nonzero(Sproject_map).cpu().numpy() Sproject_map = Sproject_map.unsqueeze(0) # Smask...
conditional_block
Labupdown.py
import os from PIL import Image import torchvision.transforms as tvt import torch from sklearn import manifold import torchvision.utils as tvu import torch.nn.functional as F import cv2 import numpy as np from sklearn.cluster import SpectralClustering from sklearn.cluster import DBSCAN from sklearn.cluster import KMea...
(allfeats=None): # features: NCWH allfeaturesChange = allfeats.permute(1, 0, 2, 3) allreshaped_features = allfeaturesChange.reshape(allfeaturesChange.size(0), allfeaturesChange.size(1) * allfeaturesChange.size( ...
getVec
identifier_name
main.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG 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...
/// Subscribe to the node API finalized heads stream and trigger a parent chain sync /// upon receiving a new header. fn subscribe_to_parentchain_new_headers<E: EnclaveBase + Sidechain>( parentchain_handler: Arc<ParentchainHandler<ParentchainApi, E>>, mut last_synced_header: Header, ) -> Result<(), Error> { let (s...
{ for evr in &events { debug!("Decoded: phase = {:?}, event = {:?}", evr.phase, evr.event); match &evr.event { Event::Balances(be) => { info!("[+] Received balances event"); debug!("{:?}", be); match &be { pallet_balances::Event::Transfer { from: transactor, to: dest, amount: ...
identifier_body
main.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG 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...
.subscribe_finalized_heads(sender) .map_err(Error::ApiClient)?; loop { let new_header: Header = match receiver.recv() { Ok(header_str) => serde_json::from_str(&header_str).map_err(Error::Serialization), Err(e) => Err(Error::ApiSubscriptionDisconnected(e)), }?; println!( "[+] Received finalized hea...
//TODO: this should be implemented by parentchain_handler directly, and not via // exposed parentchain_api. Blocked by https://github.com/scs/substrate-api-client/issues/267. parentchain_handler .parentchain_api()
random_line_split
main.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG 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...
( node_api: &ParentchainApi, register_enclave_xt_header: &Header, ) -> Result<bool, Error> { let enclave_count_of_previous_block = node_api.enclave_count(Some(*register_enclave_xt_header.parent_hash()))?; Ok(enclave_count_of_previous_block == 0) }
we_are_primary_validateer
identifier_name
main.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG 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...
if WorkerModeProvider::worker_mode() != WorkerMode::Teeracle { println!("*** [+] Finished syncing light client, syncing parentchain..."); // Syncing all parentchain blocks, this might take a while.. let mut last_synced_header = parentchain_handler.sync_parentchain(last_synced_header).unwrap(); // ------...
{ start_interval_market_update( &node_api, run_config.teeracle_update_interval, enclave.as_ref(), &teeracle_tokio_handle, ); }
conditional_block
products.page.ts
import { Component, OnInit } from '@angular/core'; import { ProductsService } from 'src/app/shared/services/products.service'; import { combineAll, first, ignoreElements, mapTo } from 'rxjs/operators'; import { ActivatedRoute, Router } from '@angular/router'; import { FollowUpService } from 'src/app/shared/services/fol...
} }); } ngOnInit() { this.idAccount =+ localStorage.getItem('accountId') console.log(this.idAccount) this.getAllProducts() if(this.isPageForUpdateFollowList) this.getSortedFolowList() if(this.addProductsToList) this.GetAllProductsByTypeId() if(this.isF...
this.typeListName = params['typeListName'] if(params['productsInList'] != undefined) { this.allSelectedProducts =(params['productsInList'].split(',')).map(x=>+x);
random_line_split
products.page.ts
import { Component, OnInit } from '@angular/core'; import { ProductsService } from 'src/app/shared/services/products.service'; import { combineAll, first, ignoreElements, mapTo } from 'rxjs/operators'; import { ActivatedRoute, Router } from '@angular/router'; import { FollowUpService } from 'src/app/shared/services/fol...
:number[]) { this.productService.getProductsByIdProduct(res).subscribe(products=>{ this.selectedsArray = [] console.log(products) console.log(Object.values(products)) for (let i = 0; i < this.arrKind.length; i++) { if(Object.values(products).find(group=> group[0].Catego...
electedArray(res
identifier_name
products.page.ts
import { Component, OnInit } from '@angular/core'; import { ProductsService } from 'src/app/shared/services/products.service'; import { combineAll, first, ignoreElements, mapTo } from 'rxjs/operators'; import { ActivatedRoute, Router } from '@angular/router'; import { FollowUpService } from 'src/app/shared/services/fol...
this.selectedsArray.length; i++)// over all Categories for checking which Categories are selected items { if (this.selectedsArray[i] != null)// if seleced items in this Categories so { Object(this.selectedsArray[i]).forEach(pr=> { if(!this.allSelectedProducts.find(item=> ...
follow up list saveList() { // this.allSelectedProducts=[] לבדוק עם מוצרים מהרשימה אם מתווסף או מה for (let i = 0; i <
conditional_block
products.page.ts
import { Component, OnInit } from '@angular/core'; import { ProductsService } from 'src/app/shared/services/products.service'; import { combineAll, first, ignoreElements, mapTo } from 'rxjs/operators'; import { ActivatedRoute, Router } from '@angular/router'; import { FollowUpService } from 'src/app/shared/services/fol...
GetAllProductsByTypeId() { this.listService.GetAllProductsByTypeId(this.typeListId).subscribe(res=> { this.setSelectedArray(res.map(p=>p.ProductId)) }) } setSelectedArray(res:number[]) { this.productService.getProductsByIdProduct(res).subscribe(products=>{ this.selectedsArray...
this.setSelectedArray(this.allSelectedProducts.map(p=>p)) }
identifier_body
material.rs
use std::ops::{Add, Div, Mul, Sub}; use crate::color::Color; use crate::hittable::HitRecord; use crate::ray::Ray; use crate::rtweekend; use crate::vec::Vec3; /// Generic material trait. pub trait Material<T: Copy> { /// Scatter an incoming light ray on a material. /// /// Returns a scattered ray and the a...
/// /// In our current design, N is a unit vector, but the same does not have to be true for V. /// Furthermore, V points inwards, so the sign has to be changed. /// All this is encoded in the reflect() function. pub struct Metal { /// Color of the object. albedo: Color, /// Fuziness of the specular reflect...
/// /// Additionally, B is an additional vector for illustration purposes. /// The reflected ray (in between N and B) has the same angle as the incident ray V with regards to // the surface. It can be computed as V + B + B.
random_line_split
material.rs
use std::ops::{Add, Div, Mul, Sub}; use crate::color::Color; use crate::hittable::HitRecord; use crate::ray::Ray; use crate::rtweekend; use crate::vec::Vec3; /// Generic material trait. pub trait Material<T: Copy> { /// Scatter an incoming light ray on a material. /// /// Returns a scattered ray and the a...
let r = ray.direction().normalized(); // cosθ = R⋅n let mut cos_theta = Vec3::dot(&(-r), &rec.normal); if cos_theta > 1.0 { cos_theta = 1.0; } // sinθ = sqrt(1 - cos²θ) let sin_theta = (1.0 - cos_theta * cos_theta).sqrt(); // Snell's law ...
and have to reflect) instead!
conditional_block
material.rs
use std::ops::{Add, Div, Mul, Sub}; use crate::color::Color; use crate::hittable::HitRecord; use crate::ray::Ray; use crate::rtweekend; use crate::vec::Vec3; /// Generic material trait. pub trait Material<T: Copy> { /// Scatter an incoming light ray on a material. /// /// Returns a scattered ray and the a...
} impl Material<f64> for Lambertian { fn scatter(&self, _ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // Diffuse reflection: True Lambertian reflection. // We aim for a Lambertian distribution of the reflected rays, which has a distribution of // cos(phi) instead of...
{ Lambertian { albedo } }
identifier_body
material.rs
use std::ops::{Add, Div, Mul, Sub}; use crate::color::Color; use crate::hittable::HitRecord; use crate::ray::Ray; use crate::rtweekend; use crate::vec::Vec3; /// Generic material trait. pub trait Material<T: Copy> { /// Scatter an incoming light ray on a material. /// /// Returns a scattered ray and the a...
{ /// Color of the object. albedo: Color, /// Fuziness of the specular reflections. fuzz: f64, } impl Metal { /// Create a new metallic material from a given intrinsic object color. /// /// * `albedo`: Intrinsic surface color. /// * `fuzz`: Fuzziness factor for specular reflection in th...
etal
identifier_name
singleVisit.component.ts
import { Component, OnDestroy, AfterViewInit, OnInit } from '@angular/core'; import {GoogleMaps, GoogleMap,GoogleMapsEvent,LatLng,CameraPosition,MarkerOptions,Marker} from '@ionic-native/google-maps'; import { Router } from '@angular/router'; import { SelectVisitServices} from '../services/selectVisit.service'; import ...
marker.addEventListener('click').subscribe((mobj)=>{ marker.showInfoWindow(); me.displayClickedMarkerDetails(mobj.get('custominfo')); }); }); }else{ //for desktop let image = { ...
{ marker.showInfoWindow(); me.defaultShowInfoWindow = true; }
conditional_block
singleVisit.component.ts
import { Component, OnDestroy, AfterViewInit, OnInit } from '@angular/core'; import {GoogleMaps, GoogleMap,GoogleMapsEvent,LatLng,CameraPosition,MarkerOptions,Marker} from '@ionic-native/google-maps'; import { Router } from '@angular/router'; import { SelectVisitServices} from '../services/selectVisit.service'; import ...
let visitLocationGrouped = _.groupBy(clientvisitLocations[1], function(locationObj: any){ return locationObj.CityName; }); let accentureOffices = []; _.forEach(visitLocationGrouped, function(paramObj, key){ //by default, display first marker position l...
random_line_split
singleVisit.component.ts
import { Component, OnDestroy, AfterViewInit, OnInit } from '@angular/core'; import {GoogleMaps, GoogleMap,GoogleMapsEvent,LatLng,CameraPosition,MarkerOptions,Marker} from '@ionic-native/google-maps'; import { Router } from '@angular/router'; import { SelectVisitServices} from '../services/selectVisit.service'; import ...
loadMap() { this.selectvisit.getVisitLocationDetails(this.selectvisit.selectedVisitObj.VisitID) .subscribe(locations => this.successLocationCallback(locations), error => this.errorMessage = <any>error); } private successLocationCallback(locations: any[]){ // create a new map ...
{ this.loadMap(); }
identifier_body
singleVisit.component.ts
import { Component, OnDestroy, AfterViewInit, OnInit } from '@angular/core'; import {GoogleMaps, GoogleMap,GoogleMapsEvent,LatLng,CameraPosition,MarkerOptions,Marker} from '@ionic-native/google-maps'; import { Router } from '@angular/router'; import { SelectVisitServices} from '../services/selectVisit.service'; import ...
() : void{ let me = this, counter = 0; me.displayVisitLocation.map(function(locationObj, key){ if(!counter){ me.selectedMapCityName = locationObj.CityName + ' '+ moment(locationObj.StartDate).format('Do MMM YYYY'); } // create LatLng object ...
addVisitLocationMarker
identifier_name
main.js
//新建二维数组用来表示table的坐标的 x坐标是第一层的数组 y坐标是第二层的数组 var arrs; //数组中有三种状态 墙1 空白0 图形2 //行 init(); function init(){ arrs = new Array(); for (var i = 0; i < 24; i++) { arrs[i] = new Array(); //列 for (var j = 0; j < 14; j++) { //当是第一行或者是最后一行或者是第一列或者是最后一列 为墙赋值为1 if (i == 0 || i == 23 || j == 0 || j == 13) { arrs[i][j] = ...
移动 能移动则把移动完数组的值赋给squarr if(canMove()){ squArr = target; //绘出来 block(); } } } } //拿到显示分数的盒子 var scoreBox = document.getElementById("score"); //显示的分数值 var score = 0; //消除的方法 function clear(){ //遍历整个数组 for(var i=22;i>=1;i--){ var isClear = true; for(var j=12;j>=1;j--){ if(arrs[i][j] != 2){ ...
r[i][0], squArr[i][1] + 1]; } else if (direction == "up") { //形状变化 给移动的数组赋变形后的值 change(); //判断是否能
identifier_body
main.js
//新建二维数组用来表示table的坐标的 x坐标是第一层的数组 y坐标是第二层的数组 var arrs; //数组中有三种状态 墙1 空白0 图形2 //行 init(); function init(){ arrs = new Array(); for (var i = 0; i < 24; i++) { arrs[i] = new Array(); //列 f
var j = 0; j < 14; j++) { //当是第一行或者是最后一行或者是第一列或者是最后一列 为墙赋值为1 if (i == 0 || i == 23 || j == 0 || j == 13) { arrs[i][j] = 1; } } } } //先拿到所有的单元格 数组 var tds = document.getElementsByTagName("td"); //控制难度的时间 datatime = 500; //随机生成颜色的方法 function randomColor(){ var r,g,b; r=Math.floor(Math.random()*166+90); g=Ma...
or (
identifier_name
main.js
//新建二维数组用来表示table的坐标的 x坐标是第一层的数组 y坐标是第二层的数组 var arrs; //数组中有三种状态 墙1 空白0 图形2 //行 init(); function init(){ arrs = new Array(); for (var i = 0; i < 24; i++) { arrs[i] = new Array(); //列 for (var j = 0; j < 14; j++) { //当是第一行或者是最后一行或者是第一列或者是最后一列 为墙赋值为1 if (i == 0 || i == 23 || j == 0 || j == 13) { arrs[i][j] = ...
le.log("我按了左箭头"); //把原本的坐标还原 hidden(); move("left"); if (canMove()) { squArr = [[-1,-1],[-1,-1],[-1,-1],[-1,-1]]; //如果可以移动 那么我的坐标就变成了移动完的坐标 squArr = target; } //赋值 block(); break; //按上箭头的时候 case 38: Chgcount++; move("up"); console.log("我按了上箭头"); break; //按右箭头的时候...
block(); //重新绘图 draw(); timer = setInterval("autoDown()", datatime); isBegin = true; } else { alert("当前游戏已经开始"); } break; //按左箭头的时候 case 37: conso
conditional_block
main.js
//新建二维数组用来表示table的坐标的 x坐标是第一层的数组 y坐标是第二层的数组 var arrs; //数组中有三种状态 墙1 空白0 图形2 //行 init(); function init(){ arrs = new Array(); for (var i = 0; i < 24; i++) { arrs[i] = new Array(); //列 for (var j = 0; j < 14; j++) { //当是第一行或者是最后一行或者是第一列或者是最后一列 为墙赋值为1 if (i == 0 || i == 23 || j == 0 || j == 13) { arrs[i][j] = ...
timer = setInterval("autoDown()", datatime); // isBegin = true; // } else { // alert("当前游戏已经开始"); // } } } randomBlock(); } //赋值 block(); //遍历二维数组 // for (var i = 0; i < arrs.length; i++) { // for (var j = 0; j < arrs[i].length; j++) { // } // } } function canMove() { va...
block(); //重新绘图 draw();
random_line_split
model.go
package word import "encoding/xml" //RelationshipTypeImage 图片文档映射关系类型 const RelationshipTypeImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" //PrefixRID rId前缀 const PrefixRID = "rId" //W word文档 type W struct { XMLName xml.Name `xml:"w:document"` Wpc string `xml:"xmlns:...
e `xml:"w:rPr"` RFonts *RFonts `xml:"w:rFonts,omitempty"` B *Bold `xml:"w:b,omitempty"` // BCs string `xml:"w:bCs,omitempty"` Color *Color `xml:"w:color"` Sz *Sz `xml:"w:sz"` SzCs *SzCs `xml:"w:szCs"` } //Bold 加粗 type Bold struct { XMLName xml.Name `xml:"w:b"` Val string `xml:"w:...
l.Nam
identifier_name
model.go
package word import "encoding/xml" //RelationshipTypeImage 图片文档映射关系类型 const RelationshipTypeImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" //PrefixRID rId前缀 const PrefixRID = "rId" //W word文档 type W struct { XMLName xml.Name `xml:"w:document"` Wpc string `xml:"xmlns:...
:"w:rPr"` RFonts *RFonts `xml:"w:rFonts,omitempty"` B *Bold `xml:"w:b,omitempty"` // BCs string `xml:"w:bCs,omitempty"` Color *Color `xml:"w:color"` Sz *Sz `xml:"w:sz"` SzCs *SzCs `xml:"w:szCs"` } //Bold 加粗 type Bold struct { XMLName xml.Name `xml:"w:b"` Val string `xml:"w:val,at...
xml
identifier_body
model.go
package word import "encoding/xml" //RelationshipTypeImage 图片文档映射关系类型 const RelationshipTypeImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" //PrefixRID rId前缀 const PrefixRID = "rId" //W word文档 type W struct { XMLName xml.Name `xml:"w:document"` Wpc string `xml:"xmlns:...
XMLName xml.Name `xml:"w:jc"` Val string `xml:"w:val,attr,omitempty"` } //T 文本 type T struct { XMLName xml.Name `xml:"w:t"` Space string `xml:"xml:space,attr,omitempty"` //"preserve" // Space string `xml:"w:space,attr,omitempty"` Text string `xml:",chardata"` } //Drawing 绘图 type Drawing struct { XMLN...
//Jc 对齐方式 <w:jc w:val="left"/> type Jc struct {
random_line_split
minesweeper.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Feb 20 11:15:50 2017 @author: yaojie """ import random import sys from copy import deepcopy class Minesweeper(object): # just for readability WIN = True IS_A_BOMB = True NOT_A_BOMB = False # Unicode just to look pretty FLA...
return mine_locations def generate_answer(self): ft = deepcopy(self.table_state) for x in range(0, self.x): for y in range(0, self.y): # get the number or mine with neighbours ft[y][x] = self.get_neighbour(y, x) return ft def get_nei...
choice = random.choice(available_places) available_places.remove(choice) mine_locations.append(choice) number -= 1
conditional_block
minesweeper.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Feb 20 11:15:50 2017 @author: yaojie """ import random import sys from copy import deepcopy class Minesweeper(object): # just for readability WIN = True IS_A_BOMB = True NOT_A_BOMB = False # Unicode just to look pretty FLA...
if self.final_table[ye][xe] == Minesweeper.BOMB and self.table_state[ye][xe] != Minesweeper.FLAG: self.show_answer_board([ye, xe]) print "KABOOM!" return Minesweeper.IS_A_BOMB self.open_neighbours(y, x) self.print_table(self...
x - 1, x + 2) if xe >= 0 for ye in range(y - 1, y + 2) if ye >= 0] for ye, xe in l: if xe >= self.x or ye >= self.y: # do not open out of bounds continue # if it is a bomb but not flagged
random_line_split
minesweeper.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Feb 20 11:15:50 2017 @author: yaojie """ import random import sys from copy import deepcopy class Minesweeper(object): # just for readability WIN = True IS_A_BOMB = True NOT_A_BOMB = False # Unicode just to look pretty FLA...
(self, height, width, mines): """initializes the Minesweeper instance with a width, height, and the number of mines. Sets up a default game table, generates random mine locations and updates another table for the solution.""" self.x = int(width) self.y = int(height) self.table_st...
__init__
identifier_name
minesweeper.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Feb 20 11:15:50 2017 @author: yaojie """ import random import sys from copy import deepcopy class Minesweeper(object): # just for readability WIN = True IS_A_BOMB = True NOT_A_BOMB = False # Unicode just to look pretty FLA...
def flags_nearby(self, y, x): """ gets number of flags nearby """ count = 0 l = [[ye, xe] for xe in range( x - 1, x + 2) if xe >= 0 for ye in range(y - 1, y + 2) if ye >= 0] for ye, xe in l: if xe >= self.x or ye >= self.y: continue ...
"""populate answer table with numbers and mines""" if [y, x] in self.mine_locations: return Minesweeper.BOMB count = 0 # (x-1, y-1), (x, y-1), (x+1, y-1), # (x-1, y), (x, y), (x+1, y), # (x-1, y+1), (x, y+1), (x+1, y+1) for xe in range(x - 1, x + 2): ...
identifier_body
IBRAHIM_OLADOKUN.py
#!/usr/bin/env python # coding: utf-8 # # Probability of default: credit scoring model # Building a model that borrowers can use to help make the best financial decisions. # The following variables are contained in the csv Dataset given: # # VARIABLE NAMES : DESCRIPTIO...
# In[64]: # Exploring Late6089 feature quantiles vs Target g = sns.factorplot(x="Late6089",y="Target",data=dataset,kind="bar", size = 6 , palette = "muted") g.despine(left=True) g = g.set_ylabels("Target probability") # # Exploring Deps # In[65]: dataset.Deps.describe() # In[66]: dataset.Deps = dataset....
if dataset.Late6089[i] >= 3: dataset.Late6089[i] = 3
conditional_block
IBRAHIM_OLADOKUN.py
#!/usr/bin/env python # coding: utf-8 # # Probability of default: credit scoring model # Building a model that borrowers can use to help make the best financial decisions. # The following variables are contained in the csv Dataset given: # # VARIABLE NAMES : DESCRIPTIO...
# Interquartile range (IQR) IQR = Q3 - Q1 # outlier step outlier_step = 1.5 * IQR # Determine a list of indices of outliers for feature col outlier_list_col = df[(df[col] < Q1 - outlier_step) | (df[col] > Q3 + outlier_step )].index # app...
Q1 = np.percentile(df[col], 25) # 3rd quartile (75%) Q3 = np.percentile(df[col],75)
random_line_split
IBRAHIM_OLADOKUN.py
#!/usr/bin/env python # coding: utf-8 # # Probability of default: credit scoring model # Building a model that borrowers can use to help make the best financial decisions. # The following variables are contained in the csv Dataset given: # # VARIABLE NAMES : DESCRIPTIO...
# detect outliers from Age, SibSp , Parch and Fare # These are the numerical features present in the dataset Outliers_to_drop = detect_outliers(train,2,["RevolvingUtilizationOfUnsecuredLines", "age", "NumberOfTime30-59DaysPastDueN...
outlier_indices = [] # iterate over features(columns) for col in features: # 1st quartile (25%) Q1 = np.percentile(df[col], 25) # 3rd quartile (75%) Q3 = np.percentile(df[col],75) # Interquartile range (IQR) IQR = Q3 - Q1 # outlier step ...
identifier_body
IBRAHIM_OLADOKUN.py
#!/usr/bin/env python # coding: utf-8 # # Probability of default: credit scoring model # Building a model that borrowers can use to help make the best financial decisions. # The following variables are contained in the csv Dataset given: # # VARIABLE NAMES : DESCRIPTIO...
(df,n,features): outlier_indices = [] # iterate over features(columns) for col in features: # 1st quartile (25%) Q1 = np.percentile(df[col], 25) # 3rd quartile (75%) Q3 = np.percentile(df[col],75) # Interquartile range (IQR) IQR = Q3 - Q1 ...
detect_outliers
identifier_name
putio-ftp-connector.py
#!/usr/bin/env python # $Id: basic_ftpd.py 569 2009-04-04 00:17:43Z billiejoex $ """A basic FTP server which uses a DummyAuthorizer for managing 'virtual users', setting a limit for incoming connections. """ import os #from pyftpdlib import ftpserver import urllib2 import base64 import putio from pathtoid import Pa...
else: key = '%s/%s' % (pathtoid._utf8(basedir), pathtoid._utf8(i.name)) self.dirlistcache[key] = i print 'key:', key yield ln.encode('utf-8') class HttpOperations(object): '''Storing connection object''' def __init__(self): self.connection = Non...
key = '/%s' % (pathtoid._utf8(i.name))
conditional_block
putio-ftp-connector.py
#!/usr/bin/env python # $Id: basic_ftpd.py 569 2009-04-04 00:17:43Z billiejoex $ """A basic FTP server which uses a DummyAuthorizer for managing 'virtual users', setting a limit for incoming connections. """ import os #from pyftpdlib import ftpserver import urllib2 import base64 import putio from pathtoid import Pa...
if not username: return False print "> welcome ", username return True def __repr__(self): return self.connection operations = HttpOperations() class HttpAuthorizer(ftpserver.DummyAuthorizer): '''FTP server authorizer. Logs the users into Putio Cloud Fil...
print "checking user & passwd" username = self.api.get_user_name()
random_line_split
putio-ftp-connector.py
#!/usr/bin/env python # $Id: basic_ftpd.py 569 2009-04-04 00:17:43Z billiejoex $ """A basic FTP server which uses a DummyAuthorizer for managing 'virtual users', setting a limit for incoming connections. """ import os #from pyftpdlib import ftpserver import urllib2 import base64 import putio from pathtoid import Pa...
(self, filename): if filename in self.dirlistcache: apifile = self.dirlistcache[filename] print 'found........', apifile.id, apifile.name else: if filename == os.path.sep: # items = operations.api.get_items() return False else: ...
_getitem
identifier_name
putio-ftp-connector.py
#!/usr/bin/env python # $Id: basic_ftpd.py 569 2009-04-04 00:17:43Z billiejoex $ """A basic FTP server which uses a DummyAuthorizer for managing 'virtual users', setting a limit for incoming connections. """ import os #from pyftpdlib import ftpserver import urllib2 import base64 import putio from pathtoid import Pa...
def listdir(self, path): ret = [] try: item = self._getitem(path) except: return [] if not item: items = operations.api.get_items() else: try: items = operations.api.get_items(parent_id=item.id) except: ...
dirs = os.path.split(path) apifile = self._getitem(dirs[0]) if not apifile: #this is root operations.api.create_folder(name = dirs[1], parent_id = 0) else: apifile.create_folder(name=dirs[1]) self.remove_from_cache(path) self.remove_from_cache(dirs[0])
identifier_body
glfw.go
// Copyright 2016 The G3N Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build !wasm // +build !wasm package window import ( "bytes" "fmt" "image" _ "image/png" "os" "runtime" "github.com/g3n/engine/core" "github.com...
// Destroy destroys this window and its context func (w *GlfwWindow) Destroy() { w.Window.Destroy() glfw.Terminate() runtime.UnlockOSThread() // Important when using the execution tracer } // Scale returns this window's DPI scale factor (FramebufferSize / Size) func (w *GlfwWindow) GetScale() (x float64, y float...
{ // If already in the desired state, nothing to do if w.fullscreen == full { return } // Set window fullscreen on the primary monitor if full { // Save current position and size of the window w.lastX, w.lastY = w.GetPos() w.lastWidth, w.lastHeight = w.GetSize() // Get size of primary monitor mon := g...
identifier_body
glfw.go
// Copyright 2016 The G3N Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build !wasm // +build !wasm package window import ( "bytes" "fmt" "image" _ "image/png" "os" "runtime" "github.com/g3n/engine/core" "github.com...
} // Set the next cursor key as the last standard cursor key + 1 w.lastCursorKey = CursorLast } // Center centers the window on the screen. //func (w *GlfwWindow) Center() { // // // TODO //}
{ w.cursors[key].Destroy() delete(w.cursors, key) }
conditional_block
glfw.go
// Copyright 2016 The G3N Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build !wasm // +build !wasm package window import ( "bytes" "fmt" "image" _ "image/png" "os" "runtime" "github.com/g3n/engine/core" "github.com...
() bool { return w.fullscreen } // SetFullScreen sets this window as fullscreen on the primary monitor // TODO allow for fullscreen with resolutions different than the monitor's func (w *GlfwWindow) SetFullScreen(full bool) { // If already in the desired state, nothing to do if w.fullscreen == full { return } ...
FullScreen
identifier_name
glfw.go
// Copyright 2016 The G3N Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build !wasm // +build !wasm package window import ( "bytes" "fmt" "image" _ "image/png" "os" "runtime" "github.com/g3n/engine/core" "github.com...
return w.lastCursorKey, nil } // DisposeCursor deletes the existing custom cursor with the provided int handle. func (w *GlfwWindow) DisposeCursor(cursor Cursor) { if cursor <= CursorLast { panic("Can't dispose standard cursor") } w.cursors[cursor].Destroy() delete(w.cursors, cursor) } // DisposeAllCursors d...
} // Create and store cursor w.lastCursorKey += 1 w.cursors[Cursor(w.lastCursorKey)] = glfw.CreateCursor(img, xhot, yhot)
random_line_split
rf_model.py
""" CCC Team 42, Melbourne Thuy Ngoc Ha - 963370 Lan Zhou - 824371 Zijian Wang - 950618 Ivan Chee - 736901 Duer Wang - 824325 """ """ A python file used for making predictions on tweeters that lack food information or homeless information. Using random forest classification model for predicting food. Using ran...
""" --------------------------------------------------------- --------------------- Main Function --------------------- --------------------------------------------------------- """ if __name__ == "__main__": COUCHDB_NAME = sys.argv[1] OUT_COUCHDB_NAME = sys.argv[2] REFORMED_FILE = sys.argv[3] ...
if food in Keywords.fastfood: return "fastfood" if food in Keywords.fruits: return "fruits" if food in Keywords.grains: return "grains" if food in Keywords.meat: return "meat" if food in Keywords.seafood: return "seafood" if food in Keywords.vegetables: ...
identifier_body
rf_model.py
""" CCC Team 42, Melbourne Thuy Ngoc Ha - 963370 Lan Zhou - 824371 Zijian Wang - 950618 Ivan Chee - 736901 Duer Wang - 824325 """ """ A python file used for making predictions on tweeters that lack food information or homeless information. Using random forest classification model for predicting food. Using ran...
(food): if food in Keywords.fastfood: return "fastfood" if food in Keywords.fruits: return "fruits" if food in Keywords.grains: return "grains" if food in Keywords.meat: return "meat" if food in Keywords.seafood: return "seafood" if food in Keywords.vegeta...
get_food_group
identifier_name
rf_model.py
""" CCC Team 42, Melbourne Thuy Ngoc Ha - 963370 Lan Zhou - 824371 Zijian Wang - 950618 Ivan Chee - 736901 Duer Wang - 824325 """ """ A python file used for making predictions on tweeters that lack food information or homeless information. Using random forest classification model for predicting food. Using ran...
entry["properties"]["polarity"] = json_obj["polarity"] entry["properties"]["followers"] = json_obj["followers"] entry["properties"]["following"] = json_obj["following"] entry["properties"]["food"] = json_obj["food"] entry["properties"]["food_group"] = json_obj["food_group"] ...
entry["properties"]["time"] = json_obj["time"]
random_line_split
rf_model.py
""" CCC Team 42, Melbourne Thuy Ngoc Ha - 963370 Lan Zhou - 824371 Zijian Wang - 950618 Ivan Chee - 736901 Duer Wang - 824325 """ """ A python file used for making predictions on tweeters that lack food information or homeless information. Using random forest classification model for predicting food. Using ran...
csvfile.close() def trans_month(month): month_dic = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', \ 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', \ 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'} return month_dic[month] # transform food ...
try: # get coordinates if dic['location']['coordinates'] is None: city = dic['location']['place_name'] city = city.replace(" ","%20") coor = cityPos(city) lng = coor['location']['lng'] lat = coor['location']['lat'] ...
conditional_block
actions.rs
use crate::cards::CardInstance; use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION}; use crate::geometry::{ Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation, TILE_RADIUS, TILE_SIZE, TILE_WIDTH, }; use crate::mechanisms::{BuildMechanism...
} #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct BuildConveyor { pub allow_splitting: bool, } #[derive(Copy, Clone, PartialEq, Serialize, Deserialize, Debug)] struct BuildConveyorCandidate { position: GridVector, input_side: Facing, } impl BuildConveyorCandidate { fn input_position(&s...
{ draw.rectangle_on_map( 5, game.player.position.containing_tile().to_floating(), TILE_SIZE.to_floating(), "#666", ); }
identifier_body
actions.rs
use crate::cards::CardInstance; use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION}; use crate::geometry::{ Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation, TILE_RADIUS, TILE_SIZE, TILE_WIDTH, }; use crate::mechanisms::{BuildMechanism...
(&self) -> bool { self.progress > self.finish_time() } fn health_to_pay_by(&self, progress: f64) -> f64 { smootherstep(self.startup_time(), self.finish_time(), progress) * self.health_cost() } } impl ActionTrait for SimpleAction { fn update(&mut self, context: ActionUpdateContext) -> ActionStatus { ...
finished
identifier_name
actions.rs
use crate::cards::CardInstance; use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION}; use crate::geometry::{ Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation, TILE_RADIUS, TILE_SIZE, TILE_WIDTH, }; use crate::mechanisms::{BuildMechanism...
} _ => unreachable!(), } } self.simple_action_type.finish(context); } } if self.progress > self.time_cost() || self.cancel_progress > self.cooldown_time() { ActionStatus::Completed } else { ActionStatus::StillGoing } } fn display...
{ context.game.cards.selected_index = Some(index + 1); }
conditional_block
actions.rs
use crate::cards::CardInstance; use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION}; use crate::geometry::{ Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation, TILE_RADIUS, TILE_SIZE, TILE_WIDTH, }; use crate::mechanisms::{BuildMechanism...
}
random_line_split
train.py
import argparse from prepro import read_correction import os import numpy as np import torch from apex import amp import ujson as json from torch.utils.data import DataLoader from transformers import AutoConfig, AutoModel, AutoTokenizer from transformers.optimization import AdamW, get_linear_schedule_with_warmup from ...
if __name__ == "__main__": main()
parser = argparse.ArgumentParser() parser.add_argument("--data_dir", default="./dataset/docred", type=str) parser.add_argument("--transformer_type", default="bert", type=str) parser.add_argument("--model_name_or_path", default="bert-base-cased", type=str) parser.add_argument("--train_file", default="t...
identifier_body
train.py
import argparse from prepro import read_correction import os import numpy as np import torch from apex import amp import ujson as json from torch.utils.data import DataLoader from transformers import AutoConfig, AutoModel, AutoTokenizer from transformers.optimization import AdamW, get_linear_schedule_with_warmup from ...
(args, model, features, tag="dev"): dataloader = DataLoader(features, batch_size=args.test_batch_size, shuffle=False, collate_fn=collate_fn, drop_last=False) preds = [] for batch in dataloader: model.eval() inputs = {'input_ids': batch[0].to(args.device), 'attention_mask'...
evaluate
identifier_name
train.py
import argparse from prepro import read_correction import os import numpy as np import torch from apex import amp import ujson as json from torch.utils.data import DataLoader from transformers import AutoConfig, AutoModel, AutoTokenizer from transformers.optimization import AdamW, get_linear_schedule_with_warmup from ...
dev_score, dev_output = evaluate(args, model, dev_features, tag="dev") #wandb.log(dev_output, step=num_steps) print(dev_output) if dev_score > best_score: best_score = dev_score pred = report(...
'''
random_line_split
train.py
import argparse from prepro import read_correction import os import numpy as np import torch from apex import amp import ujson as json from torch.utils.data import DataLoader from transformers import AutoConfig, AutoModel, AutoTokenizer from transformers.optimization import AdamW, get_linear_schedule_with_warmup from ...
output = { tag + "_F1": best_f1 * 100, tag + "_F1_ign": best_f1_ign * 100, } return best_f1, output def report(args, model, features): dataloader = DataLoader(features, batch_size=args.test_batch_size, shuffle=False, collate_fn=collate_fn, drop_last=False) preds = [] for batc...
best_f1, _, best_f1_ign, _ = official_evaluate(ans, args.data_dir)
conditional_block
Set.go
// PRELIMINARIES: package Set import ( "fmt" "strconv" ) // ***************************************************************************** // STRUCTS AND INTERFACES: type setMember interface{} // Lets the members of a set be, in effect, of arbitrary type. type Set struct { mem map[setMember]bool } /* The membe...
() string { mySetSlice := []setMember{} for i := range s.mem { mySetSlice = append(mySetSlice, i) } myString := fmt.Sprint(mySetSlice) return myString } func testSetString(theSetString string, theSet Set) { counter := 0 for i := range theSet.mem { for k := 0; k < len(theSetString); k++ { if fmt.Spri...
SetString
identifier_name
Set.go
// PRELIMINARIES: package Set import ( "fmt" "strconv" ) // ***************************************************************************** // STRUCTS AND INTERFACES: type setMember interface{} // Lets the members of a set be, in effect, of arbitrary type. type Set struct { mem map[setMember]bool } /* The membe...
unionSet := NewSet() for k := range s.mem { unionSet.mem[k] = true } // Adds the elements of the set to the union set. for k := range otherSet.mem { unionSet.mem[k] = true } // Adds the elements of the set in the argument to the union set. return unionSet } // -------------------------------------------...
another set specified in the argument of the function. */ func (s Set) Union(otherSet Set) Set {
random_line_split
Set.go
// PRELIMINARIES: package Set import ( "fmt" "strconv" ) // ***************************************************************************** // STRUCTS AND INTERFACES: type setMember interface{} // Lets the members of a set be, in effect, of arbitrary type. type Set struct { mem map[setMember]bool } /* The membe...
// ----------------------------------------------------------------------------- // Set equality: Two sets are equal if they have the same elements. func Equals(oneSet, otherSet Set) bool { if len(oneSet.mem) != len(otherSet.mem) { return false } /* Obviously, if the sets have different numbers of elements, th...
{ delete(s.mem, removeMem) }
identifier_body
Set.go
// PRELIMINARIES: package Set import ( "fmt" "strconv" ) // ***************************************************************************** // STRUCTS AND INTERFACES: type setMember interface{} // Lets the members of a set be, in effect, of arbitrary type. type Set struct { mem map[setMember]bool } /* The membe...
// Adds the elements of the set in the argument to the union set. return unionSet } // ----------------------------------------------------------------------------- /* The intersection of two sets is the set of members of both sets. This function is a method which acts on a set and returns the intersection of it ...
{ unionSet.mem[k] = true }
conditional_block
gitiles.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: go.chromium.org/luci/common/proto/gitiles/gitiles.proto package gitiles import prpc "go.chromium.org/luci/grpc/prpc" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import git "go.chromium.org/luci/common/proto/git" impo...
() string { if m != nil { return m.Project } return "" } func (m *RefsRequest) GetRefsPath() string { if m != nil { return m.RefsPath } return "" } // RefsResponse is a response message of Gitiles.Refs RPC. type RefsResponse struct { // revisions maps a ref to a revision. // Git branches have keys start w...
GetProject
identifier_name
gitiles.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: go.chromium.org/luci/common/proto/gitiles/gitiles.proto package gitiles import prpc "go.chromium.org/luci/grpc/prpc" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import git "go.chromium.org/luci/common/proto/git" impo...
return out, nil } func (c *gitilesPRPCClient) Refs(ctx context.Context, in *RefsRequest, opts ...grpc.CallOption) (*RefsResponse, error) { out := new(RefsResponse) err := c.client.Call(ctx, "gitiles.Gitiles", "Refs", in, out, opts...) if err != nil { return nil, err } return out, nil } type gitilesClient str...
{ return nil, err }
conditional_block
gitiles.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: go.chromium.org/luci/common/proto/gitiles/gitiles.proto package gitiles import prpc "go.chromium.org/luci/grpc/prpc" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import git "go.chromium.org/luci/common/proto/git" impo...
func (m *LogRequest) GetTreeDiff() bool { if m != nil { return m.TreeDiff } return false } func (m *LogRequest) GetPageToken() string { if m != nil { return m.PageToken } return "" } func (m *LogRequest) GetPageSize() int32 { if m != nil { return m.PageSize } return 0 } // LogRequest is response mes...
{ if m != nil { return m.Ancestor } return "" }
identifier_body
gitiles.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: go.chromium.org/luci/common/proto/gitiles/gitiles.proto package gitiles import prpc "go.chromium.org/luci/grpc/prpc" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import git "go.chromium.org/luci/common/proto/git" impo...
} return "" } func (m *RefsRequest) GetRefsPath() string { if m != nil { return m.RefsPath } return "" } // RefsResponse is a response message of Gitiles.Refs RPC. type RefsResponse struct { // revisions maps a ref to a revision. // Git branches have keys start with "refs/heads/". Revisions map[s...
func (m *RefsRequest) GetProject() string { if m != nil { return m.Project
random_line_split
lib.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
{ pub name: String, pub id: usize, } /// The response to [`Client::database_metadata`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct DatabaseMetadata { pub tables: Vec<Table>, } /// A table that is part of [`DatabaseMetadata`]. #[derive(Clone, Debug, Deserialize, Serialize, E...
Database
identifier_name
lib.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
/// A field of a [`Table`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct TableField { pub name: String, pub database_type: String, pub base_type: String, pub special_type: Option<String>, }
pub name: String, pub schema: String, pub fields: Vec<TableField>, }
random_line_split
transaction.rs
use std::collections::HashMap; use std::hash::Hash; use std::ops::Range; use rusqlite::Connection; use ::serde::Serialize; use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime}; use crate::db::account_dao::AccountDao; use crate::db::transaction_dao::{Split, Transaction, TransactionDao}; use crate::db::acco...
#[derive(Debug)] #[derive(Serialize)] pub struct MonthlyTotals { summaries: Vec<MonthTotal>, totalSpent: i64, pub acctSums: Vec<MonthlyExpenseGroup> } #[derive(Debug)] #[derive(Serialize)] pub struct AccountSummary { name: String, monthlyTotals: Vec<MonthlyTotal>, } #[derive(Debug)] #[derive(Ser...
{ let (since_nd, until_nd) = since_until(since, until, months, year); let dao = TransactionDao { conn: &conn }; dao.list(&since_nd, &until_nd) }
identifier_body
transaction.rs
use std::collections::HashMap; use std::hash::Hash; use std::ops::Range; use rusqlite::Connection; use ::serde::Serialize; use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime}; use crate::db::account_dao::AccountDao; use crate::db::transaction_dao::{Split, Transaction, TransactionDao}; use crate::db::acco...
; NaiveDate::from_ymd(curr_year, curr_month, 1) }).collect::<Vec<_>>(); desired_months.insert(0, NaiveDate::from_ymd(until.year(), until.month(), 1)); let mut cloned_expenses = expenses.clone(); (0..cloned_expenses.len()).for_each(|i| { let mut exp = &mut cloned_expenses[i]; ...
{ curr_month -= 1; }
conditional_block
transaction.rs
use std::collections::HashMap; use std::hash::Hash; use std::ops::Range; use rusqlite::Connection; use ::serde::Serialize; use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime}; use crate::db::account_dao::AccountDao; use crate::db::transaction_dao::{Split, Transaction, TransactionDao}; use crate::db::acco...
{ pub name: String, pub total: i64, monthlyTotals: Vec<MonthTotal>, } fn expenses_by_month( transactions: &Vec<Transaction>, accounts: &Vec<Account> ) -> Vec<MonthlyExpenseGroup> { let mut accounts_map = HashMap::new(); for a in accounts { accounts_map.insert(&a.guid, a); } ...
MonthlyExpenseGroup
identifier_name
transaction.rs
use std::collections::HashMap; use std::hash::Hash; use std::ops::Range; use rusqlite::Connection; use ::serde::Serialize; use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime}; use crate::db::account_dao::AccountDao; use crate::db::transaction_dao::{Split, Transaction, TransactionDao}; use crate::db::acco...
}).collect::<Vec<_>>(); summed.sort_by(|a, b| parse_nd(&b.month).cmp(&parse_nd(&a.month))); let total_spent = summed.iter().map(|m| m.total).sum(); //let mut acct_sums = months.clone(); MonthlyTotals { summaries: summed, totalSpent: total_spent, acctSums: months.clone() ...
month: i, total: month_summary.into_iter().map(|m| m.total).sum() }
random_line_split
glyph_brush.rs
mod builder; pub use self::builder::*; use super::*; use full_rusttype::gpu_cache::Cache; use hashbrown::hash_map::Entry; use log::error; use std::{ borrow::Cow, fmt, hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}, i32, }; /// A hash of `Section` data type SectionHash = u64; ...
Ok(None) => None, Ok(Some((tex_coords, pixel_coords))) => { if pixel_coords.min.x as f32 > bounds.max.x || pixel_coords.min.y as f32 > bounds.max.y || bound...
None }
random_line_split
glyph_brush.rs
mod builder; pub use self::builder::*; use super::*; use full_rusttype::gpu_cache::Cache; use hashbrown::hash_map::Entry; use log::error; use std::{ borrow::Cow, fmt, hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}, i32, }; /// A hash of `Section` data type SectionHash = u64; ...
let verts: Vec<V> = if some_text { let sections: Vec<_> = self .section_buffer .iter() .map(|hash| &self.calculate_glyph_cache[hash]) .collect(); let mut verts = Vec::with_capacity( ...
{ let (width, height) = self.texture_cache.dimensions(); return Err(BrushError::TextureTooSmall { suggested: (width * 2, height * 2), }); }
conditional_block
glyph_brush.rs
mod builder; pub use self::builder::*; use super::*; use full_rusttype::gpu_cache::Cache; use hashbrown::hash_map::Entry; use log::error; use std::{ borrow::Cow, fmt, hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}, i32, }; /// A hash of `Section` data type SectionHash = u64; ...
/// Adds an additional font to the one(s) initially added on build. /// /// Returns a new [`FontId`](struct.FontId.html) to reference this font. pub fn add_font<'a: 'font>(&mut self, font_data: Font<'a>) -> FontId { self.fonts.push(font_data); FontId(self.fonts.len() - 1) }...
{ self.add_font(Font::from_bytes(font_data.into()).unwrap()) }
identifier_body
glyph_brush.rs
mod builder; pub use self::builder::*; use super::*; use full_rusttype::gpu_cache::Cache; use hashbrown::hash_map::Entry; use log::error; use std::{ borrow::Cow, fmt, hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}, i32, }; /// A hash of `Section` data type SectionHash = u64; ...
<'a, S, G>(&mut self, section: S, custom_layout: &G) where S: Into<Cow<'a, VariedSection<'a>>>, G: GlyphPositioner, { if !self.cache_glyph_positioning { return; } let section = section.into(); if cfg!(debug_assertions) { for text ...
keep_cached_custom_layout
identifier_name
main.go
// Copyright 2018 Goole Inc. // Copyright 2020 Tobias Schwarz // // 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 b...
func getTendermintRPC(endpoint string) string { resp, err := resty.R(). SetHeader("Cache-Control", "no-cache"). SetHeader("Content-Type", "application/json"). Get(tendermintRPC + endpoint) if err != nil { panic(err) } return resp.String() } // writeTime writes the current system time to the timeWidget. /...
}
random_line_split
main.go
// Copyright 2018 Goole Inc. // Copyright 2020 Tobias Schwarz // // 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 b...
ntext, t *text.Text, delay time.Duration) { peers := gjson.Get(getFromRPC("net_info"), "result.n_peers").String() t.Reset() if peers != "" { t.Write(peers) } if err := t.Write(peers); err != nil { panic(err) } ticker := time.NewTicker(delay) defer ticker.Stop() for { select { case <-ticker.C: t.Re...
context.Co
identifier_name
main.go
// Copyright 2018 Goole Inc. // Copyright 2020 Tobias Schwarz // // 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 b...
unc getFromRPC(endpoint string) string { port := *givenPort resp, _ := resty.R(). SetHeader("Cache-Control", "no-cache"). SetHeader("Content-Type", "application/json"). Get(appRPC + ":" + port + "/" + endpoint) return resp.String() } func getTendermintRPC(endpoint string) string { resp, err := resty.R(). ...
{ view() connectionSignal := make(chan string) t, err := termbox.New() if err != nil { panic(err) } defer t.Close() flag.Parse() networkInfo := getFromRPC("status") networkStatus := gjson.Parse(networkInfo) if !networkStatus.Exists() { panic("Application not running on localhost:" + fmt.Sprintf("%s", *g...
identifier_body
main.go
// Copyright 2018 Goole Inc. // Copyright 2020 Tobias Schwarz // // 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 b...
return resp.String() } // writeTime writes the current system time to the timeWidget. // Exits when the context expires. func writeTime(ctx context.Context, t *text.Text, delay time.Duration) { ticker := time.NewTicker(delay) defer ticker.Stop() for { select { case <-ticker.C: currentTime := time.Now() t...
panic(err) }
conditional_block
shared.rs
/* Copyright 2016 Torbjørn Birch Moltu * * 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 agre...
let b2 = b.clone(); let mut z = Nbstr::from(b); assert_eq!(z.deref().len(), len); assert_eq!(z.deref().as_ptr(), ptr); assert_eq!(z.deref(), STR); assert_eq!(take_box(&mut z), Some(b2.clone())); assert_eq!(take_box(&mut Nbstr::from_str(STR)), Some(b2.clone())); ...
fn boxed() { let b: Box<str> = STR.to_string().into_boxed_str(); let len = b.len(); let ptr = b.as_ptr();
random_line_split
shared.rs
/* Copyright 2016 Torbjørn Birch Moltu * * 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 agre...
impl From<Nbstr> for Box<str> { fn from(mut z: Nbstr) -> Box<str> { take_box(&mut z).unwrap_or_else(|| z.deref().to_owned().into_boxed_str() ) } } impl From<Nbstr> for String { fn from(mut z: Nbstr) -> String { take_box(&mut z) .map(|b| b.into_string() ) .unwrap_or_e...
if z.variant() == BOX { // I asked on #rust, and transmuting from & to mut is apparently undefined behaviour. // Is it really in this case? let s: *mut str = unsafe{ mem::transmute(z.get_slice()) }; // Cannot just assign default; then rust tries to drop the previous value! /...
identifier_body
shared.rs
/* Copyright 2016 Torbjørn Birch Moltu * * 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 agre...
s: &'static str) -> Self { Self::with_pointer(LITERAL, s) } } impl Nbstr { fn try_stack(s: &str) -> Option<Self> {match s.len() as u8 { // Cannot have stack str with length 0, as variant might be NonZero 0 => Some(Self::default()), 1...MAX_STACK => { let mut z = Self:...
rom(
identifier_name
packfile.rs
use bytes::{BufMut, BytesMut}; use flate2::{write::ZlibEncoder, Compression}; use sha1::{ digest::{generic_array::GenericArray, FixedOutputDirty}, Digest, Sha1, }; use std::{convert::TryInto, fmt::Write, io::Write as IoWrite}; // The packfile itself is a very simple format. There is a header, a // series of pa...
} #[derive(Debug)] pub enum TreeItemKind { File, Directory, } impl TreeItemKind { #[must_use] pub const fn mode(&self) -> &'static str { match self { Self::File => "100644", Self::Directory => "40000", } } } #[derive(Debug)] pub struct TreeItem<'a> { pu...
+ " +0000".len() }
random_line_split
packfile.rs
use bytes::{BufMut, BytesMut}; use flate2::{write::ZlibEncoder, Compression}; use sha1::{ digest::{generic_array::GenericArray, FixedOutputDirty}, Digest, Sha1, }; use std::{convert::TryInto, fmt::Write, io::Write as IoWrite}; // The packfile itself is a very simple format. There is a header, a // series of pa...
e_to(&mut out)?; } } Self::Blob(blob) => { out.extend_from_slice(blob); } } Ok(sha1::Sha1::digest(&out)) } }
for item in items { item.encod
conditional_block
packfile.rs
use bytes::{BufMut, BytesMut}; use flate2::{write::ZlibEncoder, Compression}; use sha1::{ digest::{generic_array::GenericArray, FixedOutputDirty}, Digest, Sha1, }; use std::{convert::TryInto, fmt::Write, io::Write as IoWrite}; // The packfile itself is a very simple format. There is a header, a // series of pa...
pub fn encode_to(&self, original_buf: &mut BytesMut) -> Result<(), anyhow::Error> { let mut buf = original_buf.split_off(original_buf.len()); buf.reserve(Self::header_size() + Self::footer_size()); // header buf.extend_from_slice(b"PACK"); // magic header buf.put_u32(2); /...
{ 20 }
identifier_body
packfile.rs
use bytes::{BufMut, BytesMut}; use flate2::{write::ZlibEncoder, Compression}; use sha1::{ digest::{generic_array::GenericArray, FixedOutputDirty}, Digest, Sha1, }; use std::{convert::TryInto, fmt::Write, io::Write as IoWrite}; // The packfile itself is a very simple format. There is a header, a // series of pa...
(&self) -> usize { self.kind.mode().len() + " ".len() + self.name.len() + "\0".len() + self.hash.len() } } #[derive(Debug)] pub enum PackFileEntry<'a> { // jordan@Jordans-MacBook-Pro-2 0d % printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" | cat - f5/473259d9674ed66239766a013f96a3550374e3 | gzip -dc // com...
size
identifier_name
poll.rs
extern crate nix; use std::os::unix::io::AsRawFd; use std::os::unix::io::RawFd; use std::time; use std::io; use self::nix::sys::epoll; /// Polls for readiness events on all registered file descriptors. /// /// `Poll` allows a program to monitor a large number of file descriptors, waiting until one or /// more become ...
/// # } /// ``` /// /// # Exclusive access /// /// Since this `Poll` implementation is optimized for worker-pool style use-cases, all file /// descriptors are registered using `EPOLL_ONESHOT`. This means that once an event has been issued /// for a given descriptor, not more events will be issued for that descriptor un...
/// # fn main() { /// # try_main().unwrap();
random_line_split
poll.rs
extern crate nix; use std::os::unix::io::AsRawFd; use std::os::unix::io::RawFd; use std::time; use std::io; use self::nix::sys::epoll; /// Polls for readiness events on all registered file descriptors. /// /// `Poll` allows a program to monitor a large number of file descriptors, waiting until one or /// more become ...
self.events.all.get(*at).map(|e| { *at += 1; Token(e.data() as usize) }) } }
{ // events beyond .1 are old return None; }
conditional_block
poll.rs
extern crate nix; use std::os::unix::io::AsRawFd; use std::os::unix::io::RawFd; use std::time; use std::io; use self::nix::sys::epoll; /// Polls for readiness events on all registered file descriptors. /// /// `Poll` allows a program to monitor a large number of file descriptors, waiting until one or /// more become ...
<'a> { events: &'a Events, at: usize, } impl<'a> IntoIterator for &'a Events { type IntoIter = EventsIterator<'a>; type Item = Token; fn into_iter(self) -> Self::IntoIter { EventsIterator { events: self, at: 0, } } } impl<'a> Iterator for EventsIterator...
EventsIterator
identifier_name
poll.rs
extern crate nix; use std::os::unix::io::AsRawFd; use std::os::unix::io::RawFd; use std::time; use std::io; use self::nix::sys::epoll; /// Polls for readiness events on all registered file descriptors. /// /// `Poll` allows a program to monitor a large number of file descriptors, waiting until one or /// more become ...
}
{ let at = &mut self.at; if *at >= self.events.current { // events beyond .1 are old return None; } self.events.all.get(*at).map(|e| { *at += 1; Token(e.data() as usize) }) }
identifier_body