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 |
|---|---|---|---|---|
response.rs | // rust imports
use std::io::Read;
use std::ffi::OsStr;
use std::path::{PathBuf, Path};
use std::fs::{self, File};
use std::collections::HashMap;
// 3rd-party imports
use rusqlite::Connection;
use rusqlite::types::ToSql;
use hyper::http::h1::HttpReader;
use hyper::buffer::BufReader;
use hyper::net::NetworkStream;
u... | }
}
fn process_multipart<R: Read>(headers: Headers, http_reader: R) -> Option<Multipart<R>> {
let boundary = headers.get::<ContentType>().and_then(|ct| {
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
let ContentType(ref mime) = *ct;
let params = match *mime {
... | }
}
| random_line_split |
common.js |
module.exports = {
// yuming:"http://47.89.18.53:8082",
// onekey:'wancll2',
// yuming:"http://192.168.0.136:8081",
// onekey:"wancll2017072301",
// yuming:"http://120.77.177.87:8082",
// onekey:"wancll2017071902",
// yuming: "http://wancll.55555.io",
// onekey: "wancll2017080701",... | dregcode: function (tel, fun) {
if (tel !== null && tel !== "") {
var code2 = this.getrandom(6);
cc.sys.localStorage.setItem('regcode', code2);
var url = this.yuming + this.regcode;
this.async(url, fun, { "tel": tel, "yzm": code2 });
}
},
//-----... | -----------注册短信(电话,回调函数(返回 json 值))--------------------------------------------
sen | conditional_block |
common.js | module.exports = {
// yuming:"http://47.89.18.53:8082",
// onekey:'wancll2',
// yuming:"http://192.168.0.136:8081",
// onekey:"wancll2017072301",
// yuming:"http://120.77.177.87:8082",
// onekey:"wancll2017071902",
// yuming: "http://wancll.55555.io",
// onekey: "wancll2017080701",
... | // console.log(response);
response = JSON.parse(response);
if (response.msg2 == '非法操作') {
window.url = response.msg3;
cc.director.loadScene('update');
} else {
fun(resp... |
var response = xhr.responseText; | random_line_split |
read_archive.rs | //! read-archive
use backup_cli::storage::{FileHandle, FileHandleRef};
use libra_types::access_path::AccessPath;
use libra_types::account_config::AccountResource;
use libra_types::account_state::AccountState;
use libra_types::write_set::{WriteOp, WriteSetMut};
use move_core_types::move_resource::MoveResource;
use ol_... |
/// Without modifying the data convert an AccountState struct, into a WriteSet Item which can be included in a genesis transaction. This should take all of the resources in the account.
fn get_unmodified_writeset(account_state: &AccountState) -> Result<WriteSetMut, Error> {
let mut ws = WriteSetMut::new(vec![]);
... | {
let mut write_set_mut = WriteSetMut::new(vec![]);
for blob in account_state_blobs {
let account_state = AccountState::try_from(blob)?;
// TODO: borrow
let clean = get_unmodified_writeset(&account_state)?;
let auth = authkey_rotate_change_item(&account_state, get_alice_authkey_f... | identifier_body |
read_archive.rs | //! read-archive
use backup_cli::storage::{FileHandle, FileHandleRef};
use libra_types::access_path::AccessPath;
use libra_types::account_config::AccountResource;
use libra_types::account_state::AccountState;
use libra_types::write_set::{WriteOp, WriteSetMut};
use move_core_types::move_resource::MoveResource;
use ol_... |
fn read_from_file(path: &str) -> Result<Vec<u8>> {
let mut data = Vec::<u8>::new();
let mut f = File::open(path).expect("Unable to open file");
f.read_to_end(&mut data).expect("Unable to read data");
Ok(data)
}
fn read_from_json(path: &PathBuf) -> Result<StateSnapshotBackup> {
let config = std::fs... | } | random_line_split |
read_archive.rs | //! read-archive
use backup_cli::storage::{FileHandle, FileHandleRef};
use libra_types::access_path::AccessPath;
use libra_types::account_config::AccountResource;
use libra_types::account_state::AccountState;
use libra_types::write_set::{WriteOp, WriteSetMut};
use move_core_types::move_resource::MoveResource;
use ol_... |
}
}
}
println!("processed account: {:?}", address);
address_processed = true;
break;
};
if !address_processed {
panic!("Address not found for {} in recovery list", &addres... | {
panic!("MinerStateResource not found");
} | conditional_block |
read_archive.rs | //! read-archive
use backup_cli::storage::{FileHandle, FileHandleRef};
use libra_types::access_path::AccessPath;
use libra_types::account_config::AccountResource;
use libra_types::account_state::AccountState;
use libra_types::write_set::{WriteOp, WriteSetMut};
use move_core_types::move_resource::MoveResource;
use ol_... | (
archive_path: PathBuf,
) -> Result<WriteSetMut, Error> {
let backup = read_from_json(&archive_path)?;
let account_blobs = accounts_from_snapshot_backup(backup, &archive_path).await?;
accounts_into_writeset_swarm(&account_blobs)
}
/// take an archive file path and parse into a writeset
pub async fn ar... | archive_into_swarm_writeset | identifier_name |
manager.go | package monitor
import (
"fmt"
"log"
"os"
"strconv"
"strings"
"sync"
"time"
"domeagent/monitor/container"
"domeagent/monitor/container/docker"
"domeagent/monitor/container/raw"
"domeagent/monitor/events"
"domeagent/monitor/fs"
"domeagent/monitor/info"
"domeagent/monitor/storage"
"domeagent/monitor/stor... |
func (m *manager) DockerInfo() (DockerStatus, error) {
info, err := docker.DockerInfo()
if err != nil {
return DockerStatus{}, err
}
out := DockerStatus{}
out.Version = m.versionInfo.DockerVersion
if val, ok := info["KernelVersion"]; ok {
out.KernelVersion = val
}
if val, ok := info["OperatingSystem"]; ok... | {
self.eventHandler.StopWatch(watch_id)
} | identifier_body |
manager.go | package monitor
import (
"fmt"
"log"
"os"
"strconv"
"strings"
"sync"
"time"
"domeagent/monitor/container"
"domeagent/monitor/container/docker"
"domeagent/monitor/container/raw"
"domeagent/monitor/events"
"domeagent/monitor/fs"
"domeagent/monitor/info"
"domeagent/monitor/storage"
"domeagent/monitor/stor... |
return false
}
func (m *manager) GetMachineInfo() (*info.MachineInfo, error) {
// Copy and return the MachineInfo.
return &m.machineInfo, nil
}
func (m *manager) GetVersionInfo() (*info.VersionInfo, error) {
return &m.versionInfo, nil
}
// can be called by the api which will take events returned on the channel
... | {
return true
} | conditional_block |
manager.go | package monitor
import (
"fmt"
"log"
"os"
"strconv"
"strings"
"sync"
"time"
"domeagent/monitor/container"
"domeagent/monitor/container/docker"
"domeagent/monitor/container/raw"
"domeagent/monitor/events"
"domeagent/monitor/fs"
"domeagent/monitor/info"
"domeagent/monitor/storage"
"domeagent/monitor/stor... | () map[string]*containerData {
self.containersLock.RLock()
defer self.containersLock.RUnlock()
containers := make(map[string]*containerData, len(self.containers))
// Get containers in the Docker namespace.
for name, cont := range self.containers {
if name.Namespace == docker.DockerNamespace {
containers[cont... | getAllDockerContainers | identifier_name |
manager.go | package monitor
import (
"fmt"
"log"
"os"
"strconv"
"strings"
"sync"
"time"
"domeagent/monitor/container"
"domeagent/monitor/container/docker"
"domeagent/monitor/container/raw"
"domeagent/monitor/events"
"domeagent/monitor/fs"
"domeagent/monitor/info"
"domeagent/monitor/storage"
"domeagent/monitor/stor... | }
// Create a container.
func (m *manager) createContainer(containerName string) error {
handler, accept, err := container.NewContainerHandler(containerName, m.inHostNamespace)
if err != nil {
return err
}
if !accept {
// ignoring this container.
log.Printf("[Info] ignoring container %q", containerName)
re... | }()
return nil | random_line_split |
main.go | package main
//necessary imports
import (
"net/http"
"fmt"
"encoding/json"
"context"
"time"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
//error class
type... | (w http.ResponseWriter, r *http.Request){
switch r.Method{
//if method is POST
case "POST":
//disallow query strings with POST method
if keys := r.URL.Query(); len(keys)!=0{
invalid_request(w, 400, "Queries not allowed at this endpoint with this method")
}else{
//... | meets_handler | identifier_name |
main.go | package main
//necessary imports
import (
"net/http"
"fmt"
"encoding/json"
"context"
"time"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
//error class
type... | {
switch r.Method{
case "GET":
//extract meeting id from url
if meet_id := r.URL.Path[len("/meeting/"):]; len(meet_id)==0{
invalid_request(w, 400, "Not a valid Meeting ID")
}else{
//check forvalid id
id, err := primitive.ObjectIDFromHex(meet_id)
... | identifier_body | |
main.go | package main
//necessary imports
import (
"net/http"
"fmt"
"encoding/json"
"context"
"time"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
//error class
type... |
if check1 || check2 || check3 {
final_check =true
}
}
if final_check{
invalid_request(w, 400, "Meeting clashes with other meeting/s with some common participant/s")
}else{
insertRes... | {
check3 = false
} | conditional_block |
main.go | package main
//necessary imports
import (
"net/http"
"fmt"
"encoding/json"
"context"
"time"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
//error class
type... | case 2:
start, okStart := keys["start"]
end, okEnd := keys["end"]
//check both start and end time are provided, else error
if !okStart || !okEnd {invalid_request(w, 400, "Not a valid query at this end point")
}else{
start_time := start[... | json.NewEncoder(w).Encode(my_meets)
} | random_line_split |
column_chunk.go | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | else {
return nil, xerrors.New("cannot decrypt column metadata. file decryption not setup correctly")
}
}
}
for _, enc := range c.columnMeta.Encodings {
c.encodings = append(c.encodings, parquet.Encoding(enc))
}
for _, enc := range c.columnMeta.EncodingStats {
c.encodingStats = append(c.encodingStats,... | {
// should decrypt metadata
path := parquet.ColumnPath(ccmd.ENCRYPTION_WITH_COLUMN_KEY.GetPathInSchema())
keyMetadata := ccmd.ENCRYPTION_WITH_COLUMN_KEY.GetKeyMetadata()
aadColumnMetadata := encryption.CreateModuleAad(fileDecryptor.FileAad(), encryption.ColumnMetaModule, rowGroupOrdinal, columnOrdinal,... | conditional_block |
column_chunk.go | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | () parquet.ColumnPath {
return c.columnMeta.GetPathInSchema()
}
// Compression provides the type of compression used for this particular chunk.
func (c *ColumnChunkMetaData) Compression() compress.Compression {
return compress.Compression(c.columnMeta.Codec)
}
// Encodings returns the list of different encodings us... | PathInSchema | identifier_name |
column_chunk.go | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | // encrypted and how to decrypt it.
func (c *ColumnChunkMetaData) CryptoMetadata() *format.ColumnCryptoMetaData {
return c.column.GetCryptoMetadata()
}
// FileOffset is the location in the file where the column data begins
func (c *ColumnChunkMetaData) FileOffset() int64 { return c.column.FileOffset }
// FilePath gi... |
// CryptoMetadata returns the cryptographic metadata for how this column was | random_line_split |
column_chunk.go | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
// CryptoMetadata returns the cryptographic metadata for how this column was
// encrypted and how to decrypt it.
func (c *ColumnChunkMetaData) CryptoMetadata() *format.ColumnCryptoMetaData {
return c.column.GetCryptoMetadata()
}
// FileOffset is the location in the file where the column data begins
func (c *ColumnC... | {
c := &ColumnChunkMetaData{
column: column,
columnMeta: column.GetMetaData(),
descr: descr,
writerVersion: writerVersion,
mem: memory.DefaultAllocator,
}
if column.IsSetCryptoMetadata() {
ccmd := column.CryptoMetadata
if ccmd.IsSetENCRYPTION_WITH_COLUMN_KEY() {
if fileD... | identifier_body |
store.go | // Copyright 2019 Matt Layher
// 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... | (t *testing.T, s wgipam.Store) {
t.Helper()
// An IPv6 address cannot possibly reside in an IPv4 subnet.
if _, err := s.AllocateIP(okSubnet4, okIP6); err == nil {
t.Fatal("expected mismatched subnet error, but none occurred")
}
}
func testAllocateIPNoSubnet(t *testing.T, s wgipam.Store) {
t.Helper()
if _, er... | testAllocateIPMismatchedSubnet | identifier_name |
store.go | // Copyright 2019 Matt Layher
// 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... |
if diff := cmp.Diff([]*net.IPNet{want.IPs[0]}, ip4s); diff != "" {
t.Fatalf("unexpected remaining IPv4 allocation (-want +got):\n%s", diff)
}
ip6s, err := s.AllocatedIPs(okSubnet6)
if err != nil {
t.Fatalf("failed to get allocated IPv6s: %v", err)
}
if diff := cmp.Diff([]*net.IPNet{want.IPs[1]}, ip6s); di... | {
t.Fatalf("failed to get allocated IPv4s: %v", err)
} | conditional_block |
store.go | // Copyright 2019 Matt Layher
// 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 testSubnetsEmpty(t *testing.T, s wgipam.Store) {
t.Helper()
subnets, err := s.Subnets()
if err != nil {
t.Fatalf("failed to get subnets: %v", err)
}
if diff := cmp.Diff(0, len(subnets)); diff != "" {
t.Fatalf("unexpected number of subnets (-want +got):\n%s", diff)
}
}
func testSubnetsOK(t *testing.T,... | {
t.Helper()
if err := s.SaveSubnet(okSubnet4); err != nil {
t.Fatalf("failed to save subnet: %v", err)
}
ipa, err := wgipam.DualStackIPAllocator(s, []wgipam.Subnet{
{Subnet: *okSubnet4},
{Subnet: *okSubnet6},
})
if err != nil {
t.Fatalf("failed to create IP allocator: %v", err)
}
// Leases start eve... | identifier_body |
store.go | // Copyright 2019 Matt Layher
// 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... | },
{
name: "subnets OK",
fn: testSubnetsOK,
},
{
name: "allocated IPs no subnet",
fn: testAllocatedIPsNoSubnet,
},
{
name: "allocate IP mismatched subnet",
fn: testAllocateIPMismatchedSubnet,
},
{
name: "allocate IP no subnet",
fn: testAllocateIPNoSubnet,
},
{
name... | fn: testPurgeOK,
},
{
name: "subnets empty",
fn: testSubnetsEmpty, | random_line_split |
chat_template.js | 'use strict';
const util = require('util');
const EventEmitter = require('events').EventEmitter;
const WebSocket = require('ws');
const ircRegex = /^(?:@([^ ]+) )?(?:[:](\S+) )?(\S+)(?: (?!:)(.+?))?(?: [:](.+))?$/;
const tagsRegex = /([^=;]+)=([^;]*)/g;
const badgesRegex = /([^,\/]+)\/([^,]*)/g;
const emotesRegex = ... |
case 'NOTICE':
// General notices about Twitch/rooms you are in
// https://dev.twitch.tv/docs/irc/commands#notice-twitch-commands
// moderationy stuff
case 'CLEARCHAT':
// A users message is to be removed
... | {
if (payload.tags.hasOwnProperty('msg-id')) {
this.emit(
`usernotice_${payload.tags['msg-id']}`,
payload
);
}
} | conditional_block |
chat_template.js | 'use strict';
const util = require('util');
const EventEmitter = require('events').EventEmitter;
const WebSocket = require('ws');
const ircRegex = /^(?:@([^ ]+) )?(?:[:](\S+) )?(\S+)(?: (?!:)(.+?))?(?: [:](.+))?$/;
const tagsRegex = /([^=;]+)=([^;]*)/g;
const badgesRegex = /([^,\/]+)\/([^,]*)/g;
const emotesRegex = ... |
default:
console.log('No Process', payload.command, payload);
}
}
}
login = function(username, user_token, rooms) {
this.ws.send(`PASS oauth:${user_token}`);
this.ws.send(`NICK ${username}`);
if (typeof rooms == 'undefined') {
... | // close the socket and let the close handler grab it
this.ws.close();
break; | random_line_split |
chat_template.js | 'use strict';
const util = require('util');
const EventEmitter = require('events').EventEmitter;
const WebSocket = require('ws');
const ircRegex = /^(?:@([^ ]+) )?(?:[:](\S+) )?(\S+)(?: (?!:)(.+?))?(?: [:](.+))?$/;
const tagsRegex = /([^=;]+)=([^;]*)/g;
const badgesRegex = /([^,\/]+)\/([^,]*)/g;
const emotesRegex = ... | () {
console.log('Got Error');
// reconnect
this.emit('close');
if (this.reconnect) {
console.log('Reconnecting');
this._reconnect();
}
}
_onClose() {
console.log('Got Close');
// reconnect
this.emit('close');
if (... | _onError | identifier_name |
chat_template.js | 'use strict';
const util = require('util');
const EventEmitter = require('events').EventEmitter;
const WebSocket = require('ws');
const ircRegex = /^(?:@([^ ]+) )?(?:[:](\S+) )?(\S+)(?: (?!:)(.+?))?(?: [:](.+))?$/;
const tagsRegex = /([^=;]+)=([^;]*)/g;
const badgesRegex = /([^,\/]+)\/([^,]*)/g;
const emotesRegex = ... |
_onMessage(event) {
let message = event.data.toString().trim().split(/\r?\n/);
// uncomment this line to log all inbounc messages
//console.log(message);
for (var x=0;x<message.length;x++) {
// the last line is empty
if (message[x].length == 0) {
... | {
// pinger
this.pinger.start();
this.ws.send('CAP REQ :twitch.tv/commands');
this.ws.send('CAP REQ :twitch.tv/tags');
this.emit('open');
} | identifier_body |
download-ganglia-metrics.py | #!/usr/bin/env python
import os
import re
import json
import collections
from datetime import datetime
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import requests
import pandas as pd
import numpy as np
WORKFLOW_STEPS = [
'metaextract', 'metaconfig', 'imextract',
'c... |
return formatted_data
def save_formatted_metrics(data, directory):
for step in WORKFLOW_STEPS:
for metric in FORMATTED_METRICS:
subdirectory = os.path.join(directory, step)
if not os.path.exists(subdirectory):
os.makedirs(subdirectory)
filepath = os... | formatted_data[step] = pd.DataFrame(
index=HOST_GROUPS.keys(), columns=FORMATTED_METRICS.keys()
)
for group in HOST_GROUPS:
aggregates = dict()
for metric in RAW_METRICS:
values = data[step][group][metric]
# TODO: cutoff?
... | conditional_block |
download-ganglia-metrics.py | #!/usr/bin/env python
import os
import re
import json
import collections
from datetime import datetime
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import requests
import pandas as pd
import numpy as np
WORKFLOW_STEPS = [
'metaextract', 'metaconfig', 'imextract',
'c... |
def _get_compute_nodes(cluster):
n = _get_number_of_processors(cluster)
return tuple([
'{0}-slurm-worker-{1:03d}'.format(cluster, i+1) for i in range(n)
])
def _get_fs_nodes(cluster):
n = _get_number_of_processors(cluster)
# Ratio of compute to storage nodes is 1:4
return tuple([
... | match = re.search(r'^cluster-([0-9]+)$', cluster)
n = match.group(1)
# All cluster architectuers use nodes with 4 processors
return int(n)/4 | identifier_body |
download-ganglia-metrics.py | #!/usr/bin/env python
import os
import re
import json
import collections
from datetime import datetime
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import requests
import pandas as pd
import numpy as np
WORKFLOW_STEPS = [
'metaextract', 'metaconfig', 'imextract',
'c... | 'output': {
'func': lambda m: m['bytes_out'],
'unit': 'bytes per second',
'name': 'data output'
}
}
def _get_number_of_processors(cluster):
match = re.search(r'^cluster-([0-9]+)$', cluster)
n = match.group(1)
# All cluster architectuers use nodes with 4 processors
retur... | 'input': {
'func': lambda m: m['bytes_in'],
'unit': 'bytes per second',
'name': 'data input'
}, | random_line_split |
download-ganglia-metrics.py | #!/usr/bin/env python
import os
import re
import json
import collections
from datetime import datetime
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import requests
import pandas as pd
import numpy as np
WORKFLOW_STEPS = [
'metaextract', 'metaconfig', 'imextract',
'c... | (cluster):
return tuple(['{0}-postgresql-master-001'.format(cluster)])
def _get_db_worker_nodes(cluster):
n = _get_number_of_processors(cluster)
# Ratio of compute to storage nodes is 1:4
return tuple([
'{0}-postgresql-worker-{1:03d}'.format(cluster, i+1)
for i in range(n/4)
])
H... | _get_db_coordinator_nodes | identifier_name |
mfg_event_converter.py | # Copyright 2022 Google LLC
#
# 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, ... | (self,
all_phases,
attachment_cache: Optional[AttachmentCacheT] = None):
self._phases = all_phases
self._using_partial_uploads = attachment_cache is not None
self._attachment_cache = (
attachment_cache if self._using_partial_uploads else {})
def copy_measurements(sel... | __init__ | identifier_name |
mfg_event_converter.py | # Copyright 2022 Google LLC
#
# 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, ... | self._copy_attachment(name, attachment.data, attachment.mimetype,
mfg_event)
if skipped_attachment_names:
_LOGGER.info(
'Skipping upload of %r attachments for this cycle. '
'To avoid max proto size issues.', skipped_attachment_names)
retu... | sum(value_copied_attachment_sizes) + size >
MAX_TOTAL_ATTACHMENT_BYTES):
skipped_attachment_names.append(name)
else:
value_copied_attachment_sizes.append(size) | random_line_split |
mfg_event_converter.py | # Copyright 2022 Google LLC
#
# 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, ... |
for unit in units.UNITS_BY_NAME.values():
UNITS_BY_CODE[unit.code] = unit
def mfg_event_from_test_record(
record: htf_test_record.TestRecord,
attachment_cache: Optional[AttachmentCacheT] = None,
) -> mfg_event_pb2.MfgEvent:
"""Convert an OpenHTF TestRecord to an MfgEvent proto.
Most fields are co... | return | conditional_block |
mfg_event_converter.py | # Copyright 2022 Google LLC
#
# 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, ... |
json_encoder = json.JSONEncoder(
sort_keys=True,
indent=2,
ensure_ascii=False,
default=unsupported_type_handler)
return json_encoder.encode(obj).encode('utf-8', errors='replace')
def _attach_config(mfg_event, record):
"""Attaches the OpenHTF config file as JSON."""
if 'config' not in... | if isinstance(o, bytes):
return o.decode(encoding='utf-8', errors='replace')
elif isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat()
else:
raise TypeError(repr(o) + ' is not JSON serializable') | identifier_body |
fit_nixing.py | #coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import numpy as np
import matplotlib.pyplot as plt
import cPickle
from easydict import EasyDict as edict
from matplotlib.pyplot import MultipleLocator
from bfs_group import bfs_clustering
import cv2
import glob
from random import random as rand
from ... | = [_ for i, _ in enumerate(history_record) if history_cnt[i]>0]
history_platenum = [_ for i, _ in enumerate(history_platenum) if history_cnt[i]>0]
history_cnt = [_-1 for i, _ in enumerate(history_cnt) if history_cnt[i]>0]
for i, plate in enumerate(history):
ph, pw = plate.shape[:2]
if 70+50... | th, textSize, encoding="utf-8")
draw.text((left, top), unicode(text.decode('utf-8')) , textColor, font=fontText)
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
def draw_history(blend_img, history, history_cnt, history_record, history_platenum):
history = [_ for i, _ in enumerate(history) if histor... | identifier_body |
fit_nixing.py | #coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import numpy as np
import matplotlib.pyplot as plt
import cPickle
from easydict import EasyDict as edict
from matplotlib.pyplot import MultipleLocator
from bfs_group import bfs_clustering
import cv2
import glob
from random import random as rand
from ... |
def draw_box_v2(img, box, alphaReserve=0.8, color=None):
color = (rand() * 255, rand() * 255, rand() * 255) if color is None else color
h,w,_ = img.shape
x1 = max(0, int(float(box[0])))
y1 = max(0, int(float(box[1])))
x2 = min(w-1, int(float(box[2])))
y2 = min(h-1, int(float(box[3])))
B, G,... | type_map = {'BigTruck': '货车', 'Bus': '公交车', 'Lorry': '货车', 'MPV': '轿车', 'MiniVan': '轿车', 'MiniBus': '公交车',
'SUV': '轿车', 'Scooter': '轿车', 'Sedan_Car': '轿车', 'Special_vehicle': '其他', 'Three_Wheeled_Truck':'其他', 'other': '其他', 'Minibus': '公交车'}
| random_line_split |
fit_nixing.py | #coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import numpy as np
import matplotlib.pyplot as plt
import cPickle
from easydict import EasyDict as edict
from matplotlib.pyplot import MultipleLocator
from bfs_group import bfs_clustering
import cv2
import glob
from random import random as rand
from ... | (box1[2] - box1[0] + 1) * (box1[3] - box1[1] + 1)
box2_area = (box2[2] - box2[0] + 1) * (box2[3] - box2[1] + 1)
all_area = float(box1_area + box2_area - iw * ih)
return iw * ih / all_area
return 0
# judge whether line segment (xc,yc)->(xr,yr) is crossed with infinite line (x1,y1... | area = | identifier_name |
fit_nixing.py | #coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import numpy as np
import matplotlib.pyplot as plt
import cPickle
from easydict import EasyDict as edict
from matplotlib.pyplot import MultipleLocator
from bfs_group import bfs_clustering
import cv2
import glob
from random import random as rand
from ... | img,(int(x1),int(y1)),(int(x2),int(y2)), color, thickness=3)
# find the central yellow solid line
lane = lanes[np.argmax(-1 * np.array(b))]
# judge whether cross solid lane
for box in head_box:
if (box[2] - box[0] + 1) * (box[3] - box[1] + 1) < 50*50:
contin... | # cv2.line(blend_ | conditional_block |
main.rs | // This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from
// scratch based on a careful reading of the TLS 1.3 specification.
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind};
use toki... |
async fn read_length(&mut self, length: u8) -> TlsResult<usize> {
debug_assert!(length > 0 && length <= 4);
let mut result = 0;
for _ in 0..length {
result <<= 8;
result |= self.read().await? as usize;
}
Ok(result)
}
async fn into_source<W: ... | {
while self.offset >= self.limit {
self.fill_to(self.limit + 5).await?;
// section 5.1: "Handshake messages MUST NOT be interleaved with other record types.
// That is, if a handshake message is split over two or more records, there MUST NOT be
// any other reco... | identifier_body |
main.rs | // This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from
// scratch based on a careful reading of the TLS 1.3 specification.
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind};
use toki... |
_ => TlsError::InternalError,
})?;
// After this point, all I/O errors are internal errors.
// If this file exists, turn on the PROXY protocol.
// NOTE: This is a blocking syscall, but stat should be fast enough that it's not worth
// spawning off a thread.
if std::fs::metadat... | {
TlsError::UnrecognizedName
} | conditional_block |
main.rs | // This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from
// scratch based on a careful reading of the TLS 1.3 specification.
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind};
use toki... | Ok(v)
}
async fn read_length(&mut self, length: u8) -> TlsResult<usize> {
debug_assert!(length > 0 && length <= 4);
let mut result = 0;
for _ in 0..length {
result <<= 8;
result |= self.read().await? as usize;
}
Ok(result)
}
async... | }
self.fill_to(self.offset + 1).await?;
let v = self.buffer[self.offset];
self.offset += 1; | random_line_split |
main.rs | // This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from
// scratch based on a careful reading of the TLS 1.3 specification.
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind};
use toki... | (length: usize, limit: &mut usize) -> TlsResult<()> {
*limit = limit.checked_sub(length).ok_or(TlsError::DecodeError)?;
Ok(())
}
impl<R: AsyncReadExt> TlsHandshakeReader<R> {
fn new(source: R) -> Self {
TlsHandshakeReader {
source: source,
buffer: Vec::with_capacity(4096),
... | check_length | identifier_name |
app.rs | use crate::{
auth::Resource,
default_resource, diffable,
error::ServiceError,
generation,
models::{
fix_null_default,
sql::{slice_iter, SelectBuilder},
Lock, TypedAlias,
},
update_aliases, Client,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use core:... |
async fn create(
&self,
application: Application,
aliases: HashSet<TypedAlias>,
) -> Result<(), ServiceError> {
let name = application.name;
let data = application.data;
let labels = application.labels;
let annotations = application.annotations;
... | {
let select = r#"
SELECT
NAME,
UID,
LABELS,
ANNOTATIONS,
CREATION_TIMESTAMP,
GENERATION,
RESOURCE_VERSION,
DELETION_TIMESTAMP,
FINALIZERS,
OWNER,
TRANSFER_OWNER,
MEMBERS,
DATA
FROM APPLICATIONS
"#
.to_string();
let builder = SelectBuilder::ne... | identifier_body |
app.rs | use crate::{
auth::Resource,
default_resource, diffable,
error::ServiceError,
generation,
models::{
fix_null_default,
sql::{slice_iter, SelectBuilder},
Lock, TypedAlias,
},
update_aliases, Client,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use core:... | {
let select = r#"
SELECT
NAME,
UID,
LABELS,
ANNOTATIONS,
CREATION_TIMESTAMP,
GENERATION,
RESOURCE_VERSION,
DELETION_TIMESTAMP,
FINALIZERS,
OWNER,
TRANSFER_OWNER,
MEMBERS,
DATA
FROM APPLICATIONS
"#
.to_string();
let builder = SelectBuilder... | offset: Option<usize>,
id: Option<&UserInformation>,
lock: Lock,
sort: &[&str],
) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError> | random_line_split |
app.rs | use crate::{
auth::Resource,
default_resource, diffable,
error::ServiceError,
generation,
models::{
fix_null_default,
sql::{slice_iter, SelectBuilder},
Lock, TypedAlias,
},
update_aliases, Client,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use core:... | (&self, id: &str) -> Result<(), ServiceError> {
let sql = "DELETE FROM APPLICATIONS WHERE NAME = $1";
let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?;
let count = self.client.execute(&stmt, &[&id]).await?;
if count > 0 {
Ok(())
} else {
... | delete | identifier_name |
app.rs | use crate::{
auth::Resource,
default_resource, diffable,
error::ServiceError,
generation,
models::{
fix_null_default,
sql::{slice_iter, SelectBuilder},
Lock, TypedAlias,
},
update_aliases, Client,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use core:... |
let stmt = self
.client
.prepare_typed(
"INSERT INTO APPLICATION_ALIASES (APP, TYPE, ALIAS) VALUES ($1, $2, $3)",
&[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR],
)
.await?;
for alias in aliases {
self.client
... | {
return Ok(());
} | conditional_block |
main.rs | #![no_std]
#![feature(
test,
start,
array_map,
const_panic, | isa_attribute,
core_intrinsics,
maybe_uninit_ref,
bindings_after_at,
stmt_expr_attributes,
default_alloc_error_handler,
const_fn_floating_point_arithmetic,
)]
extern crate alloc;
mod gfx;
mod heap;
mod mem;
use core::fmt::Write;
use alloc::{vec::Vec, vec};
use vek::*;
use num_traits::floa... | random_line_split | |
main.rs | #![no_std]
#![feature(
test,
start,
array_map,
const_panic,
isa_attribute,
core_intrinsics,
maybe_uninit_ref,
bindings_after_at,
stmt_expr_attributes,
default_alloc_error_handler,
const_fn_floating_point_arithmetic,
)]
extern crate alloc;
mod gfx;
mod heap;
mod mem;
use co... |
if flags.timer1() {
timer1_handler();
}
}
fn vblank_handler() { BIOS_IF.write(BIOS_IF.read().with_vblank(true)); }
fn hblank_handler() { BIOS_IF.write(BIOS_IF.read().with_hblank(true)); }
fn vcounter_handler() { BIOS_IF.write(BIOS_IF.read().with_vcounter(true)); }
fn timer0_handler() { BIOS_IF.write(B... | {
timer0_handler();
} | conditional_block |
main.rs | #![no_std]
#![feature(
test,
start,
array_map,
const_panic,
isa_attribute,
core_intrinsics,
maybe_uninit_ref,
bindings_after_at,
stmt_expr_attributes,
default_alloc_error_handler,
const_fn_floating_point_arithmetic,
)]
extern crate alloc;
mod gfx;
mod heap;
mod mem;
use co... | (m: Mat4<F32>, n: Mat4<F32>) -> Mat4<F32> {
(m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0)
}
#[panic_handler]
fn panic(info: &core::panic::PanicInfo) -> ! {
gba::error!("Panic: {:?}", info);
Mode3::clear_to(Color::from_rgb(0xFF, 0, 0));
loop {}
}
#[start]
fn main(_argc: isize, _argv: *const *const u8)... | apply4 | identifier_name |
main.rs | #![no_std]
#![feature(
test,
start,
array_map,
const_panic,
isa_attribute,
core_intrinsics,
maybe_uninit_ref,
bindings_after_at,
stmt_expr_attributes,
default_alloc_error_handler,
const_fn_floating_point_arithmetic,
)]
extern crate alloc;
mod gfx;
mod heap;
mod mem;
use co... |
}
impl vek::ops::MulAdd<NumWrap, NumWrap> for NumWrap {
type Output = NumWrap;
fn mul_add(self, mul: NumWrap, add: NumWrap) -> NumWrap {
NumWrap(self.0 * mul.0 + add.0)
}
}
fn apply(m: Mat3<F32>, n: Mat3<F32>) -> Mat3<F32> {
(m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0)
}
fn apply4(m: Mat4... | { NumWrap(self.0 * rhs.0) } | identifier_body |
Assign_LLID_Toxics_DO_unverified_LASAR_Stations.py | # -*- coding: utf-8 -*-
# Assign LLID's to sampling stations
# I'm including code in here beyond simply the station location. It'll add huc, stream names, and other important info.
# Import necessary modules
custom_script_location = r'E:\GitHub\ToxicsRedo\Python_Scripts'
if custom_script_location not in sys.path:
... |
arcpy.DeleteField_management(output_success, fields_to_drop)
#Merge with output table
arcpy.JoinField_management(output_success, 'Unique_ID', output_table, 'Unique_ID')
#Now split success fc into one fc with successful qc and one with stations needing review
arcpy.MakeFeatureLayer_management(output_success, qc_... | if field.name not in ['Unique_ID', 'Shape','OBJECTID']:
fields_to_drop.append(field.name) | conditional_block |
Assign_LLID_Toxics_DO_unverified_LASAR_Stations.py | # -*- coding: utf-8 -*-
# Assign LLID's to sampling stations
# I'm including code in here beyond simply the station location. It'll add huc, stream names, and other important info.
# Import necessary modules
custom_script_location = r'E:\GitHub\ToxicsRedo\Python_Scripts'
if custom_script_location not in sys.path:
... | else:
arcpy.CreateFileGDB_management(temp_location, final_gdb)
arcpy.env.workspace = workspace
arcpy.CopyFeatures_management(original_sampling_stations, sampling_stations)
arcpy.AddField_management(sampling_stations, "Unique_ID", "DOUBLE")
arcpy.CalculateField_management(sampling_stations, "Unique_ID", "!OBJECTID... | print "It exist!" | random_line_split |
main.rs | use cargo::core::dependency::Kind;
use cargo::core::manifest::ManifestMetadata;
use cargo::core::package::PackageSet;
use cargo::core::registry::PackageRegistry;
use cargo::core::resolver::Method;
use cargo::core::shell::Shell;
use cargo::core::{Package, PackageId, Resolve, Workspace};
use cargo::ops;
use cargo::util::... | graph: petgraph::Graph<Node<'a>, Kind>,
nodes: HashMap<PackageId, NodeIndex>,
}
fn build_graph<'a>(
resolve: &'a Resolve,
packages: &'a PackageSet<'_>,
root: PackageId,
target: Option<&str>,
cfgs: Option<&[Cfg]>,
) -> CargoResult<Graph<'a>> {
let mut graph = Graph {
graph: petgra... | > {
| identifier_name |
main.rs | use cargo::core::dependency::Kind;
use cargo::core::manifest::ManifestMetadata;
use cargo::core::package::PackageSet;
use cargo::core::registry::PackageRegistry;
use cargo::core::resolver::Method;
use cargo::core::shell::Shell;
use cargo::core::{Package, PackageId, Resolve, Workspace};
use cargo::ops;
use cargo::util::... | l_main(args: Args, config: &mut Config) -> CliResult {
config.configure(
args.verbose,
args.quiet,
&args.color,
args.frozen,
args.locked,
&args.target_dir,
&args.unstable_flags,
)?;
let workspace = workspace(config, args.manifest_path)?;
let packa... | v_logger::init();
let mut config = match Config::default() {
Ok(cfg) => cfg,
Err(e) => {
let mut shell = Shell::new();
cargo::exit_with_error(e.into(), &mut shell)
}
};
let Opts::Tree(args) = Opts::from_args();
if let Err(e) = real_main(args, &mut confi... | identifier_body |
main.rs | use cargo::core::dependency::Kind;
use cargo::core::manifest::ManifestMetadata;
use cargo::core::package::PackageSet;
use cargo::core::registry::PackageRegistry;
use cargo::core::resolver::Method;
use cargo::core::shell::Shell;
use cargo::core::{Package, PackageId, Resolve, Workspace};
use cargo::ops;
use cargo::util::... | for dep in it {
let dep_idx = match graph.nodes.entry(dep_id) {
Entry::Occupied(e) => *e.get(),
Entry::Vacant(e) => {
pending.push(dep_id);
let node = Node {
id: dep_id,
... | random_line_split | |
main.rs | use cargo::core::dependency::Kind;
use cargo::core::manifest::ManifestMetadata;
use cargo::core::package::PackageSet;
use cargo::core::registry::PackageRegistry;
use cargo::core::resolver::Method;
use cargo::core::shell::Shell;
use cargo::core::{Package, PackageId, Resolve, Workspace};
use cargo::ops;
use cargo::util::... | Resolve uses Hash data types internally but we want consistent output ordering
deps.sort_by_key(|n| n.id);
let name = match kind {
Kind::Normal => None,
Kind::Build => Some("[build-dependencies]"),
Kind::Development => Some("[dev-dependencies]"),
};
if let Prefix::Indent = pref... | return;
}
// | conditional_block |
Liquid.go | /**
* Liquid.go - Go+SDL port V1 Robert Rasmay (2013)
* Liquid.go - Go+SDL port V2 Robert Ramsay (2021)
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
*
* JS version:
* Copyright Stephen Sinclair (radarsat1) (http://www.music.mcgill.ca/~sinclair)
* MIT License ( http://www.opensource.org/... | () {
var mu, mv float32
for _, p := range l.particles {
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
n := l.grid.Get(int(p.cx)+i, int(p.cy)+j)
phi := p.px[i] * p.py[j]
p.u += phi * n.ax
p.v += phi * n.ay
}
}
mu = p.material.m * p.u
mv = p.material.m * p.v
for i := 0; i < 3; i++ {... | _step3 | identifier_name |
Liquid.go | /**
* Liquid.go - Go+SDL port V1 Robert Rasmay (2013)
* Liquid.go - Go+SDL port V2 Robert Ramsay (2021)
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
*
* JS version:
* Copyright Stephen Sinclair (radarsat1) (http://www.music.mcgill.ca/~sinclair)
* MIT License ( http://www.opensource.org/... | n.gx += particle.gx[i] * particle.py[j]
n.gy += particle.px[i] * particle.gy[j]
}
}
}
}
func (l *Liquid) _density_summary(drag bool, mdx, mdy float32) {
var n01, n02, n11, n12 *Node
var cx, cy, cxi, cyi int
var pdx, pdy, C20, C02, C30, C03, csum1, csum2, C21, C31,
C12, C13, C11, density, pressure, f... | random_line_split | |
Liquid.go | /**
* Liquid.go - Go+SDL port V1 Robert Rasmay (2013)
* Liquid.go - Go+SDL port V2 Robert Ramsay (2021)
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
*
* JS version:
* Copyright Stephen Sinclair (radarsat1) (http://www.music.mcgill.ca/~sinclair)
* MIT License ( http://www.opensource.org/... |
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
n := l.grid.Get(int(p.cx)+i, int(p.cy)+j)
phi := p.px[i] * p.py[j]
n.ax += -(p.gx[i] * p.py[j] * pressure) + fx*phi
n.ay += -(p.px[i] * p.gy[j] * pressure) + fy*phi
}
}
}
}
func (l *Liquid) _step3() {
var mu, mv float32
for _, p := range l... | {
vx := Abs(p.x - l.mouse.x)
vy := Abs(p.y - l.mouse.y)
if vx < 10.0 && 10.0 > vy {
weight := p.material.m * (1.0 - vx*0.10) *
(1.0 - vy*0.10)
fx += weight * (mdx - p.u)
fy += weight * (mdy - p.v)
}
} | conditional_block |
Liquid.go | /**
* Liquid.go - Go+SDL port V1 Robert Rasmay (2013)
* Liquid.go - Go+SDL port V2 Robert Ramsay (2021)
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
*
* JS version:
* Copyright Stephen Sinclair (radarsat1) (http://www.music.mcgill.ca/~sinclair)
* MIT License ( http://www.opensource.org/... |
func (l *Liquid) _step1() {
for _, particle := range l.particles {
particle.cx = float32(int(particle.x - 0.5))
particle.cy = float32(int(particle.y - 0.5))
_equation1(&particle.px, &particle.gx, particle.cx-particle.x)
_equation1(&particle.py, &particle.gy, particle.cy-particle.y)
for i := 0; i < 3; i+... | {
pressure[0] = 0.5*x*x + 1.5*x + 1.125
gravity[0] = x + 1.5
x += 1.0
pressure[1] = -x*x + 0.75
gravity[1] = -2.0 * x
x += 1.0
pressure[2] = 0.5*x*x - 1.5*x + 1.125
gravity[2] = x - 1.5
} | identifier_body |
arena.rs | // Copyright 2019 Fullstop000 <fullstop1005@gmail.com>.
//
// 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 appli... |
#[test]
fn test_has_room_for() {
let arena = AggressiveArena::new(1);
assert_eq!(arena.has_room_for(100), false);
}
} | arena.alloc_node(MAX_HEIGHT); // 152
arena.alloc_node(1); // 64
arena.alloc_bytes(&Slice::from(vec![1u8, 2u8, 3u8, 4u8].as_slice())); // 4
assert_eq!(152 + 64 + 4, arena.memory_used())
} | random_line_split |
arena.rs | // Copyright 2019 Fullstop000 <fullstop1005@gmail.com>.
//
// 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 appli... | () {
let arena = Arc::new(AggressiveArena::new(500));
let results = Arc::new(Mutex::new(vec![]));
let mut tests = vec![vec![1u8, 2, 3, 4, 5], vec![6u8, 7, 8, 9], vec![10u8, 11]];
for t in tests
.drain(..)
.map(|test| {
let cloned_arena = arena.clon... | test_alloc_bytes_concurrency | identifier_name |
arena.rs | // Copyright 2019 Fullstop000 <fullstop1005@gmail.com>.
//
// 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 appli... |
fn alloc_bytes(&self, data: &Slice) -> u32 {
let start = self.offset.fetch_add(data.size(), Ordering::SeqCst);
unsafe {
let ptr = self.mem.as_ptr().add(start) as *mut u8;
for (i, b) in data.to_slice().iter().enumerate() {
let p = ptr.add(i) as *mut u8;
... | {
let ptr_size = mem::size_of::<*mut u8>();
// truncate node size to reduce waste
let used_node_size = MAX_NODE_SIZE - (MAX_HEIGHT - height) * ptr_size;
let n = self.offset.fetch_add(used_node_size, Ordering::SeqCst);
unsafe {
let node_ptr = self.mem.as_ptr().add(n) a... | identifier_body |
goes.py | # Author: Rishabh Sharma <rishabh.sharma.gunner@gmail.com>
# This module was developed under funding provided by
# Google Summer of Code 2014
import os
from datetime import datetime
from itertools import compress
from urllib.parse import urlsplit
import astropy.units as u
from astropy.time import Time, TimeDelta
fro... |
def _get_time_for_url(self, urls):
times = []
for uri in urls:
uripath = urlsplit(uri).path
# Extract the yymmdd or yyyymmdd timestamp
datestamp = os.path.splitext(os.path.split(uripath)[1])[0][4:]
# 1999-01-15 as an integer.
if int(dat... | raise ValueError(
"No operational GOES satellites on {}".format(
date.strftime(TIME_FORMAT)
)
) | conditional_block |
goes.py | # Author: Rishabh Sharma <rishabh.sharma.gunner@gmail.com>
# This module was developed under funding provided by
# Google Summer of Code 2014
import os
from datetime import datetime
from itertools import compress
from urllib.parse import urlsplit
import astropy.units as u
from astropy.time import Time, TimeDelta
fro... | 8: TimeRange("1996-03-21", "2003-06-18"),
9: TimeRange("1997-01-01", "1998-09-08"),
10: TimeRange("1998-07-10", "2009-12-01"),
11: TimeRange("2006-06-20", "2008-02-15"),
12: TimeRange("2002-12-13", "2007-05-08"),
13: TimeRange("2006-08-01", "2006-0... | 6: TimeRange("1983-06-01", "1994-08-18"),
7: TimeRange("1994-01-01", "1996-08-13"), | random_line_split |
goes.py | # Author: Rishabh Sharma <rishabh.sharma.gunner@gmail.com>
# This module was developed under funding provided by
# Google Summer of Code 2014
import os
from datetime import datetime
from itertools import compress
from urllib.parse import urlsplit
import astropy.units as u
from astropy.time import Time, TimeDelta
fro... | (self, urls):
these_timeranges = []
for this_url in urls:
if this_url.count('/l2/') > 0: # this is a level 2 data file
start_time = parse_time(os.path.basename(this_url).split('_s')[2].split('Z')[0])
end_time = parse_time(os.path.basename(this_url).split('_e... | _get_time_for_url | identifier_name |
goes.py | # Author: Rishabh Sharma <rishabh.sharma.gunner@gmail.com>
# This module was developed under funding provided by
# Google Summer of Code 2014
import os
from datetime import datetime
from itertools import compress
from urllib.parse import urlsplit
import astropy.units as u
from astropy.time import Time, TimeDelta
fro... |
def _get_url_for_timerange(self, timerange, **kwargs):
"""
Returns urls to the SUVI data for the specified time range.
Parameters
----------
timerange: `sunpy.time.TimeRange`
Time range for which data is to be downloaded.
level : `str`, optional
... | these_timeranges = []
for this_url in urls:
if this_url.count('/l2/') > 0: # this is a level 2 data file
start_time = parse_time(os.path.basename(this_url).split('_s')[2].split('Z')[0])
end_time = parse_time(os.path.basename(this_url).split('_e')[1].split('Z')[0])
... | identifier_body |
writeToStore.ts | import { SelectionSetNode, FieldNode, DocumentNode } from 'graphql';
import { invariant, InvariantError } from 'ts-invariant';
import { equal } from '@wry/equality';
import {
createFragmentMap,
FragmentMap,
getFragmentFromSelection,
getDefaultValues,
getFragmentDefinitions,
getOperationDefinition,
getTyp... | fieldsWithSelectionSets.has(fieldNameFromStoreName(storeFieldName));
const fieldsWithSelectionSets = new Set<string>();
workSet.forEach(selection => {
if (isField(selection) && selection.selectionSet) {
fieldsWithSelectionSets.add(selection.name.value);
}
... | random_line_split | |
writeToStore.ts | import { SelectionSetNode, FieldNode, DocumentNode } from 'graphql';
import { invariant, InvariantError } from 'ts-invariant';
import { equal } from '@wry/equality';
import {
createFragmentMap,
FragmentMap,
getFragmentFromSelection,
getDefaultValues,
getFragmentDefinitions,
getOperationDefinition,
getTyp... | {
const getChild = (objOrRef: StoreObject | Reference): StoreObject | false => {
const child = store.getFieldValue<StoreObject>(objOrRef, storeFieldName);
return typeof child === "object" && child;
};
const existing = getChild(existingRef);
if (!existing) return;
const incoming = getChild(incomingOb... | identifier_body | |
writeToStore.ts | import { SelectionSetNode, FieldNode, DocumentNode } from 'graphql';
import { invariant, InvariantError } from 'ts-invariant';
import { equal } from '@wry/equality';
import {
createFragmentMap,
FragmentMap,
getFragmentFromSelection,
getDefaultValues,
getFragmentDefinitions,
getOperationDefinition,
getTyp... | (
existingRef: Reference,
incomingObj: StoreObject,
storeFieldName: string,
store: NormalizedCache,
) {
const getChild = (objOrRef: StoreObject | Reference): StoreObject | false => {
const child = store.getFieldValue<StoreObject>(objOrRef, storeFieldName);
return typeof child === "object" && child;
... | warnAboutDataLoss | identifier_name |
service.go | package auth
import (
"database/sql"
"encoding/base64"
"errors"
"html/template"
"net/mail"
"strings"
"time"
"github.com/bryanjeal/go-helpers"
"github.com/bryanjeal/go-nonce"
tmpl "github.com/bryanjeal/go-tmpl"
// handle mysql database
_ "github.com/go-sql-driver/mysql"
// handle sqlite3 database
_ "git... | (email string) (User, error) {
u := User{}
err := s.db.Get(&u, "SELECT * FROM user WHERE email=$1", email)
if err != nil && err != sql.ErrNoRows {
return User{}, err
} else if err == sql.ErrNoRows {
return User{}, ErrIncorrectAuth
}
return u, nil
}
// saveUser saves a new user to the database or updates an ... | getUserByEmail | identifier_name |
service.go | package auth
import (
"database/sql"
"encoding/base64"
"errors"
"html/template"
"net/mail"
"strings"
"time"
"github.com/bryanjeal/go-helpers"
"github.com/bryanjeal/go-nonce"
tmpl "github.com/bryanjeal/go-tmpl"
// handle mysql database
_ "github.com/go-sql-driver/mysql"
// handle sqlite3 database
_ "git... |
// Check Password
p := strings.TrimSpace(password)
if len(p) == 0 {
return User{}, ErrInvalidPassword
}
// Get user from database
u, err := s.getUserByEmail(e.Address)
if err != nil {
return User{}, err
}
// check password
hashed, err := base64.StdEncoding.DecodeString(u.Password)
if err != nil {
r... | {
return User{}, err
} | conditional_block |
service.go | package auth
import (
"database/sql"
"encoding/base64"
"errors"
"html/template"
"net/mail"
"strings"
"time"
"github.com/bryanjeal/go-helpers"
"github.com/bryanjeal/go-nonce"
tmpl "github.com/bryanjeal/go-tmpl"
// handle mysql database
_ "github.com/go-sql-driver/mysql"
// handle sqlite3 database
_ "git... | if err := u.Validate(); err != nil {
return err
}
var sqlExec string
// if id is nil then it is a new user
if u.ID == uuid.Nil {
// generate ID
u.ID = uuid.NewV4()
sqlExec = `INSERT INTO user
(id, email, password, firstname, lastname, is_superuser, is_active, is_deleted, created_at, updated_at, delete... | random_line_split | |
service.go | package auth
import (
"database/sql"
"encoding/base64"
"errors"
"html/template"
"net/mail"
"strings"
"time"
"github.com/bryanjeal/go-helpers"
"github.com/bryanjeal/go-nonce"
tmpl "github.com/bryanjeal/go-tmpl"
// handle mysql database
_ "github.com/go-sql-driver/mysql"
// handle sqlite3 database
_ "git... |
func (s *authService) UpdateUser(u User) (User, error) {
eUser := User{}
err := s.db.Get(&eUser, "SELECT * FROM user WHERE email=$1", u.Email)
if err == sql.ErrNoRows {
return User{}, ErrUserNotFound
} else if err != nil {
return User{}, err
}
if !uuid.Equal(eUser.ID, u.ID) {
return User{}, ErrInconsiste... | {
if id == uuid.Nil {
return User{}, ErrInvalidID
}
u := User{}
err := s.db.Get(&u, "SELECT * FROM user WHERE id=$1", id)
if err != nil && err != sql.ErrNoRows {
return User{}, err
} else if err == sql.ErrNoRows {
return User{}, ErrUserNotFound
}
return u, nil
} | identifier_body |
pkg_util.go | package pkg_util
import (
"fmt"
"os"
"zip_util"
"time"
"strings"
"os/exec"
"log"
"io"
"path/filepath"
"errors"
)
var (
LOCAL_PATH1 = os.TempDir() + "\\test_file.zip" // 下载到本地的路径1
LOCAL_PATH2 = "d:\\test_file.zip" // 下载到本地的路径2
UNZIP_PATH1 = os.TempDir() + "\\hbn_pkg\\" // 更新包解压路径1
UNZIP_PATH2 ... | }
return nil;
}
/**
替换包
*/
func ReplacePkg(tomcatInfo TomcatInfo) error {
var stopErr = stopTomcat(tomcatInfo);
if stopErr != nil {
fmt.Println("停止" + tomcatInfo.ProcessName + "出错!");
} else {
fmt.Println("停止" + tomcatInfo.ProcessName + "成功。");
}
//var destDir = tomcatInfo.ProcessHome + "webapps\\agent"... |
if err != nil {
fmt.Printf("filepath.Walk() returned %v\n", err);
return err; | random_line_split |
pkg_util.go | package pkg_util
import (
"fmt"
"os"
"zip_util"
"time"
"strings"
"os/exec"
"log"
"io"
"path/filepath"
"errors"
)
var (
LOCAL_PATH1 = os.TempDir() + "\\test_file.zip" // 下载到本地的路径1
LOCAL_PATH2 = "d:\\test_file.zip" // 下载到本地的路径2
UNZIP_PATH1 = os.TempDir() + "\\hbn_pkg\\" // 更新包解压路径1
UNZIP_PATH2 ... | e {
var pkg string
fmt.Print(tomcatInfo.ProcessName + "需要哪个包进行更新(0:通用版最新包;1:安装包1114): ");
fmt.Scanln(&pkg);
if(pkg == "0") {
tomcatInfo.PackageFileName = "tyb";
break;
} else if(pkg == "1") {
tomcatInfo.PackageFileName = "agent_1114";
break;
}
fmt.Print("输入有误,请重新输入0或者1! ");
}
}
... | x(processName, tomcatSuffix) {
out2, err2 := exec.Command("cmd", "/C", "wmic process where name='" + processName + "' get ExecutablePath").Output()
if err2 == nil {
// TODO
var fileDirectoryArr[] string = strings.Split(strings.Split(string(out2), "\r\n", )[1], "\\");
if(len(fileDirectoryArr) < ... | identifier_body |
pkg_util.go | package pkg_util
import (
"fmt"
"os"
"zip_util"
"time"
"strings"
"os/exec"
"log"
"io"
"path/filepath"
"errors"
)
var (
LOCAL_PATH1 = os.TempDir() + "\\test_file.zip" // 下载到本地的路径1
LOCAL_PATH2 = "d:\\test_file.zip" // 下载到本地的路径2
UNZIP_PATH1 = os.TempDir() + "\\hbn_pkg\\" // 更新包解压路径1
UNZIP_PATH2 ... | il;
}
/**
获取tomcat信息
*/
func GetTomcatArray(
tomcatPrefix string,
tomcatSuffix string) [] TomcatInfo {
//out, err := exec.Command("cmd", "/C", "tasklist ").Output()
out, err := exec.Command("cmd", "/C", "tasklist").Output()
if err != nil {
log.Fatal(err)
}
//fmt.Printf(string(out))
var processStrList[] st... | fmt.Println("复制" + tomcatInfo.ProcessName+ "配置文件成功,文件:" + cfgFileName + ",大小:", written, "byte");
}
}
//fmt.Println(tomcatArr);
return n | conditional_block |
pkg_util.go | package pkg_util
import (
"fmt"
"os"
"zip_util"
"time"
"strings"
"os/exec"
"log"
"io"
"path/filepath"
"errors"
)
var (
LOCAL_PATH1 = os.TempDir() + "\\test_file.zip" // 下载到本地的路径1
LOCAL_PATH2 = "d:\\test_file.zip" // 下载到本地的路径2
UNZIP_PATH1 = os.TempDir() + "\\hbn_pkg\\" // 更新包解压路径1
UNZIP_PATH2 ... | identifier_name | ||
aweMBPicker.py | # coding: UTF-8
# -------------------------
# A proof of concept port of aweControlPicker
# from Maya to Motionbuilder
# -------------------------
from pyfbsdk import *
import pyfbsdk_additions as pyui
from PySide import QtGui
gDeveloperMode = True
def log(*messages):
'''Wrapper around print statement to control s... | control,event):
FBSystem().Scene.OnChange.RemoveAll()
def _monitorSet(control,event):
'''Callback:
Check for manual deletion of a picker object (FBSet).
If it's the master set, prompt for undo. If it's a picker
set, notify the associated Picker object
'''
if event.Type == FBSceneChangeType.kFBSceneChangeDeta... | removeSceneCB( | identifier_name |
aweMBPicker.py | # coding: UTF-8
# -------------------------
# A proof of concept port of aweControlPicker
# from Maya to Motionbuilder
# -------------------------
from pyfbsdk import *
import pyfbsdk_additions as pyui
from PySide import QtGui
gDeveloperMode = True
def log(*messages):
'''Wrapper around print statement to control s... |
def _addObjects(control,event):
'''Callback:
Adds selected objects to the Picker associated with the caller
'''
ml = FBModelList()
FBGetSelectedModels(ml)
objectList = [o for o in ml]
control.picker.add(objectList)
def _removeObjects(control,event):
'''Callback:
Removes selected objects from Picker associa... | ''Creates a layout that holds a Picker's option UI'''
optionLayout = pyui.FBHBoxLayout()
addBtn = FBButton()
addBtn.Caption = "+"
addBtn.OnClick.Add(_addObjects)
addBtn.picker = parentBox.picker
addBtn.Look = FBButtonLook.kFBLookColorChange
addBtn.SetStateColor(FBButtonState.kFBButtonState0, FBColor(0.4,0.5,0.... | identifier_body |
aweMBPicker.py | # coding: UTF-8
# -------------------------
# A proof of concept port of aweControlPicker
# from Maya to Motionbuilder
# -------------------------
from pyfbsdk import *
import pyfbsdk_additions as pyui
from PySide import QtGui
gDeveloperMode = True
def log(*messages):
'''Wrapper around print statement to control s... | # ----------------------
# Main Layout
# ----------------------
x = FBAddRegionParam(5,FBAttachType.kFBAttachLeft,"")
y = FBAddRegionParam(5,FBAttachType.kFBAttachTop,"")
w = FBAddRegionParam(0,FBAttachType.kFBAttachRight,"")
h = FBAddRegionParam(0,FBAttachType.kFBAttachBottom,"")
tool.AddRegion("mainRegion", ... | tool.StartSizeX = startX
tool.StartSizeY = startY
tool.OnResize.Add(_toolResize)
| random_line_split |
aweMBPicker.py | # coding: UTF-8
# -------------------------
# A proof of concept port of aweControlPicker
# from Maya to Motionbuilder
# -------------------------
from pyfbsdk import *
import pyfbsdk_additions as pyui
from PySide import QtGui
gDeveloperMode = True
def log(*messages):
'''Wrapper around print statement to control s... |
def createPickerObject(self, name, tab, pickerObject, objectList=[]):
'''Creates the Set object used to store the Picker in the Scene
When used during initPickers(), it doesn't create a new set and
returns the existing set instead.
'''
po = pickerObject
if not po:
po = aweCreateSet(name)
# sear... | self.pickerObject.PropertyList.Find('Objects').append(o) | conditional_block |
types.go | package consensus
import (
"bytes"
"math/big"
"time"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/encoding"
)
type (
Timestamp uint64
BlockHeight uint64
Siafund Currency // arbitrary-precision unsigned integer
// A Specifier is a fixed-length string that serves two purposes. In t... | // contract index.
func (t Transaction) FileContractID(i int) FileContractID {
return FileContractID(crypto.HashAll(
SpecifierFileContract,
t.SiacoinInputs,
t.SiacoinOutputs,
t.FileContracts,
t.FileContractTerminations,
t.StorageProofs,
t.SiafundInputs,
t.SiafundOutputs,
t.MinerFees,
t.ArbitraryDat... | // FileContractID returns the ID of a file contract at the given index, which
// is calculated by hashing the concatenation of the FileContract Specifier,
// all of the fields in the transaction (except the signatures), and the | random_line_split |
types.go | package consensus
import (
"bytes"
"math/big"
"time"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/encoding"
)
type (
Timestamp uint64
BlockHeight uint64
Siafund Currency // arbitrary-precision unsigned integer
// A Specifier is a fixed-length string that serves two purposes. In t... |
// Rat converts a Target to a big.Rat.
func (t Target) Rat() *big.Rat {
return new(big.Rat).SetInt(t.Int())
}
// Inverse returns the inverse of a Target as a big.Rat
func (t Target) Inverse() *big.Rat {
return new(big.Rat).Inv(t.Rat())
}
// IntToTarget converts a big.Int to a Target.
func IntToTarget(i *big.Int) ... | {
return new(big.Int).SetBytes(t[:])
} | identifier_body |
types.go | package consensus
import (
"bytes"
"math/big"
"time"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/encoding"
)
type (
Timestamp uint64
BlockHeight uint64
Siafund Currency // arbitrary-precision unsigned integer
// A Specifier is a fixed-length string that serves two purposes. In t... |
for _, termination := range cf.FileContractTerminations {
signedData = append(signedData, encoding.Marshal(t.FileContractTerminations[termination])...)
}
for _, storageProof := range cf.StorageProofs {
signedData = append(signedData, encoding.Marshal(t.StorageProofs[storageProof])...)
}
for _, siafundI... | {
signedData = append(signedData, encoding.Marshal(t.FileContracts[contract])...)
} | conditional_block |
types.go | package consensus
import (
"bytes"
"math/big"
"time"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/encoding"
)
type (
Timestamp uint64
BlockHeight uint64
Siafund Currency // arbitrary-precision unsigned integer
// A Specifier is a fixed-length string that serves two purposes. In t... | () BlockID {
return BlockID(crypto.HashAll(
b.ParentID,
b.Nonce,
b.MerkleRoot(),
))
}
// CheckTarget returns true if the block's ID meets the given target.
func (b Block) CheckTarget(target Target) bool {
blockHash := b.ID()
return bytes.Compare(target[:], blockHash[:]) >= 0
}
// MerkleRoot calculates the M... | ID | identifier_name |
SurveySimulator.py | #!/usr/bin/python
from random import random
import math
import ephem
# import field
# to be implemented once the field class has been created
class ssobj(ephem.EllipticalBody):
'Class for all Survey Simulator objects.'
def __init__(self, a, e, inc, capom, argperi, H=5, M=0.0):
# ephem.EllipticalBody._... |
self._a = value
#----------- e
@property
def e(self):
"""I'm the e property."""
return self._e
@e.setter
def e(self, value):
if not 0.0 <= value <= 1.0:
raise ValueError('Bad e value. e must be between 0 and 1')
self._e = float(value)
#-----------... | raise ValueError('Bad a value. Ensure 0.0 < a < 10E6') | conditional_block |
SurveySimulator.py | #!/usr/bin/python
from random import random
import math
import ephem
# import field
# to be implemented once the field class has been created
class ssobj(ephem.EllipticalBody):
'Class for all Survey Simulator objects.'
def __init__(self, a, e, inc, capom, argperi, H=5, M=0.0):
# ephem.EllipticalBody._... | raise ValueError('Bad a value. Ensure 0.0 < a < 10E6')
self._a = value
#----------- e
@property
def e(self):
"""I'm the e property."""
return self._e
@e.setter
def e(self, value):
if not 0.0 <= value <= 1.0:
raise ValueError('Bad e value. e must... | if not 0.0 <= value <= 10E6: | random_line_split |
SurveySimulator.py | #!/usr/bin/python
from random import random
import math
import ephem
# import field
# to be implemented once the field class has been created
class ssobj(ephem.EllipticalBody):
'Class for all Survey Simulator objects.'
def __init__(self, a, e, inc, capom, argperi, H=5, M=0.0):
# ephem.EllipticalBody._... | (self, value):
if not 0.0 <= value <= 180.0:
raise ValueError('Bad inclination value. Ensure 0.0 < inclination < 90 degrees')
self._inc = value
#----------- Om
@property
def Om(self):
"""I'm the Om property."""
return self._Om
@Om.setter
def Om(self, value)... | inc | identifier_name |
SurveySimulator.py | #!/usr/bin/python
from random import random
import math
import ephem
# import field
# to be implemented once the field class has been created
class ssobj(ephem.EllipticalBody):
'Class for all Survey Simulator objects.'
def __init__(self, a, e, inc, capom, argperi, H=5, M=0.0):
# ephem.EllipticalBody._... |
@e.setter
def e(self, value):
if not 0.0 <= value <= 1.0:
raise ValueError('Bad e value. e must be between 0 and 1')
self._e = float(value)
#----------- inc
@property
def inc(self):
"""I'm the inc property."""
return self._inc
@inc.setter
def inc(... | """I'm the e property."""
return self._e | identifier_body |
simanalysis.py | import numpy as np
from MDAnalysis.analysis.distances import distance_array
import mybiotools as mbt
def traj_nslice (u,teq,tsample) :
"""
Returns the number of frames in the trajectory in universe u, using teq as
equilibration time and tsample as sampling time
"""
# get the number of frames in the... | (sim,polymer_text,tracer_text,teq,tsample,t_threshold,p_threshold) :
# define DKL(t) vector
nframes = traj_nslice(sim.u,teq,tsample)
DKL_t = np.zeros(nframes)
# define polymer and tracers
polymer = sim.u.select_atoms(polymer_text)
tracers = sim.u.select_atoms(tracer_text)
N = polymer.n_atom... | DKL_t | identifier_name |
simanalysis.py | import numpy as np
from MDAnalysis.analysis.distances import distance_array
import mybiotools as mbt
def traj_nslice (u,teq,tsample) :
"""
Returns the number of frames in the trajectory in universe u, using teq as
equilibration time and tsample as sampling time
"""
# get the number of frames in the... |
return np.mean(np.array(c))
def fit_msd (msd,cutoff,delta_t,scale_l) :
"""
Perform a simple fit of the supplied time-dependent MSD, using a linear
regression of the logarithms of the values. User must supply the conversion
factor from time to real time and from length to real length. Also, user
... | c.append ((cB/cA) / (float(bs_n)/nbs_n)) | conditional_block |
simanalysis.py | import numpy as np
from MDAnalysis.analysis.distances import distance_array
import mybiotools as mbt
def traj_nslice (u,teq,tsample) :
"""
Returns the number of frames in the trajectory in universe u, using teq as
equilibration time and tsample as sampling time
"""
# get the number of frames in the... |
def ps (H) :
"""
Calculate the normalized probability of contact between a monomer and all
others as a function of the linear distance s.
"""
p = np.array ([np.mean (np.diagonal (H, offset=k))
for k in range (H.shape[0])])
return p/np.sum(p)
def contacts_with (sim,polymer_t... | """
Calculate the Pearson correlation coefficient between the row sum of the
given Hi-C matrix and the given ChIP-seq profile.
"""
hic_rowsum = np.sum(hic,axis=1)/float(np.sum(hic))
return np.corrcoef(hic_rowsum,chipseq)[0,1]**2 | identifier_body |
simanalysis.py | import numpy as np | import mybiotools as mbt
def traj_nslice (u,teq,tsample) :
"""
Returns the number of frames in the trajectory in universe u, using teq as
equilibration time and tsample as sampling time
"""
# get the number of frames in the slice (http://stackoverflow.com/a/7223557)
traj_slice = u.trajectory[te... | from MDAnalysis.analysis.distances import distance_array | random_line_split |
wikibrief.go | package wikibrief
import (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"os"
"sync"
"time"
"github.com/RoaringBitmap/roaring"
"github.com/remeh/sizedwaitgroup"
"github.com/negapedia/wikiassignment"
"github.com/negapedia/wikibots"
"github.com/negapedia/wikidump"
"github.com/negapedia/wikipage"
errorsO... | {
wg.Add(1)
go func() {
defer wg.Done()
for range revisions {
//skip
}
}()
} | identifier_body | |
wikibrief.go | package wikibrief
import (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"os"
"sync"
"time"
"github.com/RoaringBitmap/roaring"
"github.com/remeh/sizedwaitgroup"
"github.com/negapedia/wikiassignment"
"github.com/negapedia/wikibots"
"github.com/negapedia/wikidump"
"github.com/negapedia/wikipage"
errorsO... |
//There are 4 buffers in various forms: 4*pageBufferSize is the maximum number of wikipedia pages in memory.
//Each page has a buffer of revisionBufferSize revisions: this means that at each moment there is
//a maximum of 4*pageBufferSize*revisionBufferSize page texts in memory.
const (
pageBufferSize = 40
revis... | Text, SHA1 string
IsRevert uint32
Timestamp time.Time
} | random_line_split |
wikibrief.go | package wikibrief
import (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"os"
"sync"
"time"
"github.com/RoaringBitmap/roaring"
"github.com/remeh/sizedwaitgroup"
"github.com/negapedia/wikiassignment"
"github.com/negapedia/wikibots"
"github.com/negapedia/wikidump"
"github.com/negapedia/wikipage"
errorsO... |
bs.ErrorContext.LastTitle = title //used for error reporting purposes
be = &bTitled{
bStarted: *bs,
Title: title,
}
return
}
func (bs *bStarted) SetPageID(ctx context.Context, t xml.StartElement) (be builder, err error) { //no obligatory element "title"
err = bs.Wrapf(errInvalidXML, "Error invalid xml (... | {
err = bs.Wrapf(err, "Error while decoding the title of a page")
return
} | conditional_block |
wikibrief.go | package wikibrief
import (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"os"
"sync"
"time"
"github.com/RoaringBitmap/roaring"
"github.com/remeh/sizedwaitgroup"
"github.com/negapedia/wikiassignment"
"github.com/negapedia/wikibots"
"github.com/negapedia/wikidump"
"github.com/negapedia/wikipage"
errorsO... | (ctx context.Context, fail func(err error) error, tmpDir, lang string, restrict bool) <-chan EvolvingPage {
//Default value to a closed channel
dummyPagesChan := make(chan EvolvingPage)
close(dummyPagesChan)
ID2Bot, err := wikibots.New(ctx, lang)
if err != nil {
fail(err)
return dummyPagesChan
}
latestDump... | New | identifier_name |
keys.rs | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long... | }
(&input[1..], None)
}
}
| return (&input[length..], Some(Key {
modifier: mods,
value: Char(string.chars().next().unwrap())
}));
}
| conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.