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 |
|---|---|---|---|---|
client.ts | 'use strict'
import { IncomingMessage } from 'http'
import request from 'request'
import jwt from 'jsonwebtoken'
import createError from 'http-errors'
import { UA } from './ua'
const $setTimeout = setTimeout
const MONGO_REG = /^[0-9a-f]{24}$/i
// Network Errors, exclude 'ETIMEDOUT' and 'ESOCKETTIMEDOUT'
// https://gi... | (periodical: number = 3600, options?: jwt.SignOptions) {
const iat = Math.floor(Date.now() / (1000 * periodical)) * periodical
const payload = {
iat,
exp: iat + Math.floor(1.1 * periodical),
_appId: this._options.appId,
}
// token change in every hour, optimizing for server cache.
... | signAppToken | identifier_name |
client.ts | 'use strict'
import { IncomingMessage } from 'http'
import request from 'request'
import jwt from 'jsonwebtoken'
import createError from 'http-errors'
import { UA } from './ua'
const $setTimeout = setTimeout
const MONGO_REG = /^[0-9a-f]{24}$/i
// Network Errors, exclude 'ETIMEDOUT' and 'ESOCKETTIMEDOUT'
// https://gi... | * request with given method, url and data.
* It will genenrate a jwt token by signToken, and set to 'Authorization' header.
* It will merge headers, query and request options that preset into client.
* @param method method to request.
* @param url url to request, it will be resolved with client host.
... |
/** | random_line_split |
client.ts | 'use strict'
import { IncomingMessage } from 'http'
import request from 'request'
import jwt from 'jsonwebtoken'
import createError from 'http-errors'
import { UA } from './ua'
const $setTimeout = setTimeout
const MONGO_REG = /^[0-9a-f]{24}$/i
// Network Errors, exclude 'ETIMEDOUT' and 'ESOCKETTIMEDOUT'
// https://gi... |
const forwardHeaders: { [key: string]: string | string[] } = {}
for (const header of headers) {
if (req.headers[header] != null) {
forwardHeaders[header] = req.headers[header]
}
}
return this.withHeaders(forwardHeaders)
}
/**
* Creates (by Object.create) a **new client** ins... | {
headers = FORWARD_HEADERS
} | conditional_block |
cluster.go | // Package cluster holds the cluster CRD logic and definitions
// A cluster is comprised of a primary service, replica service,
// primary deployment, and replica deployment
package cluster
/*
Copyright 2017 - 2020 Crunchy Data Solutions, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may ... | // UpdateResources updates the PostgreSQL instance Deployments to reflect the
// update resources (i.e. CPU, memory)
func UpdateResources(clientset kubernetes.Interface, restConfig *rest.Config, cluster *crv1.Pgcluster) error {
// get a list of all of the instance deployments for the cluster
deployments, err := opera... | random_line_split | |
cluster.go | // Package cluster holds the cluster CRD logic and definitions
// A cluster is comprised of a primary service, replica service,
// primary deployment, and replica deployment
package cluster
/*
Copyright 2017 - 2020 Crunchy Data Solutions, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may ... | (cl *crv1.Pgcluster, errorMsg string) {
pgouser := cl.ObjectMeta.Labels[config.LABEL_PGOUSER]
topics := make([]string, 1)
topics[0] = events.EventTopicCluster
f := events.EventCreateClusterFailureFormat{
EventHeader: events.EventHeader{
Namespace: cl.ObjectMeta.Namespace,
Username: pgouser,
Topic: ... | publishClusterCreateFailure | identifier_name |
cluster.go | // Package cluster holds the cluster CRD logic and definitions
// A cluster is comprised of a primary service, replica service,
// primary deployment, and replica deployment
package cluster
/*
Copyright 2017 - 2020 Crunchy Data Solutions, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may ... |
// stopPostgreSQLInstance is a proxy function for the main
// StopPostgreSQLInstance function, as it preps a Deployment to have its
// PostgreSQL instance shut down. This helps to ensure that a PostgreSQL
// instance will launch and not be in crash recovery mode
func stopPostgreSQLInstance(clientset kubernetes.Interf... | {
clusterName := cluster.Name
//capture the cluster creation event
topics := make([]string, 1)
topics[0] = events.EventTopicCluster
f := events.EventShutdownClusterFormat{
EventHeader: events.EventHeader{
Namespace: cluster.Namespace,
Username: cluster.Spec.UserLabels[config.LABEL_PGOUSER],
Topic: ... | identifier_body |
cluster.go | // Package cluster holds the cluster CRD logic and definitions
// A cluster is comprised of a primary service, replica service,
// primary deployment, and replica deployment
package cluster
/*
Copyright 2017 - 2020 Crunchy Data Solutions, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may ... |
dataVolume, walVolume, tablespaceVolumes, err := pvc.CreateMissingPostgreSQLVolumes(
clientset, cluster, namespace, replica.Spec.Name, replica.Spec.ReplicaStorage)
if err != nil {
log.Error(err)
publishScaleError(namespace, replica.ObjectMeta.Labels[config.LABEL_PGOUSER], cluster)
return
}
//update the r... | {
return
} | conditional_block |
train.py | # standard modules
import sys
assert sys.version_info >= (3, 5), "Python 3.5 or greater required"
import argparse
import os
import time
import json
from packaging import version
import logging
logger = logging.getLogger('train_ganomaly')
debug = logger.debug
info = logger.info
warning = logger.warning
error ... | if args.random_flip:
image = tf.image.random_flip_left_right(image)
image = tf.image.random_flip_up_down(image)
if args.random_crop:
image_shape = (args.image_size, args.image_size,
args.image_channels)
... | def augment_image(image, label): | random_line_split |
train.py | # standard modules
import sys
assert sys.version_info >= (3, 5), "Python 3.5 or greater required"
import argparse
import os
import time
import json
from packaging import version
import logging
logger = logging.getLogger('train_ganomaly')
debug = logger.debug
info = logger.info
warning = logger.warning
error ... |
if args.random_brightness:
image = tf.image.random_brightness(image, max_delta=0.5)
image = tf.clip_by_value(image, 0, 1)
return image, label
train_ds = train_ds.map(
augment_image, num_parallel_calls=tf.data.experimental.AUTOTUNE)
if arg... | image_shape = (args.image_size, args.image_size,
args.image_channels)
image = tf.image.resize_with_crop_or_pad(
image, image_shape[-3] + 6, image_shape[-2] + 6)
image = tf.image.random_crop(image, size=image_shape) | conditional_block |
train.py | # standard modules
import sys
assert sys.version_info >= (3, 5), "Python 3.5 or greater required"
import argparse
import os
import time
import json
from packaging import version
import logging
logger = logging.getLogger('train_ganomaly')
debug = logger.debug
info = logger.info
warning = logger.warning
error ... |
def compile_default(model):
model.compile(
optimizer=tf.keras.optimizers.Adam(
learning_rate=args.learning_rate),
loss=tf.keras.losses.MeanSquaredError(),
metrics=[
tf.keras.losses.MeanAbsoluteError(),
tf.keras.losses.Bina... | return model_class(
input_shape=image_shape,
latent_size=args.latent_size,
n_filters=args.n_filters,
n_extra_layers=args.n_extra_layers,
**kwargs
) | identifier_body |
train.py | # standard modules
import sys
assert sys.version_info >= (3, 5), "Python 3.5 or greater required"
import argparse
import os
import time
import json
from packaging import version
import logging
logger = logging.getLogger('train_ganomaly')
debug = logger.debug
info = logger.info
warning = logger.warning
error ... | (args) -> tf.keras.Model:
image_shape = (args.image_size, args.image_size, args.image_channels)
def build_default(model_class, **kwargs):
return model_class(
input_shape=image_shape,
latent_size=args.latent_size,
n_filters=args.n_filters,
n_extra_layers=a... | build_model | identifier_name |
lib.rs | /*!
This crate provides a robust regular expression parser.
This crate defines two primary types:
* [`Ast`](ast::Ast) is the abstract syntax of a regular expression.
An abstract syntax corresponds to a *structured representation* of the
concrete syntax of a regular expression, where the concrete syntax is the
p... | /// Returns true if and only if the given character is an ASCII word character.
///
/// An ASCII word character is defined by the following character class:
/// `[_0-9a-zA-Z]'.
pub fn is_word_byte(c: u8) -> bool {
match c {
b'_' | b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' => true,
_ => false,
}
}
... | unicode::is_word_character(c)
}
| identifier_body |
lib.rs | /*!
This crate provides a robust regular expression parser.
This crate defines two primary types:
* [`Ast`](ast::Ast) is the abstract syntax of a regular expression.
An abstract syntax corresponds to a *structured representation* of the
concrete syntax of a regular expression, where the concrete syntax is the
p... | (c: char) -> bool {
match c {
'\\' | '.' | '+' | '*' | '?' | '(' | ')' | '|' | '[' | ']' | '{'
| '}' | '^' | '$' | '#' | '&' | '-' | '~' => true,
_ => false,
}
}
/// Returns true if the given character can be escaped in a regex.
///
/// This returns true in all cases that `is_meta_chara... | is_meta_character | identifier_name |
lib.rs | /*!
This crate provides a robust regular expression parser.
This crate defines two primary types:
* [`Ast`](ast::Ast) is the abstract syntax of a regular expression.
An abstract syntax corresponds to a *structured representation* of the
concrete syntax of a regular expression, where the concrete syntax is the
p... | /// For example, `%` is not a meta character, but it is escapeable. That is,
/// `%` and `\%` both match a literal `%` in all contexts.
///
/// The purpose of this routine is to provide knowledge about what characters
/// may be escaped. Namely, most regex engines permit "superfluous" escapes
/// where characters witho... | ///
/// This returns true in all cases that `is_meta_character` returns true, but
/// also returns true in some cases where `is_meta_character` returns false. | random_line_split |
main.rs | use std::env;
use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process;
use std::result;
use imdb_index::{Index, IndexBuilder, NgramType, Searcher};
use lazy_static::lazy_static;
use tabwriter::TabWriter;
use walkdir::WalkDir;
use crate::rename::{RenamerBuilder, RenameAction};
use cra... |
fn download_all_update(&self) -> Result<()> {
download::update_all(&self.data_dir)
}
}
fn app() -> clap::App<'static, 'static> {
use clap::{App, AppSettings, Arg};
lazy_static! {
// clap wants all of its strings tied to a particular lifetime, but
// we'd really like to determ... | {
download::download_all(&self.data_dir)
} | identifier_body |
main.rs | use std::env;
use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process;
use std::result;
use imdb_index::{Index, IndexBuilder, NgramType, Searcher};
use lazy_static::lazy_static;
use tabwriter::TabWriter;
use walkdir::WalkDir;
use crate::rename::{RenamerBuilder, RenameAction};
use cra... |
let mut searcher = args.searcher()?;
let results = match args.query {
None => None,
Some(ref query) => Some(searcher.search(&query.parse()?)?),
};
if args.files.is_empty() {
let results = match results {
None => failure::bail!("run with a file to rename or --query")... | {
args.create_index()?;
} | conditional_block |
main.rs | use std::env;
use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process;
use std::result;
use imdb_index::{Index, IndexBuilder, NgramType, Searcher};
use lazy_static::lazy_static;
use tabwriter::TabWriter;
use walkdir::WalkDir;
use crate::rename::{RenamerBuilder, RenameAction};
use cra... | .help("Choose the ngram size for indexing names. This is only \
used at index time and otherwise ignored."))
.arg(Arg::with_name("ngram-type")
.long("ngram-type")
.default_value("window")
.possible_values(NgramType::possible_names())
... | random_line_split | |
main.rs | use std::env;
use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process;
use std::result;
use imdb_index::{Index, IndexBuilder, NgramType, Searcher};
use lazy_static::lazy_static;
use tabwriter::TabWriter;
use walkdir::WalkDir;
use crate::rename::{RenamerBuilder, RenameAction};
use cra... | (matches: &clap::ArgMatches) -> Result<Args> {
let files = collect_paths(
matches
.values_of_os("file")
.map(|it| it.collect())
.unwrap_or(vec![]),
matches.is_present("follow"),
);
let query = matches
.value_of_l... | from_matches | identifier_name |
models.py | from app import db, marked_hashes
import random
from PIL import ImageDraw, Image, ImageFont
from PIL.ImageOps import invert
import numpy as np
from datetime import datetime as dt
from config import (CROP_MIN_MAX_GAP,
CROP_SIGNIFICANT_MEAN,
ROTATION_N_TO_SPLIT,
... |
else:
criteria[axis] = 1000000
return min(criteria)
print('basic image: ', image.size)
if angle is None:
# turn auto-rotating off
# search optimal angle to rotate
# current_resize_level = 0
# angles = [-45.0]
# angles += [0] * (ROTAT... | criteria[axis] = sum_over_axis[-1] - sum_over_axis[0] | conditional_block |
models.py | from app import db, marked_hashes
import random
from PIL import ImageDraw, Image, ImageFont
from PIL.ImageOps import invert
import numpy as np
from datetime import datetime as dt
from config import (CROP_MIN_MAX_GAP,
CROP_SIGNIFICANT_MEAN,
ROTATION_N_TO_SPLIT,
... | arkdown is saved here (redirection to database)"""
return db[self.basic_image_id]
@markdown.setter
def markdown(self, value):
db[self.image_id] = value
# update hash set: there is an marked image with that hash
image_hash = self.hash
marked_images = marked_hashes.get(im... | anning m | identifier_name |
models.py | from app import db, marked_hashes
import random
from PIL import ImageDraw, Image, ImageFont
from PIL.ImageOps import invert
import numpy as np
from datetime import datetime as dt
from config import (CROP_MIN_MAX_GAP,
CROP_SIGNIFICANT_MEAN,
ROTATION_N_TO_SPLIT,
... | img = Image.new('RGB', size=(width, height), color='white')
rotate_direction = random.randint(0, 3)
if rotate_direction in (0, 2):
font_size = random.randrange(width // 25, width // 10)
else:
font_size = random.randrange(height // 25, height // 10)
font = ImageFont.truetype("app/stat... | def random_image(seed):
random.seed(seed)
width = random.randint(128, 1024 + 1)
height = random.randint(128, 1024 + 1) | random_line_split |
models.py | from app import db, marked_hashes
import random
from PIL import ImageDraw, Image, ImageFont
from PIL.ImageOps import invert
import numpy as np
from datetime import datetime as dt
from config import (CROP_MIN_MAX_GAP,
CROP_SIGNIFICANT_MEAN,
ROTATION_N_TO_SPLIT,
... | cate(self):
return db.get_full_item(self.image_id).get('duplicate', False)
@duplicate.setter
def duplicate(self, value):
db.get_full_item(self.image_id)['duplicate'] = value
db.save()
def set_lock(self):
db.get_full_item(self.image_id)['lock_time'] = dt.now()
def remov... | image_id)['url']
@property
def dupli | identifier_body |
rpc_test.go | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"net"
"strconv"
"strings"
//"sync"
"os"
"os/exec"
"sync"
"testing"
"time"
)
var fsp []*exec.Cmd
var leaderUrl string
var num int
var id_from_url map[string]int
func TestStartServers(t *testing.T) {
num = 5
fsp = make([]*exec.Cmd, num)
id_from_url =... |
// nclients write to the same file. At the end the file should be
// any one clients' last write
func PTestRPC_ConcurrentWrites(t *testing.T) {
nclients := 3
niters := 3
clients := make([]*Client, nclients)
for i := 0; i < nclients; i++ {
cl := mkClientUrl(t, leaderUrl)
if cl == nil {
t.Fatalf("Unable to ... | {
cl := mkClientUrl(t, leaderUrl)
defer cl.close()
// Write file cs733, with expiry time of 2 seconds
str := "Cloud fun"
m, err := cl.write("cs733", str, 2)
expect(t, m, &Msg{Kind: 'O'}, "write success", err)
// Expect to read it back immediately.
m, err = cl.read("cs733")
expect(t, m, &Msg{Kind: 'C', Conten... | identifier_body |
rpc_test.go | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"net"
"strconv"
"strings"
//"sync"
"os"
"os/exec"
"sync"
"testing"
"time"
)
var fsp []*exec.Cmd
var leaderUrl string
var num int
var id_from_url map[string]int
func TestStartServers(t *testing.T) {
num = 5
fsp = make([]*exec.Cmd, num)
id_from_url =... | m, err := cl.cas("concCas", ver, str, 0)
if err != nil {
errorCh <- err
return
} else if m.Kind == 'O' {
break
} else if m.Kind != 'V' {
errorCh <- errors.New(fmt.Sprintf("Expected 'V' msg, got %c", m.Kind))
return
}
ver = m.Version // retry with latest versio... | str := fmt.Sprintf("cl %d %d", i, j)
for { | random_line_split |
rpc_test.go | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"net"
"strconv"
"strings"
//"sync"
"os"
"os/exec"
"sync"
"testing"
"time"
)
var fsp []*exec.Cmd
var leaderUrl string
var num int
var id_from_url map[string]int
func TestStartServers(t *testing.T) {
num = 5
fsp = make([]*exec.Cmd, num)
id_from_url =... |
return client
}
func (cl *Client) send(str string) error {
if cl.conn == nil {
return errNoConn
}
_, err := cl.conn.Write([]byte(str))
if err != nil {
err = fmt.Errorf("Write error in SendRaw: %v", err)
cl.conn.Close()
cl.conn = nil
}
return err
}
func (cl *Client) sendRcv(str string) (msg *Msg, err e... | {
t.Fatal(err)
} | conditional_block |
rpc_test.go | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"net"
"strconv"
"strings"
//"sync"
"os"
"os/exec"
"sync"
"testing"
"time"
)
var fsp []*exec.Cmd
var leaderUrl string
var num int
var id_from_url map[string]int
func TestStartServers(t *testing.T) {
num = 5
fsp = make([]*exec.Cmd, num)
id_from_url =... | (t *testing.T) {
// Should be able to accept a few bytes at a time
cl := mkClientUrl(t, leaderUrl)
defer cl.close()
var err error
snd := func(chunk string) {
if err == nil {
err = cl.send(chunk)
}
}
// Send the command "write teststream 10\r\nabcdefghij\r\n" in multiple chunks
// Nagle's algorithm is di... | TestRPC_Chunks | identifier_name |
dcy.go | package dcy
import (
"errors"
"fmt"
"math/rand"
"net"
"net/url"
"os"
"reflect"
"regexp"
"strings"
"sync"
"time"
"github.com/minus5/svckit/env"
"github.com/minus5/svckit/log"
"github.com/minus5/svckit/signal"
"github.com/hashicorp/consul/api"
)
const (
// EnvConsul is location of the consul to use. I... |
// Services returns all services registered in Consul from all of the datacenters
func ServicesByTag(name, tag string) (Addresses, error) {
sn, _ := serviceName(name, domain)
srvs := []Address{}
for _, fdc := range federatedDcs {
s, err := srv(tag, sn, fdc)
if err == nil {
srvs = append(srvs, s...)
}
}
... | {
return ServicesByTag(name, "")
} | identifier_body |
dcy.go | package dcy
import (
"errors"
"fmt"
"math/rand"
"net"
"net/url"
"os"
"reflect"
"regexp"
"strings"
"sync"
"time"
"github.com/minus5/svckit/env"
"github.com/minus5/svckit/log"
"github.com/minus5/svckit/signal"
"github.com/hashicorp/consul/api"
)
const (
// EnvConsul is location of the consul to use. I... |
srvs := parseConsulServiceEntries(ses)
if len(srvs) == 0 {
return nil, ErrNotFound
}
updateCache(tag, name, dc, srvs)
return srvs, nil
}
func srvQuery(tag, name string, dc string) (Addresses, error) {
l.RLock()
srvs, ok := cache[cacheKey(tag, name, dc)]
l.RUnlock()
if ok && len(srvs) > 0 {
return srvs, n... | {
serviceExists := len(ses) != 0
// initialize cache key and start goroutine
initializeCacheKey(tag, name, dc)
go func() {
monitor(tag, name, dc, qm.LastIndex, serviceExists)
}()
} | conditional_block |
dcy.go | package dcy
import (
"errors"
"fmt"
"math/rand"
"net"
"net/url"
"os"
"reflect"
"regexp"
"strings"
"sync"
"time"
"github.com/minus5/svckit/env"
"github.com/minus5/svckit/log"
"github.com/minus5/svckit/signal"
"github.com/hashicorp/consul/api"
)
const (
// EnvConsul is location of the consul to use. I... | (name string) bool {
parts := strings.Split(name, ".")
if len(parts) == 1 {
if parts[0] == "localhost" {
return false
}
return true
}
return parts[len(parts)-1] == domain
}
func unpackURL(s string) (scheme, host, port, path string, query url.Values) {
if strings.Contains(s, "//") {
u, err := url.Parse(... | shouldDiscoverHost | identifier_name |
dcy.go | package dcy
import (
"errors"
"fmt"
"math/rand"
"net"
"net/url"
"os"
"reflect"
"regexp"
"strings"
"sync"
"time"
"github.com/minus5/svckit/env"
"github.com/minus5/svckit/log"
"github.com/minus5/svckit/signal"
"github.com/hashicorp/consul/api"
)
const (
// EnvConsul is location of the consul to use. I... | federatedDcs []string
)
// Address is service address returned from Consul.
type Address struct {
Address string
Port int
}
// String return address in host:port string.
func (a Address) String() string {
return fmt.Sprintf("%s:%d", a.Address, a.Port)
}
func (a Address) Equal(a2 Address) bool {
return a.Addr... | consulAddr = localConsulAdr | random_line_split |
opendocument_html_xslt.py | # coding: utf-8
from logging import DEBUG
import zipfile
import os
import tempfile
import shutil
from StringIO import StringIO
from zope.interface import implements |
from plone.transforms.interfaces import ITransform, IRankedTransform
from plone.transforms.message import PloneMessageFactory as _
from plone.transforms.transform import TransformResult
from plone.transforms.log import log
import plone.opendocument.utils as utils
HAS_LXML = True
try:
from lxml import etree
exc... | random_line_split | |
opendocument_html_xslt.py | # coding: utf-8
from logging import DEBUG
import zipfile
import os
import tempfile
import shutil
from StringIO import StringIO
from zope.interface import implements
from plone.transforms.interfaces import ITransform, IRankedTransform
from plone.transforms.message import PloneMessageFactory as _
from plone.tra... |
def _concatDataFiles(self):
'''
Returns XML file object that concatenates all files stored in self._dataFiles
with xi:include.
'''
includeXML = lambda x: (x in self._dataFiles) and \
'<xi:include href="%s" />' % (self._dataFiles[... | '''
Extracts required files from data (opendocument file). They are stored
in self.subobjects and self._dataFiles.
'''
try:
#transform data to zip file object
data_ = tempfile.NamedTemporaryFile()
for chunk in data:
data_.write(chu... | identifier_body |
opendocument_html_xslt.py | # coding: utf-8
from logging import DEBUG
import zipfile
import os
import tempfile
import shutil
from StringIO import StringIO
from zope.interface import implements
from plone.transforms.interfaces import ITransform, IRankedTransform
from plone.transforms.message import PloneMessageFactory as _
from plone.tra... |
data_.seek(0)
dataZip = zipfile.ZipFile(data_)
dataIterator = utils.zipIterator(dataZip)
#extract content
for fileName, fileContent in dataIterator:
#getting data files
if (fileName == 'content.xml'):
cont... | data_.write(chunk) | conditional_block |
opendocument_html_xslt.py | # coding: utf-8
from logging import DEBUG
import zipfile
import os
import tempfile
import shutil
from StringIO import StringIO
from zope.interface import implements
from plone.transforms.interfaces import ITransform, IRankedTransform
from plone.transforms.message import PloneMessageFactory as _
from plone.tra... | (self, data, options=None):
'''
Transforms data (OpenDocument file) to XHTML. It returns an
TransformResult object.
'''
if not self.available:
log(DEBUG, "The LXML library is required to use the %s transform "
% (self.name))
retu... | transform | identifier_name |
event.go | // Copyright 2014 Orchestrate, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
// Encode the path
path = c.Name + "/" + key + "/events/" + typ + "?" + query.Encode()
} else {
path = c.Name + "/" + key + "/events/" + typ
}
return &Iterator{
client: c.client,
iteratingEvents: true,
next: path,
}
}
| {
if opts.StartOrdinal != 0 {
query.Add("startEvent", fmt.Sprintf("%d/%d",
opts.Start.UnixNano()/1000000, opts.StartOrdinal))
} else {
query.Add("startEvent",
strconv.FormatInt(opts.Start.UnixNano()/1000000, 10))
}
} | conditional_block |
event.go | // Copyright 2014 Orchestrate, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | (
key, typ string, ts time.Time, ordinal int64, value interface{},
) (*Event, error) {
event := &Event{
Collection: c,
Key: key,
Ordinal: ordinal,
Timestamp: ts,
Type: typ,
}
// Perform the actual GET
path := fmt.Sprintf("%s/%s/events/%s/%d/%d", c.Name, key, typ,
ts.UnixNano()/1000000... | GetEvent | identifier_name |
event.go | // Copyright 2014 Orchestrate, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | if rawMsg, err := json.Marshal(value); err != nil {
return nil, err
} else {
event.Value = json.RawMessage(rawMsg)
}
// Perform the actual POST
headers := map[string]string{"Content-Type": "application/json"}
var path string
if ts != nil {
path = fmt.Sprintf("%s/%s/events/%s/%d", c.Name, key, typ,
ts.U... | Type: typ,
}
// Encode the JSON message into a raw value that we can return to the
// client if necessary. | random_line_split |
event.go | // Copyright 2014 Orchestrate, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
// Like AddEvent() except this lets you specify the timestamp that will be
// attached to the event.
func (c *Collection) AddEventWithTimestamp(
key, typ string, ts time.Time, value interface{},
) (*Event, error) {
return c.innerAddEvent(key, typ, &ts, value)
}
// Inner implementation of AddEvent*
func (c *Collect... | {
return c.innerAddEvent(key, typ, nil, value)
} | identifier_body |
day15.js | /* eslint-disable no-console */
/* eslint-disable max-len */
const input = require('./input');
/**
* --- Day 15: Beverage Bandits ---
Having perfected their hot chocolate, the Elves have a new problem: the Goblins that live in these caves will do anything to steal it. Looks like they're here for a fight.
You scan th... | ({ x, y }) {}
}
function generateMap(lines = mapStrings) {
const nodes = lines.map((line, y) => [...line].map((char, x) => new Node(x, y, char)));
nodes.forEach(line => line.forEach((node) => {
if (nodes[node.x - 1]) node.left = nodes[node.y][node.x - 1];
if (nodes[node.y - 1]) node.up = nodes[node.y - 1][... | getPath | identifier_name |
day15.js | /* eslint-disable no-console */
/* eslint-disable max-len */
const input = require('./input');
/**
* --- Day 15: Beverage Bandits ---
Having perfected their hot chocolate, the Elves have a new problem: the Goblins that live in these caves will do anything to steal it. Looks like they're here for a fight.
You scan th... |
}
console.log(generateMap()[0][0].surroundings);
| {
super(x, y, map);
this.enemy = Goblin;
} | identifier_body |
day15.js | /* eslint-disable no-console */
/* eslint-disable max-len */
const input = require('./input');
/**
* --- Day 15: Beverage Bandits ---
Having perfected their hot chocolate, the Elves have a new problem: the Goblins that live in these caves will do anything to steal it. Looks like they're here for a fight.
You scan th... | ####### #######
#G..#E# #...#E# E(200)
#E#E.E# #E#...# E(197)
#G.##.# --> #.E##.# E(185)
#...#E# #E..#E# E(200), E(200)
#...E.# #.....#
####### #######
Combat ends after 37 full rounds
Elves win with 982 total hit points left
Outcome: 37 * 982 = 36334
####### #######... | #######
Before the 48th round can finish, the top-left Goblin finds that there are no targets remaining, and so combat ends. So, the number of full rounds that were completed is 47, and the sum of the hit points of all remaining units is 200+131+59+200 = 590. From these, the outcome of the battle is 47 * 590 = 27730.
... | random_line_split |
producer.rs | // Copyright 2021, The Tremor Team
//
// 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 t... | () -> Result<()> {
let _: std::result::Result<_, _> = env_logger::try_init();
let docker = DockerCli::default();
let container = redpanda_container(&docker).await?;
let port = container.get_host_port_ipv4(9092);
let mut admin_config = ClientConfig::new();
let broker = format!("127.0.0.1:{port}"... | connector_kafka_producer | identifier_name |
producer.rs | // Copyright 2021, The Tremor Team
//
// 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 t... | "field1": 0.1,
"field3": []
},
"meta": {
"kafka_producer": {
"key": "nananananana: batchman!"
}
}
}
}, {
"data": {
"value": {
"field2": "just a string"
... | let batched_data = literal!([{
"data": {
"value": { | random_line_split |
producer.rs | // Copyright 2021, The Tremor Team
//
// 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 t... |
#[tokio::test(flavor = "multi_thread")]
#[serial(kafka)]
async fn producer_unreachable() -> Result<()> {
let _: std::result::Result<_, _> = env_logger::try_init();
let port = find_free_tcp_port().await?;
let broker = format!("127.0.0.1:{port}");
let topic = "unreachable";
let connector_config = li... | {
let _: std::result::Result<_, _> = env_logger::try_init();
let docker = DockerCli::default();
let container = redpanda_container(&docker).await?;
let port = container.get_host_port_ipv4(9092);
let mut admin_config = ClientConfig::new();
let broker = format!("127.0.0.1:{port}");
let topic ... | identifier_body |
producer.rs | // Copyright 2021, The Tremor Team
//
// 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 t... |
Ok(topic) => {
info!("Created topic {}", topic);
}
}
}
let connector_config = literal!({
"reconnect": {
"retry": {
"interval_ms": 1000_u64,
"max_retries": 10_u64
}
},
"codec": {"name... | {
error!("Error creating topic {}: {}", &topic, err);
} | conditional_block |
enforsbot.py | #!/usr/bin/env python3
"enforsbot.py by Christer Enfors (c) 2015, 2016, 2017"
from __future__ import print_function
import datetime
import re
import socket
import subprocess
import sqlite3
import eb_activity
import eb_config
import eb_cmds_loader
import eb_irc
import eb_math
import eb_message
import eb_parser
import ... |
# If no pattern match found, check commands
# =========================================
if response == "":
response, choices = self.cmd_parser.parse(text, user)
# Handle any ongoing activities
# =============================
if user.current_... | pat = re.compile(pattern)
if pat.match(text):
response = pattern_response
if callable(response):
response = response(text) | conditional_block |
enforsbot.py | #!/usr/bin/env python3
"enforsbot.py by Christer Enfors (c) 2015, 2016, 2017"
from __future__ import print_function
import datetime
import re
import socket
import subprocess
import sqlite3
import eb_activity
import eb_config
import eb_cmds_loader
import eb_irc
import eb_math
import eb_message
import eb_parser
import ... | message = eb_message.Message("Main",
eb_message.MSG_TYPE_USER_MESSAGE,
{"user": user_name,
"text": response,
"choices": choices})
self.config.send_message... | # Send response
# =============
response = response.strip() + "\n"
print(" - Response: %s" % response.replace("\n", " ")) | random_line_split |
enforsbot.py | #!/usr/bin/env python3
"enforsbot.py by Christer Enfors (c) 2015, 2016, 2017"
from __future__ import print_function
import datetime
import re
import socket
import subprocess
import sqlite3
import eb_activity
import eb_config
import eb_cmds_loader
import eb_irc
import eb_math
import eb_message
import eb_parser
import ... | (user, text):
"""Send user input to ongoing activity."""
activity = user.current_activity()
if not activity:
return None
status = activity.handle_text(text)
if status.done:
user.remove_activity()
return status
@staticmethod
def start_ask_... | handle_activity | identifier_name |
enforsbot.py | #!/usr/bin/env python3
"enforsbot.py by Christer Enfors (c) 2015, 2016, 2017"
from __future__ import print_function
import datetime
import re
import socket
import subprocess
import sqlite3
import eb_activity
import eb_config
import eb_cmds_loader
import eb_irc
import eb_math
import eb_message
import eb_parser
import ... |
def respond_lights_on(self, message):
"Turn the lights on in my house."
subprocess.call(["lights", "on"])
return "Lights have been turned ON."
def respond_lights_off(self, message):
"Turn the lights out in my house."
subprocess.call(["lights", "off"])
return "L... | "Return threads status."
output = ""
for thread in self.config.threads:
output += "%s: %s\n" % (thread,
self.config.get_thread_state(thread))
return output | identifier_body |
index.ts | import { GameProfile } from "@xmcl/common";
import { fetchBuffer, fetchJson, got } from "@xmcl/net";
import { vfs } from "@xmcl/util";
import ByteBuffer from "bytebuffer";
import * as crypto from "crypto";
import * as https from "https";
import * as queryString from "querystring";
import * as url from "url";
import { d... | (uuid: string, option: { api?: API } = {}) {
const api = option.api || API_MOJANG;
return fetchProfile(API.getProfileUrl(api, uuid) + "?" + queryString.stringify({
unsigned: false,
}), api.publicKey).then((p) => p as GameProfile);
}
/**
* Look up the GameProfile by usern... | fetch | identifier_name |
index.ts | import { GameProfile } from "@xmcl/common";
import { fetchBuffer, fetchJson, got } from "@xmcl/net";
import { vfs } from "@xmcl/util";
import ByteBuffer from "bytebuffer";
import * as crypto from "crypto";
import * as https from "https";
import * as queryString from "querystring";
import * as url from "url";
import { d... |
/**
* Fetch the GameProfile by uuid.
*
* @param uuid The unique id of user/player
* @param option the options for this function
*/
export function fetch(uuid: string, option: { api?: API } = {}) {
const api = option.api || API_MOJANG;
return fetchProfile(API.getProfil... | {
const texture = parseTexturesInfo(profile);
if (texture) { return cache ? cacheTextures(texture) : texture; }
return Promise.reject(`No texture for user ${profile.id}.`);
} | identifier_body |
index.ts | import { GameProfile } from "@xmcl/common";
import { fetchBuffer, fetchJson, got } from "@xmcl/net";
import { vfs } from "@xmcl/util";
import ByteBuffer from "bytebuffer";
import * as crypto from "crypto";
import * as https from "https";
import * as queryString from "querystring";
import * as url from "url";
import { d... | };
const finish = () => {
buff.writeUTF8String(`--${boundary}--\r\n`);
};
if (option.texture.metadata) {
for (const key in option.texture.metadata) {
diposition("name", key);
content(option.texture.m... | buff.writeUTF8String("\r\n");
buff = buff.append(payload);
buff.writeUTF8String("\r\n"); | random_line_split |
index.ts | import { GameProfile } from "@xmcl/common";
import { fetchBuffer, fetchJson, got } from "@xmcl/net";
import { vfs } from "@xmcl/util";
import ByteBuffer from "bytebuffer";
import * as crypto from "crypto";
import * as https from "https";
import * as queryString from "querystring";
import * as url from "url";
import { d... |
if (tex.textures.CAPE) {
tex.textures.CAPE = await cache(tex.textures.CAPE);
}
if (tex.textures.ELYTRA) {
tex.textures.ELYTRA = await cache(tex.textures.ELYTRA);
}
return tex;
}
/**
* Cache the texture into the url as data-uri
* @param ... | {
tex.textures.SKIN = await cache(tex.textures.SKIN);
} | conditional_block |
weginfos.js | const ETAPPEN = [
// "Nummer": "Tournummer",
// "Land": "Wanderregion",
// "Berg": "Attraktion",
// "Beschreibung": "Tourbeschreibung",
// "Tourname": "Tourname",
// "Schwierigkeit": "Schwierigkeitsgrad",
// "Dauer": "Dauer",
// "KM": "Länge",
// "... | "Berg": "Innsbruck Citytour",
"Beschreibung": "Innsbruck ist keine überwältigend große Metropole. Ihre Einzigartigkeit besteht dafür in ihrer alpinen Lage. Blicke aus der Innenstadt gen Himmel bleiben an den prominenten, die Stadt umrahmenden Bergketten hängen.",
"Tourname": "Die Hauptstadt der ... | "Abstieg": 740
},
{
"Nummer": "13",
"Land": "Österreich", | random_line_split |
process.go | package process
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"time"
"github.com/pinpt/ripsrc/ripsrc/parentsgraph"
"github.com/pinpt/ripsrc/ripsrc/gitblame2"
"github.com/pinpt/ripsrc/ripsrc/pkg/logger"
"github.com/pinpt/ripsrc/ripsrc/history3/process/repo"
"github.com/pinpt/rip... |
type Timing struct {
RegularCommitsCount int
RegularCommitsTime time.Duration
MergesCount int
MergesTime time.Duration
SlowestCommits []CommitWithDuration
}
type CommitWithDuration struct {
Commit string
Duration time.Duration
}
const maxSlowestCommits = 10
func (s *Timing) UpdateSl... | {
res, err := s.processMergeCommit(s.mergePartsCommit, s.mergeParts)
if err != nil {
panic(err)
}
s.trimGraphAfterCommitProcessed(s.mergePartsCommit)
s.mergeParts = nil
resChan <- res
} | identifier_body |
process.go | package process
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"time"
"github.com/pinpt/ripsrc/ripsrc/parentsgraph"
"github.com/pinpt/ripsrc/ripsrc/gitblame2"
"github.com/pinpt/ripsrc/ripsrc/pkg/logger"
"github.com/pinpt/ripsrc/ripsrc/history3/process/repo"
"github.com/pinpt/rip... |
}
if len(s.mergeParts) > 0 {
s.processGotMergeParts(resChan)
}
if i == 0 {
// there were no items in log, happens when last processed commit was in a branch that is no longer recent and is skipped in incremental
// no need to write checkpoints
<-done
return nil
}
writer := repo.NewCheckpointWriter(s... | {
drainAndExit()
return err
} | conditional_block |
process.go | package process
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"time"
"github.com/pinpt/ripsrc/ripsrc/parentsgraph"
"github.com/pinpt/ripsrc/ripsrc/gitblame2"
"github.com/pinpt/ripsrc/ripsrc/pkg/logger"
"github.com/pinpt/ripsrc/ripsrc/history3/process/repo"
"github.com/pinpt/rip... | // empty file at temp location to set an empty attributesFile
f, err := ioutil.TempFile("", "ripsrc")
if err != nil {
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
args := []string{
"-c", "core.attributesFile=" + f.Name(),
"-c", "diff.renameLimit=10000",
"log",
"-p",
"-m",
... |
func (s *Process) gitLogPatches() (io.ReadCloser, error) { | random_line_split |
process.go | package process
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"time"
"github.com/pinpt/ripsrc/ripsrc/parentsgraph"
"github.com/pinpt/ripsrc/ripsrc/gitblame2"
"github.com/pinpt/ripsrc/ripsrc/pkg/logger"
"github.com/pinpt/ripsrc/ripsrc/history3/process/repo"
"github.com/pinpt/rip... | () Timing {
return *s.timing
}
func (s *Process) initCheckpoints() error {
if s.opts.CommitFromIncl == "" {
s.repo = repo.New()
} else {
expectedCommit := ""
if s.opts.NoStrictResume {
// validation disabled
} else {
expectedCommit = s.opts.CommitFromIncl
}
reader := repo.NewCheckpointReader(s.op... | Timing | identifier_name |
lstm.py | # coding=utf-8
import random
import string
import zipfile
import numpy as np
import tensorflow as tf
from not_mnist.img_pickle import save_obj, load_pickle
from not_mnist.load_data import maybe_download
def read_data(filename):
f = zipfile.ZipFile(filename)
for name in f.namelist():
return tf.compat... | ollings]
train_labels = train_data[1:] # labels are inputs shifted by one time step.
# Unrolled LSTM loop.
outputs = list()
output = saved_output
state = saved_state
for i in train_inputs:
output, state = lstm_cell(i, output, state)
outputs.append(output)
# State saving ac... | holder(tf.float32, shape=[batch_size, vocabulary_size]))
train_inputs = train_data[:num_unr | conditional_block |
lstm.py | # coding=utf-8
import random
import string
import zipfile
import numpy as np
import tensorflow as tf
from not_mnist.img_pickle import save_obj, load_pickle
from not_mnist.load_data import maybe_download
def read_data(filename):
f = zipfile.ZipFile(filename)
for name in f.namelist():
return tf.compat... |
def next(self):
"""Generate the next array of batches from the data. The array consists of
the last batch of the previous array, followed by num_unrollings new ones.
"""
batches = [self._last_batch]
for step in range(self._num_unrollings):
batches.append(self._ne... | ""Generate a single batch from the current cursor position in the data."""
batch = np.zeros(shape=(self._batch_size, vocabulary_size), dtype=np.float)
for b in range(self._batch_size):
# same id, same index of second dimension
batch[b, char2id(self._text[self._cursor[b]])] = 1.0
... | identifier_body |
lstm.py | # coding=utf-8
import random
import string
import zipfile
import numpy as np
import tensorflow as tf
from not_mnist.img_pickle import save_obj, load_pickle
from not_mnist.load_data import maybe_download
def read_data(filename):
f = zipfile.ZipFile(filename)
for name in f.namelist():
return tf.compat... | batches):
"""Convert a sequence of batches back into their (most likely) string
representation."""
s = [''] * batches[0].shape[0]
for b in batches:
s = [''.join(x) for x in zip(s, characters(b))]
return s
train_batches = BatchGenerator(train_text, batch_size, num_unrollings)
valid_batches ... | atches2string( | identifier_name |
lstm.py | # coding=utf-8
import random
import string
import zipfile
import numpy as np
import tensorflow as tf
from not_mnist.img_pickle import save_obj, load_pickle
from not_mnist.load_data import maybe_download
def read_data(filename):
f = zipfile.ZipFile(filename)
for name in f.namelist():
return tf.compat... | """Log-probability of the true labels in a predicted batch."""
predictions[predictions < 1e-10] = 1e-10
return np.sum(np.multiply(labels, -np.log(predictions))) / labels.shape[0]
def sample_distribution(distribution):
"""Sample one element from a distribution assumed to be an array of normalized
p... |
def logprob(predictions, labels):
# prevent negative probability | random_line_split |
dataset.py |
# This module is used to load pascalvoc datasets (2007 or 2012)
import os
import tensorflow as tf
from configs.config_common import *
from configs.config_train import *
from configs.config_test import *
import sys
import random
import numpy as np
import xml.etree.ElementTree as ET
# Original dataset organisation.
DIR... | (self, value):
if not isinstance(value, list):
value = [value]
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
# Wrapper for inserting bytes features into Example proto.
def bytes_feature(self, value):
if not isinstance(value, list):
value = ... | float_feature | identifier_name |
dataset.py |
# This module is used to load pascalvoc datasets (2007 or 2012)
import os
import tensorflow as tf
from configs.config_common import *
from configs.config_train import *
from configs.config_test import *
import sys
import random
import numpy as np
import xml.etree.ElementTree as ET
# Original dataset organisation.
DIR... |
# Convert images to tfrecords
# Args:
# dataset_dir: The dataset directory where the dataset is stored.
# output_dir: Output directory.
def run_PascalVOC(self, dataset_dir, output_dir, name='voc_train', shuffling=False):
if not tf.gfile.Exists(dataset_dir):
tf.g... | return '%s/%s_%03d.tfrecord' % (output_dir, name, idx) | identifier_body |
dataset.py | # This module is used to load pascalvoc datasets (2007 or 2012)
import os
import tensorflow as tf
from configs.config_common import *
from configs.config_train import *
from configs.config_test import *
import sys
import random
import numpy as np
import xml.etree.ElementTree as ET
# Original dataset organisation.
DIRE... | if dataset_name == 'pascalvoc_2007' or dataset_name == 'pascalvoc_2012':
dataset = self.load_dataset(dataset_name, train_or_test, dataset_path)
return dataset
# This function is used to load pascalvoc2007 or psaclvoc2012 datasets
# Inputs:
# dataset_name: pascal... | with tf.name_scope(None, "read_dataset_from_tfrecords") as scope: | random_line_split |
dataset.py |
# This module is used to load pascalvoc datasets (2007 or 2012)
import os
import tensorflow as tf
from configs.config_common import *
from configs.config_train import *
from configs.config_test import *
import sys
import random
import numpy as np
import xml.etree.ElementTree as ET
# Original dataset organisation.
DIR... |
dataset_file_name = os.path.join(dataset_path, dataset_file_name % train_or_test)
reader = tf.TFRecordReader
decoder = slim.tfexample_decoder.TFExampleDecoder(self.features, self.items)
return slim.dataset.Dataset(
data_sources=dataset_file_name,
... | train_test_sizes = {
'train': FLAGS.pascalvoc_2012_train_size,
} | conditional_block |
exec.rs | use std::{
ops::DerefMut,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};
use crate::vbus::{
BusSpawnedProcess, VirtualBusError, VirtualBusInvokable, VirtualBusProcess, VirtualBusScope,
};
use futures::Future;
use tokio::sync::mpsc;
use tracing::*;
use wasmer::{FunctionEnvMut, Instance, Mem... | else if self.commands.exists(name.as_str()) {
tracing::warn!("builtin command without a parent ctx - {}", name);
}
Err(VirtualBusError::NotFound)
}
}
#[derive(Debug)]
pub(crate) struct SpawnedProcess {
pub exit_code: Mutex<Option<ExitCode>>,
pub exit_code_rx: Mutex<mpsc::Unboun... | {
if self.commands.exists(name.as_str()) {
return self
.commands
.exec(parent_ctx, name.as_str(), store, builder);
}
} | conditional_block |
exec.rs | use std::{
ops::DerefMut,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};
use crate::vbus::{
BusSpawnedProcess, VirtualBusError, VirtualBusInvokable, VirtualBusProcess, VirtualBusScope,
};
use futures::Future;
use tokio::sync::mpsc;
use tracing::*;
use wasmer::{FunctionEnvMut, Instance, Mem... | (
module: Module,
store: Store,
env: WasiEnv,
runtime: &Arc<dyn WasiRuntime + Send + Sync + 'static>,
) -> Result<BusSpawnedProcess, VirtualBusError> {
// Create a new task manager
let tasks = runtime.task_manager();
// Create the signaler
let pid = env.pid();
let signaler = Box::ne... | spawn_exec_module | identifier_name |
exec.rs | use std::{
ops::DerefMut,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};
use crate::vbus::{
BusSpawnedProcess, VirtualBusError, VirtualBusInvokable, VirtualBusProcess, VirtualBusScope,
};
use futures::Future;
use tokio::sync::mpsc;
use tracing::*;
use wasmer::{FunctionEnvMut, Instance, Mem... |
unsafe impl Send for UnsafeWrapper {}
let inner = UnsafeWrapper {
inner: Box::new(task),
};
move || {
(inner.inner)();
}
};
tasks_outer.task_wasm(Box::new(task)).map_err(|err| {
error!("wasi[{}]::... | struct UnsafeWrapper {
inner: Box<dyn FnOnce() + 'static>,
} | random_line_split |
lib.rs | // Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
#[cfg(feature = "std")]
use std::fmt::Debug;
use sp_std::prelude::*;
pub mod abi;
pub mod contract_metadata;
pub mod gateway_inbound_protocol;
pub mod transfers;
pub use gateway_inbound_protocol::GatewayInboundProtocol;
pub type ChainId = [u8; 4];
#[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Encode, Decode, De... | use serde::{Deserialize, Serialize};
#[cfg(feature = "no_std")]
use sp_runtime::RuntimeDebug as Debug; | random_line_split |
lib.rs | // Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | {
/// The contract returned successfully.
///
/// There is a status code and, optionally, some data returned by the contract.
Success {
/// Flags that the contract passed along on returning to alter its exit behaviour.
/// Described in `pallet_contracts::exec::ReturnFlags`.
flag... | ComposableExecResult | identifier_name |
monitors_test.go | package mackerel
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/kylelemons/godebug/pretty"
)
func TestFindMonitors(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/api/... |
func BenchmarkDecodeMonitor(b *testing.B) {
for i := 0; i < b.N; i++ {
decodeMonitorsJSON(b)
}
}
func decodeMonitorsJSON(t testing.TB) []Monitor {
var data struct {
Monitors []json.RawMessage `json:"monitors"`
}
if err := json.NewDecoder(strings.NewReader(monitorsjson)).Decode(&data); err != nil {
t.Error... | {
if got := decodeMonitorsJSON(t); !reflect.DeepEqual(got, wantMonitors) {
t.Errorf("fail to get correct data: diff: (-got +want)\n%v", pretty.Compare(got, wantMonitors))
}
} | identifier_body |
monitors_test.go | package mackerel
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/kylelemons/godebug/pretty"
)
func TestFindMonitors(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/api/... | (t *testing.T) {
b, err := json.MarshalIndent(monitorsToBeEncoded, "", " ")
if err != nil {
t.Error("err shoud be nil but: ", err)
}
want := `[
{
"id": "2cSZzK3XfmB",
"warning": 0,
"critical": 400000
},
{
"id": "2cSZzK3XfmC",
"warning": 50,
"critical... | TestEncodeMonitor | identifier_name |
monitors_test.go | package mackerel
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/kylelemons/godebug/pretty"
)
func TestFindMonitors(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/api/... |
var wantMonitors = []Monitor{
&MonitorConnectivity{
ID: "2cSZzK3XfmA",
Name: "",
Type: "connectivity",
IsMute: false,
NotificationInterval: 0,
Scopes: []string{},
ExcludeScopes: []string{},
},
&MonitorHostMetric{
ID... | "notificationInterval": 60
}
]
}
` | random_line_split |
monitors_test.go | package mackerel
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/kylelemons/godebug/pretty"
)
func TestFindMonitors(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/api/... |
if m.ResponseTimeDuration != 5 {
t.Error("request sends json including responseTimeDuration but: ", m)
}
if m.CertificationExpirationCritical != 15 {
t.Error("request sends json including certificationExpirationCritical but: ", m)
}
if m.CertificationExpirationWarning != 30 {
t.Error("request sen... | {
t.Error("request sends json including responseTimeWarning but: ", m)
} | conditional_block |
impl.go | package mainimpl
import (
"fmt"
"os"
"io/ioutil"
"encoding/hex"
"path"
"path/filepath"
"os/signal"
"time"
"encoding/json"
"github.com/SmartMeshFoundation/SmartRaiden"
"github.com/SmartMeshFoundation/SmartRaiden/internal/debug"
"github.com/SmartMeshFoundation/SmartRaiden/log"
"github.com/SmartMeshFo... |
return nil
}
app.After = func(ctx *cli.Context) error {
debug.Exit()
return nil
}
app.Run(os.Args)
}
func MainCtx(ctx *cli.Context) error {
var pms *network.PortMappedSocket
var err error
fmt.Printf("Welcom to smartraiden,version %s\n", ctx.App.Version)
if ctx.String("nat") != "ice" {
host, port := ne... | {
return err
} | conditional_block |
impl.go | package mainimpl
import (
"fmt"
"os"
"io/ioutil"
"encoding/hex"
"path"
"path/filepath"
"os/signal"
"time"
"encoding/json"
"github.com/SmartMeshFoundation/SmartRaiden"
"github.com/SmartMeshFoundation/SmartRaiden/internal/debug"
"github.com/SmartMeshFoundation/SmartRaiden/log"
"github.com/SmartMeshFo... |
func buildTransportAndDiscovery(cfg *params.Config, pms *network.PortMappedSocket, bcs *rpc.BlockChainService) (transport network.Transporter, discovery network.DiscoveryInterface) {
var err error
/*
use ice and doesn't work as route node,means this node runs on a mobile phone.
*/
if cfg.NetworkMode == params.I... | {
var pms *network.PortMappedSocket
var err error
fmt.Printf("Welcom to smartraiden,version %s\n", ctx.App.Version)
if ctx.String("nat") != "ice" {
host, port := network.SplitHostPort(ctx.String("listen-address"))
pms, err = network.SocketFactory(host, port, ctx.String("nat"))
if err != nil {
log.Crit(fmt.... | identifier_body |
impl.go | package mainimpl
import (
"fmt"
"os"
"io/ioutil"
"encoding/hex"
"path"
"path/filepath"
"os/signal"
"time"
"encoding/json"
"github.com/SmartMeshFoundation/SmartRaiden"
"github.com/SmartMeshFoundation/SmartRaiden/internal/debug"
"github.com/SmartMeshFoundation/SmartRaiden/log"
"github.com/SmartMeshFo... | (cfg *params.Config, pms *network.PortMappedSocket, bcs *rpc.BlockChainService) (transport network.Transporter, discovery network.DiscoveryInterface) {
var err error
/*
use ice and doesn't work as route node,means this node runs on a mobile phone.
*/
if cfg.NetworkMode == params.ICEOnly && cfg.IgnoreMediatedNode... | buildTransportAndDiscovery | identifier_name |
impl.go | package mainimpl
import (
"fmt"
"os"
"io/ioutil"
"encoding/hex"
"path"
"path/filepath"
"os/signal"
"time"
"encoding/json"
"github.com/SmartMeshFoundation/SmartRaiden"
"github.com/SmartMeshFoundation/SmartRaiden/internal/debug"
"github.com/SmartMeshFoundation/SmartRaiden/log"
"github.com/SmartMeshFo... | cli.BoolFlag{
Name: "debugcrash",
Usage: "enable debug crash feature",
},
cli.StringFlag{
Name: "conditionquit",
Usage: "quit at specified point for test",
Value: "",
},
cli.StringFlag{
Name: "turn-server",
Usage: "tur server for ice",
Value: params.DefaultTurnServer,
},
cli.Str... | "ice"- Use ice framework for nat punching
[default: ice]`,
Value: "ice",
}, | random_line_split |
evaluation_confidence_mask_sinmul.py | import sys
sys.path.append("/home/aab10867zc/work/aist/pspicker/code")
import config
import utils
import pandas as pd
import numpy as np
from obspy import Trace,Stream
import matplotlib.pyplot as plt
from obspy.core import read
from glob import glob
import shutil
import math
import datetime
import random
import json
im... |
else:
super(self.__class__).window_reference(self, window_id)
def load_mask(self, window_id):
"""Generate instance masks for shapes of the given image ID.
"""
streams = self.load_streams(window_id)
info=self.window_info[window_id]
shape=info["shape"]
... | return info["station"] | conditional_block |
evaluation_confidence_mask_sinmul.py | import sys
sys.path.append("/home/aab10867zc/work/aist/pspicker/code")
import config
import utils
import pandas as pd
import numpy as np
from obspy import Trace,Stream
import matplotlib.pyplot as plt
from obspy.core import read
from glob import glob
import shutil
import math
import datetime
import random
import json
im... | else:
return o
class Evaluation_confidence_mask():
def __init__(self,single_model,multi_model,dataset,overlap_threshold=0.3):
self.single_model=single_model
self.multi_model=multi_model
self.dataset=dataset
self.overlap_threshold=overlap_threshold
def evaluate(self,... | return o.__str__()
elif type(o).__module__ == np.__name__:
return o.__str__() | random_line_split |
evaluation_confidence_mask_sinmul.py | import sys
sys.path.append("/home/aab10867zc/work/aist/pspicker/code")
import config
import utils
import pandas as pd
import numpy as np
from obspy import Trace,Stream
import matplotlib.pyplot as plt
from obspy.core import read
from glob import glob
import shutil
import math
import datetime
import random
import json
im... |
def load_window(self, window_id):
"""Generate an image from the specs of the given image ID.
Typically this function loads the image from a file, but
in this case it generates the image on the fly from the
specs in image_info.
"""
streams = self.load_streams(win... | info = self.window_info[window_id]
shape=info["shape"]
streams=[]
dist = []
for event in info["path"]:
paths=list(event.values())
traces=[]
for path in paths:
trace=read(path)[0]
traces.append(trace)
stream... | identifier_body |
evaluation_confidence_mask_sinmul.py | import sys
sys.path.append("/home/aab10867zc/work/aist/pspicker/code")
import config
import utils
import pandas as pd
import numpy as np
from obspy import Trace,Stream
import matplotlib.pyplot as plt
from obspy.core import read
from glob import glob
import shutil
import math
import datetime
import random
import json
im... | (self,single_model,multi_model,dataset,overlap_threshold=0.3):
self.single_model=single_model
self.multi_model=multi_model
self.dataset=dataset
self.overlap_threshold=overlap_threshold
def evaluate(self,window_id=None):
test_results = []
for window_id in self.datase... | __init__ | identifier_name |
lib.rs | use url::*;
pub struct Example<'a> {
dirty: &'a str,
clean: &'a str,
}
impl<'a> Example<'a> {
pub const fn new(dirty: &'a str, clean: &'a str) -> Self {
Self { dirty, clean }
}
}
/// Contains directives on how to extract the link from a click-tracking link forwarder.
pub struct CleanInformati... | let cleaner = UrlCleaner::default();
let clean = cleaner.clean_url(&parsed).unwrap();
assert_eq!(clean, url_clean);
}
#[test]
fn clean_facebook2() {
let url_dirty ="https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.banggood.com%2FXT30-V3-ParaBoard-Parallel-Charging-Board-Ban... | let parsed = Url::parse(&url_dirty).unwrap(); | random_line_split |
lib.rs | use url::*;
pub struct Example<'a> {
dirty: &'a str,
clean: &'a str,
}
impl<'a> Example<'a> {
pub const fn new(dirty: &'a str, clean: &'a str) -> Self {
Self { dirty, clean }
}
}
/// Contains directives on how to extract the link from a click-tracking link forwarder.
pub struct CleanInformati... | (&self, url: &url::Url) -> Option<String> {
if let Some(domain) = url.domain() {
// Check all rules that matches this domain, but return on the first clean
for domaininfo in self.cleaning_info.iter().filter(|&x| x.domain == domain) {
if domaininfo.path == url.path() {
... | clean_url | identifier_name |
lib.rs | use url::*;
pub struct Example<'a> {
dirty: &'a str,
clean: &'a str,
}
impl<'a> Example<'a> {
pub const fn new(dirty: &'a str, clean: &'a str) -> Self {
Self { dirty, clean }
}
}
/// Contains directives on how to extract the link from a click-tracking link forwarder.
pub struct CleanInformati... | else {
newurl.query_pairs_mut().append_pair(&key, &value);
}
}
(newurl, modified)
}
/// try to extract the destination url from the link if possible and also try to remove the click-id
/// query parameters that are available, if the content has been modified ret... | {
println!("key found: {:?}", key);
modified = true;
} | conditional_block |
lib.rs | use url::*;
pub struct Example<'a> {
dirty: &'a str,
clean: &'a str,
}
impl<'a> Example<'a> {
pub const fn new(dirty: &'a str, clean: &'a str) -> Self {
Self { dirty, clean }
}
}
/// Contains directives on how to extract the link from a click-tracking link forwarder.
pub struct CleanInformati... |
pub fn try_clean_string(&self, url_string: String) -> String {
if let Ok(parsed) = Url::parse(&url_string) {
if let Some(clean) = self.clean_url(&parsed) {
return clean;
}
}
url_string
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]... | {
if let Some(domain) = url.domain() {
// Check all rules that matches this domain, but return on the first clean
for domaininfo in self.cleaning_info.iter().filter(|&x| x.domain == domain) {
if domaininfo.path == url.path() {
println!("{}", url);
... | identifier_body |
generate-map.ts | import { distSq } from "./vector";
import { Delaunay } from "d3-delaunay";
import Map, { Tile } from "./map";
import { line } from "./utils";
// Crude Djikstra implementation over a d3-delaunay triangulation
function routeTo(delaunay: Delaunay<Delaunay.Point>, start: number, end: number) {
const pointCount = delauna... | () {
const addedGrasses = [];
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const t = this.map.get(x, y);
if (t === Tile.Ground) {
const pastureNeighbors =
(x > 0 && this.map.get(x - 1, y) === Tile.Grass ? 1 : 0) +
(x < width - 1 &&... | iterateGrass | identifier_name |
generate-map.ts | import { distSq } from "./vector";
import { Delaunay } from "d3-delaunay";
import Map, { Tile } from "./map";
import { line } from "./utils";
// Crude Djikstra implementation over a d3-delaunay triangulation
function routeTo(delaunay: Delaunay<Delaunay.Point>, start: number, end: number) {
const pointCount = delauna... |
iterateGrass() {
const addedGrasses = [];
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const t = this.map.get(x, y);
if (t === Tile.Ground) {
const pastureNeighbors =
(x > 0 && this.map.get(x - 1, y) === Tile.Grass ? 1 : 0) +
(... | {
[x, y] = [x, y].map(Math.round);
if (this.map.get(x, y) === Tile.Ground) {
this.map.set(x, y, Tile.Grass);
}
} | identifier_body |
generate-map.ts | import { distSq } from "./vector";
import { Delaunay } from "d3-delaunay";
import Map, { Tile } from "./map";
import { line } from "./utils";
// Crude Djikstra implementation over a d3-delaunay triangulation
function routeTo(delaunay: Delaunay<Delaunay.Point>, start: number, end: number) {
const pointCount = delauna... | const [x1, y1] = points[waterPath[i + 1]];
mapBuilder.addStream(x0, y0, x1, y1);
}
// add crossings at open points along the stream
const crossings = [];
for (let i = 0; i < waterPath.length - 1; i++) {
if (interior.includes(waterPath[i]) && !usedPoints.includes(waterPath[i])) {
crossings.pus... | random_line_split | |
generate-map.ts | import { distSq } from "./vector";
import { Delaunay } from "d3-delaunay";
import Map, { Tile } from "./map";
import { line } from "./utils";
// Crude Djikstra implementation over a d3-delaunay triangulation
function routeTo(delaunay: Delaunay<Delaunay.Point>, start: number, end: number) {
const pointCount = delauna... |
}
// calculate a triangulation of the points
const triangulation = Delaunay.from(points);
// pick a subset of points forming a circle in the center to be our playable area
const interior: number[] = [];
const sorted = points
.slice()
.sort((p0, p1) => distSq(p0, [w / 2, h / 2]) - distSq(p1, [w / ... | {
points.push([x, y]);
} | conditional_block |
callback.go | package core
import (
"context"
"fmt"
"net/http"
"github.com/anz-bank/sysl-go/log"
"github.com/anz-bank/sysl-go/common"
"github.com/anz-bank/sysl-go/config"
"github.com/anz-bank/sysl-go/core/authrules"
"github.com/anz-bank/sysl-go/jwtauth"
"github.com/go-chi/chi"
"google.golang.org/grpc"
)
// RestGenCallb... | type Hooks struct {
// Logger returns the common.Logger instance to set use within Sysl-go.
// By default, if this Logger hook is not set then an instance of the pkg logger is used.
// This hook can also be used to define a custom logger.
// For more information about logging see log/README.md within this project.... | random_line_split | |
callback.go | package core
import (
"context"
"fmt"
"net/http"
"github.com/anz-bank/sysl-go/log"
"github.com/anz-bank/sysl-go/common"
"github.com/anz-bank/sysl-go/config"
"github.com/anz-bank/sysl-go/core/authrules"
"github.com/anz-bank/sysl-go/jwtauth"
"github.com/go-chi/chi"
"google.golang.org/grpc"
)
// RestGenCallb... | (ctx context.Context, h *Hooks, endpointName string, authRuleExpression string) (authrules.Rule, error) {
return resolveAuthorizationRule(ctx, h, endpointName, authRuleExpression, authrules.MakeGRPCJWTAuthorizationRule)
}
func ResolveRESTAuthorizationRule(ctx context.Context, h *Hooks, endpointName string, authRuleEx... | ResolveGRPCAuthorizationRule | identifier_name |
callback.go | package core
import (
"context"
"fmt"
"net/http"
"github.com/anz-bank/sysl-go/log"
"github.com/anz-bank/sysl-go/common"
"github.com/anz-bank/sysl-go/config"
"github.com/anz-bank/sysl-go/core/authrules"
"github.com/anz-bank/sysl-go/jwtauth"
"github.com/go-chi/chi"
"google.golang.org/grpc"
)
// RestGenCallb... |
authenticator, err := jwtauth.AuthFromConfig(ctx, cfg.Library.Authentication.JWTAuth, httpClientFactory)
if err != nil {
return nil, err
}
return ruleFactory(claimsBasedAuthRule, authenticator)
}
| {
return nil, fmt.Errorf("method/endpoint %s requires a JWT-based authorization rule, but there is no config for library.authentication.jwtauth", endpointName)
} | conditional_block |
callback.go | package core
import (
"context"
"fmt"
"net/http"
"github.com/anz-bank/sysl-go/log"
"github.com/anz-bank/sysl-go/common"
"github.com/anz-bank/sysl-go/config"
"github.com/anz-bank/sysl-go/core/authrules"
"github.com/anz-bank/sysl-go/jwtauth"
"github.com/go-chi/chi"
"google.golang.org/grpc"
)
// RestGenCallb... |
func ResolveGrpcServerOptions(ctx context.Context, h *Hooks, grpcPublicServerConfig *config.CommonServerConfig) ([]grpc.ServerOption, error) {
switch {
case len(h.AdditionalGrpcServerOptions) > 0 && h.OverrideGrpcServerOptions != nil:
return nil, fmt.Errorf("Hooks.AdditionalGrpcServerOptions and Hooks.OverrideGrp... | {
switch {
case len(h.AdditionalGrpcDialOptions) > 0 && h.OverrideGrpcDialOptions != nil:
return nil, fmt.Errorf("Hooks.AdditionalGrpcDialOptions and Hooks.OverrideGrpcDialOptions cannot both be set")
case h.OverrideGrpcDialOptions != nil:
return h.OverrideGrpcDialOptions(serviceName, grpcDownstreamConfig)
defa... | identifier_body |
gdb.rs | use gdbstub::common::{Signal, Tid};
use gdbstub::conn::Connection;
use gdbstub::stub::state_machine::GdbStubStateMachine;
use gdbstub::stub::{GdbStubBuilder, GdbStubError, MultiThreadStopReason};
use gdbstub::target::Target;
use crate::io::SerialRead;
use crate::platform::precursor::gdbuart::GdbUart;
mod breakpoints;... | {
let mut uart = GdbUart::new(receive_irq).unwrap();
uart.enable();
let mut target = XousTarget::new();
let server = GdbStubBuilder::new(uart)
.with_packet_buffer(unsafe { &mut GDB_BUFFER })
.build()
.expect("unable to build gdb server")
.run_state_machine(&mut target)
... | identifier_body | |
gdb.rs | use gdbstub::common::{Signal, Tid};
use gdbstub::conn::Connection;
use gdbstub::stub::state_machine::GdbStubStateMachine;
use gdbstub::stub::{GdbStubBuilder, GdbStubError, MultiThreadStopReason};
use gdbstub::target::Target;
use crate::io::SerialRead;
use crate::platform::precursor::gdbuart::GdbUart;
mod breakpoints;... |
}
}
_ => {
println!("GDB is in an unexpected state!");
return;
}
};
// If the user just hit Ctrl-C, then remove the pending interrupt that may or may not exist.
if let GdbStubStateMachine::CtrlCInterrupt(_) = &new_server {
target.unpatch... | {
println!("gdbstub error in DeferredStopReason.pump: {:?}", e);
return;
} | conditional_block |
gdb.rs | use gdbstub::common::{Signal, Tid};
use gdbstub::conn::Connection;
use gdbstub::stub::state_machine::GdbStubStateMachine;
use gdbstub::stub::{GdbStubBuilder, GdbStubError, MultiThreadStopReason};
use gdbstub::target::Target;
use crate::io::SerialRead;
use crate::platform::precursor::gdbuart::GdbUart;
mod breakpoints;... | pub server: GdbStubStateMachine<'a, XousTarget, crate::platform::precursor::gdbuart::GdbUart>,
}
static mut GDB_STATE: Option<XousDebugState> = None;
static mut GDB_BUFFER: [u8; 4096] = [0u8; 4096];
trait ProcessPid {
fn pid(&self) -> Option<xous_kernel::PID>;
fn take_pid(&mut self) -> Option<xous_kernel:... | random_line_split | |
gdb.rs | use gdbstub::common::{Signal, Tid};
use gdbstub::conn::Connection;
use gdbstub::stub::state_machine::GdbStubStateMachine;
use gdbstub::stub::{GdbStubBuilder, GdbStubError, MultiThreadStopReason};
use gdbstub::target::Target;
use crate::io::SerialRead;
use crate::platform::precursor::gdbuart::GdbUart;
mod breakpoints;... | () -> Self {
MicroRingBuf {
buffer: [0u8; N],
head: 0,
tail: 0,
}
}
}
impl<const N: usize> MicroRingBuf<N> {
// pub fn capacity(&self) -> usize {
// self.buffer.len()
// }
// pub fn len(&self) -> usize {
// self.head.wrapping_sub(self.... | default | identifier_name |
tls.go | // Copyright Istio 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 wri... |
// This function can be called for namespaces with the auto generated sidecar, i.e. once per service and per port.
// OR, it could be called in the context of an egress listener with specific TCP port on a sidecar config.
// In the latter case, there is no service associated with this listen port. So we have to accou... | {
if listenPort.Protocol.IsTLS() {
return nil
}
out := make([]*filterChainOpts, 0)
// very basic TCP
// break as soon as we add one network filter with no destination addresses to match
// This is the terminating condition in the filter chain match list
defaultRouteAdded := false
TcpLoop:
for _, cfg := ran... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.