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 |
|---|---|---|---|---|
astutils.py | """
Various bits of reusable code related to L{ast.AST} node processing.
"""
import inspect
import platform
import sys
from numbers import Number
from typing import Iterator, Optional, List, Iterable, Sequence, TYPE_CHECKING, Tuple, Union
from inspect import BoundArguments, Signature
import ast
from pydoctor import v... |
return lineno
def extract_docstring(node: ast.Str) -> Tuple[int, str]:
"""
Extract docstring information from an ast node that represents the docstring.
@returns:
- The line number of the first non-blank line of the docsring. See L{extract_docstring_linenum}.
- The docstring to ... | break | conditional_block |
astutils.py | """
Various bits of reusable code related to L{ast.AST} node processing.
"""
import inspect
import platform
import sys
from numbers import Number
from typing import Iterator, Optional, List, Iterable, Sequence, TYPE_CHECKING, Tuple, Union
from inspect import BoundArguments, Signature
import ast
from pydoctor import v... | (sig: Signature, call: ast.Call) -> BoundArguments:
"""
Binds the arguments of a function call to that function's signature.
@raise TypeError: If the arguments do not match the signature.
"""
kwargs = {
kw.arg: kw.value
for kw in call.keywords
# When keywords are passed using... | bind_args | identifier_name |
astutils.py | """
Various bits of reusable code related to L{ast.AST} node processing.
"""
import inspect
import platform
import sys
from numbers import Number
from typing import Iterator, Optional, List, Iterable, Sequence, TYPE_CHECKING, Tuple, Union
from inspect import BoundArguments, Signature
import ast
from pydoctor import v... | module = ctx.module
assert module is not None
module.report(f'syntax error in {section}: {ex}', lineno_offset=node.lineno, section=section)
return node
else:
assert isinstance(expr, ast.expr), expr
return expr
class _AnnotationStringParser(ast.NodeTransformer):
"... | """
try:
expr = _AnnotationStringParser().visit(node)
except SyntaxError as ex: | random_line_split |
astutils.py | """
Various bits of reusable code related to L{ast.AST} node processing.
"""
import inspect
import platform
import sys
from numbers import Number
from typing import Iterator, Optional, List, Iterable, Sequence, TYPE_CHECKING, Tuple, Union
from inspect import BoundArguments, Signature
import ast
from pydoctor import v... |
# For Python < 3.8:
def visit_Str(self, node: ast.Str) -> ast.expr:
return ast.copy_location(self._parse_string(node.s), node)
TYPING_ALIAS = (
"typing.Hashable",
"typing.Awaitable",
"typing.Coroutine",
"typing.AsyncIterable",
"typing.AsyncIterator",
"... | value = node.value
if isinstance(value, str):
return ast.copy_location(self._parse_string(value), node)
else:
const = self.generic_visit(node)
assert isinstance(const, ast.Constant), const
return const | identifier_body |
lid_shutdown.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::error::PowerManagerError;
use crate::message::{Message, MessageReturn};
use crate::node::Node;
use crate::shutdown_request::ShutdownRequest;
use ... | (&self) -> String {
"LidShutdown".to_string()
}
async fn handle_message(&self, _msg: &Message) -> Result<MessageReturn, PowerManagerError> {
Err(PowerManagerError::Unsupported)
}
}
struct InspectData {
lid_reports: RefCell<BoundedListNode>,
read_errors: inspect::UintProperty,
l... | name | identifier_name |
lid_shutdown.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::error::PowerManagerError;
use crate::message::{Message, MessageReturn};
use crate::node::Node;
use crate::shutdown_request::ShutdownRequest;
use ... | /// Reads the report from the lid sensor and sends shutdown signal if lid is closed.
async fn check_report(&self) -> Result<(), Error> {
let (status, report, _time) = self.proxy.read_report().await?;
let status = zx::Status::from_raw(status);
if status != zx::Status::OK {
ret... | },
};
}
| random_line_split |
lid_shutdown.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::error::PowerManagerError;
use crate::message::{Message, MessageReturn};
use crate::node::Node;
use crate::shutdown_request::ShutdownRequest;
use ... |
/// Tests that when the node receives a signal on its |report_event|, it checks for a lid
/// report and, on reception of a lid open report, it does NOT trigger a system shutdown.
#[fasync::run_singlethreaded(test)]
async fn test_event_handling() {
let mut mock_maker = MockNodeMaker::new();
... | {
let mut mock_maker = MockNodeMaker::new();
let shutdown_node = mock_maker.make(
"Shutdown",
vec![(
msg_eq!(SystemShutdown(ShutdownRequest::PowerOff)),
msg_ok_return!(SystemShutdown),
)],
);
let event = zx::Event::crea... | identifier_body |
lid_shutdown.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::error::PowerManagerError;
use crate::message::{Message, MessageReturn};
use crate::node::Node;
use crate::shutdown_request::ShutdownRequest;
use ... |
_ => (),
}
}
Err(format_err!("No lid device found"))
}
/// Opens the sensor's device file. Returns the device if the correct HID
/// report descriptor is found.
async fn open_sensor(filename: &PathBuf) -> Result<LidProxy, Error> {
let path = Path::n... | {
match Self::open_sensor(&msg.filename).await {
Ok(device) => return Ok(device),
_ => (),
}
} | conditional_block |
generate_random_samples.py | import sys
sys.path.append('../')
import constants as cnst
import os
os.environ['PYTHONHASHSEED'] = '2'
import tqdm
from model.stg2_generator import StyledGenerator
import numpy as np
from my_utils.visualize_flame_overlay import OverLayViz
from my_utils.flm_dynamic_fit_overlay import camera_ringnetpp
from my_utils.gene... |
if corruption_type == 'pose' or corruption_type == 'all':
# pose_perturbation = np.random.normal(0, pose_sigma[i], (corrupted_flame.shape[0], 3))
# corrupted_flame[:, 150:153] += np.clip(pose_perturbation, -3 * pose_sigma[i], 3 * pose_sigma[i])
pose_perturbation = np.random.normal(0, pose_... | corrupted_flame[:, 100:110] = flm_params[:, 100:110] + \
np.clip(np.random.normal(0, sigma, flm_params[:, 100:110].shape),
-3 * sigma, 3 * sigma).astype('float32')
# Jaw pose
corrupted_flame[:, 153] = flm_params[:, 153] ... | conditional_block |
generate_random_samples.py | import sys
sys.path.append('../')
import constants as cnst
import os
os.environ['PYTHONHASHSEED'] = '2'
import tqdm
from model.stg2_generator import StyledGenerator
import numpy as np
from my_utils.visualize_flame_overlay import OverLayViz
from my_utils.flm_dynamic_fit_overlay import camera_ringnetpp
from my_utils.gene... |
def corrupt_flame_given_sigma(flm_params, corruption_type, sigma, jaw_sigma, pose_sigma):
# import ipdb; ipdb.set_trace()
# np.random.seed(2)
corrupted_flame = deepcopy(flm_params)
if corruption_type == 'shape' or corruption_type == 'all':
corrupted_flame[:, :10] = flm_params[:, :10] + \
... | if normal_map_cond and texture_cond:
return torch.cat((textured_rndr, norm_map), dim=1)
elif normal_map_cond:
return norm_map
elif texture_cond:
return textured_rndr
else:
return flm_params | identifier_body |
generate_random_samples.py | import sys
sys.path.append('../')
import constants as cnst
import os
os.environ['PYTHONHASHSEED'] = '2'
import tqdm
from model.stg2_generator import StyledGenerator
import numpy as np
from my_utils.visualize_flame_overlay import OverLayViz
from my_utils.flm_dynamic_fit_overlay import camera_ringnetpp
from my_utils.gene... | generator_1 = generator_1.eval()
params_to_save = {'cam': [], 'shape': [], 'exp': [], 'pose': [], 'light_code': [], 'texture_code': [],
'identity_indices': []}
for i, sigma in enumerate(corruption_sigma):
images = np.zeros((num_smpl_to_eval_on, 3, resolution, resolution)).ast... | ckpt1 = torch.load(f'{cnst.output_root}checkpoint/{run_idx}/{model_idx}.model')
generator_1.load_state_dict(ckpt1['generator_running']) | random_line_split |
generate_random_samples.py | import sys
sys.path.append('../')
import constants as cnst
import os
os.environ['PYTHONHASHSEED'] = '2'
import tqdm
from model.stg2_generator import StyledGenerator
import numpy as np
from my_utils.visualize_flame_overlay import OverLayViz
from my_utils.flm_dynamic_fit_overlay import camera_ringnetpp
from my_utils.gene... | (flm_params, textured_rndr, norm_map, normal_map_cond, texture_cond):
if normal_map_cond and texture_cond:
return torch.cat((textured_rndr, norm_map), dim=1)
elif normal_map_cond:
return norm_map
elif texture_cond:
return textured_rndr
else:
return flm_params
def corrup... | ge_gen_in | identifier_name |
fpl1617.py | import re
import requests
import json
import math
import time
import os
from operator import itemgetter
import traceback
# Parses members of each team from file
def get_all_teams(filenamePath):
myFile=open(filenamePath)
lines=myFile.readlines()
for i in range(0,len(lines)):
if lines[i].starts... | teamscores_path=curr_dir+"\TeamScores\TeamScore_gw"+str(gw)+".txt"
results_path=curr_dir+"\Results\Results_gw"+str(gw)+".txt"
captain_path=curr_dir+"\Counts\Captains\CaptainCount_gw"+str(gw)+".txt"
vicecaptain_path=curr_dir+"\Counts\ViceCaptains\ViceCaptainCount_gw"+str(gw)+".txt"
f_teamscores=ope... | os.makedirs("Counts/Captains", exist_ok=True)
os.makedirs("Counts/ViceCaptains", exist_ok=True)
| random_line_split |
fpl1617.py | import re
import requests
import json
import math
import time
import os
from operator import itemgetter
import traceback
# Parses members of each team from file
def get_all_teams(filenamePath):
myFile=open(filenamePath)
lines=myFile.readlines()
for i in range(0,len(lines)):
if lines[i].starts... |
def Captain_ViceCaptainSetup(teams):
for k,v in sorted(teams.items()):
team=k
print("-------------------\nTeam: %s" %(str(k)))
for i in range(0,len(v)):
print(str(i+1)+". "+teams[k][i][0])
captain=int(input("Enter Captain number: "))
teams[k].append(captain-... | if(prvsVcFileFound):
for line in prvsViceCaptains:
if(playername in line):
count=int(line.split(':')[1].strip())
if(count<7):
return True
else:
return False
return True
else:
return True | identifier_body |
fpl1617.py | import re
import requests
import json
import math
import time
import os
from operator import itemgetter
import traceback
# Parses members of each team from file
def get_all_teams(filenamePath):
myFile=open(filenamePath)
lines=myFile.readlines()
for i in range(0,len(lines)):
if lines[i].starts... |
return teams
def getTeamScoresfromList(TeamList):
orignalScore=[]
orignalScoreDict=[]
multiplierScore=[]
multiplierScoreDict=[]
for player in TeamList[0:6]:
player_score=get_player_score(player[1],gw)
orignalScore.append(player_score)
orignalScoreDict.append({player... | teams[k][vc-1][2]=1.5 | conditional_block |
fpl1617.py | import re
import requests
import json
import math
import time
import os
from operator import itemgetter
import traceback
# Parses members of each team from file
def get_all_teams(filenamePath):
myFile=open(filenamePath)
lines=myFile.readlines()
for i in range(0,len(lines)):
if lines[i].starts... | (id,gw):
url="https://fantasy.premierleague.com/drf/entry/"+str(id)+"/event/"+str(gw)+"/picks"
retryCount=0
while True:
try:
print("\rURL: "+str(url)+" Retry Count: "+str(retryCount),end="")
r = requests.get(url)
except:
print("\nFound exception")... | get_player_score | identifier_name |
workspace.go | // Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cache
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"golang.org/x/mod/modfile"
"golang.org/x/tools/gopls/in... |
if err := modFile.AddGoStmt(workFile.Go.Version); err != nil {
return nil, nil, err
}
return modFile, modFiles, nil
}
func parseGoplsMod(root, uri span.URI, contents []byte) (*modfile.File, map[span.URI]struct{}, error) {
modFile, err := modfile.Parse(uri.Filename(), contents, nil)
if err != nil {
return ni... | {
return nil, nil, fmt.Errorf("go.work has missing or incomplete go directive")
} | conditional_block |
workspace.go | // Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cache
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"golang.org/x/mod/modfile"
"golang.org/x/tools/gopls/in... |
// isGoMod reports if uri is a go.mod file.
func isGoMod(uri span.URI) bool {
return filepath.Base(uri.Filename()) == "go.mod"
}
func isGoSum(uri span.URI) bool {
return filepath.Base(uri.Filename()) == "go.sum" || filepath.Base(uri.Filename()) == "go.work.sum"
}
// fileExists reports if the file uri exists withi... | {
return span.URIFromPath(filepath.Join(root.Filename(), "go.mod"))
} | identifier_body |
workspace.go | // Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cache
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"golang.org/x/mod/modfile"
"golang.org/x/tools/gopls/in... | () map[span.URI]struct{} {
return w.knownModFiles
}
// ActiveModFiles returns the set of active mod files for the current workspace.
func (w *workspace) ActiveModFiles() map[span.URI]struct{} {
return w.activeModFiles
}
// criticalError returns a critical error related to the workspace setup.
func (w *workspace) cr... | getKnownModFiles | identifier_name |
workspace.go | // Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cache
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"golang.org/x/mod/modfile"
"golang.org/x/tools/gopls/in... | // Probably a permission error. Keep looking.
return filepath.SkipDir
}
// For any path that is not the workspace folder, check if the path
// would be ignored by the go command. Vendor directories also do not
// contain workspace modules.
if info.IsDir() && path != root.Filename() {
suffix := string... | if err != nil { | random_line_split |
lib.rs | #![deny(
// missing_copy_implementations,
// missing_debug_implementations,
// missing_docs,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
variant_size_differences
)]
// #![warn(rust_2018_idioms)]
#![doc(test(attr(deny(
m... | ;
impl Separator for SpaceSeparator {
#[inline]
fn separator() -> &'static str {
" "
}
}
/// Predefined separator using a single comma
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
pub struct CommaSeparator;
impl Separator for CommaSeparator {
#[inline]
fn s... | SpaceSeparator | identifier_name |
lib.rs | #![deny(
// missing_copy_implementations,
// missing_debug_implementations,
// missing_docs,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
variant_size_differences
)]
// #![warn(rust_2018_idioms)]
#![doc(test(attr(deny(
m... | //! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
//! # assert_eq!(foo, serde_json::from_str(&json).unwrap());
//! # }
//! ```
//!
//! [`DisplayFromStr`]: https://docs.rs/serde_with/*/serde_with/struct.DisplayFromStr.html
//! [`serde_as`]: https://docs.rs/serde_with/*/serd... | //! "1": "006fde"
//! }
//! }
//! # "#; | random_line_split |
notification_client.rs | // Copyright 2023 The Matrix.org Foundation C.I.C.
//
// 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... |
/// Try to run a sliding sync (without encryption) to retrieve the event
/// from the notification.
///
/// This works by requesting explicit state that'll be useful for building
/// the `NotificationItem`, and subscribing to the room which the
/// notification relates to.
async fn try_sli... | {
if !self.retry_decryption {
return Ok(None);
}
let event: AnySyncTimelineEvent =
raw_event.deserialize().map_err(|_| Error::InvalidRumaEvent)?;
let event_type = event.event_type();
let is_still_encrypted =
matches!(event_type, ruma::events... | identifier_body |
notification_client.rs | // Copyright 2023 The Matrix.org Foundation C.I.C.
//
// 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... | (
&self,
room_id: &RoomId,
event_id: &EventId,
) -> Result<Option<RawNotificationEvent>, Error> {
// Serialize all the calls to this method by taking a lock at the beginning,
// that will be dropped later.
let _guard = self.sliding_sync_mutex.lock().await;
//... | try_sliding_sync | identifier_name |
notification_client.rs | // Copyright 2023 The Matrix.org Foundation C.I.C.
//
// 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... | timeline_event.push_actions
} else {
room.event_push_actions(timeline_event).await?
}
}
RawNotificationEvent::Invite(invite_event) => {
// Invite events can't be encrypted, so they should be in clear text.
... | self.maybe_retry_decryption(&room, timeline_event).await?
{
raw_event = RawNotificationEvent::Timeline(timeline_event.event.cast()); | random_line_split |
gateway_bft_test.go | /*
Copyright IBM Corp All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package gateway
import (
"context"
"os"
"path/filepath"
"syscall"
"time"
docker "github.com/fsouza/go-dockerclient"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric-protos-go/common"
"github.com/hyperledger/f... |
}
| {
By("joining " + o.Name + " to channel as a consenter")
channelparticipation.Join(network, o, channel, genesisBlock, expectedChannelInfoPT)
channelInfo := channelparticipation.ListOne(network, o, channel)
Expect(channelInfo).To(Equal(expectedChannelInfoPT))
} | conditional_block |
gateway_bft_test.go | /*
Copyright IBM Corp All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package gateway
import (
"context"
"os"
"path/filepath"
"syscall"
"time"
docker "github.com/fsouza/go-dockerclient"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric-protos-go/common"
"github.com/hyperledger/f... | {
sess, err := network.ConfigTxGen(commands.OutputBlock{
ChannelID: channel,
Profile: network.Profiles[0].Name,
ConfigPath: network.RootDir,
OutputBlock: network.OutputBlockPath(channel),
})
Expect(err).NotTo(HaveOccurred())
Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit(0))
genesisB... | identifier_body | |
gateway_bft_test.go | /*
Copyright IBM Corp All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package gateway
import (
"context"
"os"
"path/filepath"
"syscall"
"time"
docker "github.com/fsouza/go-dockerclient"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric-protos-go/common"
"github.com/hyperledger/f... | (
ctx context.Context,
gatewayClient gateway.GatewayClient,
signer *nwo.SigningIdentity,
channel string,
chaincode string,
transactionName string,
arguments []string,
) *gateway.SubmitRequest {
args := [][]byte{}
for _, arg := range arguments {
args = append(args, []byte(arg))
}
proposedTransaction, transa... | prepareTransaction | identifier_name |
gateway_bft_test.go | /*
Copyright IBM Corp All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package gateway
import (
"context"
"os"
"path/filepath"
"syscall"
"time"
docker "github.com/fsouza/go-dockerclient"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric-protos-go/common"
"github.com/hyperledger/f... | BeforeEach(func() {
var err error
testDir, err = os.MkdirTemp("", "gateway")
Expect(err).NotTo(HaveOccurred())
client, err := docker.NewClientFromEnv()
Expect(err).NotTo(HaveOccurred())
networkConfig := nwo.MultiNodeSmartBFT()
network = nwo.New(networkConfig, testDir, client, StartPort(), components)
... | random_line_split | |
db.go | /*
* Copyright 2018 Insolar
*
* 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... | // GetLocalData retrieves data from storage.
func (db *DB) GetLocalData(ctx context.Context, pulse core.PulseNumber, key []byte) ([]byte, error) {
return db.get(
ctx,
bytes.Join([][]byte{{scopeIDLocal}, pulse.Bytes(), key}, nil),
)
}
// IterateLocalData iterates over all record with specified prefix and calls ha... | return db.set(
ctx,
bytes.Join([][]byte{{scopeIDLocal}, pulse.Bytes(), key}, nil),
data,
)
}
| identifier_body |
db.go | /*
* Copyright 2018 Insolar
*
* 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... |
opts.Dir = dir
opts.ValueDir = dir
bdb, err := badger.Open(*opts)
if err != nil {
return nil, errors.Wrap(err, "local database open failed")
}
db := &DB{
db: bdb,
txretiries: conf.Storage.TxRetriesOnConflict,
idlocker: NewIDLocker(),
nodeHistory: map[core.PulseNumber][]core.Node{},
}
... | {
return nil, err
} | conditional_block |
db.go | /*
* Copyright 2018 Insolar
*
* 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... | return db.Update(ctx, func(tx *TransactionManager) error {
return tx.set(ctx, key, value)
})
} | func (db *DB) set(ctx context.Context, key, value []byte) error { | random_line_split |
db.go | /*
* Copyright 2018 Insolar
*
* 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... | ulse core.PulseNumber, nodes []core.Node) error {
db.nodeHistoryLock.Lock()
defer db.nodeHistoryLock.Unlock()
if _, ok := db.nodeHistory[pulse]; ok {
return errors.New("node history override is forbidden")
}
db.nodeHistory[pulse] = nodes
return nil
}
// GetActiveNodes return active nodes for specified pulse... | tActiveNodes(p | identifier_name |
strutil.go | // Copyright (c) 2021 Terminus, 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 agree... | omitEmpty = true
}
result := make([]string, 0, len(ss))
m := make(map[string]struct{}, len(ss))
for _, s := range ss {
if s == "" && omitEmpty {
continue
}
if _, ok := m[s]; ok {
continue
}
result = append(result, s)
m[s] = struct{}{}
}
return result
}
// DedupUint64Slice 返回不含重复元素的 slice,各元素按第一... | .bool) []string {
var omitEmpty bool
if len(omitEmptyOpt) > 0 && omitEmptyOpt[0] {
| conditional_block |
strutil.go | // Copyright (c) 2021 Terminus, 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 agree... | ool) string {
if len(omitEmptyOpt) == 0 || !omitEmptyOpt[0] {
return strings.Join(ss, sep)
}
r := []string{}
for i := range ss {
if ss[i] != "" {
r = append(r, ss[i])
}
}
return strings.Join(r, sep)
}
// JoinPath see also filepath.Join
func JoinPath(ss ...string) string {
return filepath.Join(ss...)
}
... | nt)
}
// Concat 合并字符串
func Concat(s ...string) string {
return strings.Join(s, "")
}
// Join see also strings.Join,
// omitEmptyOpt = true 时,不拼接 `ss` 中空字符串
func Join(ss []string, sep string, omitEmptyOpt ...b | identifier_body |
strutil.go | // Copyright (c) 2021 Terminus, 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 agree... | n(cutset) == 0 {
return strings.TrimLeftFunc(s, unicode.IsSpace)
}
return strings.TrimLeft(s, cutset[0])
}
// TrimRight 裁剪 `s` 右边,如果不指定 `cutset`, 默认cutset=space
//
// TrimRight("trim ") => "trim"
//
// TrimRight(" this") => " this"
//
// TrimRight("athisa", "a") => "athis"
func TrimRight(s string, cutset ...string... | {
if le | identifier_name |
strutil.go | // Copyright (c) 2021 Terminus, 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 agree... | //
// TrimPrefixes("/tmp/file", "/tmp") => "/file"
//
// TrimPrefixes("/tmp/tmp/file", "/tmp", "/tmp/tmp") => "/tmp/file"
func TrimPrefixes(s string, prefixes ...string) string {
originLen := len(s)
for i := range prefixes {
trimmed := strings.TrimPrefix(s, prefixes[i])
if len(trimmed) != originLen {
return tr... | }
// TrimPrefixes 裁剪 `s` 的前缀 | random_line_split |
converter.go | package scope
import (
"fmt"
rbacv1 "k8s.io/api/rbac/v1"
kapierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
kutilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
kauthorizer "k8s.io/apiserver/pkg/authorization/authorizer"
rbaclisters "k8s.i... | (scope string, clusterRoleGetter rbaclisters.ClusterRoleLister) ([]string, error) {
_, scopeNamespace, _, err := scopemetadata.ClusterRoleEvaluatorParseScope(scope)
if err != nil {
return nil, err
}
rules, err := e.resolveRules(scope, clusterRoleGetter)
if err != nil {
return nil, err
}
attributes := kautho... | ResolveGettableNamespaces | identifier_name |
converter.go | package scope
import (
"fmt"
rbacv1 "k8s.io/api/rbac/v1"
kapierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
kutilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
kauthorizer "k8s.io/apiserver/pkg/authorization/authorizer"
rbaclisters "k8s.i... |
func has(set []string, value string) bool {
for _, element := range set {
if value == element {
return true
}
}
return false
}
// resolveRules doesn't enforce namespace checks
func (e clusterRoleEvaluator) resolveRules(scope string, clusterRoleGetter rbaclisters.ClusterRoleLister) ([]rbacv1.PolicyRule, err... | {
_, scopeNamespace, _, err := scopemetadata.ClusterRoleEvaluatorParseScope(scope)
if err != nil {
return nil, err
}
// if the scope limit on the clusterrole doesn't match, then don't add any rules, but its not an error
if !(scopeNamespace == scopesAllNamespaces || scopeNamespace == namespace) {
return []rbac... | identifier_body |
converter.go | package scope
import (
"fmt"
rbacv1 "k8s.io/api/rbac/v1"
kapierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
kutilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
kauthorizer "k8s.io/apiserver/pkg/authorization/authorizer"
rbaclisters "k8s.i... |
if !found {
errors = append(errors, fmt.Errorf("no scope evaluator found for %q", scope))
}
}
return rules, kutilerrors.NewAggregate(errors)
}
// ScopesToVisibleNamespaces returns a list of namespaces that the provided scopes have "get" access to.
// This exists only to support efficiently list/watch of pr... | {
if evaluator.Handles(scope) {
found = true
currRules, err := evaluator.ResolveRules(scope, namespace, clusterRoleGetter)
if err != nil {
errors = append(errors, err)
continue
}
rules = append(rules, currRules...)
}
} | conditional_block |
converter.go | package scope
import (
"fmt"
rbacv1 "k8s.io/api/rbac/v1"
kapierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
kutilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
kauthorizer "k8s.io/apiserver/pkg/authorization/authorizer"
rbaclisters "k8s.i... | // <indicator><indicator choice>
// we have the following formats:
// user:<scope name>
// role:<clusterrole name>:<namespace to allow the cluster role, * means all>
// TODO
// cluster:<comma-delimited verbs>:<comma-delimited resources>
// namespace:<namespace name>:<comma-delimited verbs>:<comma-delimited resources>
... | // scopes are in the format | random_line_split |
bond_monitor.py | import pandas as pd
import pymongo
import pymssql
import tkinter as tk
from tkinter import ttk
import re
convert_list = [ "128", "117", "125", "126", "110", "113", "131"]
def get_bond_names():
bond_names = {}
conn = pymssql.connect(host='192.168.8.120', port=14333, user='GuestUser', password='Gue... |
basedesk(root)
root.mainloop()
| conditional_block | |
bond_monitor.py | import pandas as pd
import pymongo
import pymssql
import tkinter as tk
from tkinter import ttk
import re
convert_list = [ "128", "117", "125", "126", "110", "113", "131"]
def get_bond_names():
bond_names = {}
conn = pymssql.connect(host='192.168.8.120', port=14333, user='GuestUser', password='Gue... | (self, master):
self.root = master
self.root.title('future monitor')
self.root.geometry('1080x720')
self.table_init = False
self.signal_data = {}
self.bond_names = get_bond_names()
myclient = pymongo.MongoClient("mongodb://192.168.9.1... | __init__ | identifier_name |
bond_monitor.py | import pandas as pd
import pymongo
import pymssql
import tkinter as tk
from tkinter import ttk
import re
convert_list = [ "128", "117", "125", "126", "110", "113", "131"]
def get_bond_names():
bond_names = {}
conn = pymssql.connect(host='192.168.8.120', port=14333, user='GuestUser', password='Gue... | self.target_bond = []
self.signal_list = []
self.get_target_bond()
self.db_lookup()
def get_target_bond(self):
with self.mysql.cursor() as cursor:
##取日常要订的表
sql = ''' SELECT * FROM Bond_list '''
cursor.execute(sql)
... | self.mysql = pymssql.connect(host='192.168.9.85', user='sa', password='lhtzb.123', database='BondMonitor')
| random_line_split |
bond_monitor.py | import pandas as pd
import pymongo
import pymssql
import tkinter as tk
from tkinter import ttk
import re
convert_list = [ "128", "117", "125", "126", "110", "113", "131"]
def get_bond_names():
bond_names = {}
conn = pymssql.connect(host='192.168.8.120', port=14333, user='GuestUser', password='Gue... | def set_tv_head(self,tv):
tv["columns"] = self.title
for i in range(len(self.title)):
if self.title[i] == "account_name":
tv.column(self.title[i],width=180,anchor='center')
else:
tv.column(self.title[i],width=100,anchor='center')
... | ["time"])[:4]
if s["code_name"] not in self.signal_data.keys():
self.signal_data[s["code_name"]] = {}
self.signal_data[s["code_name"]]["time"] = minute
self.signal_data[s["code_name"]]["pirce"] = []
self.signal_data[s["code_name"]]["pirce"].append(s[... | identifier_body |
main.rs | use std::env;
use std::fs;
extern crate rgsl;
use std::rc::Rc;
use std::cell::RefCell;
use plotters::prelude::*;
use std::time::Instant;
use std::path::Path;
use std::io::{Error, ErrorKind};
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use image::{imageops::FilterType, ImageFormat};
#[macro_use... | else{
println!("total elements: {}", elements.len());
println!("Can't process {}", line);
}
}
println!("Total iteration: {}", iter);
println!("Average time: {}", total_time_micros / iter);
}
}
| {
let pm0: Vec<f64> = vec![elements[3], elements[4]].iter().filter_map(|e| e.parse::<f64>().ok()).collect();
let pm1: Vec<f64> = vec![elements[5], elements[6]].iter().filter_map(|e| e.parse::<f64>().ok()).collect();
let cp_x: Vec<f64> = elements[7].split(" ").filter_map(|... | conditional_block |
main.rs | use std::env;
use std::fs;
extern crate rgsl;
use std::rc::Rc;
use std::cell::RefCell;
use plotters::prelude::*;
use std::time::Instant;
use std::path::Path;
use std::io::{Error, ErrorKind};
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use image::{imageops::FilterType, ImageFormat};
#[macro_use... | println!("run {} iterations", iter);
println!("average time: {} microsecond", total_time_ms/ iter);
}
*/
fn main() {
let args: Vec<String> = env::args().collect();
let path = Path::new(&args[1]);
if path.is_dir(){
//run_on_folder(&path.to_str().unwrap());
println!("TODO: fix bug in ru... | total_time_ms += now.elapsed().as_micros();
iter += 1;
}
}
} | random_line_split |
main.rs | use std::env;
use std::fs;
extern crate rgsl;
use std::rc::Rc;
use std::cell::RefCell;
use plotters::prelude::*;
use std::time::Instant;
use std::path::Path;
use std::io::{Error, ErrorKind};
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use image::{imageops::FilterType, ImageFormat};
#[macro_use... |
/*
fn run_on_folder(folder: &str){
let mut total_time_ms = 0;
let mut iter = 0;
for entry in fs::read_dir(folder).unwrap(){
let entry = entry.unwrap();
let file_path = entry.path();
if !file_path.is_dir(){
let lines = read_file_into_lines(file_path.to_str().unwrap());
... | {
let a = params.get(0);
let b = params.get(1);
let c = params.get(2);
let mut new_points: Vec<Vec<f64>> = Vec::new();
for point in points.iter(){
let k1 = 2f64 * a * point[0] + b;
let theta_1 = k1.atan();
let mut theta_2 = 0f64;
let mut theta = 0f64;
... | identifier_body |
main.rs | use std::env;
use std::fs;
extern crate rgsl;
use std::rc::Rc;
use std::cell::RefCell;
use plotters::prelude::*;
use std::time::Instant;
use std::path::Path;
use std::io::{Error, ErrorKind};
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use image::{imageops::FilterType, ImageFormat};
#[macro_use... | () {
let args: Vec<String> = env::args().collect();
let path = Path::new(&args[1]);
if path.is_dir(){
//run_on_folder(&path.to_str().unwrap());
println!("TODO: fix bug in run folder");
}else{
let lines = read_file_into_lines(path.to_str().unwrap());
let mut total_time_micr... | main | identifier_name |
py4_promoter_DCI_scatter.py | import sys,argparse
import os,glob
import numpy as np
import pandas as pd
import re,bisect
from scipy import stats
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size']=11
import seaborn as sns
sns.set(font_scale=1.1)
sns.set_style("whitegrid", {'axes.grid' : False})... | suffixes=['_promoter_DCI']
dci_thres = [2,5]
num_DCI_bins_df = pd.DataFrame()
for subdir in subdirs[1:2]:
outdir_tmp='{}/{}'.format(outdir,subdir)
os.makedirs(outdir_tmp,exist_ok=True)
for hm_mark in hm_marks[:]:
for suffix in suffixes[:]:
for dci_thre in dci_thres[1:]:
... |
compr_types = [['WT_over_Vector','DEL_over_WT'],['DEL_over_WT','EIF_over_DEL'],['WT_over_Vector','TPR_over_WT']]
hm_marks = ['H3K4me3','H3K27ac'] | random_line_split |
py4_promoter_DCI_scatter.py | import sys,argparse
import os,glob
import numpy as np
import pandas as pd
import re,bisect
from scipy import stats
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size']=11
import seaborn as sns
sns.set(font_scale=1.1)
sns.set_style("whitegrid", {'axes.grid' : False})... |
# ==== main()
cellType_labels= {'Vector':'Vector',\
'WT':'WT',\
'DEL':'$\Delta$cIDR',\
'EIF':'UTX-eIF$_{IDR}$',\
'TPR':'$\Delta$TPR',\
'MT2':'MT2',\
'FUS':'UTX-FUS$_{IDR}$'}
outdir = 'f4_promoter_DCI... | test_file='{}/{}/{}_{}{}.csv'.format(DCI_dir,subdir,hm_mark,'WT_over_Vector',suffix)
if os.path.isfile(test_file):
box_vals = []
xticklabels = []
sig_vals,sig_colors = [],[]
for compr_col in ['WT_over_Vector','DEL_over_WT','EIF_over_DEL','TPR_over_WT']:
dci_df = r... | identifier_body |
py4_promoter_DCI_scatter.py | import sys,argparse
import os,glob
import numpy as np
import pandas as pd
import re,bisect
from scipy import stats
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size']=11
import seaborn as sns
sns.set(font_scale=1.1)
sns.set_style("whitegrid", {'axes.grid' : False})... |
num_DCI_bins_df.to_csv(outdir+os.sep+'num_DCI_promoter_summary.csv')
| for suffix in suffixes[:]:
for dci_thre in dci_thres[1:]:
for compr_type in compr_types[:]:
up_bins,dn_bins = scatter_plot_compr_DCI(num_DCI_bins_df,subdir,hm_mark,compr_type,suffix,dci_thre)
# the box plot are ... | conditional_block |
py4_promoter_DCI_scatter.py | import sys,argparse
import os,glob
import numpy as np
import pandas as pd
import re,bisect
from scipy import stats
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size']=11
import seaborn as sns
sns.set(font_scale=1.1)
sns.set_style("whitegrid", {'axes.grid' : False})... | (DCI_dir,subdir,hm_mark,compr_type,suffix):
dci_file = '{}/{}/{}_{}{}.csv'.format(DCI_dir,subdir,hm_mark,compr_type,suffix)
if os.path.isfile(dci_file):
dci_df = pd.read_csv(dci_file,sep='\t',index_col=4)
dci_df.columns=['chr','start','end','IfOverlap','score','strand','DCI']
return dc... | return_dci_df | identifier_name |
module.js | // requires
const path = require("path")
const { withDb } = Msa.require("db")
const { Sheet } = require('./model')
const { SheetPerm } = require("./perm")
const { SheetParamDict } = require("./params")
const { MsaParamsLocalAdminModule } = Msa.require("params")
//var msaDbFiles = Msa.require("msa-db", "files.js")
//co... | if(!this.canRead(req, id, sheet))
throw Msa.FORBIDDEN
sheet.editable = this.canWrite(req, id, sheet)
return sheet
}
*/
/*
MsaSheetPt.getSheet = function(key, args1, args2) {
// args
if(args2===undefined) var args = {}, next = args1
else var args = args1, next = args2
defArg(args, "checkUserPerms", args.hasOwnP... | params: new SheetParamDict()
} | random_line_split |
module.js | // requires
const path = require("path")
const { withDb } = Msa.require("db")
const { Sheet } = require('./model')
const { SheetPerm } = require("./perm")
const { SheetParamDict } = require("./params")
const { MsaParamsLocalAdminModule } = Msa.require("params")
//var msaDbFiles = Msa.require("msa-db", "files.js")
//co... | (ctx) {
const id = ctx.sheetParamsArgs.id
const dbRow = await ctx.db.getOne("SELECT params FROM msa_sheets WHERE id=:id",
{ id })
return Sheet.newFromDb(id, dbRow).params
}
async updateRootParam(ctx, rootParam) {
const vals = {
id: ctx.sheetParamsArgs.id,
params: rootParam.getAsDbS... | getRootParam | identifier_name |
module.js | // requires
const path = require("path")
const { withDb } = Msa.require("db")
const { Sheet } = require('./model')
const { SheetPerm } = require("./perm")
const { SheetParamDict } = require("./params")
const { MsaParamsLocalAdminModule } = Msa.require("params")
//var msaDbFiles = Msa.require("msa-db", "files.js")
//co... |
function deepGet(obj, key, ...args) {
const obj2 = obj[key]
if (obj2 === undefined) return
if (args.length === 0) return obj2
return deepGet(obj2, ...args)
}
// default templates
// no need to register the head of these web elements, as they are imported directly in msa-sheet.html
registerSheetBoxTemplate("ms... | {
const ctx = Object.create(req)
Object.assign(ctx, kwargs)
return ctx
} | identifier_body |
remote_build.go | package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
ggit "gg-scm.io/pkg/git"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"github.com/johnewart/archiver"
"gith... | (ctx context.Context, project *apiProject, tagMap map[string]string) error {
startTime := time.Now()
userToken, err := config.UserToken(cmd.cfg)
if err != nil {
return err
}
patchBuffer := new(bytes.Buffer)
xzWriter, err := xz.NewWriter(patchBuffer)
if err != nil {
return fmt.Errorf("submit build: compres... | submitBuild | identifier_name |
remote_build.go | package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
ggit "gg-scm.io/pkg/git"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"github.com/johnewart/archiver"
"gith... |
// This is where the patch is actually generated see #278
p.patchData = []byte(patch.String())
log.Debugf(ctx, "Actual patch generation finished")
log.Debugf(ctx, "Reseting worktree to previous state...")
// Reset back to HEAD
if err := worktree.Reset(&git.ResetOptions{
Commit: headCommit.Hash,
}); ... | {
return fmt.Errorf("patch generation failed: %w", err)
} | conditional_block |
remote_build.go | package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
ggit "gg-scm.io/pkg/git"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"github.com/johnewart/archiver"
"gith... |
for _, u := range urls {
rem, err := ggit.ParseURL(u)
if err != nil {
log.Warnf(ctx, "Invalid remote %s (%v), ignoring", u, err)
continue
}
// We only support GitHub by now
// TODO create something more generic
if rem.Host != "github.com" {
log.Warnf(ctx, "Ignoring remote %s (only github.com supp... | func (p *remoteCmd) fetchProject(ctx context.Context, urls []string) (*apiProject, error) {
v := url.Values{}
fmt.Println()
log.Infof(ctx, "URLs used to search: %s", urls) | random_line_split |
remote_build.go | package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
ggit "gg-scm.io/pkg/git"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"github.com/johnewart/archiver"
"gith... |
// findFilesToAdd finds files to stage in Git, recursing into directories and
// ignoring any non-text files.
func findFilesToAdd(ctx context.Context, g *ggit.Git, workTree string, dst []ggit.Pathspec, file ggit.TopPath) ([]ggit.Pathspec, error) {
realPath := filepath.Join(workTree, filepath.FromSlash(string(file)))... | {
workTree, err := g.WorkTree(ctx)
if err != nil {
return fmt.Errorf("traverse changes: %w", err)
}
status, err := g.Status(ctx, ggit.StatusOptions{
DisableRenames: true,
})
if err != nil {
return fmt.Errorf("traverse changes: %w", err)
}
var addList []ggit.Pathspec
for _, ent := range status {
if ent... | identifier_body |
tf_worker.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
name = uid_to_human[val]
node_id_to_name[key] = name
return node_id_to_name
def id_to_string(self, node_id):
if node_id not in self.node_lookup:
return ''
return self.node_lookup[node_id]
def create_graph():
""""Creates a graph from saved GraphDef file and returns a saver."""
# ... | tf.logging.fatal('Failed to locate: %s', val) | conditional_block |
tf_worker.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
def main(_):
maybe_download_and_extract()
classify_images()
if __name__ == '__main__':
tf.app.run()
| """Download and extract model tar file."""
dest_directory = FLAGS.model_dir
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_si... | identifier_body |
tf_worker.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Simple image classification with Inception.
Run image cl... | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
tf_worker.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | ():
"""Download and extract model tar file."""
dest_directory = FLAGS.model_dir
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, to... | maybe_download_and_extract | identifier_name |
blt_engine.py | from bearlibterminal import terminal
from mapping.game_map import GameMap
from gameplay.dialog_tree import DialogTree
from message_log import MessageLog
from game_object import GameObject
from render_functions import draw_all, draw_map
from input_handler import handle_keys
from utils import *
from gameplay.npc import N... | (npc, player, dialog_name):
dialog_tree = DialogTree(npc.dialog_dict)
text = dialog_tree.get_say(dialog_name)
conditions = dialog_tree.get_conditions(dialog_name)
responses = dialog_tree.get_responses(dialog_name)
target = dialog_tree.get_target_dialog(dialog_name)
if not conditions is None:
... | npc_dialog | identifier_name |
blt_engine.py | from bearlibterminal import terminal
from mapping.game_map import GameMap
from gameplay.dialog_tree import DialogTree
from message_log import MessageLog
from game_object import GameObject
from render_functions import draw_all, draw_map
from input_handler import handle_keys
from utils import *
from gameplay.npc import N... | inal.close()
##layers:
##background 0
##terrain 1
##characters 2
##ui 3
| action = terminal.read()
##1202 AM TODO:
###implement map system in blt engine✅
###implement NPC and fold in dialog system✅
##by adding a 'dialog' property to NPC object.
###implement item class and item description
##0118 # TODO:
##implement conditionals✅ 0119
... | conditional_block |
blt_engine.py | from bearlibterminal import terminal
from mapping.game_map import GameMap
from gameplay.dialog_tree import DialogTree
from message_log import MessageLog
from game_object import GameObject
from render_functions import draw_all, draw_map
from input_handler import handle_keys
from utils import *
from gameplay.npc import N... | o['char'] = '@'
if not 'color' in o:
o['color'] = 'black'
if not 'type' in o:
return GameObject(o['x'], o['y'], o['char'], o['color'], name)
elif o.get('type') == 'npc':
if 'dialog' in o:
dialog = o['dialog']
else:
dialog = 'default'
r... | random_line_split | |
blt_engine.py | from bearlibterminal import terminal
from mapping.game_map import GameMap
from gameplay.dialog_tree import DialogTree
from message_log import MessageLog
from game_object import GameObject
from render_functions import draw_all, draw_map
from input_handler import handle_keys
from utils import *
from gameplay.npc import N... |
def add_to_inventory(inventory, item_to_add):
item_in_inventory = inventory.get(item_to_add.name, None)
if item_in_inventory is None:
inventory[item_to_add.name] = item_to_add
else:
item_in_inventory.quantity += item_to_add.quantity
def check_inventory_for_item(inventory, item_name, min... | map.switch_map(new_map_index)
draw_map(terminal, map)
game_map.unblock(player.x, player.y)
player.move(dx , dy )
objects.clear()
objects.append(player)
if map.map_name in map_npc_db:
load_objects = map_npc_db[map.map_name]
for key in load_objects.keys():
objects.app... | identifier_body |
main.py | import pygame
import os
import time
import random
pygame.init()
# Maximum height and width of the game surface
WIDTH, HEIGHT = (750, 750)
# To create the display surface
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
# Set the surface caption
pygame.display.set_caption("MyGame")
# Background image
... |
def shoot(self):
if self.cool_down_counter == 0:
laser = Laser(self.x-20, self.y, self.laser_img)
self.lasers.append(laser)
self.cool_down_counter = 1
def main():
# Flag to track the game status
run = True
# frame to be rendered per second
... | self.y += vel | identifier_body |
main.py | import pygame
import os
import time
import random
pygame.init()
# Maximum height and width of the game surface
WIDTH, HEIGHT = (750, 750)
# To create the display surface
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
# Set the surface caption
pygame.display.set_caption("MyGame")
# Background image
... |
player_activity()
'''
Player():
draw() --> ship.draw()
Move_laser() --> ship.cool_down()
health_bar()
Ship() ---- > ship.shoot()
Enemy():
move()
shoot()... | enemy = Enemy(random.randrange(50, WIDTH - 100),
random.randrange(-1500, -100),
random.choice(["red", "blue", "green"]))
enemies.append(enemy) | conditional_block |
main.py | import pygame
import os
import time
import random
pygame.init()
# Maximum height and width of the game surface
WIDTH, HEIGHT = (750, 750)
# To create the display surface
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
# Set the surface caption
pygame.display.set_caption("MyGame")
# Background image
... | (self, window):
window.blit(self.ship_img, (self.x, self.y))
for laser in self.lasers:
laser.draw(window)
def move_lasers(self, vel, obj):
self.cooldown()
for laser in self.lasers:
laser.move(vel)
if laser.off_screen(HEIGHT):
... | draw | identifier_name |
main.py | import pygame
import os
import time
import random
pygame.init()
# Maximum height and width of the game surface
WIDTH, HEIGHT = (750, 750)
# To create the display surface
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
# Set the surface caption
pygame.display.set_caption("MyGame")
# Background image
... | player_activity()
'''
Player():
draw() --> ship.draw()
Move_laser() --> ship.cool_down()
health_bar()
Ship() ---- > ship.shoot()
Enemy():
move()
shoot() ---... | random.choice(["red", "blue", "green"]))
enemies.append(enemy)
| random_line_split |
store.ts | import { action, observable } from "mobx";
import {
reqIpTypeList,
upload,
getIpDetail,
getDownload,
delMaterial,
uploadBusinessData, listCompany, listMainType, listCountry, getCompanyType
} from "@utils/api";
interface IUpdateStatus {
pub: object,
sub: object,
showDate: object,
}
interface IUpdateS... | let _locationList: object[] = [];
if (errorCode === "200") {
result.forEach((item: any) => {
_locationList.push(item);
});
this.locationList = _locationList;
return _locationList;
}
}
/**
* 可授权区
* @param params
*/
@action
async getAuthorityZone(params) {
... | * 国家地区
*/
@action
async getLocation() {
let { errorCode, result }: any = await listCountry(); | random_line_split |
store.ts | import { action, observable } from "mobx";
import {
reqIpTypeList,
upload,
getIpDetail,
getDownload,
delMaterial,
uploadBusinessData, listCompany, listMainType, listCountry, getCompanyType
} from "@utils/api";
interface IUpdateStatus {
pub: object,
sub: object,
showDate: object,
}
interface IUpdateS... | rCode === '200' && result.errorCode === 200) {
} else if (result.errorCode < 0) {
return { message: result.message };
}
}
// 下载招商资料
// async downloadMaterial(params) {
// const { errorCode, result }: any = await getDownloadMaterial(params);
// if (errorCode === '200' && result.errorCode ==... | } else {
return {
request: false,
message: result.errorMsg,
};
// alert(result.errorMsg)
}
}
}
@action
async setStatus(params) {
this.updateList = { ...this.updateList, ...params };
}
async setStatus2(params) {
this.updateList = { ...this.up... | conditional_block |
store.ts | import { action, observable } from "mobx";
import {
reqIpTypeList,
upload,
getIpDetail,
getDownload,
delMaterial,
uploadBusinessData, listCompany, listMainType, listCountry, getCompanyType
} from "@utils/api";
interface IUpdateStatus {
pub: object,
sub: object,
showDate: object,
}
interface IUpdateS... | defined) result.data[val] = undefined;
}
}
}
this.updateList = result.data;
this.brokerageFirmGuid = result.data && result.data.brokerageFirmGuid;
return {
request: true,
};
} else {
return {
request: false,
messag... | ata[val] === un | identifier_name |
unwind.py | # Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 and
# only version 2 as published by the Free Software Foundation.
#
# This program is distributed in the hope t... | (self, frame, trace = False) :
low = frame.sp
high = ((low + (THREAD_SIZE - 1)) & ~(THREAD_SIZE - 1)) + THREAD_SIZE
idx = self.search_idx(frame.pc)
if (idx is None) :
if trace :
print_out_str ("can't find %x" % frame.pc)
return -1
ctrl = ... | unwind_frame | identifier_name |
unwind.py | # Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 and
# only version 2 as published by the Free Software Foundation.
#
# This program is distributed in the hope t... |
def unwind_exec_insn(self, ctrl, trace = False) :
insn = self.unwind_get_byte(ctrl)
if ((insn & 0xc0) == 0x00) :
ctrl.vrs[SP] += ((insn & 0x3f) << 2) + 4
if trace :
print_out_str (" add {0} to stack".format(((insn & 0x3f) << 2) + 4))
elif ((insn ... | if (ctrl.entries <= 0) :
print_out_str("unwind: Corrupt unwind table")
return 0
val = self.ramdump.read_word(ctrl.insn)
ret = (val >> (ctrl.byte * 8)) & 0xff
if (ctrl.byte == 0) :
ctrl.insn+=4
ctrl.entries-=1
ctrl.byte = 3
el... | identifier_body |
unwind.py | # Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 and
# only version 2 as published by the Free Software Foundation.
#
# This program is distributed in the hope t... | from struct import unpack
from ctypes import *
from print_out import *
FP = 11
SP = 13
LR = 14
PC = 15
THREAD_SIZE = 8192
class Stackframe () :
def __init__(self, fp, sp, lr, pc) :
self.fp = fp
self.sp = sp
self.lr = lr
self.pc = pc
class UnwindCtrlBlock () :
def __init__ (sel... | from optparse import OptionGroup | random_line_split |
unwind.py | # Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 and
# only version 2 as published by the Free Software Foundation.
#
# This program is distributed in the hope t... |
if ctrl.vrs[reg] is None :
return -1
vsp+=4
if (insn & 0x80) :
if trace :
print_out_str (" set LR from the stack")
ctrl.vrs[14] = self.ramdump.read_word(vsp)
if ctrl.vrs[14] is None :... | print_out_str (" pop r{0} from stack".format(reg)) | conditional_block |
graph.go | package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/google/go-cmp/cmp"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/sets"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
// Step is a self-contained bit of work that... |
if !changed && len(waiting) > 0 {
errMessages := sets.Set[string]{}
for _, node := range waiting {
missing := sets.Set[string]{}
for _, link := range node.Step.Requires() {
if !HasAllLinks([]StepLink{link}, satisfied) {
if msg := link.UnsatisfiableError(); msg != "" {
missing.Insert(m... | {
for _, child := range node.Children {
if _, ok := seen[child.Step]; !ok {
waiting = append(waiting, child)
}
}
if _, ok := seen[node.Step]; ok {
continue
}
if !HasAllLinks(node.Step.Requires(), satisfied) {
waiting = append(waiting, node)
continue
}
satisfied = append(sat... | conditional_block |
graph.go | package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/google/go-cmp/cmp"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/sets"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
// Step is a self-contained bit of work that... | node := StepNode{Step: step, Children: []*StepNode{}}
allNodes = append(allNodes, &node)
}
var ret StepGraph
for _, node := range allNodes {
isRoot := true
for _, other := range allNodes {
for _, nodeRequires := range node.Step.Requires() {
for _, otherCreates := range other.Step.Creates() {
if ... | // BuildGraph returns a graph or graphs that include
// all steps given.
func BuildGraph(steps []Step) StepGraph {
var allNodes []*StepNode
for _, step := range steps { | random_line_split |
graph.go | package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/google/go-cmp/cmp"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/sets"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
// Step is a self-contained bit of work that... | () string {
return l.unsatisfiableError
}
func AllStepsLink() StepLink {
return allStepsLink{}
}
type allStepsLink struct{}
func (_ allStepsLink) SatisfiedBy(_ StepLink) bool {
return true
}
func (_ allStepsLink) UnsatisfiableError() string {
return ""
}
func ExternalImageLink(ref ImageStreamTagReference) Step... | UnsatisfiableError | identifier_name |
graph.go | package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/google/go-cmp/cmp"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/sets"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
// Step is a self-contained bit of work that... |
// +k8s:deepcopy-gen=false
type CIOperatorStepDetails struct {
CIOperatorStepDetailInfo `json:",inline"`
Substeps []CIOperatorStepDetailInfo `json:"substeps,omitempty"`
}
// +k8s:deepcopy-gen=false
type CIOperatorStepDetailInfo struct {
StepName string `json:"name"`
Descri... | {
if into.Description == "" {
into.Description = from.Description
}
if into.Dependencies == nil {
into.Dependencies = from.Dependencies
}
if into.StartedAt == nil {
into.StartedAt = from.StartedAt
}
if into.StartedAt == nil {
into.StartedAt = from.StartedAt
}
if into.FinishedAt == nil {
into.Finished... | identifier_body |
ppapi_generator.py | # Copyright 2013 The Chromium 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 collections
import datetime
import os.path
import sys
import code
import cpp_util
import model
try:
import jinja2
except ImportError:
sys.path.a... | def Generate(self):
"""Generates a Code object for a single namespace."""
return self.Render(self.TEMPLATE_NAME, {
'name': self._namespace.name,
'enums': self._enums,
'types': self._types,
'events': self._namespace.events,
'functions': self._namespace.functions,
# TODO(samm... | generated_code.Append(template.render(values))
return generated_code
| random_line_split |
ppapi_generator.py | # Copyright 2013 The Chromium 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 collections
import datetime
import os.path
import sys
import code
import cpp_util
import model
try:
import jinja2
except ImportError:
sys.path.a... |
while self._dependencies:
for name, deps in self._dependencies.items():
if not deps:
if (self._required_types[name].property_type ==
model.PropertyType.ENUM):
self._enums.append(self._required_types[name])
else:
self._types.append(self._requir... | for typename in sorted(set(self._required_types) - resolved_types):
type_ = self._required_types[typename]
self._dependencies.setdefault(typename, set())
for member in type_.properties.itervalues():
self._RegisterDependency(member, self._NameComponents(type_))
resolved_types.ad... | conditional_block |
ppapi_generator.py | # Copyright 2013 The Chromium 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 collections
import datetime
import os.path
import sys
import code
import cpp_util
import model
try:
import jinja2
except ImportError:
sys.path.a... | (self, member, depender):
self._RegisterTypeDependency(member.type_, depender, member.optional, False)
def _RegisterTypeDependency(self, type_, depender, optional, array):
if type_.property_type == model.PropertyType.ARRAY:
self._RegisterTypeDependency(type_.item_type, depender, optional, True)
eli... | _RegisterDependency | identifier_name |
ppapi_generator.py | # Copyright 2013 The Chromium 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 collections
import datetime
import os.path
import sys
import code
import cpp_util
import model
try:
import jinja2
except ImportError:
sys.path.a... |
class PpapiGenerator(object):
def __init__(self):
self.idl_generator = _GeneratorWrapper(_IdlGenerator)
| return self._generator_factory(namespace).Generate() | identifier_body |
statistic_compare.py | import scipy.stats as stats
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from re import findall
SMALL_SIZE = 9
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)
def get_metric(path, metric='loss'):
loss = -1
loss_list = []
if metric == 'l... | ():
# plt.rcParams['font.sans-serif'] = ['Times']
model = ['densenet121', 'mobilenet_v2', 'squeezenet1_1']
# model = 'mobilenet_v2'
# model = 'squeezenet1_1'
# datasets = ['UCMerced', 'RSSCN7', 'WHU19', 'AID']
datasets = ['UCMerced', 'OxfordPets', 'RSSCN7']
# datasets = ['AID']
# ntasks = [0, 50, 100, 2... | compare_n | identifier_name |
statistic_compare.py | import scipy.stats as stats
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from re import findall
SMALL_SIZE = 9
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)
def get_metric(path, metric='loss'):
loss = -1
loss_list = []
if metric == 'l... | s.pdf')
# compare_sto()
compare_n()
# plt.plot(get_checkpoint('../../results/RSSCN7_single_resnet18_seed0.txt'))
# plt.plot(get_checkpoint('../../results/RSSCN7_w_VS_rancl_resnet18_seed0.txt'))
#
# plt.show()
# kd = [95.50, 95.52, 95.94, 95.58, 95.51, 95.56, 95.76, 95.79, 95.53, 95.65]
# at = [95.44, 95.33,... | plt.figure()
# avg_loss = np.zeros((5,len(ntasks)))
# avg_acc = np.zeros((5,len(ntasks)))
avg_loss = np.zeros(len(ntasks))
avg_acc = np.zeros(len(ntasks))
for k, m in enumerate(model):
files = []
# 1007: 不同交互频率
# 1003_n: STO和MTO的结果
# files.append('../../results/1003_n/{}_single_{}_n1_se... | conditional_block |
statistic_compare.py | import scipy.stats as stats
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from re import findall
SMALL_SIZE = 9
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)
def get_metric(path, metric='loss'):
loss = -1
loss_list = []
if metric == 'l... |
def get_overall_accuracy(path, find_best=False):
oa = 0
n_trans = 0
percentage = 0
bestlist = []
# try:
with open(path, 'r') as f:
lines = f.readlines()
for line in lines:
if '# Task' in line:
pbest = float(findall(r"\d+\.?\d*", line.split('Accuracy:')[1])[0])
bestlist.append(pbest... | oa_list = []
nt_list = []
count = 0
c_trans = 0
with open(path, 'r') as f:
lines = f.readlines()
for line in lines:
if 'Task 0' in line and '# Iter:' in line:
rank_num = int(line.split('rank')[-1].split(',')[0])
if rank_num % 2 == 0:
# task_id = int(line.split('Task ')[-1].split(',')[0... | identifier_body |
statistic_compare.py | import scipy.stats as stats
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from re import findall
SMALL_SIZE = 9
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)
def get_metric(path, metric='loss'):
loss = -1
loss_list = []
if metric == 'l... | print('-------------------------')
if draw_figure:
plt.tight_layout()
fig.savefig('{}.pdf'.format(d))
print('============================')
def compare_n():
# plt.rcParams['font.sans-serif'] = ['Times']
model = ['densenet121', 'mobilenet_v2', 'squeezenet1_1']
# model = 'mobilenet_v2'
# mod... | print('trans percentage {}'.format(avg_trans))
# print('average trans percentage {}'.format(sum(avg_trans)/len(avg_trans)))
| random_line_split |
kiteworks.go | package core
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
)
var ErrNotFound = errors.New("Requested item not found.")
type FileInfo interface {
Name() string
Size() int64
ModTime() time.Time
}
type KiteMember struct {
ID int `json:"objectId"`
RoleID int `json:"roleId`
User... | if len(raw_users) == 0 {
return
}
T.offset = T.offset + len(raw_users)
users, err = T.filterUsers(raw_users)
if err != nil {
return nil, err
}
if len(users) == 0 {
continue
} else {
break
}
}
return
}
func (T *GetUsers) findEmails() (users []KiteUser, err error) {
for _, u := range T.... | } | random_line_split |
kiteworks.go | package core
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
)
var ErrNotFound = errors.New("Requested item not found.")
type FileInfo interface {
Name() string
Size() int64
ModTime() time.Time
}
type KiteMember struct {
ID int `json:"objectId"`
RoleID int `json:"roleId`
User... | (params ...interface{}) (children []KiteObject, err error) {
if len(params) == 0 {
params = SetParams(Query{"deleted": false})
}
err = s.DataCall(APIRequest{
Method: "GET",
Path: SetPath("/rest/folders/%d/children", s.folder_id),
Output: &children,
Params: SetParams(params, Query{"with": "(path,currentUs... | Contents | identifier_name |
kiteworks.go | package core
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
)
var ErrNotFound = errors.New("Requested item not found.")
type FileInfo interface {
Name() string
Size() int64
ModTime() time.Time
}
type KiteMember struct {
ID int `json:"objectId"`
RoleID int `json:"roleId`
User... |
// Get Users
type GetUsers struct {
offset int
filter Query
emails []string
params []interface{}
session *kw_rest_admin
completed bool
}
// Admin EAPI endpoint to pull all users matching parameters.
func (s kw_rest_admin) Users(emails []string, params ...interface{}) *GetUsers {
var T GetUsers
... | {
var user []struct{}
if emails != nil && emails[0] != NONE {
for _, u := range emails {
err = s.DataCall(APIRequest{
Method: "GET",
Path: "/rest/admin/users",
Params: SetParams(Query{"email": u}, params),
Output: &user}, -1, 1000)
if err != nil {
return
}
users = len(user) + users... | identifier_body |
kiteworks.go | package core
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
)
var ErrNotFound = errors.New("Requested item not found.")
type FileInfo interface {
Name() string
Size() int64
ModTime() time.Time
}
type KiteMember struct {
ID int `json:"objectId"`
RoleID int `json:"roleId`
User... | else if i == folder_len {
return
}
}
}
if found == false {
return result, ErrNotFound
}
}
return result, ErrNotFound
}
type kw_rest_admin struct {
*KWSession
}
func (s KWSession) Admin() kw_rest_admin {
return kw_rest_admin{&s}
}
// Creates a new user on the system.
func (s kw_rest_admin) ... | {
current, err = s.Folder(c.ID).Contents(params)
if err != nil {
return
}
found = true
break
} | conditional_block |
run_template.go | // Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in complian... |
runCmd.Flags().BoolVar(&filterPatchVersions, "filter-patch-versions", false, "Filters patch versions so that only the latest patch versions per minor versions is used.")
runCmd.Flags().StringVar(&shootParameters.ComponentDescriptorPath, "component-descriptor-path", "", "Path to the component descriptor (BOM) of the... | {
logger.Log.Error(err, "mark flag required", "flag", "shoot-name")
} | conditional_block |
run_template.go | // Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in complian... |
// DEPRECATED FLAGS
// is now handled by the testmachinery
runCmd.Flags().StringVar(&collectConfig.OutputDir, "output-dir-path", "./testout", "The filepath where the summary should be written to.")
runCmd.Flags().String("es-config-name", "sap_internal", "DEPRECATED: The elasticsearch secret-server config name.")
... | runCmd.Flags().StringVar(&shootParameters.Landscape, "landscape", "", "Current gardener landscape.")
runCmd.Flags().StringArrayVar(&shootParameters.SetValues, "set", make([]string, 0), "setValues additional helm values")
runCmd.Flags().StringArrayVarP(&shootParameters.FileValues, "values", "f", make([]string, 0), "... | random_line_split |
run_template.go | // Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in complian... | () {
// configuration flags
runCmd.Flags().StringVar(&tmKubeconfigPath, "tm-kubeconfig-path", "", "Path to the testmachinery cluster kubeconfig")
if err := runCmd.MarkFlagRequired("tm-kubeconfig-path"); err != nil {
logger.Log.Error(err, "mark flag required", "flag", "tm-kubeconfig-path")
}
if err := runCmd.Mark... | init | identifier_name |
run_template.go | // Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in complian... | {
// configuration flags
runCmd.Flags().StringVar(&tmKubeconfigPath, "tm-kubeconfig-path", "", "Path to the testmachinery cluster kubeconfig")
if err := runCmd.MarkFlagRequired("tm-kubeconfig-path"); err != nil {
logger.Log.Error(err, "mark flag required", "flag", "tm-kubeconfig-path")
}
if err := runCmd.MarkFla... | identifier_body | |
stat.go | package stat
import (
"fmt"
"strconv"
"sync"
"time"
"github.com/smartwalle/container/smap"
"math"
kdb "github.com/sv/kdbgo"
)
type Response struct {
Sym string
Qid string
Accountname string
Time time.Time
Entrustno int32
Stockcode string
Askprice float64
Askvol int... | rder.Bidvol > 0 {
stattax = math.Abs(float64(newOrder.Bidprice*float64(newOrder.Bidvol))) * 3 / 10000
} else {
stattax = math.Abs(float64(newOrder.Bidprice*float64(newOrder.Bidvol))) * 13 / 10000
}
fmt.Println("之前费用", stat.ProfitStk.TotalTax, " 本次费用 ", stattax)
stat.ProfitStk.TotalTax = stat.ProfitStk.... | 算均价", stat.SpaceStk.AvgPrice)
//算费用 买是万三 卖是千一加上万三
var stattax float64
if newO | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.