file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.rs | Archive, PackageIdent};
use common::ui::{Coloring, UI, NOCOLORING_ENVVAR, NONINTERACTIVE_ENVVAR};
use rand::Rng;
use export_docker::{Cli, Credentials, BuildSpec, Naming, Result};
// Synced with the version of the Habitat operator.
pub const VERSION: &'static str = "0.1.0";
// Kubernetes manifest template
const MANIF... | {
match val.parse::<u32>() {
Ok(_) => Ok(()),
Err(_) => Err(format!("{} is not a natural number", val)),
}
} | identifier_body | |
config.go | "
"strconv"
"strings"
"github.com/pkg/errors"
yaml "gopkg.in/yaml.v2"
"github.com/daos-stack/daos/src/control/common"
"github.com/daos-stack/daos/src/control/log"
)
const (
configOut = ".daos_server.active.yml"
relConfExamplesPath = "utils/config/examples/"
msgBadConfig = "insuffic... | (i int) error {
// avoid mutating subject during iteration, instead access through
// config/parent object
srv := &c.Servers[i]
srv.CliOpts = append(
srv.CliOpts,
"-t", strconv.Itoa(srv.Targets),
"-g", c.SystemName,
"-s", srv.ScmMount)
if c.Modules != "" {
srv.CliOpts = append(srv.CliOpts, "-m", c.Modu... | populateCliOpts | identifier_name |
config.go | aml "gopkg.in/yaml.v2"
"github.com/daos-stack/daos/src/control/common"
"github.com/daos-stack/daos/src/control/log"
)
const (
configOut = ".daos_server.active.yml"
relConfExamplesPath = "utils/config/examples/"
msgBadConfig = "insufficient config file, see examples in "
msgConfigNoProv... | } | random_line_split | |
config.go | "
"strconv"
"strings"
"github.com/pkg/errors"
yaml "gopkg.in/yaml.v2"
"github.com/daos-stack/daos/src/control/common"
"github.com/daos-stack/daos/src/control/log"
)
const (
configOut = ".daos_server.active.yml"
relConfExamplesPath = "utils/config/examples/"
msgBadConfig = "insuffic... |
func (c *configuration) setPath(path string) error {
if path != "" {
c.Path = path
}
if !filepath.IsAbs(c.Path) {
newPath, err := c.ext.getAbsInstallPath(c.Path)
if err != nil {
return err
}
c.Path = newPath
}
return nil
}
// loadConfigOpts derives file location and parses configuration options
/... | {
bytes, err := yaml.Marshal(c)
if err != nil {
return err
}
return ioutil.WriteFile(filename, bytes, 0644)
} | identifier_body |
config.go | "
"strconv"
"strings"
"github.com/pkg/errors"
yaml "gopkg.in/yaml.v2"
"github.com/daos-stack/daos/src/control/common"
"github.com/daos-stack/daos/src/control/log"
)
const (
configOut = ".daos_server.active.yml"
relConfExamplesPath = "utils/config/examples/"
msgBadConfig = "insuffic... |
if err := config.loadConfig(); err != nil {
return config, errors.WithMessagef(err, "loading %s", config.Path)
}
log.Debugf("DAOS config read from %s", config.Path)
// Override certificate support if specified in cliOpts
if cliOpts.Insecure {
config.TransportConfig.AllowInsecure = true
}
// get unique id... | {
return config, errors.WithMessage(err, "set path")
} | conditional_block |
main.js | most iconic monuments, visited by millions of tourists each year. The complex was designated a UNESCO World Heritage site in 1983.</p>')
$(".Taj-Mahal3").append('<br>')
$(".Taj-Mahal3").append('<br>')
$(".Taj-Mahal3").append('<img id="taj3" src="https://cdn.britannica.com/s:700x500/08/172208-004-7CCDFF72/portrait-emp... | $(".colosseum").append('<img id="colosseum3" src="https://cdn.britannica.com/s:700x500/69/94469-050-4340CF77/Colosseum-Rome.jpg"/>')
$(".colosseum").append('<div class="rome3">At present the Colosseum is, along with the Vatican City, Romes greatest tourist attraction. Each year 6 million tourists visit it. On 7 July 20... | random_line_split | |
DebugModule.go | if len(s) < 2 {
return "```Malformed key:value pair. If your key value pair has a space in it, remember to put it in parenthesis!```", false, nil
}
fields = append(fields, &discordgo.MessageEmbedField{Name: s[0], Value: s[1], Inline: true})
i++
}
embed := &discordgo.MessageEmbed{ | URL: url,
Name: msg.Author.Username + "#" + msg.Author.Discriminator,
IconURL: fmt.Sprintf("https://cdn.discordapp.com/avatars/%s/%s.jpg", msg.Author.ID, msg.Author.Avatar),
},
Color: int(color),
Fields: fields,
}
info.SendEmbed(channel, embed)
return "", false, nil
}
func (c *echoEmbedCommand... | Type: "rich",
Author: &discordgo.MessageEmbedAuthor{ | random_line_split |
DebugModule.go | if len(s) < 2 {
return "```Malformed key:value pair. If your key value pair has a space in it, remember to put it in parenthesis!```", false, nil
}
fields = append(fields, &discordgo.MessageEmbedField{Name: s[0], Value: s[1], Inline: true})
i++
}
embed := &discordgo.MessageEmbed{
Type: "rich",
Author: &... |
func (c *updateCommand) UsageShort() string { return "[RESTRICTED] Updates sweetiebot." }
func (c *updateCommand) Roles() []string { return []string{"Princesses"} }
func (c *updateCommand) Channels() []string { return []string{} }
type dumpTablesCommand struct {
}
func (c *dumpTablesCommand) Name() string {
retu... | {
return &CommandUsage{Desc: "Tells sweetiebot to shut down, calls an update script, rebuilds the code, and then restarts."}
} | identifier_body |
DebugModule.go |
return msg.Content[indices[0]:], false, nil
}
func (c *echoCommand) Usage(info *GuildInfo) *CommandUsage {
return &CommandUsage{
Desc: "Makes Sweetie Bot say the given sentence in `#channel`, or in the current channel if no channel is provided.",
Params: []CommandUsageParam{
{Name: "#channel", Desc: "The chan... | {
if len(args) < 2 {
return "```You have to tell me to say something, silly!```", false, nil
}
info.SendMessage(arg[2:len(arg)-1], msg.Content[indices[1]:])
return "", false, nil
} | conditional_block | |
DebugModule.go | if len(s) < 2 {
return "```Malformed key:value pair. If your key value pair has a space in it, remember to put it in parenthesis!```", false, nil
}
fields = append(fields, &discordgo.MessageEmbedField{Name: s[0], Value: s[1], Inline: true})
i++
}
embed := &discordgo.MessageEmbed{
Type: "rich",
Author: ... | (args []string, msg *discordgo.Message, indices []int, info *GuildInfo) (string, bool, *discordgo.MessageEmbed) {
_, isOwner := sb.O | Process | identifier_name |
plugin.go | namespace
namespacePrefix = []string{nsVendor, nsClass, nsType}
metricsKind = []string{
"space_free",
"space_reserved",
"space_used",
"space_percent_free",
"space_percent_reserved",
"space_percent_used",
"inodes_free",
"inodes_reserved",
"inodes_used",
"inodes_percent_free",
"inodes_percent... | (elt string, name string) []string {
var suffix = []string{elt, name}
return append(namespacePrefix, suffix...)
}
// GetConfigPolicy returns config policy
// It returns error in case retrieval was not successful
func (p *dfCollector) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {
cp := cpolicy.New()
rule, _ :=... | createNamespace | identifier_name |
plugin.go | namespace
namespacePrefix = []string{nsVendor, nsClass, nsType}
metricsKind = []string{
"space_free",
"space_reserved",
"space_used",
"space_percent_free",
"space_percent_reserved",
"space_percent_used",
"inodes_free",
"inodes_reserved",
"inodes_used",
"inodes_percent_free",
"inodes_percent... |
return nil
}
// GetMetricTypes returns list of available metric types
// It returns error in case retrieval was not successful
func (p *dfCollector) GetMetricTypes(cfg plugin.ConfigType) ([]plugin.MetricType, error) {
mts := []plugin.MetricType{}
for _, kind := range metricsKind {
mts = append(mts, plugin.Metric... | {
procPathStats, err := os.Stat(procPath.(string))
if err != nil {
return err
}
if !procPathStats.IsDir() {
return errors.New(fmt.Sprintf("%s is not a directory", procPath.(string)))
}
p.proc_path = procPath.(string)
} | conditional_block |
plugin.go | namespace
namespacePrefix = []string{nsVendor, nsClass, nsType}
metricsKind = []string{
"space_free",
"space_reserved",
"space_used",
"space_percent_free",
"space_percent_reserved",
"space_percent_used",
"inodes_free",
"inodes_reserved",
"inodes_used",
"inodes_percent_free",
"inodes_percent... | // GetMetricTypes returns list of available metric types
// It returns error in case retrieval was not successful
func (p *dfCollector) GetMetricTypes(cfg plugin.ConfigType) ([]plugin.MetricType, error) {
mts := []plugin.MetricType{}
for _, kind := range metricsKind {
mts = append(mts, plugin.MetricType{
Namespa... | }
| random_line_split |
plugin.go | namespace
namespacePrefix = []string{nsVendor, nsClass, nsType}
metricsKind = []string{
"space_free",
"space_reserved",
"space_used",
"space_percent_free",
"space_percent_reserved",
"space_percent_used",
"inodes_free",
"inodes_reserved",
"inodes_used",
"inodes_percent_free",
"inodes_percent... |
// GetConfigPolicy returns config policy
// It returns error in case retrieval was not successful
func (p *dfCollector) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {
cp := cpolicy.New()
rule, _ := cpolicy.NewStringRule("proc_path", false, "/proc")
node := cpolicy.NewPolicyNode()
node.Add(rule)
cp.Add([]stri... | {
var suffix = []string{elt, name}
return append(namespacePrefix, suffix...)
} | identifier_body |
aes.rs | fn disable(self) -> AES {
// Disable AES
self.aes.aes.cr.modify(|_, w| w.en().clear_bit());
self.aes
}
}
/// Can be used to write data to the AES peripheral
///
/// You can access this struct via [`Stream`].
pub struct Tx(());
impl Tx {
/// Write a block to the AES peripheral
///... | <Buffer, Channel>(
self,
dma: &mut dma::Handle,
buffer: Pin<Buffer>,
channel: Channel,
) -> Transfer<Self, Channel, Buffer, dma::Ready>
where
Self: dma::Target<Channel>,
Buffer: Deref + 'static,
Buffer::Target: AsSlice<Element = u8>,
Channel: dma::... | write_all | identifier_name |
aes.rs | }
}
/// An active encryption/decryption stream
///
/// You can get an instance of this struct by calling [`AES::enable`].
pub struct Stream {
aes: AES,
/// Can be used to write data to the AES peripheral
pub tx: Tx,
/// Can be used to read data from the AES peripheral
pub rx: Rx,
}
impl Stre... | rx: Rx(()),
tx: Tx(()),
} | random_line_split | |
peer.rs | _msg, make_id_bytes};
use super::types::*;
static CONNECT_TIMEOUT: u64 = 3000;
// Each peer should have one of these, and they should be consistent across
// nodes.
pub struct NetPeer<'a> {
pub id: u64,
pub conf: NetPeerConfig<'a>,
// If we have an open connection to this peer, then this will be Some(...)... | (&mut self) {
match self.mgmt_port.try_recv() {
Ok(msg) => {
match msg {
AttachStreamMsg(id, mut stream) => {
if id == self.conf.id {
self.attach_stream(stream);
}
}
... | check_mgmt_msg | identifier_name |
peer.rs | _msg, make_id_bytes};
use super::types::*;
static CONNECT_TIMEOUT: u64 = 3000;
// Each peer should have one of these, and they should be consistent across
// nodes.
pub struct NetPeer<'a> {
pub id: u64,
pub conf: NetPeerConfig<'a>,
// If we have an open connection to this peer, then this will be Some(...)... |
fn new(id: u64, config: NetPeerConfig, to_raft: Sender<RaftMsg>, mgmt_port: Receiver<MgmtMsg>) -> NetPeer {
NetPeer {
id: id,
conf: config,
stream: None,
to_raft: to_raft,
mgmt_port: mgmt_port,
shutdown: false,
}
}
f... | {
let (mgmt_send, mgmt_port) = channel();
let conf = conf.clone();
spawn(proc() {
let mut netpeer = NetPeer::new(id, conf, to_raft, mgmt_port);
netpeer.peer_loop();
});
mgmt_send
} | identifier_body |
peer.rs | _msg, make_id_bytes};
use super::types::*;
static CONNECT_TIMEOUT: u64 = 3000;
// Each peer should have one of these, and they should be consistent across
// nodes.
pub struct NetPeer<'a> {
pub id: u64,
pub conf: NetPeerConfig<'a>,
// If we have an open connection to this peer, then this will be Some(...)... | break;
}
}
let mut replies = 0;
// We should get the votes back out on the port that we were waiting on
| stream.write(vote_bytes);
count += 1;
debug!("[test_spawn()] Sent {} vote requests.", count);
if count > 1 { | random_line_split |
peer.rs | _msg, make_id_bytes};
use super::types::*;
static CONNECT_TIMEOUT: u64 = 3000;
// Each peer should have one of these, and they should be consistent across
// nodes.
pub struct NetPeer<'a> {
pub id: u64,
pub conf: NetPeerConfig<'a>,
// If we have an open connection to this peer, then this will be Some(...)... |
StopMsg => {
self.shutdown = true;
self.stream = None;
}
}
}
_ => {
}
}
}
/*
* Send an RPC up to Raft, waiting for a reply if we need to.
*/
fn send... | {
if self.stream.is_some() {
self.send_rpc(rpc, self.stream.clone().unwrap());
}
} | conditional_block |
import_videos.py | (signal.SIGINT, stop_thread_handler)
def next_video_id(current, path):
existing = Video.objects.filter(path=path)
if existing:
return existing[0].video_id, current
current += 1
return current, current
def create_task_list(path_list):
"""
Walks path recursively, and create a task list
... | :param rating: rating of the video, highest by default.
"""
self.video_id = video_id
self.base_path = base_path
self.file_path = path
self.rating = rating
def import_worker(thread_index):
"""
Thread worker that deals with tasks.
:return:
"""
THREAD_S... | """
Create an import task object.
:param video_id: a pre-allocated video_id in number, so we don't need to lock db in multiple thread.
:param base_path: path prefix that will be ignored when creating keywords from path.
:param path: path of the file | random_line_split |
import_videos.py | .SIGINT, stop_thread_handler)
def next_video_id(current, path):
existing = Video.objects.filter(path=path)
if existing:
return existing[0].video_id, current
current += 1
return current, current
def create_task_list(path_list):
"""
Walks path recursively, and create a task list
:pa... |
duration = float(duration)
flip_num = float(flip_num)
interval = duration / flip_num
if interval <= 0.0:
tlog = get_logger(current_thread().name)
tlog.error("Cannot | return True | conditional_block |
import_videos.py | (current_video_id, file_path)
task_list.append(ImportTask(video_id, base_path, file_path, rating))
except:
log.error('#Error while proceeding: {0}'.format(file_name))
exc_type, exc_value, exc_traceback = sys.exc_info()
t... | convert_video_to_mp4 | identifier_name | |
import_videos.py | .SIGINT, stop_thread_handler)
def next_video_id(current, path):
existing = Video.objects.filter(path=path)
if existing:
return existing[0].video_id, current
current += 1
return current, current
def create_task_list(path_list):
"""
Walks path recursively, and create a task list
:pa... |
def gen_thumb(video_path, thumb_path):
"""
Generate thumb image for the given video, and grabs duration from output
:return: (success, duration)
"""
if os.path.isfile(thumb_path):
os.remove(thumb_path)
global THUMB_SIZE
cmd = ['ffmpeg', '-itsoffset', '-5', '-i', video_path, '-vfr... | return './static/cover/' + str(fn) + '.png' | identifier_body |
DoJetFakeFactors.py |
import ROOT
from array import array
import random
from SampleManager import SampleManager
from SampleManager import Sample
ROOT.gROOT.SetBatch(False)
samplesFF = None
samplesData = None
def main() :
global samplesFF
global samplesData
if not options.baseDir.count('/eos/') and not os.path.isdir( optio... |
samplesData.create_hist( samp[0], var, draw_cmd_LT, (100, 0, 500 ) )
LT_hist = samp[0].hist.Clone( 'lt_hist' )
for idx, min in enumerate( ptbins[0:-1] ) :
max = ptbins[idx+1]
bin_lead = ( r1, min, max )
bin_subl = ( r2, 15, max )
LL_count = LL... | draw_cmd_base = 'mu_passtrig25_n>0 && mu_n==1 && ph_n > 1 && dr_ph1_ph2 > 0.3 && m_ph1_ph2>15 && dr_ph1_leadLep>0.4 && dr_ph2_leadLep>0.4 && ph_hasPixSeed[0]==0 && ph_hasPixSeed[1]==0 '
samp = samplesData.get_samples(name='Muon')
for r1,r2 in regions :
draw_cmd = draw_cmd_base + ' && is%s_leadph12... | identifier_body |
DoJetFakeFactors.py | 1.5 && neuIsoCorr_leadph12 < 1.0 && phoIsoCorr_leadph12 < 0.7 && chIsoCorr_sublph12 > 1.5 && neuIsoCorr_sublph12 > 1.0 && phoIsoCorr_sublph12 > 0.7 && chIsoCorr_sublph12 < %d && neuIsoCorr_sublph12 < %d && phoIsoCorr_sublph12 < %d && sieie_leadph12 < 0.011 && sieie_sublph12 > 0.011' %(draw_cmd, loose_cuts[0], loose_cu... | bin = (reg, 15, max )
if bin in output :
continue
num_count = num_hist.Integral( num_hist.FindBin( 15), num_hist.FindBin(max ) - 1 )
den_count = den_hist.Integral( den_hist.FindBin( 15), den_hist.FindBin(max ) - 1 )
factor = num_count/den_count
... | conditional_block | |
DoJetFakeFactors.py | _path_model=options.baseDirModel, xsFile=options.xsFile, lumi=options.lumi, readHists=options.readHists, quiet=options.quiet)
base_dir_data = '/afs/cern.ch/work/j/jkunkle/private/CMS/Wgamgam/Output/LepGammaGammaNoPhID_2014_10_29'
samplesData = SampleManager(base_dir_data, options.treeName,filename=option... | ApplySinglePhotonFF | identifier_name | |
DoJetFakeFactors.py | imp
import ROOT
from array import array
import random
from SampleManager import SampleManager
from SampleManager import Sample
ROOT.gROOT.SetBatch(False)
samplesFF = None
samplesData = None
def main() :
global samplesFF
global samplesData
if not options.baseDir.count('/eos/') and not os.path.isdir( o... | N_FF_TT = LL_count*ff_lead*ff_subl
print 'Lead pt = %d - %d, subl pt = %d - %d' %( min, max, 15, max )
print 'N_LL = ', LL_count
print 'N_LT = ', LT_count
print 'N_TL = ', TL_count
| N_FR_TT = N_FR_LT*ff_lead | random_line_split |
huffman.rs | ().max().unwrap_or(0),
safely_peek_bitwidth,
eob_symbol,
);
builder.restore_canonical_huffman_codes(bitwidthes)
}
pub fn safely_peek_bitwidth(&self) -> Option<u8> {
self.safely_peek_bitwidth
}
}
impl Builder for DecoderBuilder {
type Instance = Decoder;
... | {
z.extend(x);
break;
} | conditional_block | |
huffman.rs | , bitwidthes: &[u8]) -> io::Result<Self::Instance> {
debug_assert!(!bitwidthes.is_empty());
let mut symbols = bitwidthes
.iter()
.enumerate()
.filter(|&(_, &code_bitwidth)| code_bitwidth > 0)
.map(|(symbol, &code_bitwidth)| (symbol as u16, code_bitwidth))... | {
table: Vec<u16>,
eob_symbol: Option<u16>,
safely_peek_bitwidth: Option<u8>,
max_bitwidth: u8,
}
impl DecoderBuilder {
pub fn new(
max_bitwidth: u8,
safely_peek_bitwidth: Option<u8>,
eob_symbol: Option<u16>,
) -> Self {
debug_assert!(max_bitwidth <= MAX_BITWIDTH... | DecoderBuilder | identifier_name |
huffman.rs | , bitwidthes: &[u8]) -> io::Result<Self::Instance> {
debug_assert!(!bitwidthes.is_empty());
let mut symbols = bitwidthes
.iter()
.enumerate()
.filter(|&(_, &code_bitwidth)| code_bitwidth > 0)
.map(|(symbol, &code_bitwidth)| (symbol as u16, code_bitwidth))... | EncoderBuilder {
table: vec![Code::new(0, 0); symbol_count],
}
}
pub fn from_bitwidthes(bitwidthes: &[u8]) -> io::Result<Encoder> {
let symbol_count = bitwidthes
.iter()
.enumerate()
.filter(|e| *e.1 > 0)
.last()
.ma... | pub struct EncoderBuilder {
table: Vec<Code>,
}
impl EncoderBuilder {
pub fn new(symbol_count: usize) -> Self { | random_line_split |
huffman.rs | bitwidthes: &[u8]) -> io::Result<Self::Instance> {
debug_assert!(!bitwidthes.is_empty());
let mut symbols = bitwidthes
.iter()
.enumerate()
.filter(|&(_, &code_bitwidth)| code_bitwidth > 0)
.map(|(symbol, &code_bitwidth)| (symbol as u16, code_bitwidth))
... |
fn finish(self) -> Self::Instance {
Encoder { table: self.table }
}
}
#[derive(Debug, Clone)]
pub struct Encoder {
table: Vec<Code>,
}
impl Encoder {
#[inline(always)]
pub fn encode<W>(&self, writer: &mut bit::BitWriter<W>, symbol: u16) -> io::Result<()>
where
W: io::Write,
... | {
debug_assert_eq!(self.table[symbol as usize], Code::new(0, 0));
self.table[symbol as usize] = code.inverse_endian();
Ok(())
} | identifier_body |
views.py | staff_member_required(login_url='login')
@method_decorator(Alter_login_required,name='dispatch') | start=request.GET.get('start') #获取时间控件开始时间
end =request.GET.get('end') #获取时间控件结束时间
cxtj =request.GET.get('cxtj') #获取查询条件录入信息
#request.GET.get(参数,默认值)
#这个参数是只有没有传递参数的时候才会使用
#如果传递了,但是是一个空的字符串,也不会使用,那么可以使用 ('ReviewStatus',0) or 0
reviewStatus = int(request.GET.get('R... | # @method_decorator(permission_required('Alter_management.change_alter_managment',login_url='/alter/index/'),name="dispatch")
class Alter_manager_newview(View):#变更管理页面,返回数据
def get(self,request):
#request.GET.get获取出来的数据都是字符串类型
page = int(request.GET.get('p',1))#获当前页数,并转换成整形,没有传默认为1 | random_line_split |
views.py | iew):#变更管理页面,返回数据
# def Alter_manager_view (request):#变更管理页面,返回数据
# Alterd_datas=Alter_managment.objects.all()
# context={
# 'Alterd_datas':Alterd_datas
# }
# return render(request,"Alter_management/Alter.html",context=context)
# * @函数名: Alter_manager_newview
# * @功能描述: 变更... | iew(V | identifier_name | |
views.py | 页的页码
'left_pages': left_pages,
# right_pages:代表的是当前这页的右边的页的页码
'right_pages': right_pages,
'current_page': current_page,
'left_has_more': left_has_more,
'right_has_more': right_has_more,
'num_pages': num_pages,
'start_num':st... | conditional_block | ||
views.py | staff_member_required(login_url='login')
@method_decorator(Alter_login_required,name='dispatch')
# @method_decorator(permission_required('Alter_management.change_alter_managment',login_url='/alter/index/'),name="dispatch")
class Alter_manager_newview(View):#变更管理页面,返回数据
def get(self,request):
#request.GET.ge... | # # * @作者: 郭军
# # * @时间: 2019-6-30 15:28:19
# # * @最后编辑时间: 2019-9-3 10:00:36
# # * @最后编辑者: 郭军
class add_Alter_managerView(View):
def get(self,request):
Databases=Alt_Database.objects.all()
context={
'Databases':Databases
}
return render(request,'Alter... | 1:02
# * @最后编辑者: 郭军
@require_POST
@Alter_login_required
def delete_Alter_manager(request):#变更内容删除用
if request.user.has_perm('Alter_management.change_alter_managment'):
id=request.POST.get("id")
try:
Alter_managment.objects.filter(id=id).delete()
Alter_managment_checked.object... | identifier_body |
simpletests.py |
def aLeadKey(email=None,id=None):
leadkey = mc.factory.create("LeadKey")
if email:
leadkey.keyType = "EMAIL"
leadkey.keyValue = email
elif id:
leadkey.keyType = "IDNUM"
leadkey.keyValue = id
return leadkey
def aLeadKeyArray(leads):
lka = mc.factory.create("ArrayOfL... | asa = mc.factory.create("ArrayOfString")
asa.stringItem = strings
return asa | identifier_body | |
simpletests.py | anAttrib(**kwargs):
attrib = mc.factory.create("Attrib")
for key, value in kwargs.items():
setattr(attrib, key, value)
return attrib
def anAttribArray(attribs):
aa = mc.factory.create("ArrayOfAttrib")
aa.attrib=attribs
return aa
def anAttribute(**kwargs):
attrib = mc.factory.creat... | # <xs:enumeration value="OpenEmail"/>
# <xs:enumeration value="ClickEmail"/>
# <xs:enumeration value="NewLead"/>
# <xs:enumeration value="ChangeDataValue"/>
# <xs:enumeration value="LeadAssigned"/>
# <xs:enumeration value="NewSFDCOpprtnty"/>
# <xs:enumeration value="Wait"/>
# <xs:enumeration value="RunSubflow"/>
# <xs:... | # <xs:enumeration value="AttendEvent"/>
# <xs:enumeration value="SendEmail"/>
# <xs:enumeration value="EmailDelivered"/>
# <xs:enumeration value="EmailBounced"/>
# <xs:enumeration value="UnsubscribeEmail"/> | random_line_split |
simpletests.py | marketoCookie, )
# Untested: syncMObjects(ArrayOfMObject mObjectList, SyncOperationEnum operation, )
# Tested: syncMultipleLeads(ArrayOfLeadRecord leadRecordList, xs:boolean dedupEnabled, )
# Campaign sources
# <xs:enumeration value="MKTOWS"/>
# <xs:enumeration value="SALES"/>
def test_getCampaignsForSource():
p... | test_listOperation | identifier_name | |
simpletests.py | , ArrayOfString includeAttributes, )
# Tested: getLead(LeadKey leadKey, )
# Tested: getLeadActivity(LeadKey leadKey, ActivityTypeFilter activityFilter, StreamPosition startPosition, xs:int batchSize, )
# Tested: getLeadChanges(StreamPosition startPosition, ActivityTypeFilter activityFilter, xs:int batchSize, )
# getMOb... | attrs = attrs2dict(lead.leadAttributeList)
print "Lead", lead.Id, lead.Email
pprint(attrs) | conditional_block | |
post.rs | >(ctxt: &mut C, table: &Header) -> Result<(), WriteError> {
I32Be::write(ctxt, table.version)?;
I32Be::write(ctxt, table.italic_angle)?;
I16Be::write(ctxt, table.underline_position)?;
I16Be::write(ctxt, table.underline_thickness)?;
U32Be::write(ctxt, table.is_fixed_pitch)?;
... | "florin",
"approxequal",
"Delta",
| "radical", | random_line_split |
post.rs | `glyph_index`.
///
/// **Note:** Some fonts map more than one glyph to the same name so don't assume names are
/// unique.
pub fn glyph_name(&self, glyph_index: u16) -> Result<Option<&'a str>, ParseError> {
if let Some(sub_table) = &self.opt_sub_table {
if glyph_index >= sub_table.n... | {
// Build a post table with unused name entries
let mut w = WriteBuffer::new();
let header = Header {
version: 0x00020000,
italic_angle: 0,
underline_position: 0,
underline_thickness: 0,
is_fixed_pitch: 0,
min_mem_type_42: ... | identifier_body | |
post.rs | ctxt: &mut C, table: &Header) -> Result<(), WriteError> {
I32Be::write(ctxt, table.version)?;
I32Be::write(ctxt, table.italic_angle)?;
I16Be::write(ctxt, table.underline_position)?;
I16Be::write(ctxt, table.underline_thickness)?;
U32Be::write(ctxt, table.is_fixed_pitch)?;
... | <C: WriteContext>(ctxt: &mut C, table: &SubTable<'a>) -> Result<(), WriteError> {
U16Be::write(ctxt, table.num_glyphs)?;
<&ReadArray<'_, _>>::write(ctxt, &table.glyph_name_index)?;
for name in &table.names {
PascalString::write(ctxt, name)?;
}
Ok(())
}
}
impl<'a... | write | identifier_name |
viewer.js | return results;
}
// Public: Creates an element for viewing annotations.
var Viewer = exports.Viewer = Widget.extend({
// Public: Creates an instance of the Viewer object.
//
// options - An Object containing options.
//
// Examples
//
// # Creates a new viewer, adds a custom field... | {
cond = $.extend({}, cond, {rel: rel});
var results = [];
for (var i = 0, len = data.length; i < len; i++) {
var d = data[i],
match = true;
for (var k in cond) {
if (cond.hasOwnProperty(k) && d[k] !== cond[k]) {
match = false;
break;... | identifier_body | |
viewer.js | 'undefined' &&
links[0].href !== null);
if (hasValidLink) {
link.attr('href', links[0].href);
} else {
link.remove();
}
var controller = {};
if (this.options.permitEdit(annotation)) {
controller.showEdit = functio... | {
options.permitEdit = function (annotation) {
return authz.permits('update', annotation, ident.who());
};
} | conditional_block | |
viewer.js |
if (match) {
results.push(d);
}
}
return results;
}
// Public: Creates an element for viewing annotations.
var Viewer = exports.Viewer = Widget.extend({
// Public: Creates an instance of the Viewer object.
//
// options - An Object containing options.
//
// E... | if (cond.hasOwnProperty(k) && d[k] !== cond[k]) {
match = false;
break;
}
} | random_line_split | |
viewer.js | (data, rel, cond) {
cond = $.extend({}, cond, {rel: rel});
var results = [];
for (var i = 0, len = data.length; i < len; i++) {
var d = data[i],
match = true;
for (var k in cond) {
if (cond.hasOwnProperty(k) && d[k] !== cond[k]) {
match = false;
... | parseLinks | identifier_name | |
motorhead.go | case msg := <-rtm.IncomingEvents:
switch ev := msg.Data.(type) {
case *slack.ConnectedEvent:
fmt.Println("Connection counter:", ev.ConnectionCount)
case *slack.MessageEvent:
channelInfo, err := api.GetChannelInfo(ev.Channel)
if err != nil {
log.Println(err)
}
botCentral := &BotCent... | Loop:
for {
select { | random_line_split | |
motorhead.go | (c chan ReplyChannel, sc chan StandupChannel) {
commands := map[string]string{
"help": "see the available commands",
"play": "play some tunes LENNY !",
"stop": "pause|stop da music",
"next": "next tune LENNY, this ain't any good",
"previous": "dat tune was ace, play it again LENNY",
"a... | handleCommands | identifier_name | |
motorhead.go | "play": "play some tunes LENNY !",
"stop": "pause|stop da music",
"next": "next tune LENNY, this ain't any good",
"previous": "dat tune was ace, play it again LENNY",
"add": "queue dis beats",
"list": "list me current tunes",
"set-time": "When's my set time ?",
"set-times": "... | else {
for i := 2; i < len(commandArray); i++ {
genresSeeds = append(genresSeeds, commandArray[i])
}
}
case "current":
cp, _ := client.PlayerCurrentlyPlaying()
attachment := slack.Attachment{
Pretext: cp.Item.Name,
Text: cp.Item.Artists[0].Name,
Color: "#85929E",
}
replyC... | {
attachments := make([]slack.Attachment, 0)
genres, _ := client.GetAvailableGenreSeeds()
for i := 1; i < 5; i++ {
rand.Seed(time.Now().UTC().UnixNano())
genre := genres[rand.Intn(len(genres))]
attachment := slack.Attachment{
Text: fmt.Sprintf("added genre %s", genre),
}
atta... | conditional_block |
motorhead.go | ":
trackId := commandArray[2]
client.AddTracksToPlaylist(userId, playlistId, spotify.ID(trackId))
attachment := slack.Attachment{
Pretext: "Added da track",
Color: "#85929E",
}
replyChannel.Attachments = []slack.Attachment{attachment}
c <- replyChannel
case "list":
attachments := make... | {
var replyChannel ReplyChannel
for {
sc := <-standupChannel
replyChannel.Channel = sc.Channel
attachment := slack.Attachment{
Pretext: "Set time engaged",
Text: fmt.Sprintf("I will blast some tunes at %s", sc.StandupTime.Format("3:04PM")),
}
setTime := sc.StandupTime.Format("15:04")
newcron :... | identifier_body | |
main.rs | &str = "app_data";
const STATUS_VALUES: &[&str] = &[
"Operational",
"Degraded Performance",
"Partial Outage",
"Major Outage",
"Maintenance",
"Not Available",
];
#[derive(Serialize, Deserialize, Debug)]
struct Coordinates {
x: u32,
y: u32,
latitude: f64,
longitude: f64,
}
#[de... |
let modified_pop_status= modified_pop_status_opt.unwrap();
let mut modified_pop_status_map: HashMap<String, u8> =
serde_json::from_str(modified_pop_status.as_str()).unwrap();
let query_params: Vec<(String, String)> = req.get_query().unwrap();
println!("... | {
return Ok(Response::from_status(StatusCode::IM_A_TEAPOT)
.with_body_text_plain("Problem accessing API\n"));
} | conditional_block |
main.rs | &str = "app_data";
const STATUS_VALUES: &[&str] = &[
"Operational",
"Degraded Performance",
"Partial Outage",
"Major Outage",
"Maintenance",
"Not Available",
];
#[derive(Serialize, Deserialize, Debug)]
struct Coordinates {
x: u32,
y: u32,
latitude: f64,
longitude: f64,
}
#[de... | {
current_pop: String,
pop_status_data: Vec<PopStatusData>,
}
#[derive(Serialize, Deserialize, Debug)]
struct DictionaryInfo {
dictionary_id: String,
service_id: String,
item_key: String,
item_value: String,
}
/// The entry point for your application.
///
/// This function is triggered when y... | PopStatusResponse | identifier_name |
main.rs | : &str = "app_data";
const STATUS_VALUES: &[&str] = &[
"Operational",
"Degraded Performance",
"Partial Outage",
"Major Outage",
"Maintenance",
"Not Available",
];
#[derive(Serialize, Deserialize, Debug)]
struct Coordinates {
x: u32,
y: u32,
latitude: f64,
longitude: f64,
}
#[d... | group: pop.group.to_string(),
shield: shield.to_string(),
status,
}
})
.collect();
let pop_status_response: PopStatusResponse = PopStatusResponse {
current_pop,
... | latitude: pop.coordinates.latitude,
longitude: pop.coordinates.longitude, | random_line_split |
1-built-in-function.py | 12]
# list(map(lambda x,y:x+y,a,b))
# Out[4]:
# [6, 8, 10, 12]
# In [5]:
# # Now all three lists
# list(map(lambda x,y,z:x+y+z,a,b,c))
# Out[5]:
# [15, 18, 21, 24]
# We can see in the example above that the parameter x gets its values from the list a, while y gets its values from b and z from list c. Go ahead a... | # zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables.
# Let's see it in action in some examples:
# Examples
# In [1]:
# x = [1,2,3]
# y = [4,5,6]
# # Zip the lists together
# list(zip(x,y))
# Out[1]:
# [(1, 4), (2, 5), (3, 6)]
# Note... | # yield tuple(result)
| random_line_split |
merge_registry_pr.py | _registry_pr.py (see config env vars below)
#
# This script is inspired by Spark merge script and also borrow some codes from Kafka.
#
# This utility assumes you already have a local Registry git folder and that you
# have added remotes corresponding to both (i) the pull repository (which pull requests are available... | (prompt):
result = raw_input("\n%s (y/n): " % prompt)
if result.lower() != "y":
fail("Okay, exiting")
def clean_up():
print("Restoring head pointer to %s" % original_head)
run_cmd("git checkout %s" % original_head)
branches = run_cmd("git branch").replace(" ", "").split("\n")
for bra... | continue_maybe | identifier_name |
merge_registry_pr.py | _registry_pr.py (see config env vars below)
#
# This script is inspired by Spark merge script and also borrow some codes from Kafka.
#
# This utility assumes you already have a local Registry git folder and that you
# have added remotes corresponding to both (i) the pull repository (which pull requests are available... | try:
run_cmd(['git', 'merge', pr_branch_name, '--squash'])
except Exception as e:
msg = "Error merging: %s\nWould you like to manually fix-up this merge?" % e
continue_maybe(msg)
msg = "Okay, please fix any conflicts and 'git add' conflicting files... Finished?"
continue_... |
had_conflicts = False | random_line_split |
merge_registry_pr.py | _registry_pr.py (see config env vars below)
#
# This script is inspired by Spark merge script and also borrow some codes from Kafka.
#
# This utility assumes you already have a local Registry git folder and that you
# have added remotes corresponding to both (i) the pull repository (which pull requests are available... |
merge_message_flags += ["-m", close_line]
if should_list_commits:
merge_message_flags += ["-m", "\n".join(commits)]
run_cmd(['git', 'commit', '--author="%s"' % primary_author] + merge_message_flags)
result = raw_input("Merge complete (local ref %s). Push to %s? (y/n)" %
... | close_line += " and squashes the following commits:" | conditional_block |
merge_registry_pr.py | _registry_pr.py (see config env vars below)
#
# This script is inspired by Spark merge script and also borrow some codes from Kafka.
#
# This utility assumes you already have a local Registry git folder and that you
# have added remotes corresponding to both (i) the pull repository (which pull requests are available... |
def run_cmd(cmd):
print(cmd)
try:
if isinstance(cmd, list):
return subprocess.check_output(cmd)
else:
return subprocess.check_output(cmd.split(" "))
except subprocess.CalledProcessError as e:
print("CallProcessError occurred. More information for process is... | print(msg)
clean_up()
sys.exit(-1) | identifier_body |
spike_generators.rs | T,
idx: usize,
spike_voltage: I,
}
impl<T: From<si::Second<f64>>, I> SpikeAtTimes<T, I> {
/// Makes a new input neuron that shall spike at the given times,
/// spiking at the given rate.
///
/// The tolerance is in case of floating-point imprecision or a
/// time-step that doesn't exactly... |
}
impl<T, V> InputSpikeGenerator<V, T> for SpikeAtTimes<T, V>
where
// TODO: alias this as a trait?
T: From<si::Second<f64>>
+ Copy
+ PartialOrd<T>
+ std::ops::AddAssign
+ std::ops::Sub<Output = T>
+ std::ops::Neg<Output = T>,
... | {
if self.did_spike() {
self.spike_voltage.into()
} else {
(0.0 * si::V).into()
}
} | identifier_body |
spike_generators.rs | T,
idx: usize,
spike_voltage: I,
}
impl<T: From<si::Second<f64>>, I> SpikeAtTimes<T, I> {
/// Makes a new input neuron that shall spike at the given times,
/// spiking at the given rate.
///
/// The tolerance is in case of floating-point imprecision or a
/// time-step that doesn't exactly... | <'a>(
slot_starts_to_rate: &'a mut Vec<(T, i32)>,
) -> Box<dyn Fn(T) -> Option<(i32, T)> + 'a> {
slot_starts_to_rate.sort_unstable_by(|a, b| {
let (t1, r1) = a;
let (t2, r2) = b;
match t1.partial_cmp(t2) {
Option::None |... | rate_fn_of_times | identifier_name |
spike_generators.rs | T,
idx: usize,
spike_voltage: I,
}
impl<T: From<si::Second<f64>>, I> SpikeAtTimes<T, I> {
/// Makes a new input neuron that shall spike at the given times,
/// spiking at the given rate.
///
/// The tolerance is in case of floating-point imprecision or a
/// time-step that doesn't exactly... |
}
}
impl<T, V> InputSpikeGenerator<V, T> for SpikeAtTimes<T, V>
where
// TODO: alias this as a trait?
T: From<si::Second<f64>>
+ Copy
+ PartialOrd<T>
+ std::ops::AddAssign
+ std::ops::Sub<Output = T>
+ std::ops::Neg<Output... | {
(0.0 * si::V).into()
} | conditional_block |
spike_generators.rs | : T,
idx: usize,
spike_voltage: I,
}
impl<T: From<si::Second<f64>>, I> SpikeAtTimes<T, I> {
/// Makes a new input neuron that shall spike at the given times,
/// spiking at the given rate.
///
/// The tolerance is in case of floating-point imprecision or a
/// time-step that doesn't exactl... | ) -> Box<dyn Fn(T) -> Option<(i32, T)> + 'a> {
slot_starts_to_rate.sort_unstable_by(|a, b| {
let (t1, r1) = a;
let (t2, r2) = b;
match t1.partial_cmp(t2) {
Option::None | Option::Some(Ordering::Equal) => r1.cmp(r2),
... | slot_starts_to_rate: &'a mut Vec<(T, i32)>, | random_line_split |
utils.ts | -disable-next-line no-loop-func
describe(msg, () => {
describeFn(`test repeat ${k + 1} of ${TEST_REPEATS}`, fn)
})
}
}
describeRepeats.skip = (msg: any, fn: any) => {
describe.skip(`${msg} – test repeat ALL of ${TEST_REPEATS}`, fn)
}
describeRepeats.only = (msg: any, fn: any) => {
... | export function addAfterFn() {
const afterFns: any[] = []
afterEach(async () => {
const fns = afterFns.slice()
afterFns.length = 0
// @ts-expect-error
AggregatedError.throwAllSettled(await Promise.allSettled(fns.map((fn) => fn())))
})
return (fn: any) => {
afterF... | const addAfter = addAfterFn()
return (...args: Parameters<typeof setTimeout>) => {
const t = setTimeout(...args)
addAfter(() => {
clearTimeout(t)
})
return t
}
}
| identifier_body |
utils.ts | -disable-next-line no-loop-func
describe(msg, () => {
describeFn(`test repeat ${k + 1} of ${TEST_REPEATS}`, fn)
})
}
}
describeRepeats.skip = (msg: any, fn: any) => {
describe.skip(`${msg} – test repeat ALL of ${TEST_REPEATS}`, fn)
}
describeRepeats.only = (msg: any, fn: any) => {
... | /* eslint-disable no-await-in-loop */
return async (publishRequest: any, opts = {}) => {
const {
streamId,
streamPartition = 0,
interval = 500,
timeout = 10000,
count = 100,
messageMatchFn = defaultMessageMatchFn
} = validat... | return JSON.stringify(msgGot.content) === JSON.stringify(msgTarget.streamMessage.getParsedContent())
}
export function getWaitForStorage(client: StreamrClient, defaultOpts = {}) { | random_line_split |
utils.ts | Last({
// @ts-expect-error
streamId,
streamPartition,
count,
})
for (const lastMsg of last) {
if (messageMatchFn(publishRequest, lastMsg)) {
found = true
return
... | eckNoLeaks() | identifier_name | |
utils.ts | ,
...opts,
})
if (!publishRequest && !publishRequest.streamMessage) {
throw new Error(`should check against publish request for comparison, got: ${inspect(publishRequest)}`)
}
const start = Date.now()
let last: any
// eslint-disable-next-line no-... | return '' }
| conditional_block | |
ask_plan.pb.go | bytes,1,opt,name=size" json:"size,omitempty"`
}
func (m *AskPlanStorage) Reset() { *m = AskPlanStorage{} }
func (m *AskPlanStorage) String() string { return proto.CompactTextString(m) }
func (*AskPlanStorage) ProtoMessage() {}
func (*AskPlanStorage) Descriptor() ([]byte, []i... |
func (m *AskPlanNetwork) GetOverlay() bool {
if m != nil {
return m.Overlay
}
return false
}
func (m *AskPlanNetwork) GetOutbound() bool {
if m != nil {
return m.Outbound
}
return false
}
func (m *AskPlanNetwork) GetIncoming() bool {
if m != nil {
return m.Incoming
}
return false
}
type AskPlanResour... | return nil
} | random_line_split |
ask_plan.pb.go | bytes,1,opt,name=size" json:"size,omitempty"`
}
func (m *AskPlanStorage) Reset() { *m = AskPlanStorage{} }
func (m *AskPlanStorage) String() string { return proto.CompactTextString(m) }
func (*AskPlanStorage) ProtoMessage() {}
func (*AskPlanStorage) Descriptor() ([]byte, []i... | () string { return proto.CompactTextString(m) }
func (*AskPlan) ProtoMessage() {}
func (*AskPlan) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
func (m *AskPlan) GetID() string {
if m != nil {
return m.ID
}
return ""
}
func (m *AskPlan) GetOrderID() *BigInt {
if m !=... | String | identifier_name |
ask_plan.pb.go | bytes,1,opt,name=size" json:"size,omitempty"`
}
func (m *AskPlanStorage) Reset() { *m = AskPlanStorage{} }
func (m *AskPlanStorage) String() string |
func (*AskPlanStorage) ProtoMessage() {}
func (*AskPlanStorage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
func (m *AskPlanStorage) GetSize() *DataSize {
if m != nil {
return m.Size
}
return nil
}
type AskPlanNetwork struct {
ThroughputIn *DataSizeRate `protobuf:"bytes,1,o... | { return proto.CompactTextString(m) } | identifier_body |
ask_plan.pb.go | bytes,1,opt,name=size" json:"size,omitempty"`
}
func (m *AskPlanStorage) Reset() { *m = AskPlanStorage{} }
func (m *AskPlanStorage) String() string { return proto.CompactTextString(m) }
func (*AskPlanStorage) ProtoMessage() {}
func (*AskPlanStorage) Descriptor() ([]byte, []i... |
return IdentityLevel_ANONYMOUS
}
func (m *AskPlan) GetTag() []byte {
if m != nil {
return m.Tag
}
return nil
}
func (m *AskPlan) GetResources() *AskPlanResources {
if m != nil {
return m.Resources
}
return nil
}
func (m *AskPlan) GetStatus() AskPlan_Status {
if m != nil {
return m.Status
}
return As... | {
return m.Identity
} | conditional_block |
log.py | deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright no... | (self):
self._logfile = None
self._logfilename = None
self._verbose = False
self._attrs = None
self._verbose_attrs = None
@staticmethod
def _open_if_needed(filename):
if isinstance(filename, (str, bytes)):
return open(filename, 'w')
else:
... | __init__ | identifier_name |
log.py | deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright no... |
@property
def logfilename(self):
return os.environ.get('MARBLES_LOGFILE', self._logfilename)
@property
def attrs(self):
try:
return os.environ['MARBLES_TEST_CASE_ATTRS'].split(',')
except KeyError:
return self._attrs or ()
@property
def verbose... | if self._logfile:
return self._logfile
if self.logfilename:
self._logfile = self._open_if_needed(self.logfilename)
return self._logfile | identifier_body |
log.py | deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright n... | other attributes of interest specified by the test author.
The captured information includes the assertion's args and kwargs,
msg, note, local variables (for failed assertions, and also for
passing assertions if verbose logging is turned on), and the result of
the assertion.
Configuration is handled via the environme... | assertion called.
If configured, the :data:`marbles.core.log.logger` will log a json
object for each assertion and its success or failure, as well as any | random_line_split |
log.py | deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright no... |
else:
return verbose or ()
def _log_assertion(self, case, assertion, args, kwargs, msg, note,
*exc_info):
if not self.log_enabled:
return
now = datetime.datetime.now()
locals_, module, filename, lineno = _stack.get_stack_info()
... | return verbose_attrs | conditional_block |
fs.rs | "start" => SeekFrom::Start(size as u64),
"end" => SeekFrom::End(size as i64),
"current" | _ => SeekFrom::Current(size as i64),
})
}).unwrap_or(SeekFrom::Current(size as i64));
Ok(this.0.seek(seekfrom).map_err(LuaError::e... | {
let path = src.as_ref();
if !src.as_ref().exists() {
return Err(io::Error::from(io::ErrorKind::NotFound));
}
if !dest.as_ref().exists() {
fs::create_dir(&dest)?;
}
for entry in path.read_dir()? {
let src = entry.map(|e| e.path())?;
let src_name = match src.file_n... | identifier_body | |
fs.rs | &mut LuaFile, _: ()|{
Ok(this.0.flush().map_err(LuaError::external)?)
});
methods.add_method_mut("sync_all", |_, this: &mut LuaFile, _: ()|{
Ok(this.0.sync_all().map_err(LuaError::external)?)
});
methods.add_method_mut("sync_data", |_, this: &mut LuaFile, _: ()|{... | recursive_copy | identifier_name | |
fs.rs | Methods<'lua, Self>>(methods: &mut M) {
methods.add_method_mut("read", |_, this: &mut LuaFile, len: Option<usize>|{
let bytes = match len {
Some(len) => {
let mut bytes = vec![0u8; len];
this.0.read(&mut bytes).map_err(LuaError::external)?;
... | fs::OpenOptions::new()
.write(true)
.create(true)
.open(&path)
.map(|_| ())
.map_err(LuaError::external)
})?)?;
module.set("copy_file", lua.create_function(|_, (src, dest): (String, String)| {
copy_file(src, dest)
})?)?;
// This binding has ... | //TODO: Rename to something suitable other than touch
//Probably deprecate for path:create_file
module.set("touch", lua.create_function( |_, path: String| { | random_line_split |
centrify_desktopapp.go | are ignored)
WorkflowEnabled bool `json:"WorkflowEnabled,omitempty" schema:"workflow_enabled,omitempty"`
}
// DesktopAppParam - desktop app command line parameters
type DesktopAppParam struct {
ParamName string `json:"ParamName,omitempty" schema:"name,omitempty"`
ParamType string `j... | () (map[string]interface{}, error) {
query := "SELECT * FROM Application WHERE 1=1 AND AppType='Desktop'"
if o.Name != "" {
query += " AND Name='" + o.Name + "'"
}
return queryVaultObject(o.client, query)
}
/*
Fetch desktop app
https://developer.centrify.com/reference#post_saasmanage-getapplication
Request bo... | Query | identifier_name |
centrify_desktopapp.go | are ignored)
WorkflowEnabled bool `json:"WorkflowEnabled,omitempty" schema:"workflow_enabled,omitempty"`
}
// DesktopAppParam - desktop app command line parameters
type DesktopAppParam struct {
ParamName string `json:"ParamName,omitempty" schema:"name,omitempty"`
ParamType string `j... | "Version": 1,
"IndexingVersion": 1
},
"Description": "This template allows you to provide single sign-on to a custom desktop application.",
"DesktopAppType": "CommandLine",
"AuthRules": {
"_UniqueKey": "Condition",
"_Value": [],
"Enabled": true,
"_Type": "RowSet"
},
"AppType": ... | "RemoteDesktopUser": "shared_account (demo.lab)",
"CertificateSubjectName": "CN=Centrify Customer Application Signing Certificate",
"ParentDisplayName": null,
"_metadata": { | random_line_split |
centrify_desktopapp.go | ignored)
WorkflowEnabled bool `json:"WorkflowEnabled,omitempty" schema:"workflow_enabled,omitempty"`
}
// DesktopAppParam - desktop app command line parameters
type DesktopAppParam struct {
ParamName string `json:"ParamName,omitempty" schema:"name,omitempty"`
ParamType string `json:... |
if !resp.Success {
return errors.New(resp.Message)
}
fillWithMap(o, resp.Result)
LogD.Printf("Filled object: %+v", o)
return nil
}
// Create function creates a new DesktopApp and returns a map that contains creation result
func (o *DesktopApp) Create() (*restapi.SliceResponse, error) {
var queryArg = make(... | {
return err
} | conditional_block |
centrify_desktopapp.go | ignored)
WorkflowEnabled bool `json:"WorkflowEnabled,omitempty" schema:"workflow_enabled,omitempty"`
}
// DesktopAppParam - desktop app command line parameters
type DesktopAppParam struct {
ParamName string `json:"ParamName,omitempty" schema:"name,omitempty"`
ParamType string `json:... |
// Read function fetches a DesktopApp from source, including attribute values. Returns error if any
func (o *DesktopApp) Read() error {
if o.ID == "" {
return errors.New("error: ID is empty")
}
var queryArg = make(map[string]interface{})
queryArg["_RowKey"] = o.ID
// Attempt to read from an upstream API
resp... | {
s := DesktopApp{}
s.client = c
s.apiRead = "/SaasManage/GetApplication"
s.apiCreate = "/SaasManage/ImportAppFromTemplate"
s.apiDelete = "/SaasManage/DeleteApplication"
s.apiUpdate = "/SaasManage/UpdateApplicationDE"
s.apiPermissions = "/SaasManage/SetApplicationPermissions"
return &s
} | identifier_body |
call.component.ts | : ['./call.component.scss']
})
export class CallComponent implements OnInit{
public peer:any;
public calling:boolean;
public key:string;
public myPeerId:string;
public inCall:boolean;
public mensajeTemp:string;
public recorderWithTimer;
public audioOfCall;
//Tramos de la llamada para al finalizarlos o... | }
this.peer.on('connection',(conn)=>{
conn.on('data',async (data)=>{
if(data.action){
this.finLlamadaMedico.emit();
this.finLlamadaPaciente.emit();
this.inCall = false;
return;
}
if(data.cancelCall){
Swal.close({value:false});
... | // secure:true
}); | random_line_split |
call.component.ts | : ['./call.component.scss']
})
export class CallComponent implements OnInit{
public peer:any;
public calling:boolean;
public key:string;
public myPeerId:string;
public inCall:boolean;
public mensajeTemp:string;
public recorderWithTimer;
public audioOfCall;
//Tramos de la llamada para al finalizarlos o... | async confirm():Promise<boolean>{
let {dismiss} = await Swal.fire({
title:'Seguro desea salir?',
text:'Abandonará una llamada',
showCancelButton:true,
cancelButtonText:'Permanecer aquí',
confirmButtonText:'Seguro que quiero salir',
})
return !dismiss
}
enviarMensaje(){... | event.returnValue = true;
this.cierreVentana.emit();
this.colgar();
}
| identifier_body |
call.component.ts | ['./call.component.scss']
})
export class CallComponent implements OnInit{
public peer:any;
public calling:boolean;
public key:string;
public myPeerId:string;
public inCall:boolean;
public mensajeTemp:string;
public recorderWithTimer;
public audioOfCall;
//Tramos de la llamada para al finalizarlos ob... |
if(data.call){
const audio = new Audio();
audio.src = "https://notificationsounds.com/notification-sounds/goes-without-saying-608/download/mp3";
audio.play();
audio.onended = ()=>{
if(!this.conn){
audio.currentTime = 0;
audio.play(... | {
this.key = data.key;
this.markAsConnected.emit(data.csc);
this.conn = this.peer.connect(data.key);
return;
} | conditional_block |
call.component.ts | ['./call.component.scss']
})
export class CallComponent implements OnInit{
public peer:any;
public calling:boolean;
public key:string;
public myPeerId:string;
public inCall:boolean;
public mensajeTemp:string;
public recorderWithTimer;
public audioOfCall;
//Tramos de la llamada para al finalizarlos ob... | const canvas = document.createElement('canvas');
canvas.width = this.video.nativeElement.videoWidth;
canvas.height = this.video.nativeElement.videoHeight;
canvas.getContext("2d").drawImage(this.video.nativeElement,0,0);
let imgUrl;
canvas.toBlob(async (blob)=>{
imgUrl = window.URL.createOb... | eCapture(){
| identifier_name |
model.py | self.read_weights(weightstr)
## self.featurenames = set(self.weights.iterkeys())
if FLAGS.featstat:
self.print_templates()
def count_knowns_from_train(self, trainfile, devfile):
'''used in training'''
print >> logs, "counting word freqs from %s, unktag=%s" % (t... | self.knowns = set()
self.unk = FLAGS.unk
self.unktag = FLAGS.unktag
self.unkdel = FLAGS.unkdel
assert not (self.unkdel and self.unktag), "UNKDEL and UNKTAG can't be both true"
if FLAGS.svector: # now it is known
global svector
try:
svector... | identifier_body | |
model.py | devunk0 = set()
for line in open(devfile):
for word in line.split():
word = word.strip("()").rsplit("/", 1)[0]
if words[word] <= self.unk and words[word] > 0:
devunk1.add(word)
if ... | del fv[f] | conditional_block | |
model.py | (self, trainfile, devfile):
'''used in training'''
print >> logs, "counting word freqs from %s, unktag=%s" % (trainfile, self.unktag)
stime = time.time()
words = defaultdict(int)
for i, line in enumerate(open(trainfile)):
for word in line.split():
... |
## for freq in sorted(freqs, reverse=True):
## print >> logs, freq, len(freqs[freq]), " ".join(sorted(freqs[freq]))
## print >> logs
self.knowns = set()
for word, freq in words.items():
if freq > self.unk:
self.knowns.add(word)
... | print >> logs, "=0", len(devunk0), " ".join(sorted(devunk0))
## freqs = defaultdict(list)
## for word, freq in words.items():
## freqs[freq].append(word) | random_line_split |
model.py | (self, trainfile, devfile):
'''used in training'''
print >> logs, "counting word freqs from %s, unktag=%s" % (trainfile, self.unktag)
stime = time.time()
words = defaultdict(int)
for i, line in enumerate(open(trainfile)):
for word in line.split():
... | count_knowns_from_train | identifier_name | |
resolver.rs | Function,
// TODO: add more kinds supposedly...
}
pub struct Resolver {
// track what things are currently in scope, for local block scopes
// (global scope is not tracked)
scopes: Vec<HashMap<String, bool>>,
// track if we are currently in a function, and if so what kind
current_fn: FunctionK... |
// exit the current scope
pub fn end_scope(&mut self) {
self.scopes.pop();
}
// declare a variable in the current scope
pub fn declare(&mut self, ident: &Identifier) {
// try to access the top element of the stack
match self.scopes.last_mut() {
// if empty, do ... | {
self.scopes.push(HashMap::new());
} | identifier_body |
resolver.rs | Function,
// TODO: add more kinds supposedly...
}
pub struct Resolver {
// track what things are currently in scope, for local block scopes
// (global scope is not tracked)
scopes: Vec<HashMap<String, bool>>,
// track if we are currently in a function, and if so what kind
current_fn: Functi... | (&mut self, ident: &Identifier) {
// try to access the top element of the stack
match self.scopes.last_mut() {
// if empty, do nothing (don't worry about global vars)
None => (),
Some(scope) => {
// check if this has already been declared
... | declare | identifier_name |
resolver.rs | Function,
// TODO: add more kinds supposedly...
}
pub struct Resolver {
// track what things are currently in scope, for local block scopes
// (global scope is not tracked)
scopes: Vec<HashMap<String, bool>>,
// track if we are currently in a function, and if so what kind
current_fn: Functi... | // variable binding is split into 2 steps - declaring and defining
self.declare(name);
self.visit_expr(expr, env)?;
self.define(name);
}
Stmt::While(ref mut condition_expr, ref mut body) => {
// resolve the condition... | Stmt::Var(name, ref mut expr) => {
// this adds a new entry to the innermost scope | random_line_split |
list-view.js | url: options.url,
data: options.needData ? JSON.stringify(options.data) : "",
success: function(resp) {
console.log('审核结果:' + (resp.success || '') + (resp.msg || ''));
$(dialog).dialog("destroy");
$(grid).trigger("reloadGrid", [{current:true}]);
if(resp.success) {
... | }
if(valid){
$($(e.target).closest('button')).addClass('disabled').find('span').html("<i class='icon-ok'></i> 正在提交...");
me.ajaxRequest(me.getRequestDateSelect(roleGird), this, roleGird);
}
}
}, {
html: "<i class='icon-remove'></i> 取消",
"class" : ... | var $form = $('form.form-total-account-detall');
var validator = $form.validate();
var valid = true;
if(validator && !validator.form()){
valid = false; | random_line_split |
list-view.js | url: options.url,
data: options.needData ? JSON.stringify(options.data) : "",
success: function(resp) {
console.log('审核结果:' + (resp.success || '') + (resp.msg || ''));
$(dialog).dialog("destroy");
$(grid).trigger("reloadGrid", [{current:true}]);
if(resp.success) {
... | end('付款账户');
me.ajaxGetAccount(form, value, $acctSelect);
} else if (value === '2') {
$acctSelect.attr('name', 'inAcctId');
$caption.empty().append('收款账户');
me.ajaxGetAccount(form, value, $acctSelect);
}
});
$select.trigger('change')... | me.ajaxGetAccount(form, value, $acctSelect);
} else if (value === '1') {
$acctSelect.attr('name', 'outAcctId');
$caption.empty().app | conditional_block |
list-view.js | ').find('select');
var $caption = $('#tr_outAcctId').find('.CaptionTD');
var value = $(this).val();
if (value === '0') {
$acctSelect.attr('name', 'outAcctId');
$caption.empty().append('付款账户');
me.ajaxGetAccount(form, value, $acctSelect);
} else if (valu... | identifier_body | ||
list-view.js | ').find('select');
var $caption = $('#tr_outAcctId').find('.CaptionTD');
var value = $(this).val();
if (value === '0') {
$acctSelect.attr('name', 'outAcctId');
$caption.empty().append('付款账户');
me.ajaxGetAccount(form, value, $acctSelect);
} else if (valu... | identifier_name | ||
ACPF_ExportMuRaster.py | arcpy.AddWarning(string)
elif severity == 2:
arcpy.AddMessage(" ")
arcpy.AddError(string)
except:
pass
## ===================================================================================
def errorMsg():
try:
tb = sys.exc_info()[2]... | (outputRaster):
# For no apparent reason, ArcGIS sometimes fails to build statistics. Might work one
# time and then the next time it may fail without any error message.
#
try:
#PrintMsg(" \n\tChecking raster statistics", 0)
for propType in ['MINIMUM', 'MAXIMUM', 'MEAN', 'STD']:
... | CheckStatistics | identifier_name |
ACPF_ExportMuRaster.py | arcpy.AddWarning(string)
elif severity == 2:
arcpy.AddMessage(" ")
arcpy.AddError(string)
except:
pass
## ===================================================================================
def errorMsg():
try:
tb = sys.exc_info()[2]... | #
stDict = StateNames()
st = os.path.basename(outputWS)[8:-4]
if st in stDict:
# Get state name from the geodatabase
mdState = stDict[st]
else:
# Leave state name blank. In the future it would be nice to include a tile name when appr... | try:
PrintMsg("\tUpdating metadata...")
arcpy.SetProgressor("default", "Updating metadata")
# Set metadata translator file
dInstall = arcpy.GetInstallInfo()
installPath = dInstall["InstallDir"]
prod = r"Metadata/Translator/ARCGIS2FGDC.xml"
mdTranslator = ... | identifier_body |
ACPF_ExportMuRaster.py | arcpy.AddWarning(string)
elif severity == 2:
arcpy.AddMessage(" ")
arcpy.AddError(string)
except:
pass
## ===================================================================================
def errorMsg():
try:
tb = sys.exc_info()[2]... |
# Update credits
eIdInfo = root.find('idinfo')
if not eIdInfo is None:
#PrintMsg("\t\tcredits", 0)
for child in eIdInfo.iter('datacred'):
sCreds = child.text
if sCreds.find("xxSTATExx") >= 0:
#PrintMsg("\t... | if child.text == "xxSTATExx":
child.text = mdState
elif child.text == "xxSURVEYSxx":
child.text = surveyInfo | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.