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 |
|---|---|---|---|---|
gobuild.go | // Copyright 2009-2010 by Maurice Gilden. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
gobuild - build tool to automate building go programs/libraries
*/
package main
// import "fmt"
import (
"os"
"runtime"
"exec"
"flag"
path "p... | case -benchmarks/-match/-v are also passed on.
*/
func buildTestExecutable() {
// this will create a file called "_testmain.go"
testPack := createTestPackage()
if compile(testPack) {
linkErrors = !link(testPack) || linkErrors
} else {
logger.Error("Can't link executable because of compile errors.\n")
compil... |
/*
Creates a new file called _testmain.go and compiles/links it to _testmain.
If the -run command line option is given it will also run the tests. In this | random_line_split |
gobuild.go | // Copyright 2009-2010 by Maurice Gilden. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
gobuild - build tool to automate building go programs/libraries
*/
package main
// import "fmt"
import (
"os"
"runtime"
"exec"
"flag"
path "p... | (argv []string) {
logger.Info("Executing %s:\n", argv[0])
logger.Debug("%s\n", getCommandline(argv))
cmd, err := exec.Run(argv[0], argv, os.Environ(), rootPath,
exec.PassThrough, exec.PassThrough, exec.PassThrough)
if err != nil {
logger.Error("%s\n", err)
os.Exit(1)
}
waitmsg, err := cmd.Wait(0)
if err !=... | runExec | identifier_name |
sa_collection.py | from __future__ import print_function
import mysql.connector
import requests
import time
import json
from http.cookies import SimpleCookie
from bs4 import BeautifulSoup
##################################
# #
# CONSTANTS #
# #
##########... | 'comment_date': self.date,
'content': self.text.encode('ascii', errors='ignore').decode(),
'parentID': self.parentID,
'discussionID': self.discussionID
}
##################################
# #
# FILE FUNCTIONS #
# ... | 'commentID': self.commentID,
'userID': self.userID, | random_line_split |
sa_collection.py | from __future__ import print_function
import mysql.connector
import requests
import time
import json
from http.cookies import SimpleCookie
from bs4 import BeautifulSoup
##################################
# #
# CONSTANTS #
# #
##########... | (self):
"""
Returns json representation of an article (for writing
to the database).
"""
if self.valid:
return {
'articleID': self._id,
'ticker_symbol': self.ticker,
'published_date': self.pub_date,
'auth... | json | identifier_name |
sa_collection.py | from __future__ import print_function
import mysql.connector
import requests
import time
import json
from http.cookies import SimpleCookie
from bs4 import BeautifulSoup
##################################
# #
# CONSTANTS #
# #
##########... |
def try_add_article(art_json, cursor):
"""
Given an article json, tries to write that article to database.
"""
try:
cursor.execute(add_article, art_json)
except mysql.connector.errors.IntegrityError:
print("Duplicate Article")
def try_add_db(art_json, com_jsons, cursor, article_... | """
Given array of comment jsons, adds comments to database.
"""
if not com_jsons:
print("\t No comments found for " + article_id)
for c in com_jsons:
try:
cursor.execute(add_comment, c)
except mysql.connector.DatabaseError as err:
if not err.errno == 106... | identifier_body |
sa_collection.py | from __future__ import print_function
import mysql.connector
import requests
import time
import json
from http.cookies import SimpleCookie
from bs4 import BeautifulSoup
##################################
# #
# CONSTANTS #
# #
##########... |
return r
def get_comment_jsons(article_id, cookie):
"""
Returns all comments for the given article as array of
jsons.
"""
url = "https://seekingalpha.com/account/ajax_get_comments?id=%s&type=Article&commentType=" % article_id
r = safe_request(url, cookie)
comments = []
if r.statu... | try:
r = requests.get(url, cookies=cookie, headers=user_agent)
if r.status_code != 200:
print(r.status_code, "blocked")
count += 1
else:
break
except requests.exceptions.ConnectionError:
print("timeout", url)
... | conditional_block |
set.js | "use strict";
module.exports = {
AbzanCharm: require("./AbzanCharm"),
AbzanFalconer: require("./AbzanFalconer"),
AcademyElite: require("./AcademyElite"),
AeonChronicler: require("./AeonChronicler"),
AkiriLineSlinger: require("./AkiriLineSlinger"),
AkroanHorse: require("./AkroanHorse"),
AleshaWhoSmilesatDe... | window.mtgSets.setC16 = module.exports;} | { window.mtgSets = {}; } | conditional_block |
set.js | "use strict";
module.exports = {
AbzanCharm: require("./AbzanCharm"),
AbzanFalconer: require("./AbzanFalconer"),
AcademyElite: require("./AcademyElite"),
AeonChronicler: require("./AeonChronicler"),
AkiriLineSlinger: require("./AkiriLineSlinger"),
AkroanHorse: require("./AkroanHorse"),
AleshaWhoSmilesatDe... | SaskiatheUnyielding: require("./SaskiatheUnyielding"),
SatyrWayfinder: require("./SatyrWayfinder"),
SavageLands: require("./SavageLands"),
ScavengingOoze: require("./ScavengingOoze"),
SeasideCitadel: require("./SeasideCitadel"),
SeatoftheSynod: require("./SeatoftheSynod"),
SeedsofRenewal: require("./Seeds... | SandsteppeCitadel: require("./SandsteppeCitadel"),
Sangromancer: require("./Sangromancer"), | random_line_split |
utils.rs | use crate::config::{config, CheckLook, CritterRates, MovingRates, SenseRates};
use tnf_common::{
dll::param_getters,
engine_types::{critter::Critter, map::Map},
primitives::{Hex, MaybeInvalid},
utils::map::{
get_distance_hex,
server::{get_hex_in_path, get_hex_in_path_wall},
HexEx... | {
if( !player.IsPlayer() ) return false;
if( !isLoadedGMs )
LoadGMs( player, 0, 0, 0 );
if( player.StatBase[ ST_ACCESS_LEVEL ] < ACCESS_MODER && ( player.GetAccess() >= ACCESS_MODER || isPocketGM( player.Id ) ) )
player.StatBase[ ST_ACCESS_LEVEL ] = ACCESS_MODER;
return player.StatBase[ ST_ACCESS_LEVEL ] >= ACCESS_M... | random_line_split | |
utils.rs | use crate::config::{config, CheckLook, CritterRates, MovingRates, SenseRates};
use tnf_common::{
dll::param_getters,
engine_types::{critter::Critter, map::Map},
primitives::{Hex, MaybeInvalid},
utils::map::{
get_distance_hex,
server::{get_hex_in_path, get_hex_in_path_wall},
HexEx... | er, rates: &MovingRates) -> f32 {
if cr.IsRuning {
rates.running
//} else if cr.is_walking() {
// rates.walking
} else {
rates.still
}
}
fn sense_mul(rates: &SenseRates, cr: &Critter, opponent: &Critter, look_dir: i8) -> f32 {
rates.dir... | (cr: &Critt | identifier_name |
utils.rs | use crate::config::{config, CheckLook, CritterRates, MovingRates, SenseRates};
use tnf_common::{
dll::param_getters,
engine_types::{critter::Critter, map::Map},
primitives::{Hex, MaybeInvalid},
utils::map::{
get_distance_hex,
server::{get_hex_in_path, get_hex_in_path_wall},
HexEx... | enses: Vec<(f32, f32)> = config
.senses
.iter()
.map(|sense| {
let critter_rates = if self_is_npc {
&sense.npc
} else {
&sense.player
};
let basic_dist = basic_dist(critter_rates, cr_perception);
let sens... | ates.dir_rate[look_dir as usize]
* moving_rate(cr, &rates.self_moving)
* moving_rate(opponent, &rates.target_moving)
}
let s | identifier_body |
utils.rs | use crate::config::{config, CheckLook, CritterRates, MovingRates, SenseRates};
use tnf_common::{
dll::param_getters,
engine_types::{critter::Critter, map::Map},
primitives::{Hex, MaybeInvalid},
utils::map::{
get_distance_hex,
server::{get_hex_in_path, get_hex_in_path_wall},
HexEx... | ;
if dist > cr_hex.get_distance(end_hex) {
is_view = false;
hear_mul *= match cr_perception {
1..=4 => 0.1,
5..=8 => 0.3,
9..=10 => 0.4,
_ => 1.0,
};
}
if dist > max_view {
is_view = false;
}
let max_hear = (max_hear as... | , cr_hex, opp_hex, 0.0, dist) | conditional_block |
token_flow.go | package cautils
import (
"crypto"
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/authority/provisioner"
"github.com/smallstep/cli/crypto/pki"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/exec"
"github.com/smallste... | audience, err := url.Parse(caURL)
if err != nil {
return "", errs.InvalidFlagValue(ctx, "ca-url", caURL, "")
}
switch strings.ToLower(audience.Scheme) {
case "https", "":
var path string
switch tokType {
// default
case SignType, SSHUserSignType, SSHHostSignType:
path = "/1.0/sign"
// revocation tok... | }
| random_line_split |
token_flow.go | package cautils
import (
"crypto"
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/authority/provisioner"
"github.com/smallstep/cli/crypto/pki"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/exec"
"github.com/smallste... | (provisioners provisioner.List, f func(provisioner.Interface) bool) provisioner.List {
var result provisioner.List
for _, p := range provisioners {
if f(p) {
result = append(result, p)
}
}
return result
}
| provisionerFilter | identifier_name |
token_flow.go | package cautils
import (
"crypto"
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/authority/provisioner"
"github.com/smallstep/cli/crypto/pki"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/exec"
"github.com/smallste... |
out, err := exec.Step(args...)
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
case *provisioner.GCP: // Do the identity request to get the token
sharedContext.DisableCustomSANs = p.DisableCustomSANs
return p.GetIdentityToken(subject, caURL)
case *provisioner.AWS: // Do the... | {
args = append(args, "--listen", p.ListenAddress)
} | conditional_block |
token_flow.go | package cautils
import (
"crypto"
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/authority/provisioner"
"github.com/smallstep/cli/crypto/pki"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/exec"
"github.com/smallste... |
// provisionerFilter returns a slice of provisioners that pass the given filter.
func provisionerFilter(provisioners provisioner.List, f func(provisioner.Interface) bool) provisioner.List {
var result provisioner.List
for _, p := range provisioners {
if f(p) {
result = append(result, p)
}
}
return result
}... | {
// Filter by type
provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
switch p.GetType() {
case provisioner.TypeJWK, provisioner.TypeOIDC, provisioner.TypeACME:
return true
case provisioner.TypeGCP, provisioner.TypeAWS, provisioner.TypeAzure:
return true
default:
ret... | identifier_body |
recorder.go | // Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
// Gather descriptor from store.
descriptor, err := mr.mu.stores[storeID].Descriptor()
if err != nil {
log.Errorf("Could not record status summaries: Store %d could not return descriptor, error: %s", storeID, err)
}
status := storage.StoreStatus{
Desc: *descriptor,
NodeID: ... | {
gauge := r.GetGauge(name)
if gauge == nil {
log.Errorf("Could not record status summaries: Store %d did not have '%s' gauge in registry.", storeID, name)
return nil, nil
}
gauges[name] = gauge
} | conditional_block |
recorder.go | // Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
// GetStatusSummaries returns a status summary messages for the node, along with
// a status summary for every individual store within the node.
// TODO(mrtracy): The status summaries deserve a near-term, significant
// overhaul. Their primary usage is as an indicator of the most recent metrics
// of a node or store ... | {
mr.mu.Lock()
defer mr.mu.Unlock()
if mr.mu.desc.NodeID == 0 {
// We haven't yet processed initialization information; do nothing.
if log.V(1) {
log.Warning("MetricsRecorder.GetTimeSeriesData() called before NodeID allocation")
}
return nil
}
data := make([]ts.TimeSeriesData, 0, mr.mu.lastDataCount)
... | identifier_body |
recorder.go | // Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | storeLevel[strconv.Itoa(int(id))] = reg
}
topLevel["stores"] = storeLevel
return json.Marshal(topLevel)
}
// GetTimeSeriesData serializes registered metrics for consumption by
// CockroachDB's time series system.
func (mr *MetricsRecorder) GetTimeSeriesData() []ts.TimeSeriesData {
mr.mu.Lock()
defer mr.mu.Unloc... | for id, reg := range mr.mu.storeRegistries { | random_line_split |
recorder.go | // Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (prefixFmt string, registry *metric.Registry) {
mr.nodeRegistry.MustAdd(prefixFmt, registry)
}
// AddStore adds the Registry from the provided store as a store-level registry
// in this recoder. A reference to the store is kept for the purpose of
// gathering some additional information which is present in store stat... | AddNodeRegistry | identifier_name |
sdkcallback.go | package main
import (
"crypto/md5"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
proto "code.google.com/p/goprotobuf/proto"
martini "github.com/codegangsta/martini"
nats "github.com/nats-io/nats"
batteryapi "guanghuan.com/xiaoyao/ba... | rameterslice {
if parameterslice[k].key != "sign" {
keys = append(keys, parameterslice[k].key)
}
}
sort.Strings(keys) // 参数升序排序
for index, arg := range keys {
v, result := parameterslice.Get(arg)
if result {
uriStr = fmt.Sprintf("%s%s=%s", uriStr, arg... | identifier_body | |
sdkcallback.go | package main
import (
"crypto/md5"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
proto "code.google.com/p/goprotobuf/proto"
martini "github.com/codegangsta/martini"
nats "github.com/nats-io/nats"
batteryapi "guanghuan.com/xiaoyao/ba... | error.ErrOK {
xylog.WarningNoId("strconv.ParseUint for uid failed : %v", err)
err = xyerror.ErrOK
} else {
req.GoodsId = proto.Uint64(goodsId)
}
v = r.PostFormValue(CallParameter_Sandbox)
if v == "" {
xylog.ErrorNoId("get sandbox from parameterfail")
return nil, ... |
parameterSlice.Add(CallParameter_EXT, v)
goodsId, err = strconv.ParseUint(v, 10, 64)
if err != xy | conditional_block |
sdkcallback.go | package main
import (
"crypto/md5"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
proto "code.google.com/p/goprotobuf/proto"
martini "github.com/codegangsta/martini"
nats "github.com/nats-io/nats"
batteryapi "guanghuan.com/xiaoyao/ba... | }
respone := &battery.SDKAddOrderResponse{}
err = proto.Unmarshal(respData, respone)
if err != nil {
resp = "unmarshal false"
return
}
if respone.Error.GetCode() != battery.ErrorCode_NoError {
resp = "add order fail"
return
}
resp = "ok"
return
}
/... | random_line_split | |
sdkcallback.go | package main
import (
"crypto/md5"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
proto "code.google.com/p/goprotobuf/proto"
martini "github.com/codegangsta/martini"
nats "github.com/nats-io/nats"
batteryapi "guanghuan.com/xiaoyao/ba... | ng, 0, len(parameterslice))
for k := range parameterslice {
if parameterslice[k].key != "sign" {
keys = append(keys, parameterslice[k].key)
}
}
sort.Strings(keys) // 参数升序排序
for index, arg := range keys {
v, result := parameterslice.Get(arg)
if result {
... | := make([]stri | identifier_name |
vjAnnotListTableView.js | /*
* ::718604!
*
* Copyright(C) November 20, 2014 U.S. Food and Drug Administration
* Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al
* Affiliation: Food and Drug Administration (1), George Washington University (2)
*
* All rights Reserved.
*
* The MIT License (MIT)
*
* Permission is hereb... |
_mainControl_.constructViewers = function() {
this.constructPanel();
this.constructTable();
this.constructSubmitPanel();
this.reload();
}
// Construct All Viewers
this.constructViewers();
return [this.anotPanel, this.manualPanel,this.anotTable, this.checked... | this.viewersArr.push(this.anotSubmitPanel);
} | random_line_split |
vjAnnotListTableView.js | /*
* ::718604!
*
* Copyright(C) November 20, 2014 U.S. Food and Drug Administration
* Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al
* Affiliation: Food and Drug Administration (1), George Washington University (2)
*
* All rights Reserved.
*
* The MIT License (MIT)
*
* Permission is hereb... |
}
return 1;
}
function accumulateRows (viewer, node, ir,ic) {
var objAdded = _mainControl_.objAdded;
var range = "", seqID ="", type = "", id= "",strand = "+", checked = true;
if (viewer.myName && viewer.myName=="manualPanel")
{
seqID = view... | {
return dicPath[myArr[ia]];
} | conditional_block |
vjAnnotListTableView.js | /*
* ::718604!
*
* Copyright(C) November 20, 2014 U.S. Food and Drug Administration
* Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al
* Affiliation: Food and Drug Administration (1), George Washington University (2)
*
* All rights Reserved.
*
* The MIT License (MIT)
*
* Permission is hereb... |
_mainControl_.reload = function () {
if (this.annotObjList.length){
var ionList = this.annotObjList.join(",");
var refList = this.referenceObjList.join(";");
this.annotTypeDS.url = urlExchangeParameter(this.defaultAnnotUrl, "ionObjs", ionList);
this... | {
console.log("removing selected element");
var checkedTbl = _mainControl_.checkedTable;
var objAdded = _mainControl_.objAdded;
for (var i=0; i<checkedTbl.selectedCnt; ++i) {
var curNode = checkedTbl.selectedNodes[i];
if (objAdded[curNode.seqID]) {
... | identifier_body |
vjAnnotListTableView.js | /*
* ::718604!
*
* Copyright(C) November 20, 2014 U.S. Food and Drug Administration
* Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al
* Affiliation: Food and Drug Administration (1), George Washington University (2)
*
* All rights Reserved.
*
* The MIT License (MIT)
*
* Permission is hereb... | (dicPath, curPath) {
var myArr = Object.keys(dicPath);
for (var ia=0; ia<myArr.length; ++ia) {
if (curPath.indexOf(myArr[ia])!=-1) {
return dicPath[myArr[ia]];
}
}
return 1;
}
function accumulateRows (viewer, node, ir,ic) {
va... | checkDirection | identifier_name |
fifo.rs | // 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... | (
#[values(true, false)] unbounded_file: bool,
) -> Result<()> {
// Create session context
let config = SessionConfig::new()
.with_batch_size(TEST_BATCH_SIZE)
.with_collect_statistics(false)
.with_target_partitions(1);
let ctx = SessionContext::wit... | unbounded_file_with_swapped_join | identifier_name |
fifo.rs | // 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 {
JoinOperation::LeftUnmatched
};
operations.push(op);
}
tasks.into_iter().for_each(|jh| jh.join().unwrap());
// The SymmetricHashJoin executor produces FULL join results at every
// pruning, which happens before it reaches the end of input a... | {
JoinOperation::RightUnmatched
} | conditional_block |
fifo.rs | // 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... | }
// This test provides a relatively realistic end-to-end scenario where
// we swap join sides to accommodate a FIFO source.
#[rstest]
#[timeout(std::time::Duration::from_secs(30))]
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
async fn unbounded_file_with_swapped_join(
... | }
}
return Err(DataFusionError::Execution(e.to_string()));
}
Ok(()) | random_line_split |
gpt.go | package gpt
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"github.com/qeedquan/disktools/endian"
"github.com/qeedquan/disktools/mbr"
)
type Option struct {
Sectsz int
}
type GUID [16]byte
type Header struct {
Sig [8]byte
Rev uint32
Hdrsz uint32
Hdrcrc uint32
_ uint32
... |
func MustParseGUID(guid string) GUID {
p, err := ParseGUID(guid)
if err != nil {
panic(err)
}
return p
}
func (p GUID) String() string {
return fmt.Sprintf("%X-%X-%X-%X-%X",
endian.Read32be(p[0:]),
endian.Read32be(p[4:]),
endian.Read32be(p[6:]),
endian.Read32be(p[8:]),
endian.Read48be(p[10:]),
)
}
... | {
var (
a uint32
b, c, d uint16
e uint64
p [16]byte
)
n, err := fmt.Sscanf(guid, "%x-%x-%x-%x-%x", &a, &b, &c, &d, &e)
if err != nil {
return p, err
}
if n != 5 {
return p, errors.New("invalid GUID format")
}
endian.Put32le(p[0:], a)
endian.Put16le(p[4:], b)
endian.Put16le(p[6:]... | identifier_body |
gpt.go | package gpt
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"github.com/qeedquan/disktools/endian"
"github.com/qeedquan/disktools/mbr"
)
type Option struct {
Sectsz int
}
type GUID [16]byte
type Header struct {
Sig [8]byte
Rev uint32
Hdrsz uint32
Hdrcrc uint32
_ uint32
... |
if d.MBR.Part[0].Type != 0xee {
return ErrHeader
}
d.Header, err = d.readHeader(int64(d.Sectsz))
if err != nil {
return err
}
d.Entries, err = d.readEntry(int64(d.Sectsz * 2))
if err != nil {
return err
}
return nil
}
func (d *decoder) readHeader(off int64) (Header, error) {
var h Header
sr := io.... | } | random_line_split |
gpt.go | package gpt
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"github.com/qeedquan/disktools/endian"
"github.com/qeedquan/disktools/mbr"
)
type Option struct {
Sectsz int
}
type GUID [16]byte
type Header struct {
Sig [8]byte
Rev uint32
Hdrsz uint32
Hdrcrc uint32
_ uint32
... | () error {
var err error
d.MBR, err = mbr.Open(d.r)
if err != nil {
return err
}
if d.MBR.Part[0].Type != 0xee {
return ErrHeader
}
d.Header, err = d.readHeader(int64(d.Sectsz))
if err != nil {
return err
}
d.Entries, err = d.readEntry(int64(d.Sectsz * 2))
if err != nil {
return err
}
return n... | decode | identifier_name |
gpt.go | package gpt
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"github.com/qeedquan/disktools/endian"
"github.com/qeedquan/disktools/mbr"
)
type Option struct {
Sectsz int
}
type GUID [16]byte
type Header struct {
Sig [8]byte
Rev uint32
Hdrsz uint32
Hdrcrc uint32
_ uint32
... |
d := decoder{
r: r,
Table: Table{Sectsz: o.Sectsz},
}
err := d.decode()
if err != nil {
return nil, err
}
return &d.Table, nil
}
type decoder struct {
Table
r io.ReaderAt
}
func (d *decoder) decode() error {
var err error
d.MBR, err = mbr.Open(d.r)
if err != nil {
return err
}
if d.MBR.Par... | {
o = &Option{Sectsz: 512}
} | conditional_block |
serving.py | # coding:utf-8
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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 req... |
else:
if self.args.use_multiprocess:
if platform.system() == "Windows":
log.logger.warning(
"Warning: Windows cannot use multiprocess working mode, PaddleHub Serving will switch to single process mode"
)
... | if self.args.use_multiprocess:
log.logger.warning('`use_multiprocess` will be ignored if specify `use_gpu`.')
self.start_zmq_serving_with_args() | conditional_block |
serving.py | # coding:utf-8
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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 req... |
if not pid_is_exist(pid):
log.logger.info("PaddleHub Serving has been stopped.")
return
log.logger.info("PaddleHub Serving will stop.")
if platform.system() == "Windows":
os.kill(pid, signal.SIGTERM)
else:
try:
os.killpg(pi... | if os.path.exists(filepath):
os.remove(filepath) | random_line_split |
serving.py | # coding:utf-8
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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 req... |
@staticmethod
def show_help():
str = "serving <option>\n"
str += "\tManage PaddleHub Serving.\n"
str += "sub command:\n"
str += "1. start\n"
str += "\tStart PaddleHub Serving.\n"
str += "2. stop\n"
str += "\tStop PaddleHub Serving.\n"
str += "3. ... | '''
Start PaddleHub-Serving with flask and gunicorn
'''
if self.args.use_gpu:
if self.args.use_multiprocess:
log.logger.warning('`use_multiprocess` will be ignored if specify `use_gpu`.')
self.start_zmq_serving_with_args()
else:
if self... | identifier_body |
serving.py | # coding:utf-8
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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 req... | (args):
'''
Start bert serving server.
'''
if platform.system() != "Linux":
log.logger.error("Error. Bert Service only support linux.")
return False
if is_port_occupied("127.0.0.1", args.port) is True:
log.logger.error("Port %s is occupied, pl... | start_bert_serving | identifier_name |
main.rs | use clap::{App, AppSettings, Arg, SubCommand};
use default_boxed::DefaultBoxed;
#[derive(DefaultBoxed)]
struct Outer<'a, 'b> {
inner: HeapApp<'a, 'b>,
}
struct HeapApp<'a, 'b> {
app: App<'a, 'b>,
}
impl<'a, 'b> Default for HeapApp<'a, 'b> {
fn | () -> Self {
let mut app = App::new("servicemanagement1")
.setting(clap::AppSettings::ColoredHelp)
.author("Sebastian Thiel <byronimo@gmail.com>")
.version("0.1.0-20200619")
.about("Google Service Management allows service producers to publish their services on Go... | default | identifier_name |
main.rs | use clap::{App, AppSettings, Arg, SubCommand};
use default_boxed::DefaultBoxed;
#[derive(DefaultBoxed)]
struct Outer<'a, 'b> {
inner: HeapApp<'a, 'b>,
}
struct HeapApp<'a, 'b> {
app: App<'a, 'b>,
}
impl<'a, 'b> Default for HeapApp<'a, 'b> {
fn default() -> Self {
let mut app = App::new("servicema... | use google_servicemanagement1 as api;
fn main() {
// TODO: set homedir afterwards, once the address is unmovable, or use Pin for the very first time
// to allow a self-referential structure :D!
let _home_dir = dirs::config_dir()
.expect("configuration directory can be obtained")
.join("goog... | random_line_split | |
main.rs | use clap::{App, AppSettings, Arg, SubCommand};
use default_boxed::DefaultBoxed;
#[derive(DefaultBoxed)]
struct Outer<'a, 'b> {
inner: HeapApp<'a, 'b>,
}
struct HeapApp<'a, 'b> {
app: App<'a, 'b>,
}
impl<'a, 'b> Default for HeapApp<'a, 'b> {
fn default() -> Self {
let mut app = App::new("servicema... | {
// TODO: set homedir afterwards, once the address is unmovable, or use Pin for the very first time
// to allow a self-referential structure :D!
let _home_dir = dirs::config_dir()
.expect("configuration directory can be obtained")
.join("google-service-cli");
let outer = Outer::default_... | identifier_body | |
cert.go | // http://golang.org/src/pkg/crypto/tls/generate_cert.go
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shared
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha25... | (input string) (*api.CertificateAddToken, error) {
joinTokenJSON, err := base64.StdEncoding.DecodeString(input)
if err != nil {
return nil, err
}
var j api.CertificateAddToken
err = json.Unmarshal(joinTokenJSON, &j)
if err != nil {
return nil, err
}
if j.ClientName == "" {
return nil, fmt.Errorf("No cli... | CertificateTokenDecode | identifier_name |
cert.go | // http://golang.org/src/pkg/crypto/tls/generate_cert.go
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shared
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha25... |
func CertFingerprintStr(c string) (string, error) {
pemCertificate, _ := pem.Decode([]byte(c))
if pemCertificate == nil {
return "", fmt.Errorf("invalid certificate")
}
cert, err := x509.ParseCertificate(pemCertificate.Bytes)
if err != nil {
return "", err
}
return CertFingerprint(cert), nil
}
func GetR... | {
return fmt.Sprintf("%x", sha256.Sum256(cert.Raw))
} | identifier_body |
cert.go | // http://golang.org/src/pkg/crypto/tls/generate_cert.go
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shared
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha25... | if err != nil {
hostname = "UNKNOWN"
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"LXD"},
CommonName: fmt.Sprintf("%s@%s", username, hostname),
},
NotBefore: validFrom,
NotAfter: validTo,
KeyUsage: x509.KeyUsageKeyEnciphe... | } else {
username = "UNKNOWN"
}
hostname, err := os.Hostname() | random_line_split |
cert.go | // http://golang.org/src/pkg/crypto/tls/generate_cert.go
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package shared
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha25... |
dir = filepath.Dir(keyf)
err = os.MkdirAll(dir, 0750)
if err != nil {
return err
}
certBytes, keyBytes, err := GenerateMemCert(certtype, addHosts)
if err != nil {
return err
}
certOut, err := os.Create(certf)
if err != nil {
return fmt.Errorf("Failed to open %s for writing: %w", certf, err)
}
_, e... | {
return err
} | conditional_block |
ycsb.rs | /* Copyright (c) 2018 University of Utah
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DIS... |
// Add the receiver to a netbricks pipeline.
match scheduler.add_task(YcsbRecv::new(
ports[0].clone(),
34 * 1000 * 1000 as u64,
master,
native,
)) {
Ok(_) => {
info!(
"Successfully added YcsbRecv with rx queue {}.",
ports[... | {
error!("Client should be configured with exactly 1 port!");
std::process::exit(1);
} | conditional_block |
ycsb.rs | /* Copyright (c) 2018 University of Utah
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DIS... |
fn dependencies(&mut self) -> Vec<usize> {
vec![]
}
}
/// Receives responses to YCSB requests sent out by YcsbSend.
struct YcsbRecv<T>
where
T: PacketTx + PacketRx + Display + Clone + 'static,
{
// The network stack required to receives RPC response packets from a network port.
receiver: ... | {
// Return if there are no more requests to generate.
if self.requests <= self.sent {
return;
}
// Get the current time stamp so that we can determine if it is time to issue the next RPC.
let curr = cycles::rdtsc();
// If it is either time to send out a req... | identifier_body |
ycsb.rs | /* Copyright (c) 2018 University of Utah
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DIS... | // Setup Netbricks.
let mut net_context = setup::config_and_init_netbricks(&config);
// Setup the client pipeline.
net_context.start_schedulers();
// The core id's which will run the sender and receiver threads.
// XXX The following two arrays heavily depend on the set of cores
// configur... | random_line_split | |
ycsb.rs | /* Copyright (c) 2018 University of Utah
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DIS... | (port: T, resps: u64, master: bool, native: bool) -> YcsbRecv<T> {
YcsbRecv {
receiver: dispatch::Receiver::new(port),
responses: resps,
start: cycles::rdtsc(),
recvd: 0,
latencies: Vec::with_capacity(resps as usize),
master: master,
... | new | identifier_name |
workspace.rs | use std::mem;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::ffi::OsStr;
use std::collections::{hash_map, HashMap};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use futures::{future, stream, Future, Stream, BoxFuture};
use futures_cpupool::CpuPool;
use url::Url;
use parking_lot::{R... | (&mut self, version: u64,
event: protocol::TextDocumentContentChangeEvent) -> WorkspaceResult<()> {
// TODO, there are several ambiguities with offsets?
if event.range.is_some() || event.rangeLength.is_some() {
return Err(WorkspaceError("incremental edits not yet supp... | apply_change | identifier_name |
workspace.rs | use std::mem;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::ffi::OsStr;
use std::collections::{hash_map, HashMap};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use futures::{future, stream, Future, Stream, BoxFuture};
use futures_cpupool::CpuPool;
use url::Url;
use parking_lot::{R... | impl fmt::Debug for Workspace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Workspace")
.field("message_locale", &self.message_locale)
.field("pool", &Ellipsis)
.field("files", &self.files)
.field("source", &Ellipsis)
.field("shared", &... | random_line_split | |
workspace.rs | use std::mem;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::ffi::OsStr;
use std::collections::{hash_map, HashMap};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use futures::{future, stream, Future, Stream, BoxFuture};
use futures_cpupool::CpuPool;
use url::Url;
use parking_lot::{R... |
pub fn on_file_deleted(&self, uri: &str) {
if let Ok(path) = uri_to_path(uri) {
let mut files = self.files.write();
if let Some(file) = files.remove(&path) {
self.destroy_file(file);
}
}
}
#[allow(dead_code)]
pub fn cancel(&self) {
... | {
if let Ok(path) = uri_to_path(uri) {
let file = self.ensure_file(&path);
file.cancel();
let _ = file.ensure_chunk();
Some(file)
} else {
None
}
} | identifier_body |
train.py | ''' Sentence VAE '''
import os
import sys
import json
import time
import math
import random
import argparse
import ipdb as pdb
import logging as log
import torch
import torch.optim as optim
from torch.nn.utils import clip_grad_norm
import numpy as np
from multiprocessing import cpu_count
from tensorboardX import Summa... |
with open(os.path.join('dumps/'+ ts +'/valid_E%i.json'%epoch), 'w') as dump_file:
json.dump(dump, dump_file)
if loss < global_tracker['best_score'] or global_tracker['best_score'] < 0:
log.info(" Best model found")
global_trac... | os.makedirs('dumps/' + ts) | conditional_block |
train.py | ''' Sentence VAE '''
import os
import sys
import json
import time
import math
import random
import argparse
import ipdb as pdb
import logging as log
import torch
import torch.optim as optim
from torch.nn.utils import clip_grad_norm
import numpy as np
from multiprocessing import cpu_count
from tensorboardX import Summa... |
def loss_fn(NLL, logp, target, length, mean, logv, anneal_function, step, k, x0):
# cut-off unnecessary padding from target, and flatten
target = target[:, :torch.max(length).data[0]].contiguous().view(-1)
logp = logp.view(-1, logp.size(2))
# Negative Log Likelihood
nll_loss = NLL(logp, target)
... | if anneal_function == 'logistic':
return float(1/(1+np.exp(-k*(step-x0))))
elif anneal_function == 'linear':
return min(1, step/x0) | identifier_body |
train.py | ''' Sentence VAE '''
import os
import sys
import json
import time
import math
import random
import argparse
import ipdb as pdb
import logging as log
import torch
import torch.optim as optim
from torch.nn.utils import clip_grad_norm
import numpy as np
from multiprocessing import cpu_count
from tensorboardX import Summa... | parser = argparse.ArgumentParser()
parser.add_argument('--seed', help='random seed', type=int, default=19)
parser.add_argument('-gpu', '--gpu_id', help='GPU ID', type=int, default=0)
parser.add_argument('--run_dir', help='prefix to save ckpts to', type=str,
default=SCR_PREFIX + ... | def main(arguments): | random_line_split |
train.py | ''' Sentence VAE '''
import os
import sys
import json
import time
import math
import random
import argparse
import ipdb as pdb
import logging as log
import torch
import torch.optim as optim
from torch.nn.utils import clip_grad_norm
import numpy as np
from multiprocessing import cpu_count
from tensorboardX import Summa... | (NLL, logp, target, length, mean, logv, anneal_function, step, k, x0):
# cut-off unnecessary padding from target, and flatten
target = target[:, :torch.max(length).data[0]].contiguous().view(-1)
logp = logp.view(-1, logp.size(2))
# Negative Log Likelihood
nll_loss = NLL(logp, target)
# KL Div... | loss_fn | identifier_name |
menu.rs | //! Menu abstrction module
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use dbusmenu::ComCanonicalDbusmenu;
use dbus::arg;
use dbus;
#[derive(Default)]
pub struct Menu {
/// - `revision: i32`: The revision number of the layout.
/// For matching with layoutUpdated signals.
revis... |
fn get_status(&self) -> Result<String, Self::Err> {
println!("get_status called!");
// Menus will always be in "normal" state, may change later on
Ok("normal".into())
}
}
#[derive(Default, Clone)]
pub struct MData;
impl<'a> dbus::tree::DataType for MData {
type Tree = ();
type ... |
// ????
println!("about_to_show called!");
Ok(3)
}
| identifier_body |
menu.rs | //! Menu abstrction module
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use dbusmenu::ComCanonicalDbusmenu;
use dbus::arg;
use dbus;
#[derive(Default)]
pub struct Menu {
/// - `revision: i32`: The revision number of the layout.
/// For matching with layoutUpdated signals.
revis... | &self) -> Result<u32, Self::Err> {
// ????
println!("about_to_show called!");
Ok(3)
}
fn get_status(&self) -> Result<String, Self::Err> {
println!("get_status called!");
// Menus will always be in "normal" state, may change later on
Ok("normal".into())
}
}
#... | et_version( | identifier_name |
menu.rs | //! Menu abstrction module
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use dbusmenu::ComCanonicalDbusmenu;
use dbus::arg;
use dbus;
#[derive(Default)]
pub struct Menu {
/// - `revision: i32`: The revision number of the layout.
/// For matching with layoutUpdated signals.
revis... | }
#[derive(Default, Clone)]
pub struct MData;
impl<'a> dbus::tree::DataType for MData {
type Tree = ();
type ObjectPath = Menu; // Every objectpath in the tree now owns a menu object.
type Property = ();
type Interface = ();
type Method = ();
type Signal = ();
}
/// Since parts of the menu ar... | random_line_split | |
poll_evented.rs | use crate::io::driver::{Direction, Handle, ReadyEvent};
use crate::io::registration::Registration;
use crate::io::{AsyncRead, AsyncWrite, ReadBuf};
use mio::event::Evented;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::pin::Pin;
use std::task::{Context, Poll};
cfg_io_driver! {
/... | (mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
loop {
let ev = ready!(self.poll_write_ready(cx))?;
let r = (*self).get_mut().flush();
if is_wouldblock(&r) {
self.clear_readiness(ev);
continue;
}
... | poll_flush | identifier_name |
poll_evented.rs | use crate::io::driver::{Direction, Handle, ReadyEvent};
use crate::io::registration::Registration;
use crate::io::{AsyncRead, AsyncWrite, ReadBuf};
use mio::event::Evented;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::pin::Pin;
use std::task::{Context, Poll};
cfg_io_driver! {
/... |
/// Returns a shared reference to the underlying I/O object this readiness
/// stream is wrapping.
#[cfg(any(
feature = "process",
feature = "tcp",
feature = "udp",
feature = "uds",
feature = "signal"
))]
pub(crate) fn get_ref(&self) -> &E {
self.io.... | {
let registration = Registration::new_with_ready_and_handle(&io, ready, handle)?;
Ok(Self {
io: Some(io),
registration,
})
} | identifier_body |
poll_evented.rs | use crate::io::driver::{Direction, Handle, ReadyEvent};
use crate::io::registration::Registration;
use crate::io::{AsyncRead, AsyncWrite, ReadBuf};
use mio::event::Evented;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::pin::Pin;
use std::task::{Context, Poll};
cfg_io_driver! {
/... |
return Poll::Ready(r.map(|n| {
buf.add_filled(n);
}));
}
}
}
impl<E> AsyncWrite for PollEvented<E>
where
E: Evented + Write + Unpin,
{
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Resul... | {
self.clear_readiness(ev);
continue;
} | conditional_block |
poll_evented.rs | use crate::io::driver::{Direction, Handle, ReadyEvent};
use crate::io::registration::Registration;
use crate::io::{AsyncRead, AsyncWrite, ReadBuf};
use mio::event::Evented;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::pin::Pin;
use std::task::{Context, Poll};
cfg_io_driver! {
/... | ///
/// # Warning
///
/// This method may not be called concurrently. It takes `&self` to allow
/// calling it concurrently with `poll_write_ready`.
pub(crate) fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> {
self.registration.poll_readiness(cx, Direction... | /// This function panics if:
///
/// * `ready` includes writable.
/// * called from outside of a task context. | random_line_split |
projects.ts | export default [
{
year: 2018,
name: {
ru: 'Мобильное приложение Hello TV',
en: 'Hello TV mobile app',
},
description: {
ru: 'Мобильное приложение для iOS и Android. Реализован личный кабинет учеников, которые могут видеть свои достижения и доступные награды. Зайти в него можно по ло... | name: {ru: 'Рабочий репозиторий проекта', en: 'Project\'s working repository'},
icon: 'github'
}
],
feedback: true,
best: true,
forBanner: true
},
{
year: 2015,
name: {ru: 'Мой первый личный сайт', en: 'My first personal site'},
description: {ru: 'Представлена фотог... | {
url: 'https://github.com/polyakovin/yourChoice2', | random_line_split |
api.go | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package grpc
import (
"context"
"errors"
"fmt"
"time"
"github.com/dapr/components-contrib/bindings"
"github.... |
req.Options.RetryPolicy = retryPolicy
}
}
err := a.stateStores[storeName].Delete(&req)
if err != nil {
return &empty.Empty{}, fmt.Errorf("ERR_STATE_DELETE: failed deleting state with key %s: %s", in.Key, err)
}
return &empty.Empty{}, nil
}
func (a *api) getModifiedStateKey(key string) string {
if a.id !... | {
dur, err := duration(in.Options.RetryPolicy.Interval)
if err == nil {
retryPolicy.Interval = dur
}
} | conditional_block |
api.go | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package grpc
import (
"context"
"errors"
"fmt"
"time"
"github.com/dapr/components-contrib/bindings"
"github.... | (key string) string {
if a.id != "" {
return fmt.Sprintf("%s%s%s", a.id, daprSeparator, key)
}
return key
}
func duration(p *durpb.Duration) (time.Duration, error) {
if err := validateDuration(p); err != nil {
return 0, err
}
d := time.Duration(p.Seconds) * time.Second
if int64(d/time.Second) != p.Seconds {... | getModifiedStateKey | identifier_name |
api.go | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package grpc
import (
"context"
"errors"
"fmt"
"time"
"github.com/dapr/components-contrib/bindings"
"github.... | for _, s := range in.Requests {
req := state.SetRequest{
Key: a.getModifiedStateKey(s.Key),
Metadata: s.Metadata,
Value: s.Value.Value,
}
if s.Options != nil {
req.Options = state.SetStateOption{
Consistency: s.Options.Consistency,
Concurrency: s.Options.Concurrency,
}
if s.Opti... |
reqs := []state.SetRequest{} | random_line_split |
api.go | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package grpc
import (
"context"
"errors"
"fmt"
"time"
"github.com/dapr/components-contrib/bindings"
"github.... |
func (a *api) DeleteState(ctx context.Context, in *dapr_pb.DeleteStateEnvelope) (*empty.Empty, error) {
if a.stateStores == nil || len(a.stateStores) == 0 {
return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_CONFIGURED")
}
storeName := in.StoreName
if a.stateStores[storeName] == nil {
return &empty.Empt... | {
if a.stateStores == nil || len(a.stateStores) == 0 {
return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_CONFIGURED")
}
storeName := in.StoreName
if a.stateStores[storeName] == nil {
return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_FOUND")
}
reqs := []state.SetRequest{}
for _, s := range in.Req... | identifier_body |
relay.py | import time
import zones
import smbus
import GD
import system
################################################################################
##
## Function: ActivateSystemRelay (I2CPort, systemRelay, setHigh)
##
## Parameters: I2CPort - I2C smbus object
## systemRelay - the relay to activate
## ... |
################################################################################
##
## Function: ActivateHeatingZoneRelay (I2CPort, relayZone)
##
## Parameters: I2CPort - I2C smbus object
## relayZone - integer - the zone to check if activation required.
##
## Returns:
##
## Globals modified:
##
#... | relayStatus = I2CPort.read_byte (register)
# Set the relay to pulse (active low pulse).
relayStatus &= ~relayBit
# Pulse it low.
I2CPort.write_byte (register, relayStatus)
print 'pulse on ', hex(relayStatus^0xff)
# Give it some time to activate.
time.sleep (0.1)
# Now set up to cl... | identifier_body |
relay.py | import time
import zones
import smbus
import GD
import system
################################################################################
##
## Function: ActivateSystemRelay (I2CPort, systemRelay, setHigh)
##
## Parameters: I2CPort - I2C smbus object
## systemRelay - the relay to activate
## ... | (I2CPort) :
for systemOutput in GD.SYSTEM_PULSED_OUTPUTS_GROUP :
if system.systemControl [systemOutput].CheckIfBitTimerFinished () == True :
ActivateSystemRelay (I2CPort, systemOutput, False)
print 'SET IT LOW'
#############################################################... | UpdatePulsedOutputLines | identifier_name |
relay.py | import time
import zones
import smbus
import GD
import system
################################################################################
##
## Function: ActivateSystemRelay (I2CPort, systemRelay, setHigh)
##
## Parameters: I2CPort - I2C smbus object
## systemRelay - the relay to activate
## ... |
# Has the status changed or is it time for cleardown on this zone?
if statusChanged or clearDown :
print 'STATUS CHANGED'
# Select the correct I2C status register for UFH or RAD relays.
register = GD.I2C_ADDRESS_0X38 if relayZone >= 14 else GD.I2C_ADDRESS_0X39
# R... | zones.zoneData[relayZone].UpdateCurrentZoneStatus() | conditional_block |
relay.py | import time
import zones
import smbus
import GD
import system
################################################################################
##
## Function: ActivateSystemRelay (I2CPort, systemRelay, setHigh)
##
## Parameters: I2CPort - I2C smbus object
## systemRelay - the relay to activate
## ... |
# TEMP TO ALLOW WITHOUT SYSTEM HARDWARE
## if systemRelay not in (GD.SYSTEM_RAD_PUMP, GD.SYSTEM_UFH_PUMP) : return
# Get the I2C parameters from our system control data.
address = system.systemControl [systemRelay].GetAddress ()
mask = system.systemControl [systemRelay].GetBitMask ()
# Re... | random_line_split | |
util.rs | // Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::{
collections::VecDeque,
future::Future,
sync::{
atomic::{self, AtomicU64},
Arc,
},
};
use crate::ipld::{CidHashSet, Ipld};
use crate::shim::clock::ChainEpoch;
use crate::utils::db::car_stream... | }
}
enum Task {
// Yield the block, don't visit it.
Emit(Cid),
// Visit all the elements, recursively.
Iterate(DfsIter),
}
pin_project! {
pub struct ChainStream<DB, T> {
#[pin]
tipset_iter: T,
db: DB,
dfs: VecDeque<Task>, // Depth-first work queue.
seen:... | Ipld::Map(map) => map.into_values().rev().for_each(|elt| self.walk_next(elt)),
other => return Some(other),
}
}
None | random_line_split |
util.rs | // Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::{
collections::VecDeque,
future::Future,
sync::{
atomic::{self, AtomicU64},
Arc,
},
};
use crate::ipld::{CidHashSet, Ipld};
use crate::shim::clock::ChainEpoch;
use crate::utils::db::car_stream... |
/// Depth-first-search iterator for `ipld` leaf nodes.
///
/// This iterator consumes the given `ipld` structure and returns leaf nodes (i.e.,
/// no list or map) in depth-first order. The iterator can be extended at any
/// point by the caller.
///
/// Consider walking this `ipld` graph:
/// ```text
/// List
/// ├ ... | {
// Don't include identity CIDs.
// We only include raw and dagcbor, for now.
// Raw for "code" CIDs.
if cid.hash().code() == u64::from(cid::multihash::Code::Identity) {
false
} else {
matches!(
cid.codec(),
crate::shim::crypto::IPLD_RAW | fvm_ipld_encoding::... | identifier_body |
util.rs | // Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::{
collections::VecDeque,
future::Future,
sync::{
atomic::{self, AtomicU64},
Arc,
},
};
use crate::ipld::{CidHashSet, Ipld};
use crate::shim::clock::ChainEpoch;
use crate::utils::db::car_stream... | Yield the block, don't visit it.
Emit(Cid),
// Visit all the elements, recursively.
Iterate(DfsIter),
}
pin_project! {
pub struct ChainStream<DB, T> {
#[pin]
tipset_iter: T,
db: DB,
dfs: VecDeque<Task>, // Depth-first work queue.
seen: CidHashSet,
statero... | // | identifier_name |
octree_gui.rs | use std::collections::VecDeque;
use std::ops::RangeInclusive;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use cgmath::{Rotation, Vector3};
use glium::{Display, Surface};
use glium::glutin;
use glium::glutin::event::WindowEvent;
use glium::glutin::window::WindowBuilder;
use imgui::*;
use imgui::{Context, Font... | (&mut self) -> Vec<Filter> {
vec![
crate::filter!(Octree, Mesh, Transformation),
crate::filter!(Camera, Transformation),
]
}
fn handle_input(&mut self, _event: &Event<()>) {
let platform = &mut self.platform;
let display = self.display.lock().unwrap();
... | get_filter | identifier_name |
octree_gui.rs | use std::collections::VecDeque;
use std::ops::RangeInclusive;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use cgmath::{Rotation, Vector3};
use glium::{Display, Surface};
use glium::glutin;
use glium::glutin::event::WindowEvent;
use glium::glutin::window::WindowBuilder;
use imgui::*;
use imgui::{Context, Font... |
fn handle_input(&mut self, _event: &Event<()>) {
let platform = &mut self.platform;
let display = self.display.lock().unwrap();
let gl_window = display.gl_window();
let mut imgui = self.imgui.lock().unwrap();
match _event {
Event::MainEventsCleared => {
... | {
vec![
crate::filter!(Octree, Mesh, Transformation),
crate::filter!(Camera, Transformation),
]
} | identifier_body |
octree_gui.rs | use std::collections::VecDeque;
use std::ops::RangeInclusive;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use cgmath::{Rotation, Vector3};
use glium::{Display, Surface};
use glium::glutin;
use glium::glutin::event::WindowEvent;
use glium::glutin::window::WindowBuilder;
use imgui::*;
use imgui::{Context, Font... | view_dir.as_mut(),
).read_only(true).build();
InputFloat3::new(
&ui,
im_str!("Camera Position"),
camera_transform.position.as_mut(),
).build();
camera_transform.update();
}
}
}
impl System for ... | random_line_split | |
lib.rs | //! This is a platform agnostic Rust driver for the MAX3010x high-sensitivity
//! pulse oximeter and heart-rate sensor for wearable health, based on the
//! [`embedded-hal`] traits.
//!
//! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal
//!
//! This driver allows you to:
//! - Get the number of samples... |
pub struct MultiLed(());
}
pub mod ic {
pub struct Max30102(());
}
}
/// MAX3010x device driver.
#[derive(Debug, Default)]
pub struct Max3010x<I2C, IC, MODE> {
/// The concrete I²C device implementation.
i2c: I2C,
temperature_measurement_started: bool,
mode: Config,
fif... | ter(()); | identifier_name |
lib.rs | //! This is a platform agnostic Rust driver for the MAX3010x high-sensitivity
//! pulse oximeter and heart-rate sensor for wearable health, based on the
//! [`embedded-hal`] traits.
//!
//! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal
//!
//! This driver allows you to:
//! - Get the number of samples... | const DEVICE_ADDRESS: u8 = 0b101_0111;
struct Register;
impl Register {
const INT_STATUS: u8 = 0x0;
const INT_EN1: u8 = 0x02;
const INT_EN2: u8 = 0x03;
const FIFO_WR_PTR: u8 = 0x04;
const OVF_COUNTER: u8 = 0x05;
const FIFO_DATA: u8 = 0x07;
const FIFO_CONFIG: u8 = 0x08;
const MODE: u8 =... | pub alc_overflow: bool,
/// Internal die temperature conversion ready interrupt
pub temperature_ready: bool,
}
| random_line_split |
grpc.go | package protocols
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"reflect"
"github.com/feiyuw/simgo/logger"
"github.com/fullstorydev/grpcurl"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/dynamic"
"github.com/jhump/protoreflect/grpcreflect"
"google.golang.org/grpc"
"google.... | c := rpb.NewServerReflectionClient(conn)
refClient := grpcreflect.NewClient(clientCTX, c)
descSource = grpcurl.DescriptorSourceFromServer(clientCTX, refClient)
return &GrpcClient{addr: addr, conn: conn, desc: descSource}, nil
}
func (gc *GrpcClient) ListServices() ([]string, error) {
svcs, err := grpcurl.ListSer... |
// fetch from server reflection RPC | random_line_split |
grpc.go | package protocols
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"reflect"
"github.com/feiyuw/simgo/logger"
"github.com/fullstorydev/grpcurl"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/dynamic"
"github.com/jhump/protoreflect/grpcreflect"
"google.golang.org/grpc"
"google.... | (mtd string, handler func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error) error {
if _, exists := gs.handlerM[mtd]; exists {
logger.Warnf("protocols/grpc", "handler for method %s exists, will be overrided", mtd)
}
gs.handlerM[mtd] = handler
return nil
}
// NOTE: thread unsafe, use loc... | SetMethodHandler | identifier_name |
grpc.go | package protocols
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"reflect"
"github.com/feiyuw/simgo/logger"
"github.com/fullstorydev/grpcurl"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/dynamic"
"github.com/jhump/protoreflect/grpcreflect"
"google.golang.org/grpc"
"google.... |
func (gs *GrpcServer) Start() error {
lis, err := net.Listen("tcp", gs.addr)
if err != nil {
return err
}
logger.Infof("protocols/grpc", "server listening at %v", lis.Addr())
go func() {
if err := gs.server.Serve(lis); err != nil {
logger.Errorf("protocols/grpc", "failed to serve: %v", err)
}
}()
re... | {
descFromProto, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...)
if err != nil {
return nil, fmt.Errorf("cannot parse proto file: %v", err)
}
gs := &GrpcServer{
addr: addr,
desc: descFromProto,
server: grpc.NewServer(opts...),
handlerM: map[string]func(in *dynamic.Message, o... | identifier_body |
grpc.go | package protocols
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"reflect"
"github.com/feiyuw/simgo/logger"
"github.com/fullstorydev/grpcurl"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/dynamic"
"github.com/jhump/protoreflect/grpcreflect"
"google.golang.org/grpc"
"google.... |
return nil
}
func (gs *GrpcServer) ListMethods() ([]string, error) {
methods := []string{}
services, err := grpcurl.ListServices(gs.desc)
if err != nil {
return nil, fmt.Errorf("failed to list services")
}
for _, svcName := range services {
dsc, err := gs.desc.FindSymbol(svcName)
if err != nil {
return... | {
delete(gs.handlerM, mtd)
} | conditional_block |
asn1.rs | //! Support for ECDSA signatures encoded as ASN.1 DER.
// Adapted from BearSSL. Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>.
// Relicensed under Apache 2.0 + MIT (from original MIT) with permission.
//
// <https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_atr.c>
// <https://www.bearssl.org/gitweb... | (&self) -> &[u8] {
&self.bytes.as_slice()[..self.len()]
}
/// Serialize this signature as a boxed byte slice
#[cfg(feature = "alloc")]
pub fn to_bytes(&self) -> Box<[u8]> {
self.as_bytes().to_vec().into_boxed_slice()
}
/// Create an ASN.1 DER encoded signature from big endian `... | as_bytes | identifier_name |
asn1.rs | //! Support for ECDSA signatures encoded as ASN.1 DER.
// Adapted from BearSSL. Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>.
// Relicensed under Apache 2.0 + MIT (from original MIT) with permission.
//
// <https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_atr.c>
// <https://www.bearssl.org/gitweb... |
/// Get the `r` component of the signature (leading zeros removed)
pub(crate) fn r(&self) -> &[u8] {
&self.bytes[self.r_range.clone()]
}
/// Get the `s` component of the signature (leading zeros removed)
pub(crate) fn s(&self) -> &[u8] {
&self.bytes[self.s_range.clone()]
}
}
... | {
let r_len = int_length(r);
let s_len = int_length(s);
let scalar_size = C::FieldSize::to_usize();
let mut bytes = DocumentBytes::<C>::default();
// SEQUENCE header
bytes[0] = SEQUENCE_TAG as u8;
let zlen = r_len.checked_add(s_len).unwrap().checked_add(4).unwrap... | identifier_body |
asn1.rs | //! Support for ECDSA signatures encoded as ASN.1 DER.
// Adapted from BearSSL. Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>.
// Relicensed under Apache 2.0 + MIT (from original MIT) with permission.
//
// <https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_atr.c>
// <https://www.bearssl.org/gitweb... |
if bytes[0] != 0 {
return Err(Error::new());
}
bytes = &bytes[1..];
offset += 1;
}
while !bytes.is_empty() && bytes[0] == 0 {
bytes = &bytes[1..];
offset += 1;
}
Ok(offset)
}
#[cfg(all(feature = "dev", test))]
mod tests {
use crate::d... | {
return Err(Error::new());
} | conditional_block |
asn1.rs | //! Support for ECDSA signatures encoded as ASN.1 DER.
// Adapted from BearSSL. Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>.
// Relicensed under Apache 2.0 + MIT (from original MIT) with permission.
//
// <https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_atr.c>
// <https://www.bearssl.org/gitweb... | if s_end != bytes.as_ref().len() {
return Err(Error::new());
}
let mut byte_arr = DocumentBytes::<C>::default();
byte_arr[..s_end].copy_from_slice(bytes.as_ref());
Ok(Signature {
bytes: byte_arr,
r_range: Range {
start: r_star... | let s_range = parse_int(&bytes[r_end..], C::FieldSize::to_usize())?;
let s_start = r_end.checked_add(s_range.start).unwrap();
let s_end = r_end.checked_add(s_range.end).unwrap();
| random_line_split |
lsp_plugin.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (
&mut self,
language_id: &str,
workspace_root: &Option<Url>,
) -> Option<(String, Arc<Mutex<LanguageServerClient>>)> {
workspace_root
.clone()
.map(|r| r.into_string())
.or_else(|| {
let config = &self.config.language_config[langua... | get_lsclient_from_workspace_root | identifier_name |
lsp_plugin.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
})
}
/// Tries to get language for the View using the extension of the document.
/// Only searches for the languages supported by the Language Plugin as
/// defined in the config
fn get_language_for_view(&mut self, view: &View<ChunkCache>) -> Option<String> {
view.get_path()
... | {
let config = &self.config.language_config[language_id];
let client = start_new_server(
config.start_command.clone(),
config.start_arguments.clone(),
config.extensions.clone(),
langua... | conditional_block |
lsp_plugin.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | Err(err) => {
error!(
"Error occured while starting server for Language: {}: {:?}",
language_id, err
);
None
}
... | self.language_server_clients
.insert(language_server_identifier.clone(), client);
Some((language_server_identifier, client_clone))
} | random_line_split |
lsp_plugin.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
fn new_view(&mut self, view: &mut View<Self::Cache>) {
trace!("new view {}", view.get_id());
let document_text = view.get_document().unwrap();
let path = view.get_path();
let view_id = view.get_id();
// TODO: Use Language Idenitifier assigned by core when the
// i... | {
trace!("close view {}", view.get_id());
self.with_language_server_for_view(view, |ls_client| {
ls_client.send_did_close(view.get_id());
});
} | identifier_body |
cluster.ts | import * as path from 'path';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as kms from 'aws-cdk-lib/aws-kms';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
... | }));
const provider = new Provider(this, 'ResourceProvider', {
onEventHandler: rebootFunction,
});
const customResource = new CustomResource(this, 'RedshiftClusterRebooterCustomResource', {
resourceType: 'Custom::RedshiftClusterRebooter',
serviceToken: provider.serviceToken,
prop... | resourceName: this.clusterName,
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
}),
], | random_line_split |
cluster.ts | import * as path from 'path';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as kms from 'aws-cdk-lib/aws-kms';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
... | (): secretsmanager.SecretAttachmentTargetProps {
return {
targetId: this.clusterName,
targetType: secretsmanager.AttachmentTargetType.REDSHIFT_CLUSTER,
};
}
}
/**
* Create a Redshift cluster a given number of nodes.
*
* @resource AWS::Redshift::Cluster
*/
export class Cluster extends ClusterB... | asSecretAttachmentTarget | identifier_name |
cluster.ts | import * as path from 'path';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as kms from 'aws-cdk-lib/aws-kms';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
... |
return new secretsmanager.SecretRotation(this, id, {
secret: this.secret,
automaticallyAfter,
application: this.singleUserRotationApplication,
vpc: this.vpc,
vpcSubnets: this.vpcSubnets,
target: this,
});
}
/**
* Adds the multi user rotation to this cluster.
*/
... | {
throw new Error('A single user rotation was already added to this cluster.');
} | conditional_block |
cluster.ts | import * as path from 'path';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as kms from 'aws-cdk-lib/aws-kms';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
... |
/**
* Identifier of the cluster
*/
public readonly clusterName: string;
/**
* The endpoint to use for read/write operations
*/
public readonly clusterEndpoint: Endpoint;
/**
* Access to the network connections
*/
public readonly connections: ec2.Connections;
/**
* The secret atta... | {
class Import extends ClusterBase {
public readonly connections = new ec2.Connections({
securityGroups: attrs.securityGroups,
defaultPort: ec2.Port.tcp(attrs.clusterEndpointPort),
});
public readonly clusterName = attrs.clusterName;
public readonly instanceIdentifiers: strin... | identifier_body |
ipProcess.py | # -*- coding: utf-8 -*-
'''
Created on Mon May 14 16:31:21 2018
@author: TimL
'''
# Copyright (c) 2019. Induced Polarization Associates, LLC, Seattle, WA
import os
import scipy as sp
import commonSense as cs
from scipy import fftpack as spfftpack
from datetime import datetime
import pickle
def ipProcess():
'''... |
elif lidx == 7:
# Voltage measurement names.
# 0-indexed by channel number.
self.measStr = line.split(',')
elif lidx == 8:
# Construct arrays using the scipy package.
# 5B amplifier maxim... | (self.rCurrentMeas, # (Ohm) resistance.
self.rExtraSeries) = line.split(',') # (Ohm).
# Type casting.
self.rCurrentMeas = float(self.rCurrentMeas)
self.rExtraSeries = float(self.rCurrentMeas) | conditional_block |
ipProcess.py | # -*- coding: utf-8 -*-
'''
Created on Mon May 14 16:31:21 2018
@author: TimL
'''
# Copyright (c) 2019. Induced Polarization Associates, LLC, Seattle, WA
import os
import scipy as sp
import commonSense as cs
from scipy import fftpack as spfftpack
from datetime import datetime
import pickle
def ipProcess():
'''... |
def countLines(self, fh):
# Counter lidx starts counting at 1 for the first line.
for lidx, line in enumerate(fh, 1):
pass
return lidx
def postRead(self, saveThis):
# Whether to correct for channel skew.
corrChSkewBool = True
# Channel on which the... | phys = sp.zeros_like(pct, dtype=float)
for ch in range(self.chCount):
phys[ch, :] = (pct[ch, :] / 100 *
self.ALoadQHi[ch] * self.In5BHi[ch] /
self.Out5BHi[ch]) # (V)
# Convert the voltage on the current measurement channel to a current.
... | identifier_body |
ipProcess.py | # -*- coding: utf-8 -*-
'''
Created on Mon May 14 16:31:21 2018
@author: TimL
'''
# Copyright (c) 2019. Induced Polarization Associates, LLC, Seattle, WA
import os
import scipy as sp
import commonSense as cs
from scipy import fftpack as spfftpack
from datetime import datetime
import pickle
def ipProcess():
'''... | (self, saveThis):
# Whether to correct for channel skew.
corrChSkewBool = True
# Channel on which the current is measured. This channel's phase is
# subtracted from the other channels in phase difference calculation.
# This channel's voltage is divided by the current measurement... | postRead | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.