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 |
|---|---|---|---|---|
index.ts | import { assert } from '@0x/assert';
import { schemas } from '@0x/json-schemas';
import {
AbiEncoder,
abiUtils,
BigNumber,
decodeBytesAsRevertError,
decodeThrownErrorAsRevertError,
providerUtils,
RevertError,
StringRevertError,
} from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wr... |
protected static _throwIfCallResultIsRevertError(rawCallResult: string): void {
// Try to decode the call result as a revert error.
let revert: RevertError;
try {
revert = decodeBytesAsRevertError(rawCallResult);
} catch (err) {
// Can't decode it as a revert... | {
const constructorAbiIfExists = abi.find(
(abiDefinition: AbiDefinition) => abiDefinition.type === AbiType.Constructor,
// tslint:disable-next-line:no-unnecessary-type-assertion
) as ConstructorAbi | undefined;
if (constructorAbiIfExists !== undefined) {
retu... | identifier_body |
index.ts | import { assert } from '@0x/assert';
import { schemas } from '@0x/json-schemas';
import {
AbiEncoder,
abiUtils,
BigNumber,
decodeBytesAsRevertError,
decodeThrownErrorAsRevertError,
providerUtils,
RevertError,
StringRevertError,
} from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wr... | {
protected _abiEncoderByFunctionSignature: AbiEncoderByFunctionSignature;
protected _web3Wrapper: Web3Wrapper;
public abi: ContractAbi;
public address: string;
public contractName: string;
public constructorArgs: any[] = [];
public _deployedBytecodeIfExists?: Buffer;
private _evmIfExis... | BaseContract | identifier_name |
index.ts | import { assert } from '@0x/assert';
import { schemas } from '@0x/json-schemas';
import {
AbiEncoder,
abiUtils,
BigNumber,
decodeBytesAsRevertError,
decodeThrownErrorAsRevertError,
providerUtils,
RevertError,
StringRevertError,
} from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wr... | ContractEvent,
SendTransactionOpts,
AwaitTransactionSuccessOpts,
ContractFunctionObj,
ContractTxFunctionObj,
SubscriptionErrors,
} from './types';
export interface AbiEncoderByFunctionSignature {
[key: string]: AbiEncoder.Method;
}
const ARBITRARY_PRIVATE_KEY = 'e331b6d69882b4cb4ea581d88e0... | export { | random_line_split |
cluster.go | package v1
/*
Copyright 2017 - 2020 Crunchy Data Solutions, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law ... | // PgclusterStateBootstrapping defines the state of a cluster when it is being bootstrapped
// from an existing data source
PgclusterStateBootstrapping PgclusterState = "pgcluster Bootstrapping"
// PgclusterStateBootstrapped defines the state of a cluster when it has been bootstrapped
// successfully from an exist... | random_line_split | |
cluster.go | package v1
/*
Copyright 2017 - 2020 Crunchy Data Solutions, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law ... |
const (
// PgclusterStateCreated ...
PgclusterStateCreated PgclusterState = "pgcluster Created"
// PgclusterStateProcessed ...
PgclusterStateProcessed PgclusterState = "pgcluster Processed"
// PgclusterStateInitialized ...
PgclusterStateInitialized PgclusterState = "pgcluster Initialized"
// PgclusterStateBoot... | {
return (t.TLSSecret != "" && t.CASecret != "")
} | identifier_body |
cluster.go | package v1
/*
Copyright 2017 - 2020 Crunchy Data Solutions, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law ... | () bool {
return s.Replicas > 0
}
// TLSSpec contains the information to set up a TLS-enabled PostgreSQL cluster
type TLSSpec struct {
// CASecret contains the name of the secret to use as the trusted CA for the
// TLSSecret
// This is our own format and should contain at least one key: "ca.crt"
// It can also co... | Enabled | identifier_name |
service.go | // Package youtube provides loading audio from video files for given youtube channels
package youtube
import (
"context"
"crypto/sha1"
"encoding/xml"
"fmt"
"os"
"path"
"regexp"
"sort"
"strings"
"time"
"github.com/bogem/id3v2/v2"
log "github.com/go-pkgz/lgr"
"github.com/google/uuid"
"github.com/pkg/error... |
// procChannels processes all channels, downloads audio, updates metadata and stores RSS
func (s *Service) procChannels(ctx context.Context) error {
var allStats stats
for _, feedInfo := range s.Feeds {
entries, err := s.ChannelService.Get(ctx, feedInfo.ID, feedInfo.Type)
if err != nil {
log.Printf("[WARN]... | {
entries, err := s.Store.Load(fi.ID, s.keep(fi))
if err != nil {
return "", errors.Wrap(err, "failed to get channel entries")
}
if len(entries) == 0 {
return "", nil
}
items := []rssfeed.Item{}
for _, entry := range entries {
fileURL := s.RootURL + "/" + path.Base(entry.File)
var fileSize int
if f... | identifier_body |
service.go | // Package youtube provides loading audio from video files for given youtube channels
package youtube
import (
"context"
"crypto/sha1"
"encoding/xml"
"fmt"
"os"
"path"
"regexp"
"sort"
"strings"
"time"
"github.com/bogem/id3v2/v2"
log "github.com/go-pkgz/lgr"
"github.com/google/uuid"
"github.com/pkg/error... |
for _, f := range s.Feeds {
log.Printf("[INFO] youtube feed %+v", f)
}
tick := time.NewTicker(s.CheckDuration)
defer tick.Stop()
if err := s.procChannels(ctx); err != nil {
return errors.Wrap(err, "failed to process channels")
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-tick.C:
... | {
log.Printf("[DEBUG] skip youtube episodes shorter than %v", s.SkipShorts)
} | conditional_block |
service.go | // Package youtube provides loading audio from video files for given youtube channels
package youtube
import (
"context"
"crypto/sha1"
"encoding/xml"
"fmt"
"os"
"path"
"regexp"
"sort"
"strings"
"time"
"github.com/bogem/id3v2/v2"
log "github.com/go-pkgz/lgr"
"github.com/google/uuid"
"github.com/pkg/error... | () (res int) {
for _, fi := range s.Feeds {
res += s.keep(fi)
}
return res
}
// countAllEntries returns total number of entries across all channels, respects keep settings
func (s *Service) countAllEntries() int {
var result int
for _, fi := range s.Feeds {
if entries, err := s.Store.Load(fi.ID, s.keep(fi)); ... | totalEntriesToKeep | identifier_name |
service.go | // Package youtube provides loading audio from video files for given youtube channels
package youtube
import (
"context"
"crypto/sha1"
"encoding/xml"
"fmt"
"os"
"path"
"regexp"
"sort"
"strings"
"time"
"github.com/bogem/id3v2/v2"
log "github.com/go-pkgz/lgr"
"github.com/google/uuid"
"github.com/pkg/error... | return entry
}
// removeOld deletes old entries from store and corresponding files
func (s *Service) removeOld(fi FeedInfo) int {
removed := 0
keep := s.keep(fi)
files, err := s.Store.RemoveOld(fi.ID, keep+1)
if err != nil { // even with error we get a list of files to remove
log.Printf("[WARN] failed to remove... | log.Printf("[DEBUG] updated entry: %s", entry.String()) | random_line_split |
mod.rs | use std::mem;
use std::time::SystemTime;
#[cfg(feature="dynamic_mem")]
const MAX_MEMORY_SLOTS: usize = 1024 * 1024 * 2;
#[cfg(not(feature="dynamic_mem"))]
const MAX_MEMORY_SLOTS: usize = 1024 * 128;
type Bits = u128;
const MARK_BITS_PER_SLOT: usize = mem::size_of::<Bits>();
const MARK_BITS: usize = MAX_MEMORY_SLO... | (&mut self, obj: usize, next: usize) {
self.mem[obj + 1] = next;
}
fn mark_object(&mut self, obj: usize) {
self.mark_bits[obj / MARK_BITS_PER_SLOT] |= 1 << (obj % MARK_BITS_PER_SLOT);
}
fn unmark_object(&mut self, obj: usize) {
self.mark_bits[obj / MARK_BITS_PER_SLOT] &= !(1 << (obj % MARK_BITS_P... | set_fl_next | identifier_name |
mod.rs | use std::mem;
use std::time::SystemTime; | #[cfg(not(feature="dynamic_mem"))]
const MAX_MEMORY_SLOTS: usize = 1024 * 128;
type Bits = u128;
const MARK_BITS_PER_SLOT: usize = mem::size_of::<Bits>();
const MARK_BITS: usize = MAX_MEMORY_SLOTS / MARK_BITS_PER_SLOT;
#[cfg(feature="dynamic_mem")]
type Mem = Vec<usize>;
#[cfg(not(feature="dynamic_mem"))]
type Mem =... |
#[cfg(feature="dynamic_mem")]
const MAX_MEMORY_SLOTS: usize = 1024 * 1024 * 2; | random_line_split |
mod.rs | use std::mem;
use std::time::SystemTime;
#[cfg(feature="dynamic_mem")]
const MAX_MEMORY_SLOTS: usize = 1024 * 1024 * 2;
#[cfg(not(feature="dynamic_mem"))]
const MAX_MEMORY_SLOTS: usize = 1024 * 128;
type Bits = u128;
const MARK_BITS_PER_SLOT: usize = mem::size_of::<Bits>();
const MARK_BITS: usize = MAX_MEMORY_SLO... |
let slots = self.get_size(object);
self.mark_object(object);
for i in OBJECT_HEADER_SLOTS..slots {
self.mark_and_scan(self.mem[object + i]);
}
}
pub fn print_gc_stats(&self) {
println!(
"{} gcs, {} object allocates, Last GC: Live {} Dead {} in {} ms, Lifetime GC {} ms\n",
sel... | {
return;
} | conditional_block |
utils.py | '''
Script implements several preprocessing and evaluation steps that have to be done for the triplet loss network
'''
## Imports
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import matplotlib... |
def iter_scale(X:np.array, scaler:object) -> np.array:
'''
iterates over fiven X, scales given 3D array using given (trained) scaler
Parameters:
- X: 3D array with shape samples x length x features [numpy.array]
- scaler: scaler object, e.g., sklearn.preprocessing.StandardScaler, sklearn.p... | '''
flattens a 3D array into 2D array
Parameters:
- X: a 3D array with shape samples x width x height [numpy.array]
Returns:
- flattened_X: 2D array with shape sample x width*height [numpy.array]
'''
flattened_X = X.reshape(X.shape[0], -1)
return flattened_X | identifier_body |
utils.py | '''
Script implements several preprocessing and evaluation steps that have to be done for the triplet loss network
'''
## Imports
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import matplotlib... | - X_transformed: Array containing the transformed x values [numpy.array]
- y: Array containing the labels [numpy.array]
'''
## init pca with two components
pca = PCA(n_components = 2)
## copy data to be sure not to accidentally overwrite something
pca_x = X.copy()
## check whethe... | plots a scatter showing the transformed dataset (if it is 2D) with different coloring for the different classes
Parameters:
- X: Array containing the original x values [numpy.array]
- y: Array containing the labels [numpy.array]
Returns: | random_line_split |
utils.py | '''
Script implements several preprocessing and evaluation steps that have to be done for the triplet loss network
'''
## Imports
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import matplotlib... |
elif strategy == "mean":
value = df[columns].mean()
elif strategy == "median":
value = df[columns].median()
elif strategy == "min":
value = df[columns].min()
elif strategy == "max":
value = df[columns].max()
else:
print("strategy not implemented (yet). Fillin... | value = [0 for _ in range(columns.__len__())] | conditional_block |
utils.py | '''
Script implements several preprocessing and evaluation steps that have to be done for the triplet loss network
'''
## Imports
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import matplotlib... | (data:pd.DataFrame, approach:str = "reuse") -> pd.DataFrame:
'''
function to balance the appearance of samples from different classes -> tackle distribution shift
Parameters:
- data: data with distribution shift [pandas.DataFrame]
- approach: strategy to tackle the distribution shift. Possib... | tackle_distribution_shift | identifier_name |
models.go | //go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lo... | Created *time.Time
// READ-ONLY; The key rotation policy's last updated time in UTC.
Updated *time.Time
}
// KeyVerifyResult - The key verify result.
type KeyVerifyResult struct {
// READ-ONLY; True if the signature is verified, otherwise false.
Value *bool
}
// LifetimeAction - Action and its trigger that will... | ExpiryTime *string
// READ-ONLY; The key rotation policy created time in UTC. | random_line_split |
stateful.go | // Package stateful defines a nested stateful lexer.
//
// This lexer is based heavily on the approach used by Chroma (and Pygments).
//
// The lexer is a state machine defined by a map of rules keyed by state. Each rule
// is a named regex and optional operation to apply when the rule matches.
//
// As a convenience, ... | {
if candidate.RE != nil {
return candidate.RE, nil
}
// We don't have a compiled RE. This means there are back-references
// that need to be substituted first.
parent := l.stack[len(l.stack)-1]
key := candidate.Pattern + "\000" + strings.Join(parent.groups, "\000")
cached, ok := l.def.backrefCache.Load(key)
... | identifier_body | |
stateful.go | // Package stateful defines a nested stateful lexer.
//
// This lexer is based heavily on the approach used by Chroma (and Pygments).
//
// The lexer is a state machine defined by a map of rules keyed by state. Each rule
// is a named regex and optional operation to apply when the rule matches.
//
// As a convenience, ... |
func (p ActionPop) applyAction(lexer *Lexer, groups []string) error {
if groups[0] == "" {
return errors.New("did not consume any input")
}
lexer.stack = lexer.stack[:len(lexer.stack)-1]
return nil
}
// Pop to the previous state.
func Pop() Action {
return ActionPop{}
}
// ReturnRule signals the lexer to retu... | type ActionPop struct{} | random_line_split |
stateful.go | // Package stateful defines a nested stateful lexer.
//
// This lexer is based heavily on the approach used by Chroma (and Pygments).
//
// The lexer is a state machine defined by a map of rules keyed by state. Each rule
// is a named regex and optional operation to apply when the rule matches.
//
// As a convenience, ... | () map[string]rune { // nolint: golint
return d.symbols
}
type lexerState struct {
name string
groups []string
}
// Lexer implementation.
type Lexer struct {
stack []lexerState
def *Definition
data string
pos lexer.Position
}
func (l *Lexer) Next() (lexer.Token, error) { // nolint: golint
parent := l.... | Symbols | identifier_name |
stateful.go | // Package stateful defines a nested stateful lexer.
//
// This lexer is based heavily on the approach used by Chroma (and Pygments).
//
// The lexer is a state machine defined by a map of rules keyed by state. Each rule
// is a named regex and optional operation to apply when the rule matches.
//
// As a convenience, ... |
lexer.stack = append(lexer.stack, lexerState{name: p.State, groups: groups})
return nil
}
// Push to the given state.
//
// The target state will then be the set of rules used for matching
// until another Push or Pop is encountered.
func Push(state string) Action {
return ActionPush{state}
}
type include struct{... | {
return errors.New("did not consume any input")
} | conditional_block |
gaiatools.py | import numpy as np
import pandas as pd
from scipy import interpolate
import warnings
import gala.integrate as gi
import gala.dynamics as gd
import gala.potential as gp
from gala.units import galactic
from astropy import coordinates as coord
from astropy.coordinates import SkyCoord
from astropy import units as u
from ... |
h,x = np.histogram(x, bins=bins)
xm = (x[1:]+x[:-1])/2.
ix = np.argmax(h)
return xm[ix]
def get_finite(x,y):
""" Get x and y that are both finite """
finite = np.logical_and(np.isfinite(x), np.isfinite(y))
xf = x[finite]; yf = y[finite]
return xf, yf
def fit_spline(x, y, **kwargs... | x = x[np.isfinite(x)] | conditional_block |
gaiatools.py | import numpy as np
import pandas as pd
from scipy import interpolate
import warnings
import gala.integrate as gi
import gala.dynamics as gd
import gala.potential as gp
from gala.units import galactic
from astropy import coordinates as coord
from astropy.coordinates import SkyCoord
from astropy import units as u
from ... | (c):
cstr = "CONTAINS(POINT('ICRS',{0:}.ra,{0:}.dec),CIRCLE('ICRS',{1:},{2:},{3:}))=1".format(
source, c.ra.deg, c.dec.deg, radius.to("deg").value)
return cstr
cstrs = map(_make_contains_str, coords)
out += " or ".join(cstrs)
return out
def create_samples(Nsamp,mu,cov):
Nsta... | _make_contains_str | identifier_name |
gaiatools.py | import numpy as np
import pandas as pd
from scipy import interpolate
import warnings
import gala.integrate as gi
import gala.dynamics as gd
import gala.potential as gp
from gala.units import galactic
from astropy import coordinates as coord
from astropy.coordinates import SkyCoord
from astropy import units as u
from ... | stdev = np.nanstd if ignore_nan else np.std
kws = {}
if axis is not None: kws['axis'] = axis
mu = mean(x,**kws)
sig = stdev(x,**kws)
return np.vstack([mu,sig]).T
def medscat(x,sigma=2,ignore_nan=False, axis=None, for_errorbar_plot=False):
percentile = np.nanpercentile if ignore_nan else... | def avgstd(x,ignore_nan=False, axis=None):
mean = np.nanmean if ignore_nan else np.mean | random_line_split |
gaiatools.py | import numpy as np
import pandas as pd
from scipy import interpolate
import warnings
import gala.integrate as gi
import gala.dynamics as gd
import gala.potential as gp
from gala.units import galactic
from astropy import coordinates as coord
from astropy.coordinates import SkyCoord
from astropy import units as u
from ... | """
Query gaia given source_ids
Return a table in the order of the source_ids
"""
from pyia import GaiaDataNew
unique_arr, indexes = np.unique(source_ids, return_inverse=True)
assert len(unique_arr) == len(source_ids), "Not all IDs are unique"
query = create_source_query_from_ids(source_ids,... | identifier_body | |
langviews.js | /**
* Langviews Analysis tool
* @file Main file for Langviews application
* @author MusikAnimal
* @copyright 2016 MusikAnimal
* @license MIT License: https://opensource.org/licenses/MIT
*/
const config = require('./config');
const siteMap = require('../shared/site_map');
const siteDomains = Object.keys(siteMap).... |
getState() {
const classList = $('main')[0].classList;
return this.config.formStates.filter(stateName => {
return classList.contains(stateName);
})[0];
}
/**
* Helper to set a CSS class on the `main` node,
* styling the document based on a 'state'
* @param {String} state - class to... | {
let startDate, endDate, params = this.parseQueryString('pages');
$(this.config.projectInput).val(params.project || this.config.defaults.project);
if (this.validateProject()) return;
// FIXME: only run this when they actually submit
this.patchUsage('lv');
/**
* Check if we're using a va... | identifier_body |
langviews.js | /**
* Langviews Analysis tool
* @file Main file for Langviews application
* @author MusikAnimal
* @copyright 2016 MusikAnimal
* @license MIT License: https://opensource.org/licenses/MIT
*/
const config = require('./config');
const siteMap = require('../shared/site_map');
const siteDomains = Object.keys(siteMap).... | () {
// XXX: throttling
/** allow resubmission of queries that are cached */
if (!this.isRequestCached()) {
/** Check if user has exceeded request limit and throw error */
if (simpleStorage.hasKey('pageviews-throttle')) {
const timeRemaining = Math.round(simpleStorage.getTTL('pageviews-t... | processArticle | identifier_name |
langviews.js | /**
* Langviews Analysis tool
* @file Main file for Langviews application
* @author MusikAnimal
* @copyright 2016 MusikAnimal
* @license MIT License: https://opensource.org/licenses/MIT
*/
const config = require('./config');
const siteMap = require('../shared/site_map');
const siteDomains = Object.keys(siteMap).... | totalRequestCount++;
return this.rateLimit(makeRequest, 100, this)(dbName);
}
/** retries exceeded */
failedPages.push(failedPageLink);
} else {
this.writeMessage(
`${failedPageLink}: ${$.i18n('api-error', 'Pageviews API')} - ${errorDa... | failureRetries[dbName] = 1;
}
/** maximum of 3 retries */
if (failureRetries[dbName] < 3) { | random_line_split |
langviews.js | /**
* Langviews Analysis tool
* @file Main file for Langviews application
* @author MusikAnimal
* @copyright 2016 MusikAnimal
* @license MIT License: https://opensource.org/licenses/MIT
*/
const config = require('./config');
const siteMap = require('../shared/site_map');
const siteDomains = Object.keys(siteMap).... |
}
/**
* Parses the URL query string and sets all the inputs accordingly
* Should only be called on initial page load, until we decide to support pop states (probably never)
* @returns {null} nothing
*/
popParams() {
let startDate, endDate, params = this.parseQueryString('pages');
$(this.con... | {
return url.match(/\/wiki\/(.*?)(?:\?|$)/)[1];
} | conditional_block |
gaia_executor.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... |
}
| {
let rpc_port = self.rpc_runtime.block_on(async {
let query_vineyard = QueryVineyard::new(
self.graph.clone(),
self.partition_manager.clone(),
self.partition_worker_mapping.clone(),
self.worker_partition_list_mapping.clone(),
... | identifier_body |
gaia_executor.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... |
init_log4rs();
let mut store_config = {
let args: Vec<String> = std::env::args().collect();
if args.len() <= 6 && args[1] == "--config" {
let mut store_config = StoreConfig::init_from_file(&args[2], &args[4]);
if args.len() == 6 {
store_config.graph_name ... | {
util::get_build_info();
return;
} | conditional_block |
gaia_executor.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... | server_manager,
store_config.clone(),
Box::new(recover_prepare),
)
.unwrap();
let gaia_service = GaiaService::new(
store_config.clone(),
graph.clone(),
partition_manager.clone(),
partition_worker_mapping,
worker_partition_list_mapping,
);
... | random_line_split | |
gaia_executor.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... | <V, VI, E, EI>(
store_config: Arc<StoreConfig>,
graph: Arc<GlobalGraphQuery<V = V, E = E, VI = VI, EI = EI>>,
partition_manager: Arc<GraphPartitionManager>,
) where
V: Vertex + 'static,
VI: Iterator<Item = V> + Send + 'static,
E: Edge + 'static,
EI: Iterator<Item = E> + Send + 'static,
{
... | run_main | identifier_name |
conn.go | // This code is either inspired from or taken directly from go's tls package
package noise
import (
"errors"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
)
// Conn represents a secured connection.
// It implements the net.Conn interface.
type Conn struct {
conn net.Conn
isClient bool
// handshake
con... | // the first Read or Write will call it automatically.
func (c *Conn) Handshake() (err error) {
c.handshakeMutex.Lock()
defer c.handshakeMutex.Unlock()
if c.handshakeComplete {
return nil
}
var remoteKeyPair *DHKey
if c.config.PeerStatic != nil {
if len(c.config.PeerStatic) != 32 {
return errors.New("noi... | random_line_split | |
conn.go | // This code is either inspired from or taken directly from go's tls package
package noise
import (
"errors"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
)
// Conn represents a secured connection.
// It implements the net.Conn interface.
type Conn struct {
conn net.Conn
isClient bool
// handshake
con... | () bool {
return c.isRemoteAuthenticated
}
// RemoteKey returns the static key of the remote peer.
// It is useful in case the static key is only transmitted during the handshake.
func (c *Conn) RemoteKey() ([]byte, error) {
if !c.handshakeComplete {
return nil, errors.New("handshake not completed")
}
return c.h... | IsRemoteAuthenticated | identifier_name |
conn.go | // This code is either inspired from or taken directly from go's tls package
package noise
import (
"errors"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
)
// Conn represents a secured connection.
// It implements the net.Conn interface.
type Conn struct {
conn net.Conn
isClient bool
// handshake
con... |
// Noise-related functions
// Handshake runs the client or server handshake protocol if
// it has not yet been run.
// Most uses of this package need not call Handshake explicitly:
// the first Read or Write will call it automatically.
func (c *Conn) Handshake() (err error) {
c.handshakeMutex.Lock()
defer c.handsh... | {
return c.conn.Close()
} | identifier_body |
conn.go | // This code is either inspired from or taken directly from go's tls package
package noise
import (
"errors"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
)
// Conn represents a secured connection.
// It implements the net.Conn interface.
type Conn struct {
conn net.Conn
isClient bool
// handshake
con... |
_, c1, c2, err = c.hs.ReadMessage(nil, msg)
if err != nil {
return err
}
}
state = !state
}
if c.isClient {
c.out, c.in = c1, c2
} else {
c.out, c.in = c2, c1
}
c.handshakeComplete = true
return nil
}
// IsRemoteAuthenticated can be used to check if the remote peer has been
// properly aut... | {
return err
} | conditional_block |
barnacle_vcf.py | """
barnacle_vcf.py
Created by William Li
Copyright (c) 2012 Canada's Michael Smith Genome Sciences Centre. All rights reserved.
"""
import sys, os, time, datetime, commands, re
from optparse import OptionParser
sys.path.append("/projects/transabyss/trans-ABySS/v1.2.4/code")
from parsers.candidate_group_parser impor... | (member, refseq):
pos = dup_POS(member)
chrom = dup_CHROM(member)
seq = refseq.GetSequence(chrom, int(pos), int(pos))
return seq
def dup_ALT():
alt = '<DUP:TANDEM>'
return alt
def dup_INFO(member):
pos = int(dup_POS(member))
svtype = 'FND'
length = len(member.event_seq)
end = pos + length - 1
in... | dup_REF | identifier_name |
barnacle_vcf.py | """
barnacle_vcf.py
Created by William Li
Copyright (c) 2012 Canada's Michael Smith Genome Sciences Centre. All rights reserved.
"""
import sys, os, time, datetime, commands, re
from optparse import OptionParser
sys.path.append("/projects/transabyss/trans-ABySS/v1.2.4/code")
from parsers.candidate_group_parser impor... |
dp = int(member.avg_read_to_ctg_unique)
info += ';SR='+str(dp)+';CTG='
dup = chrom+'\t'+pos+'\t.\t'+ref+'\t'+alt+'\t'+qual+'\t'+filt+'\t'+info
counter = 0
for m in group.members:
contig = m.contig_info.ToString()
contig = contig.replace(':', '_')
contig = contig.partiti... | info = ptd_INFO(member) | conditional_block |
barnacle_vcf.py | """
barnacle_vcf.py
Created by William Li
Copyright (c) 2012 Canada's Michael Smith Genome Sciences Centre. All rights reserved.
"""
import sys, os, time, datetime, commands, re
from optparse import OptionParser
sys.path.append("/projects/transabyss/trans-ABySS/v1.2.4/code")
from parsers.candidate_group_parser impor... | seq = refseq.GetSequence(chrom, int(pos), int(pos))
return seq
def dup_ALT():
alt = '<DUP:TANDEM>'
return alt
def dup_INFO(member):
pos = int(dup_POS(member))
svtype = 'FND'
length = len(member.event_seq)
end = pos + length - 1
info = 'SVTYPE='+svtype+';END='+str(end)
return info
def ptd_POS(me... |
def dup_REF(member, refseq):
pos = dup_POS(member)
chrom = dup_CHROM(member) | random_line_split |
barnacle_vcf.py | """
barnacle_vcf.py
Created by William Li
Copyright (c) 2012 Canada's Michael Smith Genome Sciences Centre. All rights reserved.
"""
import sys, os, time, datetime, commands, re
from optparse import OptionParser
sys.path.append("/projects/transabyss/trans-ABySS/v1.2.4/code")
from parsers.candidate_group_parser impor... |
#header output method
def write_header(GIN_user, GIN_pass, LIMS_user, LIMS_pass, refseq_flag, library, filetype_flag, out_file, contig=None):
#file format
out_file.write('##fileformat=VCFv4.1\n')
#file date
out_file.write('##filedate='+time.strftime("%Y%m%d")+'\n')
#tcga version
out_file.write('##t... | overlap = str(member.meta_fields['ctg_overlap'])
svtype = 'FND'
dp = int(member.avg_read_to_ctg_unique)
if int(overlap) > 0:
return 'SVTYPE='+svtype+';MATEID='+str(id2)+'b;CIPOS=0,'+overlap+';SR='+str(dp)+';CTG=', svtype+';MATEID='+str(id1)+'a;CIPOS=0,'+overlap+';SR='+str(dp)+';CTG='
else:
return 'S... | identifier_body |
MakeGoodGamesBot.py | # -*- coding: utf-8 -*-
#MakeGoodGamesBot
#Requiered libraries
from twitter import *
from collections import Counter
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler, API
from tweepy import Stream
import time
import pandas as pd
import matplotlib.pyplot as plt
import json
import random as rd... | ():
print 'Tit for Tat!'
follow_me = twitter_client.followers_ids() #who follows me
follow_you = twitter_client.friends_ids() #who do I follow
erros_ids = []
fol_len = len([1 for id_ in follow_me if id_ not in follow_you])
print 'Following '+str(fol_len)+' new users.'
for id_ in follow_me:
... | tit_for_tat | identifier_name |
MakeGoodGamesBot.py | # -*- coding: utf-8 -*-
#MakeGoodGamesBot
#Requiered libraries
from twitter import *
from collections import Counter
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler, API
from tweepy import Stream
import time
import pandas as pd
import matplotlib.pyplot as plt
import json
import random as rd... |
def loop_schedule(date):
while True:
for ky in ['#indiedev','#indiegame']:
print 'Day '+str(date)+' and keyword '+str(ky)
run_schedule(dt=date,ky=ky)
d = get_date()
if date != d:
date = d
break
#Main Functions for... | run_schedule(folow=True)
run_schedule(ky='#indiegame',clean=True,folow=True) | identifier_body |
MakeGoodGamesBot.py | # -*- coding: utf-8 -*-
#MakeGoodGamesBot
#Requiered libraries
from twitter import *
from collections import Counter
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler, API
from tweepy import Stream
import time
import pandas as pd
import matplotlib.pyplot as plt
import json
import random as rd... |
if folow: RT_followers(key_=ky,max_=mx)
RT_last_day(dt,key_=ky)
def twice():
run_schedule(folow=True)
run_schedule(ky='#indiegame',clean=True,folow=True)
def loop_schedule(date):
while True:
for ky in ['#indiedev','#indiegame']:
print 'Day '+str(date)+' and keyword '+str(k... | tit_for_tat() | conditional_block |
MakeGoodGamesBot.py | # -*- coding: utf-8 -*-
#MakeGoodGamesBot
#Requiered libraries
from twitter import *
from collections import Counter
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler, API
from tweepy import Stream
import time
import pandas as pd
import matplotlib.pyplot as plt
import json
import random as rd... | i,twts=4,twts+1
print 'RTed : '+str(twts)+' at '+str(time.ctime())
time.sleep(sleep_t)
i=5
if type(tweet[11]) != None:
banRT.append(tweet[11])
if len(tweet[27]) > 14:
... | if publish:
try:
twitter_client.retweet(tweet[8]) | random_line_split |
calibrate_gripper_g1r1.py | #Copyright 2008, Meka Robotics
#All rights reserved.
#http://mekabot.com
#Redistribution and use in source and binary forms, with or without
#modification, are permitted.
#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED... | print 'Pos: (mm) : '+'%3.3f'%pos+' Qei On '+'%d'%q_on+' Qei Period '+'%d'%q_p+' Qei Rollover '+'%d'%q_r
raw=self.comp_ec.status.adc_torque
c=self.torque.raw_2_mNm(self.comp_rt.config['calib']['torque'],raw)
mN=c/self.comp_j.config['calib']['cb_drive_radius_m']
print 'Force: (g) : '+'%3.2f'%m3u.mN2g(mN)+'... | q_on=self.comp_ec.status.qei_on
q_p=self.comp_ec.status.qei_period
q_r=self.comp_ec.status.qei_rollover
c=self.theta.raw_2_deg(self.comp_rt.config['calib']['theta'],q_on,q_p,q_r)
pos=1000.0*math.pi*2*self.comp_j.config['calib']['cb_drive_radius_m']*c/360.0 | random_line_split |
calibrate_gripper_g1r1.py | #Copyright 2008, Meka Robotics
#All rights reserved.
#http://mekabot.com
#Redistribution and use in source and binary forms, with or without
#modification, are permitted.
#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED... |
if ct=='tt':
self.reset_sensor('theta')
self.calibrate_theta()
self.write_config()
return True
if M3CalibrateActuatorEc.do_task(self,ct):
return True
return False
def print_tasks(self):
M3CalibrateActuatorEcR1.print_tasks(self)
print 'ch: calibrate torque'
print 'tt: calibrate theta'
... | self.reset_sensor('torque')
self.calibrate_torque()
self.write_config()
return True | conditional_block |
calibrate_gripper_g1r1.py | #Copyright 2008, Meka Robotics
#All rights reserved.
#http://mekabot.com
#Redistribution and use in source and binary forms, with or without
#modification, are permitted.
#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED... |
def print_tasks(self):
M3CalibrateActuatorEcR1.print_tasks(self)
print 'ch: calibrate torque'
print 'tt: calibrate theta'
def display_sensors(self):
M3CalibrateActuatorEcR1.display_sensors(self)
q_on=self.comp_ec.status.qei_on
q_p=self.comp_ec.status.qei_period
q_r=self.comp_ec.status.qei_rollov... | if ct=='ch':
self.reset_sensor('torque')
self.calibrate_torque()
self.write_config()
return True
if ct=='tt':
self.reset_sensor('theta')
self.calibrate_theta()
self.write_config()
return True
if M3CalibrateActuatorEc.do_task(self,ct):
return True
return False | identifier_body |
calibrate_gripper_g1r1.py | #Copyright 2008, Meka Robotics
#All rights reserved.
#http://mekabot.com
#Redistribution and use in source and binary forms, with or without
#modification, are permitted.
#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED... | (self,ct):
if ct=='ch':
self.reset_sensor('torque')
self.calibrate_torque()
self.write_config()
return True
if ct=='tt':
self.reset_sensor('theta')
self.calibrate_theta()
self.write_config()
return True
if M3CalibrateActuatorEc.do_task(self,ct):
return True
return False
def print_t... | do_task | identifier_name |
getfood_base.py | import cv2
from enum import IntEnum
from rlkit.envs.gym_minigrid.gym_minigrid.register import register
from gym import spaces
import numpy as np
from collections import defaultdict
from rlkit.envs.gym_minigrid.gym_minigrid.minigrid_absolute import MiniGridAbsoluteEnv, Food, GridAbsolute, CELL_PIXELS
class FoodEnvBas... |
else:
obs = img.flatten()
else:
if incl_health:
obs = np.concatenate((img.flatten(), full_img.flatten(), np.array([self.health])))
else:
obs = np.concatenate((img.flatten(), full_img.flatten()))
obs_string = obs.tostrin... | obs = np.concatenate((img.flatten(), np.array([self.health]))) | conditional_block |
getfood_base.py | import cv2
from enum import IntEnum
from rlkit.envs.gym_minigrid.gym_minigrid.register import register
from gym import spaces
import numpy as np
from collections import defaultdict
from rlkit.envs.gym_minigrid.gym_minigrid.minigrid_absolute import MiniGridAbsoluteEnv, Food, GridAbsolute, CELL_PIXELS
class FoodEnvBas... | (FoodEnvBase):
def __init__(self):
super().__init__(fully_observed=True)
def decay_health(self):
pass
register(
id='MiniGrid-Food-8x8-Empty-FullObs-v1',
entry_point='rlkit.envs.gym_minigrid.gym_minigrid.envs:FoodEnvEmptyFullObs'
)
| FoodEnvEmptyFullObs | identifier_name |
getfood_base.py | import cv2
from enum import IntEnum
from rlkit.envs.gym_minigrid.gym_minigrid.register import register
from gym import spaces
import numpy as np
from collections import defaultdict
from rlkit.envs.gym_minigrid.gym_minigrid.minigrid_absolute import MiniGridAbsoluteEnv, Food, GridAbsolute, CELL_PIXELS
class FoodEnvBas... | if self.fully_observed:
if incl_health:
obs = np.concatenate((full_img.flatten(), np.array([self.health]), np.array(self.agent_pos)))
else:
obs = np.concatenate((full_img.flatten(), np.array(self.agent_pos)))
elif self.only_partial_obs:
... | # # ignore second channel since redundant (due to one-to-one mapping btwn color and obj type for now)
# img = np.concatenate([np.eye(len(self.object_to_idx))[ch].transpose(2, 0, 1) for ch in img[:1]])
# full_img = np.concatenate([np.eye(len(self.object_to_idx))[ch].transpose(2, 0, 1) for ch i... | random_line_split |
getfood_base.py | import cv2
from enum import IntEnum
from rlkit.envs.gym_minigrid.gym_minigrid.register import register
from gym import spaces
import numpy as np
from collections import defaultdict
from rlkit.envs.gym_minigrid.gym_minigrid.minigrid_absolute import MiniGridAbsoluteEnv, Food, GridAbsolute, CELL_PIXELS
class FoodEnvBas... |
def place_items(self):
pass
def extra_gen_grid(self):
pass
def place_prob(self, obj, prob, top=None, size=None):
if np.random.binomial(1, prob):
pos = self.place_obj(obj, top, size)
obj.cur_pos = pos
return True
return False
def de... | pass | identifier_body |
codeHost.ts | import { trimStart } from 'lodash'
import { defer, of } from 'rxjs'
import { map } from 'rxjs/operators'
import { Omit } from 'utility-types'
import { AdjustmentDirection, PositionAdjuster } from '@sourcegraph/codeintellify'
import { NotificationType } from '@sourcegraph/shared/src/api/extension/extensionHostApi'
impo... | const actualLine = lines[position.line - 1]
const documentLine = codeElement.textContent || ''
const actualLeadingWhiteSpace = actualLine.length - trimStart(actualLine).length
const documentLeadingWhiteSpace = documentLine.length - trimStart(documentLine).length
... | throw new Error('(adjustPosition) could not find code element for line provided')
}
| conditional_block |
codeHost.ts | import { trimStart } from 'lodash'
import { defer, of } from 'rxjs'
import { map } from 'rxjs/operators'
import { Omit } from 'utility-types'
import { AdjustmentDirection, PositionAdjuster } from '@sourcegraph/codeintellify'
import { NotificationType } from '@sourcegraph/shared/src/api/extension/extensionHostApi'
impo... | /**
* Returns true if the current page is github.com.
*/
export const checkIsGitHubDotCom = (url = window.location.href): boolean => /^https?:\/\/(www\.)?github\.com/.test(url)
/**
* Returns true if the current page is either github.com or GitHub Enterprise.
*/
export const checkIsGitHub = (): boolean => checkIsGi... | const ogSiteName = document.head.querySelector<HTMLMetaElement>('meta[property="og:site_name"]')
return (
!!ogSiteName &&
// GitHub Enterprise v2.14.11 has "GitHub" as og:site_name
(ogSiteName.content === 'GitHub Enterprise' || ogSiteName.content === 'GitHub') &&
document.body.cl... | identifier_body |
codeHost.ts | import { trimStart } from 'lodash'
import { defer, of } from 'rxjs'
import { map } from 'rxjs/operators'
import { Omit } from 'utility-types'
import { AdjustmentDirection, PositionAdjuster } from '@sourcegraph/codeintellify'
import { NotificationType } from '@sourcegraph/shared/src/api/extension/extensionHostApi'
impo... | (codeView: HTMLElement): HTMLElement {
const className = 'github-file-actions-toolbar-mount'
const existingMount = codeView.querySelector('.' + className) as HTMLElement
if (existingMount) {
return existingMount
}
const mountElement = document.createElement('div')
mountElement.className... | createFileActionsToolbarMount | identifier_name |
codeHost.ts | import { trimStart } from 'lodash'
import { defer, of } from 'rxjs'
import { map } from 'rxjs/operators'
import { Omit } from 'utility-types'
import { AdjustmentDirection, PositionAdjuster } from '@sourcegraph/codeintellify'
import { NotificationType } from '@sourcegraph/shared/src/api/extension/extensionHostApi'
impo... | // Stay on same page in PR if possible.
// TODO to be entirely correct, this would need to compare the revision of the code view with the target revision.
const isSameRepo = rawRepoName === target.rawRepoName
if (isSameRepo && context.part !== undefined) {
const containers = ... | random_line_split | |
edgehub.rs | use std::{
env, fs,
future::Future,
path::{Path, PathBuf},
time::Duration as StdDuration,
};
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use futures_util::{
future::{self, Either},
FutureExt,
};
use tracing::{debug, error, info};
us... |
snapshot??
}
// one of sidecars exited first
Either::Right(((res, stopped, sidecars), server)) => {
debug!("a sidecar has stopped. shutting down all sidecars...");
if let Err(e) = res {
error!(message = "failed wait... | // wait for the rest to exit
future::join_all(sidecars).await; | random_line_split |
edgehub.rs | use std::{
env, fs,
future::Future,
path::{Path, PathBuf},
time::Duration as StdDuration,
};
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use futures_util::{
future::{self, Either},
FutureExt,
};
use tracing::{debug, error, info};
us... |
fn session_expiration(&self, settings: &Self::Settings) -> StdDuration {
settings.broker().session().expiration()
}
fn session_cleanup_interval(&self, settings: &Self::Settings) -> StdDuration {
settings.broker().session().cleanup_interval()
}
async fn run(
self,
... | {
settings.broker().persistence().time_interval()
} | identifier_body |
edgehub.rs | use std::{
env, fs,
future::Future,
path::{Path, PathBuf},
time::Duration as StdDuration,
};
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use futures_util::{
future::{self, Either},
FutureExt,
};
use tracing::{debug, error, info};
us... | (&self, settings: &Self::Settings) -> StdDuration {
settings.broker().session().cleanup_interval()
}
async fn run(
self,
config: Self::Settings,
broker: Broker<Self::Authorizer>,
) -> Result<BrokerSnapshot> {
let broker_handle = broker.handle();
let sidecars ... | session_cleanup_interval | identifier_name |
edgehub.rs | use std::{
env, fs,
future::Future,
path::{Path, PathBuf},
time::Duration as StdDuration,
};
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use futures_util::{
future::{self, Either},
FutureExt,
};
use tracing::{debug, error, info};
us... |
};
Ok(state)
}
}
async fn make_server<Z>(
config: Settings,
broker: Broker<Z>,
broker_ready: BrokerReady,
) -> Result<Server<Z, MakeEdgeHubPacketProcessor<MakeMqttPacketProcessor>>>
where
Z: Authorizer + Send + 'static,
{
let broker_handle = broker.handle();
let make_proc... | {
debug!("a sidecar has stopped. shutting down all sidecars...");
if let Err(e) = res {
error!(message = "failed waiting for sidecar shutdown", error = %e);
}
// send shutdown event to each of the rest sidecars
shutdown... | conditional_block |
utils.ts | import {
IVertex,
Ellipse,
DrawPolygonOption,
DrawLineOption,
DrawCircleOption,
DrawEllipseOption,
DrawRectOption,
LinearGradientOption,
DrawRoundRectConfig,
} from './layer.d';
/**
* 16进制颜色值转为 rgba
* @param hexColor ("#ffffff")
* @param opacity number
*/
export function hex2rgba(hexCo | city) {
const hex = hexColor.replace('#', '');
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
const result = `rgba(${r}, ${g}, ${b}, ${opacity})`;
return result;
}
/**
*
* @param target {object}
*/
export function is... | lor, opa | identifier_name |
utils.ts | import {
IVertex,
Ellipse,
DrawPolygonOption,
DrawLineOption,
DrawCircleOption,
DrawEllipseOption,
DrawRectOption,
LinearGradientOption,
DrawRoundRectConfig,
} from './layer.d';
/**
* 16进制颜色值转为 rgba
* @param hexColor ("#ffffff")
* @param opacity number
*/
export function hex2rgba(hexColor, opacit... | export function getDirection(start: IVertex, end: IVertex) {
let left: boolean = false;
let top: boolean = false;
let right: boolean = false;
let bottom: boolean = false;
if (start.x <= end.x) {
right = true;
} else {
left = true;
}
if (start.y <= end.y) {
bottom = true;
} else {
top... | */ | random_line_split |
utils.ts | import {
IVertex,
Ellipse,
DrawPolygonOption,
DrawLineOption,
DrawCircleOption,
DrawEllipseOption,
DrawRectOption,
LinearGradientOption,
DrawRoundRectConfig,
} from './layer.d';
/**
* 16进制颜色值转为 rgba
* @param hexColor ("#ffffff")
* @param opacity number
*/
export function hex2rgba(hexColor, opacit... |
/**
*
* @param ctx
* @param vertex
* @param radius
* @param options
*/
export const drawCircle = (
ctx: any,
vertex: IVertex,
radius,
options: DrawCircleOption
) => {
if (!options.hasOwnProperty('dashed') || options.dashed === false) {
ctx.setLineDash([]);
} else {
const _dashedConfig =
... | et[key] = options[key];
}
}
});
} | conditional_block |
utils.ts | import {
IVertex,
Ellipse,
DrawPolygonOption,
DrawLineOption,
DrawCircleOption,
DrawEllipseOption,
DrawRectOption,
LinearGradientOption,
DrawRoundRectConfig,
} from './layer.d';
/**
* 16进制颜色值转为 rgba
* @param hexColor ("#ffffff")
* @param opacity number
*/
export function hex2rgba(hexColor, opacit... | Rect(vertex: IVertex, rect: [IVertex, IVertex]): boolean {
if (
vertex.x > rect[0].x &&
vertex.x < rect[1].x &&
vertex.y > rect[0].y &&
vertex.y < rect[1].y
) {
return true;
}
return false;
}
/**
* 在 canvas 上下文新建一个渐变区域
* @param ctx
* @param option
*/
export const createLinearGradient =... | , offsetY: y } = event;
return { x: x / zoom, y: y / zoom };
}
export function isIn | identifier_body |
v4-signature.go | /*
* Minio Cloud Storage, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... |
// Sign - local variables
type Sign struct {
accessKeyID string
secretAccessKey string
region string
httpRequest *http.Request
extractedSignedHeaders http.Header
}
// AWS Signature Version '4' constants.
const (
signV4Algorithm = "AWS4-HMAC-SHA256"
iso8601Format =... | "github.com/minio/minio/pkg/probe"
) | random_line_split |
v4-signature.go | /*
* Minio Cloud Storage, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... | (presignedQuery string) string {
rawQuery := strings.Replace(presignedQuery, "+", "%20", -1)
encodedPath := getURLEncodedName(s.httpRequest.URL.Path)
// Convert any space strings back to "+".
encodedPath = strings.Replace(encodedPath, "+", "%20", -1)
canonicalRequest := strings.Join([]string{
s.httpRequest.Metho... | getPresignedCanonicalRequest | identifier_name |
v4-signature.go | /*
* Minio Cloud Storage, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... |
query[k] = v
}
// Get the encoded query.
encodedQuery := query.Encode()
// Verify if date query is same.
if s.httpRequest.URL.Query().Get("X-Amz-Date") != query.Get("X-Amz-Date") {
return false, nil
}
// Verify if expires query is same.
if s.httpRequest.URL.Query().Get("X-Amz-Expires") != query.Get("X-Am... | {
continue
} | conditional_block |
v4-signature.go | /*
* Minio Cloud Storage, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... |
// SetHTTPRequestToVerify - sets the http request which needs to be verified.
func (s *Sign) SetHTTPRequestToVerify(r *http.Request) *Sign {
// Do not set http request if its 'nil'.
if r == nil {
return s
}
s.httpRequest = r
return s
}
// getCanonicalHeaders generate a list of request headers with their value... | {
if !isValidAccessKey.MatchString(accessKeyID) {
return nil, ErrInvalidAccessKeyID("Invalid access key id.", accessKeyID).Trace(accessKeyID)
}
if !isValidSecretKey.MatchString(secretAccessKey) {
return nil, ErrInvalidAccessKeyID("Invalid secret key.", secretAccessKey).Trace(secretAccessKey)
}
if region == "" ... | identifier_body |
policy_row.ts | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/js/action_link.js';
import './policy_conflict.js';
import './strings.m.js';
import {CustomElement} from 'chrome://resources/js/custom_element.js';
i... | extends CustomElement {
static override get template() {
return getTemplate();
}
policy: Policy;
private unset_: boolean;
private hasErrors_: boolean;
private hasWarnings_: boolean;
private hasInfos_: boolean;
private hasConflicts_: boolean;
private hasSuperseded_: boolean;
private isMergedVal... | PolicyRowElement | identifier_name |
policy_row.ts | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/js/action_link.js';
import './policy_conflict.js';
import './strings.m.js';
import {CustomElement} from 'chrome://resources/js/custom_element.js';
i... |
if (format) {
return JSON.stringify(value, null, 2);
} else {
return JSON.stringify(value, null);
}
};
// If value is longer than 256 characters, truncate and add ellipsis.
const policyValueStr = convertValue(policy.value);
const truncatedValue = pol... | {
return value;
} | conditional_block |
policy_row.ts | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/js/action_link.js';
import './policy_conflict.js';
import './strings.m.js';
import {CustomElement} from 'chrome://resources/js/custom_element.js';
i... |
policy: Policy;
private unset_: boolean;
private hasErrors_: boolean;
private hasWarnings_: boolean;
private hasInfos_: boolean;
private hasConflicts_: boolean;
private hasSuperseded_: boolean;
private isMergedValue_: boolean;
private deprecated_: boolean;
private future_: boolean;
connectedCal... | {
return getTemplate();
} | identifier_body |
policy_row.ts | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/js/action_link.js';
import './policy_conflict.js';
import './strings.m.js';
import {CustomElement} from 'chrome://resources/js/custom_element.js';
i... | }
if (format) {
return JSON.stringify(value, null, 2);
} else {
return JSON.stringify(value, null);
}
};
// If value is longer than 256 characters, truncate and add ellipsis.
const policyValueStr = convertValue(policy.value);
const truncatedVa... | // Skip 'string' policy to avoid unnecessary conversions.
if (typeof value == 'string') {
return value; | random_line_split |
server.go | package dynamiclistener
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"log"
"net"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"time"
cert "github.com/rancher/dynamiclistener/cert"
"github.com/sirupsen/logrus"
... |
if err := s.serveHTTPS(); err != nil {
return err
}
return nil
}
func (s *server) getCertificate(hello *tls.ClientHelloInfo) (_servingCert *tls.Certificate, _err error) {
s.Lock()
changed := false
defer func() {
defer s.Unlock()
if _err != nil {
logrus.Errorf("Get certificate error: %s", _err)
r... | {
return err
} | conditional_block |
server.go | package dynamiclistener
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"log"
"net"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"time"
cert "github.com/rancher/dynamiclistener/cert"
"github.com/sirupsen/logrus"
... | if err := s.userConfigure(); err != nil {
return nil, err
}
lc, err := listenConfigStorage.Get()
if err != nil {
return nil, err
}
return s, s.Update(lc)
}
func (s *server) CACert() (string, error) {
if s.userConfig.NoCACerts {
return "", nil
}
if s.userConfig.CACerts != "" {
return s.userConfig.CAC... | s.ips = map[string]bool{}
s.domains = map[string]bool{}
| random_line_split |
server.go | package dynamiclistener
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"log"
"net"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"time"
cert "github.com/rancher/dynamiclistener/cert"
"github.com/sirupsen/logrus"
... | () error {
if s.userConfig.HTTPSPort == 0 {
s.userConfig.HTTPSPort = 8443
}
for _, d := range s.userConfig.Domains {
s.domains[d] = true
}
for _, ip := range s.userConfig.KnownIPs {
if netIP := net.ParseIP(ip); netIP != nil {
s.ips[ip] = true
}
}
if bindAddress := net.ParseIP(s.userConfig.BindAddre... | userConfigure | identifier_name |
server.go | package dynamiclistener
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"log"
"net"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"time"
cert "github.com/rancher/dynamiclistener/cert"
"github.com/sirupsen/logrus"
... |
func (s *server) getCertificate(hello *tls.ClientHelloInfo) (_servingCert *tls.Certificate, _err error) {
s.Lock()
changed := false
defer func() {
defer s.Unlock()
if _err != nil {
logrus.Errorf("Get certificate error: %s", _err)
return
}
if changed {
s.save()
}
}()
if hello.ServerName != ... | {
if len(s.listeners) > 0 {
return nil
}
if err := s.shutdown(); err != nil {
return err
}
if err := s.serveHTTPS(); err != nil {
return err
}
return nil
} | identifier_body |
cli.rs | // Copyright 2015 Axel Rasmussen
//
// 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 w... |
}
impl AbstractStream for Stream {
type Attributes = TerminalAttributes;
fn isatty(&self) -> bool {
let ret = unsafe { libc::isatty(self.to_fd()) };
let error: i32 = errno::errno().into();
match ret {
1 => true,
0 => match error {
libc::EBADF =>... | {
match *self {
Stream::Stdout => libc::STDOUT_FILENO,
Stream::Stderr => libc::STDERR_FILENO,
Stream::Stdin => libc::STDIN_FILENO,
}
} | identifier_body |
cli.rs | // Copyright 2015 Axel Rasmussen
//
// 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 w... | <IS: AbstractStream, OS: AbstractStream>(
mut input_stream: IS,
mut output_stream: OS,
prompt: &str,
is_sensitive: bool,
) -> Result<String> {
let mut input_reader = build_input_reader(&mut input_stream)?;
prompt_for_string_impl(
&mut input_stream,
&mut input_reader,
&mut... | prompt_for_string | identifier_name |
cli.rs | // Copyright 2015 Axel Rasmussen
//
// 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 w... | && self.inner.c_oflag == other.inner.c_oflag
&& self.inner.c_cflag == other.inner.c_cflag
&& self.inner.c_lflag == other.inner.c_lflag
&& self.inner.c_line == other.inner.c_line
&& self.inner.c_cc == other.inner.c_cc
&& self.inner.c_ispeed == other... | random_line_split | |
helmrepoutils.go | /*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (client client.Client, parentNamespace string, secretRef *corev1.ObjectReference) (secret *corev1.Secret, err error) {
srLogger := log.WithValues("package", "utils", "method", "getSecret")
if secretRef != nil {
srLogger.Info("Retreive secret", "parentNamespace", parentNamespace, "secretRef", secretRef)
ns := secr... | GetSecret | identifier_name |
helmrepoutils.go | /*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | srLogger := log.WithValues("HelmRelease.Namespace", s.Namespace, "SubscrptionRelease.Name", s.Name)
if s.Spec.Source.HelmRepo == nil {
err := fmt.Errorf("HelmRepo type but Spec.HelmRepo is not defined")
return "", err
}
if _, err := os.Stat(chartsDir); os.IsNotExist(err) {
err := os.MkdirAll(chartsDir, 0755)
... | func DownloadChartFromHelmRepo(configMap *corev1.ConfigMap, secret *corev1.Secret, chartsDir string, s *appv1alpha1.HelmRelease) (chartDir string, err error) { | random_line_split |
helmrepoutils.go | /*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
}
// if it's a file create it
case tar.TypeReg:
dir := filepath.Dir(target)
if _, err := os.Stat(dir); err != nil {
if err := os.MkdirAll(dir, 0755); err != nil {
srLogger.Error(err, "")
return err
}
}
f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
... | {
srLogger.Error(err, "")
return err
} | conditional_block |
helmrepoutils.go | /*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
//DownloadChartFromHelmRepo downloads a chart into the charsDir
func DownloadChartFromHelmRepo(configMap *corev1.ConfigMap, secret *corev1.Secret, chartsDir string, s *appv1alpha1.HelmRelease) (chartDir string, err error) {
srLogger := log.WithValues("HelmRelease.Namespace", s.Namespace, "SubscrptionRelease.Name", s... | {
srLogger := log.WithValues("HelmRelease.Namespace", s.Namespace, "SubscrptionRelease.Name", s.Name)
if s.Spec.Source.GitHub == nil {
err := fmt.Errorf("GitHub type but Spec.GitHub is not defined")
return "", err
}
if _, err := os.Stat(chartsDir); os.IsNotExist(err) {
err := os.MkdirAll(chartsDir, 0755)
if... | identifier_body |
ResNet50_augmentation.py | import pathlib, random, cv2
import tensorflow as tf
import numpy as np
import tensorflow.keras.backend as K
import albumentations as A
from matplotlib import pyplot as plt
from functools import partial
from sklearn.model_selection import train_test_split
# GPU setup
gpus = tf.config.experimental.list_physical_devices(... |
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(AUTOTUNE)
return dataset
def residual_block(x, filters, kernel_size=3, stride=1, conv_shortcut=True, name=None):
if conv_shortcut:
shortcut = tf.keras.layers.Conv2D(4 * filters, 1, strides=stride, name=name+'_0_conv', kernel_init... | dataset = dataset.map(partial(process_data), num_parallel_calls=AUTOTUNE) | random_line_split |
ResNet50_augmentation.py | import pathlib, random, cv2
import tensorflow as tf
import numpy as np
import tensorflow.keras.backend as K
import albumentations as A
from matplotlib import pyplot as plt
from functools import partial
from sklearn.model_selection import train_test_split
# GPU setup
gpus = tf.config.experimental.list_physical_devices(... |
def make_tf_data(images, labels, augmentation):
images = tf.data.Dataset.from_tensor_slices(images)
images = images.map(preprocess_image, num_parallel_calls=AUTOTUNE)
labels = tf.data.Dataset.from_tensor_slices(labels)
dataset = tf.data.Dataset.zip((images, labels))
dataset = dataset.repeat()
... | aug_img = tf.numpy_function(func=aug_fn, inp=[image], Tout=tf.float32)
return aug_img, label | identifier_body |
ResNet50_augmentation.py | import pathlib, random, cv2
import tensorflow as tf
import numpy as np
import tensorflow.keras.backend as K
import albumentations as A
from matplotlib import pyplot as plt
from functools import partial
from sklearn.model_selection import train_test_split
# GPU setup
gpus = tf.config.experimental.list_physical_devices(... | ():
if epoch < LR_RAMPUP_EPOCHS:
lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN
return lr
def tf_d... | lrfn | identifier_name |
ResNet50_augmentation.py | import pathlib, random, cv2
import tensorflow as tf
import numpy as np
import tensorflow.keras.backend as K
import albumentations as A
from matplotlib import pyplot as plt
from functools import partial
from sklearn.model_selection import train_test_split
# GPU setup
gpus = tf.config.experimental.list_physical_devices(... |
print('Learning Finished')
model.save('/home/v100/tf_workspace/model/resnet50_adam_he_l2_aug.h5') | PATIENCE -= 1
if PATIENCE == 0:
break | conditional_block |
sriov.go | // Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (conf *NetConf, ifName string, netns ns.NetNS) (*current.Interface, error) {
vf := ¤t.Interface{}
// 申请一个可用的Virtual Function
m, vfIdx, vfDevName, err := allocFreeVF()
if err != nil {
return nil, err
}
fmt.Fprintf(os.Stderr, "***********CNI SR-IOV 成功申请%v网卡的第%v个VF, 名称为: %v\n", m.Attrs().Name, vfIdx, vfDevN... | setupVF | identifier_name |
sriov.go | // Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | }
func cmdDel(args *skel.CmdArgs) error {
fmt.Fprintf(os.Stderr, "***********CNI SR-IOV cmdDel args.ContainerID = %v\n", args.ContainerID)
fmt.Fprintf(os.Stderr, "***********CNI SR-IOV cmdDel args.Netns = %v\n", args.Netns)
fmt.Fprintf(os.Stderr, "***********CNI SR-IOV cmdDel args.IfName = %v\n", args... | result.DNS = n.DNS
fmt.Fprintf(os.Stderr, "***********CNI SR-IOV cmdAdd result = %v\n", result)
return types.PrintResult(result, cniVersion) | random_line_split |
sriov.go | // Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | tdinData)
if err != nil {
return err
}
// Convert whatever the IPAM result was into the current Result type
result, err := current.NewResultFromResult(r)
if err != nil {
return err
}
if len(result.IPs) == 0 {
return errors.New("IPAM plugin returned missing IP config")
}
for _, ipc := range result.IPs {
... | IPAM.Type, args.S | conditional_block |
sriov.go | // Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | ()
fmt.Fprintf(os.Stderr, "***********CNI SR-IOV releaseVF initns = %v\n", initns)
if err != nil {
return fmt.Errorf("failed to get init netns: %v", err)
}
// for IPAM in cmdDel
return netns.Do(func(_ ns.NetNS) error {
// get VF device
vfDev, err := netlink.LinkByName(ifName)
if err != nil {
return fm... | Dir); err != nil {
return "", fmt.Errorf("failed to open the virtfn%d dir of the device %q: %v", vf, master, err)
}
infos, err := ioutil.ReadDir(vfDir)
if err != nil {
return "", fmt.Errorf("failed to read the virtfn%d dir of the device %q: %v", vf, master, err)
}
if len(infos) != 1 {
return "", fmt.Errorf... | identifier_body |
ngx-grid-table.component.ts | import { ColumnApi, GridApi, GridOptions, GridReadyEvent, IServerSideGetRowsParams, RowNode } from '@ag-grid-community/core';
import { CellRange } from '@ag-grid-community/core/dist/cjs/interfaces/iRangeController';
import { IServerSideDatasource, IServerSideGetRowsRequest } from '@ag-grid-community/core/dist/cjs/inter... | conditional_block | ||
ngx-grid-table.component.ts | import { ColumnApi, GridApi, GridOptions, GridReadyEvent, IServerSideGetRowsParams, RowNode } from '@ag-grid-community/core';
import { CellRange } from '@ag-grid-community/core/dist/cjs/interfaces/iRangeController';
import { IServerSideDatasource, IServerSideGetRowsRequest } from '@ag-grid-community/core/dist/cjs/inter... | type: 'String',
value: `${item.label}:${item.value}`,
},
} as ExcelCell);
});
return rows;
});
footers.push(...footer);
}
return footers;
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete(... | data: { | random_line_split |
ngx-grid-table.component.ts | import { ColumnApi, GridApi, GridOptions, GridReadyEvent, IServerSideGetRowsParams, RowNode } from '@ag-grid-community/core';
import { CellRange } from '@ag-grid-community/core/dist/cjs/interfaces/iRangeController';
import { IServerSideDatasource, IServerSideGetRowsRequest } from '@ag-grid-community/core/dist/cjs/inter... | oading = loading;
this.dataLoadingChange.emit(this.dataLoading);
}
toggleDataModel(): void {
if ('pageable' === this.dataLoadModel) {
this.setDataMode('infinite');
} else {
this.setDataMode('pageable');
}
}
setDataMode(model: 'pageable' | 'infinite'): void {
this.dataLoadModel ... | this.dataL | identifier_name |
ngx-grid-table.component.ts | import { ColumnApi, GridApi, GridOptions, GridReadyEvent, IServerSideGetRowsParams, RowNode } from '@ag-grid-community/core';
import { CellRange } from '@ag-grid-community/core/dist/cjs/interfaces/iRangeController';
import { IServerSideDatasource, IServerSideGetRowsRequest } from '@ag-grid-community/core/dist/cjs/inter... | i.autoSizeColumn('_action');
// }
// });
if (this.initLoadData) {
this.refresh();
}
}
private filters(): IFilter[] {
let filters = [] as IFilter[];
if (this.form) {
filters = [...this.form.filter];
}
if (this.filterHand) {
filters = [...this.filterHand(filters, t... | ;
buildResizable(this.gridOptions, this.resizable);
buildOptionField(this.gridOptions, this.optionCell);
reuseTabFix(this.router, this.currentUrl, this.destroy$, apiGetter);
repairRowModeType(this.gridOptions, this.dataLoadModel);
buildColACL(this.gridOptions, this.aclService, this.colACLTmpl);
... | identifier_body |
normalizations.py | # Lint as: python3
# Copyright 2021 The TensorFlow 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 ... |
else:
# Use the batch statistics for normalization.
norm_mean = mean
norm_variance = variance
beta, gamma = self._get_beta_gamma(theta)
return norm_mean, norm_variance, beta, gamma
def fprop(self,
theta: NestedMap,
inputs: JTensor,
paddings:... | norm_mean = theta.moving_mean
norm_variance = theta.moving_variance | conditional_block |
normalizations.py | # Lint as: python3
# Copyright 2021 The TensorFlow 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 ... |
class BatchNorm(base_layer.BaseLayer):
"""Batch normalization layer."""
@classmethod
def Params(cls) -> InstantiableParams:
p = super().Params()
p.Define('dim', 0, 'Depth of the input/output.')
p.Define(
'decay', 0.999,
'Decay in updating the mean and variance moving average used i... | """Computes mean and variance over the valid data points in inputs."""
assert inputs.ndim == padding.ndim
rank = inputs.ndim
assert all([0 <= dim < rank for dim in reduce_over_dims])
mask = 1.0 - padding
sum_v = jnp.sum(inputs * mask, axis=reduce_over_dims, keepdims=keepdims)
count_v = jnp.sum(
jnp.on... | identifier_body |
normalizations.py | # Lint as: python3
# Copyright 2021 The TensorFlow 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 ... | """
p = self.params
inputs, paddings = self._cast_to_fprop_dtype((inputs, paddings))
if paddings is None:
paddings = self._get_default_paddings(inputs)
assert inputs.ndim == paddings.ndim
assert paddings.shape[-1] == 1
norm_mean, norm_variance, beta, gamma = self.compute_and_update_m... | paddings: The paddings JTensor. Shaped [..., 1].
Returns:
Output after applying batch normalization, with the same shape as
'inputs'. | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.