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
server.go
// Copyright (c) 2017-2020 VMware, Inc. or its affiliates // SPDX-License-Identifier: Apache-2.0 package hub import ( "context" "encoding/json" "fmt" "io" "net" "os" "strconv" "strings" "sync" "time" "github.com/greenplum-db/gp-common-go-libs/gplog" "github.com/hashicorp/go-multierror" "github.com/pkg/e...
return nil } func LoadConfig(conf *Config, path string) error { file, err := os.Open(path) if err != nil { return xerrors.Errorf("opening configuration file: %w", err) } defer file.Close() err = conf.Load(file) if err != nil { return xerrors.Errorf("reading configuration file: %w", err) } return nil }...
{ return xerrors.Errorf("saving hub configuration: %w", err) }
conditional_block
server.go
// Copyright (c) 2017-2020 VMware, Inc. or its affiliates // SPDX-License-Identifier: Apache-2.0 package hub import ( "context" "encoding/json" "fmt" "io" "net" "os" "strconv" "strings" "sync" "time" "github.com/greenplum-db/gp-common-go-libs/gplog" "github.com/hashicorp/go-multierror" "github.com/pkg/e...
func (s *Server) RestartAgents(ctx context.Context, in *idl.RestartAgentsRequest) (*idl.RestartAgentsReply, error) { restartedHosts, err := RestartAgents(ctx, nil, AgentHosts(s.Source), s.AgentPort, s.StateDir) return &idl.RestartAgentsReply{AgentHosts: restartedHosts}, err } func RestartAgents(ctx context.Context...
{ s.mu.Lock() defer s.mu.Unlock() // StopServices calls Stop(false) because it has already closed the agentConns if closeAgentConns { s.closeAgentConns() } if s.server != nil { s.server.Stop() <-s.stopped // block until it is OK to stop } // Mark this server stopped so that a concurrent Start() doesn't...
identifier_body
server.go
// Copyright (c) 2017-2020 VMware, Inc. or its affiliates // SPDX-License-Identifier: Apache-2.0 package hub import ( "context" "encoding/json" "fmt" "io" "net" "os" "strconv" "strings" "sync" "time" "github.com/greenplum-db/gp-common-go-libs/gplog" "github.com/hashicorp/go-multierror" "github.com/pkg/e...
daemon.Daemonize() } err = server.Serve(lis) if err != nil { err = xerrors.Errorf("serve: %w", err) } // inform Stop() that is it is OK to stop now s.stopped <- struct{}{} return err } func (s *Server) StopServices(ctx context.Context, in *idl.StopServicesRequest) (*idl.StopServicesReply, error) { err :...
if s.daemon { fmt.Printf("Hub started on port %d (pid %d)\n", s.Port, os.Getpid())
random_line_split
console_test.go
// Copyright 2018 The gVisor 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 agree...
// Test that an pty FD is sent over the console socket if one is provided. func TestMultiContainerConsoleSocket(t *testing.T) { for name, conf := range configs(t, false /* noOverlay */) { t.Run(name, func(t *testing.T) { rootDir, cleanup, err := testutil.SetupRootDir() if err != nil { t.Fatalf("error cre...
{ for name, conf := range configs(t, false /* noOverlay */) { t.Run(name, func(t *testing.T) { spec := testutil.NewSpecWithArgs("true") spec.Process.Terminal = true _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf) if err != nil { t.Fatalf("error setting up container: %v", err) } ...
identifier_body
console_test.go
// Copyright 2018 The gVisor 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 agree...
t.Fatalf("error getting socket path: %v", err) } srv, cleanup := createConsoleSocket(t, sock) defer cleanup() // Create the container and pass the socket name. args = Args{ ID: ids[1], Spec: testSpecs[1], BundleDir: bundleDir, ConsoleSocket: sock, } cont...
sock, err := socketPath(bundleDir) if err != nil {
random_line_split
console_test.go
// Copyright 2018 The gVisor 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 agree...
ptyMaster.Close() }) } } // Test that job control signals work on a console created with "exec -ti". func TestJobControlSignalExec(t *testing.T) { spec := testutil.NewSpecWithArgs("/bin/sleep", "10000") conf := testutil.TestConfig(t) _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf) if err ...
{ t.Fatalf("error receiving console FD: %v", err) }
conditional_block
console_test.go
// Copyright 2018 The gVisor 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 agree...
(t *testing.T) { spec := testutil.NewSpecWithArgs("/bin/sleep", "10000") conf := testutil.TestConfig(t) _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf) if err != nil { t.Fatalf("error setting up container: %v", err) } defer cleanup() // Create and start the container. args := Args{ ID: ...
TestJobControlSignalExec
identifier_name
build.py
#!/usr/bin/python # Copyright 2010 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. import os import shutil import subprocess import sys import action_tree import cmd_env script_dir = os.path.abspath(os.path.dirna...
def remove_tree(dir_path): if os.path.exists(dir_path): shutil.rmtree(dir_path) def copy_onto(source_dir, dest_dir): for leafname in os.listdir(source_dir): subprocess.check_call(["cp", "-a", os.path.join(source_dir, leafname), "-t", dest_dir]) def install_d...
temp_dir = "%s.temp" % self._source_dir os.makedirs(temp_dir) self.source.write_tree(self._env, temp_dir) os.rename(temp_dir, self._source_dir)
conditional_block
build.py
#!/usr/bin/python # Copyright 2010 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. import os import shutil import subprocess import sys import action_tree import cmd_env script_dir = os.path.abspath(os.path.dirna...
(self, log): def run(dest): cmd = [arg % {"destdir": dest} for arg in install_cmd] self._build_env.cmd(cmd) install_destdir(self._prefix, self._install_dir, run) Mod.name = name Mod.source = source return Mod ModuleBinutils = Module( name="binut...
install
identifier_name
build.py
#!/usr/bin/python # Copyright 2010 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. import os import shutil import subprocess import sys import action_tree import cmd_env script_dir = os.path.abspath(os.path.dirna...
def install_destdir(prefix_dir, install_dir, func): temp_dir = "%s.tmp" % install_dir remove_tree(temp_dir) func(temp_dir) remove_tree(install_dir) # Tree is installed into $DESTDIR/$prefix. # We need to strip $prefix. assert prefix_dir.startswith("/") os.rename(os.path.join(temp_dir, pr...
"-t", dest_dir])
random_line_split
build.py
#!/usr/bin/python # Copyright 2010 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. import os import shutil import subprocess import sys import action_tree import cmd_env script_dir = os.path.abspath(os.path.dirna...
class TestModule(ModuleBase): name = "test" source = EmptyTree() def configure(self, log): pass def make(self, log): mkdir_p(self._build_dir) write_file(os.path.join(self._build_dir, "hellow.c"), """ #include <stdio.h> int main() { printf("Hello world\\n"); return 0; } ...
name = "libnacl" source = EmptyTree() def configure(self, log): pass def make(self, log): pass def install(self, log): mkdir_p(self._build_dir) # This requires scons to pass PATH through so that it can run # nacl-gcc. We set naclsdk_mode to point to an empty ...
identifier_body
response.rs
use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie}; use hyper::status::StatusCode as Status; use hyper::Headers; use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use serde_json::value as json; use serde_json::value::ToJson; use std::any::Any; use std::boxed::Box; use std::borrow...
(&self) -> Option<&error::Error> { None } } impl From<Status> for Error { fn from(status: Status) -> Error { Error::new(status, None) } } impl From<(Status, &'static str)> for Error { fn from(pair: (Status, &'static str)) -> Error { Error::new(pair.0, Some(Cow::Borrowed(pair.1)...
cause
identifier_name
response.rs
use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie}; use hyper::status::StatusCode as Status; use hyper::Headers; use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use serde_json::value as json; use serde_json::value::ToJson; use std::any::Any; use std::boxed::Box; use std::borrow...
{ response.streaming }
identifier_body
response.rs
use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie}; use hyper::status::StatusCode as Status; use hyper::Headers; use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use serde_json::value as json; use serde_json::value::ToJson; use std::any::Any; use std::boxed::Box; use std::borrow...
self.status(Status::InternalServerError).content_type("text/plain"); Some(format!("{}", err).into()) } else { Some(buf) } }, Err(ref err) if err.kind() == ErrorKind::NotFound => { self.sta...
// probably not the best idea for big files, we should use stream instead in that case match File::open(path) { Ok(mut file) => { let mut buf = Vec::with_capacity(file.metadata().ok().map_or(1024, |meta| meta.len() as usize)); if let Err(err) = file.read_to_en...
random_line_split
node.go
// Copyright © 2019 Banzai Cloud // // 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 ...
func (n *Node) RegisterFlags(flags *pflag.FlagSet) { // Kubernetes version flags.String(constants.FlagKubernetesVersion, n.config.Kubernetes.Version, "Kubernetes version") // Kubernetes container runtime flags.String(constants.FlagContainerRuntime, n.config.ContainerRuntime.Type, "Kubernetes container runtime") /...
return short }
identifier_body
node.go
// Copyright © 2019 Banzai Cloud // // 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 ...
} n.podNetworkCIDR, err = cmd.Flags().GetString(constants.FlagPodNetworkCIDR) if err != nil { return } n.cloudProvider, err = cmd.Flags().GetString(constants.FlagCloudProvider) if err != nil { return } n.nodepool, err = cmd.Flags().GetString(constants.FlagPipelineNodepool) if err != nil { return } n.a...
return }
conditional_block
node.go
// Copyright © 2019 Banzai Cloud // // 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 ...
flags *pflag.FlagSet) { // Kubernetes version flags.String(constants.FlagKubernetesVersion, n.config.Kubernetes.Version, "Kubernetes version") // Kubernetes container runtime flags.String(constants.FlagContainerRuntime, n.config.ContainerRuntime.Type, "Kubernetes container runtime") // Kubernetes network flags.St...
egisterFlags(
identifier_name
node.go
// Copyright © 2019 Banzai Cloud // // 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 ...
return err } if err := validator.NotEmpty(map[string]interface{}{ constants.FlagKubernetesVersion: n.kubernetesVersion, constants.FlagContainerRuntime: n.containerRuntime, constants.FlagAPIServerHostPort: n.apiServerHostPort, constants.FlagKubeadmToken: n.kubeadmToken, constants.FlagCACertHash: ...
random_line_split
perf_tool.go
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package debugd import ( "bytes" "context" "fmt" "io" "io/ioutil" "os" "os/exec" "strconv" "sync" "time" "chromiumos/tast/errors" "chromiumos/tast/local/debugd" ...
if sessionID == 0 { s.Fatal("Invalid session ID from GetPerfOutputFd") } return rPipe, sessionID, nil } func checkPerfData(s *testing.State, result []byte) { const minResultLength = 20 s.Logf("GetPerfOutputV2() returned %d bytes of perf data", len(result)) if len(result) < minResultLength { s.Fatal("Perf ou...
{ rPipe.Close() return nil, 0, err }
conditional_block
perf_tool.go
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package debugd import ( "bytes" "context" "fmt" "io" "io/ioutil" "os" "os/exec" "strconv" "sync" "time" "chromiumos/tast/errors" "chromiumos/tast/local/debugd" ...
func testSingleCall(ctx context.Context, s *testing.State, d *debugd.Debugd) { s.Run(ctx, "testSingleCall", func(ctx context.Context, s *testing.State) { tc := s.Param().(testCase) if tc.disableCPUIdle { time.AfterFunc(time.Second, func() { if err := checkCPUIdleDisabled(true); err != nil { s.Error("...
{ const minResultLength = 20 s.Logf("GetPerfOutputV2() returned %d bytes of perf data", len(result)) if len(result) < minResultLength { s.Fatal("Perf output is too small") } if bytes.HasPrefix(result, []byte("<process exited with status: ")) { s.Fatalf("Quipper failed: %s", string(result)) } }
identifier_body
perf_tool.go
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package debugd import ( "bytes" "context" "fmt" "io" "io/ioutil" "os" "os/exec" "strconv" "sync" "time" "chromiumos/tast/errors" "chromiumos/tast/local/debugd" ...
(ctx context.Context, s *testing.State, d *debugd.Debugd) { s.Run(ctx, "testSingleCall", func(ctx context.Context, s *testing.State) { tc := s.Param().(testCase) if tc.disableCPUIdle { time.AfterFunc(time.Second, func() { if err := checkCPUIdleDisabled(true); err != nil { s.Error("CPU Idle state not di...
testSingleCall
identifier_name
perf_tool.go
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package debugd import ( "bytes" "context" "fmt" "io" "io/ioutil" "os" "os/exec" "strconv" "sync" "time" "chromiumos/tast/errors" "chromiumos/tast/local/debugd" ...
func testConsecutiveCalls(ctx context.Context, s *testing.State, d *debugd.Debugd) { s.Run(ctx, "testConsecutiveCalls", func(ctx context.Context, s *testing.State) { tc := s.Param().(testCase) durationSec := 1 for i := 0; i < 3; i++ { output, sessionID, err := getPerfOutput(ctx, s, d, tc, durationSec) if e...
}) }
random_line_split
dockerapi.go
// Package dockerapi is the facade to the Docker remote api. package dockerapi import ( "sync" "context" "fmt" "io" "log" "os" "tlex/mapsi2disk" "golang.org/x/sync/errgroup" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/do...
// CreateNewContainer // 1. creates a new container for the given dockeImageName and // 2. starts it into an active live state: // at the container httpServerContainerPort value, // and at the host httpServerHostPort value. // Returns the new container ID, error. func setNewContainerLive(dockerClient *client.Client, ...
{ err := dockerClient.ContainerStart(context.Background(), containerID, types.ContainerStartOptions{}) return containerID, err }
identifier_body
dockerapi.go
// Package dockerapi is the facade to the Docker remote api. package dockerapi import ( "sync" "context" "fmt" "io" "log" "os" "tlex/mapsi2disk" "golang.org/x/sync/errgroup" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/do...
() { readObj, err := mapsi2disk.ReadContainerPortsFromDisk(mapsi2disk.GobFilename) readBackOwnedContainers := readObj.(map[string]int) if err == nil { defer mapsi2disk.DeleteFile(mapsi2disk.GobFilename) dockerClient := GetDockerClient() for containerID := range readBackOwnedContainers { log.Printf("Dele...
RemoveLiveContainersFromPreviousRun
identifier_name
dockerapi.go
// Package dockerapi is the facade to the Docker remote api. package dockerapi import ( "sync" "context" "fmt" "io" "log" "os" "tlex/mapsi2disk" "golang.org/x/sync/errgroup" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/do...
if err == nil { defer mapsi2disk.DeleteFile(mapsi2disk.GobFilename) dockerClient := GetDockerClient() for containerID := range readBackOwnedContainers { log.Printf("Deleting container: %v from previous launch.\n", containerID) err = dockerClient.ContainerStop(context.Background(), containerID, nil) } ...
readObj, err := mapsi2disk.ReadContainerPortsFromDisk(mapsi2disk.GobFilename) readBackOwnedContainers := readObj.(map[string]int)
random_line_split
dockerapi.go
// Package dockerapi is the facade to the Docker remote api. package dockerapi import ( "sync" "context" "fmt" "io" "log" "os" "tlex/mapsi2disk" "golang.org/x/sync/errgroup" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/do...
fmt.Printf("\n**** Passed RequestedContainers == Live assertion. ****\n\n") } // AssertRequestedContainersAreGone check that no containers exist and that the system cleaned up otherwise it panics. // This is called by tests. func AssertRequestedContainersAreGone() { cli := GetDockerClient() containers, err := g...
{ if container.State == containerRunningStateString { log.Printf("Container %s in %s state.\n", container.ID, container.State) } else { log.Panicf("Found container %s that is not running with state %s, status %s.\n", container.ID, container.State, container.Status) } }
conditional_block
set6.go
package main import ( "bufio" "encoding/hex" "errors" "fmt" "math/big" "os" "strings" "time" "github.com/fatih/color" "github.com/jgblight/matasano/pkg/ciphers" "github.com/jgblight/matasano/pkg/hashes" "github.com/jgblight/matasano/pkg/secrets" "github.com/jgblight/matasano/pkg/utils" ) const ( dataDi...
middle := new(big.Int).Add(lowerBound, upperBound) middle = middle.Div(middle, two) if even { upperBound = middle } else { lowerBound = middle } time.Sleep(5 * time.Millisecond) printInline(upperBound.Bytes()) multiplier = multiplier.Mul(multiplier, two) } fmt.Println() return nil } type Inte...
{ return err }
conditional_block
set6.go
package main import ( "bufio" "encoding/hex" "errors" "fmt" "math/big" "os" "strings" "time" "github.com/fatih/color" "github.com/jgblight/matasano/pkg/ciphers" "github.com/jgblight/matasano/pkg/hashes" "github.com/jgblight/matasano/pkg/secrets" "github.com/jgblight/matasano/pkg/utils" ) const ( dataDi...
func nextInterval(interval *Interval, s, r, n *big.Int) *Interval { rn := new(big.Int).Mul(r, n) a1 := new(big.Int) a1 = ceilDiv(a1.Add(interval.TwoB, rn), s) b1 := new(big.Int) b1 = b1.Div(b1.Add(interval.ThreeBSub1, rn), s) var newInt Interval newInt = *interval if interval.Lower.Cmp(a1) == -1 { newInt...
{ one := utils.GetBigInt(1) r := new(big.Int) r = ceilDiv(r.Mul(utils.GetBigInt(2), r.Sub(r.Mul(interval.Upper, s0), interval.TwoB)), server.N) s := new(big.Int) minS := new(big.Int) maxS := new(big.Int) var err error valid := false for r.Cmp(server.N) == -1 { rn := new(big.Int).Mul(r, server.N) minS = mi...
identifier_body
set6.go
package main import ( "bufio" "encoding/hex" "errors" "fmt" "math/big" "os" "strings" "time" "github.com/fatih/color" "github.com/jgblight/matasano/pkg/ciphers" "github.com/jgblight/matasano/pkg/hashes" "github.com/jgblight/matasano/pkg/secrets" "github.com/jgblight/matasano/pkg/utils" ) const ( dataDi...
} } } return nil, errors.New("Found nothing") } func removePadding(plaintext []byte) []byte { var i int for i = 2; i < len(plaintext); i++ { if plaintext[i] == '\x00' { break } } return plaintext[i+1 : len(plaintext)] } func problemSeven() error { server, err := secrets.NewRSAServer(256) if err !=...
} else { _, s, err = searchRS(s, c, bounds, server) if err != nil { return nil, err
random_line_split
set6.go
package main import ( "bufio" "encoding/hex" "errors" "fmt" "math/big" "os" "strings" "time" "github.com/fatih/color" "github.com/jgblight/matasano/pkg/ciphers" "github.com/jgblight/matasano/pkg/hashes" "github.com/jgblight/matasano/pkg/secrets" "github.com/jgblight/matasano/pkg/utils" ) const ( dataDi...
() error { e, d, n, err := ciphers.RSAKeygen(1024) if err != nil { return err } plaintext := []byte("hi mom") signature, err := ciphers.PKCS15Sign(plaintext, d, n) fmt.Printf("Valid Signature: %s\n", signature) verified := ciphers.PKCS15Verify(plaintext, signature, e, n) fmt.Printf("Verified: %t\n", verified...
problemTwo
identifier_name
OrganizationListDetail.ts
const imgHostname = 'https://cyxbsmobile.redrock.team/static/register/' interface PosterStyle { backgroundImage: string } interface Department { name: string posterStyle: PosterStyle introduction: string } interface Organization { name: string departmentList: Array<Department> } interfa...
name: '学术交流部', posterStyle: { backgroundImage: `url(${imgHostname}yanhui/yanhui-xueshu.jpg)` }, introduction: '以举办特色鲜明的学术讲座和论坛活动为主,拓宽研究生的学术视野,增强同学们的学术研究氛围。同时根据在校研究生的需求,开展切实有效的不同主题交流活动,构建各领域专家与同学们面对面交流的平台。学术交流部,看似高冷却超接地气的部门!' } ] }, huweidui: { ...
introduction: '研究生校园文化生活的缔造者和领跑人。于文,主办迎新晚会等大型活动,丰富研究生的课余生活,协助各分研会举办各类文艺活动,营造活跃向上的氛围。于体,参与组建、管理研究生各类球队,积极参加各类校级比赛,如运动会、“青春杯”篮球、足球赛、公园排球赛、校园马拉松等,宣传体育育人理念,提高研究生的综合素质。' }, {
random_line_split
dominogame.go
package main import ( "fmt" "math/rand" "strconv" ) type dominoGame struct { players []player pieces []dominoPiece grid dominoGrid turnOrder []int } type player struct { playerNumber int ownedPieces []dominoPiece } type dominoPiece struct { top int bot int } type dominoGrid struct { grid [][...
} } //determining which player places the first piece func firstMove(piece dominoPiece, highestDouble, firstTurn, playerNum int) (int, int) { if (piece.top == piece.bot) && (piece.top > highestDouble) { firstTurn = playerNum highestDouble = piece.top } return firstTurn, highestDouble } func remove(s []dominoP...
if firstTurn != 0 { return game, firstTurn }
random_line_split
dominogame.go
package main import ( "fmt" "math/rand" "strconv" ) type dominoGame struct { players []player pieces []dominoPiece grid dominoGrid turnOrder []int } type player struct { playerNumber int ownedPieces []dominoPiece } type dominoPiece struct { top int bot int } type dominoGrid struct { grid [][...
func checkPiece(piece dominoPiece, grid dominoGrid) bool { viable := false for y := 1; y <= len(grid.grid)-2; y++ { for x := 1; x <= len(grid.grid[0])-2; x++ { //check if it could be matched with any domino on the board if grid.grid[y][x] == strconv.Itoa(piece.top) || grid.grid[y][x] == strconv.Itoa(piece.b...
{ var x, y, ori int var end2 string var newGrid dominoGrid //check viability of piece selected if !checkPiece(piece, grid) && !firstTurn { return nil, newGrid } //select which end of piece to place first end := selectPieceEnd(piece) //select square for end to go for { newGrid = grid printGrid(newGrid) ...
identifier_body
dominogame.go
package main import ( "fmt" "math/rand" "strconv" ) type dominoGame struct { players []player pieces []dominoPiece grid dominoGrid turnOrder []int } type player struct { playerNumber int ownedPieces []dominoPiece } type dominoPiece struct { top int bot int } type dominoGrid struct { grid [][...
(gameRaw dominoGame) (dominoGame, int) { var firstTurn, highestDouble int //pieces will be reshuffled if nobody starts with a double for { game := gameRaw //assign domino pieces to players for k, player := range game.players { for i := 1; i <= 7; i++ { r := rand.Intn(len(game.pieces) - 1) player.own...
assignPieces
identifier_name
dominogame.go
package main import ( "fmt" "math/rand" "strconv" ) type dominoGame struct { players []player pieces []dominoPiece grid dominoGrid turnOrder []int } type player struct { playerNumber int ownedPieces []dominoPiece } type dominoPiece struct { top int bot int } type dominoGrid struct { grid [][...
} } return viable } func selectPieceEnd(piece dominoPiece) (end string) { for { fmt.Println("Piece ", piece, " selected. Select end: Top -", piece.top, " Bot -", piece.bot) fmt.Scan(&end) endInt, err := strconv.Atoi(end) if err != nil { fmt.Println("Invalid input. Type in a number.") continue } ...
{ //check if there is room to place if grid.grid[y+1][x] == "X" || grid.grid[y-1][x] == "X" || grid.grid[y][x+1] == "X" || grid.grid[y][x-1] == "X" { viable = true } }
conditional_block
lib.rs
//! An element-tree style XML library //! //! # Examples //! //! ## Reading //! //! ``` //! use treexml::Document; //! //! let doc_raw = r#" //! <?xml version="1.1" encoding="UTF-8"?> //! <table> //! <fruit type="apple">worm</fruit> //! <vegetable /> //! </table> //! "#; //! //! let doc = Document::parse(doc_ra...
use indexmap::IndexMap; use xml::common::XmlVersion as BaseXmlVersion; /// Enumeration of XML versions /// /// This exists solely because `xml-rs`'s `XmlVersion` doesn't implement Debug #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum XmlVersion { /// XML Version 1.0 Version10, /// XML Version 1.1 ...
pub use errors::*; pub use builder::*;
random_line_split
lib.rs
//! An element-tree style XML library //! //! # Examples //! //! ## Reading //! //! ``` //! use treexml::Document; //! //! let doc_raw = r#" //! <?xml version="1.1" encoding="UTF-8"?> //! <table> //! <fruit type="apple">worm</fruit> //! <vegetable /> //! </table> //! "#; //! //! let doc = Document::parse(doc_ra...
(value: XmlVersion) -> BaseXmlVersion { match value { XmlVersion::Version10 => BaseXmlVersion::Version10, XmlVersion::Version11 => BaseXmlVersion::Version11, } } } /// An XML element #[derive(Debug, Clone, PartialEq, Eq)] pub struct Element { /// Tag prefix, used for nam...
from
identifier_name
metamandering_north_carolina.py
import os import random import json import geopandas as gpd import functools import datetime import matplotlib from facefinder import * import time import requests import zipfile import io import matplotlib.pyplot as plt import numpy as np import csv from networkx.readwrite import json_graph import math import seaborn...
(partition): parent = partition.parent if not parent: return 0 return parent["step_num"] + 1 def always_true(proposal): return True def produce_gerrymanders(graph, k, tag, sample_size, chaintype): #Samples k partitions of the graph #stor...
step_num
identifier_name
metamandering_north_carolina.py
import os import random import json import geopandas as gpd import functools import datetime import matplotlib from facefinder import * import time import requests import zipfile import io import matplotlib.pyplot as plt import numpy as np import csv from networkx.readwrite import json_graph import math import seaborn...
if 'EL16G_PR_D' not in g_sierpinsky.nodes[node]: g_sierpinsky.nodes[node]['EL16G_PR_D'] = 0 if 'EL16G_PR_R' not in g_sierpinsky.nodes[node]: g_sierpinsky.nodes[node]['EL16G_PR_R'] = 0 ##Need to add the voting data # Seanna: So it looks like it initialize populati...
g_sierpinsky.nodes[node]['population'] = 0
conditional_block
metamandering_north_carolina.py
import os import random import json import geopandas as gpd import functools import datetime import matplotlib from facefinder import * import time import requests import zipfile import io import matplotlib.pyplot as plt import numpy as np import csv from networkx.readwrite import json_graph import math
import numpy as np import copy from gerrychain.tree import bipartition_tree as bpt from gerrychain import Graph from gerrychain import MarkovChain from gerrychain.constraints import (Validator, single_flip_contiguous, within_percent_of_ideal_population, UpperBound) from gerrychain.p...
import seaborn as sns from functools import partial import networkx as nx
random_line_split
metamandering_north_carolina.py
import os import random import json import geopandas as gpd import functools import datetime import matplotlib from facefinder import * import time import requests import zipfile import io import matplotlib.pyplot as plt import numpy as np import csv from networkx.readwrite import json_graph import math import seaborn...
def produce_sample(graph, k, tag, sample_size = 500, chaintype='tree'): #Samples k partitions of the graph, stores the cut edges and records them graphically #Also stores vote histograms, and returns most extreme partitions. print("producing sample") updaters = {'population': Tally('population'),...
updaters = {'population': Tally('population'), 'cut_edges': cut_edges, 'step_num': step_num, } assignment = {} for x in graph.nodes(): color = 0 for block in target_partition.keys(): if x in target_partition...
identifier_body
component.rs
use crate::code::CodeObject; use crate::signatures::SignatureCollection; use crate::{Engine, Module}; use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeSet, HashMap}; use std::fs; use std::mem; use std::path::Path; use std::ptr::NonNull; use std::sync::Arc; use wasmti...
pub(crate) fn signatures(&self) -> &SignatureCollection { self.inner.code.signatures() } pub(crate) fn text(&self) -> &[u8] { self.inner.code.code_memory().text() } pub(crate) fn lowering_ptr(&self, index: LoweredIndex) -> NonNull<VMFunctionBody> { let info = &self.inner....
{ match self.inner.code.types() { crate::code::Types::Component(types) => types, // The only creator of a `Component` is itself which uses the other // variant, so this shouldn't be possible. crate::code::Types::Module(_) => unreachable!(), } }
identifier_body
component.rs
use crate::code::CodeObject; use crate::signatures::SignatureCollection; use crate::{Engine, Module}; use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeSet, HashMap}; use std::fs; use std::mem; use std::path::Path; use std::ptr::NonNull; use std::sync::Arc; use wasmti...
let loc = &self.inner.info.always_trap[index]; self.func(loc) } pub(crate) fn transcoder_ptr(&self, index: RuntimeTranscoderIndex) -> NonNull<VMFunctionBody> { let info = &self.inner.info.transcoders[index]; self.func(info) } fn func(&self, loc: &FunctionLoc) -> NonNull...
let info = &self.inner.info.lowerings[index]; self.func(info) } pub(crate) fn always_trap_ptr(&self, index: RuntimeAlwaysTrapIndex) -> NonNull<VMFunctionBody> {
random_line_split
component.rs
use crate::code::CodeObject; use crate::signatures::SignatureCollection; use crate::{Engine, Module}; use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeSet, HashMap}; use std::fs; use std::mem; use std::path::Path; use std::ptr::NonNull; use std::sync::Arc; use wasmti...
(&self) -> &[u8] { self.inner.code.code_memory().text() } pub(crate) fn lowering_ptr(&self, index: LoweredIndex) -> NonNull<VMFunctionBody> { let info = &self.inner.info.lowerings[index]; self.func(info) } pub(crate) fn always_trap_ptr(&self, index: RuntimeAlwaysTrapIndex) -> N...
text
identifier_name
images.go
/* Copyright 2020 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, ...
} } return nil }, ); err != nil { return nil, fmt.Errorf("traversing path: %w", err) } } return manifestImages, nil } // normalizeVersion normalizes an container image version by replacing all invalid characters. func (i *Images) normalizeVersion(version string) string { return strings.Replac...
); err != nil { return fmt.Errorf("executing tarball callback: %w", err)
random_line_split
images.go
/* Copyright 2020 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, ...
// GetManifestImages can be used to retrieve the map of built images and // architectures. func (i *Images) GetManifestImages( registry, version, buildPath string, forTarballFn func(path, origTag, newTagWithArch string) error, ) (map[string][]string, error) { manifestImages := make(map[string][]string) releaseIm...
{ logrus.Infof("Validating image manifests in %s", registry) version = i.normalizeVersion(version) manifestImages := ManifestImages arches := SupportedArchitectures if fast { arches = FastArchitectures } for _, image := range manifestImages { imageVersion := fmt.Sprintf("%s/%s:%s", registry, image, versio...
identifier_body
images.go
/* Copyright 2020 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, ...
else if strings.Contains(err.Error(), "request canceled while waiting for connection") { // The error is unfortunately not exported: // https://github.com/golang/go/blob/dc04f3b/src/net/http/client.go#L720 // https://github.com/golang/go/blob/dc04f3b/src/net/http/transport.go#L2518 // ref: https://gith...
{ return true, nil }
conditional_block
images.go
/* Copyright 2020 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, ...
(impl imageImpl) { i.imageImpl = impl } // imageImpl is a client for working with container images. // //counterfeiter:generate . imageImpl type imageImpl interface { Execute(cmd string, args ...string) error ExecuteOutput(cmd string, args ...string) (string, error) RepoTagFromTarball(path string) (string, error) ...
SetImpl
identifier_name
settings.go
// Copyright (c) 2018 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
return strconv.Itoa(int(g)) } // The Is functions do not validate if the plugin type is known // as this is supposed to be done in ConfigProvider. // It's a lot easier if they just return a bool. // IsGo returns true if the plugin type is associated with // github.com/golang/protobuf. func (g GenPluginType) IsGo() ...
{ return s }
conditional_block
settings.go
// Copyright (c) 2018 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
Lint LintConfig // The gen config. Gen GenConfig } // CompileConfig is the compile config. type CompileConfig struct { // The Protobuf version to use from https://github.com/protocolbuffers/protobuf/releases. // Must have a valid protoc zip file asset, so for example 3.5.0 is a valid version // but 3.5.0.1 is no...
random_line_split
settings.go
// Copyright (c) 2018 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
// IsGogo returns true if the plugin type is associated with // github.com/gogo/protobuf. func (g GenPluginType) IsGogo() bool { return _genPluginTypeToIsGogo[g] } // ParseGenPluginType parses the GenPluginType from the given string. // // Input is case-insensitive. func ParseGenPluginType(s string) (GenPluginType,...
{ return _genPluginTypeToIsGo[g] }
identifier_body
settings.go
// Copyright (c) 2018 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
() string { if s, ok := _genPluginTypeToString[g]; ok { return s } return strconv.Itoa(int(g)) } // The Is functions do not validate if the plugin type is known // as this is supposed to be done in ConfigProvider. // It's a lot easier if they just return a bool. // IsGo returns true if the plugin type is associa...
String
identifier_name
lib.rs
//! # L2 //!# What is L2? //! //!> L2 is named after the L2 or Euclidean distance, a popular distance function in deep learning //! //!L2 is a Pytorch-style Tensor+Autograd library written in the Rust programming language. It contains a multidimensional array class, `Tensor`, with support for strided arrays, numpy-styl...
() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = sum(&a, 0).unwrap(); assert!((c.data == vec![5.0]) && (c.shape == vec![1])) } #[test] fn test_mean() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = mean(&a, 0).unwrap(); asser...
test_sum
identifier_name
lib.rs
//! # L2 //!# What is L2? //! //!> L2 is named after the L2 or Euclidean distance, a popular distance function in deep learning //! //!L2 is a Pytorch-style Tensor+Autograd library written in the Rust programming language. It contains a multidimensional array class, `Tensor`, with support for strided arrays, numpy-styl...
pub fn matmul<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.matmul(rhs) } pub fn concat<'a>(lhs: &'a Tensor, rhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.concat(&rhs, dim) } #[cfg(test)] mod tests { use super::tensor::*; use super::*; #[t...
}
random_line_split
lib.rs
//! # L2 //!# What is L2? //! //!> L2 is named after the L2 or Euclidean distance, a popular distance function in deep learning //! //!L2 is a Pytorch-style Tensor+Autograd library written in the Rust programming language. It contains a multidimensional array class, `Tensor`, with support for strided arrays, numpy-styl...
#[test] fn test_mean() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = mean(&a, 0).unwrap(); assert!((c.data == vec![2.5]) && (c.shape == vec![1])) } #[test] fn test_max() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = max(&a,...
{ let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = sum(&a, 0).unwrap(); assert!((c.data == vec![5.0]) && (c.shape == vec![1])) }
identifier_body
lib.rs
use ndarray::{concatenate, s, Array1, Array2, Axis}; #[macro_use] extern crate lazy_static; peg::parser!(grammar parse_tile() for str { pub rule parse_tile_id() -> usize = "Tile " id:$(['0'..='9']+) ":" { id.parse().unwrap() } pub rule parse_border() -> (u32, u32) = line:$(['#' | '.']+) { ...
<'a>( &'a self, row: usize, col: usize, prev_images: &[(&'a Tile, usize)], ) -> Vec<(&'a Tile, usize)> { let mut result: Vec<(&Tile, usize)> = vec![]; result.extend_from_slice(prev_images); for tile in self.tiles.iter() { if result.iter().any(|(t, ...
fits
identifier_name
lib.rs
use ndarray::{concatenate, s, Array1, Array2, Axis}; #[macro_use] extern crate lazy_static; peg::parser!(grammar parse_tile() for str { pub rule parse_tile_id() -> usize = "Tile " id:$(['0'..='9']+) ":" { id.parse().unwrap() } pub rule parse_border() -> (u32, u32) = line:$(['#' | '.']+) { ...
} }
let testcase = read_input("../testcase1.txt"); let test_image = BigImage::new(testcase); let result = vec![]; let result = test_image.fits(0, 0, &result); assert_eq!(part2_solution(&test_image, &result), 273);
random_line_split
lib.rs
use ndarray::{concatenate, s, Array1, Array2, Axis}; #[macro_use] extern crate lazy_static; peg::parser!(grammar parse_tile() for str { pub rule parse_tile_id() -> usize = "Tile " id:$(['0'..='9']+) ":" { id.parse().unwrap() } pub rule parse_border() -> (u32, u32) = line:$(['#' | '.']+) { ...
pub fn get_sub_image(&self, idx: usize) -> Array2<u8> { match idx { 0 => self.sub_image.original(), 1 => self.sub_image.rot90_clockwise(), 2 => self.sub_image.rot180_clockwise(), 3 => self.sub_image.rot270_clockwise(), 4 => self.sub_image.flip_ve...
{ let lines = data .split('\n') .map(|s| s.trim_end().to_string()) .collect::<Vec<_>>(); let shape = lines[1].len() - 2; let tile_id = parse_tile::parse_tile_id(&lines[0]).unwrap(); let (top, top_rev) = parse_tile::parse_border(&lines[1]).unwrap(); ...
identifier_body
tasty_trade_importer.py
import os import re import copy import math from collections import OrderedDict import arrow import csv # import a tasty_trade csv, and emit 1 row for every sell with the # transaction_type(money_transfer,trade),account,date, symbol, quantity, *stock (0/1), *option (0/1), credit/debit (including fees) # only works fo...
trades[symbol]['commons']['amount_sold'] += math.fabs(netAmount) # reduce total holdings trades[symbol]['commons']['quantity'] -= int(row['Quantity']) print('calulated all {} trades for {}'.format(len(trades.items()), day)) return trades def is_commons_swing_trade(symbol, trade_type): return tra...
random_line_split
tasty_trade_importer.py
import os import re import copy import math from collections import OrderedDict import arrow import csv # import a tasty_trade csv, and emit 1 row for every sell with the # transaction_type(money_transfer,trade),account,date, symbol, quantity, *stock (0/1), *option (0/1), credit/debit (including fees) # only works fo...
if __name__ == "__main__": create_formatted_csv()
print('...creating csv') with open('formatted_tt.csv', 'w', newline='') as out_csvfile: fieldnames = ['transaction_type','account','date','symbol','quantity','stock','option','p_l', '%'] writer = csv.DictWriter(out_csvfile, fieldnames=fieldnames) writer.writeheader() for formatted in formatted_rows: write...
identifier_body
tasty_trade_importer.py
import os import re import copy import math from collections import OrderedDict import arrow import csv # import a tasty_trade csv, and emit 1 row for every sell with the # transaction_type(money_transfer,trade),account,date, symbol, quantity, *stock (0/1), *option (0/1), credit/debit (including fees) # only works fo...
print('calulated all {} trades for {}'.format(len(trades.items()), day)) return trades def is_commons_swing_trade(symbol, trade_type): return trade_type['commons']['quantity'] != 0 def is_options_swing_trade(symbol, trade_type): return trade_type['options']['quantity'] != 0 def get_swing_trades(swing_trades, ...
netAmount = amountWithFees(row) # save stock trades if symbol not in trades: trades[symbol] = create_trade_dict() trades[symbol]['commons']['net_amount'] += netAmount # update buy and sell totals if isPurchase(row): trades[symbol]['commons']['amount_bought'] += math.fabs(netA...
conditional_block
tasty_trade_importer.py
import os import re import copy import math from collections import OrderedDict import arrow import csv # import a tasty_trade csv, and emit 1 row for every sell with the # transaction_type(money_transfer,trade),account,date, symbol, quantity, *stock (0/1), *option (0/1), credit/debit (including fees) # only works fo...
(day, money_movement): formatted_rows = [] for event in money_movement: formatted_row = { 'transaction_type': 'money_transfer', 'account': None, 'date': day, 'symbol': None, 'quantity': None, # doesn't matter 'stock': None, 'option': None, 'p_l': str(round(event, 2)), '%': 0 } formatt...
getFormattedRowsForMoneyMoneyMovement
identifier_name
redis_performance_monitor.js
/** * This script was developed by Guberni and is part of Tellki's Monitoring Solution * * March, 2015 * * Version 1.0 * * DESCRIPTION: Monitor Redis performance * * SYNTAX: node redis_performance_monitor.js <METRIC_STATE> <HOST> <PORT> <PASS_WORD> * * EXAMPLE: node redis_performance_monitor.js "1,1,1,1,1...
try { fs.writeFileSync(filePath, json); } catch(e) { var ex = new WriteOnTmpFileError(e.message); ex.message = e.message; errorHandler(ex); } } // ############################################################################ // ERROR HANDLER /** * Used to handle errors of async functions * Receive: E...
{ try { fs.mkdirSync( __dirname + tempDir); } catch(e) { var ex = new CreateTmpDirError(e.message); ex.message = e.message; errorHandler(ex); } }
conditional_block
redis_performance_monitor.js
/** * This script was developed by Guberni and is part of Tellki's Monitoring Solution * * March, 2015 * * Version 1.0 * * DESCRIPTION: Monitor Redis performance * * SYNTAX: node redis_performance_monitor.js <METRIC_STATE> <HOST> <PORT> <PASS_WORD> * * EXAMPLE: node redis_performance_monitor.js "1,1,1,1,1...
this.name = "InvalidAuthenticationError"; this.message = "Invalid authentication."; this.code = 2; } InvalidAuthenticationError.prototype = Object.create(Error.prototype); InvalidAuthenticationError.prototype.constructor = InvalidAuthenticationError; function UnknownHostError() { this.name = "UnknownHostE...
random_line_split
redis_performance_monitor.js
/** * This script was developed by Guberni and is part of Tellki's Monitoring Solution * * March, 2015 * * Version 1.0 * * DESCRIPTION: Monitor Redis performance * * SYNTAX: node redis_performance_monitor.js <METRIC_STATE> <HOST> <PORT> <PASS_WORD> * * EXAMPLE: node redis_performance_monitor.js "1,1,1,1,1...
// ############################################################################ // EXCEPTIONS /** * Exceptions used in this script. */ function InvalidParametersNumberError() { this.name = "InvalidParametersNumberError"; this.message = "Wrong number of parameters."; this.code = 3; } InvalidParametersNumbe...
{ if(err instanceof InvalidAuthenticationError) { console.log(err.message); process.exit(err.code); } else if(err instanceof UnknownHostError) { console.log(err.message); process.exit(err.code); } else if(err instanceof MetricNotFoundError) { console.log(err.message); process.exit(err.code); } els...
identifier_body
redis_performance_monitor.js
/** * This script was developed by Guberni and is part of Tellki's Monitoring Solution * * March, 2015 * * Version 1.0 * * DESCRIPTION: Monitor Redis performance * * SYNTAX: node redis_performance_monitor.js <METRIC_STATE> <HOST> <PORT> <PASS_WORD> * * EXAMPLE: node redis_performance_monitor.js "1,1,1,1,1...
(metrics) { for (var i in metrics) { var out = ""; var metric = metrics[i]; out += metric.id; out += "|"; out += metric.value; out += "|"; console.log(out); } } // ############################################################################ // RATE PROCESSING /** * Process performance results...
output
identifier_name
script.js
//global var to store the state name var state_name_array=[]; //change to 1 if user search by specific data because if user search by specific date it dont has active element var no_active=0; const STATE_CODES={ AN: "Andaman and Nicobar Islands", AP: "Andhra Pradesh", AR: "Arunachal Pradesh", AS: "Ass...
(date) { //setting no active to 1 no_active=1; $(".state-container").empty(); document.querySelector(".state-container").style.display="flex"; document.querySelector(".error_container").style.display="none"; let link="https://api.covid19india.org/v3/data-"+date+".json"; $.getJSON(link,function(datas){ for(dat...
getSpecificData
identifier_name
script.js
//global var to store the state name var state_name_array=[]; //change to 1 if user search by specific data because if user search by specific date it dont has active element var no_active=0; const STATE_CODES={ AN: "Andaman and Nicobar Islands", AP: "Andhra Pradesh", AR: "Arunachal Pradesh", AS: "Ass...
let date=data_array[0]; let active=data_array[1]; let confirmed=data_array[2]; let recovered=data_array[3]; let deaths=data_array[4]; let prev_confirm=prev_data_array[0] let prev_recoverd=prev_data_array[1] let prev_deaths=prev_data_array[2] if(!isold) { //calculating the d...
//retrive the valu from array
random_line_split
script.js
//global var to store the state name var state_name_array=[]; //change to 1 if user search by specific data because if user search by specific date it dont has active element var no_active=0; const STATE_CODES={ AN: "Andaman and Nicobar Islands", AP: "Andhra Pradesh", AR: "Arunachal Pradesh", AS: "Ass...
function handleError() { document.querySelector(".state-container").style.display="none"; document.querySelector(".error_container").style.display="flex"; document.querySelector(".loading__container").style.display="none"; } search(); //added this at api closed on feb 6 2:47 if(new Date()<new Date(API_CLOSED_DATE)...
{ //setting no active to 1 no_active=1; $(".state-container").empty(); document.querySelector(".state-container").style.display="flex"; document.querySelector(".error_container").style.display="none"; let link="https://api.covid19india.org/v3/data-"+date+".json"; $.getJSON(link,function(datas){ for(data in da...
identifier_body
collect-raman.py
#!/usr/bin/env python # * read dark with a certain int time # * turn laser on at a certain power level, does not need to be calibrated # * read signal with the same int time # * turn laser off # # The script then repeats this over and over. import sys import re from time import sleep from datetime import datetime im...
(self, db): db = round(db, 1) msb = int(db) lsb = int((db - int(db)) * 10) raw = (msb << 8) | lsb self.debug("setting gainDB 0x%04x (FunkyFloat)" % raw) self.send_cmd(0xb7, raw) def set_modulation_enable(self, flag): self.debug(f"setting laserModulationEnable...
set_gain_db
identifier_name
collect-raman.py
#!/usr/bin/env python # * read dark with a certain int time # * turn laser on at a certain power level, does not need to be calibrated # * read signal with the same int time # * turn laser off # # The script then repeats this over and over. import sys import re from time import sleep from datetime import datetime im...
# take measurements spectra = [] try: for i in range(self.args.count): # take dark-corrected measurement spectrum = self.get_averaged_spectrum() if self.dark is not None: spectrum -= dark spectra.ap...
print("*** not firing laser because --fire-laser not specified ***")
conditional_block
collect-raman.py
#!/usr/bin/env python # * read dark with a certain int time # * turn laser on at a certain power level, does not need to be calibrated # * read signal with the same int time # * turn laser off # # The script then repeats this over and over. import sys import re from time import sleep from datetime import datetime im...
def generate_wavelengths(self): self.wavelengths = [] self.wavenumbers = [] for i in range(self.pixels): wavelength = self.wavecal_C0 \ + self.wavecal_C1 * i \ + self.wavecal_C2 * i * i \ + self.wavecal_C3 * i ...
self.min_laser_power_mW = self.unpack((3, 32, 4), "f")
random_line_split
collect-raman.py
#!/usr/bin/env python # * read dark with a certain int time # * turn laser on at a certain power level, does not need to be calibrated # * read signal with the same int time # * turn laser off # # The script then repeats this over and over. import sys import re from time import sleep from datetime import datetime im...
def set_raman_mode(self, flag): self.debug(f"setting ramanMode {flag}") self.send_cmd(0xff, 0x16, 1 if flag else 0) def set_raman_delay_ms(self, ms): if ms < 0 or ms > 0xffff: print("ERROR: ramanDelay requires uint16") return self.debug(f"setting raman...
self.debug(f"setting laserModulationEnable {flag}") self.send_cmd(0xbd, 1 if flag else 0)
identifier_body
MT3D_PP_viz.py
import os import flopy import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt import flopy from HydroModelBuilder.Utilities.model_assessment import metric_me, metric_pbias, metric_rmse, plot_obs_vs_sim def compareAllObs(self): """TODO: Docs""" concobj = self.import_concs() tim...
# End compareAllObs()
conc = None sft_conc = None obs_group = self.mf_model.model_data.observations.obs_group obs_sim_zone_all = [] # Write observation to file for obs_set in obs_group: obs_sim_zone_all = [] obs_type = obs_group[obs_set]['obs_type'] # Import the required model outputs for proc...
identifier_body
MT3D_PP_viz.py
import os import flopy import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt import flopy from HydroModelBuilder.Utilities.model_assessment import metric_me, metric_pbias, metric_rmse, plot_obs_vs_sim def
(self): """TODO: Docs""" concobj = self.import_concs() times = concobj.get_times() scatterx = [] scattery = [] obs_sim_zone_all = [] # The definition of obs_sim_zone looks like: for i in range(self.mf_model.model_data.model_time.t['steps']): conc = concobj.get_data(totim=times...
compareAllObs
identifier_name
MT3D_PP_viz.py
import os import flopy import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt import flopy from HydroModelBuilder.Utilities.model_assessment import metric_me, metric_pbias, metric_rmse, plot_obs_vs_sim def compareAllObs(self): """TODO: Docs""" concobj = self.import_concs() tim...
ax.set_title('Sim vs Obs (%d points)' % (len(scatterx))) comp_zone_plots = {} colours = ['r', 'orangered', 'y', 'green', 'teal', 'blue', 'fuchsia'] for i in xrange(1, 8): scatterx2 = [loc[0] for loc in obs_sim_zone_all if loc[2] == float(i)] scattery2 = [loc[1] for loc in obs_sim_zone_a...
ax = fig.add_subplot(1, 3, 2)
random_line_split
MT3D_PP_viz.py
import os import flopy import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt import flopy from HydroModelBuilder.Utilities.model_assessment import metric_me, metric_pbias, metric_rmse, plot_obs_vs_sim def compareAllObs(self): """TODO: Docs""" concobj = self.import_concs() tim...
# End for # End for zone = np.array(zone) rgba_colors = np.zeros((len(x), 4)) # for red the first column needs to be one for i in range(1, 8): rgba_colors[:, 0][zone == i] = rgb_ref[i - 1][0] rgba_colors[:, 1][zone == i] = rgb_ref[i - 1][1] rgba_colors[:, 2][zone ==...
if col == nam: rgb_ref += [rgb_all[index]] # End if
conditional_block
linebreak.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (ToDO) INFTY MULT accum breakwords linebreak linebreaking linebreaks linelen maxlength minlength nchars ostream...
<'a>(paths: &[LineBreak<'a>], active: &[usize]) -> Vec<(&'a WordInfo<'a>, bool)> { let mut breakwords = vec![]; // of the active paths, we select the one with the fewest demerits let mut best_idx = match active.iter().min_by_key(|&&a| paths[a].demerits) { None => crash!( 1, "...
build_best_path
identifier_name
linebreak.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (ToDO) INFTY MULT accum breakwords linebreak linebreaking linebreaks linelen maxlength minlength nchars ostream...
} // break_simple implements a "greedy" breaking algorithm: print words until // maxlength would be exceeded, then print a linebreak and indent and continue. fn break_simple<'a, T: Iterator<Item = &'a WordInfo<'a>>>( mut iter: T, args: &mut BreakArgs<'a>, ) -> std::io::Result<()> { iter.try_fold((args.ini...
{ break_knuth_plass(p_words_words, &mut break_args) }
conditional_block
linebreak.rs
// This file is part of the uutils coreutils package. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // spell-checker:ignore (ToDO) INFTY MULT accum breakwords linebreak linebreaking linebreaks linelen maxlength minlength nchars ostream...
1 } } else { 0 } } // If we're on a fresh line, slen=0 and we slice off leading whitespace. // Otherwise, compute slen and leave whitespace alone. fn slice_if_fresh( fresh: bool, word: &str, start: usize, uniform: bool, newline: bool, sstart: bool, punct:...
if uniform || newline { if start || (newline && punct) { 2 } else {
random_line_split
Helper.js
/* Also Jlow wants to implement a way to change the workout scorer and generator both if user chooses his own custom rest time Commitment per week - if it changes halfway through --> skip workout --> if workout skipped or if current date doesn't match the date the next workout was supposed to happen calculated from dat...
const testObj = { permSetCount: "9", permDistance: "300", timings: ["63.75", "63.75", "63.75", "63.75", "63.75", "63.75", "63.75", "63.75", "63.75"], //todo for now code below assumes these set times are in seconds permPaceTime: "21250", //in ms }; const myResults = { difficultyMultiplier: 69, personalis...
{ try { const raw = await fetch(url); return await raw.json(); } catch (error) { throw error; } }
identifier_body
Helper.js
/* Also Jlow wants to implement a way to change the workout scorer and generator both if user chooses his own custom rest time Commitment per week - if it changes halfway through --> skip workout --> if workout skipped or if current date doesn't match the date the next workout was supposed to happen calculated from dat...
(questionnaireData, previousFitness) { const {duration, workoutFrequency} = questionnaireData //todo fix currentFitness return { currentTime: convertToSeconds(questionnaireData.latest), targetTime: convertToSeconds(questionnaireData.target), duration, workoutFrequency, currentFitness: previous...
getUserInfo
identifier_name
Helper.js
/* Also Jlow wants to implement a way to change the workout scorer and generator both if user chooses his own custom rest time Commitment per week - if it changes halfway through --> skip workout --> if workout skipped or if current date doesn't match the date the next workout was supposed to happen calculated from dat...
} if (!diffs.stDiff) { diffs.stDiff = diffs.vDiff + intermediateFunc(deltas[3], vVelocity, stVelocity); } } if (diffs.stDiff && !diffs.vDiff) { diffs.vDiff = diffs.stDiff - intermediateFunc(deltas[3], vVelocity, stVelocity); } } return diffs; } export const getSpeedDiffi...
} if (diffs.vDiff && !(diffs.ltDiff && diffs.stDiff)) { if (!diffs.ltDiff) { diffs.ltDiff = diffs.vDiff - intermediateFunc(deltas[2], ltVelocity, vVelocity);
random_line_split
knapsack.py
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np np.random.seed(1335) # for reproducibility np.set_printoptions(precision=5, suppress=True, linewidth=150) import os import pandas as pd import backtest as twp from matplotlib import pyplot as plt from sklearn import metrics, preprocessin...
new_state, time_step, signal, terminal_state = take_action(state, xdata, action, signal, time_step) # Observe reward eval_reward = get_reward(new_state, time_step, action, price_data, signal, terminal_state, eval=True, epoch=epoch) state = new_state ...
action = (np.argmax(qval)) # Take action, observe new state S'
random_line_split
knapsack.py
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np np.random.seed(1335) # for reproducibility np.set_printoptions(precision=5, suppress=True, linewidth=150) import os import pandas as pd import backtest as twp from matplotlib import pyplot as plt from sklearn import metrics, preprocessin...
# Take Action def take_action(state, xdata, action, signal, time_step): # this should generate a list of trade signals that at evaluation time are fed to the backtester # the backtester should get a list of trade signals and a list of price data for the assett # make necessary adjustments to state and t...
filepath = 'util/stock_dfs/' all = [] scaler = preprocessing.StandardScaler() for f in os.listdir(filepath): datapath = os.path.join(filepath, f) if datapath.endswith('.csv'): # print(datapath) Res = init_state(datapath, test=test) all.append(Res) all ...
identifier_body
knapsack.py
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np np.random.seed(1335) # for reproducibility np.set_printoptions(precision=5, suppress=True, linewidth=150) import os import pandas as pd import backtest as twp from matplotlib import pyplot as plt from sklearn import metrics, preprocessin...
(file, test=None): scaler = preprocessing.MinMaxScaler() d = pd.read_csv(file).set_index('Date') d.fillna(0, inplace=True) ticker = get_ticker(file) d['ticker'] = ticker d.rename(columns={'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Adj Close': 'adj_close', ...
read_file
identifier_name
knapsack.py
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np np.random.seed(1335) # for reproducibility np.set_printoptions(precision=5, suppress=True, linewidth=150) import os import pandas as pd import backtest as twp from matplotlib import pyplot as plt from sklearn import metrics, preprocessin...
else: return x_train, ticker # Initialize first state, all items are placed deterministically def init_state(file, test): d, ticker = read_file(file, test=test) xdata = pd.DataFrame() scaler = preprocessing.StandardScaler() xdata['adj_close'] = d['adj_close'] # .values xdata['diff'] ...
return x_test, ticker
conditional_block
DAC16bit.py
from qcodes.instrument.base import Instrument import types import logging import numpy as np import serial import visa import traceback import threading import time from qcodes import VisaInstrument, validators as vals from qcodes.instrument.parameter import ManualParameter from qcodes.utils.validators import Bool, N...
self.Halfrange = Halfrange self.communication_bytes = 3 if numdacs % 4 == 0 and numdacs > 0: self._numdacs = int(numdacs) else: logging.error('Number of dacs needs to be multiple of 4') # initialize pol_num, the voltage offset due to the polarity self.pol_num = np.zeros(self._numdacs) for i in rang...
self._interface = interface self.Fullrange = Fullrange
random_line_split
DAC16bit.py
from qcodes.instrument.base import Instrument import types import logging import numpy as np import serial import visa import traceback import threading import time from qcodes import VisaInstrument, validators as vals from qcodes.instrument.parameter import ManualParameter from qcodes.utils.validators import Bool, N...
(self, channel): ''' Returns the value of the specified dac Input: channel (int) : 1 based index of the dac Output: voltage (float) : dacvalue in mV ''' logging.info('Reading dac%s', channel) mvoltages = self._get_dacs() logging.info(mvoltages) #return mvoltages[channel - 1] return mvoltages...
do_get_dac
identifier_name
DAC16bit.py
from qcodes.instrument.base import Instrument import types import logging import numpy as np import serial import visa import traceback import threading import time from qcodes import VisaInstrument, validators as vals from qcodes.instrument.parameter import ManualParameter from qcodes.utils.validators import Bool, N...
def do_set_trigger(self): ''' Sets the trigger; trigger is 1ms and around 4.2V Input: none Output: reply (string) : errormessage ''' logging.debug('Trigger out') message = "%c%c%c%c" % (4, 0, 2, 6) reply = self._send_and_read(message.encode()) return reply def get_dacs(self): mvoltages =...
if channel>2: print('Error: Only channels 1-2 have ramping.') else: logging.info('Setting dac%s to %.04f mV', channel, mvoltage) mvoltage = self._mvoltage_to_bytes(mvoltage) mvoltage_bytes = [0,0] mvoltage_bytes = [mvoltage >> i & 0xff for i in (8,0)] channel = (int(channel)-1) | 0b10100000 #110 is...
identifier_body
DAC16bit.py
from qcodes.instrument.base import Instrument import types import logging import numpy as np import serial import visa import traceback import threading import time from qcodes import VisaInstrument, validators as vals from qcodes.instrument.parameter import ManualParameter from qcodes.utils.validators import Bool, N...
else: return 'Invalid polarity in memory' def get_numdacs(self): ''' Get the number of DACS. ''' return self._numdacs def _gen_ch_set_func(self, fun, ch): def set_func(val): return fun(val, ch) return set_func def _gen_ch_get_func(self, fun, ch): def get_func(): return fun(ch) return ...
return 'POS'
conditional_block
gm.go
package gm import ( "fmt" "github.com/lightpaw/logrus" "github.com/lightpaw/male7/config" "github.com/lightpaw/male7/config/kv" "github.com/lightpaw/male7/config/regdata" "github.com/lightpaw/male7/entity" "github.com/lightpaw/male7/entity/npcid" "github.com/lightpaw/male7/gen/iface" "github.com/lightpaw/male...
ender) DisconnectAndWait(err msg.ErrMsg) {} func (m *fake_sender) IsClosed() bool { return false } //func (module *GmModule) processGoodsCmd(args []string, hc iface.HeroController) bool { // // module.goodsCmd("", hc) // // return true //} // //func (module *GmModule) goodsCmd(args string, hc iface.H...
_s
identifier_body
gm.go
package gm import ( "fmt" "github.com/lightpaw/logrus" "github.com/lightpaw/male7/config" "github.com/lightpaw/male7/config/kv" "github.com/lightpaw/male7/config/regdata" "github.com/lightpaw/male7/entity" "github.com/lightpaw/male7/entity/npcid" "github.com/lightpaw/male7/gen/iface" "github.com/lightpaw/male...
if m.config.IsDebug { if m.config.IsDebugYuanbao { m.groups = []*gm_group{ { tab: "常用", handler: []*gm_handler{ newCmdIntHandler("加元宝(负数表示减)_10", "加元宝(负数表示减)", "100000", func(amount int64, hc iface.HeroController) { hc.FuncWithSend(func(hero *entity.Hero, result herolock.LockResult) { ...
seasonService: seasonService, buffService: buffService, country: country, gameExporter: gameExporter, }
random_line_split
gm.go
package gm import ( "fmt" "github.com/lightpaw/logrus" "github.com/lightpaw/male7/config" "github.com/lightpaw/male7/config/kv" "github.com/lightpaw/male7/config/regdata" "github.com/lightpaw/male7/entity" "github.com/lightpaw/male7/entity/npcid" "github.com/lightpaw/male7/gen/iface" "github.com/lightpaw/male...
*GmModule) ProcessInvaseTargetIdMsg(proto *gm.C2SInvaseTargetIdProto, hc iface.HeroController) { var heroBaseX, heroBaseY int hc.Func(func(hero *entity.Hero, err error) (heroChanged bool) { heroBaseX, heroBaseY = hero.BaseX(), hero.BaseY() return false }) mapData := m.realmService.GetBigMap().GetMapData() ux...
" + proto.Cmd)) } //gogen:iface func (m
conditional_block
gm.go
package gm import ( "fmt" "github.com/lightpaw/logrus" "github.com/lightpaw/male7/config" "github.com/lightpaw/male7/config/kv" "github.com/lightpaw/male7/config/regdata" "github.com/lightpaw/male7/entity" "github.com/lightpaw/male7/entity/npcid" "github.com/lightpaw/male7/gen/iface" "github.com/lightpaw/male...
d(args []string, hc iface.HeroController) bool { // // module.goodsCmd("", hc) // // return true //} // //func (module *GmModule) goodsCmd(args string, hc iface.HeroController) { // for _, data := range module.datas.GoodsData().Array { // newCount := hero.Depot().AddGoods(data.Id, 100) // result.Add(depot.NewS2cUpdat...
e) processGoodsCm
identifier_name
prune_head_with_taylor.py
"Pruning attention heads with taylor expansion methods" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import logging import argparse import random import json from tqdm import tqdm, trange import numpy as np import torch from torch.u...
logger.info("device: {} n_gpu: {}, distributed training: {}".format( device, n_gpu, bool(args.local_rank != -1))) random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if n_gpu > 0: torch.cuda.manual_seed_all(args.seed) os.makedirs(args.output_dir, exis...
torch.cuda.set_device(args.local_rank) device = torch.device("cuda", args.local_rank) n_gpu = 1 # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.distributed.init_process_group(backend='nccl')
conditional_block
prune_head_with_taylor.py
"Pruning attention heads with taylor expansion methods" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import logging import argparse import random import json from tqdm import tqdm, trange import numpy as np import torch from torch.u...
def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, sin...
"""Loads a data file into a list of `InputBatch`s.""" if label_list: label_map = {label: i for i, label in enumerate(label_list)} else: label_map = None features = [] tokenslist = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a...
identifier_body
prune_head_with_taylor.py
"Pruning attention heads with taylor expansion methods" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import logging import argparse import random import json from tqdm import tqdm, trange import numpy as np import torch from torch.u...
(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is ver...
_truncate_seq_pair
identifier_name
prune_head_with_taylor.py
"Pruning attention heads with taylor expansion methods" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import logging import argparse import random import json from tqdm import tqdm, trange import numpy as np import torch from torch.u...
"rte": RteProcessor, "sst-2": SstProcessor, "qqp": QqpProcessor, "qnli": QnliProcessor, "wnli": WnliProcessor, "sts-b": StsProcessor, "scitail": ScitailProcessor, } num_labels_task = { "cola": 2, "mnli": 3, "mrpc": 2, "rte": 2, "sst-2": 2, "qqp": 2, "qnli": 2, ...
processors = { "cola": ColaProcessor, "mnli": MnliProcessor, "mrpc": MrpcProcessor,
random_line_split
family.go
// Copyright (c) 2019-2021 Leonid Kneller. All rights reserved. // Licensed under the MIT license. // See the LICENSE file for full license information. package randomnames // family -- 1000 most frequent family names from the 2010 US Census. var family [1000]string = [1000]string{ "Smith", "Johnson", "Williams", ...
"Wu", "Hines", "Mullins", "Castaneda", "Malone", "Cannon", "Tate", "Mack", "Sherman", "Hubbard", "Hodges", "Zhang", "Guerra", "Wolf", "Valencia", "Saunders", "Franco", "Rowe", "Gallagher", "Farmer", "Hammond", "Hampton", "Townsend", "Ingram", "Wise", "Gallegos", "Clarke", "Barton", "Schroed...
"Todd",
random_line_split