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 |
|---|---|---|---|---|
leaderboard.go | // Copyright (c) 2015, Sgt. Kabukiman | MIT licensed
package srapi
import (
"net/url"
"strconv"
)
// Leaderboard represents a leaderboard, i.e. a collection of ranked runs for a
// certain configuration of game, category, level and a few others.
type Leaderboard struct {
// a link to the leaderboard on speedrun.c... | return toLevel(lb.LevelData, true), nil
}
// Platforms returns a list of all platforms that are used in the leaderboard.
// If they have not been embedded, an empty collection is returned.
func (lb *Leaderboard) Platforms() *PlatformCollection {
return toPlatformCollection(lb.PlatformsData)
}
// Regions returns a l... | }
| random_line_split |
leaderboard.go | // Copyright (c) 2015, Sgt. Kabukiman | MIT licensed
package srapi
import (
"net/url"
"strconv"
)
// Leaderboard represents a leaderboard, i.e. a collection of ranked runs for a
// certain configuration of game, category, level and a few others.
type Leaderboard struct {
// a link to the leaderboard on speedrun.c... |
return fetchLeaderboard(request{"GET", "/leaderboards/" + game.ID + "/category/" + cat.ID, options, nil, nil, embeds})
}
// LevelLeaderboard retrieves a the leaderboard for a specific game and one of
// its levels in a specific category. An error is returned if no category or
// level is given or if a full-game cat... | {
var err *Error
game, err = cat.Game("")
if err != nil {
return nil, err
}
} | conditional_block |
leaderboard.go | // Copyright (c) 2015, Sgt. Kabukiman | MIT licensed
package srapi
import (
"net/url"
"strconv"
)
// Leaderboard represents a leaderboard, i.e. a collection of ranked runs for a
// certain configuration of game, category, level and a few others.
type Leaderboard struct {
// a link to the leaderboard on speedrun.c... |
// Level returns the level that the leaderboard is for. If it's a full-game
// leaderboard, nil is returned. If the level was not embedded, it is fetched
// from the network.
func (lb *Leaderboard) Level(embeds string) (*Level, *Error) {
if lb.LevelData == nil {
return nil, nil
}
// we only have the level ID at... | {
// we only have the category ID at hand
asserted, okay := lb.CategoryData.(string)
if okay {
return CategoryByID(asserted, embeds)
}
return toCategory(lb.CategoryData, true), nil
} | identifier_body |
leaderboard.go | // Copyright (c) 2015, Sgt. Kabukiman | MIT licensed
package srapi
import (
"net/url"
"strconv"
)
// Leaderboard represents a leaderboard, i.e. a collection of ranked runs for a
// certain configuration of game, category, level and a few others.
type Leaderboard struct {
// a link to the leaderboard on speedrun.c... | () *VariableCollection {
return toVariableCollection(lb.VariablesData)
}
// Players returns a list of all players that are present in the leaderboard.
// If they have not been embedded, an empty slice is returned.
func (lb *Leaderboard) Players() *PlayerCollection {
return toPlayerCollection(lb.PlayersData)
}
// fo... | Variables | identifier_name |
cyclone.go | /*-
* Copyright © 2016-2017, Jörg Pernfuß <code.jpe@gmail.com>
* Copyright © 2016, 1&1 Internet SE
* All rights reserved.
*
* Use of this source code is governed by a 2-clause BSD license
* that can be found in the LICENSE file.
*/
package cyclone // import "github.com/mjolnir42/cyclone/lib/cyclone"
import (
... |
runloop:
for {
select {
case <-c.Shutdown:
// received shutdown, drain input channel which will be
// closed by main
goto drainloop
case msg := <-c.Input:
if msg == nil {
// this can happen if we read the closed Input channel
// before the closed Shutdown channel
continue runloop
}
... | ) { | identifier_name |
cyclone.go | /*-
* Copyright © 2016-2017, Jörg Pernfuß <code.jpe@gmail.com>
* Copyright © 2016, 1&1 Internet SE
* All rights reserved.
*
* Use of this source code is governed by a 2-clause BSD license
* that can be found in the LICENSE file.
*/
package cyclone // import "github.com/mjolnir42/cyclone/lib/cyclone"
import (
... | m.Update(m)
m = mm.Calculate()
c.MemData[id] = mm
case `/sys/disk/blk_total`:
fallthrough
case `/sys/disk/blk_used`:
fallthrough
case `/sys/disk/blk_read`:
fallthrough
case `/sys/disk/blk_wrtn`:
if len(m.Tags) == 0 {
m = nil
break
}
d := disk.Disk{}
id := m.AssetID
mpt := m.Tags[0]
if c... | mm = c.MemData[id]
}
m | conditional_block |
cyclone.go | /*-
* Copyright © 2016-2017, Jörg Pernfuß <code.jpe@gmail.com>
* Copyright © 2016, 1&1 Internet SE
* All rights reserved.
*
* Use of this source code is governed by a 2-clause BSD license
* that can be found in the LICENSE file.
*/
package cyclone // import "github.com/mjolnir42/cyclone/lib/cyclone"
import (
... | process evaluates a metric and raises alarms as required
func (c *Cyclone) process(msg *erebos.Transport) error {
if msg == nil || msg.Value == nil {
logrus.Warnf("Ignoring empty message from: %d", msg.HostID)
if msg != nil {
go c.commit(msg)
}
return nil
}
m := &legacy.MetricSplit{}
if err := json.Unm... | unloop:
for {
select {
case <-c.Shutdown:
// received shutdown, drain input channel which will be
// closed by main
goto drainloop
case msg := <-c.Input:
if msg == nil {
// this can happen if we read the closed Input channel
// before the closed Shutdown channel
continue runloop
}
i... | identifier_body |
cyclone.go | /*-
* Copyright © 2016-2017, Jörg Pernfuß <code.jpe@gmail.com>
* Copyright © 2016, 1&1 Internet SE
* All rights reserved.
*
* Use of this source code is governed by a 2-clause BSD license
* that can be found in the LICENSE file.
*/
package cyclone // import "github.com/mjolnir42/cyclone/lib/cyclone"
import (
... | CTXData map[int64]cpu.CTX
DskData map[int64]map[string]disk.Disk
redis *redis.Client
internalInput chan *legacy.MetricSplit
}
// AlarmEvent is the datatype for sending out alarm notifications
type AlarmEvent struct {
Source string `json:"source"`
EventID string `json:"event_id"`
Versi... | random_line_split | |
server.rs | use std::io::IoResult;
use crypto::sha1::Sha1;
use crypto::digest::Digest;
use serialize::base64::{ToBase64, STANDARD};
use std::ascii::AsciiExt;
use time;
use std::io::{Listener, Acceptor};
use std::io::net::tcp::TcpListener;
use std::io::net::tcp::TcpStream;
use http::buffer::BufferedStream;
use std::thread::Thread... |
// check if the http request is a web socket upgrade request, and return true if so.
// otherwise, fall back on the regular http request handler
fn handle_possible_ws_request(&self, r: Request, w: &mut ResponseWriter) -> bool {
// TODO allow configuration of endpoint for websocket
match (r... | {
// NOTE from RFC 6455
//
// To prove that the handshake was received, the server has to take two
// pieces of information and combine them to form a response. The first
// piece of information comes from the |Sec-WebSocket-Key| header field
// in the client handshake:
... | identifier_body |
server.rs | use std::io::IoResult;
use crypto::sha1::Sha1;
use crypto::digest::Digest;
use serialize::base64::{ToBase64, STANDARD};
use std::ascii::AsciiExt;
use time;
use std::io::{Listener, Acceptor};
use std::io::net::tcp::TcpListener;
use std::io::net::tcp::TcpStream; | use http::server::{Server, Request, ResponseWriter};
use http::status::SwitchingProtocols;
use http::headers::HeaderEnum;
use http::headers::response::Header::ExtensionHeader;
use http::headers::connection::Connection::Token;
use http::method::Method::Get;
pub use message::Payload::{Text, Binary, Empty};
pub use messa... | use http::buffer::BufferedStream;
use std::thread::Thread;
use std::sync::mpsc::{channel, Sender, Receiver};
| random_line_split |
server.rs | use std::io::IoResult;
use crypto::sha1::Sha1;
use crypto::digest::Digest;
use serialize::base64::{ToBase64, STANDARD};
use std::ascii::AsciiExt;
use time;
use std::io::{Listener, Acceptor};
use std::io::net::tcp::TcpListener;
use std::io::net::tcp::TcpStream;
use http::buffer::BufferedStream;
use std::thread::Thread... | (&self, r: Request, w: &mut ResponseWriter) -> bool {
// TODO allow configuration of endpoint for websocket
match (r.method.clone(), r.headers.upgrade.clone()){
// (&Get, &Some("websocket"), &Some(box [Token(box "Upgrade")])) => //\{ FIXME this doesn't work. but client must have the header "... | handle_possible_ws_request | identifier_name |
site.js | //Alert variables
const alertMessage = document.getElementById("alert-message");
let alertMessageText = "<p><strong>Alert: </strong>Here is the medium length sentence long alert popup up purple bar.</p><i class='alert-clear fa fa-times'></i>";
const alertText = document.getElementsByClassName("alert-text");
const clear... |
});
}
}
function toggleOff(i){
toggleButton[i].style.transform = "translateX(-43px)";
toggleButton[i].style.transition = ".25s";
toggleText[i].textContent = "Off";
toggleText[i].style.transform = "translateX(25px)";
toggleText[i].style.transition = ".25s";
toggleContainer[i].style.backgroundColor = ... | {
toggleOn(i);
localStorage.setItem('toggle' + i, 'on');
} | conditional_block |
site.js | //Alert variables
const alertMessage = document.getElementById("alert-message");
let alertMessageText = "<p><strong>Alert: </strong>Here is the medium length sentence long alert popup up purple bar.</p><i class='alert-clear fa fa-times'></i>";
const alertText = document.getElementsByClassName("alert-text");
const clear... | (i){
toggleButton[i].style.transform = "translateX(0)";
toggleButton[i].style.transition = ".25s";
toggleText[i].textContent = "On";
toggleText[i].style.transform = "translateX(0)";
toggleText[i].style.transition = ".25s";
toggleContainer[i].style.backgroundColor = "#7377bf";
toggleContainer[i].style.tran... | toggleOn | identifier_name |
site.js | //Alert variables
const alertMessage = document.getElementById("alert-message");
let alertMessageText = "<p><strong>Alert: </strong>Here is the medium length sentence long alert popup up purple bar.</p><i class='alert-clear fa fa-times'></i>";
const alertText = document.getElementsByClassName("alert-text");
const clear... | // var result = instantiatePage();
// var t1 = performance.now();
// console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to generate:', result);
instantiatePage();
//Instantiate listeners, constructors
function instantiatePage(){
document.addEventListener("DOMContentLoaded", () => {
displayAlert(alertMessag... | ///////////////////////////////
//File performance
// var t0 = performance.now(); | random_line_split |
site.js | //Alert variables
const alertMessage = document.getElementById("alert-message");
let alertMessageText = "<p><strong>Alert: </strong>Here is the medium length sentence long alert popup up purple bar.</p><i class='alert-clear fa fa-times'></i>";
const alertText = document.getElementsByClassName("alert-text");
const clear... |
function globalKeyListener(){
search.addEventListener("keyup", (e) => {
if(!search.value){
count = -1;
}
//if user has typed and there are results
if(search.value && searchList.children){
search.style.textTransform = "capitalize";
//up arrow key
if(e.key === 'ArrowUp'){
... | {
document.addEventListener("click", (e) => {
if (dropDown.style.display === "block" &&
!(e.target.className.includes("bell") ||
e.target.parentElement.className.includes("dropdown-container") ||
e.target.className.includes("notification-clear"))) {
dropDown.style.display = "none";
dropDow... | identifier_body |
generator.go | package parse
import (
"bytes"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/importer"
"go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
// _ "golang.org/x/tools/go/gcimporter"
"go/types"
)
//The caller will send a function of this type to do all the actual
//modification of the targ... | func (g *Generator) format() []byte {
//DEBUG: fmt.Print(g.Buf.String())
src, err := format.Source(g.Buf.Bytes())
if err != nil {
// Should never happen, but can arise when developing this code.
// The user can compile the output to see the error.
log.Printf("warning: internal error: invalid Go generated: %s",... | fmt.Fprint(&g.Buf, output)
}
//format returns the gofmt-ed contents of the Generator's buffer. | random_line_split |
generator.go | package parse
import (
"bytes"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/importer"
"go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
// _ "golang.org/x/tools/go/gcimporter"
"go/types"
)
//The caller will send a function of this type to do all the actual
//modification of the targ... |
// parsePackageFiles parses the package occupying the named files.
func (g *Generator) parsePackageFiles(names []string) {
g.parsePackage(".", names, nil)
}
// prefixDirectory places the directory name on the beginning of each name in the list.
func prefixDirectory(directory string, names []string) []string {
if d... | {
var files []*File
var astFiles []*ast.File
g.pkg = new(Package)
fs := token.NewFileSet()
for _, name := range names {
if !strings.HasSuffix(name, ".go") {
continue
}
log.Printf("Parsing file: %s", name)
parsedFile, err := parser.ParseFile(fs, name, text, 0)
if err != nil {
log.Fatalf("parsing pac... | identifier_body |
generator.go | package parse
import (
"bytes"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/importer"
"go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
// _ "golang.org/x/tools/go/gcimporter"
"go/types"
)
//The caller will send a function of this type to do all the actual
//modification of the targ... | (pathName string, imports []Import) bool {
for _, val := range imports {
if pathName == val.ImportedName {
return true
}
}
return false
}
// parsePackageDir parses the package residing in the directory.
func (g *Generator) parsePackageDir(directory string) {
log.Printf("Collecting objects in package %s for ... | importExists | identifier_name |
generator.go | package parse
import (
"bytes"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/importer"
"go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
// _ "golang.org/x/tools/go/gcimporter"
"go/types"
)
//The caller will send a function of this type to do all the actual
//modification of the targ... |
fieldObj, _, _ := types.LookupFieldOrMethod(typesObj.Type(), false, f.pkg.typesPkg, field.Name)
typeStr := fieldObj.Type().String()
tags := parseFieldTags(fieldLine.Tag)
//Skip here so we don't include rubbish import lines
if tags["exclude_dao"].Value == "true" {
continue
}
processed... | {
continue
} | conditional_block |
s3driver.go | package sftp
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
var BLOCK_DOWNLOADS_IP_ADDRESSES []string
type S3 interf... |
func (d S3Driver) Rename(oldpath string, newpath string) error {
translatedOldpath, err := TranslatePath(d.prefix, d.homePath, oldpath)
if err != nil {
return err
}
translatedNewpath, err := TranslatePath(d.prefix, d.homePath, newpath)
if err != nil {
return err
}
input := &s3.CopyObjectInput{
Bucket: ... | {
translatedPath, err := TranslatePath(d.prefix, d.homePath, path)
if err != nil {
return err
}
_, err = d.s3.DeleteObject(&s3.DeleteObjectInput{
Bucket: aws.String(d.bucket),
Key: aws.String(translatedPath),
})
return err
} | identifier_body |
s3driver.go | package sftp
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
var BLOCK_DOWNLOADS_IP_ADDRESSES []string
type S3 interf... | urlArray := strings.Split(combined, ":")
ip := ""
port := ""
if len(urlArray) > 0 {
ip = urlArray[0]
}
if len(urlArray) > 1 {
port = urlArray[1]
}
return ip, port
} | func getIPAndPort(combined string) (string, string) { | random_line_split |
s3driver.go | package sftp
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
var BLOCK_DOWNLOADS_IP_ADDRESSES []string
type S3 interf... | (path string) error {
translatedPath, err := TranslatePath(d.prefix, d.homePath, path)
if err != nil {
return err
}
// s3 DeleteObject needs a trailing slash for directories
directoryPath := translatedPath
if !strings.HasSuffix(translatedPath, "/") {
directoryPath = translatedPath + "/"
}
_, err = d.s3.De... | DeleteDir | identifier_name |
s3driver.go | package sftp
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
var BLOCK_DOWNLOADS_IP_ADDRESSES []string
type S3 interf... |
files = append(files, &fileInfo{
name: strings.TrimPrefix(*o.Key, prefix),
size: *o.Size,
mtime: *o.LastModified,
})
}
for _, o := range objects.CommonPrefixes {
files = append(files, &fileInfo{
name: strings.TrimSuffix(strings.TrimPrefix(*o.Prefix, prefix), "/"),
size: 4096,
m... | {
continue
} | conditional_block |
app.js | // scroll header
function eventScroll() {
window.addEventListener("scroll", function() {
let header = document.querySelector("header");
if (window.scrollY >= 20)
header.classList.add('sticky');
else if (window.scrollY < 19) {
header.classList.remove('sticky');
... | indow.location = "./pages/products-detail.html?" + productID;
})
}
}
var showDetailProduct = function() {
var linkItem = window.location.href;
var id = linkItem.split("?")[1];
var data = dataProducts.find(function(value, index) {
return value.id == id;
})
var imgProduct = docume... | tion(e) {
e.preventDefault();
var productID = this.id;
w | conditional_block |
app.js | // scroll header
function eventScroll() {
window.addEventListener("scroll", function() {
let header = document.querySelector("header");
if (window.scrollY >= 20)
header.classList.add('sticky');
else if (window.scrollY < 19) {
header.classList.remove('sticky');
... | ty = item.n;
products.push(product)
}
}
return products;
}
// add product vào cart
// userCartList(users[0])
var addProduct = function(products) {
var prd = products(checkLogin());
if (prd) {
for (var product of prd) {
addRow(product);
}
totalPric... | ) {
var product = dataProducts.find(function(value) {
return value.id == item.id;
});
product.orderQ | identifier_body |
app.js | // scroll header
function eventScroll() {
window.addEventListener("scroll", function() {
let header = document.querySelector("header");
if (window.scrollY >= 20)
header.classList.add('sticky');
else if (window.scrollY < 19) {
header.classList.remove('sticky');
... | .url}" class="img-product">
</td>
<td class="text-center" >${product.name}</td>
<td class="text-center">${product.price}</td>
<td class="text-center d-flex justify-content-center">
<input style="width: 45px; border: none; outline: none;" type="number"
class="d-bl... | c="${product | identifier_name |
app.js | // scroll header
function eventScroll() {
window.addEventListener("scroll", function() {
let header = document.querySelector("header");
if (window.scrollY >= 20)
header.classList.add('sticky');
else if (window.scrollY < 19) {
header.classList.remove('sticky');
... | var lbEmail = document.querySelector("#lbEmail");
var lbNgaySinh = document.querySelector("#lbNgaySinh");
if (!regUserName.test(data.username)) {
lbUserName.innerText = "Tên đăng nhập ít nhất phải có 6 ký tự không chứa ký tự đặc biệt";
return false;
}
lbUserName.innerText = "";
... | var lbNhapLaiMatKhau = document.querySelector("#lbNhapLaiMatKhau");
var lbTen = document.querySelector("#lbTen");
var lbDiaChi = document.querySelector("#lbDiaChi");
var lbDt = document.querySelector("#lbDt"); | random_line_split |
x25519.rs | use core::ops::{Deref, DerefMut};
use super::common::*;
use super::error::Error;
use super::field25519::*;
const POINT_BYTES: usize = 32;
/// Non-uniform output of a scalar multiplication.
/// This represents a point on the curve, and should not be used directly as a
/// cipher key.
#[derive(Clone, Debug, Eq, Partia... |
sk_.copy_from_slice(sk);
Ok(SecretKey::new(sk_))
}
/// Perform the X25519 clamping magic
pub fn clamped(&self) -> SecretKey {
let mut clamped = self.clone();
clamped[0] &= 248;
clamped[31] &= 63;
clamped[31] |= 64;
clamped
}
/// Recover the ... | {
return Err(Error::InvalidSecretKey);
} | conditional_block |
x25519.rs | use core::ops::{Deref, DerefMut};
use super::common::*;
use super::error::Error;
use super::field25519::*;
const POINT_BYTES: usize = 32;
/// Non-uniform output of a scalar multiplication.
/// This represents a point on the curve, and should not be used directly as a
/// cipher key.
#[derive(Clone, Debug, Eq, Partia... | (dh: DHOutput) -> Self {
PublicKey(dh.0)
}
}
impl From<DHOutput> for SecretKey {
fn from(dh: DHOutput) -> Self {
SecretKey(dh.0)
}
}
impl Drop for DHOutput {
fn drop(&mut self) {
Mem::wipe(self.0)
}
}
/// A public key.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub... | from | identifier_name |
x25519.rs | use core::ops::{Deref, DerefMut};
use super::common::*;
use super::error::Error;
use super::field25519::*;
const POINT_BYTES: usize = 32;
/// Non-uniform output of a scalar multiplication.
/// This represents a point on the curve, and should not be used directly as a
/// cipher key.
#[derive(Clone, Debug, Eq, Partia... | let sk_1 = SecretKey::from_slice(&[
1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
])
.unwrap();
let output = PublicKey::base_point().unclamped_mul(&sk_1).unwrap();
assert_eq!(PublicKey::from(output), PublicKey::base_point());
le... | #[cfg(not(feature = "disable-signatures"))]
pub use from_ed25519::*;
#[test]
fn test_x25519() { | random_line_split |
nasdaq_itch_vwap.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ==============================================================================
# Created By : Karl Thompson
# Created Date: Mon March 25 17:34:00 CDT 2019
# ==============================================================================
"""nasdaq_itch_vwap - Genera... |
# advance the file position to the next message:
msg_header = itch_data.read(1)
# close the csv files:
add_order_data.close()
ord_exec_data.close()
ord_exec_pr_data.close()
trade_data.close()
# function to calculate the hourly VWAP based on parsed ITCH data:
def cal... | message = itch_data.read(43)
if len(message) < 43: break
un_pkd = struct.unpack('>4s6sQcI8cIQ',message)
re_pkd = struct.pack('>s4s2s6sQsI8sIQ',msg_header,un_pkd[0],
b'\x00\x00',un_pkd[1],un_pkd[2],un_pkd[3],un_pkd[4],
b''.join(list(un_pkd[5:13])),... | conditional_block |
nasdaq_itch_vwap.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ==============================================================================
# Created By : Karl Thompson
# Created Date: Mon March 25 17:34:00 CDT 2019
# ==============================================================================
"""nasdaq_itch_vwap - Genera... | sha = parsed_oewp[5] # shares
pri = float(parsed_oewp[8])/1e4 # new price
ord_exec_pr_wrtr.writerow([ref, sha, pri])
# process Trade messages:
if msg_header == b'P':
message = itch_data.read(43)
if len(message) < 43: break
... | if (parsed_oewp[4] < 1e14 and parsed_oewp[5] < 1e6 and
parsed_oewp[6] < 1e10 and parsed_oewp[7] == b'Y'):
# write the parsed message to the csv file:
ref = parsed_oewp[4] # order reference number
| random_line_split |
nasdaq_itch_vwap.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ==============================================================================
# Created By : Karl Thompson
# Created Date: Mon March 25 17:34:00 CDT 2019
# ==============================================================================
"""nasdaq_itch_vwap - Genera... |
if __name__ == '__main__':
# open the ITCH data file:
itch_data = gzip.open('01302019.NASDAQ_ITCH50.gz','rb')
# parse the data:
parse_itch_data(itch_data)
# close the ITCH data file:
itch_data.close()
# calculate the hourly VWAP for all stocks:
calculate_vwap()
| add_order_df = pd.read_csv('add_order_data.csv', index_col = None,
names = ['Stock', 'Timestamp', 'Reference', 'Shares', 'Price'])
# import the parsed Order Executed data into a Pandas dataframe:
ord_exec_df = pd.read_csv('ord_exec_data.csv', index_col = None,
names = ['Referenc... | identifier_body |
nasdaq_itch_vwap.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ==============================================================================
# Created By : Karl Thompson
# Created Date: Mon March 25 17:34:00 CDT 2019
# ==============================================================================
"""nasdaq_itch_vwap - Genera... | ():
# import the parsed Add Order data into a Pandas dataframe:
add_order_df = pd.read_csv('add_order_data.csv', index_col = None,
names = ['Stock', 'Timestamp', 'Reference', 'Shares', 'Price'])
# import the parsed Order Executed data into a Pandas dataframe:
ord_exec_df = pd.read_... | calculate_vwap | identifier_name |
physically_monotonic.rs | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by ... | (
&self,
ctx: &Context<Self::Domain>,
id: &Id,
_keys: &AvailableCollections,
_plan: &GetPlan,
) -> Self::Domain {
// A get operator yields physically monotonic output iff the corresponding
// `Plan::Get` is on a local or global ID that is known to provide phys... | get | identifier_name |
physically_monotonic.rs | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by ... | &self,
_ctx: &Context<Self::Domain>,
input: Self::Domain,
_forms: &AvailableCollections,
_input_key: &Option<Vec<MirScalarExpr>>,
_input_mfp: &MapFilterProject,
) -> Self::Domain {
// `Plan::ArrangeBy` is better thought of as `ensure_collections`, i.e., it
... | fn arrange_by( | random_line_split |
spinning_table_states.py | PKG = "spinning_table_sm"
import roslib; roslib.load_manifest(PKG)
import rospy
import smach
import sensor_msgs.msg
import trajectory_msgs.msg as tm
import geometry_msgs.msg as gm
import smach_ros
from numpy import *
from numpy.linalg import norm
from collections import defaultdict
from misc_msgs.msg import ... | self.vel_limits = [0.42, 0.42,0.65,0.66,0.72, 0.62,0.72]
def goto_posture(self, name):
l_joints = self.L_POSTURES[name]
joints = l_joints if self.lr == 'l' else mirror_arm_joints(l_joints)
self.goto_joint_positions(joints)
def goto_joint_positions(self, positions... | self.lr = lr
self.lrlong = {"r":"right", "l":"left"}[lr]
self.tool_frame = "%s_gripper_tool_frame"%lr
self.cart_command = rospy.Publisher('%s_cart/command_pose'%lr, gm.PoseStamped)
| random_line_split |
spinning_table_states.py | PKG = "spinning_table_sm"
import roslib; roslib.load_manifest(PKG)
import rospy
import smach
import sensor_msgs.msg
import trajectory_msgs.msg as tm
import geometry_msgs.msg as gm
import smach_ros
from numpy import *
from numpy.linalg import norm
from collections import defaultdict
from misc_msgs.msg import ... |
return angle
class Head(TrajectoryControllerWrapper):
def __init__(self, listener):
TrajectoryControllerWrapper.__init__(self,"head_traj_controller",listener)
self.vel_limits = [1.,1.]
def set_pan_tilt(self, pan, tilt):
self.goto_joint_positions([pan, tilt])
... | angle = angle + 2*math.pi | conditional_block |
spinning_table_states.py | PKG = "spinning_table_sm"
import roslib; roslib.load_manifest(PKG)
import rospy
import smach
import sensor_msgs.msg
import trajectory_msgs.msg as tm
import geometry_msgs.msg as gm
import smach_ros
from numpy import *
from numpy.linalg import norm
from collections import defaultdict
from misc_msgs.msg import ... | (smach.State):
def __init__(self):
smach.State.__init__(self, outcomes=["success", "failure","missed"],input_keys=["center","radius","rotation_rate","init_angle","init_time","object_radius","object_height"])
self.n_consecutive_grasp_failures = 0
def execute(self, userdata):
center... | ExecuteGrasp | identifier_name |
spinning_table_states.py | PKG = "spinning_table_sm"
import roslib; roslib.load_manifest(PKG)
import rospy
import smach
import sensor_msgs.msg
import trajectory_msgs.msg as tm
import geometry_msgs.msg as gm
import smach_ros
from numpy import *
from numpy.linalg import norm
from collections import defaultdict
from misc_msgs.msg import ... |
def fix_angle(angle, center_point=math.pi):
while angle > center_point + math.pi:
angle = angle - 2*math.pi
while angle < center_point - math.pi:
angle = angle + 2*math.pi
return angle
class Head(TrajectoryControllerWrapper):
def __init__(self, listener):
Trajecto... | L_POSTURES = dict(
untucked = [0.4, 1.0, 0.0, -2.05, 0.0, -0.1, 0.0],
tucked = [0.06, 1.25, 1.79, -1.68, -1.73, -0.10, -0.09],
up = [ 0.33, -0.35, 2.59, -0.15, 0.59, -1.41, -0.27],
side = [ 1.832, -0.332, 1.011, -1.437, 1.1 , -2.106, 3.074]
)
... | identifier_body |
action.py | import pandas as pd
import math
import json
import html
import bs4
import re
import dateparser
from bs4 import BeautifulSoup
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, List, Dict, ClassVar, Union
from urllib.parse import urlparse
from .markdown import MarkdownData, Ma... | f"<a href='{source}' target='_blank'>{urlparse(source).netloc}</a>"
)
ret.append(tag)
td.append(BeautifulSoup(html.unescape(", ".join(ret)), "html.parser"))
else:
td.string = value
return td
@classmethod
def create_fro... | elif field == "sources":
ret = []
for source in value:
tag = ( | random_line_split |
action.py | import pandas as pd
import math
import json
import html
import bs4
import re
import dateparser
from bs4 import BeautifulSoup
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, List, Dict, ClassVar, Union
from urllib.parse import urlparse
from .markdown import MarkdownData, Ma... |
return False
def sort(self, *args, **kwargs) -> "Actions":
""" Sorts the list of actions. """
self.actions.sort(*args, **kwargs)
return self
def append(self, action: Action):
""" Append an action onto this instance of Actions. """
self.actions.append(action)
... | return self.actions == other.actions | conditional_block |
action.py | import pandas as pd
import math
import json
import html
import bs4
import re
import dateparser
from bs4 import BeautifulSoup
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, List, Dict, ClassVar, Union
from urllib.parse import urlparse
from .markdown import MarkdownData, Ma... | (self, field: Union[List[Any], Any]) -> List[Any]:
if self.is_none(field):
return None
else:
if isinstance(field, (list,)):
return field
else:
return [s.strip().lower() for s in field.split(",")]
def __post_init__(self):
""... | listify | identifier_name |
action.py | import pandas as pd
import math
import json
import html
import bs4
import re
import dateparser
from bs4 import BeautifulSoup
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, List, Dict, ClassVar, Union
from urllib.parse import urlparse
from .markdown import MarkdownData, Ma... |
def to_md(self, field: str, td: bs4.element.Tag) -> str:
""" Convert field for markdown
Takes a td BeautifulSoup object and updates it according to the field
type so that it renders correctly in markdown.
"""
assert (
field in self.__dataclass_fields__
... | """ Return the value of the field rendered for df. """
value = self.__getattribute__(field)
if field in ["date", "workers"]:
return str(value)
elif field in ["locations", "struggles", "companies", "tags", "sources"]:
return str(value).strip("[").strip("]").replace("'", ""... | identifier_body |
web.rs | //! This is the initial MVP of the events service to get the BDD tests to work
use db;
use models::user::IOModel;
use models::user::pg::PgModel as UserModel;
use rouille;
use rouille::input::post;
use rouille::{Request, Response};
use services::user;
use services::user::Service as UserService;
use std::collections::Has... |
#[test]
fn test_form_to_password_grant() {
assert_eq!(
form_to_password_grant(&vec![
("grant_type".into(), "password".into()),
("username".into(), "test-user".into()),
("password".into(), "test-password".into()),
]).unwrap(),
user::PasswordGrantRequest {
... | {
let fields = form_to_map(fields);
let username = fields.get("username").ok_or(WebError::MissingUsername)?;
let password = fields.get("password").ok_or(WebError::MissingPassword)?;
Ok(user::PasswordGrantRequest { username, password })
} | identifier_body |
web.rs | //! This is the initial MVP of the events service to get the BDD tests to work
use db;
use models::user::IOModel;
use models::user::pg::PgModel as UserModel;
use rouille;
use rouille::input::post;
use rouille::{Request, Response};
use services::user;
use services::user::Service as UserService;
use std::collections::Has... | <'a> {
pub status: &'a str,
}
/// this is the status endpoint
fn status(user_model: &UserModel) -> Response {
let status = user_model
.find(&Uuid::new_v4())
.map(|_| Status { status: "up" })
.unwrap_or_else(|_| Status { status: "down" });
Response::json(&status)
}
#[derive(Deseria... | Status | identifier_name |
web.rs | //! This is the initial MVP of the events service to get the BDD tests to work
use db;
use models::user::IOModel;
use models::user::pg::PgModel as UserModel;
use rouille;
use rouille::input::post;
use rouille::{Request, Response};
use services::user;
use services::user::Service as UserService;
use std::collections::Has... | );
assert_eq!(
form_to_password_grant(&vec![("password".into(), "test-pass".into())]).unwrap_err(),
WebError::MissingUsername
);
}
/// Converts the Form Fields into a `RefreshGrantRequest`
fn form_to_refresh_grant(fields: &Fields) -> Result<user::RefreshGrantRequest, WebError> {
let fi... | WebError::MissingPassword | random_line_split |
chmod.rs | //
// Copyright (c) 2018, The MesaLock Linux Project Contributors
// All rights reserved.
//
// This work is licensed under the terms of the BSD 3-Clause License.
// For a copy, see the LICENSE file.
//
// This file incorporates work covered by the following copyright and
// permission notice:
//
// Copyright (c) 2... | .validator_os(validate_mode)
.required(true))
//.conflicts_with("reference"))
.arg(Arg::with_name("FILES")
.index(2)
.required(true)
... | random_line_split | |
chmod.rs | //
// Copyright (c) 2018, The MesaLock Linux Project Contributors
// All rights reserved.
//
// This work is licensed under the terms of the BSD 3-Clause License.
// For a copy, see the LICENSE file.
//
// This file incorporates work covered by the following copyright and
// permission notice:
//
// Copyright (c) 2... | (data: String) -> Self {
Self {
kind: MessageKind::Stdout,
data,
}
}
pub fn stderr(data: String) -> Self {
Self {
kind: MessageKind::Stderr,
data,
}
}
}
struct Options<'a> {
verbosity: Verbosity,
preserve_root: bool,
... | stdout | identifier_name |
chmod.rs | //
// Copyright (c) 2018, The MesaLock Linux Project Contributors
// All rights reserved.
//
// This work is licensed under the terms of the BSD 3-Clause License.
// For a copy, see the LICENSE file.
//
// This file incorporates work covered by the following copyright and
// permission notice:
//
// Copyright (c) 2... |
}
}
#[cfg(unix)]
fn change_file(
options: &Options,
msgs: &mut [Option<Message>; 2],
fperm: u32,
mode: u32,
file: &Path,
) -> i32 {
if fperm == mode {
if options.verbosity == Verbosity::Verbose {
msgs[0] = Some(Message::stdout(format!(
"mode of '{}' reta... | {
let cmode_unwrapped = options.cmode.clone().unwrap();
for mode in cmode_unwrapped.split(',') {
// cmode is guaranteed to be Some in this case
let arr: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7'];
let result = if mode.contains(arr) {
... | conditional_block |
cnn.py | """
Finetuning Torchvision Models
=============================
**Author:** `Nathan Inkawhich <https://github.com/inkawhich>`__
"""
######################################################################
# In this tutorial we will take a deeper look at how to finetune and
# feature extract the `torchvision
# models ... | isualize feature maps after jpeg layer
def get_activation(name):
def hook(model, input, output):
activation[name] = output.detach()
return hook
if args.add_jpeg_layer:
activation = {}
model_ft[0].register_forward_hook(get_activation('0.JpegLayer'))
data, _ = image_datasets["val"][0]
... | res_grad == True and\
name == "0.quantize":
print('Y',param.data[0]*255)
print('Cb',param.data[1]*255)
print('Cr',param.data[2]*255)
break
# Let's v | conditional_block |
cnn.py | """
Finetuning Torchvision Models
=============================
**Author:** `Nathan Inkawhich <https://github.com/inkawhich>`__
"""
######################################################################
# In this tutorial we will take a deeper look at how to finetune and
# feature extract the `torchvision
# models ... |
######################################################################
# Set Model Parameters’ .requires_grad attribute
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# This helper function sets the ``.requires_grad`` attribute of the
# parameters in the model to False when we are feature extracting. By
# default... | nce = time.time()
val_acc_history = []
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
phases =['train', 'val']
if not train:
phases = ['val']
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
#... | identifier_body |
cnn.py | """
Finetuning Torchvision Models
=============================
**Author:** `Nathan Inkawhich <https://github.com/inkawhich>`__
"""
######################################################################
# In this tutorial we will take a deeper look at how to finetune and
# feature extract the `torchvision
# models ... | odel, dataloaders, criterion, optimizer, num_epochs=25, is_inception=False, train = True):
since = time.time()
val_acc_history = []
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
phases =['train', 'val']
if not train:
phases = ['val']
for epoch in range(num_epoch... | ain_model(m | identifier_name |
cnn.py | """
Finetuning Torchvision Models
=============================
**Author:** `Nathan Inkawhich <https://github.com/inkawhich>`__
"""
######################################################################
# In this tutorial we will take a deeper look at how to finetune and
# feature extract the `torchvision
# models ... | # (2): ReLU(inplace)
# (3): AvgPool2d(kernel_size=13, stride=1, padding=0)
# )
#
# To modify the network, we reinitialize the Conv2d layer to have an
# output feature map of depth 2 as
#
# ::
#
# model.classifier[1] = nn.Conv2d(512, num_classes, kernel_size=(1,1), stride=(1,1))
#
# Densenet
# ... | # (1): Conv2d(512, 1000, kernel_size=(1, 1), stride=(1, 1)) | random_line_split |
Server.go | package server
import (
"bufio"
//"bytes"
"io"
"log"
"net"
"strings"
)
var (
MainServer *Server
//EndPacket []byte = []byte{128, 0, 128, 1}
)
type Job func()
type PacketHandler func(c *Client, rawPacket Packet)
type PacketProcessor func([]byte) Packet
type Server struct {
Socket *net.TCPListener
... | )
_, addr, err := UDP_Listner.ReadFromUDP(buf[0:])
if err != nil {
log.Printf("AcceptUDP error:" + err.Error())
continue
}
if buf[0] == ID_ResolveUDP {
PlayerID = ID(buf[3]) | (ID(buf[4]) << 8) | (ID(buf[5])<<16 | ID(buf[6])<<24)
for _, c := range MainServer.Clients {
if PlayerID == c.ID { /... | for {
var (
buf = make([]byte, 1024)
PlayerID ID | random_line_split |
Server.go | package server
import (
"bufio"
//"bytes"
"io"
"log"
"net"
"strings"
)
var (
MainServer *Server
//EndPacket []byte = []byte{128, 0, 128, 1}
)
type Job func()
type PacketHandler func(c *Client, rawPacket Packet)
type PacketProcessor func([]byte) Packet
type Server struct {
Socket *net.TCPListener
... |
buf = make([]byte, 1024)
continue
}
}
}
func StartServer() {
TCP_addr, TCP_err := net.ResolveTCPAddr("tcp", "0.0.0.0:4354")
if TCP_err != nil {
log.Println(TCP_err)
return
}
ln, err := net.ListenTCP("tcp", TCP_addr)
if err != nil {
log.Println(err)
return
}
log.Printf("Server started (TCP)! at... | {
if PlayerID == c.ID { // TODO: must be reply TCP message with approve connection
log.Printf("%s pid=%d", addr.String(), PlayerID)
c.UDPCon = UDP_Listner
c.UDPAddr = addr
}
} | conditional_block |
Server.go | package server
import (
"bufio"
//"bytes"
"io"
"log"
"net"
"strings"
)
var (
MainServer *Server
//EndPacket []byte = []byte{128, 0, 128, 1}
)
type Job func()
type PacketHandler func(c *Client, rawPacket Packet)
type PacketProcessor func([]byte) Packet
type Server struct {
Socket *net.TCPListener
... | () {
defer c.OnPanic()
log.Println("Income connection")
c.TCPReader = bufio.NewReader(c.Socket)
c.TCPWriter = bufio.NewWriter(c.Socket)
//c.UDPCon = net.ResolveUDPAddr(c.Socket.RemoteAddr().Network(), c.Socket.RemoteAddr().String())
var (
buf = make([]byte, 1024)
)
for {
bufLength, err := c.TCPReader.Re... | Run | identifier_name |
Server.go | package server
import (
"bufio"
//"bytes"
"io"
"log"
"net"
"strings"
)
var (
MainServer *Server
//EndPacket []byte = []byte{128, 0, 128, 1}
)
type Job func()
type PacketHandler func(c *Client, rawPacket Packet)
type PacketProcessor func([]byte) Packet
type Server struct {
Socket *net.TCPListener
... |
//func (c *Client) Run() {
// defer c.OnPanic()
// log.Println("Income connection")
// c.TCPReader = bufio.NewReader(c.Socket)
// c.TCPWriter = bufio.NewWriter(c.Socket)
// //c.UDPCon = net.ResolveUDPAddr(c.Socket.RemoteAddr().Network(), c.Socket.RemoteAddr().String())
// var (
// buf = make([]byte, 512)
// )
//... | {
defer c.OnPanic()
log.Println("Income connection")
c.TCPReader = bufio.NewReader(c.Socket)
c.TCPWriter = bufio.NewWriter(c.Socket)
//c.UDPCon = net.ResolveUDPAddr(c.Socket.RemoteAddr().Network(), c.Socket.RemoteAddr().String())
var (
buf = make([]byte, 1024)
)
for {
bufLength, err := c.TCPReader.Read(... | identifier_body |
plugins.go | package plugins
import (
"os"
"encoding/json"
"fmt"
"math/rand"
"strings"
"sync"
"time"
"log"
"net/url"
"github.com/PuerkitoBio/goquery"
"../bot"
"github.com/sorcix/irc"
"github.com/turnage/graw/reddit"
)
type AutoJoin struct {
Channels []string
bot *bot.Bot
}
type Misc struct {
bot *bot.Bot
banned... |
func (p *Misc) buzz(source *irc.Prefix, target string, cmd string, args []string) (bool, error) {
if len(args) == 0 {
return true, nil
}
perms, err := p.bot.Auth(source)
if err != nil {
return false, err
}
if perms == nil || !perms.Can("annoy") {
return true, nil
}
lines := []string{
"%s",
"%s!",
... | {
if len(args) == 0 {
return true, nil
}
msg := fmt.Sprintf("%s: I am bullshitting you!", args[0])
p.bot.Message(bot.PrivMsg(target, msg))
return true, nil
} | identifier_body |
plugins.go | package plugins
import (
"os"
"encoding/json"
"fmt"
"math/rand"
"strings"
"sync"
"time"
"log"
"net/url"
"github.com/PuerkitoBio/goquery"
"../bot"
"github.com/sorcix/irc"
"github.com/turnage/graw/reddit"
)
type AutoJoin struct {
Channels []string
bot *bot.Bot
}
type Misc struct {
bot *bot.Bot
banned... | () error {
return nil
}
func (p *Misc) Load(b *bot.Bot) (*bot.PluginInfo, error) {
p.bot = b
p.textCmd("cmd.hey", []string{"how are you?", "heya!", "hello"})
p.bot.HandleCmdRateLimited("cmd.buzz", p.buzz)
file, _ := os.Open("config/reply.json")
defer file.Close()
decoder := json.NewDecoder(file)
replyTerms := ... | Unload | identifier_name |
plugins.go | package plugins
import (
"os"
"encoding/json"
"fmt"
"math/rand"
"strings"
"sync"
"time"
"log"
"net/url"
"github.com/PuerkitoBio/goquery"
"../bot"
"github.com/sorcix/irc"
"github.com/turnage/graw/reddit"
)
type AutoJoin struct {
Channels []string
bot *bot.Bot
}
type Misc struct {
bot *bot.Bot
banned... | cmd = RedditSearch.Commands[0]
return p.bot.Event("cmd." + cmd, source, target, cmd, args)
}
func checkIsImage(post *reddit.Post, b *bot.Bot) bool {
linkURL, err := url.Parse(post.URL)
if err != nil {
return false
}
for _, host := range b.Config.ImageHosts {
if strings.Contains(linkURL.Host, host) {
retur... | RedditSearch := RedditSearches[rand.Intn(len(RedditSearches))] | random_line_split |
plugins.go | package plugins
import (
"os"
"encoding/json"
"fmt"
"math/rand"
"strings"
"sync"
"time"
"log"
"net/url"
"github.com/PuerkitoBio/goquery"
"../bot"
"github.com/sorcix/irc"
"github.com/turnage/graw/reddit"
)
type AutoJoin struct {
Channels []string
bot *bot.Bot
}
type Misc struct {
bot *bot.Bot
banned... |
var msg string
if len(args) > 0 {
if m.NSFW == true {
msg = fmt.Sprintf("%s, here is some %s from %s: %s NSFW (https://redd.it/%s)", args[0], what, source.Name, post.URL, post.ID)
} else {
msg = fmt.Sprintf("%s, here is some %s from %s: %s (https://redd.it/%s)", args[0], what, source.Name, post.URL, ... | {
plug.bot.Message(bot.PrivMsg(target, fmt.Sprintf("%s: haven't indexed any %s yet", source.Name, what)))
return true, nil
} | conditional_block |
partitions.go | // Copyright 2018 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | (sgdiskOut string, partitionNumbers []int) (map[int]sgdiskOutput, error) {
if len(partitionNumbers) == 0 {
return nil, nil
}
startRegex := regexp.MustCompile(`^First sector: (\d*) \(.*\)$`)
endRegex := regexp.MustCompile(`^Last sector: (\d*) \(.*\)$`)
const (
START = iota
END = iota... | parseSgdiskPretend | identifier_name |
partitions.go | // Copyright 2018 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | }
for _, part := range resolvedPartitions {
shouldExist := partitionShouldExist(part)
info, exists := diskInfo.GetPartition(part.Number)
var matchErr error
if exists {
matchErr = partitionMatches(info, part)
}
matches := exists && matchErr == nil
wipeEntry := cutil.IsTrue(part.WipePartitionEntry)
... | resolvedPartitions, err := s.getRealStartAndSize(dev, devAlias, diskInfo)
if err != nil {
return err | random_line_split |
partitions.go | // Copyright 2018 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
if end != -1 {
current.size = 1 + end - current.start
output[partitionNumbers[i]] = current
i++
if i == len(partitionNumbers) {
state = FAIL_ON_START_END
} else {
current = sgdiskOutput{}
state = START
}
}
case FAIL_ON_START_END:
if len(startRegex.FindStringSubmatch(li... | {
return nil, err
} | conditional_block |
partitions.go | // Copyright 2018 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
func convertMiBToSectors(mib *int, sectorSize int) *int64 {
if mib != nil {
v := int64(*mib) * (1024 * 1024 / int64(sectorSize))
return &v
} else {
return nil
}
}
// getRealStartAndSize returns a map of partition numbers to a struct that contains what their real start
// and end sector should be. It runs sg... | {
if part.Number == 0 {
return false
}
return (part.StartSector != nil && *part.StartSector == 0) ||
(part.SizeInSectors != nil && *part.SizeInSectors == 0)
} | identifier_body |
file.rs | use crate::reader::{LittleEndian, ReadBytesExt, Reader};
use std::fmt;
use std::io::Read;
use thiserror::Error;
const ELF_MAGIC: [u8; 4] = [0x7f, b'E', b'L', b'F'];
fn show_machine(value: u16) -> &'static str {
match value {
0 => "No machine",
1 => "AT&T WE 32100",
2 => "SUN SPARC",
... | pub enum FileClass {
// Invalid class
None,
// 32-bit objects
ElfClass32,
// 64 bit objects
ElfClass64,
// Unknown class
Invalid(u8),
}
#[derive(Debug)]
pub enum Encoding {
// Invalid data encoding
None,
// 2's complement, little endian
LittleEndian,
// 2's complemen... | #[derive(Debug)] | random_line_split |
file.rs | use crate::reader::{LittleEndian, ReadBytesExt, Reader};
use std::fmt;
use std::io::Read;
use thiserror::Error;
const ELF_MAGIC: [u8; 4] = [0x7f, b'E', b'L', b'F'];
fn show_machine(value: u16) -> &'static str {
match value {
0 => "No machine",
1 => "AT&T WE 32100",
2 => "SUN SPARC",
... | {
// Invalid data encoding
None,
// 2's complement, little endian
LittleEndian,
// 2's complement big endian
BigEndian,
// Uknown data encoding
Invalid(u8),
}
#[derive(Debug)]
pub enum OsAbi {
// UNIX System V ABI
UnixVSystem,
// HP-UX
HpUx,
// NetBDS
NetBsd,
... | Encoding | identifier_name |
mod.rs | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use deno_core::error::bad_resource_id;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::op;
use deno_core::OpState;
use libz_sys::*;
use std::borrow::Cow;
use std::cell::RefCell;
use std::future::Future;
use std:... | (state: &mut OpState, handle: u32) -> Result<(), AnyError> {
let resource = zlib(state, handle)?;
let mut zlib = resource.inner.borrow_mut();
// If there is a pending write, defer the close until the write is done.
zlib.close()?;
Ok(())
}
#[op]
pub fn op_zlib_write_async(
state: Rc<RefCell<OpState>>,
h... | op_zlib_close | identifier_name |
mod.rs | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use deno_core::error::bad_resource_id;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::op;
use deno_core::OpState;
use libz_sys::*;
use std::borrow::Cow;
use std::cell::RefCell;
use std::future::Future;
use std:... |
}
self.err = match self.mode {
Mode::Deflate | Mode::Gzip | Mode::DeflateRaw => self.strm.deflate_init(
self.level,
self.window_bits,
self.mem_level,
self.strategy,
),
Mode::Inflate | Mode::Gunzip | Mode::InflateRaw | Mode::Unzip => {
self.strm.inflate... | {} | conditional_block |
mod.rs | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use deno_core::error::bad_resource_id;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::op;
use deno_core::OpState;
use libz_sys::*;
use std::borrow::Cow;
use std::cell::RefCell;
use std::future::Future;
use std:... |
}
struct Zlib {
inner: RefCell<ZlibInner>,
}
impl deno_core::Resource for Zlib {
fn name(&self) -> Cow<str> {
"zlib".into()
}
}
#[op]
pub fn op_zlib_new(state: &mut OpState, mode: i32) -> Result<u32, AnyError> {
let mode = Mode::try_from(mode)?;
let inner = ZlibInner {
mode,
..Default::defaul... | {
self.err = self.strm.reset(self.mode);
Ok(())
} | identifier_body |
mod.rs | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use deno_core::error::bad_resource_id;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::op;
use deno_core::OpState;
use libz_sys::*;
use std::borrow::Cow;
use std::cell::RefCell;
use std::future::Future;
use std:... | self.pending_close = false;
check(self.init_done, "close before init")?;
self.strm.end(self.mode);
self.mode = Mode::None;
Ok(true)
}
fn reset_stream(&mut self) -> Result<(), AnyError> {
self.err = self.strm.reset(self.mode);
Ok(())
}
}
struct Zlib {
inner: RefCell<ZlibInner>,
}
... | self.pending_close = true;
return Ok(false);
}
| random_line_split |
seq2seq_chatbot_Learning.py | # -*- coding: utf-8 -*-
"""Chatbot learning
학습시 생성된 vocab 딕셔너리 파일을 Cindy ui 실행시 경로를 동일시 해주어야 연결성 있는 문장을 생성해줍니다.
"""
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras import optimizers, losses, metrics
from tensorflow.keras import preprocessing
import numpy as np
import pa... | [target_seq] + states)
# 결과의 원핫인코딩 형식을 인덱스로 변환
index = np.argmax(decoder_outputs[0, 0, :])
indexs.append(index)
# 종료 검사
if index == END_INDEX or len(indexs) >= max_sequences:
break
# 목표 시퀀스를 바로 이전의 출력으로 설정
target_seq = np.zer... | edict(
| conditional_block |
seq2seq_chatbot_Learning.py | # -*- coding: utf-8 -*-
"""Chatbot learning
학습시 생성된 vocab 딕셔너리 파일을 Cindy ui 실행시 경로를 동일시 해주어야 연결성 있는 문장을 생성해줍니다.
"""
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras import optimizers, losses, metrics
from tensorflow.keras import preprocessing
import numpy as np
import pa... | 중복된 단어 삭제
words = list(set(words))
# 제일 앞에 태그 단어 삽입
words[:0] = [PAD, STA, END, OOV]
# 단어 개수
len(words)
# 단어와 인덱스의 딕셔너리 생성
word_to_index = {word: index for index, word in enumerate(words)}
index_to_word = {index: word for index, word in enumerate(words)}
#word_index vocab 저장 - >
with open('./seq2seq/vocab_dict/wo... | sentence = " ".join(tagger.morphs(sentence))
sentences_pos.append(sentence)
return sentences_pos
# 형태소분석 수행
question = pos_tag(question)
answer = pos_tag(answer)
# 질문과 대답 문장들을 하나로 합침
sentences = []
sentences.extend(question)
sentences.extend(answer)
words = []
# 단어들의 배열 생성
for sentence in se... | identifier_body |
seq2seq_chatbot_Learning.py | # -*- coding: utf-8 -*-
"""Chatbot learning
학습시 생성된 vocab 딕셔너리 파일을 Cindy ui 실행시 경로를 동일시 해주어야 연결성 있는 문장을 생성해줍니다.
"""
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras import optimizers, losses, metrics
from tensorflow.keras import preprocessing
import numpy as np
import pa... | dropout=0.1,
recurrent_dropout=0.5,
return_state=True)(encoder_outputs)
# 히든 상태와 셀 상태를 하나로 묶음
encoder_states = [state_h, state_c]
#-----------------------------------------... | random_line_split | |
seq2seq_chatbot_Learning.py | # -*- coding: utf-8 -*-
"""Chatbot learning
학습시 생성된 vocab 딕셔너리 파일을 Cindy ui 실행시 경로를 동일시 해주어야 연결성 있는 문장을 생성해줍니다.
"""
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras import optimizers, losses, metrics
from tensorflow.keras import preprocessing
import numpy as np
import pa... | _seq
# 텍스트 생성
def generate_text(input_seq):
# 입력을 인코더에 넣어 마지막 상태 구함
states = encoder_model.predict(input_seq)
# 목표 시퀀스 초기화
target_seq = np.zeros((1, 1))
# 목표 시퀀스의 첫 번째에 <START> 태그 추가
target_seq[0, 0] = STA_INDEX
# 인덱스 초기화
indexs = []
# 디코더 타임 스텝 반복
while 1:
... |
return input | identifier_name |
mod.rs | mod assignments;
mod colors;
mod directory_stack;
mod flow;
/// The various blocks
pub mod flow_control;
mod job;
mod pipe_exec;
mod shell_expand;
mod signals;
pub mod sys;
/// Variables for the shell
pub mod variables;
use self::{
directory_stack::DirectoryStack,
flow_control::{Block, Function, FunctionError,... | (&mut self) -> &mut BuiltinMap<'a> { &mut self.builtins }
/// Access to the shell options
#[must_use]
pub const fn opts(&self) -> &Options { &self.opts }
/// Mutable access to the shell options
#[must_use]
pub fn opts_mut(&mut self) -> &mut Options { &mut self.opts }
/// Access to the var... | builtins_mut | identifier_name |
mod.rs | mod assignments;
mod colors;
mod directory_stack;
mod flow;
/// The various blocks
pub mod flow_control;
mod job;
mod pipe_exec;
mod shell_expand;
mod signals;
pub mod sys;
/// Variables for the shell
pub mod variables;
use self::{
directory_stack::DirectoryStack,
flow_control::{Block, Function, FunctionError,... |
/// Set the callback to call on each command
pub fn set_on_command(&mut self, callback: Option<OnCommandCallback<'a>>) {
self.on_command = callback;
}
/// Set the callback to call on each command
pub fn on_command_mut(&mut self) -> &mut Option<OnCommandCallback<'a>> { &mut self.on_command... | {
&mut self.pre_command
} | identifier_body |
mod.rs | mod assignments;
mod colors;
mod directory_stack;
mod flow;
/// The various blocks
pub mod flow_control;
mod job;
mod pipe_exec;
mod shell_expand;
mod signals;
pub mod sys;
/// Variables for the shell
pub mod variables;
use self::{
directory_stack::DirectoryStack,
flow_control::{Block, Function, FunctionError,... | flow_control: Block,
/// Contains the directory stack parameters.
directory_stack: DirectoryStack,
/// When a command is executed, the final result of that command is stored
/// here.
previous_status: Status,
/// The job ID of the previous command sent to the background.
prev... | /// started.
builtins: BuiltinMap<'a>,
/// Contains the aliases, strings, and array variable maps.
variables: Variables,
/// Contains the current state of flow control parameters. | random_line_split |
lib.rs | //! The SGX root enclave
//!
//! ## Authors
//!
//! The Veracruz Development Team.
//!
//! ## Licensing and copyright notice
//!
//! See the `LICENSE_MIT.markdown` file in the Veracruz root directory for
//! information on licensing and copyright.
#![no_std]
#[macro_use]
extern crate sgx_tstd as std;
use lazy_static:... |
fn from_slice(bytes: &[u8]) -> [u8; 32] {
let mut array = [0; 32];
let bytes = &bytes[..array.len()]; // panics if not enough data
for index in 0..32 {
array[index] = bytes[index];
}
array
}
|
let dh_msg3_raw_len =
mem::size_of::<sgx_dh_msg3_t>() as u32 + dh_msg3_raw.msg3_body.additional_prop_length;
let dh_msg3 = unsafe { SgxDhMsg3::from_raw_dh_msg3_t(dh_msg3_raw, dh_msg3_raw_len) };
assert!(!dh_msg3.is_none());
let dh_msg3 = match dh_msg3 {
Some(msg) => msg,
None =... | identifier_body |
lib.rs | //! The SGX root enclave
//!
//! ## Authors
//!
//! The Veracruz Development Team.
//!
//! ## Licensing and copyright notice
//!
//! See the `LICENSE_MIT.markdown` file in the Veracruz root directory for
//! information on licensing and copyright.
#![no_std]
#[macro_use]
extern crate sgx_tstd as std;
use lazy_static:... | p_fwv_len: &mut usize) -> sgx_status_t {
let version = env!("CARGO_PKG_VERSION");
*p_fwv_len = version.len();
sgx_status_t::SGX_SUCCESS
}
#[no_mangle]
pub extern "C" fn get_firmware_version(
p_firmware_version_buf: *mut u8,
fv_buf_size: usize,
) -> sgx_status_t {
let version = env!("CARGO_PKG_V... | et_firmware_version_len( | identifier_name |
lib.rs | //! The SGX root enclave
//!
//! ## Authors
//!
//! The Veracruz Development Team.
//!
//! ## Licensing and copyright notice
//!
//! See the `LICENSE_MIT.markdown` file in the Veracruz root directory for
//! information on licensing and copyright.
#![no_std]
#[macro_use]
extern crate sgx_tstd as std;
use lazy_static:... | }
#[no_mangle]
pub extern "C" fn sgx_get_collateral_report(
p_pubkey_challenge: *const u8,
pubkey_challenge_size: usize,
p_target_info: *const sgx_target_info_t,
report: *mut sgx_types::sgx_report_t,
csr_buffer: *mut u8,
csr_buf_size: usize,
p_csr_size: *mut usize,
) -> sgx_status_t {
l... | *private_key_guard = Some(pkcs8_bytes.as_ref().to_vec());
pkcs8_bytes.as_ref().to_vec()
}
};
return Ok(pkcs8_bytes); | random_line_split |
config.pb.go | /*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | () ([]byte, []int) { return fileDescriptor0, []int{2} }
func (m *LinkTemplate) GetOptions() []*LinkOptionsTemplate {
if m != nil {
return m.Options
}
return nil
}
// A simple key/value pair for link options.
type LinkOptionsTemplate struct {
// The key for the option. This is not expanded.
Key string `protobuf... | Descriptor | identifier_name |
config.pb.go | /*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
func (TestGroup_TestsName) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} }
// Specifies a group of tests to gather.
type TestGroup struct {
// Name of this TestGroup, for mapping dashboard tabs to tests.
Name string `protobuf:"bytes,1,opt,name=name" yaml:"name,omitempty"`
// Path to the te... | {
return proto.EnumName(TestGroup_TestsName_name, int32(x))
} | identifier_body |
config.pb.go | /*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | }
func (m *DashboardTab) GetResultsUrlTemplate() *LinkTemplate {
if m != nil {
return m.ResultsUrlTemplate
}
return nil
}
func (m *DashboardTab) GetCodeSearchUrlTemplate() *LinkTemplate {
if m != nil {
return m.CodeSearchUrlTemplate
}
return nil
}
// A service configuration consisting of multiple test grou... | random_line_split | |
config.pb.go | /*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
return nil
}
type DefaultConfiguration struct {
// A default testgroup with default initialization data
DefaultTestGroup *TestGroup `protobuf:"bytes,1,opt,name=default_test_group,json=defaultTestGroup" yaml:"default_test_group,omitempty"`
// A default dashboard with default initialization data
DefaultDashboardTa... | {
return m.Dashboards
} | conditional_block |
main.rs | #![allow(clippy::needless_return)]
#![feature(portable_simd)]
use core_simd::Simd;
use core::convert::TryInto;
use srng::SRng;
use simd_aes::SimdAes;
const DEFAULT_SEED: Simd<u8, 16> = Simd::from_array([
178, 201, 95, 240, 40, 41, 143, 216,
2, 209, 178, 114, 232, 4, 176, 188,
]);
#[allow(non_snake_case)]
fn ... |
fn chosen_prefix(prefix: &[u8]) {
let zero = Simd::splat(0);
let mut message = prefix.to_vec();
let remainder = 16 - (message.len() % 16);
message.extend((0..remainder).map(|_| b'A'));
message.extend((0..16).map(|_| 0));
let hash = ComputeGlyphHash(&message);
let pre_current = invert_last(... | {
let mut target_hash = Simd::<u64, 2>::from_array([message.len() as u64, 0]).to_ne_bytes();
target_hash ^= DEFAULT_SEED;
let prefix = single_prefix(message.len(), target_hash);
println!("Demonstrating prefix attack");
println!("message: {:x?}", message);
println!("hash: {:x?}", ComputeGlyph... | identifier_body |
main.rs | #![allow(clippy::needless_return)]
#![feature(portable_simd)]
use core_simd::Simd;
use core::convert::TryInto;
use srng::SRng;
use simd_aes::SimdAes;
const DEFAULT_SEED: Simd<u8, 16> = Simd::from_array([
178, 201, 95, 240, 40, 41, 143, 216,
2, 209, 178, 114, 232, 4, 176, 188,
]);
#[allow(non_snake_case)]
fn ... | (prefix: Simd<u8, 16>, target: &[u8]) -> Vec<u8> {
let mut image = prefix.to_array().to_vec();
image.extend_from_slice(target);
image
}
fn prefix_collision_attack(message: &[u8]) {
let mut target_hash = Simd::<u64, 2>::from_array([message.len() as u64, 0]).to_ne_bytes();
target_hash ^= DEFAULT_SEED... | concat | identifier_name |
main.rs | #![allow(clippy::needless_return)]
#![feature(portable_simd)]
use core_simd::Simd;
use core::convert::TryInto;
use srng::SRng;
use simd_aes::SimdAes;
const DEFAULT_SEED: Simd<u8, 16> = Simd::from_array([
178, 201, 95, 240, 40, 41, 143, 216,
2, 209, 178, 114, 232, 4, 176, 188,
]);
#[allow(non_snake_case)]
fn ... | b" known methods: https://m1el.github.io/refterm-hash",
b" Best regards, -- Igor",
];
fn main() {
padding_attack();
invert_attack(b"Qwerty123");
prefix_collision_attack(b"hello");
chosen_prefix(b"hello");
preimage_attack(b"hello");
const THREADS: u64 = 16;
for msg in MESSAGE {
... | br#" two strings "A" and "B\x00" yield the same hash, because"#,
b" the padding is constant, so zero byte in the end doens't",
b" matter, and the first byte is `xor`ed with input length.",
b" If you'd like to, you can read this blog post explaining",
b" these attacks in detail and how to avoid them us... | random_line_split |
main.rs | #![allow(clippy::needless_return)]
#![feature(portable_simd)]
use core_simd::Simd;
use core::convert::TryInto;
use srng::SRng;
use simd_aes::SimdAes;
const DEFAULT_SEED: Simd<u8, 16> = Simd::from_array([
178, 201, 95, 240, 40, 41, 143, 216,
2, 209, 178, 114, 232, 4, 176, 188,
]);
#[allow(non_snake_case)]
fn ... |
buffer[0] ^= len as u8;
let recovered = &buffer[..len];
println!("recovered: {:x?}", recovered);
println!("hash: {:x?}", ComputeGlyphHash(recovered));
println!();
}
pub fn check_alphanum(bytes: Simd<u8, 16>) -> bool {
// check if the characters are outside of '0'..'z' range
if (bytes ... | {
println!("the plaintext mus be shorter than 16 bytes, cannot invert");
return;
} | conditional_block |
constants.go | // Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE-CODE in the project root for license information.
package main
const (
AvereAdminUsername = "admin"
MaxZonalNodesCount = 3
MinNodesCount = 3
MaxNodesCount ... | cifs_netbios_domain_name = "cifs_netbios_domain_name"
cifs_dc_addreses = "cifs_dc_addreses"
cifs_server_name = "cifs_server_name"
cifs_username = "cifs_username"
cifs_password = "cifs_password"
cifs_flatfile_pas... | active_support_upload = "active_support_upload"
enable_secure_proactive_support = "enable_secure_proactive_support"
cifs_ad_domain = "cifs_ad_domain" | random_line_split |
FRB_MCMC.py | import numpy as np
import sys
from subprocess import *
import os
import emcee
from emcee.utils import MPIPool
#from schwimmbad import MPIPool
import astropy
import xi_2D
import time
import lightcone_FRB_decreasingz_xlos as lc
import DM
import h5py
#import matplotlib.pyplot as pl
import misc_functions as misc
import mpi... |
def lnprob(x, fiducial_DM_z ):
lp = lnprior(x)
if not np.isfinite(lp):
return -np.inf
return lp + lnlike(x, fiducial_DM_z)
beta_list = []
zeta_list = []
Mturn_list = []
model_DM_z = []
Rmfp_list = []
chi2_model = []
def lnlike(x, fiducial_DM_z):
#draw a tag for this run
OUTPUT_NUMBER = i... | beta = x[0]
zeta = x[1]
Mturn = x[2]
Rmfp = x[3]
if -1 < beta < 1 and 200 < zeta < 1000 and 1e7 < (Mturn*5e7) < 9e9 and 5 < Rmfp < 60:
os.system("echo RUN " + str(RUN) + " accepting the fuck out of beta " + str(beta) + " " + str(zeta) + " " + str(Mturn) + " " + str(Rmfp) )
return... | identifier_body |
FRB_MCMC.py | import numpy as np
import sys
from subprocess import *
import os
import emcee
from emcee.utils import MPIPool
#from schwimmbad import MPIPool
import astropy
import xi_2D
import time
import lightcone_FRB_decreasingz_xlos as lc
import DM
import h5py
#import matplotlib.pyplot as pl
import misc_functions as misc
import mpi... |
else:
sign = np.sign(-np.pi*(beta) - np.pi)
sigma = np.abs(-np.pi*(beta) - np.pi)
return (sign*sigma)
####################################################################
# Cosmology and Astrophysical Parameters #
###################################################... | sign = np.sign(-np.pi*(beta) + np.pi)
sigma = np.abs(-np.pi*(beta) + np.pi)
return (sign*sigma) | conditional_block |
FRB_MCMC.py | import numpy as np
import sys
from subprocess import *
import os
import emcee
from emcee.utils import MPIPool
#from schwimmbad import MPIPool
import astropy
import xi_2D
import time
import lightcone_FRB_decreasingz_xlos as lc
import DM
import h5py
#import matplotlib.pyplot as pl
import misc_functions as misc
import mpi... | (x):
beta = x[0]
zeta = x[1]
Mturn = x[2]
Rmfp = x[3]
if -1 < beta < 1 and 200 < zeta < 1000 and 1e7 < (Mturn*5e7) < 9e9 and 5 < Rmfp < 60:
os.system("echo RUN " + str(RUN) + " accepting the fuck out of beta " + str(beta) + " " + str(zeta) + " " + str(Mturn) + " " + str(Rmfp) )
... | lnprior | identifier_name |
FRB_MCMC.py | import numpy as np
import sys
from subprocess import *
import os
import emcee
from emcee.utils import MPIPool
#from schwimmbad import MPIPool
import astropy
import xi_2D
import time
import lightcone_FRB_decreasingz_xlos as lc
import DM
import h5py
#import matplotlib.pyplot as pl
import misc_functions as misc
import mpi... |
####################################################################
# FRB script loader #
####################################################################
#Constants for the script
Box_length = 300
HII_DIM = 200
DIM = 800
#######################################################... | #os.chdir("/home/grx40/projects/def-acliu/grx40/soft/21cmFASTM/Programs/")
#dimensions and walkers of EnsembleSampler
ndim = 4
nwalkers = 24
| random_line_split |
marker_detector.py | import numpy as np
import cv2
import imutils
from imutils import contours
import copy
class ColorLabel:
def __init__(self, area, w, h):
self.area = area
(self.width, self.height) = (w, h)
self.bgr = [0, 0, 0]
pass
def label(self):
return self.__label_square()
... |
def draw_train_status(self, image, idx):
string = "Train: " + str(idx)
cv2.putText(image, string, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)
pass
def draw_crosshair(self, image, shape):
(startX, endX) = (int(shape.centerX - (shape.w * 0.15)), int(shape.centerX ... | string = "Station: " + text
cv2.putText(image, string, (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)
pass | identifier_body |
marker_detector.py | import numpy as np
import cv2
import imutils
from imutils import contours
import copy
class ColorLabel:
def __init__(self, area, w, h):
self.area = area
(self.width, self.height) = (w, h)
self.bgr = [0, 0, 0]
pass
def label(self):
return self.__label_square()
... |
return None, None
def check_similarity_of_two_cw(self, cw_1, cw_2):
err = 50
if abs(cw_1.cX - cw_2.cX) <= err:
if abs(cw_1.cY - cw_2.cY) <= err:
return True
return False
##################################################################
##############... | for j in range(0, len(cnts_array)):
if cnts_array[j].area != 0:
ratio = cnts_array[i].area / cnts_array[j].area
if abs(ratio-expected_ratio) <= err and self.check_similarity_of_two_cw(cnts_array[i], cnts_array[j]):
return cnts_array[i], cnt... | conditional_block |
marker_detector.py | import numpy as np
import cv2
import imutils
from imutils import contours
import copy
class ColorLabel:
def __init__(self, area, w, h):
self.area = area
(self.width, self.height) = (w, h)
self.bgr = [0, 0, 0]
pass
def label(self):
return self.__label_square()
... | (self):
self.__contours(self.thresh)
return self.cnts
class ContourWrapper:
def __init__(self, contour, ratio=1):
self.contour = contour
self.ratio = ratio
self.peri = cv2.arcLength(self.contour, True)
self.approx = cv2.approxPolyDP(self.contour, 0.04 * self.peri, T... | contours_color | identifier_name |
marker_detector.py | import numpy as np
import cv2
import imutils
from imutils import contours
import copy
class ColorLabel:
def __init__(self, area, w, h):
self.area = area
(self.width, self.height) = (w, h)
self.bgr = [0, 0, 0]
pass
def label(self):
return self.__label_square()
... | # def main():
# video()
# pass
#
# if __name__ == "__main__":
# main() | #
# | random_line_split |
application.py | from flask import Flask, render_template, jsonify, request, make_response #BSD License
|
#StdLibs
import json
from os import path
import csv
###################################################
#Programmato da Alex Prosdocimo e Matteo Mirandola#
###################################################
application = Flask(__name__)
@application.route("/") # Index
def index():
return mak... | import requests #Apache 2.0
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.