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 |
|---|---|---|---|---|
io_export_arm.py | # Armory Mesh Exporter
# http://armory3d.org/
#
# Based on Open Game Engine Exchange
# http://opengex.org/
# Export plugin for Blender by Eric Lengyel
# Copyright 2015, Terathon Software LLC
#
# This software is licensed under the Creative Commons
# Attribution-ShareAlike 3.0 Unported License:
# http://creati... | cdata = np.array(cdata, dtype='<i2')
if has_tang:
tangdata *= 32767
tangdata = np.array(tangdata, dtype='<i2')
# Output
o['vertex_arrays'] = []
o['vertex_arrays'].append({ 'attrib': 'pos', 'values': pdata })
o['vertex_arrays'].append({ 'attrib... | random_line_split | |
geom_func.py | import numpy as np
##########################################################################################
# Geometric Functions for rotating/deforming/aligning triangles.
# For the purpose of measuring deformation gradient between two triangles
# Tim Tyree
# 6.25.2020
###########################################... |
def test_func(tris,trim):
retval = align_triangles(trim,tris, testing=True)
xm2, xm1, ym2, ym1, xs2, xs1, ys2, ys1, xhat, yhat, xi1, xi2, s = retval
return True
def test_main(tid1 = 71, tid2 = 30):
import trimesh
mesh = trimesh.load('../Data/spherical_meshesspherical_mesh_64.stl')
#subtract the center of mass
... | F = get_F(trim,tris)
b = tris[0] - F.dot(trim[0])
return lambda X: phi(F,X,b) | identifier_body |
geom_func.py | import numpy as np
##########################################################################################
# Geometric Functions for rotating/deforming/aligning triangles.
# For the purpose of measuring deformation gradient between two triangles
# Tim Tyree
# 6.25.2020
###########################################... | (F,X,b):
return F.dot(X) + b
def get_phi(trim,tris):
F = get_F(trim,tris)
b = tris[0] - F.dot(trim[0])
return lambda X: phi(F,X,b)
def test_func(tris,trim):
retval = align_triangles(trim,tris, testing=True)
xm2, xm1, ym2, ym1, xs2, xs1, ys2, ys1, xhat, yhat, xi1, xi2, s = retval
return True
def test_main(tid1... | phi | identifier_name |
geom_func.py | import numpy as np
##########################################################################################
# Geometric Functions for rotating/deforming/aligning triangles.
# For the purpose of measuring deformation gradient between two triangles
# Tim Tyree
# 6.25.2020
###########################################... | # # test the explicit deformation map for a number of triangles
# tris = mesh.triangles[71]
# trim = mesh.triangles[30]
# mtos = get_phi(trim,tris)
# trim_mapped = np.array([mtos(trim[0]),mtos(trim[1]),mtos(trim[2])])
# print('tris is')
# print(tris)
# print('trim is mapped to')
# print(trim_mapped)
# print('difference... | # #normalize the mean radius to 1
# mesh.vertices /= np.cbrt(mesh.volume*3/(4*np.pi)) | random_line_split |
geom_func.py | import numpy as np
##########################################################################################
# Geometric Functions for rotating/deforming/aligning triangles.
# For the purpose of measuring deformation gradient between two triangles
# Tim Tyree
# 6.25.2020
###########################################... |
R = Rb.dot(Ra)
if testing:
# test that R = Rb.dot(Ra).T rotates Amhat onto Ashat
assert(np.isclose(np.abs(np.dot(R.dot(Amhat),Ashat)),1.).all())
# test that R = (Rb*Ra).T rotates dm1 onto ds1
assert(np.isclose(R.dot(dm1/np.linalg.norm(dm1)),ds1/np.linalg.norm(ds1)).all())
return R
########################... | assert(np.isclose(np.dot(Rb, v1),v2).all())
assert(np.isclose(np.abs(np.dot(np.dot(Ra, Amhat),Ashat)),1.).all()) | conditional_block |
train_i2t_gan.py | from tqdm import tqdm
import numpy as np
from PIL import Image
import argparse
import random
import pickle
import os
from copy import deepcopy
from shutil import copy
from itertools import chain
import torch
import torch.nn.functional as F
from torch import nn, optim
from torch.autograd import Variable, grad
from torc... |
def make_target(word_idcs):
target = torch.zeros(word_idcs.size(0), 2100).cuda()
for idx in range(word_idcs.shape[0]):
target[idx][word_idcs[idx]] = 1
return target
from random import shuffle
def true_randperm(size, device=torch.device("cuda:0")):
def unmatched_randperm(size):
l1 = ... | """Analytically computes
E_N(mu_2,sigma_2^2) [ - log N(mu_1, sigma_1^2) ]
If mu_2, and sigma_2^2 are not provided, defaults to entropy.
"""
mu = params[:,:,0]
logsigma = params[:,:,1]
c = normalization.to(mu.device)
inv_sigma = torch.exp(-logsigma)
tmp = (sample - mu) * in... | identifier_body |
train_i2t_gan.py | from tqdm import tqdm
import numpy as np
from PIL import Image
import argparse
import random
import pickle
import os
from copy import deepcopy
from shutil import copy
from itertools import chain
import torch
import torch.nn.functional as F
from torch import nn, optim
from torch.autograd import Variable, grad
from torc... | (img_root='/media/bingchen/research3/CUB_birds/CUB_200_2011/images'):
img_meta_root = img_root
img_meta_root = img_meta_root.replace('images','birds_meta')
def loader(transform, batch_size=4):
data = CaptionImageDataset(img_root, img_meta_root, transform=transform)
data_loader = DataLoader(... | image_cap_loader | identifier_name |
train_i2t_gan.py | from tqdm import tqdm
import numpy as np
from PIL import Image
import argparse
import random
import pickle
import os
from copy import deepcopy
from shutil import copy
from itertools import chain
import torch
import torch.nn.functional as F
from torch import nn, optim
from torch.autograd import Variable, grad
from torc... |
print(args.path)
loader = image_cap_loader(args.path)
total_iter = args.total_iter
train_image_gan_with_text(net_tg, net_td, opt_tg, opt_td, total_iter, loader, args) | opt_tg.add_param_group({'params': chain(net_tg.word_attn_4.parameters(),
net_tg.word_attn_16.parameters(),
net_tg.sentence_attn_4.parameters(),
net_tg.sentence_attn_16.parameters(),
), 'lr... | conditional_block |
train_i2t_gan.py | from tqdm import tqdm
import numpy as np
from PIL import Image
import argparse
import random
import pickle
import os
from copy import deepcopy
from shutil import copy
from itertools import chain
import torch
import torch.nn.functional as F
from torch import nn, optim
from torch.autograd import Variable, grad
from torc... | loss_disc.backward()
opt_td.step()
text_d_val += real_predict.mean().item()
### 3.2 train the image-text discriminator
net_tdi.zero_grad()
real_predict = net_tdi(real_text_latent, img_feat_4, img_feat_16)
fake_predict = net_tdi(g_text_latent.detach(), img_feat_4... | real_predict = net_td(real_text_latent)
fake_predict = net_id(g_text_latent.detach())
loss_disc = F.relu(1-real_predict).mean() + F.relu(1+fake_predict).mean() | random_line_split |
jquery.pagination.js | /**
* This jQuery plugin displays pagination links inside the selected elements.
*
* @author Gabriel Birke (birke *at* d-scribe *dot* de)
* @version 1.1
* @param {int} maxentries Number of entries to paginate
* @param {Object} opts Several options (see README for documentation)
* @return {Object} jQuery Object
... | ge = function() {
if (current_page < numPages() - 1) {
pageSelected(current_page + 1);
return true;
}
else {
return false;
}
}
// When all initialisation is done, draw the links
drawLinks();
});
}... | ;
}
}
this.nextPa | conditional_block |
jquery.pagination.js | /**
* This jQuery plugin displays pagination links inside the selected elements.
*
* @author Gabriel Birke (birke *at* d-scribe *dot* de)
* @version 1.1
* @param {int} maxentries Number of entries to paginate
* @param {Object} opts Several options (see README for documentation)
* @return {Object} jQuery Object
... | });
};
}
// Extract current_page from options
var current_page = opts.current_page;
// Create a sane value for maxentries and items_per_page
maxentries = (!maxentries || maxentries < 0) ? 1 : maxentries;
opts.items_per_page = (!opts.items_per_page || opts.items_pe... | pageSelected(page_id-1,e); | random_line_split |
jquery.pagination.js | /**
* This jQuery plugin displays pagination links inside the selected elements.
*
* @author Gabriel Birke (birke *at* d-scribe *dot* de)
* @version 1.1
* @param {int} maxentries Number of entries to paginate
* @param {Object} opts Several options (see README for documentation)
* @return {Object} jQuery Object
... |
/**
* This is the event handling function for the pagination links.
* @param {int} page_id The new page number
*/
function pageSelected(page_id, evt) {
current_page = page_id;
drawLinks();
var continuePropagation = opts.callback(page_id, pan... | {
var ne_half = Math.ceil(opts.num_display_entries / 2);
var np = numPages();
var upper_limit = np - opts.num_display_entries;
var start = current_page > ne_half ? Math.max(Math.min(current_page - ne_half, upper_limit), 0) : 0;
var end = current_page > ne_half... | identifier_body |
jquery.pagination.js | /**
* This jQuery plugin displays pagination links inside the selected elements.
*
* @author Gabriel Birke (birke *at* d-scribe *dot* de)
* @version 1.1
* @param {int} maxentries Number of entries to paginate
* @param {Object} opts Several options (see README for documentation)
* @return {Object} jQuery Object
... | () {
return Math.ceil(maxentries / opts.items_per_page);
}
/**
* Calculate start and end point of pagination links depending on
* current_page and num_display_entries.
* @return {Array}
*/
function getInterval() {
var ne_half = Math.ceil(... | numPages | identifier_name |
tag_processor.go | /*
* Copyright (c) 2018, Juniper Networks, Inc.
* All rights reserved.
*/
package util
import "sync"
type ProtobufLabel uint
type ProtobufType uint
type ProtobufWireType uint
type ProtobufArchType uint
const (
/** A well-formed message must have exactly one of this field. */
PROTOBUF_LABEL_REQUIRED = iota
/*... | (v int64) uint32 {
return uint64Size(zigzag64(v))
}
/*
* Pack an unsigned 32-bit integer in base-128 varint encoding and return the
* number of bytes written, which must be 5 or less.
*/
func Uint32Pack(value uint32, buf []byte) ([]byte, uint32) {
var rv uint32 = 0
if value >= 0x80 {
buf = append(buf, byte(va... | sint64Size | identifier_name |
tag_processor.go | /*
* Copyright (c) 2018, Juniper Networks, Inc.
* All rights reserved.
*/
package util
import "sync"
type ProtobufLabel uint
type ProtobufType uint
type ProtobufWireType uint
type ProtobufArchType uint
const (
/** A well-formed message must have exactly one of this field. */
PROTOBUF_LABEL_REQUIRED = iota
/*... |
func ParseFixedUint64(data []byte) uint64 {
return uint64(ParseFixedUint32(data)) |
(uint64(ParseFixedUint32(data[4:])) << 32)
}
func ParseBoolean(length uint32, data []byte) bool {
var i uint32
for i = 0; i < length; i++ {
if b := uint8(data[i]) & 0x7f; b != 0 {
return true
}
}
return false
}
func... | {
if b := v & 1; b != 0 {
return -int64(v>>1) - 1
} else {
return int64(v >> 1)
}
} | identifier_body |
tag_processor.go | /*
* Copyright (c) 2018, Juniper Networks, Inc.
* All rights reserved.
*/
package util
import "sync"
type ProtobufLabel uint
type ProtobufType uint
type ProtobufWireType uint
type ProtobufArchType uint
const (
/** A well-formed message must have exactly one of this field. */
PROTOBUF_LABEL_REQUIRED = iota
/*... | }
return 0 /* error: bad header */
}
/*
* get prefix data length
*/
func ScanLengthPrefixData(length uint32, data []byte,
prefix_len_out *uint32) uint32 {
var hdr_max uint32
if length < 5 {
hdr_max = length
} else {
hdr_max = 5
}
var hdr_len uint32
var val uint32 = 0
var shift uint32 = 0
var i uint... | random_line_split | |
tag_processor.go | /*
* Copyright (c) 2018, Juniper Networks, Inc.
* All rights reserved.
*/
package util
import "sync"
type ProtobufLabel uint
type ProtobufType uint
type ProtobufWireType uint
type ProtobufArchType uint
const (
/** A well-formed message must have exactly one of this field. */
PROTOBUF_LABEL_REQUIRED = iota
/*... |
rv = (uint64(data[0] & 0x7f)) |
(uint64(data[1]&0x7f) << 7) |
(uint64(data[2]&0x7f) << 14) |
(uint64(data[3]&0x7f) << 21)
shift = 28
for i = 4; i < length; i++ {
rv = rv | ((uint64(data[i] & 0x7f)) << shift)
shift += 7
}
return rv
}
func Unzigzag64(v uint64) int64 {
if b := v & 1; b != 0 {
return... | {
return uint64(ParseUint32(length, data))
} | conditional_block |
forothree.go | package main
import "fmt"
import "github.com/valyala/fasthttp"
import "time"
import "strconv"
import "os"
import "bufio"
import "net/url"
import "strings"
import "sync"
import "flag"
import "io/ioutil"
import "unicode"
import "regexp"
import "github.com/dchest/uniuri"
//forothree v.0.1
//created by hanhanhan
type... | else if unicode.IsLower(run[0]) {
str := string(run[0])
str = strings.ToUpper(str)
slic[i] = str
res := strings.Join(slic,"")
return res
} else {
continue
}
}
return ""
}
func strtoaciicode(s string, n int) (string) { //change a char number n in string to ascicode
slic := strings.... | {
str := string(run[0])
str = strings.ToLower(str)
slic[i] = str
res := strings.Join(slic,"")
return res
} | conditional_block |
forothree.go | package main
import "fmt"
import "github.com/valyala/fasthttp"
import "time"
import "strconv"
import "os"
import "bufio"
import "net/url"
import "strings"
import "sync"
import "flag"
import "io/ioutil"
import "unicode"
import "regexp"
import "github.com/dchest/uniuri"
//forothree v.0.1
//created by hanhanhan
type... | (r rawconf, dir string) {
var wg sync.WaitGroup
myrequest(r,dir,"","",&wg)
defer func(){
wg.Wait()
}()
go myrequest(r,dir,"DOMAINMOD",".",&wg)
go myrequest(r,dir,"%2" + "e/","",&wg)
go myrequest(r,dir,"","..;/",&wg) // LOOP?
go myrequest(r,dir,"..;/","",&wg) //and ../ LOOP?
go myrequest(r,d... | payloads2 | identifier_name |
forothree.go | package main
import "fmt"
import "github.com/valyala/fasthttp"
import "time"
import "strconv"
import "os"
import "bufio"
import "net/url"
import "strings"
import "sync"
import "flag"
import "io/ioutil"
import "unicode"
import "regexp"
import "github.com/dchest/uniuri"
//forothree v.0.1
//created by hanhanhan
type... |
func main() {
var r = rawconf{}
flag.BoolVar(&(r.Bodylen),"l",false," show response length")
//code still redundant/inefficient
t1 := flag.String("s","200,404,403,301,404","-s specify status code, ex 200,404")
//code still redundant/inefficient
t2 := flag.String("e","Connectio... | {
r.Xheaders = true
var wg sync.WaitGroup
defer func(){
//wg.Done()
wg.Wait()
}()
g,_ := os.Open("headerbypass.txt") // iterate file lineByLine
g2 := bufio.NewScanner(g)
var lol []string
for g2.Scan() {
var line =... | identifier_body |
forothree.go | package main
import "fmt"
import "github.com/valyala/fasthttp"
import "time"
import "strconv"
import "os"
import "bufio"
import "net/url"
import "strings"
import "sync"
import "flag"
import "io/ioutil"
import "unicode"
import "regexp"
import "github.com/dchest/uniuri"
//forothree v.0.1
//created by hanhanhan
type... |
return domain,dir
}
func parseurldirs (urlz string) (string,[]string) { //parse url with subdirectory
unparse,err := url.QueryUnescape(urlz)
u,err := url.Parse(unparse)
var temp,domain = "",""
if err != nil {
fmt.Println("[-]error, something wrong when parsing the url in directory: %s",err)
}
if u.Schem... | random_line_split | |
Sponsoring.js | import React from "react";
import {
CardBody,
Card,
CardImg,
Container,
Row,
Col,
} from "reactstrap";
import { Link } from "react-router-dom";
import DemoNavbar from "components/Navbars/DemoNavbar.js";
import CardsFooter from "components/Footers/CardsFooter.js";
import { MovingComponent } from "react-movin... | () {
const { status } = this.state;
const { form } = this.state;
return (
<>
<DemoNavbar />
<main ref="main" style={{userSelect: 'none'}}>
<div className="position-relative">
<section className="section section-lg section-shaped pb-150 " style={{backgroundCol... | render | identifier_name |
Sponsoring.js | import React from "react";
import {
CardBody,
Card,
CardImg,
Container,
Row,
Col,
} from "reactstrap";
import { Link } from "react-router-dom";
import DemoNavbar from "components/Navbars/DemoNavbar.js";
import CardsFooter from "components/Footers/CardsFooter.js";
import { MovingComponent } from "react-movin... | v.preventDefault();
const form = ev.target;
const data = new FormData(form);
const xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = () => {
if (xhr.readyState !== XMLHttpRequest.DONE) return;
... | {
const { status } = this.state;
const { form } = this.state;
return (
<>
<DemoNavbar />
<main ref="main" style={{userSelect: 'none'}}>
<div className="position-relative">
<section className="section section-lg section-shaped pb-150 " style={{backgroundColor:... | identifier_body |
Sponsoring.js | import React from "react";
import {
CardBody,
Card,
CardImg,
Container,
Row,
Col,
} from "reactstrap";
import { Link } from "react-router-dom";
import DemoNavbar from "components/Navbars/DemoNavbar.js";
import CardsFooter from "components/Footers/CardsFooter.js";
import { MovingComponent } from "react-movin... | xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = () => {
if (xhr.readyState !== XMLHttpRequest.DONE) return;
if (xhr.status === 200) {
form.reset();
this.setState({ status: "SUCCESS" });
this.setState({ form: "off" });
setTimeout(() => {
... | random_line_split | |
Sponsoring.js | import React from "react";
import {
CardBody,
Card,
CardImg,
Container,
Row,
Col,
} from "reactstrap";
import { Link } from "react-router-dom";
import DemoNavbar from "components/Navbars/DemoNavbar.js";
import CardsFooter from "components/Footers/CardsFooter.js";
import { MovingComponent } from "react-movin... | tate({ status: "ERROR" });
}
};
xhr.send(data);
}
}
export default Sponsoring;
| this.setState({ status: "SUCCESS" });
this.setState({ form: "off" });
setTimeout(() => {
this.setState({ status: "" });
this.setState({ form: "on" });
}, (5000));
} else {
this.setS | conditional_block |
model.go | // Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//=== High-level schema ===
// Each playground bundle is stored once as a BundleData in the bundle_data
// table. The BundleData contains the json string ... | // BundleLink with a particular id or slug. Id is tried first, slug if id
// doesn't exist.
// Note: This can fail if the bundle is deleted between fetching BundleLink
// and BundleData. However, it is highly unlikely, costly to mitigate (using
// a serializable transaction), and unimportant (error 500 instead of 404).... | return bLinks, nil
}
// GetBundleByLinkIdOrSlug retrieves a BundleData object linked to by a | random_line_split |
model.go | // Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//=== High-level schema ===
// Each playground bundle is stored once as a BundleData in the bundle_data
// table. The BundleData contains the json string ... |
if err != nil {
return nil, nil, err
}
bData, err := getBundleDataByHash(dbRead, bLink.Hash)
if err != nil {
return nil, nil, err
}
return bLink, bData, nil
}
// GetDefaultBundleList retrieves a list of BundleLink objects describing
// default bundles. All default bundles have slugs.
func GetDefaultBundleLi... | {
bLink, err = getDefaultBundleLinkBySlug(dbRead, idOrSlug)
} | conditional_block |
model.go | // Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//=== High-level schema ===
// Each playground bundle is stored once as a BundleData in the bundle_data
// table. The BundleData contains the json string ... | (tx *sqlx.Tx, bundle *NewBundle, asDefault bool) (*BundleLink, *BundleData, error) {
// All default bundles must have non-empty slugs.
if asDefault && bundle.Slug == "" {
return nil, nil, fmt.Errorf("default bundle must have non-empty slug")
}
bHashRaw := hash.Raw([]byte(bundle.Json))
bHash := bHashRaw[:]
// ... | storeBundle | identifier_name |
model.go | // Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//=== High-level schema ===
// Each playground bundle is stored once as a BundleData in the bundle_data
// table. The BundleData contains the json string ... |
// All default bundles have non-empty slugs. Check just in case.
func getDefaultBundleList(q sqlx.Queryer) ([]*BundleLink, error) {
var bLinks []*BundleLink
if err := sqlx.Select(q, &bLinks, "SELECT * FROM bundle_link WHERE is_default AND slug IS NOT NULL"); err != nil {
return nil, err
}
return bLinks, nil
}
... | {
var bData BundleData
if err := sqlx.Get(q, &bData, "SELECT * FROM bundle_data WHERE hash=?", hash); err != nil {
if err == sql.ErrNoRows {
err = ErrNotFound
}
return nil, err
}
return &bData, nil
} | identifier_body |
selenium_test.go | // +build selenium
/*
* Copyright (C) 2017 Red Hat, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you und... | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package tests
import (
"errors"
"fmt"
"net"
"os"
"testing"
"time"
"github.com/tebeka/selenium"
gclien... | *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an | random_line_split |
selenium_test.go | // +build selenium
/*
* Copyright (C) 2017 Red Hat, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you und... | {
ifaces, err := net.Interfaces()
if err != nil {
return "", err
}
for _, iface := range ifaces {
//neglect interfaces which are down
if iface.Flags&net.FlagUp == 0 {
continue
}
//neglect loopback interface
if iface.Flags&net.FlagLoopback != 0 {
continue
}
addrs, err := iface.Addrs()
if err... | identifier_body | |
selenium_test.go | // +build selenium
/*
* Copyright (C) 2017 Red Hat, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you und... |
injectSrc, err := findElement(selenium.ByXPATH, ".//*[@id='inject-src']/input")
if err != nil {
return err
}
if err := injectSrc.Click(); err != nil {
return fmt.Errorf("Failed to click on inject input: %s", err.Error())
}
if err = selectNode("G.V().Has('Name', 'eth0', 'IPV4', Contains('124.65.54.... | {
return fmt.Errorf("Could not click on generator tab: %s", err.Error())
} | conditional_block |
selenium_test.go | // +build selenium
/*
* Copyright (C) 2017 Red Hat, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you und... | (t *testing.T) {
gopath := os.Getenv("GOPATH")
topology := gopath + "/src/github.com/skydive-project/skydive/scripts/simple.sh"
setupCmds := []helper.Cmd{
{fmt.Sprintf("%s start 124.65.54.42/24 124.65.54.43/24", topology), true},
{"docker pull elgalu/selenium", true},
{"docker run -d --name=grid -p 4444:24444... | TestSelenium | identifier_name |
lib.rs | // Copyright (C) 2021 Subspace Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// Unle... | (&self) -> Weight {
T::WeightInfo::message()
}
fn message_response(
&self,
dst_chain_id: ChainId,
message_id: MessageIdOf<T>,
req: EndpointRequest,
resp: EndpointResponse,
) -> DispatchResult {
// ensure request... | message_weight | identifier_name |
lib.rs | // Copyright (C) 2021 Subspace Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// Unle... | ChainId,
Identity,
MessageIdOf<T>,
Transfer<BalanceOf<T>>,
OptionQuery,
>;
/// Events emitted by pallet-transporter.
#[pallet::event]
#[pallet::generate_deposit(pub (super) fn deposit_event)]
pub enum Event<T: Config> {
/// Emits when there is a new o... | _,
Identity, | random_line_split |
api-blueprint-resource.js | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var fspath = require('path');
var async = require('async');
var dd = require('drilldown');
var theme = require('aglio-theme-olio');
var handlebars = require('handlebars');
var apiBlueprint = require('./api-blueprint');
module.exports.apiBlueprintDocsUri... |
function addQueryParameter(parameter, checkFunction, json, done) {
if (json.__domain && json.__domain !== 'local') {
return done(null, json);
}
async.each(json.ast.resourceGroups, function(resourceGroup, groupDone) {
async.each(resourceGroup.resources, function(resource, resourceDone) {
... | {
addQueryParameter({
name: 'spy-for-versioning',
description: '**DEVELOPMENT ONLY:** when `true`, generate a schema from this resource\'s response, and capture responses from external systems like JDS and VistA.\n\nSchemas are generated under `src/core/api-blueprint/schemas`, and external responses... | identifier_body |
api-blueprint-resource.js | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var fspath = require('path');
var async = require('async');
var dd = require('drilldown');
var theme = require('aglio-theme-olio');
var handlebars = require('handlebars');
var apiBlueprint = require('./api-blueprint');
module.exports.apiBlueprintDocsUri... |
fullHtml = html;
sendHtml(res, error, html);
});
});
}
function renderSingleResource(mountpoint, req, res) {
if (renderedHtml[mountpoint]) {
return sendHtml(res, null, renderedHtml[mountpoint]);
}
async.waterfall([
apiBlueprint.jsonDocumentationForPath.... | {
return res.status(500).rdkSend(error);
} | conditional_block |
api-blueprint-resource.js | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var fspath = require('path');
var async = require('async');
var dd = require('drilldown');
var theme = require('aglio-theme-olio');
var handlebars = require('handlebars');
var apiBlueprint = require('./api-blueprint');
module.exports.apiBlueprintDocsUri... | (parameter, checkFunction, json, done) {
if (json.__domain && json.__domain !== 'local') {
return done(null, json);
}
async.each(json.ast.resourceGroups, function(resourceGroup, groupDone) {
async.each(resourceGroup.resources, function(resource, resourceDone) {
var applies = fal... | addQueryParameter | identifier_name |
api-blueprint-resource.js | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var fspath = require('path');
var async = require('async');
var dd = require('drilldown');
var theme = require('aglio-theme-olio');
var handlebars = require('handlebars');
var apiBlueprint = require('./api-blueprint');
module.exports.apiBlueprintDocsUri... | theme.render(json.ast, {themeForms: true}, done);
}
function sendHtml(res, error, html) {
if (error) {
return res.status(500).rdkSend(error);
}
return res.send(html);
} | });
return resource;
}
function renderHtml(json, done) { | random_line_split |
LFEDocumentClassifier.py | import gc
import pandas as pd
from rake_nltk import Rake
from ReutersDataManager import *
from ArgParser import *
from InputCleaner import *
from WordEmbedding import *
from FeatureCreation import *
from Classifiers import *
from TestManager import *
from FileIO import *
# Handle command line arguments and set progra... |
# Apply all pre-processing to clean text and themes
ic = InputCleaner(dataFile, themePairs, 'excellenceText', 'themeExcellence', GENERATE_1D_THEMES)
ic.cleanText(REMOVE_NUMERIC, REMOVE_SINGLE_LETTERS, REMOVE_KEYWORDS, REMOVE_EXTRA_SPACES)
categoryCount = len(ALL_THEMES_LIST)
# TODO: [PIPELINE SPLIT 2]... | else:
# Read raw .XLSX file and store as pandas data-frame
dataFile = pd.read_excel(LFE_DATA_FILE_PATH, engine='openpyxl') | random_line_split |
LFEDocumentClassifier.py | import gc
import pandas as pd
from rake_nltk import Rake
from ReutersDataManager import *
from ArgParser import *
from InputCleaner import *
from WordEmbedding import *
from FeatureCreation import *
from Classifiers import *
from TestManager import *
from FileIO import *
# Handle command line arguments and set progra... |
elif CLASSIFIER_NAME == 'nn':
if NN_USE_KERAS:
classifier = MultiLayerPerceptronKeras(featuresMasks, targetMasks,
TEST_GROUP_SIZE,
RANDOM_STATE,
NN_BATCH_SIZE,
... | classifier = ComplementNaiveBayes(featuresMasks, targetMasks,
USE_MULTI_LABEL_CLASSIFICATION,
TEST_GROUP_SIZE,
RANDOM_STATE,
PRINT_PROGRESS) | conditional_block |
state_chart.js | // define a custom ForceDirectedLayout for this sample
function DemoForceDirectedLayout() {
go.ForceDirectedLayout.call(this);
}
go.Diagram.inherit(DemoForceDirectedLayout, go.ForceDirectedLayout);
// Override the makeNetwork method to also initialize
// ForceDirectedVertex.isFixed from the corresponding Node.isS... | // read in the JSON data from the "mySavedModel" element
// load();
}
// Show the diagram's model in JSON format
// function save() {
// document.getElementById("mySavedModel").value = myDiagram.model.toJson();
// }
function load(val) {
myDiagram.model = go.Model.fromJson(val);
}
// function load() {... | random_line_split | |
state_chart.js | // define a custom ForceDirectedLayout for this sample
function DemoForceDirectedLayout() {
go.ForceDirectedLayout.call(this);
}
go.Diagram.inherit(DemoForceDirectedLayout, go.ForceDirectedLayout);
// Override the makeNetwork method to also initialize
// ForceDirectedVertex.isFixed from the corresponding Node.isS... | () {
go.ForceDirectedLayout.call(this);
this._isObserving = false;
}
go.Diagram.inherit(ContinuousForceDirectedLayout, go.ForceDirectedLayout);
ContinuousForceDirectedLayout.prototype.isFixed = function (v) {
return v.node.isSelected;
};
// optimization: reuse the ForceDirectedNetwork rather than re-crea... | ContinuousForceDirectedLayout | identifier_name |
state_chart.js | // define a custom ForceDirectedLayout for this sample
function DemoForceDirectedLayout() {
go.ForceDirectedLayout.call(this);
}
go.Diagram.inherit(DemoForceDirectedLayout, go.ForceDirectedLayout);
// Override the makeNetwork method to also initialize
// ForceDirectedVertex.isFixed from the corresponding Node.isS... | function addPeropertyNode(e, obj) {
var adornment = obj.part;
var diagram = e.diagram;
diagram.startTransaction("Add State");
// get the node data for which the user clicked the button
var fromNode = adornment.adornedPart;
var fromData = fromNode.data;
// create ... | nment = obj.part;
var diagram = e.diagram;
diagram.startTransaction("Add State");
// get the node data for which the user clicked the button
var fromNode = adornment.adornedPart;
var fromData = fromNode.data;
// create a new "State" data object, positioned off to the rig... | identifier_body |
multisig.go | /*
User interface for Dero multisig wallet by thedudelebowski.
Version 1.0
Please note: This UI was written for the Dero Stargate testnet. Use at your own risk! The code could be simplified in some areas, and error handling may not be 100% complete.
Github link: https://github.com/lebowski1234/multisig-ui
*/
pack... | }
//Enter deposit amount, return value.
func getDepositAmount() (int64, bool) {
scanner := bufio.NewScanner(os.Stdin)
var amountString string
fmt.Print("Enter deposit amount in Dero: ")
scanner.Scan()
amountString = scanner.Text()
wmenu.Clear()
fmt.Printf("Do you want to deposit %s Dero? Enter Y/N (Yes/No)", ... | random_line_split | |
multisig.go | /*
User interface for Dero multisig wallet by thedudelebowski.
Version 1.0
Please note: This UI was written for the Dero Stargate testnet. Use at your own risk! The code could be simplified in some areas, and error handling may not be 100% complete.
Github link: https://github.com/lebowski1234/multisig-ui
*/
pack... |
}
return -1
}
// containsString returns true if slice contains element
func containsString(slice []string, element string) bool {
return !(posString(slice, element) == -1)
}
/*-----------------------------------------------------------RPC Functions--------------------------------------------------------------... | {
return index
} | conditional_block |
multisig.go | /*
User interface for Dero multisig wallet by thedudelebowski.
Version 1.0
Please note: This UI was written for the Dero Stargate testnet. Use at your own risk! The code could be simplified in some areas, and error handling may not be 100% complete.
Github link: https://github.com/lebowski1234/multisig-ui
*/
pack... |
/*-----------------------------------------------------------RPC Functions-----------------------------------------------------------------*/
//sendTransaction: send a transaction to the wallet or sign a transaction. entry should be "Send" or "Sign".
func sendTransaction(scid string, entry string, to string, ... | {
return !(posString(slice, element) == -1)
} | identifier_body |
multisig.go | /*
User interface for Dero multisig wallet by thedudelebowski.
Version 1.0
Please note: This UI was written for the Dero Stargate testnet. Use at your own risk! The code could be simplified in some areas, and error handling may not be 100% complete.
Github link: https://github.com/lebowski1234/multisig-ui
*/
pack... | (scid string, keys []string) string {
deamonURL:= "http://127.0.0.1:30306/gettransactions"
txHashes:= []string{scid}
data := PayloadKeys{
TxsHashes: txHashes,
ScKeys: keys,
}
payloadBytes, err := json.Marshal(data)
if err != nil {
println("Error in function getKeysFromDaemon:")
fmt.Println(err)
re... | getKeysFromDaemon | identifier_name |
local.rs | use super::{EntryType, ShrinkBehavior, GIGABYTES};
use std::collections::BinaryHeap;
use std::path::Path;
use std::sync::Arc;
use std::time::{self, Duration};
use bytes::Bytes;
use digest::{Digest as DigestTrait, FixedOutput};
use futures::future;
use hashing::{Digest, Fingerprint, EMPTY_DIGEST};
use lmdb::Error::Not... |
}).await
}
pub fn all_digests(&self, entry_type: EntryType) -> Result<Vec<Digest>, String> {
let database = match entry_type {
EntryType::File => self.inner.file_dbs.clone(),
EntryType::Directory => self.inner.directory_dbs.clone(),
};
let mut digests = vec![];
for &(ref env, ref d... | {
Err(format!("Got hash collision reading from store - digest {:?} was requested, but retrieved bytes with that fingerprint had length {}. Congratulations, you may have broken sha256! Underlying bytes: {:?}", digest, bytes.len(), bytes))
} | conditional_block |
local.rs | use super::{EntryType, ShrinkBehavior, GIGABYTES};
use std::collections::BinaryHeap;
use std::path::Path;
use std::sync::Arc;
use std::time::{self, Duration};
use bytes::Bytes;
use digest::{Digest as DigestTrait, FixedOutput};
use futures::future;
use hashing::{Digest, Fingerprint, EMPTY_DIGEST};
use lmdb::Error::Not... | .begin_rw_txn()
.and_then(|mut txn| {
let key = VersionedFingerprint::new(
aged_fingerprint.fingerprint,
ShardedLmdb::schema_version(),
);
txn.del(database, &key, None)?;
txn
.del(lease_database, &key, None)
... | env | random_line_split |
local.rs | use super::{EntryType, ShrinkBehavior, GIGABYTES};
use std::collections::BinaryHeap;
use std::path::Path;
use std::sync::Arc;
use std::time::{self, Duration};
use bytes::Bytes;
use digest::{Digest as DigestTrait, FixedOutput};
use futures::future;
use hashing::{Digest, Fingerprint, EMPTY_DIGEST};
use lmdb::Error::Not... | <T: Send + 'static, F: Fn(&[u8]) -> T + Send + Sync + 'static>(
&self,
entry_type: EntryType,
digest: Digest,
f: F,
) -> Result<Option<T>, String> {
if digest == EMPTY_DIGEST {
// Avoid I/O for this case. This allows some client-provided operations (like merging
// snapshots) to work w... | load_bytes_with | identifier_name |
runtime.rs | //#![allow(dead_code)]
use std::sync::{Arc};
use std::path::{PathBuf};
use cgmath::{Vector2, Point2};
use input::{Input, Button, Key, ButtonState, ButtonArgs};
use window::{Window, WindowSettings};
use slog::{Logger};
use calcium_flowy::FlowyRenderer;
use flowy::{Ui, Element};
use flowy::style::{Style, Position, Size... |
}
pub fn render(&mut self, batches: &mut Vec<RenderBatch<R>>) {
//let mut batches = Vec::new();
let mut normaltexture = RenderBatch::new(
ShaderMode::Texture(self.tex.clone()), UvMode::YDown
);
normaltexture.push_rectangle_full_texture(
// position is cen... | {
if pinput.w {self.position.y -= self.speed * delta;}
if pinput.a {self.position.x -= self.speed * delta;}
if pinput.s {self.position.y += self.speed * delta;}
if pinput.d {self.position.x += self.speed * delta;}
} | conditional_block |
runtime.rs | //#![allow(dead_code)]
use std::sync::{Arc};
use std::path::{PathBuf};
use cgmath::{Vector2, Point2};
use input::{Input, Button, Key, ButtonState, ButtonArgs};
use window::{Window, WindowSettings};
use slog::{Logger};
use calcium_flowy::FlowyRenderer;
use flowy::{Ui, Element};
use flowy::style::{Style, Position, Size... | (&mut self) -> Point2<f32> {
self.position
}
pub fn get_name(&mut self) -> &String {
&self.name
}
}
struct PlayerInput {
pub w: bool,
pub a: bool,
pub s: bool,
pub d: bool,
pub tab: bool,
}
pub struct StaticRuntime {
pub log: Logger,
}
impl Runtime for StaticRuntim... | get_position | identifier_name |
runtime.rs | //#![allow(dead_code)]
use std::sync::{Arc};
use std::path::{PathBuf};
use cgmath::{Vector2, Point2};
use input::{Input, Button, Key, ButtonState, ButtonArgs};
use window::{Window, WindowSettings};
use slog::{Logger};
use calcium_flowy::FlowyRenderer;
use flowy::{Ui, Element};
use flowy::style::{Style, Position, Size... | );
normaltexture.push_rectangle_full_texture(
// position is centered in the texture
Rectangle::new(self.position + -self.size/2.0, self.position + self.size/2.0)
);
batches.push(normaltexture);
if self.selected {
let mut selectiontexture = Re... | }
pub fn render(&mut self, batches: &mut Vec<RenderBatch<R>>) {
//let mut batches = Vec::new();
let mut normaltexture = RenderBatch::new(
ShaderMode::Texture(self.tex.clone()), UvMode::YDown | random_line_split |
runtime.rs | //#![allow(dead_code)]
use std::sync::{Arc};
use std::path::{PathBuf};
use cgmath::{Vector2, Point2};
use input::{Input, Button, Key, ButtonState, ButtonArgs};
use window::{Window, WindowSettings};
use slog::{Logger};
use calcium_flowy::FlowyRenderer;
use flowy::{Ui, Element};
use flowy::style::{Style, Position, Size... |
pub fn get_position(&mut self) -> Point2<f32> {
self.position
}
pub fn get_name(&mut self) -> &String {
&self.name
}
}
struct PlayerInput {
pub w: bool,
pub a: bool,
pub s: bool,
pub d: bool,
pub tab: bool,
}
pub struct StaticRuntime {
pub log: Logger,
}
impl ... | {
//let mut batches = Vec::new();
let mut normaltexture = RenderBatch::new(
ShaderMode::Texture(self.tex.clone()), UvMode::YDown
);
normaltexture.push_rectangle_full_texture(
// position is centered in the texture
Rectangle::new(self.position + -self.s... | identifier_body |
manager.py | # Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of so... |
stats = {}
for result in initial_results.results_by_name.values():
if result.type != ResultType.Skip:
stats[result.test_name] = {
'results': (_worker_number(result.worker_name),
result.test_number, result.pid,
... | return int(worker_name.split('/')[1]) if worker_name else -1 | identifier_body |
manager.py | # Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of so... | (self, tests_to_run, tests_to_skip):
# Don't show results in a new browser window because we're already
# printing the link to diffs in the loop
self._options.show_results = False
while True:
initial_results, all_retry_results = self._run_test_once(
tests_to_... | _run_test_loop | identifier_name |
manager.py | # Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of so... |
test_names += list(set(original_test_names) - set(test_names))
return test_names
def _collect_tests(self, args):
return self._finder.find_tests(
args,
test_lists=self._options.test_list,
filter_files=self._options.isolated_script_test_filter_file,
... | if test.startswith(path) or fnmatch.fnmatch(test, path):
test_names.append(test) | conditional_block |
manager.py | # Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of so... | exit_code = exit_codes.INTERRUPTED_EXIT_STATUS
else:
if initial_results.interrupted:
exit_code = exit_codes.EARLY_EXIT_STATUS
if (self._options.show_results
and (exit_code or initial_results.total_failures)):
... | self._copy_results_html_file(self._artifacts_directory,
'results.html')
if (initial_results.interrupt_reason is
test_run_results.InterruptReason.EXTERNAL_SIGNAL): | random_line_split |
decision_tree.py | from math import log
from collections import Counter
import copy
import csv
import carTreePlotter
import re
def calEntropy(dataSet):
"""
输入:二维数据集
输出:二维数据集标签的熵
描述:
计算数据集的标签的香农熵;香农熵越大,数据集越混乱;
在计算 splitinfo 和通过计算熵减选择信息增益最大的属性时可以用到
"""
entryNum = len(dataSet)
labelsCount... | print("正在用C4.5决策树计算验证集...", end='')
car_C45_Tree = loadTree('./output/car_C45_Tree/car_C45_Tree.txt')
car_C45_SetRes = classifierSet(carTestSet, carTestAttr, car_C45_Tree)
car_C45_accuracy = calAccuracy(carTestSet, car_C45_SetRes)
print("完成,准确率为 %f" % car_C45_accuracy)
print("正在用CART决策树计算... | random_line_split | |
decision_tree.py | from math import log
from collections import Counter
import copy
import csv
import carTreePlotter
import re
def calEntropy(dataSet):
"""
输入:二维数据集
输出:二维数据集标签的熵
描述:
计算数据集的标签的香农熵;香农熵越大,数据集越混乱;
在计算 splitinfo 和通过计算熵减选择信息增益最大的属性时可以用到
"""
entryNum = len(dataSet)
labelsCount... | float(labelsCount[key])/entryNum # propotion 特定标签占总标签比例
entropy -= propotion * log(propotion, 2)
return entropy
def calGini(dataSet):
"""
输入:二维数据集
输出:二维数据集的基尼系数
描述:计算数据集的基尼系数,基尼系数越大数据集越混乱
"""
entryNum = len(dataSet)
labelsCount = {}
for entry in dataSet:
... | :
propotion = | conditional_block |
decision_tree.py | from math import log
from collections import Counter
import copy
import csv
import carTreePlotter
import re
def calEntropy(dataSet):
"""
输入:二维数据集
输出:二维数据集标签的熵
描述:
计算数据集的标签的香农熵;香农熵越大,数据集越混乱;
在计算 splitinfo 和通过计算熵减选择信息增益最大的属性时可以用到
"""
entryNum = len(dataSet)
labelsCount... | tries) # 获得数据集二维列表
attr = ['attr' + str(i) for i in range(len(dataSet[0])-1)] # 获得属性向量
return dataSet, attr
def saveCarDataRes(path, carDataSetRes):
with open(path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(carDataSetRes)
def ca... | :
with open(path, 'r') as rf:
tree = eval(rf.read())
return tree
def loadCarDataSet(path):
with open(path, 'r') as csvfile:
entries = csv.reader(csvfile)
dataSet = list(en | identifier_body |
decision_tree.py | from math import log
from collections import Counter
import copy
import csv
import carTreePlotter
import re
def calEntropy(dataSet):
"""
输入:二维数据集
输出:二维数据集标签的熵
描述:
计算数据集的标签的香农熵;香农熵越大,数据集越混乱;
在计算 splitinfo 和通过计算熵减选择信息增益最大的属性时可以用到
"""
entryNum = len(dataSet)
labelsCount... | ART_Tree.txt', car_CART_Tree)
print("完成,保存为'./output/car_ID3_Tree/car_CART_Tree.txt'")
print("正在绘制CART决策树图像...", end='')
carTreePlotter.createPlot(car_CART_Tree, "./output/car_CART_Tree/car_CART_Tree.png")
print("完成,保存为'./output/car_CART_Tree/car_CART_Tree.png'")
def mainCalAccu():
car... | RT_Tree/car_C | identifier_name |
bitfinex.py | import base64
import hashlib
import hmac
import json
import re
import time
import datetime
import numpy as np
import pandas as pd
import pytz
import requests
import six
from catalyst.assets._assets import TradingPair
from logbook import Logger
from catalyst.exchange.exchange import Exchange
from catalyst.exchange.exc... |
def _get_v2_symbols(self, assets):
"""
Workaround to support Bitfinex v2
TODO: Might require a separate asset dictionary
:param assets:
:return:
"""
v2_symbols = []
for asset in assets:
v2_symbols.append(self._get_v2_symbol(asset))
... | pair = asset.symbol.split('_')
symbol = 't' + pair[0].upper() + pair[1].upper()
return symbol | identifier_body |
bitfinex.py | import base64
import hashlib
import hmac
import json
import re
import time
import datetime
import numpy as np
import pandas as pd
import pytz
import requests
import six
from catalyst.assets._assets import TradingPair
from logbook import Logger
from catalyst.exchange.exchange import Exchange
from catalyst.exchange.exc... | order_status = response.json()
except Exception as e:
raise ExchangeRequestError(error=e)
if 'message' in order_status:
raise ExchangeRequestError(
error='Unable to retrieve order status: {}'.format(
order_status['message'])
... | response = self._request(
'order/status', {'order_id': int(order_id)}) | random_line_split |
bitfinex.py | import base64
import hashlib
import hmac
import json
import re
import time
import datetime
import numpy as np
import pandas as pd
import pytz
import requests
import six
from catalyst.assets._assets import TradingPair
from logbook import Logger
from catalyst.exchange.exchange import Exchange
from catalyst.exchange.exc... |
if end_dt is not None:
end_ms = get_ms(end_dt)
url += '&end={0:f}'.format(end_ms)
else:
is_list = False
url += '/last'
try:
self.ask_request()
response = requests.get(url)
... | start_ms = get_ms(start_dt)
url += '&start={0:f}'.format(start_ms) | conditional_block |
bitfinex.py | import base64
import hashlib
import hmac
import json
import re
import time
import datetime
import numpy as np
import pandas as pd
import pytz
import requests
import six
from catalyst.assets._assets import TradingPair
from logbook import Logger
from catalyst.exchange.exchange import Exchange
from catalyst.exchange.exc... | (self):
# TODO: fetch account data and keep in cache
return None
def get_candles(self, data_frequency, assets, bar_count=None,
start_dt=None, end_dt=None):
"""
Retrieve OHLVC candles from Bitfinex
:param data_frequency:
:param assets:
:pa... | get_account | identifier_name |
compile.py | #!/usr/bin/env python3
import argparse
import json
import sys
warn = None
def unpack_brackets(s):
pairs = ["<>", "[]", "()"]
if len(s) < 2:
return None, s
for a, b in pairs:
if s[0] == a and s[-1] == b:
return a, s[1:-1]
return None, s
def parse_inner_arg(arg, ret):
i... | split_on_space = False
continue
if split_on_space and c.isspace():
if gather:
tokens.append(gather)
gather = ''
else:
gather += c
if gather:
tokens.append(gather)
if expectstack:
warn('unbalanced brackets... | if c in expectmap:
expectstack.append(expectmap[c])
if expectstack and c == expectstack[-1]:
expectstack.pop()
if c == ':' and not expectstack: | random_line_split |
compile.py | #!/usr/bin/env python3
import argparse
import json
import sys
warn = None
def unpack_brackets(s):
pairs = ["<>", "[]", "()"]
if len(s) < 2:
return None, s
for a, b in pairs:
if s[0] == a and s[-1] == b:
return a, s[1:-1]
return None, s
def parse_inner_arg(arg, ret):
i... |
# names should be [a-z][0-9] and - only
if not all(c.isalpha() or c.isdigit() or c == '-' for c in name):
warn('name has invalid characters: {}'.format(name))
return name
def check_verb(verb):
if not verb.upper() == verb: # verbs should be upper case
warn('verb not upcased: {}'.format(... | warn('name has whitespace: {}'.format(name)) | conditional_block |
compile.py | #!/usr/bin/env python3
import argparse
import json
import sys
warn = None
def unpack_brackets(s):
pairs = ["<>", "[]", "()"]
if len(s) < 2:
return None, s
for a, b in pairs:
if s[0] == a and s[-1] == b:
return a, s[1:-1]
return None, s
def parse_inner_arg(arg, ret):
i... | (fmt, data):
data['format'] = fmt
# do our own tokenizing, to force balanced parens but handle : outside
tokens = []
expectstack = []
expectmap = {'(': ')', '[': ']', '<': '>'}
gather = ''
split_on_space = True
for c in fmt:
if c in expectmap:
expectstack.append(expe... | parse_format | identifier_name |
compile.py | #!/usr/bin/env python3
import argparse
import json
import sys
warn = None
def unpack_brackets(s):
pairs = ["<>", "[]", "()"]
if len(s) < 2:
return None, s
for a, b in pairs:
if s[0] == a and s[-1] == b:
return a, s[1:-1]
return None, s
def parse_inner_arg(arg, ret):
i... |
def check_name(name):
name = name.strip()
if not name: # names should have length
warn('zero-length name')
if name.lower() != name: # names should be lower-case
warn('name not lowcased: {}'.format(name))
if len(name.split()) > 1: # names should have no whitespace
warn('name has... | b, arg = unpack_brackets(arg_orig)
ret = {}
if not b:
# literal
return (['left', 'right'], {'type': 'literal', 'type-argument': arg})
elif b == '<':
typ = parse_inner_arg(arg, ret)
ret.update(typ)
return (['left', 'right'], ret)
elif b == '[':
ret['type'] ... | identifier_body |
splayTree.py | #!/usr/bin/python
"""
Implementation of a splay tree. Splay trees are binary search trees which are
"splayed" around the most recently-accessed node, an operation that raises it to
the root. Frequently-accessed nodes rise to the top of the tree over time, and
the specific splay algorithm also ensures that they bri... |
p.right = l
# move parent down + left
p.parent = self
self.left = p
# move this node up + left
self.parent = g
if g is not None:
if p is g.left:
g.left = self
elif p is g.right:
g.right = self
... | l.parent = p | conditional_block |
splayTree.py | #!/usr/bin/python
"""
Implementation of a splay tree. Splay trees are binary search trees which are
"splayed" around the most recently-accessed node, an operation that raises it to
the root. Frequently-accessed nodes rise to the top of the tree over time, and
the specific splay algorithm also ensures that they bri... |
def delete(self, value):
"""deletes value if found in tree"""
if self.root is not None: # else do nothing
if type(value) == self.typing: # else do nothing
hasValue, self.root = self.root.contains(value)
if hasValue: # always deletes root
... | """inserts value into tree. sets type if this hasn't been done yet."""
if self.typing is None: # first insertion: set type of this tree
self.typing = type(value)
else: # perform type check
if type(value) != self.typing:
raise TypeError("Type " + str(type(value))... | identifier_body |
splayTree.py | #!/usr/bin/python
"""
Implementation of a splay tree. Splay trees are binary search trees which are
"splayed" around the most recently-accessed node, an operation that raises it to
the root. Frequently-accessed nodes rise to the top of the tree over time, and
the specific splay algorithm also ensures that they bri... | Inserts a new node with the specified value into the tree, which is then
splayed around it.
O(n), amortized O(log n).
"""
insertion_point = self._find(value)
n = SplayNode(value)
# value already in the tree; add at leftmost position in right subtreepa
if... | def insert(self, value):
""" | random_line_split |
splayTree.py | #!/usr/bin/python
"""
Implementation of a splay tree. Splay trees are binary search trees which are
"splayed" around the most recently-accessed node, an operation that raises it to
the root. Frequently-accessed nodes rise to the top of the tree over time, and
the specific splay algorithm also ensures that they bri... | (self, value):
"""
Searches for the specified value. If found, splays the tree around it;
removes it from the tree; finds its immediate predecessor; splays the
left subtree around that node; and attaches it to the right subtree. If
not found, splays the tree around its neare... | delete | identifier_name |
catalog.py | #!/usr/bin/env python2
#
# Catalog App
from flask import Flask, render_template, url_for, request, redirect
from flask import flash, session as login_session, make_response, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Item, User
import... | (item):
delItem = session.query(Item).filter_by(name=item).one_or_none()
if delItem is not None:
creator = getUserInfo(delItem.user_id)
if 'username' in login_session:
if creator.id == login_session[user_id]:
if request.method == 'POST':
session.de... | deleteItem | identifier_name |
catalog.py | #!/usr/bin/env python2
#
# Catalog App
from flask import Flask, render_template, url_for, request, redirect
from flask import flash, session as login_session, make_response, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Item, User
import... | return response
access_token = credentials.access_token
url = ('https://www.googleapis.com/oauth2/v1/'
'tokeninfo?access_token=%s' % access_token)
h = httplib2.Http()
result = json.loads(h.request(url, 'GET')[1])
if result.get('error') is not None:
response = make_response... | except FlowExchangeError:
response = make_response(json.dumps(
'Failed to upgrade the authorization code'), 401)
response.headers['Content-Type'] = 'application/json' | random_line_split |
catalog.py | #!/usr/bin/env python2
#
# Catalog App
from flask import Flask, render_template, url_for, request, redirect
from flask import flash, session as login_session, make_response, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Item, User
import... |
# function to retrieve User from user ID
def getUserInfo(user_id):
user = session.query(User).filter_by(id=user_id).one()
return user
# create new User in database
def createUser(login_session):
newUser = User(
name=login_session['username'],
email=login_session['email'])
session.ad... | try:
user = session.query(User).filter_by(email=email).one()
return user.id
except:
return None | identifier_body |
catalog.py | #!/usr/bin/env python2
#
# Catalog App
from flask import Flask, render_template, url_for, request, redirect
from flask import flash, session as login_session, make_response, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Item, User
import... |
return render_template(
'catalog.html',
categories=categories,
items=items,
STATE=state)
# single category listing - all items in category
@app.route('/catalog/<category>/')
def showCategory(category):
cat = session.query(Category).filter_by(name=category).one_or_none()
if... | return render_template(
'publiccatalog.html',
categories=categories,
items=items, STATE=state) | conditional_block |
consumer.go | package cluster
import (
"sync"
"time"
"github.com/Shopify/sarama"
"github.com/samuel/go-zookeeper/zk"
"gopkg.in/tomb.v2"
)
// Config contains the consumer configuration options
type Config struct {
// Config contains the standard consumer configuration
*sarama.Config
// IDPrefix allows to force custom pref... |
// Fetch all partitions for a topic
func (c *Consumer) partitions() (PartitionSlice, error) {
ids, err := c.client.Partitions(c.topic)
if err != nil {
return nil, err
}
slice := make(PartitionSlice, len(ids))
for n, id := range ids {
broker, err := c.client.Leader(c.topic, id)
if err != nil {
return ni... | {
if err := c.zoo.RegisterGroup(c.group, c.topic); err != nil {
return err
}
if err := c.zoo.RegisterConsumer(c.group, c.id, c.topic); err != nil {
return err
}
return nil
} | identifier_body |
consumer.go | package cluster
import (
"sync"
"time"
"github.com/Shopify/sarama"
"github.com/samuel/go-zookeeper/zk"
"gopkg.in/tomb.v2"
)
// Config contains the consumer configuration options
type Config struct {
// Config contains the standard consumer configuration
*sarama.Config
// IDPrefix allows to force custom pref... | () string { return c.group }
// Topic exposes the group topic
func (c *Consumer) Topic() string { return c.topic }
// Offset manually retrives the stored offset for a partition ID
func (c *Consumer) Offset(partitionID int32) (int64, error) {
return c.zoo.Offset(c.group, c.topic, partitionID)
}
// Ack marks a consum... | Group | identifier_name |
consumer.go | package cluster
import (
"sync"
"time"
"github.com/Shopify/sarama"
"github.com/samuel/go-zookeeper/zk"
"gopkg.in/tomb.v2"
)
// Config contains the consumer configuration options
type Config struct {
// Config contains the standard consumer configuration
*sarama.Config
// IDPrefix allows to force custom pref... |
select {
case c.errors <- msg:
// fmt.Printf("!,%s,%d,%s\n", c.id, msg.Partition, msg.Error())
case <-done:
// fmt.Printf("@,%s\n", c.id)
return
}
case <-done:
// fmt.Printf("@,%s\n", c.id)
return
}
}
}
// PRIVATE
// Shutdown the consumer, triggered by the main loop
func (c *Consu... | {
offset, err := c.client.GetOffset(c.topic, msg.Partition, sarama.EarliestOffset)
if err == nil {
c.rLock.Lock()
c.read[msg.Partition] = offset
c.rLock.Unlock()
}
errs <- struct{}{}
} | conditional_block |
consumer.go | package cluster
import (
"sync"
"time"
"github.com/Shopify/sarama"
"github.com/samuel/go-zookeeper/zk"
"gopkg.in/tomb.v2"
)
// Config contains the consumer configuration options
type Config struct {
// Config contains the standard consumer configuration
*sarama.Config
// IDPrefix allows to force custom pref... | c.read[msg.Partition] = offset
c.rLock.Unlock()
}
errs <- struct{}{}
}
select {
case c.errors <- msg:
// fmt.Printf("!,%s,%d,%s\n", c.id, msg.Partition, msg.Error())
case <-done:
// fmt.Printf("@,%s\n", c.id)
return
}
case <-done:
// fmt.Printf("@,%s\n", c.id)
retur... | if err == nil {
c.rLock.Lock() | random_line_split |
meetingPlanner.py | import datetime
#Defining a graph type class for my dates
#basically the user will enter people and the dates that they cannot make it
#then, we will create a graph with all the dates of absences
#if there are as many absences as dates in the range, then we will choose the dates with the least people absent
#otherwise... |
#adding a user that is completely absent
def addAbsentUser(self,user):
self.completelyAbsent.add(user)
#adding a user that is completely present
def addPresentUser(self,user):
self.completelyPresent.add(user)
#getting all the users that are absent on a specific date
... | dataToConsider = self.dates[timedate]
dataToConsider.usersAbsent.add(user)
dataToConsider.degree=len(dataToConsider.usersAbsent) | identifier_body |
meetingPlanner.py | import datetime
#Defining a graph type class for my dates
#basically the user will enter people and the dates that they cannot make it
#then, we will create a graph with all the dates of absences
#if there are as many absences as dates in the range, then we will choose the dates with the least people absent
#otherwise... |
#now we find the list of the best dates and print them
#we first print the list of all the users
print("Users associated with this event: \n")
for x in users:
print(x+"\n")
#now i print the output of the best dates
graph.printBestDates()
#running my main
if (__name__=="__main__"):
... | dates=None
if (userSelectedDate):
dates=input("Please enter an individual date in the form mm/dd/yyyy or a range in the form mm/dd/yyyy:mm/dd/yyyy, or - if you wish to stop entering dates.")
else:
dates=input("Please enter either ALL ABSENT, ALL PRESENT, a date r... | conditional_block |
meetingPlanner.py | import datetime
#Defining a graph type class for my dates
#basically the user will enter people and the dates that they cannot make it
#then, we will create a graph with all the dates of absences
#if there are as many absences as dates in the range, then we will choose the dates with the least people absent
#otherwise... | (self,timedate):
absentees=[]
for x in self.dates[timedate].usersAbsent:
absentees.append(x)
for x in self.completelyAbsent:
absentees.append(x)
return absentees
#counts the degree of a node
def countDegree(self,timedate):
#count the degree here
... | getAbsentUsers | identifier_name |
meetingPlanner.py | import datetime
#Defining a graph type class for my dates
#basically the user will enter people and the dates that they cannot make it
#then, we will create a graph with all the dates of absences
#if there are as many absences as dates in the range, then we will choose the dates with the least people absent
#otherwise... | print("\n")
print("------------------------------------------------------\n")
#some functions to help with date stuff
#gets all the dates in the given range (returns a list of datetimes)
def getDateRange(begDate,endDate):
testDate=datetime.date(begDate.year,begDate.month,be... | if (y!=len(listAbsent)-1):
print(" "+y+",")
else:
print(" "+y)
| random_line_split |
supervisor.go | package gen
import (
"fmt"
"time"
"github.com/ergo-services/ergo/etf"
"github.com/ergo-services/ergo/lib"
)
// SupervisorBehavior interface
type SupervisorBehavior interface {
ProcessBehavior
Init(args ...etf.Term) (SupervisorSpec, error)
}
// SupervisorStrategy
type SupervisorStrategy struct {
Type Sup... | (supervisor Process, spec *SupervisorSpec, message interface{}) (interface{}, error) {
switch m := message.(type) {
case MessageDirectChildren:
children := []etf.Pid{}
for i := range spec.Children {
if spec.Children[i].process == nil {
continue
}
children = append(children, spec.Children[i].process.S... | handleDirect | identifier_name |
supervisor.go | package gen
import (
"fmt"
"time"
"github.com/ergo-services/ergo/etf"
"github.com/ergo-services/ergo/lib"
)
// SupervisorBehavior interface
type SupervisorBehavior interface {
ProcessBehavior
Init(args ...etf.Term) (SupervisorSpec, error)
}
// SupervisorStrategy
type SupervisorStrategy struct {
Type Sup... | {
for i := range spec {
if spec[i].Name == specName {
return spec[i], nil
}
}
return SupervisorChildSpec{}, fmt.Errorf("unknown child")
} | identifier_body | |
supervisor.go | package gen
import (
"fmt"
"time"
"github.com/ergo-services/ergo/etf"
"github.com/ergo-services/ergo/lib"
)
// SupervisorBehavior interface
type SupervisorBehavior interface {
ProcessBehavior
Init(args ...etf.Term) (SupervisorSpec, error)
}
// SupervisorStrategy
type SupervisorStrategy struct {
Type Sup... |
if child.Self() == terminated {
if haveToDisableChild(spec.Strategy.Restart, reason) {
// wont be restarted due to restart strategy
spec.Children[i] = spec.Children[0]
spec.Children = spec.Children[1:]
break
}
process := startChild(p, spec.Children[i].Name, spec.Children[i].Child, ... | {
continue
} | conditional_block |
supervisor.go | package gen
import (
"fmt"
"time"
"github.com/ergo-services/ergo/etf"
"github.com/ergo-services/ergo/lib"
)
// SupervisorBehavior interface
type SupervisorBehavior interface {
ProcessBehavior
Init(args ...etf.Term) (SupervisorSpec, error)
}
// SupervisorStrategy
type SupervisorStrategy struct {
Type Sup... | return process, nil
}
func startChildren(supervisor Process, spec *SupervisorSpec) {
spec.restarts = append(spec.restarts, time.Now().Unix())
if len(spec.restarts) > int(spec.Strategy.Intensity) {
period := time.Now().Unix() - spec.restarts[0]
if period <= int64(spec.Strategy.Period) {
lib.Warning("Superviso... | return nil, fmt.Errorf("internal error: can't start child %#v", value)
} | random_line_split |
array.rs | /*
#![feature(collections_range)]
#![feature(drain_filter)]
#![feature(slice_rsplit)]
#![feature(slice_get_slice)]
#![feature(vec_resize_default)]
#![feature(vec_remove_item)]
#![feature(collections_range)]
#![feature(slice_rotate)]
#![feature(swap_with_slice)]
*/
foo bar baz
use collections::range::RangeArgument;
us... | {
self.0.splice(range,replace_with)
}
pub fn drain_filter<F:FnMut(&mut T)->bool>(&mut self, filter: F) -> DrainFilter<T, F> {
self.0.drain_filter(filter)
}
}
impl<T,INDEX:IndexTrait> Deref for Array<T,INDEX>{
type Target=[T];
fn deref(&self)->&Self::Target { self.0.deref() }
}
impl<T,INDEX:IndexTrait> Array... |
impl<T,INDEX:IndexTrait> Array<T,INDEX>{
/// TODO - figure out how to convert RangeArguemnt indices
pub fn splice<I:IntoIterator<Item=T>,R:RangeArgument<usize>>(&mut self, range:R, replace_with:I)-> Splice<<I as IntoIterator>::IntoIter> | random_line_split |
array.rs | /*
#![feature(collections_range)]
#![feature(drain_filter)]
#![feature(slice_rsplit)]
#![feature(slice_get_slice)]
#![feature(vec_resize_default)]
#![feature(vec_remove_item)]
#![feature(collections_range)]
#![feature(slice_rotate)]
#![feature(swap_with_slice)]
*/
foo bar baz
use collections::range::RangeArgument;
us... | (&self)->*const T{self.0.as_ptr()}
fn as_mut_ptr(&mut self)->*mut T{self.0.as_mut_ptr()}
fn swap(&mut self, a:INDEX,b:INDEX){
self.0.swap(a.my_into(),b.my_into())
}
fn reverse(&mut self){self.0.reverse()}
fn iter(&self)->Iter<T>{self.0.iter()}
fn iter_mut(&mut self)->IterMut<T>{self.0.iter_mut()}
fn windows(&s... | as_ptr | identifier_name |
array.rs | /*
#![feature(collections_range)]
#![feature(drain_filter)]
#![feature(slice_rsplit)]
#![feature(slice_get_slice)]
#![feature(vec_resize_default)]
#![feature(vec_remove_item)]
#![feature(collections_range)]
#![feature(slice_rotate)]
#![feature(swap_with_slice)]
*/
foo bar baz
use collections::range::RangeArgument;
us... |
pub fn as_slice(&self) -> &[T]{
self.0.as_slice()
}
pub fn as_mut_slice(&mut self) -> &mut [T]{
self.0.as_mut_slice()
}
pub fn swap_remove(&mut self, index: I) -> T{
self.0.swap_remove(index.my_into())
}
pub fn insert(&mut self, index: I, element: T){
self.0.insert(index.my_into(),element)
}
pub fn re... | {
self.0.truncate(len.my_into());
} | identifier_body |
codemap.rs | use std::cell::RefCell;
use std::cmp;
use std::env;
use std::{fmt, fs};
use std::io::{self, Read};
use std::ops::{Add, Sub};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use ast::Name;
pub trait Pos {
fn from_usize(n: usize) -> Self;
fn to_usize(&self) -> usize;
}
/// A byte offset. Keep this small (currentl... |
let end_pos = start_pos + src.len();
let filemap = Rc::new(FileMap {
name: filename,
abs_path: abs_path,
src: Some(Rc::new(src)),
start_pos: Pos::from_usize(start_pos),
end_pos: Pos::from_usize(end_pos),
lines: RefCell::new(Vec::new()),
multibyte_chars: RefCell::new(... | {
src.drain(..3);
} | conditional_block |
codemap.rs | use std::cell::RefCell;
use std::cmp;
use std::env;
use std::{fmt, fs};
use std::io::{self, Read};
use std::ops::{Add, Sub};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use ast::Name;
pub trait Pos {
fn from_usize(n: usize) -> Self;
fn to_usize(&self) -> usize;
}
/// A byte offset. Keep this small (currentl... | /// The absolute path of the file that the source came from.
pub abs_path: Option<FileName>,
/// The complete source code
pub src: Option<Rc<String>>,
/// The start position of this source in the CodeMap
pub start_pos: BytePos,
/// The end position of this source in the CodeMap
pub end_pos: BytePos,
/... | /// originate from files has names between angle brackets by convention,
/// e.g. `<anon>`
pub name: FileName, | random_line_split |
codemap.rs | use std::cell::RefCell;
use std::cmp;
use std::env;
use std::{fmt, fs};
use std::io::{self, Read};
use std::ops::{Add, Sub};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use ast::Name;
pub trait Pos {
fn from_usize(n: usize) -> Self;
fn to_usize(&self) -> usize;
}
/// A byte offset. Keep this small (currentl... | (self, other: Span) -> Option<Span> {
if self.hi > other.hi {
Some(Span { lo: cmp::max(self.lo, other.hi), .. self })
} else {
None
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy)]
pub struct Spanned<T> {
pub node: T,
pub span: Span,
}
/// A collection of spans. Spans have two or... | trim_start | identifier_name |
lstm.py | '''
Created on 18-Nov-2019
@author: 91984
'''
import pandas as pd
import numpy as np
import sys
# from datetime import datetime
import statsmodels.api as sm
import matplotlib.pylab as plt
from audioop import rms
# df = pd.read_csv('C:\\Users\\91984\\Desktop\\shampoo.csv')
from datetime import datetime
fr... |
valX, valY = get_val()
# create and fit the LSTM network
from pandas import DataFrame
train1 = DataFrame()
val1 = DataFrame()
# for i in range(5):
model = Sequential()
model.add(LSTM(units=300, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(LSTM(units=25... | X1, y1 = [], []
print(train_size + 6)
print(len(df))
for i in range(train_size + 6, len(df)):
X1.append(scaled_data[i - 6:i, 0])
y1.append(scaled_data[i, 0])
X1, y1 = np.array(X1), np.array(y1)
print(X1)
print(len(X1))
X1 = np.r... | identifier_body |
lstm.py | '''
Created on 18-Nov-2019
@author: 91984
'''
import pandas as pd
import numpy as np
import sys
# from datetime import datetime
import statsmodels.api as sm
import matplotlib.pylab as plt
from audioop import rms
# df = pd.read_csv('C:\\Users\\91984\\Desktop\\shampoo.csv')
from datetime import datetime
fr... |
X1, y1 = np.array(X1), np.array(y1)
print(X1)
print(len(X1))
X1 = np.reshape(X1, (X1.shape[0], X1.shape[1], 1))
return X1, y1
X2, y2 = get_train()
print(X2)
print(y2)
valX, valY = get_val()
print(valX)
print(valY)
| X1.append(scaled_data[i - 6:i, 0])
y1.append(scaled_data[i, 0]) | conditional_block |
lstm.py | '''
Created on 18-Nov-2019
@author: 91984
'''
import pandas as pd
import numpy as np
import sys
# from datetime import datetime
import statsmodels.api as sm
import matplotlib.pylab as plt
from audioop import rms
# df = pd.read_csv('C:\\Users\\91984\\Desktop\\shampoo.csv')
from datetime import datetime
fr... | ():
X1, y1 = list(), list()
for i in range(6, len(train)):
X1.append(scaled_data[i - 6:i, 0])
y1.append(scaled_data[i, 0])
X1, y1 = np.array(X1), np.array(y1)
print(X1)
print(len(X1))
X1 = np.reshape(X1, (X1.shape[0], X1.shape[1], 1))
return X1, y1
# return... | get_train | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.