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 |
|---|---|---|---|---|
message.go | package message
import (
"fmt"
"bytes"
"errors"
"time"
"unsafe" | "encoding/hex"
"dad-go/common"
"dad-go/node"
)
const (
MSGCMDLEN = 12
CMDOFFSET = 4
CHECKSUMLEN = 4
HASHLEN = 32 // hash length in byte
MSGHDRLEN = 24
)
// The Inventory type
const (
TXN = 0x01 // Transaction
BLOCK = 0x02
CONSENSUS = 0xe0
)
type messager interface {
verify([]byte) error
serialization... | "crypto/sha256"
"encoding/binary" | random_line_split |
message.go | package message
import (
"fmt"
"bytes"
"errors"
"time"
"unsafe"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"dad-go/common"
"dad-go/node"
)
const (
MSGCMDLEN = 12
CMDOFFSET = 4
CHECKSUMLEN = 4
HASHLEN = 32 // hash length in byte
MSGHDRLEN = 24
)
// The Inventory type
const (
TXN = 0x01 // Tran... | {
var val uint64
var size uint8
len := binary.LittleEndian.Uint64(msg.p.blk[0:1])
if (len < 0xfd) {
val = len
size = 1
} else if (len == 0xfd) {
val = binary.LittleEndian.Uint64(msg.p.blk[1 : 3])
size = 3
} else if (len == 0xfe) {
val = binary.LittleEndian.Uint64(msg.p.blk[1 : 5])
size = 5
} else if... | identifier_body | |
message.go | package message
import (
"fmt"
"bytes"
"errors"
"time"
"unsafe"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"dad-go/common"
"dad-go/node"
)
const (
MSGCMDLEN = 12
CMDOFFSET = 4
CHECKSUMLEN = 4
HASHLEN = 32 // hash length in byte
MSGHDRLEN = 24
)
// The Inventory type
const (
TXN = 0x01 // Tran... |
str := hex.EncodeToString(buf)
fmt.Printf("The message tx verack length is %d, %s", len(buf), str)
return buf, err
}
func newGetAddr() ([]byte, error) {
var msg addrReq
// Fixme the check is the []byte{0} instead of 0
var sum []byte
sum = []byte{0x5d, 0xf6, 0xe0, 0xe2}
msg.Hdr.init("getaddr", sum, 0)
buf,... | {
return nil, err
} | conditional_block |
Reinforcement_Learning_second_train.py | import gym
import tensorflow as tf
from tensorflow.keras.models import load_model
import numpy as np
import matplotlib.pyplot as plt
import concurrent.futures
import math
try:
#取得實體GPU數量
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
for gpu in gpus:
#將GPU記憶體使用率設為動... | return len(self.memory['state'])
def get_loss_value(self):
return self.loss_value
#對於在eager model中的tensorflow運算可以在function前面加上@tf.function來改善運算效率
#但是該function會不能用debug監看
@tf.function
def calculate_gradient(self, train_state, train_action, nextq_value):
#在GradientTape中計算loss_valu... | for key, value in new_memory.items():
self.memory[key].append(value)
def get_memory_size(self):
| conditional_block |
Reinforcement_Learning_second_train.py | import gym
import tensorflow as tf
from tensorflow.keras.models import load_model
import numpy as np
import matplotlib.pyplot as plt
import concurrent.futures
import math
try:
#取得實體GPU數量
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
for gpu in gpus:
#將GPU記憶體使用率設為動... | t = self.train_model.trainable_variables
gradients = tape.gradient(loss_value, weight)
#根據梯度更新權重
self.optimizer.apply_gradients(zip(gradients, weight))
#self.loss_value = loss_value.numpy()
def training_model(self):
if len(self.memory['state']) > self.min_memory:
... | 計算梯度
weigh | identifier_name |
Reinforcement_Learning_second_train.py | import gym
import tensorflow as tf
from tensorflow.keras.models import load_model
import numpy as np
import matplotlib.pyplot as plt
import concurrent.futures
import math
try:
#取得實體GPU數量
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
for gpu in gpus:
#將GPU記憶體使用率設為動... | * tf.one_hot(train_action, self.num_actions, dtype = 'float64'), axis=1)
loss_value = self.loss_function(nextq_value, q_value)
#計算梯度
weight = self.train_model.trainable_variables
gradients = tape.gradient(loss_value, weight)
#根據梯度更新權重
... | in_model_output
| identifier_body |
Reinforcement_Learning_second_train.py | import gym
import tensorflow as tf
from tensorflow.keras.models import load_model
import numpy as np
import matplotlib.pyplot as plt
import concurrent.futures
import math
try:
#取得實體GPU數量
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
for gpu in gpus:
#將GPU記憶體使用率設為動... | self.memory_capacity = memory_capacity
#最少保留幾筆紀錄後開始做訓練
self.min_memory = min_memory
#每次訓練的取樣數量
self.batch_size = batch_size
#目前主流的Deep Q learning會用兩個一樣的模型來做訓練
#只對train_model做訓練
#target_model只被動接收權重
#訓練模型
self.train_model = creat_model()
... | #每一筆memory資料包含 state, action, reward, next_state
self.memory = {'state': [], 'action': [], 'reward': [], 'next_state': [], 'done': []}
#最多要保留幾筆紀錄 | random_line_split |
useful.rs | use rand::{Rng, thread_rng};
use serenity::builder::CreateEmbed;
use serenity::client::Context;
use serenity::model::channel::Message;
use tokio_postgres::{Error, NoTls, types::ToSql};
use crate::format_emojis;
const POSTGRE: &'static str = "host=192.168.1.146 user=postgres";
pub const GRIST_TYPES: (&'stat... | lse if author_exile == 4 {
send_embed(ctx, msg, exile_4[rand_index as usize]).await;
}
}
pub trait InVec: std::cmp::PartialEq + Sized {
fn in_vec(self, vector: Vec<Self>) -> bool {
vector.contains(&self)
}
}
impl<T> InVec for T where T: std::cmp::PartialEq {}
pub trait Conver... |
send_embed(ctx, msg, exile_3[rand_index as usize]).await;
} e | conditional_block |
useful.rs | use rand::{Rng, thread_rng};
use serenity::builder::CreateEmbed;
use serenity::client::Context;
use serenity::model::channel::Message;
use tokio_postgres::{Error, NoTls, types::ToSql};
use crate::format_emojis;
const POSTGRE: &'static str = "host=192.168.1.146 user=postgres";
pub const GRIST_TYPES: (&'stat... | let new_vec = self.into_iter().rev().collect::<Vec<_>>();
let mut return_string = "".to_owned();
for x in new_vec {
return_string = format!("{}\n{}", return_string, x);
}
if return_string.replace("\n", "") == "" {
return "Empty".to_owned()
}... |
impl<T: std::fmt::Display> FormatVec for Vec<T> {
fn format_vec(&self) -> String {
| random_line_split |
useful.rs | use rand::{Rng, thread_rng};
use serenity::builder::CreateEmbed;
use serenity::client::Context;
use serenity::model::channel::Message;
use tokio_postgres::{Error, NoTls, types::ToSql};
use crate::format_emojis;
const POSTGRE: &'static str = "host=192.168.1.146 user=postgres";
pub const GRIST_TYPES: (&'stat... | (statement: &str) -> Result<(), Error> {
let (client, connection) = tokio_postgres::connect(POSTGRE, NoTls).await.unwrap();
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("connection error: {}", e);
}
});
let _ = client.execu... | sqlstatement | identifier_name |
main.go | package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
flags "github.com/jessevdk/go-flags"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const nonBlockingKey = "non-blocking"
var log = logrus.WithField... |
// GetUploadStatus returns the status of the possibly running upload.
func (a *App) GetUploadStatus(writer http.ResponseWriter, request *http.Request) {
id := mux.Vars(request)["id"]
foundRecord := a.uploadRecords.FindRecord(id)
if foundRecord == nil {
writer.WriteHeader(http.StatusNotFound)
return
}
if er... | {
id := mux.Vars(request)["id"]
foundRecord := a.downloadRecords.FindRecord(id)
if foundRecord == nil {
writer.WriteHeader(http.StatusNotFound)
return
}
if err := foundRecord.MarshalAndWrite(writer); err != nil {
log.Error(err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
}
} | identifier_body |
main.go | package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
flags "github.com/jessevdk/go-flags"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const nonBlockingKey = "non-blocking"
var log = logrus.WithField... | PathListFile string `long:"path-list-file" default:"/input-paths/input-path-list" description:"The path to the input paths list file"`
IRODSConfig string `long:"irods-config" default:"/etc/porklock/irods-config.properties" description:"The path to the porklock iRODS config file"`
InvocationID ... | User string `long:"user" required:"true" description:"The user to run the transfers for"`
UploadDestination string `long:"upload-destination" required:"true" description:"The destination directory for uploads"`
DownloadDestination string `long:"download-destination" default:"/input-files" d... | random_line_split |
main.go | package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
flags "github.com/jessevdk/go-flags"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const nonBlockingKey = "non-blocking"
var log = logrus.WithField... |
_, err := exec.LookPath("porklock")
if err != nil {
log.Fatal(err)
}
app := &App{
LogDirectory: options.LogDirectory,
InvocationID: options.InvocationID,
ConfigPath: options.IRODSConfig,
User: options.User,
UploadDestination: options.UploadDestination,
Downlo... | {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
os.Exit(0)
}
log.Fatal(err)
} | conditional_block |
main.go | package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
flags "github.com/jessevdk/go-flags"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const nonBlockingKey = "non-blocking"
var log = logrus.WithField... | () *TransferRecord {
return &TransferRecord{
UUID: uuid.New(),
StartTime: time.Now(),
Status: RequestedStatus,
Kind: DownloadKind,
}
}
// MarshalAndWrite serializes the TransferRecord to json and writes it out using writer.
func (r *TransferRecord) MarshalAndWrite(writer io.Writer) error {
var ... | NewUploadRecord | identifier_name |
server.go | package main
import (
"bufio"
"encoding/csv"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
"golang.org/x/text/encoding/korean"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/labstack/echo"
"... |
func initObservatory(c echo.Context) error {
db, err := gorm.Open("mysql", "user:passwd@tcp(localhost:3306)/dev_gowind?charset=utf8")
if err != nil {
log.Fatal(err)
}
defer db.Close()
if !db.HasTable(&Observatory{}) {
db.CreateTable(&Observatory{})
}
obsFile, err := os.Open("data/observatory.csv")
if er... | {
db, err := gorm.Open("mysql", "user:passwd@tcp(localhost:3306)/dev_gowind?charset=utf8")
if err != nil {
log.Fatal(err)
}
defer db.Close()
airPollution := []AirPollution{}
weatherData := []WeatherData{}
observatory := []Observatory{}
airPollutionItem := AirPollution{}
db.Last(&airPollutionItem)
timeStri... | identifier_body |
server.go | package main
import (
"bufio"
"encoding/csv"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
"golang.org/x/text/encoding/korean"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/labstack/echo"
"... | trValue string) float64 {
val, err := strconv.ParseFloat(strValue, 64)
if err == nil {
return val
} else {
return -999
}
}
func weatherDataScrape(c echo.Context) error {
db, err := gorm.Open("mysql", "user:passwd@tcp(localhost:3306)/dev_gowind?charset=utf8")
if err != nil {
log.Fatal(err)
}
defer db.Clos... | ringToFloat(s | identifier_name |
server.go | package main
import (
"bufio"
"encoding/csv"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
"golang.org/x/text/encoding/korean"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/labstack/echo"
"... | urn -1
}
func getIndexWeatherData(data []WeatherData, obsName string) int {
for i := 0; i < len(data); i++ {
if data[i].ObsName == obsName {
return i
}
}
return -1
}
func main() {
db, err := gorm.Open("mysql", "user:passwd@tcp(localhost:3306)/dev_gowind?charset=utf8")
if err != nil {
log.Fatal(err)
}
... | data[i].ItemPM10 == -999 {
return -1
}
if data[i].ItemPM25 == -999 {
return -1
}
if data[i].ItemCO == -999 {
return -1
}
if data[i].ItemNO2 == -999 {
return -1
}
if data[i].ItemSO2 == -999 {
return -1
}
if data[i].ItemO3 == -999 {
return -1
}
return i
}
}... | conditional_block |
server.go | package main
import (
"bufio"
"encoding/csv"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
"golang.org/x/text/encoding/korean"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/labstack/echo"
"... | db.NewRecord(obs)
db.Create(&obs)
}
}
return c.String(http.StatusOK, "Hello, World!")
}
func getIndexAirPollution(data []AirPollution, obsName string) int {
for i := 0; i < len(data); i++ {
log.Println(data[i].ObsName, obsName)
if data[i].ObsName == obsName {
if data[i].ItemPM10 == -999 {
return ... | obs.ItemCO = co
obs.ItemSO2 = so2 | random_line_split |
main.rs | use tetra::graphics::text::{Text, Font};
use tetra::graphics::{self, Color, Texture, DrawParams};
use tetra::math::Vec2;
use tetra::input::{self, Key};
use tetra::{Context, ContextBuilder, State};
// visual consts
const SCREEN_WIDTH: i32 = 1280;
const SCREEN_HEIGHT: i32 = 720;
const FONT_SIZE: f32 = 32.0;
const PADDIN... |
}
fn update_ball(&mut self, _ctx: &mut Context){
self.update_ai(_ctx);
self.ball.position += self.ball.velocity;
if !self.simulated {
GameState::update_collision(&mut self.ball, &self.player_paddle);
GameState::update_collision(&mut self.ball, &self.enemy_paddl... | {
GameState::apply_collision_response(ball, paddle);
} | conditional_block |
main.rs | use tetra::graphics::text::{Text, Font};
use tetra::graphics::{self, Color, Texture, DrawParams};
use tetra::math::Vec2;
use tetra::input::{self, Key};
use tetra::{Context, ContextBuilder, State};
// visual consts
const SCREEN_WIDTH: i32 = 1280;
const SCREEN_HEIGHT: i32 = 720;
const FONT_SIZE: f32 = 32.0;
const PADDIN... | {
ball_texture: Texture,
position: Vec2<f32>,
velocity: Vec2<f32>,
}
impl Ball {
fn reset(&mut self){
self.position = Vec2::new(
(SCREEN_WIDTH as f32)/2.0 - (self.ball_texture.width() as f32)/2.0,
(SCREEN_HEIGHT as f32)/2.0 - (self.ball_texture.height() as f32)/2.0
... | Ball | identifier_name |
main.rs | use tetra::graphics::text::{Text, Font};
use tetra::graphics::{self, Color, Texture, DrawParams};
use tetra::math::Vec2;
use tetra::input::{self, Key};
use tetra::{Context, ContextBuilder, State};
// visual consts
const SCREEN_WIDTH: i32 = 1280;
const SCREEN_HEIGHT: i32 = 720;
const FONT_SIZE: f32 = 32.0;
const PADDIN... | fn draw_paddle(ctx: &mut Context, paddle: &Paddle){
graphics::draw(ctx, &paddle.paddle_texture, paddle.position)
}
fn handle_inputs(&mut self, ctx: &mut Context){
if input::is_key_down(ctx, Key::W) {
self.player_paddle.position.y -= PADDLE_SPEED;
}
if input::is_k... | }
| random_line_split |
ffi.rs | // Take a look at the license at the top of the repository in the LICENSE file.
use core_foundation_sys::base::{mach_port_t, CFAllocatorRef};
use core_foundation_sys::dictionary::{CFDictionaryRef, CFMutableDictionaryRef};
use core_foundation_sys::string::CFStringRef;
use libc::{c_char, kern_return_t}; |
#[allow(non_camel_case_types)]
pub type io_object_t = mach_port_t;
#[allow(non_camel_case_types)]
pub type io_iterator_t = io_object_t;
#[allow(non_camel_case_types)]
pub type io_registry_entry_t = io_object_t;
// This is a hack, `io_name_t` should normally be `[c_char; 128]` but Rust makes it very annoying
// to dea... |
// Note: IOKit is only available on MacOS up until very recent iOS versions: https://developer.apple.com/documentation/iokit | random_line_split |
ffi.rs | // Take a look at the license at the top of the repository in the LICENSE file.
use core_foundation_sys::base::{mach_port_t, CFAllocatorRef};
use core_foundation_sys::dictionary::{CFDictionaryRef, CFMutableDictionaryRef};
use core_foundation_sys::string::CFStringRef;
use libc::{c_char, kern_return_t};
// Note: IOKit... | {
pub version: u16,
pub length: u16,
pub cpu_plimit: u32,
pub gpu_plimit: u32,
pub mem_plimit: u32,
}
#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))]
#[repr(C)]
pub struct KeyData_keyInfo_t {
pub data_size: u32,
pub data_type: ... | KeyData_pLimitData_t | identifier_name |
dma.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 22:28:43 2017
@author: liuhuihui
"""
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation,Flatten,Lambda,Reshape
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.layers.normalization ... |
validation_generator = generate_sequences(n_train_batches,images1,images2,images3,images4,images5,labels,mean1,mean2,mean3,mean4,mean5,train_idxs)
ReduceLR = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10,
verbose=1, mode='min', epsilon=1e-4, cooldown=0, min_lr... | n_validation_batches = n_validation_batches + 1 | conditional_block |
dma.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 22:28:43 2017
@author: liuhuihui
"""
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation,Flatten,Lambda,Reshape
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.layers.normalization ... | (xx):
print xx.shape
x_min=tf.reduce_min(xx,axis=1)
print x_min.shape
x_max=tf.reduce_max(xx,axis=1)
x_sum=tf.reduce_sum(xx,axis=1)
x_mean=tf.reduce_mean(xx,axis=1)
x_sta=tf.concat([x_min,x_max,x_sum,x_mean],1)
print x_sta.shape
return x_sta
if __name__ == '__main__':
input... | statistics_layer | identifier_name |
dma.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 22:28:43 2017
@author: liuhuihui
"""
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation,Flatten,Lambda,Reshape
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.layers.normalization ... | validation_idxs = idxs[int(len(images1) * (1 - validation_ratio)) :]
images2 = train_file2['images']
mean2 = train_file2['mean'][...]
images3 = train_file3['images']
mean3 = train_file3['mean'][...]
images4 = train_file4['images']
... | random_line_split | |
dma.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 22:28:43 2017
@author: liuhuihui
"""
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation,Flatten,Lambda,Reshape
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.layers.normalization ... |
def statistics_layer(xx):
print xx.shape
x_min=tf.reduce_min(xx,axis=1)
print x_min.shape
x_max=tf.reduce_max(xx,axis=1)
x_sum=tf.reduce_sum(xx,axis=1)
x_mean=tf.reduce_mean(xx,axis=1)
x_sta=tf.concat([x_min,x_max,x_sum,x_mean],1)
print x_sta.shape
return x_sta
if ... | while True:
for bid in xrange(0, n_batches):
if bid == n_batches - 1:
batch_idxs = idxs[bid * batch_size:]
else:
batch_idxs = idxs[bid * batch_size: (bid + 1) * batch_size]
batch_length=len(batch_idxs)
X1= np.zeros(... | identifier_body |
test_helper.go | package helper
import (
"context"
"crypto/tls"
"database/sql"
"fmt"
"io/ioutil"
"log"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/gocql/gocql"
"github.com/gomodule/redigo/redis"
http_helper "github.com/gruntwork-io/te... |
return false
},
)
return err == nil
}
//CheckSQLConnectivity checks if we can successfully connect to a SQL Managed Instance, MySql server or Azure SQL Server
func CheckSQLConnectivity(t *testing.T, driver string, connString string) {
// Create connection pool
db, err := sql.Open(driver, connStri... | {
t.Log("Warning: 404 response from endpoint. Test will still PASS.")
return true
} | conditional_block |
test_helper.go | package helper
import (
"context"
"crypto/tls"
"database/sql"
"fmt"
"io/ioutil"
"log"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/gocql/gocql"
"github.com/gomodule/redigo/redis"
http_helper "github.com/gruntwork-io/te... |
func getPropertyValueFromString(object string, propertyKey string) string {
// compile regex to look for key="value"
regexString := fmt.Sprintf(`%s=\"(.*?)\"`, propertyKey)
re := regexp.MustCompile(regexString)
match := string(re.Find([]byte(object)))
if len(match) == 0 {
log.Printf("Warning: Could not... | {
fields := reflect.ValueOf(s).Elem()
// iterate across all configuration properties
for i := 0; i < fields.NumField(); i++ {
typeField := fields.Type().Field(i)
environmentVariablesKey := typeField.Tag.Get("env")
if fields.Field(i).Kind() == reflect.String {
// check if we want a property inside a c... | identifier_body |
test_helper.go | package helper
import (
"context"
"crypto/tls"
"database/sql"
"fmt"
"io/ioutil"
"log"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/gocql/gocql"
"github.com/gomodule/redigo/redis"
http_helper "github.com/gruntwork-io/te... | log.Fatal(err)
}
defer conn.Close()
key := "CheckRedisCacheConnectivity"
_, err = conn.Do("SET", key, "hello world")
assert.NoErrorf(t, err, "Error connecting to Redis Cache %s", redisCacheURL)
result, err := redis.String(conn.Do("GET", key))
assert.NoErrorf(t, err, "Error connecting to Redis Cache %s... | redis.DialUseTLS(true))
if err != nil {
| random_line_split |
test_helper.go | package helper
import (
"context"
"crypto/tls"
"database/sql"
"fmt"
"io/ioutil"
"log"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/gocql/gocql"
"github.com/gomodule/redigo/redis"
http_helper "github.com/gruntwork-io/te... | (t *testing.T) error {
envFileName := os.Getenv(TestEnvFilePath)
err := godotenv.Load(envFileName)
if err != nil {
return fmt.Errorf("Can not read .env file: %s", envFileName)
}
return nil
}
// InitializeTestValuesE fill the value from environment variables.
func InitializeTestValues(s interface{}) in... | LoadEnvFile | identifier_name |
yolo-and-dlib.py | from tracking.centroidtracker import CentroidTracker
from tracking.trackableobject import TrackableObject
import tensornets as nets
import cv2
import numpy as np
import time
import dlib
import tensorflow.compat.v1 as tf
import os
# For 'disable_v2_behavior' see https://github.com/theislab/scgen/issues/14
tf.disable_v2... | (img, center, radius, color, thickness, width_scale=width_scale, height_scale=height_scale):
center = (int(center[0] * width_scale), int(center[1] * height_scale))
cv2.circle(img, center, radius, color, thickness)
# Python 3.5.6 does not support f-strings (next line will generate syntax error)
... | drawCircleCV2 | identifier_name |
yolo-and-dlib.py | from tracking.centroidtracker import CentroidTracker
from tracking.trackableobject import TrackableObject
import tensornets as nets
import cv2
import numpy as np
import time
import dlib
import tensorflow.compat.v1 as tf
import os
# For 'disable_v2_behavior' see https://github.com/theislab/scgen/issues/14
tf.disable_v2... |
def drawCircleCV2(img, center, radius, color, thickness, width_scale=width_scale, height_scale=height_scale):
center = (int(center[0] * width_scale), int(center[1] * height_scale))
cv2.circle(img, center, radius, color, thickness)
# Python 3.5.6 does not support f-strings (next line will ... | pt = (int(pt[0] * width_scale), int(pt[1] * height_scale))
cv2.putText(img, text, pt, font, font_scale, color, lineType) | identifier_body |
yolo-and-dlib.py | from tracking.centroidtracker import CentroidTracker
from tracking.trackableobject import TrackableObject
import tensornets as nets
import cv2
import numpy as np
import time
import dlib
import tensorflow.compat.v1 as tf
import os
# For 'disable_v2_behavior' see https://github.com/theislab/scgen/issues/14
tf.disable_v2... |
# Store the trackable object in our dictionary
trackableObjects[objectID] = to
# Draw both the ID of the object and the centroid of the object on the output frame
object_id = "ID {}".format(objectID)
drawTextCV2(output_img, object_id, (centroid[0] - 10, cen... | total += 1
to.counted = True | conditional_block |
yolo-and-dlib.py | from tracking.centroidtracker import CentroidTracker
from tracking.trackableobject import TrackableObject
import tensornets as nets
import cv2
import numpy as np
import time
import dlib | import os
# For 'disable_v2_behavior' see https://github.com/theislab/scgen/issues/14
tf.disable_v2_behavior()
# Image size must be '416x416' as YoloV3 network expects that specific image size as input
img_size = 416
inputs = tf.placeholder(tf.float32, [None, img_size, img_size, 3])
model = nets.YOLOv3COCO(inputs, n... | import tensorflow.compat.v1 as tf | random_line_split |
main.ts | import * as dat from 'dat.gui';
import * as Phaser from 'phaser';
import { Terrain, HEIGHTMAP_RESOLUTION, HEIGHTMAP_YRESOLUTION, FINISH_FLAG_X_POSITION } from './terrain';
import { BodyType } from 'matter';
import { Truck } from './truck';
import { Vehicles } from './vehicles';
import { TitleScene } from './title';
imp... |
public preload() {
Vehicles.PickupTruck.preload(this);
this.sceneData = (<BetweenLevelState>this.scene.settings.data) || new BetweenLevelState();
if (this.sceneData.startImmediately) {
this.isScrolling = true;
} else {
this.isScrolling = false;
}
this.truck.preload(this);
... | {
this.terrain = new Terrain();
this.truck = new Truck();
this.totalTime = 0;
this.startTruckTime = 0;
this.startTruckX = 0;
this.truckProgress = new ProgressCounter();
this.isLosing = false;
this.isLosingStartTime = 0;
this.isWinning = false;
this.isWinningStartTime =... | identifier_body |
main.ts | import * as dat from 'dat.gui';
import * as Phaser from 'phaser';
import { Terrain, HEIGHTMAP_RESOLUTION, HEIGHTMAP_YRESOLUTION, FINISH_FLAG_X_POSITION } from './terrain';
import { BodyType } from 'matter';
import { Truck } from './truck';
import { Vehicles } from './vehicles';
import { TitleScene } from './title';
imp... |
if (this.totalTime > 2000)
{
this.instructionText.visible = false;
if (this.startTruckTime == 0) {
this.startTruckTime = this.totalTime;
this.startTruckX = this.pickupTruck.chasis.x;
}
this.pickupTruck.applyDrivingForce(0.005, 1);
this.pickupTruc... | random_line_split | |
main.ts | import * as dat from 'dat.gui';
import * as Phaser from 'phaser';
import { Terrain, HEIGHTMAP_RESOLUTION, HEIGHTMAP_YRESOLUTION, FINISH_FLAG_X_POSITION } from './terrain';
import { BodyType } from 'matter';
import { Truck } from './truck';
import { Vehicles } from './vehicles';
import { TitleScene } from './title';
imp... |
this.progress.splice(0, cutoff);
this.times.splice(0, cutoff);
this.totalTime = 0;
this.times.forEach( time => this.totalTime += time );
}
}
getAverage() {
let total = 0;
for (let n = 0; n < this.progress.length; n++) {
total += this.progress[n] * this.times[n];
}
... | {
time -= this.times[n];
if (time < 1000) {
cutoff = n;
break;
}
} | conditional_block |
main.ts | import * as dat from 'dat.gui';
import * as Phaser from 'phaser';
import { Terrain, HEIGHTMAP_RESOLUTION, HEIGHTMAP_YRESOLUTION, FINISH_FLAG_X_POSITION } from './terrain';
import { BodyType } from 'matter';
import { Truck } from './truck';
import { Vehicles } from './vehicles';
import { TitleScene } from './title';
imp... | () {
Vehicles.PickupTruck.preload(this);
this.sceneData = (<BetweenLevelState>this.scene.settings.data) || new BetweenLevelState();
if (this.sceneData.startImmediately) {
this.isScrolling = true;
} else {
this.isScrolling = false;
}
this.truck.preload(this);
this.load.imag... | preload | identifier_name |
lib.rs | //! This crate allows running a process with a timeout, with the option to
//! terminate it automatically afterward. The latter is surprisingly difficult
//! to achieve on Unix, since process identifiers can be arbitrarily reassigned
//! when no longer used. Thus, it would be extremely easy to inadvertently
//! termina... | (&self, formatter: &mut Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}
impl From<process::ExitStatus> for ExitStatus {
#[inline]
fn from(value: process::ExitStatus) -> Self {
#[cfg_attr(windows, allow(clippy::useless_conversion))]
Self(value.into())
}
}
/// Equivalen... | fmt | identifier_name |
lib.rs | //! This crate allows running a process with a timeout, with the option to
//! terminate it automatically afterward. The latter is surprisingly difficult
//! to achieve on Unix, since process identifiers can be arbitrarily reassigned
//! when no longer used. Thus, it would be extremely easy to inadvertently
//! termina... |
#[inline]
fn with_timeout(
&'a mut self,
time_limit: Duration,
) -> Self::ExitStatusTimeout {
Self::ExitStatusTimeout::new(self, time_limit)
}
#[inline]
fn with_output_timeout(self, time_limit: Duration) -> Self::OutputTimeout {
Self::OutputTimeout::new(self, t... | {
imp::Handle::new(self).map(Terminator)
} | identifier_body |
lib.rs | //! This crate allows running a process with a timeout, with the option to
//! terminate it automatically afterward. The latter is surprisingly difficult
//! to achieve on Unix, since process identifiers can be arbitrarily reassigned
//! when no longer used. Thus, it would be extremely easy to inadvertently
//! termina... | ///
/// Instances can only be constructed using [`ChildExt::terminator`].
#[derive(Debug)]
pub struct Terminator(imp::Handle);
impl Terminator {
/// Terminates a process as immediately as the operating system allows.
///
/// Behavior should be equivalent to calling [`Child::kill`] for the same
/// proc... | mod timeout;
/// A wrapper that stores enough information to terminate a process. | random_line_split |
boundarypslg.py | import numpy as np
from numpy import linalg as npl
from meshpy import triangle
from mesh_sphere_packing import logger, ONE_THIRD, GROWTH_LIMIT
from mesh_sphere_packing.area_constraints import AreaConstraints
# TODO : change nomenclature. Segment is used in geometry to refer to an
# : edge connecting two points. ... | :param points numpy.ndarray: array of PLC vertex coordinates.
:param adges numpy.ndarray: array of PLC tris (vertex topology).
:param holes numpy.ndarray: array of coordinates of holes in the PLC.
"""
self.points = points
self.tris = tris
self.holes = holes
def ... | """
def __init__(self, points, tris, holes):
"""Constructs BoundaryPLC object. | random_line_split |
boundarypslg.py | import numpy as np
from numpy import linalg as npl
from meshpy import triangle
from mesh_sphere_packing import logger, ONE_THIRD, GROWTH_LIMIT
from mesh_sphere_packing.area_constraints import AreaConstraints
# TODO : change nomenclature. Segment is used in geometry to refer to an
# : edge connecting two points. ... |
holes[i] = np.vstack(holes[i]) if len(holes[i])\
else np.empty((0,2), dtype=np.float64)
return holes
def reindex_edges(points, points_ax, edges_ax):
"""Reindexes edges along a given axis.
:param points numpy.ndarray: all point coordinates.
:param points_... | points_ax = points[np.isclose(points[:,i], 0.)]
if points_ax.shape[0]:
holes[i].append([
0.5 * (points_ax[:,j].max() + points_ax[:,j].min()),
0.5 * (points_ax[:,k].max() + points_ax[:,k].min())
]) | conditional_block |
boundarypslg.py | import numpy as np
from numpy import linalg as npl
from meshpy import triangle
from mesh_sphere_packing import logger, ONE_THIRD, GROWTH_LIMIT
from mesh_sphere_packing.area_constraints import AreaConstraints
# TODO : change nomenclature. Segment is used in geometry to refer to an
# : edge connecting two points. ... |
perim = filter_colocated_points(perim, axis)
refined_points = [perim[0]]
for e in [[i, i+1] for i in range(perim.shape[0]-1)]:
e_len = perim[e[1], axis] - perim[e[0], axis]
ne = int(np.ceil(e_len / ds))
if ne > 1:
dse = e_len / ne
... | delta = np.diff(perim[:,axis])
keep_idx = np.hstack(([0], np.where(~np.isclose(delta,0.))[0] + 1))
return perim[keep_idx] | identifier_body |
boundarypslg.py | import numpy as np
from numpy import linalg as npl
from meshpy import triangle
from mesh_sphere_packing import logger, ONE_THIRD, GROWTH_LIMIT
from mesh_sphere_packing.area_constraints import AreaConstraints
# TODO : change nomenclature. Segment is used in geometry to refer to an
# : edge connecting two points. ... | (domain, sphere_pieces, config):
"""Handles creation of high quality triangulations of the domain boundaries.
:param domain Domain: spatial domain for mesh.
:param sphere_pieces list: list of SpherePiece objects.
:param config Config: configuration for mesh build.
:return: list of BoundaryPLC object... | boundarypslg | identifier_name |
config.go | package server
import (
"github.com/Bogh/gcm"
log "github.com/Sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
"fmt"
"net"
"runtime"
"strconv"
"strings"
"github.com/cosminrentea/gobbler/server/apns"
"github.com/cosminrentea/gobbler/server/configstring"
"github.com/cosminrentea/gobbler/server/fcm"
"githu... | APNS: apns.Config{
Enabled: kingpin.Flag("apns", "Enable the APNS connector (by default, in Development mode)").
Envar(g("APNS")).
Bool(),
Production: kingpin.Flag("apns-production", "Enable the APNS connector in Production mode").
Envar(g("APNS_PRODUCTION")).
Bool(),
CertificateFileName: kin... | String(),
IntervalMetrics: &defaultFCMMetrics,
}, | random_line_split |
config.go | package server
import (
"github.com/Bogh/gcm"
log "github.com/Sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
"fmt"
"net"
"runtime"
"strconv"
"strings"
"github.com/cosminrentea/gobbler/server/apns"
"github.com/cosminrentea/gobbler/server/configstring"
"github.com/cosminrentea/gobbler/server/fcm"
"githu... |
func (h *tcpAddrList) String() string {
return ""
}
| {
slist := make(tcpAddrList, 0)
s.SetValue(&slist)
return &slist
} | identifier_body |
config.go | package server
import (
"github.com/Bogh/gcm"
log "github.com/Sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
"fmt"
"net"
"runtime"
"strconv"
"strings"
"github.com/cosminrentea/gobbler/server/apns"
"github.com/cosminrentea/gobbler/server/configstring"
"github.com/cosminrentea/gobbler/server/fcm"
"githu... | () {
if parsed {
return
}
kingpin.Parse()
parsed = true
return
}
type tcpAddrList []*net.TCPAddr
func (h *tcpAddrList) Set(value string) error {
addresses := strings.Split(value, " ")
// Reset the list also, when running tests we add to the same list and is incorrect
*h = make(tcpAddrList, 0)
for _, addr ... | parseConfig | identifier_name |
config.go | package server
import (
"github.com/Bogh/gcm"
log "github.com/Sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
"fmt"
"net"
"runtime"
"strconv"
"strings"
"github.com/cosminrentea/gobbler/server/apns"
"github.com/cosminrentea/gobbler/server/configstring"
"github.com/cosminrentea/gobbler/server/fcm"
"githu... |
kingpin.Parse()
parsed = true
return
}
type tcpAddrList []*net.TCPAddr
func (h *tcpAddrList) Set(value string) error {
addresses := strings.Split(value, " ")
// Reset the list also, when running tests we add to the same list and is incorrect
*h = make(tcpAddrList, 0)
for _, addr := range addresses {
logger... | {
return
} | conditional_block |
SelectOneView.js | /**
* Create by Uncle Charlie, 4/1/2018
* @flow
*/
import React from 'react';
import { Body, Icon, Left, Right, Picker, Title, Button, Text as TextNB } from 'native-base';
import { Text, TouchableOpacity, View, StyleSheet } from 'react-native';
import _ from 'lodash';
import ModalSelector from '../../../lib/modalSe... | && apiName === 'customer') {
_.set(selected, 'selected', [relatedParentData]);
_.set(selected, 'apiName', apiName);
_.set(selected, 'renderType', renderType);
}
this.setState({
selected: selected.selected,
});
if (onChange) {
const value = _.get(selected, 'selected[0].valu... | }
}
};
// 调用的回调函数
handleSelect = (selected) => {
const { handleCreate, fieldDesc, onChange, renderType, relatedParentData } = this.props;
const apiName = _.get(fieldDesc, 'api_name');
_.set(selected, 'apiName', apiName);
_.set(selected, 'renderType', renderType);
if (selected['selected'... | conditional_block |
SelectOneView.js | /**
* Create by Uncle Charlie, 4/1/2018
* @flow
*/
import React from 'react';
import { Body, Icon, Left, Right, Picker, Title, Button, Text as TextNB } from 'native-base';
import { Text, TouchableOpacity, View, StyleSheet } from 'react-native';
import _ from 'lodash';
import ModalSelector from '../../../lib/modalSe... | lue } = this.props;
if (!_.isEmpty(this.dataSource)) {
const { object_api_name, criterias = [], target_field = '' } = this.dataSource;
this.target_field = target_field;
this.fetchData(token, object_api_name, criterias);
}
if (renderType === 'subordinate') {
// ? 筛选下属组件?
this.... | fieldLayout, fieldDesc } = props;
const mergedObjectFieldDescribe = Object.assign({}, fieldDesc, fieldLayout);
//* data_source 配置项
this.dataSource = _.get(fieldLayout, 'data_source', {});
this.target_field = '';
// * 单选多选配置查询布局
this.targetRecordType =
_.get(fieldLayout, 'target_record_ty... | identifier_body |
SelectOneView.js | /**
* Create by Uncle Charlie, 4/1/2018
* @flow
*/
import React from 'react';
import { Body, Icon, Left, Right, Picker, Title, Button, Text as TextNB } from 'native-base';
import { Text, TouchableOpacity, View, StyleSheet } from 'react-native';
import _ from 'lodash';
import ModalSelector from '../../../lib/modalSe... | const tmpData = this.target_field ? _.get(fetchData, this.target_field) : fetchData;
if (_.get(tmpData, 'id') == val) {
selected.push({
label: labelExp ? executeDetailExp(labelExp, tmpData) : _.get(tmpData, 'name'),
value: val,
});
}
... | const selected = [];
const labelExp = _.get(fieldLayout, 'render_label_expression');
if (renderType === 'select_multiple' && placeholderValue) {
_.each(placeholderValue, (val) => {
_.each(fetchList, (fetchData) => { | random_line_split |
SelectOneView.js | /**
* Create by Uncle Charlie, 4/1/2018
* @flow
*/
import React from 'react';
import { Body, Icon, Left, Right, Picker, Title, Button, Text as TextNB } from 'native-base';
import { Text, TouchableOpacity, View, StyleSheet } from 'react-native';
import _ from 'lodash';
import ModalSelector from '../../../lib/modalSe... | const { fieldLayout, fieldDesc } = props;
const mergedObjectFieldDescribe = Object.assign({}, fieldDesc, fieldLayout);
//* data_source 配置项
this.dataSource = _.get(fieldLayout, 'data_source', {});
this.target_field = '';
// * 单选多选配置查询布局
this.targetRecordType =
_.get(fieldLayout, 'target_r... | rops);
| identifier_name |
GUI test backup.py | from __future__ import print_function
from glob import glob
from os.path import join, basename, isfile
from os import mkdir, walk, listdir
from PIL import Image as pimage
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix... | path: The path to the photos shown, in "showphotos" layout.
"""
global layout
#Removes the widgets in the scroll layout, if there is any.
scroll.remove_widget(layout)
#Loads the new updated layout, and updates the showphotos layout.
layout = self._showphotos(... | random_line_split | |
GUI test backup.py | from __future__ import print_function
from glob import glob
from os.path import join, basename, isfile
from os import mkdir, walk, listdir
from PIL import Image as pimage
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix... |
def _validate(self, fileChooser):
"""
Function to add the path chosen by user to "curdir" and initiate functions that needs to be run.
Args:
fileChooser: Takes the path chosen by the user.
Returns:
None, but initiates several other functions.
"""... | global progress
progress_bar = ProgressBar(max=max)
popup = Popup(title="Filtering and sorting pictures",
content=progress_bar)
progress_bar.value = progress
popup.open() | identifier_body |
GUI test backup.py | from __future__ import print_function
from glob import glob
from os.path import join, basename, isfile
from os import mkdir, walk, listdir
from PIL import Image as pimage
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix... | (self):
global sorting_queue
filter_path = join(curdir, "filtered")
onlyfiles = [f for f in listdir(filter_path) if isfile(join(filter_path, f))]
for i in range(0, len(onlyfiles)):
j = onlyfiles[i]
onlyfiles[i] = join(filter_path, j)
files = []
... | _cnn | identifier_name |
GUI test backup.py | from __future__ import print_function
from glob import glob
from os.path import join, basename, isfile
from os import mkdir, walk, listdir
from PIL import Image as pimage
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix... |
elif group == 3:
print("Pictures belongs to Monica")
thumb.save(join(curdir, "thumb", "Monica", picture_name), "JPEG")
elif group == 2:
print("Pictures belongs to Wenche")
thumb.save(join(curdir, "thumb", "W... | print("Pictures belongs to Gabrielle")
thumb.save(join(curdir, "thumb", "Gabrielle", picture_name), "JPEG") | conditional_block |
app.rs | // vim: tw=80
use std::{
collections::{btree_map, BTreeMap},
error::Error,
mem,
num::NonZeroUsize,
ops::AddAssign,
};
use cfg_if::cfg_if;
use ieee754::Ieee754;
use nix::{
sys::time::TimeSpec,
time::{clock_gettime, ClockId},
};
use regex::Regex;
cfg_if! {
if #[cfg(target_os = "freebsd")... | {
name: String,
nunlinked: u64,
nunlinks: u64,
nread: u64,
reads: u64,
nwritten: u64,
writes: u64,
}
impl Snapshot {
fn compute(&self, prev: Option<&Self>, etime: f64) -> Element {
if let Some(prev) = prev {
Element {
name: self.na... | Snapshot | identifier_name |
app.rs | // vim: tw=80
use std::{
collections::{btree_map, BTreeMap},
error::Error,
mem,
num::NonZeroUsize,
ops::AddAssign,
};
use cfg_if::cfg_if;
use ieee754::Ieee754;
use nix::{
sys::time::TimeSpec,
time::{clock_gettime, ClockId},
};
use regex::Regex;
cfg_if! {
if #[cfg(target_os = "freebsd")... | } else {
match self.depth {
None => None,
Some(x) => NonZeroUsize::new(x.get() - 1),
}
}
}
pub fn on_minus(&mut self) {
self.sort_idx = match self.sort_idx {
Some(0) => None,
Some(old) => Some(old - 1),
... | None => NonZeroUsize::new(1),
Some(x) => NonZeroUsize::new(x.get() + 1),
} | random_line_split |
vr-party-participant.js | var _viewerLeft, _viewerRight;
var _updatingLeft, _updatingRight;
var _leftLoaded, _rightLoaded;
var _baseDir;
var _upVector;
var _deg2rad = Math.PI / 180;
var _wasFlipped;
var _readyToApplyEvents = false;
var _model_state = {};
var _orbitInitialPosition;
var _lastVert, _lastHoriz;
var _socket = io();
var _sessionId;
... |
function unwatchCameras() {
if (_viewerLeft) {
_viewerLeft.removeEventListener('cameraChanged', left2right);
}
if (_viewerRight) {
_viewerRight.removeEventListener('cameraChanged', right2left);
}
}
function watchTilt() {
if (window.DeviceOrientationEvent) {
window.addEv... | {
_viewerLeft.addEventListener('cameraChanged', left2right);
_viewerRight.addEventListener('cameraChanged', right2left);
} | identifier_body |
vr-party-participant.js | var _viewerLeft, _viewerRight;
var _updatingLeft, _updatingRight;
var _leftLoaded, _rightLoaded;
var _baseDir;
var _upVector;
var _deg2rad = Math.PI / 180;
var _wasFlipped;
var _readyToApplyEvents = false;
var _model_state = {};
var _orbitInitialPosition;
var _lastVert, _lastHoriz;
var _socket = io();
var _sessionId;
... | else {
Autodesk.Viewing.Initializer(getViewingOptions(), function() {
var avp = Autodesk.Viewing.Private;
avp.GPU_OBJECT_LIMIT = 100000;
avp.onDemandLoading = false;
showMessage('Waiting...');
if (_sessionId === "demo") {
launchVi... | initConnection();
});
}
);
} | random_line_split |
vr-party-participant.js | var _viewerLeft, _viewerRight;
var _updatingLeft, _updatingRight;
var _leftLoaded, _rightLoaded;
var _baseDir;
var _upVector;
var _deg2rad = Math.PI / 180;
var _wasFlipped;
var _readyToApplyEvents = false;
var _model_state = {};
var _orbitInitialPosition;
var _lastVert, _lastHoriz;
var _socket = io();
var _sessionId;
... | (e) {
if (!e.alpha || !e.beta || !e.gamma || _updatingLeft || _updatingRight) return;
// Remove our handlers watching for camera updates,
// as we'll make any changes manually
// (we won't actually bother adding them back, afterwards,
// as this means we're in mobile mode and probably inside
//... | orb | identifier_name |
vr-party-participant.js | var _viewerLeft, _viewerRight;
var _updatingLeft, _updatingRight;
var _leftLoaded, _rightLoaded;
var _baseDir;
var _upVector;
var _deg2rad = Math.PI / 180;
var _wasFlipped;
var _readyToApplyEvents = false;
var _model_state = {};
var _orbitInitialPosition;
var _lastVert, _lastHoriz;
var _socket = io();
var _sessionId;
... |
console.log('Applied zoom');
watchTilt();
}
if (_model_state.explode_factor !== undefined) {
viewersApply('explode', _model_state.explode_factor);
_model_state.explode_factor = undefined;
console.log('Applied explode');
}
if (_model_state.isolate_... | {
orbitViews(_lastVert, _lastHoriz);
} | conditional_block |
main.py | import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.cluster import AgglomerativeClustering
import scipy.cluster.hierarchy as shc
from sklearn.metrics import silhouette_score #avg of avgs
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_... | temp = [sum(1 for p in premiums if p < 0) for i, premiums in df[['premium_motor','premium_household','premium_health', 'premium_life','premium_work_comp']].iterrows()]
df["cancelled_contracts"] = [1 if i != 0 else 0 for i in temp]
# True if customers has premium for every part
temp = [sum(1 for p in premiums if p > 0) ... | random_line_split | |
main.py | import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.cluster import AgglomerativeClustering
import scipy.cluster.hierarchy as shc
from sklearn.metrics import silhouette_score #avg of avgs
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_... |
else:
X = df[cols]
y = df["c_cluster"]
clf = DecisionTreeClassifier()
clf = clf.fit(X,y)
y_pred = clf.predict([df_topredc.loc[i,cols]])
pred_cclusters.append(y_pred[0])
trained_models[', '.join(cols)] = clf
# p_cluster
pcols = ["premium_motor","premium_household","premium_health","premium_life","pre... | y_pred = trained_models[', '.join(cols)].predict([df_topredc.loc[i,cols]])
pred_cclusters.append(y_pred[0])
continue | conditional_block |
moc_guestagent_exec.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: exec/moc_guestagent_exec.proto
package admin
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
common "github.com/microsoft/moc/rpc/common"
grpc "google.golang.org/grpc"
... | () int {
return xxx_messageInfo_ExecResponse.Size(m)
}
func (m *ExecResponse) XXX_DiscardUnknown() {
xxx_messageInfo_ExecResponse.DiscardUnknown(m)
}
var xxx_messageInfo_ExecResponse proto.InternalMessageInfo
func (m *ExecResponse) GetExecs() []*Exec {
if m != nil {
return m.Execs
}
return nil
}
func (m *Exec... | XXX_Size | identifier_name |
moc_guestagent_exec.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: exec/moc_guestagent_exec.proto
package admin
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
common "github.com/microsoft/moc/rpc/common"
grpc "google.golang.org/grpc"
... |
return nil
}
func (m *ExecResponse) GetError() string {
if m != nil {
return m.Error
}
return ""
}
type Exec struct {
Command string `protobuf:"bytes,1,opt,name=command,proto3" json:"command,omitempty"`
Output string `protobuf:"bytes,2,opt,name=output,proto3" json:"... | {
return m.Result
} | conditional_block |
moc_guestagent_exec.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: exec/moc_guestagent_exec.proto
package admin
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
common "github.com/microsoft/moc/rpc/common"
grpc "google.golang.org/grpc"
... | }
func (*UnimplementedExecAgentServer) Invoke(ctx context.Context, req *ExecRequest) (*ExecResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Invoke not implemented")
}
func RegisterExecAgentServer(s *grpc.Server, srv ExecAgentServer) {
s.RegisterService(&_ExecAgent_serviceDesc, srv)
}
func ... | random_line_split | |
moc_guestagent_exec.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: exec/moc_guestagent_exec.proto
package admin
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
common "github.com/microsoft/moc/rpc/common"
grpc "google.golang.org/grpc"
... |
func (m *ExecRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExecRequest.Merge(m, src)
}
func (m *ExecRequest) XXX_Size() int {
return xxx_messageInfo_ExecRequest.Size(m)
}
func (m *ExecRequest) XXX_DiscardUnknown() {
xxx_messageInfo_ExecRequest.DiscardUnknown(m)
}
var xxx_messageInfo_ExecRequest proto.Int... | {
return xxx_messageInfo_ExecRequest.Marshal(b, m, deterministic)
} | identifier_body |
generate_synthetic_immunoblot_dataset.py | # MW Irvin -- Lopez Lab -- 2019-10-08
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy.stats import norm
from opt2q.simulator import Simulator
from opt2q.data import DataSet
from opt2q.measurement.base import LogisticClassifier, Interpolate, ScaleToMinMax, Pipeline
from ... |
IC_RP__n_cats = immunoblot_number_of_categories(dataset.measurement_error_df['norm_IC-RP__error'])
EC_RP__n_cats = immunoblot_number_of_categories(dataset.measurement_error_df['norm_EC-RP__error'])
# ------- Immunoblot Data Set -------
ordinal_dataset_size = 14 # 28, 16, 14, 7 divide evenly into the total 112 rows... | data_rms = np.sqrt(variances).mean()
z_stat = norm.ppf(1 - expected_misclassification_rate)
peak_noise = z_stat*data_rms
signal_to_noise_ratio = 20*np.log10(peak_noise/data_range)
effective_number_of_bits = -(signal_to_noise_ratio+1.76)/6.02
return int(np.floor(0.70*(2**effective_number_of_bits))) ... | identifier_body |
generate_synthetic_immunoblot_dataset.py | # MW Irvin -- Lopez Lab -- 2019-10-08
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy.stats import norm
from opt2q.simulator import Simulator
from opt2q.data import DataSet
from opt2q.measurement.base import LogisticClassifier, Interpolate, ScaleToMinMax, Pipeline
from ... | fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6), sharey='all', gridspec_kw={'width_ratios': [2, 1]})
ax1.scatter(x=synthetic_immunoblot_data.data['time'],
y=synthetic_immunoblot_data.data['cPARP_blot'].values / (EC_RP__n_cats-1),
s=10, color=cm.colors[0], label=f'cPARP blot data... | conditional_block | |
generate_synthetic_immunoblot_dataset.py | # MW Irvin -- Lopez Lab -- 2019-10-08
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy.stats import norm
from opt2q.simulator import Simulator
from opt2q.data import DataSet
from opt2q.measurement.base import LogisticClassifier, Interpolate, ScaleToMinMax, Pipeline
from ... | lc_results = lc.transform(plot_domain)
cPARP_results = lc_results.filter(regex='cPARP_blot')
tBID_results = lc_results.filter(regex='tBID_blot')
# ------- Synthetic Immunoblot Data -------
n = 180
time_span = list(range(fluorescence_data['time'].max()))[::n] # ::30 = one measurement per 30s; 6x fluorescence data
x_s... |
# plot classifier
lc.do_fit_transform = False
plot_domain = pd.DataFrame({'tBID_obs': np.linspace(0, 1, 100), 'cPARP_obs': np.linspace(0, 1, 100)}) | random_line_split |
generate_synthetic_immunoblot_dataset.py | # MW Irvin -- Lopez Lab -- 2019-10-08
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy.stats import norm
from opt2q.simulator import Simulator
from opt2q.data import DataSet
from opt2q.measurement.base import LogisticClassifier, Interpolate, ScaleToMinMax, Pipeline
from ... | (variances, expected_misclassification_rate=0.05, data_range=1):
# Effective Number of Bits in Fluorescence Data
# ref -- https://en.wikipedia.org/wiki/Effective_number_of_bits
# Fluorescence data was normalized to 0-1 :. data_range=1.
data_rms = np.sqrt(variances).mean()
z_stat = norm.ppf(1 - expec... | immunoblot_number_of_categories | identifier_name |
media.py | """
Accessing media associated with a CLDF dataset.
You can iterate over the `File` objects associated with media using the `Media` wrapper:
.. code-block:: python
from pycldf.media import Media
for f in Media(dataset):
if f.mimetype.type == 'audio':
f.save(directory)
or instantiate a `... |
def __eq__(self, other):
return self.string == other if isinstance(other, str) else \
(self.type, self.subtype) == (other.type, other.subtype)
@property
def is_text(self) -> bool:
return self.type == 'text'
@property
def extension(self) -> typing.Union[None, str]:
... | self.string = s
mtype, _, param = self.string.partition(';')
param = param.strip()
self.type, _, self.subtype = mtype.partition('/')
if param.startswith('charset='):
self.encoding = param.replace('charset=', '').strip()
else:
self.encoding = 'utf8' | identifier_body |
media.py | """
Accessing media associated with a CLDF dataset.
You can iterate over the `File` objects associated with media using the `Media` wrapper:
.. code-block:: python
from pycldf.media import Media
for f in Media(dataset):
if f.mimetype.type == 'audio':
f.save(directory)
or instantiate a `... | zipcontent = self.local_path(d).read_bytes()
if self.url:
zipcontent = self.url_reader[self.scheme](
self.parsed_url, Mimetype('application/zip'))
if zipcontent:
zf = zipfile.ZipFile(io.BytesIO(zipcontent))
retur... | if d: | random_line_split |
media.py | """
Accessing media associated with a CLDF dataset.
You can iterate over the `File` objects associated with media using the `Media` wrapper:
.. code-block:: python
from pycldf.media import Media
for f in Media(dataset):
if f.mimetype.type == 'audio':
f.save(directory)
or instantiate a `... | (self, d=None) -> typing.Union[None, str, bytes]:
"""
:param d: A local directory where the file has been saved before. If `None`, the content \
will read from the file's URL.
"""
if self.path_in_zip:
zipcontent = None
if d:
zipcontent = se... | read | identifier_name |
media.py | """
Accessing media associated with a CLDF dataset.
You can iterate over the `File` objects associated with media using the `Media` wrapper:
.. code-block:: python
from pycldf.media import Media
for f in Media(dataset):
if f.mimetype.type == 'audio':
f.save(directory)
or instantiate a `... |
if self.url:
self.url = anyURI.to_string(self.url)
self.parsed_url = urllib.parse.urlparse(self.url)
self.scheme = self.parsed_url.scheme
@classmethod
def from_dataset(
cls, ds: pycldf.Dataset, row_or_object: typing.Union[dict, orm.Media]) -> 'File':
... | if media.id_col and media.id_col.valueUrl:
self.url = media.id_col.valueUrl.expand(**row) | conditional_block |
ui.js | /**
* @license
* ui.js - v0.1
* Copyright (c) 2014, Alexandre Ayotte
*
* misc.js is licensed under the MIT License.
* https://www.opensource.org/licenses/MIT
**/
define(
['pixi454/pixi', 'libayo/misc'],
function( PIXI, MISC ) {
var ui = {
debog : false,
// 1 2 3 4 5 ... | unction fouilleUnPeu( ceci, tempPoint ) {
//console.log("..fouilleUnPeu() ceci=", ceci)
var children,i,tot,objet, enfant
children = ceci.children
tot = children.length - 1
for(i=tot; i>=0 ; i--) {
objet = children[i]
if (objet.contientDesTouchables) {
enfant = fouilleUnPeu( objet, tempPoint ... | var i,tot,d,circ,p, zonesDoigts
zonesDoigts = luimeme.zonesDoigts
tot = zonesDoigts.length
for(i=0; i<tot; i++) {
circ = zonesDoigts[i]
circ.visible = false
//c.position.x = -100
//c.position.y = -100
}
var layer = luimeme.layer
tot = someFingers.length
for(i=0; i<tot; i++) {
... | identifier_body |
ui.js | /**
* @license
* ui.js - v0.1
* Copyright (c) 2014, Alexandre Ayotte
*
* misc.js is licensed under the MIT License.
* https://www.opensource.org/licenses/MIT
**/
define(
['pixi454/pixi', 'libayo/misc'],
function( PIXI, MISC ) {
var ui = {
debog : false,
// 1 2 3 4 5 ... | rité
if (btn==null) {
console.log("bizarre!! personne ne peut recevoir le bouton!!??", layer)
}
else {
if (btn.recoitUnDoigt( doigt, dessus )) doigt.target = btn
}
return
}
if (qty >= 2) {
if (this.recoitPlusieursDoigts && this.recoitPlusieursDoigts( doigtsQuiTouchent )... | CI ON S'EN FOUT SI INSIDE OU NON?
btn = doigt.target
//
if (btn && btn.hitArea) dessus = btn.hitArea.contains( tempPoint.x, tempPoint.y )
//onsole.log("on connait l'objet, YÉ: ", btn.hitArea, dessus, tempPoint )
}
//secu | conditional_block |
ui.js | /**
* @license
* ui.js - v0.1
* Copyright (c) 2014, Alexandre Ayotte
*
* misc.js is licensed under the MIT License.
* https://www.opensource.org/licenses/MIT
**/
define(
['pixi454/pixi', 'libayo/misc'],
function( PIXI, MISC ) {
var ui = {
debog : false,
// 1 2 3 4 5 ... | st, derniers ) {
if (derniers==null || derniers==undefined) derniers = 10
//
var tot,i,j,d,sum,ponderation, a
ponderation = 0.0
sum = {x:0, y:0}
tot = dlst.length
a = Math.max( 0, tot-derniers )
for(i=a, j=1; i<tot; i++, j++) {
d = dlst[i]
sum.x = sum.x + (d.x * j)
sum.y = sum.y + (d... | Vitesse( dl | identifier_name |
ui.js | /**
* @license
* ui.js - v0.1
* Copyright (c) 2014, Alexandre Ayotte
*
* misc.js is licensed under the MIT License.
* https://www.opensource.org/licenses/MIT
**/
define(
['pixi454/pixi', 'libayo/misc'],
function( PIXI, MISC ) {
var ui = {
debog : false,
// 1 2 3 4 5 ... | textColorLT : 0x95e3ff,
path : svp_paths( "app/media/ui/" )
//app_paths.app + '/media/ui/'
}
ui.addBtn = function( layer, icoName, icoScale, actionOnClick, bigw, bigh ) {
var sp,ico
var baseAlpha = 0.8
var base = new PIXI.Container()
layer.addChild( base )
//sp.anchor.x = sp.anchor.y ... | fillColor : 0x95e3ff, //0x77d4f4, //0xb2f1ff, //0x95e4f6, ////0x89d3e4, //0x59b6b9,
textColor : 0x6fcbf0, //0x8dd0d5, //0xb7f2ff, //0xdbfbff, ///0xcef6ff, //b2f8f3, | random_line_split |
manterGrupoTaxaControle.js | /**
* @author F620600
*
* JavaScript que controla as ações das paginas:
* manterGrupo.html
* manterListaTaxaIOF.html
*
* @version 1.0.0.0
*
*
*/
define(['enumeracoes/eMensagemCCR',
'enumeracoes/eTipoServicos',
'util/retorno',
'modelo/taxas/grupoTaxa',
'text!visao/taxas/m... |
});
return ManterGrupoTaxaControle;
}); |
atualizar: function(){
_/*this.consultarTaxaIOF();
$('ul.nav a#manterTaxaIOF.links-menu').trigger('click');*/
} | random_line_split |
manterGrupoTaxaControle.js | /**
* @author F620600
*
* JavaScript que controla as ações das paginas:
* manterGrupo.html
* manterListaTaxaIOF.html
*
* @version 1.0.0.0
*
*
*/
define(['enumeracoes/eMensagemCCR',
'enumeracoes/eTipoServicos',
'util/retorno',
'modelo/taxas/grupoTaxa',
'text!visao/taxas/m... |
getCollection: function () {
if (_this.collection == null || this.collection == undefined)
_this.collection = new GrupoTaxaModel();
return _this.collection;
},
findGrupoTaxas : function(request, response) {
console.log("Manter Grupo Taxa - findGrupoTaxas");
... | .find('#listaGrupoTaxa').removeClass("hidden");
loadCCR.start();
// var codigo=0;
// var nome="teste";
// lista taxas
_this.getCollection().buscar(codigo,nome)
.done(function sucesso(data) {
_this.$el.find('#divListaGrupoTaxaShow').removeClass("hidden");
Retorno.trataR... | conditional_block |
bip32.rs | // Rust Bitcoin Library
// Written in 2014 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//... |
}
#[cfg(test)]
mod tests {
use serialize::hex::FromHex;
use test::{Bencher, black_box};
use network::constants::{Network, Bitcoin};
use util::base58::{FromBase58, ToBase58};
use super::{ChildNumber, ExtendedPrivKey, ExtendedPubKey, Hardened, Normal};
fn test_path(network: Network,
seed: ... | {
if data.len() != 78 {
return Err(InvalidLength(data.len()));
}
let cn_int = u64_from_be_bytes(data.as_slice(), 9, 4) as u32;
let child_number = if cn_int < (1 << 31) { Normal(cn_int) }
else { Hardened(cn_int - (1 << 31)) };
Ok(ExtendedPubKey {
network: match da... | identifier_body |
bip32.rs | // Rust Bitcoin Library
// Written in 2014 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//... | (master: &ExtendedPrivKey, path: &[ChildNumber])
-> Result<ExtendedPrivKey, Error> {
let mut sk = *master;
for &num in path.iter() {
sk = try!(sk.ckd_priv(num));
}
Ok(sk)
}
/// Private->Private child key derivation
pub fn ckd_priv(&self, i: ChildNumber) -> Result<Extended... | from_path | identifier_name |
bip32.rs | // Rust Bitcoin Library
// Written in 2014 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//... | impl Default for Fingerprint {
fn default() -> Fingerprint { Fingerprint([0, 0, 0, 0]) }
}
/// Extended private key
#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Show)]
pub struct ExtendedPrivKey {
/// The network this key is to be used on
pub network: Network,
/// How many derivations this key is fro... | impl_array_newtype!(Fingerprint, u8, 4)
impl_array_newtype_show!(Fingerprint)
impl_array_newtype_encodable!(Fingerprint, u8, 4)
| random_line_split |
f2s.rs | // Translated from C to Rust. The original C code can be found at
// https://github.com/ulfjack/ryu and carries the following license:
//
// Copyright 2018 Ulf Adams
//
// The contents of this file may be used under the terms of the Apache License,
// Version 2.0.
//
// (See accompanying file LICENSE-Apache or copy ... | ;
let exp = e10 + removed;
FloatingDecimal32 {
exponent: exp,
mantissa: output,
}
}
| {
// Specialized for the common case (~96.0%). Percentages below are relative to this.
// Loop iterations below (approximately):
// 0: 13.6%, 1: 70.7%, 2: 14.1%, 3: 1.39%, 4: 0.14%, 5+: 0.01%
while vp / 10 > vm / 10 {
last_removed_digit = (vr % 10) as u8;
vr /= 10... | conditional_block |
f2s.rs | // Translated from C to Rust. The original C code can be found at
// https://github.com/ulfjack/ryu and carries the following license:
//
// Copyright 2018 Ulf Adams
//
// The contents of this file may be used under the terms of the Apache License,
// Version 2.0.
//
// (See accompanying file LICENSE-Apache or copy ... | (m: u32, q: u32, j: i32) -> u32 {
debug_assert!(q < FLOAT_POW5_INV_SPLIT.len() as u32);
unsafe { mul_shift(m, *FLOAT_POW5_INV_SPLIT.get_unchecked(q as usize), j) }
}
#[cfg_attr(feature = "no-panic", inline)]
fn mul_pow5_div_pow2(m: u32, i: u32, j: i32) -> u32 {
debug_assert!(i < FLOAT_POW5_SPLIT.len() as u... | mul_pow5_inv_div_pow2 | identifier_name |
f2s.rs | // Translated from C to Rust. The original C code can be found at
// https://github.com/ulfjack/ryu and carries the following license:
//
// Copyright 2018 Ulf Adams
//
// The contents of this file may be used under the terms of the Apache License,
// Version 2.0.
//
// (See accompanying file LICENSE-Apache or copy ... |
// Returns true if value is divisible by 5^p.
#[cfg_attr(feature = "no-panic", inline)]
fn multiple_of_power_of_5(value: u32, p: u32) -> bool {
pow5_factor(value) >= p
}
// Returns true if value is divisible by 2^p.
#[cfg_attr(feature = "no-panic", inline)]
fn multiple_of_power_of_2(value: u32, p: u32) -> bool {
... | }
count
} | random_line_split |
discovery.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: proto/v1/discovery.proto
package discovery_go_proto
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
common_go_proto "github.com/grafeas/grafeas/proto/v1/common_go_proto"
status "google.... | proto.RegisterEnum("grafeas.v1.discovery.Discovered_ContinuousAnalysis", Discovered_ContinuousAnalysis_name, Discovered_ContinuousAnalysis_value)
proto.RegisterEnum("grafeas.v1.discovery.Discovered_AnalysisStatus", Discovered_AnalysisStatus_name, Discovered_AnalysisStatus_value)
proto.RegisterType((*Discovery)(nil),... | return nil
}
func init() { | random_line_split |
discovery.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: proto/v1/discovery.proto
package discovery_go_proto
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
common_go_proto "github.com/grafeas/grafeas/proto/v1/common_go_proto"
status "google.... |
return nil
}
func init() {
proto.RegisterEnum("grafeas.v1.discovery.Discovered_ContinuousAnalysis", Discovered_ContinuousAnalysis_name, Discovered_ContinuousAnalysis_value)
proto.RegisterEnum("grafeas.v1.discovery.Discovered_AnalysisStatus", Discovered_AnalysisStatus_name, Discovered_AnalysisStatus_value)
proto.R... | {
return m.AnalysisStatusError
} | conditional_block |
discovery.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: proto/v1/discovery.proto
package discovery_go_proto
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
common_go_proto "github.com/grafeas/grafeas/proto/v1/common_go_proto"
status "google.... | () *Discovered {
if m != nil {
return m.Discovered
}
return nil
}
// Provides information about the analysis status of a discovered resource.
type Discovered struct {
// Whether the resource is continuously analyzed.
ContinuousAnalysis Discovered_ContinuousAnalysis `protobuf:"varint,1,opt,name=continuous_analys... | GetDiscovered | identifier_name |
discovery.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: proto/v1/discovery.proto
package discovery_go_proto
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
common_go_proto "github.com/grafeas/grafeas/proto/v1/common_go_proto"
status "google.... |
func (Discovered_AnalysisStatus) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_046437f686d0269e, []int{2, 1}
}
// DO NOT USE: UNDER HEAVY DEVELOPMENT.
// TODO(aysylu): finalize this.
//
// A note that indicates a type of analysis a provider would perform. This note
// exists in a provider's project. A `D... | {
return proto.EnumName(Discovered_AnalysisStatus_name, int32(x))
} | identifier_body |
word2vec.py | import os
from collections import Counter
from datetime import datetime
import numpy as np
import tensorflow as tf
from tensorflow.compat import v1 as tfv1
from mixins import BoardRecorderMixin
class DistributedRepresentations:
|
class Word2Vec(BoardRecorderMixin):
"""Base class for wor2vec.
Attributes:
words (list): List of words
vocab_size (int): Size of `words`
corpus (list): Corpus
word_vectors (:obj:`WordVectors`): Results of model. You can reforence
after call `train` method.
"""... | """Distributed Represendations of the words.
Args:
words (list): List of words
vectors (numpy.array): Vectors encoded words
Attributes:
vecs (numpy.array): Vectors encoded words
words (list): List of words
"""
def __init__(self, words, vectors):
self.words = wor... | identifier_body |
word2vec.py | import os
from collections import Counter
from datetime import datetime
import numpy as np
import tensorflow as tf
from tensorflow.compat import v1 as tfv1
from mixins import BoardRecorderMixin
class DistributedRepresentations:
"""Distributed Represendations of the words.
Args:
words (list): List o... | (self):
raise NotImplementedError
def get_labels(self):
raise NotImplementedError
def fetch_batch(self, incomes, labels, epoch_i, batch_i, batch_size):
raise NotImplementedError
def train(self, log_dir=None, max_epoch=10000, learning_rate=0.001,
batch_size=None, inte... | get_incomes | identifier_name |
word2vec.py | import os
from collections import Counter
from datetime import datetime
import numpy as np
import tensorflow as tf
from tensorflow.compat import v1 as tfv1
from mixins import BoardRecorderMixin
class DistributedRepresentations:
"""Distributed Represendations of the words.
Args:
words (list): List o... |
self.record(sess, writer, step, feed_dict=fd)
step += 1
self.word_reps.vecs = sess.run(self.W_in)
self.record(sess, writer, step, feed_dict=fd, force_write=True)
| writer.add_run_metadata(metadata, f'step: {step}') | conditional_block |
word2vec.py | import os
from collections import Counter
from datetime import datetime
import numpy as np
import tensorflow as tf
from tensorflow.compat import v1 as tfv1
from mixins import BoardRecorderMixin
class DistributedRepresentations:
"""Distributed Represendations of the words.
Args:
words (list): List o... | feed_dict=fd,
options=options,
run_metadata=metadata)
if run_metadata:
writer.add_run_metadata(metadata, f'step: {step}')
self.record(sess, write... | }
sess.run(self.training_op, | random_line_split |
elasticsearch_adapter.js | const MainDatabase = require('../mainDatabase.js');
const elasticsearch = require('elasticsearch');
const AgentKeepAlive = require('agentkeepalive');
const cloneObject = require('clone');
const async = require('async');
const {BuilderNode} = require('../../../utils/filterbuilder');
const NexxusError = require('../../Ne... |
return {errors};
}
async updateObjects (patches) {
if (!Array.isArray(patches) || patches.length === 0) {
throw new NexxusError(NexxusError.errors.InvalidFieldValue, 'ElasticSearchDB.updateObjects: "patches" should be a non-empty array');
}
let errors = [];
let shouldRefresh = false;
let finalResul... | {
res.items.forEach(error => {
errors.push(new NexxusError('ServerFailure', `Error creating ${error.index._type}: ${error.index.error}`));
});
} | conditional_block |
elasticsearch_adapter.js | const MainDatabase = require('../mainDatabase.js');
const elasticsearch = require('elasticsearch');
const AgentKeepAlive = require('agentkeepalive');
const cloneObject = require('clone');
const async = require('async');
const {BuilderNode} = require('../../../utils/filterbuilder');
const NexxusError = require('../../Ne... |
/**
*
* @param {FilterBuilder} builder
* @return {Object} The result of <code>builder.build()</code> but with a few translations for ES
*/
getQueryObject (builder) {
const translationMappings = {
is: 'term',
not: 'not',
exists: 'exists',
range: 'range',
in_array: 'terms',
lik... | {
if (modifications.added.schema) {
const addedModels = Object.keys(modifications.added.schema);
await addedModels.reduce(async (promise, modelName) => {
await promise;
try {
await this.connection.indices.create({
index: `${constants.CHANNEL_KEY_PREFIX}-${applicationId}-${modelName}`
}... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.