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 |
|---|---|---|---|---|
sandbox.ts | import invariant from 'tiny-invariant';
import { datasetParser, isElement, evaluate, createSequence } from 'yuzu-utils';
import { IComponentConstructable } from 'yuzu/types';
import { Component } from 'yuzu';
import { createContext, IContext } from './context';
export type entrySelectorFn = (sbx: Sandbox<any>) => bool... |
/**
* Removes events and associated store
*
* @ignore
*/
public clear(): void {
this.$ctx = undefined; // release the context
this.off('beforeStart');
this.off('start');
this.off('error');
this.off('beforeStop');
this.off('stop');
}
}
| {
this.emit('beforeStop');
await this.beforeDestroy();
this.removeListeners();
try {
if (this.$el) {
this.$el.removeAttribute(Sandbox.SB_DATA_ATTR);
}
await this.destroyRefs();
this.$active = false;
} catch (e) {
this.emit('error', e);
return Promise.rejec... | identifier_body |
sandbox.ts | import invariant from 'tiny-invariant';
import { datasetParser, isElement, evaluate, createSequence } from 'yuzu-utils';
import { IComponentConstructable } from 'yuzu/types';
import { Component } from 'yuzu';
import { createContext, IContext } from './context';
export type entrySelectorFn = (sbx: Sandbox<any>) => bool... | (
selector: string | entrySelectorFn,
): HTMLElement[] | boolean {
let targets = evaluate(selector, this);
if (typeof targets === 'string') {
targets = this.findNodes(targets) as HTMLElement[];
}
return targets;
}
/**
* Creates a component instance.
* Reads inline components from ... | resolveSelector | identifier_name |
HexSnake.py | from time import sleep
from random import random as rnd
from numpy import zeros
import pygame
from pygame.locals import *
further = lambda x, y, d: {
0: (x ,y-1),
1: (x-1,y-1),
2: (x-1 ,y),
3: (x,y+1),
4: (x+1 ,y+1),
5: (x+1 ,y)
}[d]
def dir(x,y,i,j):
d=3 if abs(x-i)>1 or abs(y-j)>1 ... |
def crawl(self):
f=self.field
x,y=self.body[-1]
if f[x][y]==BODY: f[x][y],t=TAIL,[(x,y)]
else : f[x][y],t=EMPTY,[]
x,y=self.body[0]
if f[x][y]!=BODY:
f[x][y]=TAIL
x,y=self.next(x,y,self.cdir)
self.body=[(x,y)]+self.body[:-1]+t
re... | rx, ry= further(x,y,d)
if self.out(rx,ry):
while (not self.out(x,y) ) :
x,y= further(x,y,(d+3)%6)
rx, ry= further(x,y,d)
if not loop:
self.field[rx][ry]=KILLER
return rx,ry | identifier_body |
HexSnake.py | from time import sleep
from random import random as rnd
from numpy import zeros
import pygame
from pygame.locals import *
further = lambda x, y, d: {
0: (x ,y-1),
1: (x-1,y-1),
2: (x-1 ,y),
3: (x,y+1),
4: (x+1 ,y+1),
5: (x+1 ,y)
}[d]
def dir(x,y,i,j):
d=3 if abs(x-i)>1 or abs(y-j)>1 ... |
if l==BONUS or l==EXTRASCORE:
pygame.draw.circle(screen, colorBonus, crds, dh/2, 0)
return
def drawfield(self):
n=self.field_dimension
s=self.field_size
ds=self.drawsymbol
screen.fill((0,0,0))
pygame.draw.polygon(screen, colorGrass, [
... | cx,cy=crds
pygame.draw.line(screen,colorBonus,(cx-dh/3,cy-dh/3),(cx+dh/3,cy+dh/3),2)
pygame.draw.line(screen,colorBonus,(cx+dh/3,cy-dh/3),(cx-dh/3,cy+dh/3),2) | conditional_block |
HexSnake.py | from time import sleep
from random import random as rnd
from numpy import zeros
import pygame
from pygame.locals import *
further = lambda x, y, d: {
0: (x ,y-1),
1: (x-1,y-1),
2: (x-1 ,y),
3: (x,y+1),
4: (x+1 ,y+1),
5: (x+1 ,y)
}[d]
def dir(x,y,i,j):
d=3 if abs(x-i)>1 or abs(y-j)>1 ... | dh=self.display_height_step
if l==TAIL:
pygame.draw.circle(screen, colorSnake, crds, dh/2, 0)
if l==BODY:
pygame.draw.circle(screen, colorSnake, crds, dw/2, 0)
if l==HEAD:
x,y=further(i,j,self.cdir)
x,y=self.display_crds(x,y)
mc... | random_line_split | |
HexSnake.py | from time import sleep
from random import random as rnd
from numpy import zeros
import pygame
from pygame.locals import *
further = lambda x, y, d: {
0: (x ,y-1),
1: (x-1,y-1),
2: (x-1 ,y),
3: (x,y+1),
4: (x+1 ,y+1),
5: (x+1 ,y)
}[d]
def | (x,y,i,j):
d=3 if abs(x-i)>1 or abs(y-j)>1 else 0
v=(x-i)/abs(x-i) if x!=i else 0
h=(y-j)/abs(y-j) if y!=j else 0
return (d+{
(0,-1):0,
(-1,-1):1,
(-1,0):2,
(0,1):3,
(1,1):4,
(1,0):5
}[(v,h)])%6
if True: # objects
HEAD=-3
BODY=-2
... | dir | identifier_name |
helpers.ts | 'use strict';
import * as vscode from 'vscode';
import * as cp from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import { resolve } from 'path';
export default class Helpers {
static wordMatchRegex = /[\w\d\-_\.\:\\\/@]+/g;
static phpParser:any = null;
static cachedParseFunction:any = null... | }
let basePathForCode = vscode.workspace.getConfiguration("LaravelExtraIntellisense").get<string>('basePathForCode');
if (forCode && basePathForCode && basePathForCode.length > 0) {
if (basePathForCode.startsWith('.') && vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) {
... | return basePath + path; | random_line_split |
helpers.ts | 'use strict';
import * as vscode from 'vscode';
import * as cp from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import { resolve } from 'path';
export default class Helpers {
static wordMatchRegex = /[\w\d\-_\.\:\\\/@]+/g;
static phpParser:any = null;
static cachedParseFunction:any = null... | (path:string, forCode: boolean = false) : string {
if (path[0] !== '/') {
path = '/' + path;
}
let basePath = vscode.workspace.getConfiguration("LaravelExtraIntellisense").get<string>('basePath');
if (forCode === false && basePath && basePath.length > 0) {
if (basePath.startsWith('.') && vscode.workspace... | projectPath | identifier_name |
helpers.ts | 'use strict';
import * as vscode from 'vscode';
import * as cp from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import { resolve } from 'path';
export default class Helpers {
static wordMatchRegex = /[\w\d\-_\.\:\\\/@]+/g;
static phpParser:any = null;
static cachedParseFunction:any = null... |
/**
* Parse php code with 'php-parser' package.
* @param code
*/
static parsePhp(code: string): any {
if (! Helpers.phpParser) {
var PhpEngine = require('php-parser');
Helpers.phpParser = new PhpEngine({
parser: {
extractDoc: true,
php7: true
},
ast: {
withPositions: true
... | {
code = code.replace(/\"/g, "\\\"");
if (['linux', 'openbsd', 'sunos', 'darwin'].some(unixPlatforms => os.platform().includes(unixPlatforms))) {
code = code.replace(/\$/g, "\\$");
code = code.replace(/\\\\'/g, '\\\\\\\\\'');
code = code.replace(/\\\\"/g, '\\\\\\\\\"');
}
let command = vscode.workspace... | identifier_body |
httpProcess.go | package main
import (
"net/http"
"fmt"
"net"
"log"
"strings"
"encoding/json"
"github.com/go-redis/redis"
"runtime"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"database/sql"
_"github.com/go-sql-driver/mysql"
"math/rand"
)
type User struct {//mysql ile handshake yapmak için user modeli
UserNam... | err := db.Prepare("SELECT app_id FROM app where pub_key = ? AND sub_key = ?")
check(err,"")
err = stmtOut.QueryRow(pubkey,subkey).Scan(&appId)
if appId > 0{
isCheck =appId
}else{
isCheck = -1
}
defer stmtOut.Close()
return
}
func (broker *Broker)subscribeHttpToRedis(w http.ResponseWriter, r *http.Requ... | check(err,"")
err = stmtOut.QueryRow(subkey).Scan(&appId)
if appId > 0{
isCheck =appId
}else{
isCheck = -1
}
defer stmtOut.Close()
return
}
func checkPupKeySubKey(pubkey string,subkey string) (isCheck int) {//handchake yaparken gelen datamızı mysql ile kontrol ediyoruz
var appId int
stmtOut, | identifier_body |
httpProcess.go | package main
import (
"net/http"
"fmt"
"net"
"log"
"strings"
"encoding/json"
"github.com/go-redis/redis"
"runtime"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"database/sql"
_"github.com/go-sql-driver/mysql"
"math/rand"
)
type User struct {//mysql ile handshake yapmak için user modeli
UserNam... | sonStatus(message string, status int, jw http.ResponseWriter) {//Genel Response metodumuz
jw.Header().Set("Content-Type", "application/json")
return_message := &StatusMessage{Message: message, StatusCode: status}
jw.WriteHeader(http.StatusCreated)
json.NewEncoder(jw).Encode(return_message)
}
func ByteToStr(data [... | "onlineUserTokens")
fmt.Println("online Users:",onlieUsers)
onlineUsersCount := client.SCard("onlineUserTokens")
fmt.Println("online users count:",onlineUsersCount)
case s := <-broker.closingClients://Bir client ayrıldı ve mesaj göndermeyi bırakmak istiyoruz
onlieUsers := client.SMembers("onlineUserToke... | conditional_block |
httpProcess.go | package main
import (
"net/http"
"fmt"
"net"
"log"
"strings"
"encoding/json"
"github.com/go-redis/redis"
"runtime"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"database/sql"
_"github.com/go-sql-driver/mysql"
"math/rand"
)
type User struct {//mysql ile handshake yapmak için user modeli
UserNam... | := &StatusMessage{Message: message, StatusCode: status}
jw.WriteHeader(http.StatusCreated)
json.NewEncoder(jw).Encode(return_message)
}
func ByteToStr(data []byte) string{//byte to str
d :=string(data[8:])
d = d[:len(d)-1]
return d
}
func randToken() string {//random token üreten fonksiyon
b := make([]byte, 8)... | rn_message | identifier_name |
httpProcess.go | package main
import (
"net/http"
"fmt"
"net"
"log"
"strings"
"encoding/json"
"github.com/go-redis/redis"
"runtime"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"database/sql"
_"github.com/go-sql-driver/mysql"
"math/rand"
)
type User struct {//mysql ile handshake yapmak için user modeli
UserNam... | check(err,"")
err = stmtOut.QueryRow(userId,c.PubKey,c.SubKey).Scan(&appId)
if appId > 0 {
isCheck = appId
token = randToken()
client.SAdd(c.SubKey[:8],token)
}
}
defer stmtOut.Close()
return
}
func checkSubKey(subkey string) (isCheck int) {//handchake yaparken gelen datamızı mysql ile kontrol ediy... | stmtOut, err := db.Prepare("SELECT app_id FROM app where user_id = ? AND pub_key = ? AND sub_key = ?") | random_line_split |
blocks.go | package labelmap
import (
"bytes"
"compress/gzip"
"encoding/binary"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/janelia-flyem/dvid/datastore"
"github.com/janelia-flyem/dvid/datatype/common/labels"
"github.com/janelia-flyem/dvid/dvid"
"github.com/janelia-flyem/dvid/storage"... |
// getBlockLabels returns a block of labels at given scale in packed little-endian uint64 format.
func (d *Data) getBlockLabels(v dvid.VersionID, bcoord dvid.ChunkPoint3d, scale uint8, supervoxels bool) ([]byte, error) {
block, err := d.getSupervoxelBlock(v, bcoord, scale)
if err != nil {
return nil, err
}
var ... | {
store, err := datastore.GetOrderedKeyValueDB(d)
if err != nil {
return nil, err
}
// Retrieve the block of labels
ctx := datastore.NewVersionedCtx(d, v)
index := dvid.IndexZYX(bcoord)
serialization, err := store.Get(ctx, NewBlockTKey(scale, &index))
if err != nil {
return nil, fmt.Errorf("error getting '... | identifier_body |
blocks.go | package labelmap
import (
"bytes"
"compress/gzip"
"encoding/binary"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/janelia-flyem/dvid/datastore"
"github.com/janelia-flyem/dvid/datatype/common/labels"
"github.com/janelia-flyem/dvid/dvid"
"github.com/janelia-flyem/dvid/storage"... | () string {
var readAvgT, transcodeAvgT, writeAvgT time.Duration
if bt.readN == 0 {
readAvgT = 0
} else {
readAvgT = bt.readT / time.Duration(bt.readN)
}
if bt.transcodeN == 0 {
transcodeAvgT = 0
} else {
transcodeAvgT = bt.transcodeT / time.Duration(bt.transcodeN)
}
if bt.readN == 0 {
writeAvgT = 0
... | String | identifier_name |
blocks.go | package labelmap
import (
"bytes"
"compress/gzip"
"encoding/binary"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/janelia-flyem/dvid/datastore"
"github.com/janelia-flyem/dvid/datatype/common/labels"
"github.com/janelia-flyem/dvid/dvid"
"github.com/janelia-flyem/dvid/storage"... |
// Can only handle 3d requests.
blockSize, okBlockSize := d.BlockSize().(dvid.Point3d)
subvolSize, okSubvolSize := subvol.Size().(dvid.Point3d)
startPt, okStartPt := subvol.StartPoint().(dvid.Point3d)
if !okBlockSize || !okSubvolSize || !okStartPt {
return
}
// Can only handle single block for now.
if subv... | {
return
} | conditional_block |
blocks.go | package labelmap
import (
"bytes"
"compress/gzip"
"encoding/binary"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/janelia-flyem/dvid/datastore"
"github.com/janelia-flyem/dvid/datatype/common/labels"
"github.com/janelia-flyem/dvid/dvid"
"github.com/janelia-flyem/dvid/storage"... | bcoordStr := bcoord.ToIZYXString()
block, err := d.getLabelBlock(ctx, scale, bcoordStr)
if err != nil {
return err
}
if !supervoxels {
mapping, err := getMapping(d, ctx.VersionID())
if err != nil {
return err
}
modifyBlockMapping(ctx.VersionID(), block, mapping)
}
if err := block.WriteLabelVolume(w)... | }
// writes a block of data as uncompressed ZYX uint64 to the writer in streaming fashion, allowing
// for possible termination / error at any point.
func (d *Data) streamRawBlock(ctx *datastore.VersionedCtx, w http.ResponseWriter, bcoord dvid.ChunkPoint3d, scale uint8, supervoxels bool) error { | random_line_split |
external_accounts.go | package db
import (
"context"
"database/sql"
"fmt"
multierror "github.com/hashicorp/go-multierror"
"github.com/keegancsmith/sqlf"
"github.com/sourcegraph/sourcegraph/cmd/frontend/db/dbconn"
"github.com/sourcegraph/sourcegraph/pkg/extsvc"
log15 "gopkg.in/inconshreveable/log15.v2"
)
// userExternalAccountNotFo... |
res, err := dbconn.Global.ExecContext(ctx, "UPDATE user_external_accounts SET deleted_at=now() WHERE id=$1 AND deleted_at IS NULL", id)
if err != nil {
return err
}
nrows, err := res.RowsAffected()
if err != nil {
return err
}
if nrows == 0 {
return userExternalAccountNotFoundError{[]interface{}{id}}
}
... | {
return Mocks.ExternalAccounts.Delete(id)
} | conditional_block |
external_accounts.go | package db
import (
"context"
"database/sql"
"fmt"
multierror "github.com/hashicorp/go-multierror"
"github.com/keegancsmith/sqlf"
"github.com/sourcegraph/sourcegraph/cmd/frontend/db/dbconn"
"github.com/sourcegraph/sourcegraph/pkg/extsvc"
log15 "gopkg.in/inconshreveable/log15.v2"
)
// userExternalAccountNotFo... | (ctx context.Context, serviceType string) error {
// TEMP: Delete all external accounts associated with deleted users. Due to a bug in this
// migration code, it was possible for deleted users to be associated with non-deleted external
// accounts. This caused unexpected behavior in the UI (although did not pose a s... | TmpMigrate | identifier_name |
external_accounts.go | package db
import (
"context"
"database/sql"
"fmt"
multierror "github.com/hashicorp/go-multierror"
"github.com/keegancsmith/sqlf"
"github.com/sourcegraph/sourcegraph/cmd/frontend/db/dbconn"
"github.com/sourcegraph/sourcegraph/pkg/extsvc"
log15 "gopkg.in/inconshreveable/log15.v2"
)
// userExternalAccountNotFo... | return nil, err
}
if len(results) != 1 {
return nil, userExternalAccountNotFoundError{querySuffix.Args()}
}
return results[0], nil
}
func (*userExternalAccounts) listBySQL(ctx context.Context, querySuffix *sqlf.Query) ([]*extsvc.ExternalAccount, error) {
q := sqlf.Sprintf(`SELECT t.id, t.user_id, t.service_ty... | random_line_split | |
external_accounts.go | package db
import (
"context"
"database/sql"
"fmt"
multierror "github.com/hashicorp/go-multierror"
"github.com/keegancsmith/sqlf"
"github.com/sourcegraph/sourcegraph/cmd/frontend/db/dbconn"
"github.com/sourcegraph/sourcegraph/pkg/extsvc"
log15 "gopkg.in/inconshreveable/log15.v2"
)
// userExternalAccountNotFo... |
func (*userExternalAccounts) listBySQL(ctx context.Context, querySuffix *sqlf.Query) ([]*extsvc.ExternalAccount, error) {
q := sqlf.Sprintf(`SELECT t.id, t.user_id, t.service_type, t.service_id, t.client_id, t.account_id, t.auth_data, t.account_data, t.created_at, t.updated_at FROM user_external_accounts t %s`, quer... | {
results, err := s.listBySQL(ctx, querySuffix)
if err != nil {
return nil, err
}
if len(results) != 1 {
return nil, userExternalAccountNotFoundError{querySuffix.Args()}
}
return results[0], nil
} | identifier_body |
smt.rs | use std::sync::Arc;
use anyhow::Result;
use criterion::{criterion_group, BenchmarkId, Criterion, Throughput};
use gw_builtin_binaries::{file_checksum, Resource};
use gw_common::{
blake2b::new_blake2b,
builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID},
registry_address::RegistryAddress,
state::St... | (c: &mut Criterion) {
let config = StoreConfig {
path: "./smt_data/db".parse().unwrap(),
options_file: Some("./smt_data/db.toml".parse().unwrap()),
cache_size: Some(1073741824),
};
let store = Store::open(&config, COLUMNS).unwrap();
let ee = BenchExecutionEnvironment::new_with_ac... | bench_ckb_transfer | identifier_name |
smt.rs | use std::sync::Arc;
use anyhow::Result;
use criterion::{criterion_group, BenchmarkId, Criterion, Throughput};
use gw_builtin_binaries::{file_checksum, Resource};
use gw_common::{
blake2b::new_blake2b,
builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID},
registry_address::RegistryAddress,
state::St... | // meta contract
const META_GENERATOR_PATH: &str =
"../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/meta-contract-generator";
const META_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [1u8; 32];
// sudt contract
const SUDT_GENERATOR_PATH: &str =
"../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/sudt-generat... | random_line_split | |
smt.rs | use std::sync::Arc;
use anyhow::Result;
use criterion::{criterion_group, BenchmarkId, Criterion, Throughput};
use gw_builtin_binaries::{file_checksum, Resource};
use gw_common::{
blake2b::new_blake2b,
builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID},
registry_address::RegistryAddress,
state::St... |
}
struct BenchExecutionEnvironment {
generator: Generator,
chain: BenchChain,
mem_pool_state: MemPoolState,
}
impl BenchExecutionEnvironment {
fn new_with_accounts(store: Store, accounts: u32) -> Self {
let genesis_config = GenesisConfig {
meta_contract_validator_type_hash: META_V... | {
unreachable!("bench chain store")
} | identifier_body |
smt.rs | use std::sync::Arc;
use anyhow::Result;
use criterion::{criterion_group, BenchmarkId, Criterion, Throughput};
use gw_builtin_binaries::{file_checksum, Resource};
use gw_common::{
blake2b::new_blake2b,
builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID},
registry_address::RegistryAddress,
state::St... |
}
let mut db = store.begin_transaction();
db.setup_chain_id(ROLLUP_TYPE_HASH).unwrap();
let (mut db, genesis_state) =
build_genesis_from_store(db, config, Default::default()).unwrap();
let smt = db
.state_smt_with_merkle_state(genesis_state.genesis.raw(... | {
panic!("store genesis already initialized");
} | conditional_block |
run.py | from typing import Any, Callable, ClassVar, Collection, Dict, FrozenSet, \
Hashable, IO, Iterable, Iterator, List, Literal, NewType, Optional, \
Protocol, Sequence, Sequence, Set, Tuple, Type, TypeGuard, TypeVar, Union, \
runtime_checkable, TYPE_CHECKING, no_type_check
import sys
import argparse
import mat... |
def runab13_ajaqb(seed='a '):
run(seed, ltm=['ajaqb'], ab=[ab1, ab3])
def runabs3():
# abs painters with more LTM
run(seed='a ', ltm=['abcde', 'ggggg'], ab=[ab1])
# problem: many sames => many nonadjacent 'same' painters
# therefore 'aaaaa' wins
def runrel():
kw = dict(
seed=... | run(seed='a ', ltm=['ajaqb'], ab=[ab1])
# no reln with j or q | identifier_body |
run.py | from typing import Any, Callable, ClassVar, Collection, Dict, FrozenSet, \
Hashable, IO, Iterable, Iterator, List, Literal, NewType, Optional, \
Protocol, Sequence, Sequence, Set, Tuple, Type, TypeGuard, TypeVar, Union, \
runtime_checkable, TYPE_CHECKING, no_type_check
import sys
import argparse
import mat... |
set_global_param('punishing', pun)
set_global_param('painter_clarity', pcl)
set_global_param('cell_clarity', ccl)
set_log_level(llr)
lo(1, 'LTS\n' + m.lts.state_str())
#lo(1, 'LTS\n' + m.lts.state_str_with_authors())
if rsteps:
set_global_param('allow_ab_initio_painters', abr)
... | for s in ltm:
m.absorb(s, timesteps=asteps) | conditional_block |
run.py | from typing import Any, Callable, ClassVar, Collection, Dict, FrozenSet, \
Hashable, IO, Iterable, Iterator, List, Literal, NewType, Optional, \
Protocol, Sequence, Sequence, Set, Tuple, Type, TypeGuard, TypeVar, Union, \
runtime_checkable, TYPE_CHECKING, no_type_check
import sys
import argparse
import mat... | ():
# abs painters with a different seed
run(seed='m ', ltm=['abcde'], ab=[ab1])
def runabs_ajaqb(**kwargs):
run(seed='a ', ltm=['ajaqb'], ab=[ab1])
# no reln with j or q
def runab13_ajaqb(seed='a '):
run(seed, ltm=['ajaqb'], ab=[ab1, ab3])
def runabs3():
# abs painters with more LTM... | runabs2 | identifier_name |
run.py | from typing import Any, Callable, ClassVar, Collection, Dict, FrozenSet, \
Hashable, IO, Iterable, Iterator, List, Literal, NewType, Optional, \
Protocol, Sequence, Sequence, Set, Tuple, Type, TypeGuard, TypeVar, Union, \
runtime_checkable, TYPE_CHECKING, no_type_check
import sys
import argparse
import mat... | ccl=False,
pcl=False,
pun=False
)
# hoplike_few
# pcl=False => ignore painter clarity
# ccl=False => ignore cell clarity
# TODO rsteps=None => run until all clarities >= 4
# ann=False => no cell annotations
# TODO Collect together some named experiments that show each point in
# sequence. ... | ab=[ab1a],
asteps=30, | random_line_split |
rfc7539_test.go | // test vectors from https://tools.ietf.org/html/rfc7539
package rfc7539_test
import (
"bytes"
"github.com/ascottqqq/rfc7539"
"testing"
)
func TestChaCha20BlockFunction(t *testing.T) {
type testCase struct {
key [32]uint8
counter uint32
nonce [12]uint8
ciphertext []byte
}
plaintext := mak... | uint32(42),
[12]uint8{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x02},
[]byte{0x62, 0xe6, 0x34, 0x7f, 0x95, 0xed, 0x87, 0xa4, 0x5f, 0xfa,
0xe7, 0x42, 0x6f, 0x27, 0xa1, 0xdf, 0x5f, 0xb6, 0x91, 0x10, 0x04,
0x4c, 0x0d, 0x73, 0x11, 0x8e, 0xff, 0xa9, 0x5b, 0x01, 0xe5, 0xcf,
0... | "wabe:\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.",
[32]uint8{0x1c, 0x92, 0x40, 0xa5, 0xeb, 0x55, 0xd3, 0x8a, 0xf3, 0x33,
0x88, 0x86, 0x04, 0xf6, 0xb5, 0xf0, 0x47, 0x39, 0x17, 0xc1, 0x40,
0x2b, 0x80, 0x09, 0x9d, 0xca, 0x5c, 0xbc, 0x20, 0x70, 0x75, 0xc0}, | random_line_split |
rfc7539_test.go | // test vectors from https://tools.ietf.org/html/rfc7539
package rfc7539_test
import (
"bytes"
"github.com/ascottqqq/rfc7539"
"testing"
)
func TestChaCha20BlockFunction(t *testing.T) {
type testCase struct {
key [32]uint8
counter uint32
nonce [12]uint8
ciphertext []byte
}
plaintext := mak... | {
type testCase struct {
plaintext string
key [32]uint8
counter uint32
nonce [12]uint8
ciphertext []byte
}
testCases := [...]testCase{{"Ladies and Gentlemen of the class of '99: " +
"If I could offer you only one tip for the future, sunscreen would be it.",
[32]uint8{0x00, 0x01, 0x02, ... | identifier_body | |
rfc7539_test.go | // test vectors from https://tools.ietf.org/html/rfc7539
package rfc7539_test
import (
"bytes"
"github.com/ascottqqq/rfc7539"
"testing"
)
func TestChaCha20BlockFunction(t *testing.T) {
type testCase struct {
key [32]uint8
counter uint32
nonce [12]uint8
ciphertext []byte
}
plaintext := mak... |
}
}
func TestChaCha20Encryption(t *testing.T) {
type testCase struct {
plaintext string
key [32]uint8
counter uint32
nonce [12]uint8
ciphertext []byte
}
testCases := [...]testCase{{"Ladies and Gentlemen of the class of '99: " +
"If I could offer you only one tip for the future, sunscre... | {
t.Errorf("key: % x\n nonce: % x\n block counter: %d\n "+
"keystream: % x\nexpected: % x", test.key, test.nonce, test.counter,
encrypt, test.ciphertext)
} | conditional_block |
rfc7539_test.go | // test vectors from https://tools.ietf.org/html/rfc7539
package rfc7539_test
import (
"bytes"
"github.com/ascottqqq/rfc7539"
"testing"
)
func TestChaCha20BlockFunction(t *testing.T) {
type testCase struct {
key [32]uint8
counter uint32
nonce [12]uint8
ciphertext []byte
}
plaintext := mak... | (t *testing.T) {
type testCase struct {
plaintext string
key [32]uint8
counter uint32
nonce [12]uint8
ciphertext []byte
}
testCases := [...]testCase{{"Ladies and Gentlemen of the class of '99: " +
"If I could offer you only one tip for the future, sunscreen would be it.",
[32]uint8{0x0... | TestChaCha20Encryption | identifier_name |
stream.rs | // Copyright 2016 Jeffrey Burdges.
//! Sphinx header symmetric cryptographic routines
//!
//! ...
use std::fmt;
use std::ops::Range;
use std::marker::PhantomData;
// use clear_on_drop::ClearOnDrop;
use crypto::mac::Mac;
use crypto::poly1305::Poly1305;
use chacha::ChaCha as ChaCha20;
use keystream::{KeyStream,Seek... | (&self, beta: &[u8]) -> SphinxResult<Gamma> {
if beta.len() != P::BETA_LENGTH as usize {
return Err( SphinxError::InternalError("Beta has the incorrect length for MAC!") );
}
// According to the current API gamma_out lies in a buffer supplied
// by our caller, so no need for... | create_gamma | identifier_name |
stream.rs | // Copyright 2016 Jeffrey Burdges.
//! Sphinx header symmetric cryptographic routines
//!
//! ...
use std::fmt;
use std::ops::Range;
use std::marker::PhantomData;
// use clear_on_drop::ClearOnDrop;
use crypto::mac::Mac;
use crypto::poly1305::Poly1305;
use chacha::ChaCha as ChaCha20;
use keystream::{KeyStream,Seek... |
self.stream.seek_to(self.chunks.surb_log.start as u64).unwrap();
self.stream.xor_read(surb_log).unwrap();
Ok(())
}
/// Sender's sugested delay for this packet.
pub fn delay(&mut self) -> ::std::time::Duration {
use rand::{ChaChaRng, SeedableRng}; // Rng, Rand
let mu... | {
return Err( SphinxError::InternalError("SURB log too long!") );
} | conditional_block |
stream.rs | // Copyright 2016 Jeffrey Burdges.
//! Sphinx header symmetric cryptographic routines
//!
//! ...
use std::fmt;
use std::ops::Range;
use std::marker::PhantomData;
// use clear_on_drop::ClearOnDrop;
use crypto::mac::Mac;
use crypto::poly1305::Poly1305;
use chacha::ChaCha as ChaCha20;
use keystream::{KeyStream,Seek... |
/// Verify the poly1305 MAC `Gamma` given in a Sphinx packet.
///
/// Returns an InvalidMac error if the check fails. Does not
/// verify the lengths of Beta or the SURB.
pub fn verify_gamma(&self, beta: &[u8], gamma_given: &Gamma)
-> SphinxResult<()> {
let gamma_found = self.create... | {
if beta.len() != P::BETA_LENGTH as usize {
return Err( SphinxError::InternalError("Beta has the incorrect length for MAC!") );
}
// According to the current API gamma_out lies in a buffer supplied
// by our caller, so no need for games to zero it here.
let mut gamm... | identifier_body |
stream.rs | // Copyright 2016 Jeffrey Burdges.
//! Sphinx header symmetric cryptographic routines
//!
//! ...
use std::fmt;
use std::ops::Range;
use std::marker::PhantomData;
// use clear_on_drop::ClearOnDrop;
use crypto::mac::Mac;
use crypto::poly1305::Poly1305;
use chacha::ChaCha as ChaCha20;
use keystream::{KeyStream,Seek... | /// Initalize our IETF ChaCha20 stream cipher by invoking
/// `ChaChaKnN::header_cipher` with our paramaters `P: Params`.
pub fn header_cipher(&self) -> SphinxResult<HeaderCipher<P>> {
self.chacha.header_cipher::<P>()
}
}
/// Amount of key stream consumed by `hop()` itself
const HOP_EATS : usi... | }
}
| random_line_split |
client_darwin.go | package debugapi
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"github.com/ks888/tgo/log"
"golang.org/x/sys/unix"
)
// Assumes the packet size is not larger than this.
const (
maxPacketSize = 4096
excBadAccess = syscall.Signal(0x91) ... |
var threadIDs []int
for _, kvInStr := range strings.Split(packet[3:len(packet)-1], ";") {
kvArr := strings.Split(kvInStr, ":")
key, value := kvArr[0], kvArr[1]
if key == "threads" {
for _, threadID := range strings.Split(value, ",") {
threadIDInNum, err := hexToUint64(threadID, false)
if err != nil... | {
log.Debugf("bad memory access: %s", packet)
return Event{}, fmt.Errorf("bad memory access")
} | conditional_block |
client_darwin.go | package debugapi
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"github.com/ks888/tgo/log"
"golang.org/x/sys/unix"
)
// Assumes the packet size is not larger than this.
const (
maxPacketSize = 4096
excBadAccess = syscall.Signal(0x91) ... |
return nil
}
func verifyPacket(packet string) error {
if packet[0:1] != "$" {
return fmt.Errorf("invalid head data: %v", packet[0])
}
if packet[len(packet)-3:len(packet)-2] != "#" {
return fmt.Errorf("invalid tail data: %v", packet[len(packet)-3])
}
body := packet[1 : len(packet)-3]
bodyChecksum := strco... | } else if c.buffer[0] != '+' {
return errors.New("failed to receive ack")
} | random_line_split |
client_darwin.go | package debugapi
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"github.com/ks888/tgo/log"
"golang.org/x/sys/unix"
)
// Assumes the packet size is not larger than this.
const (
maxPacketSize = 4096
excBadAccess = syscall.Signal(0x91) ... | (data string) []string {
replies := strings.Split(data, "$")
for i, reply := range replies {
if reply[len(reply)-3] == '#' {
replies[i] = reply[0 : len(reply)-3]
}
}
return replies
}
func (c *Client) processOutputPacket(stopReplies []string) ([]string, error) {
var unprocessedReplies []string
for _, stopR... | buildStopReplies | identifier_name |
client_darwin.go | package debugapi
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"github.com/ks888/tgo/log"
"golang.org/x/sys/unix"
)
// Assumes the packet size is not larger than this.
const (
maxPacketSize = 4096
excBadAccess = syscall.Signal(0x91) ... |
func (c *Client) handleWPacket(packet string) (Event, error) {
exitStatus, err := hexToUint64(packet[1:3], false)
return Event{Type: EventTypeExited, Data: int(exitStatus)}, err
}
func (c *Client) handleXPacket(packet string) (Event, error) {
signalNumber, err := hexToUint64(packet[1:3], false)
// TODO: signalNu... | {
command := fmt.Sprintf("qThreadStopInfo%02x", threadID)
if err := c.send(command); err != nil {
return "", err
}
data, err := c.receive()
if err != nil {
return "", err
} else if strings.HasPrefix(data, "E") {
return data, fmt.Errorf("error response: %s", data)
}
return data, nil
} | identifier_body |
router.go | package atreugo
import (
"net/http"
"sort"
"strings"
fastrouter "github.com/fasthttp/router"
gstrings "github.com/savsgio/gotils/strings"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
)
func defaultErrorView(ctx *RequestCtx, err error, statusCode int) {
ctx.Error(err.Error(), st... |
return path
}
func (r *Router) handler(fn View, middle Middlewares) fasthttp.RequestHandler {
middle = r.buildMiddlewares(middle)
chain := make([]Middleware, 0)
chain = append(chain, middle.Before...)
chain = append(chain, func(ctx *RequestCtx) error {
if !ctx.skipView {
if err := fn(ctx); err != nil {
... | {
path = r.parent.getGroupFullPath(r.prefix + path)
} | conditional_block |
router.go | package atreugo
import (
"net/http"
"sort"
"strings"
fastrouter "github.com/fasthttp/router"
gstrings "github.com/savsgio/gotils/strings"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
)
func defaultErrorView(ctx *RequestCtx, err error, statusCode int) {
ctx.Error(err.Error(), st... | (path string) *Router {
groupFunc := r.router.Group
if r.group != nil {
groupFunc = r.group.Group
}
return &Router{
parent: r,
router: r.router,
routerMutable: r.routerMutable,
errorView: r.errorView,
prefix: path,
group: groupFunc(path),
handleOPTIONS: r.handleOPTI... | NewGroupPath | identifier_name |
router.go | package atreugo
import (
"net/http"
"sort"
"strings"
fastrouter "github.com/fasthttp/router"
gstrings "github.com/savsgio/gotils/strings"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
)
func defaultErrorView(ctx *RequestCtx, err error, statusCode int) {
ctx.Error(err.Error(), st... | // Middlewares defines the middlewares (before, after and skip) in the order in which you want to execute them
// for the view or group
//
// WARNING: The previous middlewares configuration could be overridden.
func (r *Router) Middlewares(middlewares Middlewares) *Router {
r.middlewares = middlewares
return r
}
//... | }
| random_line_split |
router.go | package atreugo
import (
"net/http"
"sort"
"strings"
fastrouter "github.com/fasthttp/router"
gstrings "github.com/savsgio/gotils/strings"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
)
func defaultErrorView(ctx *RequestCtx, err error, statusCode int) {
ctx.Error(err.Error(), st... |
func (r *Router) buildMiddlewares(m Middlewares) Middlewares {
m2 := Middlewares{}
m2.Before = append(m2.Before, r.middlewares.Before...)
m2.Before = append(m2.Before, m.Before...)
m2.After = append(m2.After, m.After...)
m2.After = append(m2.After, r.middlewares.After...)
m2.Skip = append(m2.Skip, m.Skip...)
... | {
if v != r.routerMutable {
r.routerMutable = v
r.router.Mutable(v)
}
} | identifier_body |
ciao-vendor.go | //
// Copyright (c) 2016 Intel Corporation
//
// 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... |
err = json.Unmarshal(d, &repos)
if err != nil {
return fmt.Errorf("Unable to unmarshall %s : %v", packageFile, err)
}
return nil
}
func writeRepos(projectRoot string) error {
packageFile := path.Join(projectRoot, "packages.json")
d, err := json.MarshalIndent(&repos, "", "\t")
if err != nil {
return fmt.... | {
if !os.IsNotExist(err) {
return fmt.Errorf("Unable to read %s : %v", packageFile, err)
}
return nil
} | conditional_block |
ciao-vendor.go | //
// Copyright (c) 2016 Intel Corporation
//
// 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... | (cwd, sourceRoot, projectRoot, repo string, ri repoInfo) error {
_, ok := repos[repo]
if ok {
return fmt.Errorf("%s is already vendored", repo)
}
repos[repo] = ri
if err := writeRepos(cwd); err != nil {
return err
}
return vendor(cwd, projectRoot, sourceRoot)
}
func unvendor(cwd, sourceRoot, projectRoot, ... | vendorNew | identifier_name |
ciao-vendor.go | //
// Copyright (c) 2016 Intel Corporation
//
// 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... | }
return clientMap
}
func verify(deps piList, vendorRoot string) ([]string, []string, []string, []string) {
uninstalled := make([]string, 0, 128)
missing := make([]string, 0, 128)
notVendored := make([]string, 0, 128)
notUsed := make([]string, 0, 128)
reposUsed := make(map[string]struct{})
depLoop:
for _, d :... | for _, p := range packages {
clientMap[p.name] = usedBy(p.name, packages, depsMap) | random_line_split |
ciao-vendor.go | //
// Copyright (c) 2016 Intel Corporation
//
// 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... |
func computeClients(packages piList) map[string]string {
depsMap := depsByPackage(packages)
clientMap := make(map[string]string)
for _, p := range packages {
clientMap[p.name] = usedBy(p.name, packages, depsMap)
}
return clientMap
}
func verify(deps piList, vendorRoot string) ([]string, []string, []string, []... | {
depsMap := make(map[string][]string)
depsCh := make(chan packageDeps)
for _, p := range packages {
go func(p string) {
var output bytes.Buffer
cmd := exec.Command("go", "list", "-f", listTemplate, p)
cmd.Stdout = &output
err := cmd.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to call g... | identifier_body |
newtoon.py | import os
import re
import sys
from textwrap import wrap
import zipfile
from contextlib import asynccontextmanager
from datetime import datetime
from io import BytesIO
from typing import Any, AsyncGenerator, Coroutine, Dict, List, Optional, Tuple, Union, Type, Callable
import asyncio
import aiohttp
from asyncio_pool i... | filename = f'{index:03}.jpg'
yield filename, url
def _progress(self) -> None:
self.log('.', end='')
def _start_pull(self) -> None:
self.log(f'{self.name}: ', end='')
def _no_content(self) -> None:
self.log('No content')
def log(self, *args, **kwargs) -... | random_line_split | |
newtoon.py | import os
import re
import sys
from textwrap import wrap
import zipfile
from contextlib import asynccontextmanager
from datetime import datetime
from io import BytesIO
from typing import Any, AsyncGenerator, Coroutine, Dict, List, Optional, Tuple, Union, Type, Callable
import asyncio
import aiohttp
from asyncio_pool i... |
def __lt__(self, other: "Chapter") -> bool:
return self.episode < other.episode
def __eq__(self, other: "Chapter") -> bool:
return self.episode == other.episode
class ToonManager(QuerySet):
async def leech(self, pool_size: int = 1, driver: Optional[uc.Chrome] = None) -> None:
# ... | return self.episode > other.episode | identifier_body |
newtoon.py | import os
import re
import sys
from textwrap import wrap
import zipfile
from contextlib import asynccontextmanager
from datetime import datetime
from io import BytesIO
from typing import Any, AsyncGenerator, Coroutine, Dict, List, Optional, Tuple, Union, Type, Callable
import asyncio
import aiohttp
from asyncio_pool i... |
options.add_argument('--disable-gpu')
options.add_argument('--no-first-run --no-service-autorun --password-store=basic')
extenssions_paths = [
'/usr/lib/ublock-origin'
]
for extenssion in extenssions_paths:
options.add_argument(f'--load-extension={extenss... | options.headless = True
options.add_argument('--headless') | conditional_block |
newtoon.py | import os
import re
import sys
from textwrap import wrap
import zipfile
from contextlib import asynccontextmanager
from datetime import datetime
from io import BytesIO
from typing import Any, AsyncGenerator, Coroutine, Dict, List, Optional, Tuple, Union, Type, Callable
import asyncio
import aiohttp
from asyncio_pool i... | (QuerySet):
async def leech(self, pool_size: int = 1, driver: Optional[uc.Chrome] = None) -> None:
# we want to iterate over all toons that are not explictly finished.
async for toon in self.filter(Q(finished=False) | Q(finished__exists=False)):
# if this can have a driver
if... | ToonManager | identifier_name |
overlay.js | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
... | /* Add a listener for changed message */
gMessageListeners.push({
onStartHeaders: function() {
var msg = gMessageDisplay.displayedMessage;
if(!msg) return;
var folder = msg.folder;
if(tbParanoia.paranoiaIsFeedFolder(folder)) return;
var offset = new Object();
var messageSize = ... | },
init: function() {
// http://stackoverflow.com/questions/5089405/thunderbird-extension-add-field-to-messagepane-how-to-deal-with-windows-instan | random_line_split |
cassandraMetadataPersistence.go | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | `config.archival_bucket, config.archival_status, ` +
`config.history_archival_status, config.history_archival_uri, ` +
`config.visibility_archival_status, config.visibility_archival_uri, ` +
`config.bad_binaries, config.bad_binaries_encoding, ` +
`replication_config.active_cluster_name, replication_config.clu... |
templateGetDomainByNameQuery = `SELECT domain.id, domain.name, domain.status, domain.description, ` +
`domain.owner_email, domain.data, config.retention, config.emit_metric, ` + | random_line_split |
cassandraMetadataPersistence.go | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | (request *p.ListDomainsRequest) (*p.InternalListDomainsResponse, error) {
panic("cassandraMetadataPersistence do not support list domain operation.")
}
func (m *cassandraMetadataPersistence) GetMetadata() (*p.GetMetadataResponse, error) {
panic("cassandraMetadataPersistence do not support get metadata operation.")
}... | ListDomains | identifier_name |
cassandraMetadataPersistence.go | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... |
return err
}
return m.deleteDomain(request.Name, ID)
}
func (m *cassandraMetadataPersistence) ListDomains(request *p.ListDomainsRequest) (*p.InternalListDomainsResponse, error) {
panic("cassandraMetadataPersistence do not support list domain operation.")
}
func (m *cassandraMetadataPersistence) GetMetadata() (*... | {
return nil
} | conditional_block |
cassandraMetadataPersistence.go | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... |
func (m *cassandraMetadataPersistence) DeleteDomain(request *p.DeleteDomainRequest) error {
var name string
query := m.session.Query(templateGetDomainQuery, request.ID)
err := query.Scan(&name)
if err != nil {
if err == gocql.ErrNotFound {
return nil
}
return err
}
return m.deleteDomain(name, request.... | {
var nextVersion int64 = 1
var currentVersion *int64
if request.NotificationVersion > 0 {
nextVersion = request.NotificationVersion + 1
currentVersion = &request.NotificationVersion
}
query := m.session.Query(templateUpdateDomainByNameQuery,
request.Info.ID,
request.Info.Name,
request.Info.Status,
req... | identifier_body |
bikeshareproject.py | ### ******************************************** Project Assignment on " Explore US Bikeshare Data " ***************************************************************
import time
import datetime
import pandas as pd
import statistics as st
##All the include Filenames
#1.chicago = 'chicago.csv'
#2.new_york_city = 'new_y... | (city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "a... | load_data | identifier_name |
bikeshareproject.py | ### ******************************************** Project Assignment on " Explore US Bikeshare Data " ***************************************************************
import time
import datetime
import pandas as pd
import statistics as st
##All the include Filenames
#1.chicago = 'chicago.csv'
#2.new_york_city = 'new_y... |
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\n******************** Calculating Trip Duration... *********************\n')
start_time = time.time()
# display total travel time
total_travel_time = df['Trip Duration'].sum()
time1... | print('-'*40)
| random_line_split |
bikeshareproject.py | ### ******************************************** Project Assignment on " Explore US Bikeshare Data " ***************************************************************
import time
import datetime
import pandas as pd
import statistics as st
##All the include Filenames
#1.chicago = 'chicago.csv'
#2.new_york_city = 'new_y... |
else:
city = input('Sorry, I do not understand your input. Please input either '
'Chicago, New York, or Washington.\n(Enter Correct city):\t ').lower()
#lower() command is used to take input of any type formate
# TO DO: get user input for month (all, januar... | break | conditional_block |
bikeshareproject.py | ### ******************************************** Project Assignment on " Explore US Bikeshare Data " ***************************************************************
import time
import datetime
import pandas as pd
import statistics as st
##All the include Filenames
#1.chicago = 'chicago.csv'
#2.new_york_city = 'new_y... |
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df, month, day)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
restart = input('\n******************** Would you like to restart? Enter yes or... | """Displays statistics on bikeshare users."""
print('\n******************** Calculating User Stats... *********************\n')
start_time = time.time()
# Display counts of user types
no_of_subscribing_user = df['User Type'].str.count('Subscriber').sum()
no_of_customers_using = df['User T... | identifier_body |
bparser.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Original source: github.com/okfn/bibserver
# Authors:
# markmacgillivray
# Etienne Posthumus (epoz)
# Francois Boulogne <fboulogne at april dot org>
import sys
import logging
import io
import re
from bibtexparser.bibdatabase import BibDatabase
logger = logging.getLogge... | (object):
"""
A parser for reading BibTeX bibliographic data files.
Example::
from bibtexparser.bparser import BibTexParser
bibtex_str = ...
parser = BibTexParser()
parser.ignore_nonstandard_types = False
parser.homogenise_fields = False
bib_database = bib... | BibTexParser | identifier_name |
bparser.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Original source: github.com/okfn/bibserver
# Authors:
# markmacgillivray
# Etienne Posthumus (epoz)
# Francois Boulogne <fboulogne at april dot org>
import sys
import logging
import io
import re
from bibtexparser.bibdatabase import BibDatabase
logger = logging.getLogge... |
def _string_subst(self, val):
""" Substitute string definitions
:param val: a value
:type val: string
:returns: string -- value
"""
logger.debug('Substitute string definitions')
if not val:
return ''
for k in list(self.bib_database.strin... | cnt = 0
for i in range(0, len(val)):
if val[i] == '{':
cnt += 1
elif val[i] == '}':
cnt -= 1
if cnt == 0:
break
if i == len(val) - 1:
return True
else:
... | identifier_body |
bparser.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Original source: github.com/okfn/bibserver
# Authors:
# markmacgillivray
# Etienne Posthumus (epoz)
# Francois Boulogne <fboulogne at april dot org>
import sys
import logging
import io
import re
from bibtexparser.bibdatabase import BibDatabase
logger = logging.getLogge... |
if i == len(val) - 1:
return True
else:
return False
def _string_subst(self, val):
""" Substitute string definitions
:param val: a value
:type val: string
:returns: string -- value
"""
logger.debug('Substitute string ... | if val[i] == '{':
cnt += 1
elif val[i] == '}':
cnt -= 1
if cnt == 0:
break | conditional_block |
bparser.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Original source: github.com/okfn/bibserver
# Authors:
# markmacgillivray
# Etienne Posthumus (epoz)
# Francois Boulogne <fboulogne at april dot org>
import sys
import logging
import io
import re
from bibtexparser.bibdatabase import BibDatabase
logger = logging.getLogge... | elif inkey:
logger.debug('Continues the previous line to complete the key pair value...')
# if this line continues the value from a previous line, append
inval += ', ' + kv
# if it looks like this line finishes the value, store it and clear for... | else:
logger.debug('The line is the end of the record.')
d[key] = self._add_val(val) | random_line_split |
fill_data.py | # -*- coding: utf-8 -*-
'''
Toda la informacion de un fichero
'''
import urllib, re
from flask import g, Markup
from flask.ext.babelex import gettext as _
from urlparse import urlparse
from itertools import izip_longest, chain
from foofind.services import *
from foofind.blueprints.files.helpers import *
from foofi... | (file_data, ntts=[]):
'''
Inicializa el diccionario de datos del archivo
'''
content_fixes(file_data)
file_data["id"]=mid2url(file_data['_id'])
file_data['name']=file_data['src'].itervalues().next()['url']
file_se = file_data["se"] if "se" in file_data else None
ntt = ntts[int(float(fil... | init_data | identifier_name |
fill_data.py | # -*- coding: utf-8 -*-
'''
Toda la informacion de un fichero
'''
import urllib, re
from flask import g, Markup
from flask.ext.babelex import gettext as _
from urlparse import urlparse
from itertools import izip_longest, chain
from foofind.services import *
from foofind.blueprints.files.helpers import *
from foofi... | def choose_file_type(f):
'''
Elige el tipo de archivo
'''
ct, file_tags, file_format = guess_doc_content_type(f["file"], g.sources)
f['view']["ct"] = ct
f['view']['file_type'] = CONTENTS[ct].lower()
f['view']["tags"] = file_tags
if file_format: f['view']['format'] = file_format
def get_... | ''
Construye los enlaces correctamente
'''
def get_domain(src):
'''
Devuelve el dominio de una URL
'''
url_parts=urlparse(src).netloc.split('.')
i=len(url_parts)-1
if len(url_parts[i])<=2 and len(url_parts[i-1])<=3:
return url_parts[i-2]+'.'+url_pa... | identifier_body |
fill_data.py | # -*- coding: utf-8 -*-
'''
Toda la informacion de un fichero
'''
import urllib, re
from flask import g, Markup
from flask.ext.babelex import gettext as _
from urlparse import urlparse
from itertools import izip_longest, chain
from foofind.services import *
from foofind.blueprints.files.helpers import *
from foofi... | # Metadatos multimedia
try:
#extraccion del codec de video y/o audio
if "video_codec" in file_md: #si hay video_codec se concatena el audio_codec detras si es necesario
view_md["codec"]=file_md["video_codec"]+" "+file_md["audio_codec"] if "audio_codec" in file_md else fi... | s = {}
for path, size in izip_longest(u(file_md["filepaths"]).split("///"), u(file_md.get("filesizes","")).split(" "), fillvalue=None):
# no permite tamaños sin fichero
if not path: break
parts = path.strip("/").split("/")
# crea subdirectorio... | conditional_block |
fill_data.py | # -*- coding: utf-8 -*-
'''
Toda la informacion de un fichero
'''
import urllib, re
from flask import g, Markup
from flask.ext.babelex import gettext as _
from urlparse import urlparse
from itertools import izip_longest, chain
from foofind.services import *
from foofind.blueprints.files.helpers import *
from foofi... | value = adict[key]
if isinstance(value, (int,long)):
return value
elif isinstance(value, float):
return int(value)
elif isinstance(value, basestring):
result = None
for c in value:
digit = ord(c)-48
if 0<=digit<=9:
if result:
... | random_line_split | |
main.rs | use crate::avro_encode::encode;
use avro_rs::schema::{RecordField, Schema, SchemaFingerprint, UnionSchema};
use avro_rs::types::Value;
use avro_rs::{from_value, types::Record, Codec, Reader, Writer};
use clap::{App, Arg};
use failure::bail;
use failure::Error;
use futures::StreamExt;
use futures_util::future::FutureExt... |
fn deserialize(bytes: &Vec<u8>) -> Result<String, Error> {
let schema = get_schema();
let out = match avro_rs::Reader::with_schema(&schema, &bytes[..]) {
Ok(reader) => {
let value = reader.map(|v| format!("{:?}", v)).collect::<Vec<String>>();
// let value =
// ... | {
let schema = get_schema();
let mut writer = Writer::new(&schema, Vec::new());
let record = Value::Record(vec![
(
"before".to_string(),
Value::Union(Box::new(Value::Record(vec![
("FirstName".to_string(), Value::String("Greg".to_string())),
("... | identifier_body |
main.rs | use crate::avro_encode::encode;
use avro_rs::schema::{RecordField, Schema, SchemaFingerprint, UnionSchema};
use avro_rs::types::Value;
use avro_rs::{from_value, types::Record, Codec, Reader, Writer};
use clap::{App, Arg};
use failure::bail;
use failure::Error;
use futures::StreamExt;
use futures_util::future::FutureExt... | () {
let matches = App::new("consumer example")
.version(option_env!("CARGO_PKG_VERSION").unwrap_or(""))
.about("Simple command line consumer")
.arg(
Arg::with_name("brokers")
.short("b")
.long("brokers")
.help("Broker list in kafka... | main | identifier_name |
main.rs | use crate::avro_encode::encode;
use avro_rs::schema::{RecordField, Schema, SchemaFingerprint, UnionSchema};
use avro_rs::types::Value;
use avro_rs::{from_value, types::Record, Codec, Reader, Writer};
use clap::{App, Arg};
use failure::bail;
use failure::Error;
use futures::StreamExt;
use futures_util::future::FutureExt... | let input = writer.into_inner();
//add header info: '01111'
// required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394
let body = [b'O', b'1', b'1', b'1', b'1'].to_vec();
let output = [&body[..], &input[..]].concat();
Ok(output)
}
fn serialize2() -... | random_line_split | |
logg.go | package log
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/gookit/color"
uberatomic "go.uber.org/atomic"
)
const (
_Off = iota
_Fatal
_Error
_Chek
_Warn
_Info
_Debug
_Trace
)
type (
// LevelPrinter def... |
func Caller(comment string, skip int) string {
_, file, line, _ := runtime.Caller(skip + 1)
o := fmt.Sprintf("%s: %s:%d", comment, file, line)
// L.Debug(o)
return o
} | return e == nil
} | random_line_split |
logg.go | package log
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/gookit/color"
uberatomic "go.uber.org/atomic"
)
const (
_Off = iota
_Fatal
_Error
_Chek
_Warn
_Info
_Debug
_Trace
)
type (
// LevelPrinter def... | (hl string) struct{} {
_logFilterMx.Lock()
logFilter[hl] = struct{}{}
_logFilterMx.Unlock()
return struct{}{}
}
func getTimeText(level int32) string {
// since := time.Now().Sub(logger_started).Round(time.Millisecond).String()
// diff := 12 - len(since)
// if diff > 0 {
// since = strings.Repeat(" ", diff) + ... | AddFilteredSubsystem | identifier_name |
logg.go | package log
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/gookit/color"
uberatomic "go.uber.org/atomic"
)
const (
_Off = iota
_Fatal
_Error
_Chek
_Warn
_Info
_Debug
_Trace
)
type (
// LevelPrinter def... |
// joinStrings constructs a string from an slice of interface same as Println but
// without the terminal newline
func joinStrings(sep string, a ...interface{}) (o string) {
for i := range a {
o += fmt.Sprint(a[i])
if i < len(a)-1 {
o += sep
}
}
return
}
// getLoc calls runtime.Caller and formats as expe... | {
return func(e error) bool {
if level <= currentLevel.Load() && !_isSubsystemFiltered(subsystem) {
if e != nil {
printer := fmt.Sprintf
if _isHighlighted(subsystem) {
printer = color.Bold.Sprintf
}
fmt.Fprintf(
writer,
printer(
"%-58v%s%s%-6v %s\n",
getLoc(2, level, sub... | identifier_body |
logg.go | package log
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/gookit/color"
uberatomic "go.uber.org/atomic"
)
const (
_Off = iota
_Fatal
_Error
_Chek
_Warn
_Info
_Debug
_Trace
)
type (
// LevelPrinter def... |
var fileWriter *os.File
if fileWriter, e = os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC,
0600); e != nil {
fmt.Fprintln(os.Stderr, "unable to write log to", path, "error:", e)
return
}
mw := io.MultiWriter(os.Stderr, fileWriter)
fileWriter.Write([]byte("logging to file '" + path + "'\n"))
mw.Write([]... | {
var b []byte
b, e = ioutil.ReadFile(path)
if e == nil {
ioutil.WriteFile(path+fmt.Sprint(time.Now().Unix()), b, 0600)
}
} | conditional_block |
cogroup.rs | //! Group records by a key, and apply a reduction function.
//!
//! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records
//! with the same key, and apply user supplied functions to the key and a list of values, which are
//! expected to populate a list of output values.
//!
//!... |
}
// we may need to produce output at index
let mut session = output.session(&index);
// 2b. We must now determine for each interesting key at this time, how does the
// currently reported output match up with what we need as ou... | {
for key in &compact.keys {
stash.push(index.clone());
source2.interesting_times(key, &index, &mut stash);
for time in &stash {
let mut queue = to_do.entry_or_insert((*time).clon... | conditional_block |
cogroup.rs | //! Group records by a key, and apply a reduction function.
//!
//! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records
//! with the same key, and apply user supplied functions to the key and a list of values, which are
//! expected to populate a list of output values.
//!
//!... | if let Some(compact) = compact {
for key in &compact.keys {
stash.push(index.clone());
source2.interesting_times(key, &index, &mut stash);
for time in &stash {
... | vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0))));
Compact::from_radix(&mut vec![vec], &|k| key_h(k))
};
| random_line_split |
cogroup.rs | //! Group records by a key, and apply a reduction function.
//!
//! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records
//! with the same key, and apply user supplied functions to the key and a list of values, which are
//! expected to populate a list of output values.
//!
//!... | <
D: Data,
V2: Data+Default,
V3: Data+Default,
U: Unsigned+Default,
KH: Fn(&K)->U+'static,
Look: Lookup<K, Offset>+'static,
LookG: Fn(u64)->Look,
Logic: Fn(&K, &mut CollectionIterator<V1>, &mut CollectionIterator<V2>, &mut Vec<(V3, i32)>)... | cogroup_by_inner | identifier_name |
cogroup.rs | //! Group records by a key, and apply a reduction function.
//!
//! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records
//! with the same key, and apply user supplied functions to the key and a list of values, which are
//! expected to populate a list of output values.
//!
//!... |
}
| {
let mut source1 = Trace::new(look(0));
let mut source2 = Trace::new(look(0));
let mut result = Trace::new(look(0));
// A map from times to received (key, val, wgt) triples.
let mut inputs1 = Vec::new();
let mut inputs2 = Vec::new();
// A map from times to a l... | identifier_body |
create-cp-input.py | #!/usr/bin/env python3
###################
#
# Creates input to cp-ansible (ksql, connect) & julieops (topic provision)
#
# Author: Venky Narayanan (vnarayanan@confluent.io)
# Date: May 26, 2021
#
###################
from __future__ import print_function
from datetime import datetime
import argparse
from jinja2 imp... | (docs, config_type, override_apikey, override_apisecret):
newdocs = {}
if config_type in docs and CONST_API_KEY in docs[config_type]:
newdocs[CONST_API_KEY] = docs[config_type][CONST_API_KEY]
newdocs[CONST_API_SECRET] = docs[config_type][CONST_API_SECRET]
else:
newdocs[CONST_API_KEY]... | get_api_config | identifier_name |
create-cp-input.py | #!/usr/bin/env python3
###################
#
# Creates input to cp-ansible (ksql, connect) & julieops (topic provision)
#
# Author: Venky Narayanan (vnarayanan@confluent.io)
# Date: May 26, 2021
#
###################
from __future__ import print_function
from datetime import datetime
import argparse | import os
CONST_TIMESTAMP = 'timestamp'
CONST_NAME = 'name'
CONST_PARTITIONS = 'partitions'
CONST_REPLICATION = 'replication'
CONST_OVERRIDE = 'override'
CONST_DEPENDENCIES = 'dependencies'
CONST_KSQL = 'ksql'
CONST_CONNECT = 'connect'
CONST_TOPIC = 'topic'
CONST_TOPICS = 'topics'
CONST_BROKER = 'broker'
CONST_PROVISI... | from jinja2 import Template
import yaml
import json
import logging
import requests | random_line_split |
create-cp-input.py | #!/usr/bin/env python3
###################
#
# Creates input to cp-ansible (ksql, connect) & julieops (topic provision)
#
# Author: Venky Narayanan (vnarayanan@confluent.io)
# Date: May 26, 2021
#
###################
from __future__ import print_function
from datetime import datetime
import argparse
from jinja2 imp... |
# Create cp-ansible yaml with ksql section
def process_ksql (feid, doc):
logging.debug ('-------')
if CONST_PROVISION in doc and doc[CONST_PROVISION] == True:
provision_ksql_hosts (feid, doc[CONST_HOSTS])
provision_ksql_query (feid, doc[CONST_QUERIES])
logging.debug ('-------')
def provi... | hosts = []
for host in doc:
logging.info ('ksql host is ' + host)
hosts.append(host)
inputs_map[CONST_KSQL + '_' + CONST_HOSTS] = hosts | identifier_body |
create-cp-input.py | #!/usr/bin/env python3
###################
#
# Creates input to cp-ansible (ksql, connect) & julieops (topic provision)
#
# Author: Venky Narayanan (vnarayanan@confluent.io)
# Date: May 26, 2021
#
###################
from __future__ import print_function
from datetime import datetime
import argparse
from jinja2 imp... |
return newdocs
def process_ccloud_config (docs):
override_apikey = ""
override_apisecret = ""
if CONST_OVERRIDE in docs[CONST_CREDENTIALS]:
override = docs[CONST_CREDENTIALS][CONST_OVERRIDE]
if CONST_API_KEY in override:
override_apikey = override[CONST_API_KEY]
... | newdocs[CONST_API_KEY] = override_apikey
newdocs[CONST_API_SECRET] = override_apisecret | conditional_block |
mod.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::io;
#... | (&self) -> *const kvm_cpuid2 {
&self.kvm_cpuid[0]
}
/// Get a mutable pointer so it can be passed to the kernel. Using this pointer is unsafe.
///
pub fn as_mut_ptr(&mut self) -> *mut kvm_cpuid2 {
&mut self.kvm_cpuid[0]
}
}
/// Safe wrapper over the `kvm_run` struct.
///
/// The wr... | as_ptr | identifier_name |
mod.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::io;
#... |
Ok(KvmRunWrapper {
kvm_run_ptr: addr as *mut u8,
mmap_size: size,
})
}
/// Returns a mutable reference to `kvm_run`.
///
#[allow(clippy::mut_from_ref)]
pub fn as_mut_ref(&self) -> &mut kvm_run {
// Safe because we know we mapped enough memory to hol... | {
return Err(io::Error::last_os_error());
} | conditional_block |
mod.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::io;
#... |
/// Get a pointer so it can be passed to the kernel. Using this pointer is unsafe.
///
pub fn as_ptr(&self) -> *const kvm_cpuid2 {
&self.kvm_cpuid[0]
}
/// Get a mutable pointer so it can be passed to the kernel. Using this pointer is unsafe.
///
pub fn as_mut_ptr(&mut self) -> *... | {
// Mapping the unsized array to a slice is unsafe because the length isn't known. Using
// the length we originally allocated with eliminates the possibility of overflow.
if self.kvm_cpuid[0].nent as usize > self.allocated_len {
self.kvm_cpuid[0].nent = self.allocated_len as u32;
... | identifier_body |
mod.rs | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::io;
#... |
CpuId {
kvm_cpuid,
allocated_len: entries.len(),
}
}
/// Returns the mutable entries slice so they can be modified before passing to the VCPU.
///
/// # Example
/// ```rust
/// use kvm_ioctls::{CpuId, Kvm, MAX_KVM_CPUID_ENTRIES};
/// let kvm = Kvm::n... | random_line_split | |
file_server.rs | use crate::file_watcher::FileWatcher;
use bytes::Bytes;
use futures::{stream, Future, Sink, Stream};
use glob::{glob, Pattern};
use std::collections::HashMap;
use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::PathBuf;
use std::sync::mpsc::RecvTimeoutError;
use std::time;
use tracing::field;
/// `FileSer... | (
&self,
path: &PathBuf,
buffer: &mut Vec<u8>,
) -> Option<FileFingerprint> {
let i = self.ignored_header_bytes as u64;
let b = self.fingerprint_bytes;
buffer.resize(b, 0u8);
if let Ok(mut fp) = fs::File::open(path) {
if fp.seek(SeekFrom::Start(i))... | get_fingerprint_of_file | identifier_name |
file_server.rs | use crate::file_watcher::FileWatcher;
use bytes::Bytes;
use futures::{stream, Future, Sink, Stream};
use glob::{glob, Pattern};
use std::collections::HashMap;
use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::PathBuf;
use std::sync::mpsc::RecvTimeoutError;
use std::time;
use tracing::field;
/// `FileSer... |
fn get_fingerprint_of_file(
&self,
path: &PathBuf,
buffer: &mut Vec<u8>,
) -> Option<FileFingerprint> {
let i = self.ignored_header_bytes as u64;
let b = self.fingerprint_bytes;
buffer.resize(b, 0u8);
if let Ok(mut fp) = fs::File::open(path) {
... | {
let mut line_buffer = Vec::new();
let mut fingerprint_buffer = Vec::new();
let mut fp_map: HashMap<FileFingerprint, FileWatcher> = Default::default();
let mut backoff_cap: usize = 1;
let mut lines = Vec::new();
let mut start_of_run = true;
// Alright friends, ... | identifier_body |
file_server.rs | use crate::file_watcher::FileWatcher;
use bytes::Bytes;
use futures::{stream, Future, Sink, Stream};
use glob::{glob, Pattern};
use std::collections::HashMap;
use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::PathBuf;
use std::sync::mpsc::RecvTimeoutError;
use std::time;
use tracing::field;
/// `FileSer... |
} else {
// unknown (new) file fingerprint
let read_file_from_beginning = if start_of_run {
self.start_at_beginning
} else {
... | {
// matches a file with a different path
if !was_found_this_cycle {
info!(
message = "Watched file has been renamed.",
... | conditional_block |
file_server.rs | use crate::file_watcher::FileWatcher;
use bytes::Bytes;
use futures::{stream, Future, Sink, Stream};
use glob::{glob, Pattern};
use std::collections::HashMap;
use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::PathBuf;
use std::sync::mpsc::RecvTimeoutError;
use std::time;
use tracing::field;
/// `FileSer... | let mut start_of_run = true;
// Alright friends, how does this work?
//
// We want to avoid burning up users' CPUs. To do this we sleep after
// reading lines out of files. But! We want to be responsive as well. We
// keep track of a 'backoff_cap' to decide how long we'll... | let mut backoff_cap: usize = 1;
let mut lines = Vec::new(); | random_line_split |
BAT.py | #!/usr/bin/env python
import numpy as np
from Scientific.Geometry.Objects3D import Sphere, Cone, Plane, Line, \
rotatePoint
from Scientific.Geometry import Vector
import MMTK
# Vector functions
def normalize(v1):
return v1 / np.sqrt(np.sum(v1 * v1))
def cross(v1, v2):
... | # Write PDB file
# To set Occupancy, change atom.occupancy
# To set Beta, change atom.temperature_factor
import os.path
pdbFN = os.path.join(MMTK.Database.molecule_types.directory,
'showMolecule.pdb')
outF = MMTK.PDB.PDBOutputFile(pdbFN)
outF.write(self.molecule)
... | :param colorBy: color atoms by 'Occupancy', or 'Beta'. None uses default colors.
""" | random_line_split |
BAT.py | #!/usr/bin/env python
import numpy as np
from Scientific.Geometry.Objects3D import Sphere, Cone, Plane, Line, \
rotatePoint
from Scientific.Geometry import Vector
import MMTK
# Vector functions
def normalize(v1):
return v1 / np.sqrt(np.sum(v1 * v1))
def cross(v1, v2):
... |
def BAT(self, XYZ, extended=False):
"""
Conversion from Cartesian to Bond-Angle-Torsion coordinates
:param extended: whether to include external coordinates or not
:param Cartesian: Cartesian coordinates. If None, then the molecules' coordinates will be used
"""
root = [distance(XYZ[self.roo... | """
Indices of the first torsions in the BAT array
"""
offset = 6 if extended else 0
torsionInds = np.array(range(offset + 5, self.natoms * 3, 3))
primaryTorsions = sorted(list(set(self._firstTorsionTInd)))
return list(torsionInds[primaryTorsions]) | identifier_body |
BAT.py | #!/usr/bin/env python
import numpy as np
from Scientific.Geometry.Objects3D import Sphere, Cone, Plane, Line, \
rotatePoint
from Scientific.Geometry import Vector
import MMTK
# Vector functions
def normalize(v1):
return v1 / np.sqrt(np.sum(v1 * v1))
def cross(v1, v2):
... |
return XYZ
for ((a1,a2,a3,a4), bond, angle, torsion) in \
zip(self._torsionIndL,bonds,angles,torsions):
p2 = XYZ[a2]
p3 = XYZ[a3]
p4 = XYZ[a4]
# circle = sphere.intersectWith(cone)
n23 = normalize(p3 - p2)
# points = circle.intersectWith(plane123)
# plane.... | sphere = Sphere(Vector(XYZ[a2]), bond)
cone = Cone(Vector(XYZ[a2]), Vector(XYZ[a3] - XYZ[a2]), angle)
plane123 = Plane(Vector(XYZ[a4]), Vector(XYZ[a3]), Vector(XYZ[a2]))
points = sphere.intersectWith(cone).intersectWith(plane123)
p = points[0] if (Plane(Vector(XYZ[a3]), Vector(
XYZ[a2]),... | conditional_block |
BAT.py | #!/usr/bin/env python
import numpy as np
from Scientific.Geometry.Objects3D import Sphere, Cone, Plane, Line, \
rotatePoint
from Scientific.Geometry import Vector
import MMTK
# Vector functions
def normalize(v1):
return v1 / np.sqrt(np.sum(v1 * v1))
def cross(v1, v2):
... | (self, extended):
"""
Indices of the first torsions in the BAT array
"""
offset = 6 if extended else 0
torsionInds = np.array(range(offset + 5, self.natoms * 3, 3))
primaryTorsions = sorted(list(set(self._firstTorsionTInd)))
return list(torsionInds[primaryTorsions])
def BAT(self, XYZ, ext... | getFirstTorsionInds | identifier_name |
gen_mike_input_rf_linux.py | #!/home/uwcc-admin/curw_mike_data_handler/venv/bin/python3
"only she bang, root dir, output dir and filename are different from generic one"
import pymysql
from datetime import datetime, timedelta
import traceback
import json
import os
import sys
import getopt
import pandas as pd
import numpy as np
DATE_TIME_FORMAT =... | else:
print('Mike rainfall input file already in path : ', mike_rf_file_path)
except Exception:
traceback.print_exc() | print("{} completed preparing mike rainfall input".format(datetime.now()))
print("Mike input rainfall file is available at {}".format(mike_rf_file_path)) | random_line_split |
gen_mike_input_rf_linux.py | #!/home/uwcc-admin/curw_mike_data_handler/venv/bin/python3
"only she bang, root dir, output dir and filename are different from generic one"
import pymysql
from datetime import datetime, timedelta
import traceback
import json
import os
import sys
import getopt
import pandas as pd
import numpy as np
DATE_TIME_FORMAT =... |
if __name__ == "__main__":
set_db_config_file_path(os.path.join(ROOT_DIRECTORY, 'db_adapter_config.json'))
try:
start_time = None
end_time = None
try:
opts, args = getopt.getopt(sys.argv[1:], "h:s:e:",
["help", "start_time=", "end... | usageText = """
Usage: ./inputs/gen_mike_input_rf_linux.py [-s "YYYY-MM-DD HH:MM:SS"] [-e "YYYY-MM-DD HH:MM:SS"]
-h --help Show usage
-s --start_time Mike rainfall timeseries start time (e.g: "2019-06-05 00:00:00"). Default is 00:00:00, 3 days before today.
-e --end_time Mike rainfa... | identifier_body |
gen_mike_input_rf_linux.py | #!/home/uwcc-admin/curw_mike_data_handler/venv/bin/python3
"only she bang, root dir, output dir and filename are different from generic one"
import pymysql
from datetime import datetime, timedelta
import traceback
import json
import os
import sys
import getopt
import pandas as pd
import numpy as np
DATE_TIME_FORMAT =... |
else:
check_time_format(time=end_time)
if output_dir is None:
output_dir = os.path.join(OUTPUT_DIRECTORY, (datetime.utcnow() + timedelta(hours=5, minutes=30)).strftime('%Y-%m-%d_%H-00-00'))
if file_name is None:
file_name = 'mike_rf.txt'.format(start_time, e... | end_time = (datetime.now() + timedelta(days=2)).strftime('%Y-%m-%d 00:00:00') | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.