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 |
|---|---|---|---|---|
ipProcess.py | # -*- coding: utf-8 -*-
'''
Created on Mon May 14 16:31:21 2018
@author: TimL
'''
# Copyright (c) 2019. Induced Polarization Associates, LLC, Seattle, WA
import os
import scipy as sp
import commonSense as cs
from scipy import fftpack as spfftpack
from datetime import datetime
import pickle
def ipProcess():
'''... | if qp == 3 or qp == 4 or qp == 5:
typ = float # Means are saved as floats.
else:
typ = int # Counts are saved as integers.
assignArr = sp.fromstring(line, dtype=typ, sep=',')
... | self.longi[p] = float(self.longi[p])
elif qp < 7:
qp += 1 | random_line_split |
tracer.go | package tortoise
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/common/types/resu... |
}
if err == nil {
if diff := cmp.Diff(rst, r.Results, cmpopts.EquateEmpty()); len(diff) > 0 && rt.assertOutputs {
return errors.New(diff)
}
}
return nil
}
type UpdatesTrace struct {
ResultsTrace `json:",inline"`
}
func (u *UpdatesTrace) Type() eventType {
return traceUpdates
}
func (u *UpdatesTrace) Ne... | {
return err
} | conditional_block |
tracer.go | package tortoise
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/common/types/resu... |
func (s *StoreBallotTrace) New() traceEvent {
return &StoreBallotTrace{}
}
func (s *StoreBallotTrace) Run(r *traceRunner) error {
pending, exist := r.pending[s.ID]
if !exist {
return fmt.Errorf("id %v should be pending", s.ID)
}
if s.Malicious {
pending.SetMalicious()
}
delete(r.pending, s.ID)
err := r.t... | {
return traceStore
} | identifier_body |
tracer.go | package tortoise
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/common/types/resu... | traceActiveset
traceResults
traceUpdates
traceMalfeasence
)
type traceEvent interface {
Type() eventType
New() traceEvent
Run(*traceRunner) error
}
type ConfigTrace struct {
Hdist uint32 `json:"hdist"`
Zdist uint32 `json:"zdist"`
WindowSize uint32 `json:"w... | traceStore
traceEncode
traceTally
traceBlock
traceHare | random_line_split |
tracer.go | package tortoise
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/common/types/resu... | () traceEvent {
return &StoreBallotTrace{}
}
func (s *StoreBallotTrace) Run(r *traceRunner) error {
pending, exist := r.pending[s.ID]
if !exist {
return fmt.Errorf("id %v should be pending", s.ID)
}
if s.Malicious {
pending.SetMalicious()
}
delete(r.pending, s.ID)
err := r.trt.StoreBallot(pending)
if r.as... | New | identifier_name |
SemaIndexerStage2.py | #coding: latin-1
''' inicializa o ambiente para captura de informacoes do clipping '''
''' ractionline p auto-ask(classify,relactionate,composition) ->auto-ask para classificar,relacionar,build objectos dentro dos purposes(ambientes) , as quais sao passadas por linha de comando, roda automaticamente '''
import ... | f,usr,rcts_impo,layers_param=[]):
process_sentences2(usr,rcts_impo,layers_param)
mdNeural.GlobalStack.proc_pg=ProcessPgStack ()
def process_pagest(layersc,purpose,usr,result_onto_tree_er,onto_basis,relactionate):
#try:
id=usr
if True:
#===
#try:
if True:
print 'LayersC-1:',la... | _process2(sel | identifier_name |
SemaIndexerStage2.py | #coding: latin-1
''' inicializa o ambiente para captura de informacoes do clipping '''
''' ractionline p auto-ask(classify,relactionate,composition) ->auto-ask para classificar,relacionar,build objectos dentro dos purposes(ambientes) , as quais sao passadas por linha de comando, roda automaticamente '''
import ... |
#print 'collected.layer.dump():============================================='
#lay.dump_layer_file()
return lay
def get_ontology(aliases,purposes,usr):
tree_h=[]
for alias in aliases:
if True:
tree_cen=[]
if True:
''' '''
if alias == '$$all$$': alias=... | =range(0,50)
resultSet1=iterat.get_level(levs)
#sess=conn3.prepare(sql1)
#resultSet = sess.execute ()
ky,results = resultSet1.next()
while results :
DT=results[u"datach"]
TOP=results[u... | conditional_block |
SemaIndexerStage2.py | #coding: latin-1
''' inicializa o ambiente para captura de informacoes do clipping '''
''' ractionline p auto-ask(classify,relactionate,composition) ->auto-ask para classificar,relacionar,build objectos dentro dos purposes(ambientes) , as quais sao passadas por linha de comando, roda automaticamente '''
import ... | purp=sys.argv[3]
#print purp
tp_n=sys.argv[4] # type of neural objects
#print 'Cmd line :',usr
mdNeural.self_usr=usr
mdNeural.type_coll=tp_n
if sentence.find('.') <=-1 and sentence.find('!') <=-1 and sentence.find('?') <=-1 and sentence.find(';') <=-1:
sentence=sentence+'.'
#pr... | random_line_split | |
SemaIndexerStage2.py | #coding: latin-1
''' inicializa o ambiente para captura de informacoes do clipping '''
''' ractionline p auto-ask(classify,relactionate,composition) ->auto-ask para classificar,relacionar,build objectos dentro dos purposes(ambientes) , as quais sao passadas por linha de comando, roda automaticamente '''
import ... | def get_all(self):
rt=[]
while True:
s=self.next()
if s[0] == None: break
rt.append(s)
return rt
def next(self):
if self.start == -1:
self.start=0
else:
self.start+=1
if self.start < len(... | ]
arr=self.arr
for ky,cols in arr:
for level in level2:
if int(cols[u'LEV']) == level:
rt.append([ky,cols])
rt2=iter_cd(rt)
return rt2
| identifier_body |
HaaLimitsHMass.py | import os
import sys
import logging
import itertools
import numpy as np
import argparse
import math
import errno
import array
import ROOT
ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gROOT.SetBatch()
import CombineLimits.Limits.Models as Models
from CombineLimits.Limits.Limits import Limits
from CombineLimits.H... | '''
Create the Haa Limits workspace
'''
SPLINENAME = 'sig{a}'
XRANGE = [50,1000]
XLABEL = 'm_{#mu#mu#tau_{#mu}#tau_{h}}'
def __init__(self,histMap):
'''
Required arguments:
histMap = histogram map. the structure should be:
histMap[region][shift][pro... | identifier_body | |
HaaLimitsHMass.py | import os
import sys
import logging
import itertools
import numpy as np
import argparse
import math
import errno
import array
import ROOT
ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gROOT.SetBatch()
import CombineLimits.Limits.Models as Models
from CombineLimits.Limits.Limits import Limits
from CombineLimits.H... | (self):
for region in self.REGIONS:
for shift in ['']+self.SHIFTS:
for a in self.AMASSES:
self.buildSpline(a,region=region,shift=shift)
self.workspace.factory('{}_{}_norm[1,0,9999]'.format(self.SPLINENAME.format(a=a),region))
#####################... | addSignalModels | identifier_name |
HaaLimitsHMass.py | import os
import sys
import logging
import itertools
import numpy as np
import argparse
import math
import errno
import array
import ROOT
ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gROOT.SetBatch()
import CombineLimits.Limits.Models as Models
from CombineLimits.Limits.Limits import Limits
from CombineLimits.H... |
# create model
for h in self.HMASSES:
print h, a, results[a][h]
model = Models.VoigtianSpline(self.SPLINENAME.format(a=a),
**{
'masses' : self.HMASSES,
'means' : [results[a][h]['mean_h{0}_a{1}_{2}'.format(h,a,tag)] for h in self.HMAS... | ws = ROOT.RooWorkspace(param)
ws.factory('x[{},{}]'.format(*self.XRANGE))
ws.var('x').setUnit('GeV')
ws.var('x').setPlotLabel(self.XLABEL)
ws.var('x').SetTitle(self.XLABEL)
model = models[param]
model.build(ws, param)
name = '{}_{}{}'.f... | conditional_block |
HaaLimitsHMass.py | import os
import sys
import logging
import itertools
import numpy as np
import argparse
import math
import errno
import array
import ROOT
ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gROOT.SetBatch()
import CombineLimits.Limits.Models as Models
from CombineLimits.Limits.Limits import Limits
from CombineLimits.H... | for shift in ['']+self.SHIFTS:
for a in self.AMASSES:
self.buildSpline(a,region=region,shift=shift)
self.workspace.factory('{}_{}_norm[1,0,9999]'.format(self.SPLINENAME.format(a=a),region))
######################
### Setup datacard ###
###########... | def addSignalModels(self):
for region in self.REGIONS: | random_line_split |
sphere.rs | // Copyright 2017 Dasein Phaos aka. Luxko
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except a... |
/// Constructs a full sphere
#[inline]
pub fn full(radius: Float) -> Sphere {
Sphere::new(radius, -radius, radius, float::pi() * (2.0 as Float))
}
/// returns the local space bounding box
#[inline]
pub fn bounding(&self) -> BBox3f {
BBox3f::new(
Point3f::new(-s... | {
assert!(radius>(0.0 as Float), "Sphere radius should be positive");
assert!(zmin<zmax, "zmin should be lower than zmax");
if zmin < -radius { zmin = -radius; }
if zmax > radius { zmax = radius; }
if phimax < (0.0 as Float) { phimax = 0.0 as Float; }
let twopi = float:... | identifier_body |
sphere.rs | // Copyright 2017 Dasein Phaos aka. Luxko
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except a... | // #[inline]
// pub fn intersect_ray(&self, ray: &RawRay) -> Option<Float>
// {
// if let Some(t) = Sphere::intersect_ray_full(self.radius, ray) {
// let p = ray.evaluate(t);
// // TODO: refine sphere intersection
// let mut phi = p.y.atan2(p.x);
// if... | Point3f::new(self.radius, self.radius, self.zmax)
)
}
// /// test intersection in local frame, returns `t` when first hit | random_line_split |
sphere.rs | // Copyright 2017 Dasein Phaos aka. Luxko
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except a... | (radius: Float, ray: &RawRay) -> Option<Float>
{
let origin = ray.origin().to_vec();
let direction = ray.direction();
let a = direction.magnitude2();
let b = (direction.mul_element_wise(origin) * (2.0 as Float)).sum();
let c = origin.magnitude2() - radius * radius;
l... | intersect_ray_full | identifier_name |
Dom.ts | import { Blend, Component } from "@blendsdk/core";
import { ICreateElementConfig, ICssClassDictionary, IHTMLElementProvider } from "./Types";
// tslint:disable-next-line:no-namespace
export namespace Dom {
/**
* Finds an element using a CSS selector. This method internally uses querySelector.
*
* @e... |
/**
* Finds the first parent element containing the given class name
* or the element itself with the class name.
*
* @param {string} cssClass
* @param {HTMLElement} element
* @returns {HTMLElement}
* @memberof Element
*/
public findParentByClass(cssClass: string): HTMLEle... | {
const me = this,
ref = me.getReference();
if (ref) {
if (ref === ".." && me.el.parentElement) {
return DOMElement.getElement(me.el.parentElement).getReferencedParent();
} else {
return DOMElement.getElement(me.el);
}
} else {
return null;
}
} | identifier_body |
Dom.ts | import { Blend, Component } from "@blendsdk/core";
import { ICreateElementConfig, ICssClassDictionary, IHTMLElementProvider } from "./Types";
// tslint:disable-next-line:no-namespace
export namespace Dom {
/**
* Finds an element using a CSS selector. This method internally uses querySelector.
*
* @e... | }
/**
* Utility function for creating en `HTMLElement`.
* The reference callback function `refCallback` can be used
* to assign child elements which have a `reference` to class
* properties.
*
* The windows parameters `win` can be used to create the element from
* a specific `Wi... | ): NodeListOf<T> {
return (fromRoot || document).querySelectorAll(selector) as NodeListOf<T>; | random_line_split |
Dom.ts | import { Blend, Component } from "@blendsdk/core";
import { ICreateElementConfig, ICssClassDictionary, IHTMLElementProvider } from "./Types";
// tslint:disable-next-line:no-namespace
export namespace Dom {
/**
* Finds an element using a CSS selector. This method internally uses querySelector.
*
* @e... | else {
return DOMElement.getElement(me.el);
}
} else {
return null;
}
}
/**
* Finds the first parent element containing the given class name
* or the element itself with the class name.
*
* @param {string} cssClass
* @param {HTMLElement} element
* @returns {HTMLElement... | {
return DOMElement.getElement(me.el.parentElement).getReferencedParent();
} | conditional_block |
Dom.ts | import { Blend, Component } from "@blendsdk/core";
import { ICreateElementConfig, ICssClassDictionary, IHTMLElementProvider } from "./Types";
// tslint:disable-next-line:no-namespace
export namespace Dom {
/**
* Finds an element using a CSS selector. This method internally uses querySelector.
*
* @e... | (el?: HTMLElement | string | ICreateElementConfig) {
const me = this;
me.el = me.renderElement(el);
}
/**
* Internal method that is used to parse and render the HTMLElement.
*
* @protected
* @param {(HTMLElement | string | ICreateElementConfig)} [el]
* @returns {HTMLElement}
* @m... | constructor | identifier_name |
Career and Job Agent.py | ##Author: Rashmi Varma
##Created: September 28, 2017
##Career and Job Center Agent
##Agent accepts a list of free-form keywords from the command line and outputs Career
##and job opportunities that closely match the input keywords. Agent uses
##k-nearest neighbor algorithm to find matches for any given value of k.
l... |
return co
if source == 'indeed':
for everyline in soup2.find_all('span',{'class':'summary','itemprop':'description'}):
if hasattr(everyline, "text"):
co.append(everyline.text)
return co
##The scrapper is a web scrapping function which uses Beaut... | co.append(everyline.text) | conditional_block |
Career and Job Agent.py | ##Author: Rashmi Varma
##Created: September 28, 2017
##Career and Job Center Agent
##Agent accepts a list of free-form keywords from the command line and outputs Career
##and job opportunities that closely match the input keywords. Agent uses
##k-nearest neighbor algorithm to find matches for any given value of k.
l... |
#Here, we calculate Jaccard's distance and send it back to the Analysis
##function of the agent
## http://journocode.com/2016/03/10/similarity-and-distance-part-1/
def JacCal(str1, str2, lenFreq, lenLink, lenKey):
num = float(str1)
den = float(lenKey + lenLink)
deno = den - num
j = num/den
... | d=[]
d1=[]
knn_k = int(k)
orderedJacc = sorted(k1)
takingK = []
## for x in range(0,k):
takingK = (orderedJacc[:k])
for x in range(0,len(link)):
for k in takingK:
d.append(list_duplicates_of(k1,k))
count=0
for everyd in range(0,len(d)):
if count==knn_k:
... | identifier_body |
Career and Job Agent.py | ##Author: Rashmi Varma
##Created: September 28, 2017
##Career and Job Center Agent
##Agent accepts a list of free-form keywords from the command line and outputs Career
##and job opportunities that closely match the input keywords. Agent uses
##k-nearest neighbor algorithm to find matches for any given value of k.
l... | (key,k):
filename = 'Dictionary.csv'
title = []
content = []
link = []
freq = []
index = 0
ind = []
with open(filename,'rb') as infile:
reader = csv.reader(infile,dialect='excel')
rows = reader.next()
for rows in reader:
title.append(rows[1])
... | agent | identifier_name |
Career and Job Agent.py | ##Author: Rashmi Varma
##Created: September 28, 2017
##Career and Job Center Agent
##Agent accepts a list of free-form keywords from the command line and outputs Career
##and job opportunities that closely match the input keywords. Agent uses
##k-nearest neighbor algorithm to find matches for any given value of k.
l... | ##frequency of the keyword's occurence in our retreieved links
def agent(key,k):
filename = 'Dictionary.csv'
title = []
content = []
link = []
freq = []
index = 0
ind = []
with open(filename,'rb') as infile:
reader = csv.reader(infile,dialect='excel')
rows = reader.next()... | k1.append(jacc)
actuator(k1, link,k)
##Agent computes all the details. Agent reads details from our table and computes | random_line_split |
implicit.go | package teams
import (
"fmt"
"sort"
"strings"
lru "github.com/hashicorp/golang-lru"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
"golang.org/x/net/context"
)
type implicitTeamConflict struct {
// Note this TeamID is not validat... | (ctx context.Context, g *libkb.GlobalContext, impTeamName keybase1.ImplicitTeamDisplayName,
nameWithoutConflict string, preResolveDisplayName string, skipCache bool) (conflicts []keybase1.ImplicitTeamConflictInfo, teamID keybase1.TeamID, hitCache bool, err error) {
defer g.CTrace(ctx,
fmt.Sprintf("attemptLoadImpte... | attemptLoadImpteamAndConflict | identifier_name |
implicit.go | package teams
import (
"fmt"
"sort"
"strings"
lru "github.com/hashicorp/golang-lru"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
"golang.org/x/net/context"
)
type implicitTeamConflict struct {
// Note this TeamID is not validat... |
return imp, err
}
return imp, nil
}
// attemptLoadImpteamAndConflits attempts to lead the implicit team with
// conflict, but it might find the team but not the specific conflict if the
// conflict was not in cache. This can be detected with `hitCache` return
// value, and mitigated by passing skipCache=false arg... | {
code := keybase1.StatusCode(aerr.Code)
switch code {
case keybase1.StatusCode_SCTeamReadError:
return imp, NewTeamDoesNotExistError(public, displayName)
case keybase1.StatusCode_SCTeamProvisionalCanKey, keybase1.StatusCode_SCTeamProvisionalCannotKey:
return imp, libkb.NewTeamProvisionalError(
... | conditional_block |
implicit.go | package teams
import (
"fmt"
"sort"
"strings"
lru "github.com/hashicorp/golang-lru"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
"golang.org/x/net/context"
)
type implicitTeamConflict struct {
// Note this TeamID is not validat... |
// attemptLoadImpteamAndConflits attempts to lead the implicit team with
// conflict, but it might find the team but not the specific conflict if the
// conflict was not in cache. This can be detected with `hitCache` return
// value, and mitigated by passing skipCache=false argument.
func attemptLoadImpteamAndConflic... | {
mctx := libkb.NewMetaContext(ctx, g)
arg := libkb.NewAPIArg("team/implicit")
arg.SessionType = libkb.APISessionTypeOPTIONAL
arg.Args = libkb.HTTPArgs{
"display_name": libkb.S{Val: displayName},
"public": libkb.B{Val: public},
}
if err = mctx.G().API.GetDecode(mctx, arg, &imp); err != nil {
if aerr, ... | identifier_body |
implicit.go | package teams
import (
"fmt"
"sort"
"strings"
lru "github.com/hashicorp/golang-lru"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
"golang.org/x/net/context"
)
type implicitTeamConflict struct {
// Note this TeamID is not validat... | for _, u := range impTeamName.Writers.UnresolvedUsers {
writerNames = append(writerNames, u.String())
}
if optionalFrontName == nil {
sort.Strings(writerNames)
} else {
sortStringsFront(writerNames, optionalFrontName.String())
}
readerNames := make([]string, 0, len(impTeamName.Readers.KeybaseUsers)+len(im... |
func formatImplicitTeamDisplayNameCommon(ctx context.Context, g *libkb.GlobalContext, impTeamName keybase1.ImplicitTeamDisplayName, optionalFrontName *libkb.NormalizedUsername) (string, error) {
writerNames := make([]string, 0, len(impTeamName.Writers.KeybaseUsers)+len(impTeamName.Writers.UnresolvedUsers))
writerNam... | random_line_split |
keyframe.go | // keyframe: take a snapshot (as a raw raster) of th specified slide
package main
import (
"code.google.com/p/go-charset/charset"
_ "code.google.com/p/go-charset/data"
"flag"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"github.com/ajstarks/deck"
"github.com/ajstarks/openvg"
)
var wintrans, _ = charset.Trans... |
func fromUTF8(s string) string {
_, b, err := wintrans.Translate([]byte(s), true)
if err != nil {
return s
}
return string(b)
}
//showtext displays text
func showtext(x, y openvg.VGfloat, s, align, font string, fs openvg.VGfloat) {
t := fromUTF8(s)
fontsize := int(fs)
switch align {
case "center", "middle"... | {
pw := deck.Pwidth(p, float64(p1), float64(p2))
return openvg.VGfloat(pw)
} | identifier_body |
keyframe.go | // keyframe: take a snapshot (as a raw raster) of th specified slide
package main
import (
"code.google.com/p/go-charset/charset"
_ "code.google.com/p/go-charset/data"
"flag"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"github.com/ajstarks/deck"
"github.com/ajstarks/openvg"
)
var wintrans, _ = charset.Trans... | wordspacing := openvg.TextWidth("m", font, size)
words := strings.FieldsFunc(s, whitespace)
xp := x
yp := y
edge := x + w
for _, s := range words {
tw := openvg.TextWidth(s, font, size)
openvg.Text(xp, yp, s, font, size)
xp += tw + (wordspacing * factor)
if xp > edge {
xp = x
yp -= leading
}
}
}
... | } | random_line_split |
keyframe.go | // keyframe: take a snapshot (as a raw raster) of th specified slide
package main
import (
"code.google.com/p/go-charset/charset"
_ "code.google.com/p/go-charset/data"
"flag"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"github.com/ajstarks/deck"
"github.com/ajstarks/openvg"
)
var wintrans, _ = charset.Trans... | else {
px[i] = pct(x, cw)
}
y, err := strconv.ParseFloat(ys[i], 32)
if err != nil {
py[i] = 0
} else {
py[i] = pct(y, ch)
}
}
openvg.FillColor(poly.Color, openvg.VGfloat(poly.Opacity))
openvg.Polygon(px, py)
}
openvg.FillColor(slide.Fg)
// every list in the slide
var offset, text... | {
px[i] = 0
} | conditional_block |
keyframe.go | // keyframe: take a snapshot (as a raw raster) of th specified slide
package main
import (
"code.google.com/p/go-charset/charset"
_ "code.google.com/p/go-charset/data"
"flag"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"github.com/ajstarks/deck"
"github.com/ajstarks/openvg"
)
var wintrans, _ = charset.Trans... | (r rune) bool {
return r == ' ' || r == '\n' || r == '\t' || r == '-'
}
// textwrap draws text at location, wrapping at the specified width
func textwrap(x, y, w openvg.VGfloat, s string, font string, fs, leading, factor openvg.VGfloat) {
size := int(fs)
if font == "mono" {
factor = 1.0
}
wordspacing := openvg.... | whitespace | identifier_name |
Mash.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 3 23:35:49 2016
@author: Beiwen Liu
"""
from music21 import *
c = converter.parse('./ChopinNocturneOp9No2.xml') # Get Info from Original Sheet
sc = stream.Score(id="MainScore") # New Stream
def switch():
c = converter.parse('./KL_Rains_of_Cas... |
def main():
c = converter.parse('./ChopinNocturneOp9No2.xml')
melody = c.parts[0] #Melody part
chord = c.parts[1] #Chord part
measureLength = len(melody) #Number of measures
print "length: " + str(measureLength)
for x in range(1,measureLength): #For all measures
print "index" + str(x)
... | print "melody" + str(measure.notes[x].offset) | conditional_block |
Mash.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 3 23:35:49 2016
@author: Beiwen Liu
"""
from music21 import *
c = converter.parse('./ChopinNocturneOp9No2.xml') # Get Info from Original Sheet
sc = stream.Score(id="MainScore") # New Stream
def switch():
c = converter.parse('./KL_Rains_of_Cas... | (measure):
totalList = []
totalList2 = []
for x in measure.flat.recurse():
print x
if type(x) == chord.Chord:
totalList.append([x,x.duration,x.offset])
#print x,x.duration,x.offset
elif type(x) == note.Note:
totalList2.append([x,x.duration,x.offset... | findAllNotesWithinMeasureChord | identifier_name |
Mash.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 3 23:35:49 2016
@author: Beiwen Liu
"""
from music21 import *
c = converter.parse('./ChopinNocturneOp9No2.xml') # Get Info from Original Sheet
sc = stream.Score(id="MainScore") # New Stream
def switch():
c = converter.parse('./KL_Rains_of_Cas... |
def findAllMeasuresWithinParts(melody,chords,newChord,newMelody):
chordMeasures = chords.measure(0)
if chordMeasures is None:
chordMeasures = chords.measure(1)
c1 = chordMeasures
melodyMeasures = melody.measure(0)
if melodyMeasures is None:
melodyMeasures = melody.measure... | n = note.Note(pitch)
n.duration = duration
n.offset = offset
return n | identifier_body |
Mash.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 3 23:35:49 2016
@author: Beiwen Liu
"""
from music21 import *
c = converter.parse('./ChopinNocturneOp9No2.xml') # Get Info from Original Sheet
sc = stream.Score(id="MainScore") # New Stream
def switch(): | number = len(c2.parts[1]) #number of measures
number2 = len(c2.parts[1].measure(4))
c = c.parts[0].flat
print c2.parts[1].measure(4).notes[1].duration.type
print number2
#s = stream.Score()
#s.insert(0,c)
#s.insert(1,c2)
#s.show()
def determineChord(measure):
#measure.notes[... | c = converter.parse('./KL_Rains_of_Castamere.xml')
c2 = converter.parse('./FurElise.xml') | random_line_split |
chain.go | // Copyright 2017, Square, Inc.
// Package chain implements a job chain. It provides the ability to traverse a chain
// and run all of the jobs in it.
package chain
import (
"fmt"
"sync"
"time"
"github.com/square/spincycle/proto"
)
// chain represents a job chain and some meta information about it.
type chain s... |
// adjacencyListIsValid returns whether or not the chain's adjacency list is
// not valid. An adjacency list is not valid if any of the jobs in it do not
// exist in chain.Jobs.
func (c *chain) adjacencyListIsValid() bool {
for job, adjJobs := range c.JobChain.AdjacencyList {
if _, ok := c.JobChain.Jobs[job]; !ok ... | {
indegreeCounts := c.indegreeCounts()
queue := make(map[string]struct{})
// Add all of the first jobs to the queue (in reality there should
// only be 1).
for job, indegreeCount := range indegreeCounts {
if indegreeCount == 0 {
queue[job] = struct{}{}
}
}
jobsVisited := 0
for {
// Break when there a... | identifier_body |
chain.go | // Copyright 2017, Square, Inc.
// Package chain implements a job chain. It provides the ability to traverse a chain
// and run all of the jobs in it.
package chain
import (
"fmt"
"sync"
"time"
"github.com/square/spincycle/proto"
)
// chain represents a job chain and some meta information about it.
type chain s... |
if len(jobIds) != 1 {
return proto.Job{}, ErrInvalidChain{
Message: fmt.Sprintf("chain has %d last job(s), should "+
"have one (last job(s) = %v)", len(jobIds), jobIds),
}
}
return c.JobChain.Jobs[jobIds[0]], nil
}
// NextJobs finds all of the jobs adjacent to the given job.
func (c *chain) NextJobs(j... | {
if count == 0 {
jobIds = append(jobIds, jobId)
}
} | conditional_block |
chain.go | // Copyright 2017, Square, Inc.
// Package chain implements a job chain. It provides the ability to traverse a chain
// and run all of the jobs in it.
package chain
import (
"fmt"
"sync"
"time"
"github.com/square/spincycle/proto"
)
// chain represents a job chain and some meta information about it.
type chain s... | _, err := c.FirstJob()
if err != nil {
return err
}
// Make sure there is one last job.
_, err = c.LastJob()
if err != nil {
return err
}
// Make sure there are no cycles.
if !c.isAcyclic() {
return ErrInvalidChain{Message: "chain is cyclic"}
}
return nil
}
// RequestId returns the request id of th... | // Make sure there is one first job. | random_line_split |
chain.go | // Copyright 2017, Square, Inc.
// Package chain implements a job chain. It provides the ability to traverse a chain
// and run all of the jobs in it.
package chain
import (
"fmt"
"sync"
"time"
"github.com/square/spincycle/proto"
)
// chain represents a job chain and some meta information about it.
type chain s... | (jobId string) proto.Jobs {
var prevJobs proto.Jobs
for curJob, nextJobs := range c.JobChain.AdjacencyList {
if contains(nextJobs, jobId) {
if val, ok := c.JobChain.Jobs[curJob]; ok {
prevJobs = append(prevJobs, val)
}
}
}
return prevJobs
}
// JobIsReady returns whether or not a job is ready to run. ... | PreviousJobs | identifier_name |
node.rs | use std::convert::TryFrom;
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use casbin::prelude::{Enforcer, MgmtApi};
use dashmap::DashMap;
use http::Uri;
use prost::Message;
use raft::prelude::*;
use raft::{Config, RawNode};
use slog::Logger;
use tokio::sync::mpsc::*;
use tokio::sync::RwLock;
use tokio:... | (
&mut self,
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
let mut ready = self.node.ready();
let is_leader = self.node.raft.leader_id == self.node.raft.id;
slog::info!(
self.logger,
"Leader ID: {}, Node ID: {}",
self.node.... | ready | identifier_name |
node.rs | use std::convert::TryFrom;
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use casbin::prelude::{Enforcer, MgmtApi};
use dashmap::DashMap;
use http::Uri;
use prost::Message;
use raft::prelude::*;
use raft::{Config, RawNode};
use slog::Logger;
use tokio::sync::mpsc::*;
use tokio::sync::RwLock;
use tokio:... |
match timeout(Duration::from_millis(100), self.conf_recv.recv()).await {
Ok(Some(cc)) => {
let ccc = cc.clone();
let state = self.node.apply_conf_change(&cc)?;
self.node.mut_store().set_conf_state(state);
let ... | {
slog::info!(self.logger, "Inbound raft message: {:?}", msg);
self.node.step(msg.into())?;
} | conditional_block |
node.rs | use std::convert::TryFrom;
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use casbin::prelude::{Enforcer, MgmtApi};
use dashmap::DashMap;
use http::Uri;
use prost::Message;
use raft::prelude::*;
use raft::{Config, RawNode};
use slog::Logger;
use tokio::sync::mpsc::*;
use tokio::sync::RwLock;
use tokio:... |
fn set_hard_state(
&mut self,
commit: u64,
term: u64,
) -> Result<(), crate::error::Error> {
self.node.raft.mut_store().set_hard_state(commit, term);
Ok(())
}
#[allow(irrefutable_let_patterns)]
pub async fn run(
mut self,
) -> Result<(), Box<dyn... | {
self.node.raft.raft_log.committed = 0;
self.node.raft.become_candidate();
self.node.raft.become_leader();
} | identifier_body |
node.rs | use std::convert::TryFrom;
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use casbin::prelude::{Enforcer, MgmtApi};
use dashmap::DashMap;
use http::Uri;
use prost::Message;
use raft::prelude::*;
use raft::{Config, RawNode};
use slog::Logger;
use tokio::sync::mpsc::*;
use tokio::sync::RwLock;
use tokio:... | internal_raft_message
.merge(Bytes::from(entry.data.clone()))
.unwrap();
if let Err(error) = self.apply(internal_raft_message) {
slog::error!(self.logger, "Unable to apply entry. {:?}", error);
// TODO: retu... | let mut internal_raft_message = InternalRaftMessage::default(); | random_line_split |
script.py | # -*- coding: utf-8 -*-
##############################################################################
# Visión por Computador
# Trabajo 3: Indexación y recuperación de imágenes.
# @author Álvaro Fernández García
##############################################################################
import numpy as np
import... | tle):
assert len(vim) > 0
if len(vim) == 1:
finalImg = vim
else:
finalImg = vim[0]
vim.pop(0)
for img in vim:
finalImg = cv2.hconcat((finalImg, img))
_showImage(finalImg, title)
return finalImg
# Muestra en una imagen 10 parches de 24x24 pixeles:
def dibuja10par... | vim, ti | identifier_name |
script.py | # -*- coding: utf-8 -*-
##############################################################################
# Visión por Computador
# Trabajo 3: Indexación y recuperación de imágenes.
# @author Álvaro Fernández García
##############################################################################
import numpy as np
import... | alculada con la función anterior,
# muestra las 5 imágenes más cercanas:
def get_5_nearest_images(img, bolsa_palabras):
# Paso 1: obtener la bolsa de palabras de la imagen:
# Declaramos los objetos necesarios:
dicc = axf.loadDictionary('kmeanscenters2000.pkl')[2]
sift = cv2.xfeatures2d.SIFT_create()
... | )[2]
sift = cv2.xfeatures2d.SIFT_create()
bf = cv2.BFMatcher(crossCheck=False)
# Inicializar el índice invertido:
indice_invert = dict()
for i in range(dicc.shape[0]):
indice_invert[i] = set()
# Inicializar la bolsa de palabras:
bolsa_palabras = dict()
for i in range(441):
... | identifier_body |
script.py | # -*- coding: utf-8 -*-
##############################################################################
# Visión por Computador
# Trabajo 3: Indexación y recuperación de imágenes.
# @author Álvaro Fernández García
##############################################################################
import numpy as np
import... | for i in words:
print(i)
myPatches = []
for m in matches[i]:
# Convertirlo a escala de grises y hacer el reshape del parche:
img = cv2.cvtColor(patches[m.trainIdx], cv2.COLOR_BGR2GRAY).reshape(24,24)
myPatches.append(img)
dibuja10parches(myPatches... | # Mostrar los ejemplos:
# en los dos primeros matches los parches son muy parecidos (casi idénticos)
# en el tercero, hay ligeras variaciones
# en el último son distintos: | random_line_split |
script.py | # -*- coding: utf-8 -*-
##############################################################################
# Visión por Computador
# Trabajo 3: Indexación y recuperación de imágenes.
# @author Álvaro Fernández García
##############################################################################
import numpy as np
import... | #####################################
# EJERCICIO 3:
#######################################################################################
# Visualización del vocabulario [3 puntos]
# • Usando las imágenes dadas en imagenesIR.rar se han extraido 600
# regiones de cada imagen de forma directa y se han re-escalado e... | .png', 1)
PintaMI([img, ima], "{}ª imagen más cercana: Similaridad = {:.4f}".format(i, similaridades[i][1]))
################################################## | conditional_block |
index_file_deleter.rs | // Copyright 2019 Zhizhesihai (Beijing) Technology Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by a... | }
impl Ord for CommitPoint {
fn cmp(&self, other: &Self) -> Ordering {
self.generation.cmp(&other.generation)
}
}
impl PartialOrd for CommitPoint {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for CommitPoint {}
impl PartialEq for Commit... | }
pub fn has_dv_updates(&self) -> bool {
self.has_dv_updates
} | random_line_split |
index_file_deleter.rs | // Copyright 2019 Zhizhesihai (Beijing) Technology Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by a... |
pub fn dec_ref_files_no_error(&self, files: &HashSet<String>) {
if let Err(e) = self.dec_ref_files(files) {
warn!("dec_ref_files_no_error failed with '{:?}'", e);
}
}
/// Returns true if the file should now be deleted.
fn dec_ref(&self, filename: &str) -> bool {
se... | {
let mut to_delete = HashSet::new();
for f in files {
if self.dec_ref(f) {
to_delete.insert(f.clone());
}
}
self.delete_files(&to_delete, true)
} | identifier_body |
index_file_deleter.rs | // Copyright 2019 Zhizhesihai (Beijing) Technology Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by a... | (&mut self) -> Result<()> {
self.deleted = true;
Ok(())
}
pub fn has_dv_updates(&self) -> bool {
self.has_dv_updates
}
}
impl Ord for CommitPoint {
fn cmp(&self, other: &Self) -> Ordering {
self.generation.cmp(&other.generation)
}
}
impl PartialOrd for CommitPoint ... | delete | identifier_name |
index_file_deleter.rs | // Copyright 2019 Zhizhesihai (Beijing) Technology Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by a... |
}
self.delete_commits()?;
self.inited = true;
Ok(starting_commit_deleted)
}
/// Set all gens beyond what we currently see in the directory, to avoid double-write
/// in cases where the previous IndexWriter did not gracefully close/rollback (e.g.
/// os/machine crashed... | {
starting_commit_deleted = true;
} | conditional_block |
goclass.go | // Copyright 2014 Elliott Stoneham and The TARDIS Go Authors
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package haxe
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"unicode"
"github.com/tardisgo/tardisgo/pogo"
"golang.org/x/tools/go/exact"
"g... | ackageName, objectName string, lit ssa.Const, position string) string {
typ, rhs := l.Const(lit, position+":"+packageName+"."+objectName)
return fmt.Sprintf("public static var %s:%s = %s;%s",
l.LangName(packageName, objectName), typ, rhs, l.Comment(position))
}
func (l langType) Global(packageName, objectName stri... | medConst(p | identifier_name |
goclass.go | // Copyright 2014 Elliott Stoneham and The TARDIS Go Authors
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package haxe
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"unicode"
"github.com/tardisgo/tardisgo/pogo"
"golang.org/x/tools/go/exact"
"g... | pos += fmt.Sprintf(`if(pos>%d) return prefix+"%s:"+Std.string(pos-%d);`,
pogo.PosHashFileList[p].BasePosHash,
strings.Replace(pogo.PosHashFileList[p].FileName, "\\", "\\\\", -1),
pogo.PosHashFileList[p].BasePosHash) + "\n"
}
pos += "else return \"(invalid pogo.PosHash:\"+Std.string(pos)+\")\";\n}\n"
if po... | pos += "else "
}
| conditional_block |
goclass.go | // Copyright 2014 Elliott Stoneham and The TARDIS Go Authors
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package haxe
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"unicode"
"github.com/tardisgo/tardisgo/pogo"
"golang.org/x/tools/go/exact"
"g... | pub := "public " // all globals have to be public in Haxe terms
//gTyp := glob.Type().Underlying().(*types.Pointer).Elem().Underlying() // globals are always pointers to an underlying element
/*
ptrTyp := "Pointer"
//ltDesc := "Dynamic" // these values suitable for *types.Struct
ltInit := "null"
switch gTyp.... | identifier_body | |
goclass.go | // Copyright 2014 Elliott Stoneham and The TARDIS Go Authors
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package haxe
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"unicode"
"github.com/tardisgo/tardisgo/pogo"
"golang.org/x/tools/go/exact"
"g... | */
/*
val := exact.MakeFloat64(frac)
num := exact.Num(val)
den := exact.Denom(val)
n64i, nok := exact.Int64Val(num)
d64i, dok := exact.Int64Val(den)
res := float64(n64i) * math.Pow(2, float64(exp)) / float64(d64i)
if !math.IsNaN(res) && !math.IsInf(res, +1) && !math.IsInf(res, -1) { //drop thro... | if float64(intPart) == frac*float64(uint64(1)<<sigBits) &&
expPart >= -1022 && expPart <= 1023 {
//it is an integer in the correct range
haxeVal = fmt.Sprintf("(%d*Math.pow(2,%d))", intPart, expPart) // NOTE: need the Math.pow to avoid haxe constant folding
} | random_line_split |
ssh.rs | //! The "ssh-rsa" and "ssh-ed25519" recipient types, which allow reusing existing SSH keys
//! for encryption with age-encryption.org/v1.
//!
//! These recipient types should only be used for compatibility with existing keys, and
//! native X25519 keys should be preferred otherwise.
//!
//! Note that these recipient ty... | (
self,
kdf: &OpenSshKdf,
p: SecretString,
ct: &[u8],
) -> Result<Vec<u8>, DecryptError> {
match self {
OpenSshCipher::Aes256Cbc => decrypt::aes_cbc::<Aes256CbcDec>(kdf, p, ct),
OpenSshCipher::Aes128Ctr => Ok(decrypt::aes_ctr::<Aes128Ctr>(kdf, p, ct)),... | decrypt | identifier_name |
ssh.rs | //! The "ssh-rsa" and "ssh-ed25519" recipient types, which allow reusing existing SSH keys
//! for encryption with age-encryption.org/v1.
//!
//! These recipient types should only be used for compatibility with existing keys, and
//! native X25519 keys should be preferred otherwise.
//!
//! Note that these recipient ty... | }
}
mod decrypt {
use aes::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit, StreamCipher};
use aes_gcm::aead::{AeadMut, KeyInit};
use age_core::secrecy::SecretString;
use cipher::generic_array::{ArrayLength, GenericArray};
use super::OpenSshKdf;
use crate::error::DecryptError... | Identity::Encrypted(_) => unreachable!(),
} | random_line_split |
ssh.rs | //! The "ssh-rsa" and "ssh-ed25519" recipient types, which allow reusing existing SSH keys
//! for encryption with age-encryption.org/v1.
//!
//! These recipient types should only be used for compatibility with existing keys, and
//! native X25519 keys should be preferred otherwise.
//!
//! Note that these recipient ty... | else {
None
}
}),
alt((
map(openssh_rsa_privkey, move |sk| {
UnencryptedKey::SshRsa(ssh_key_rsa.clone(), Box::new(sk)).into()
}),
map(openssh_ed25519_privkey, move |privkey| {
... | {
Some(c1)
} | conditional_block |
Rmag_aperture_annulus_per_target.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 9 05:22:35 2019
@author: altsai
"""
import os
import sys
import shutil
import numpy as np
import csv
import pandas as pd
from astropy import units as u
from astropy.coordinates import SkyCoord # High-level coordinates
#from astropy.coordinates im... | r_circle_as=r_circle*u.arcsec
r_inner=20.
r_outer=25.
r_inner_as=r_inner*u.arcsec
r_outer_as=r_outer*u.arcsec
aperture=SkyCircularAperture(positions, r_circle_as)
#print(aperture)
r_as=aperture.r
print('r_as =',r_as)
print('number of reference stars : ',n_refstar)
k=0
for i in idx_fitsheader:
print('--------------... | #sys.exit(0)
r_circle=15. | random_line_split |
Rmag_aperture_annulus_per_target.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 9 05:22:35 2019
@author: altsai
"""
import os
import sys
import shutil
import numpy as np
import csv
import pandas as pd
from astropy import units as u
from astropy.coordinates import SkyCoord # High-level coordinates
#from astropy.coordinates im... |
mag_instrument_1=mag_instrument[1:n_refstar]
rmag_1=rmag[1:n_refstar]
b,m=polyfit(mag_instrument_1,rmag_1,1)
# print('b =','%.3f' %b)
# print('m =','%.3f' %m)
# print('Rmag =','%.3f' %b,'+','%.3f' %m,'*(Instrument Magnitude)')
rmag[0]=b+m*mag_instrument[0]
# print(rmag[0])
Rmag0[k]=rma... | mag_instrument[j]=-2.5*np.log10(final_sum[j])
print(j, final_sum[j],mag_instrument[j],rmag[j]) | conditional_block |
save_secret_in_image_better.py | #! /usr/bin/env -S /usr/bin/time /usr/bin/python3.8.6 -i
# -*- coding: utf-8 -*-
import dill
import gzip
import os
import sys
import string
import shutil
from typing import List, Dict, Set, Mapping, Any, Tuple
# import tempfile
from memory_tempfile import MemoryTempfile
tempfile : MemoryTempfile = MemoryTempfile()... |
l_arr_secret_bin_content = [np.array(create_secret_bin_content(secret_str), dtype=np.uint8) for secret_str in l_secret_str]
# TODO: make this into a multiprocessing function too!
def find_best_possible_parameters(n : int=100):
def inner_function():
arr_line_param_offset : np.ndarray =... | secret_int : List[int] = convert_base_100_to_int(secret_str)
secret_bin : List[int] = convert_int_to_lst_bin(secret_int)
l_len_secret_bin = convert_int_to_lst_bin(len(secret_bin))
len_l_len_secret_bin = len(l_len_secret_bin)
assert len_l_len_secret_bin <= MIN_BITS_LENGTH
if len_l... | identifier_body |
save_secret_in_image_better.py | #! /usr/bin/env -S /usr/bin/time /usr/bin/python3.8.6 -i
# -*- coding: utf-8 -*-
import dill
import gzip
import os
import sys
import string
import shutil
from typing import List, Dict, Set, Mapping, Any, Tuple
# import tempfile
from memory_tempfile import MemoryTempfile
tempfile : MemoryTempfile = MemoryTempfile()... | (num_int):
l = []
while num_int > 0:
l.append(num_int % base_100_len)
num_int //= base_100_len
n = list(map(lambda x: lst_int_base_100[x], reversed(l)))
return "".join(n)
def convert_int_to_lst_bin(num_int):
return list(map(int, bin(num_int)[2:]))
def convert_lst_bin_to_int(l_bin... | convert_int_to_base_100 | identifier_name |
save_secret_in_image_better.py | #! /usr/bin/env -S /usr/bin/time /usr/bin/python3.8.6 -i
# -*- coding: utf-8 -*-
import dill
import gzip
import os
import sys
import string
import shutil
from typing import List, Dict, Set, Mapping, Any, Tuple
# import tempfile
from memory_tempfile import MemoryTempfile
tempfile : MemoryTempfile = MemoryTempfile()... |
return l_possible_params
mult_proc_mng = MultiprocessingManager(cpu_count=mp.cpu_count())
mult_proc_mng.test_worker_threads_response()
l_jump_all = list(range(JUMP_MIN, JUMP_MAX+1))
amount_parts = 7
len_l_jump_all = len(l_jump_all)
factor = len_l_jump_all / amount_parts
l_jump_r... | t_params = (jump, offset_prefix, offset_jump + len_arr_suffix)
print("t_params: {}".format(t_params))
l_possible_params.append(t_params) | conditional_block |
save_secret_in_image_better.py | #! /usr/bin/env -S /usr/bin/time /usr/bin/python3.8.6 -i
# -*- coding: utf-8 -*-
import dill
import gzip
import os
import sys
import string
import shutil
from typing import List, Dict, Set, Mapping, Any, Tuple
# import tempfile
from memory_tempfile import MemoryTempfile
tempfile : MemoryTempfile = MemoryTempfile()... |
img_src = Image.open(img_src_new_path)
img_dst = Image.open(img_dst_path)
pix_src = np.array(img_src)
pix_dst = np.array(img_dst)
pix_src_1bit = (pix_src & 0x1) * 255
pix_dst_1bit = (pix_dst & 0x1) * 255
pix_src_dst_1bit = pix_src_1bit ^ pix_dst_1bit
img_path_src_1bit = 'images/... | Image.fromarray(pix_1_bit).save('images/img_path_src_1bit_encoded_in.png')
img_secret : Image = Image.fromarray(pix_secret)
img_secret.save(img_dst_path) | random_line_split |
start.py | import os
import sys
import re
from pathlib import Path
from functools import wraps
import signal
import shutil
import socket
import urllib.request, urllib.error
import ssl
import json
# append proper (snap) site-packages path
sys.path.append("/snap/nextbox/current/lib/python3.6/site-packages")
from queue import Que... |
@app.route("/backup")
@requires_auth
def backup():
data = dict(cfg["config"])
data["operation"] = check_for_backup_process()
data["found"] = []
if get_partitions()["backup"] is not None:
for name in os.listdir("/media/backup"):
p = Path("/media/backup") / name
try:
... | global backup_proc
out = dict(cfg["config"])
if backup_proc is None:
out["running"] = False
return out
assert isinstance(backup_proc, CommandRunner)
backup_proc.get_new_output()
if backup_proc.finished:
if backup_proc.returncode == 0:
backup_proc.parsed["state... | identifier_body |
start.py | import os
import sys
import re
from pathlib import Path
from functools import wraps
import signal
import shutil
import socket
import urllib.request, urllib.error
import ssl
import json
# append proper (snap) site-packages path
sys.path.append("/snap/nextbox/current/lib/python3.6/site-packages")
from queue import Que... | ():
global backup_proc
out = dict(cfg["config"])
if backup_proc is None:
out["running"] = False
return out
assert isinstance(backup_proc, CommandRunner)
backup_proc.get_new_output()
if backup_proc.finished:
if backup_proc.returncode == 0:
backup_proc.parse... | check_for_backup_process | identifier_name |
start.py | import os
import sys
import re
from pathlib import Path
from functools import wraps
import signal
import shutil
import socket
import urllib.request, urllib.error
import ssl
import json
# append proper (snap) site-packages path
sys.path.append("/snap/nextbox/current/lib/python3.6/site-packages")
from queue import Que... |
# save dyndns related values to configuration
elif request.method == "POST":
for key in request.form:
val = request.form.get(key)
if key == "conf":
old_conf = Path(DDCLIENT_CONFIG_PATH).read_text("utf-8")
if old_conf != val:
l... | data = dict(cfg["config"])
data["conf"] = Path(DDCLIENT_CONFIG_PATH).read_text("utf-8").split("\n")
return success(data=data) | conditional_block |
start.py | import os
import sys
import re
from pathlib import Path
from functools import wraps
import signal
import shutil
import socket
import urllib.request, urllib.error
import ssl
import json
# append proper (snap) site-packages path
sys.path.append("/snap/nextbox/current/lib/python3.6/site-packages")
from queue import Que... | @app.route("/dyndns/test/proxy")
@requires_auth
def test_http():
what = request.path.split("/")[-1]
if what == "proxy":
domain = cfg["config"]["proxy_domain"]
what = "https"
else:
domain = cfg["config"]["domain"]
url = f"{what}://{domain}"
try:
content = urllib.reques... | @app.route("/dyndns/test/http")
@app.route("/dyndns/test/https") | random_line_split |
Исследование_1705.py | # ## Определения
from operator import itemgetter
import bz2, json
from collections import defaultdict
import math
from bisect import bisect_left
WORD_LEN_COEFF = 1
THRESHOLD_COEFF = 0.5
DROP = 1.5
DROP_1 = 2
AFFIX_LEN = 1
THRESHOLD_OSTAT = 0.5
N = 5 # шлейфовый порог
trie, voc, words, prob, word_count, average_word... | print("* Ускоренный ход!!! *")
del_aff = []
next_affixes = fast_alg(bases[-1], specter[-1], freq_bases, step, del_aff)
if not next_affixes:
fast = False
continue
# основы следующего вида
next_bases = [b for b in bases[-1] i... | print("* Прямой ход * ")
next_affixes = direct_alg(bases[-1], specter[-1], false_affixes)
if not next_affixes:
break
else: | random_line_split |
Исследование_1705.py | # ## Определения
from operator import itemgetter
import bz2, json
from collections import defaultdict
import math
from bisect import bisect_left
WORD_LEN_COEFF = 1
THRESHOLD_COEFF = 0.5
DROP = 1.5
DROP_1 = 2
AFFIX_LEN = 1
THRESHOLD_OSTAT = 0.5
N = 5 # шлейфовый порог
trie, voc, words, prob, word_count, average_word... | ontrol_bases) == 1:
lower = [(b, freq) for b, freq in freq_cur_bases.items() if freq < max_freq_cur]
control_bases.append(max(lower, key=itemgetter(1))[0])
print("Контрольные базы:", control_bases)
# Первый критерий принадлежности к парадигме - сочетаемость остатков в звене с основами control_b... | if len(c | identifier_name |
Исследование_1705.py | # ## Определения
from operator import itemgetter
import bz2, json
from collections import defaultdict
import math
from bisect import bisect_left
WORD_LEN_COEFF = 1
THRESHOLD_COEFF = 0.5
DROP = 1.5
DROP_1 = 2
AFFIX_LEN = 1
THRESHOLD_OSTAT = 0.5
N = 5 # шлейфовый порог
trie, voc, words, prob, word_count, average_word... | current_dict[ch]
else:
break
aff_len += 1
return affix
# узел trie, соответствующий окончанию aff
def affix_node(aff):
global trie
current_node = trie
for char in aff[::-1]:
current_node = current_node[char]
return current_node
# узел trie, соответст... | длины аффикса
while aff_len < len_search:
# составляем список всех букв предшествующих аффиксу с количествами
L = [(l, current_dict[l]["n"]) for l in current_dict.keys() if l not in '#n']
# сортируем по количествам
L.sort(key=itemgetter(1), reverse=True)
# if affix=='нан':
... | identifier_body |
Исследование_1705.py | # ## Определения
from operator import itemgetter
import bz2, json
from collections import defaultdict
import math
from bisect import bisect_left
WORD_LEN_COEFF = 1
THRESHOLD_COEFF = 0.5
DROP = 1.5
DROP_1 = 2
AFFIX_LEN = 1
THRESHOLD_OSTAT = 0.5
N = 5 # шлейфовый порог
trie, voc, words, prob, word_count, average_word... | rol_bases.append(max(lower, key=itemgetter(1))[0])
print("Контрольные базы:", control_bases)
# Первый критерий принадлежности к парадигме - сочетаемость остатков в звене с основами control_bases
keep_ost = [ost for ost in inf_zveno if all([b + ost in voc for b in control_bases])]
removed_ost = [ost for... | cont | conditional_block |
Player.js | import React, { useState, useEffect, useRef, useLayoutEffect } from 'react';
import { useDragObservable } from '../../hooks/eventHooks';
import Card from '../card/Card';
import css from './Player.sass';
const Player = ({ cards, onSelect }) => { | const [ draggingLeft, setDraggingLeft ] = useState(0);
const [ jokerSelect, setJokerSelect ] = useState(undefined);
const [ jokerValue, setJokerValue ] = useState({rank: 'two', suit: 'spades'});
const [ cardWidth, setCardWidth ] = useState(0);
const playerWidth = useRef(0);
const draggingRef = useRef([])... |
const [ selected, setSelected ] = useState([]);
const [ order, setOrder ] = useState(cards.map(card => card.id)); | random_line_split |
Player.js | import React, { useState, useEffect, useRef, useLayoutEffect } from 'react';
import { useDragObservable } from '../../hooks/eventHooks';
import Card from '../card/Card';
import css from './Player.sass';
const Player = ({ cards, onSelect }) => {
const [ selected, setSelected ] = useState([]);
const [ order, set... |
}
if (point1 >= 0 && point2 >= 0) {
const touchOneChange = touches[0].pageX - lastTouches[point1].pageX;
const touchTwoChange = touches[1].pageX - lastTouches[point2].pageX;
// check if swipe
if (touchOneChange * touchTwoChange > 0) {
return { type:... | { point2 = i; } | conditional_block |
Player.js | import React, { useState, useEffect, useRef, useLayoutEffect } from 'react';
import { useDragObservable } from '../../hooks/eventHooks';
import Card from '../card/Card';
import css from './Player.sass';
const Player = ({ cards, onSelect }) => {
const [ selected, setSelected ] = useState([]);
const [ order, set... |
function selectCard(card) {
// make all jokers two of spades (until select feature done)
// const joker = { rank: 'two', suit: 'spades' };
// const playedCard = {
// ...joker,
// ...card,
// is_joker: card.type === 'joker'
// };
const filteredSelect = selected.filter(selectedC... | {
const minScroll = playerRef.current
? playerRef.current.parentElement.offsetWidth - (cards.length * cardOverlapRef.current + (cardWidth - cardOverlapRef.current))
: -Infinity;
return Math.min(0, Math.max(minScroll, scroll));
} | identifier_body |
Player.js | import React, { useState, useEffect, useRef, useLayoutEffect } from 'react';
import { useDragObservable } from '../../hooks/eventHooks';
import Card from '../card/Card';
import css from './Player.sass';
const Player = ({ cards, onSelect }) => {
const [ selected, setSelected ] = useState([]);
const [ order, set... | (card) {
// make all jokers two of spades (until select feature done)
// const joker = { rank: 'two', suit: 'spades' };
// const playedCard = {
// ...joker,
// ...card,
// is_joker: card.type === 'joker'
// };
const filteredSelect = selected.filter(selectedCard => selectedCard.id ... | selectCard | identifier_name |
wd.rs | //! WebDriver types and declarations.
use crate::error;
#[cfg(doc)]
use crate::Client;
use http::Method;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::convert::TryFrom;
use std::fmt;
use std::fmt::Debug;
use std::time::Duration;
use url::{ParseError, Url};
use webdriver::command::TimeoutsParamete... | }
/// Return true if this session should only support the legacy webdriver protocol.
///
/// This only applies to the obsolete JSON Wire Protocol and should return `false`
/// for all implementations that follow the W3C specification.
///
/// See <https://www.selenium.dev/documentation/lega... | random_line_split | |
wd.rs | //! WebDriver types and declarations.
use crate::error;
#[cfg(doc)]
use crate::Client;
use http::Method;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::convert::TryFrom;
use std::fmt;
use std::fmt::Debug;
use std::time::Duration;
use url::{ParseError, Url};
use webdriver::command::TimeoutsParamete... | (&self, request_url: &Url) -> (Method, Option<String>) {
T::method_and_body(self, request_url)
}
fn is_new_session(&self) -> bool {
T::is_new_session(self)
}
fn is_legacy(&self) -> bool {
T::is_legacy(self)
}
}
/// A [handle][1] to a browser window.
///
/// Should be obtai... | method_and_body | identifier_name |
plotting_utils.py | import numpy as np
from get_luminosity import *
from astropy.cosmology import Planck15
import matplotlib.pyplot as pl
pl.ioff()
import matplotlib.cm as cm
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.ticker import MaxNLocator
import scipy.ndimage
from copy import deepcopy
# Contains a few rout... | (um_rest,Sfit,um_data,mjy_data,mjy_errors,axobj,*args,**kwargs):
"""
Plot an SED
"""
sedcolor = kwargs.pop('sedcolor','b')
axobj.set_axis_on()
axobj.plot(um_rest,Sfit,color=sedcolor,ls='-')
axobj.set_xscale('log'); axobj.set_yscale('log')
axobj.set_xlabel('$\\lambd... | plot_sed | identifier_name |
plotting_utils.py | import numpy as np
from get_luminosity import *
from astropy.cosmology import Planck15
import matplotlib.pyplot as pl
pl.ioff()
import matplotlib.cm as cm
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.ticker import MaxNLocator
import scipy.ndimage
from copy import deepcopy
# Contains a few rout... |
def make_outputplot(plotfile,samples,labels,plotsed=True,um_rest=None,
Sfit=None,um_data=None, mjy_data=None,mjy_errors=None):
"""
Assemble the whole output thing.
"""
f,axarr = triangleplot(samples,labels)
if plotsed: trcax = plot_sed(um_rest,Sfit,um_data,mjy_data,mjy_erro... | """
Assemble the MCMC samples into the usual triangle plot format.
Parameters:
samples: 2-D array
Array of MCMC samples, of shape (Nsamples,Nparameters)
labels: list of strings
What to label the axes. Latex math-mode is okay.
Returns:
f,axarr: ma... | identifier_body |
plotting_utils.py | import numpy as np
from get_luminosity import *
from astropy.cosmology import Planck15
import matplotlib.pyplot as pl
pl.ioff()
import matplotlib.cm as cm
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.ticker import MaxNLocator
import scipy.ndimage
from copy import deepcopy
# Contains a few rout... |
if mjy_data[i] > 0:
axobj.errorbar(point,mjy_data[i],yerr=mjy_errors[i],color=color,\
marker='o')
else: # Draw upper limits, but make errobar sizes consistent on log-log
ylims,xlims = axobj.get_ylim(), axobj.get_xlim()
... | color = 'r' | conditional_block |
plotting_utils.py | import numpy as np
from get_luminosity import *
from astropy.cosmology import Planck15
import matplotlib.pyplot as pl
pl.ioff()
import matplotlib.cm as cm
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.ticker import MaxNLocator
import scipy.ndimage
from copy import deepcopy
# Contains a few rout... | altax.set_xlim(axobj.get_xlim()[0],axobj.get_xlim()[1])
altax.set_ylim(axobj.get_ylim()[0],axobj.get_ylim()[1])
altax.set_xscale('log'); altax.set_xlabel('$\\lambda_{rest}$, $\\mu m$')
# Plot the data points, and plot upper limits if they exist
for i,point in enumerate(um_data):
... | axobj.set_ylim(0.5*mjy_data[mjy_data>0.].min(),2*np.max(Sfit))
altax = axobj.twiny() | random_line_split |
decoder.rs | use crate::ebml;
use crate::schema::{Schema, SchemaDict};
use crate::vint::{read_vint, UnrepresentableLengthError};
use chrono::{DateTime, NaiveDateTime, Utc};
use err_derive::Error;
use log_derive::{logfn, logfn_inputs};
use std::convert::TryFrom;
pub trait ReadEbmlExt: std::io::Read {
#[logfn(ok = "TRACE", err =... | if parent_pos.r#type != 'm' {
// throw new Error("parent element is not master element");
unreachable!();
}
self.queue.push(
(
ebml::MasterEndElement {
ebml_id: parent_pos.ebml_id,
... | }
// 閉じタグを挿入すべきタイミングが来た | random_line_split |
decoder.rs | use crate::ebml;
use crate::schema::{Schema, SchemaDict};
use crate::vint::{read_vint, UnrepresentableLengthError};
use chrono::{DateTime, NaiveDateTime, Utc};
use err_derive::Error;
use log_derive::{logfn, logfn_inputs};
use std::convert::TryFrom;
pub trait ReadEbmlExt: std::io::Read {
#[logfn(ok = "TRACE", err =... | eadContentError {
#[error(display = "Date")]
Date(#[error(cause)] std::io::Error),
#[error(display = "Utf8")]
Utf8(#[error(cause)] std::io::Error),
#[error(display = "UnsignedInteger")]
UnsignedInteger(#[error(cause)] std::io::Error),
#[error(display = "Integer")]
Integer(#[error(cause)]... | // スタックからこのタグを捨てる
self.stack.pop();
}
Ok(true)
}
}
#[derive(Debug, Error)]
pub enum R | conditional_block |
decoder.rs | use crate::ebml;
use crate::schema::{Schema, SchemaDict};
use crate::vint::{read_vint, UnrepresentableLengthError};
use chrono::{DateTime, NaiveDateTime, Utc};
use err_derive::Error;
use log_derive::{logfn, logfn_inputs};
use std::convert::TryFrom;
pub trait ReadEbmlExt: std::io::Read {
#[logfn(ok = "TRACE", err =... |
}
impl From<ReadContentError> for DecodeError {
fn from(o: ReadContentError) -> Self {
DecodeError::ReadContent(o)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum State {
Tag,
Size,
Content,
}
pub struct Decoder<'a, D: SchemaDict<'a>> {
schema: &'a D,
... | {
DecodeError::ReadVint(o)
} | identifier_body |
decoder.rs | use crate::ebml;
use crate::schema::{Schema, SchemaDict};
use crate::vint::{read_vint, UnrepresentableLengthError};
use chrono::{DateTime, NaiveDateTime, Utc};
use err_derive::Error;
use log_derive::{logfn, logfn_inputs};
use std::convert::TryFrom;
pub trait ReadEbmlExt: std::io::Read {
#[logfn(ok = "TRACE", err =... | (o: ReadContentError) -> Self {
DecodeError::ReadContent(o)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum State {
Tag,
Size,
Content,
}
pub struct Decoder<'a, D: SchemaDict<'a>> {
schema: &'a D,
state: State,
buffer: Vec<u8>,
cursor: usize,
to... | from | identifier_name |
message.py | # encoding: utf-8
"""MIME-encoded electronic mail message classes."""
import logging
import os
import time
import warnings
from datetime import datetime
from turbomail import release
from turbomail.compat import Header, MIMEBase, MIMEImage, MIMEMultipart, MIMEText, encode_base64, formatdate, make_msgid
from turbom... | self._mime = message
self._processed = True
self._dirty = False
return message
mime = property(mime)
def attach(self, file, name=None):
"""Attach an on-disk file to this message."""
part = MIMEBase('application', "octet-stream")
if ... | random_line_split | |
message.py | # encoding: utf-8
"""MIME-encoded electronic mail message classes."""
import logging
import os
import time
import warnings
from datetime import datetime
from turbomail import release
from turbomail.compat import Header, MIMEBase, MIMEImage, MIMEMultipart, MIMEText, encode_base64, formatdate, make_msgid
from turbom... |
author = AddressList.protected('_author')
bcc = AddressList.protected('_bcc')
cc = AddressList.protected('_cc')
disposition = AddressList.protected('_disposition')
reply_to = AddressList.protected('_reply_to')
sender = AddressList.protected('_sender')
def __setattr__(self, name, v... | """Instantiate a new Message object.
No arguments are required, as everything can be set using class
properties. Alternatively, I{everything} can be set using the
constructor, using named arguments. The first three positional
arguments can be used to quickly prepare a simple m... | identifier_body |
message.py | # encoding: utf-8
"""MIME-encoded electronic mail message classes."""
import logging
import os
import time
import warnings
from datetime import datetime
from turbomail import release
from turbomail.compat import Header, MIMEBase, MIMEImage, MIMEMultipart, MIMEText, encode_base64, formatdate, make_msgid
from turbom... | (self, kw, new_name, deprecated_name, value=None):
deprecated_value = self.kwpop(kw, deprecated_name)
if deprecated_value != None:
self._warn_about_deprecated_property(deprecated_name, new_name)
value = deprecated_value
elif value == None:
value = self.kwpop(k... | pop_deprecated | identifier_name |
message.py | # encoding: utf-8
"""MIME-encoded electronic mail message classes."""
import logging
import os
import time
import warnings
from datetime import datetime
from turbomail import release
from turbomail.compat import Header, MIMEBase, MIMEImage, MIMEMultipart, MIMEText, encode_base64, formatdate, make_msgid
from turbom... |
def mime(self):
"""Produce the final MIME message."""
author = self.author
sender = self.sender
if not author and sender:
msg = 'Please specify the author using the "author" property. ' + \
'Using "sender" for the From header is deprecated!'
... | message.add_header(**header) | conditional_block |
kubeseal.go | package kubeseal
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
ssv1alpha1 "github.com/bitnami-labs/sealed-secrets/pkg/apis/sealedsecrets/v1alpha1"
"github.com/bitnami-labs/sealed-secrets/pkg/crypto... |
conf.AcceptContentTypes = "application/x-pem-file, */*"
restClient, err := corev1.NewForConfig(conf)
if err != nil {
return nil, err
}
return openCertCluster(ctx, restClient, controllerNs, controllerName)
}
// Seal reads a k8s Secret resource parsed from an input reader by a given codec, encrypts all its secre... | {
return nil, err
} | conditional_block |
kubeseal.go | package kubeseal
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
ssv1alpha1 "github.com/bitnami-labs/sealed-secrets/pkg/apis/sealedsecrets/v1alpha1"
"github.com/bitnami-labs/sealed-secrets/pkg/crypto... | (w io.Writer, secretName, ns string, data []byte, scope ssv1alpha1.SealingScope, pubKey *rsa.PublicKey) error {
// TODO(mkm): refactor cluster-wide/namespace-wide to an actual enum so we can have a simple flag
// to refer to the scope mode that is not a tuple of booleans.
label := ssv1alpha1.EncryptionLabel(ns, secr... | EncryptSecretItem | identifier_name |
kubeseal.go | package kubeseal
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
ssv1alpha1 "github.com/bitnami-labs/sealed-secrets/pkg/apis/sealedsecrets/v1alpha1"
"github.com/bitnami-labs/sealed-secrets/pkg/crypto... |
if len(secret.Data) == 0 && len(secret.StringData) == 0 && !allowEmptyData {
return fmt.Errorf("secret.data is empty in input Secret, assuming this is an error and aborting. To work with empty data, --allow-empty-data can be used")
}
if overrideName != "" {
secret.Name = overrideName
}
if secret.GetName() =... | if err != nil {
return err
} | random_line_split |
kubeseal.go | package kubeseal
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
ssv1alpha1 "github.com/bitnami-labs/sealed-secrets/pkg/apis/sealedsecrets/v1alpha1"
"github.com/bitnami-labs/sealed-secrets/pkg/crypto... |
func EncryptSecretItem(w io.Writer, secretName, ns string, data []byte, scope ssv1alpha1.SealingScope, pubKey *rsa.PublicKey) error {
// TODO(mkm): refactor cluster-wide/namespace-wide to an actual enum so we can have a simple flag
// to refer to the scope mode that is not a tuple of booleans.
label := ssv1alpha1.... | {
// #nosec G304 -- should open user provided file
f, err := os.OpenFile(filename, os.O_RDWR, 0)
if err != nil {
return err
}
// #nosec G307 -- we are explicitly managing a potential error from f.Close() at the end of the function
defer f.Close()
b, err := io.ReadAll(f)
if err != nil {
return err
}
orig... | identifier_body |
TableLaporan.ts | <?php
declare(strict_types=1);
namespace tlm\his\FatmaPharmacy\views\IkiDokterUi;
use tlm\libs\LowEnd\components\DateTimeException;
use Yii;
use yii\db\Exception;
/**
* @copyright PT Affordable App (Jl Mampang Prapatan VI no. 15B, Tegal Parang, Mampang, Jakarta Selatan, Jakarta, Indonesia)
* @license Affordabl... | ob_clean();
}
public function __toString(): string
{
return $this->output;
}
} | <?php
$this->output = ob_get_contents(); | random_line_split |
TableLaporan.ts | <?php
declare(strict_types=1);
namespace tlm\his\FatmaPharmacy\views\IkiDokterUi;
use tlm\libs\LowEnd\components\DateTimeException;
use Yii;
use yii\db\Exception;
/**
* @copyright PT Affordable App (Jl Mampang Prapatan VI no. 15B, Tegal Parang, Mampang, Jakarta Selatan, Jakarta, Indonesia)
* @license Affordabl... | else {
$racik++;
}
if ($resep->noResep != $resepnow) {
if ($resepnow) {
$tdSmf = $smfIsAll ? '<td></td>' : "";
$tdDokter = $dokterIsAll ? '<td></td>' : "";
$html .= "
... | {
$r++;
} | conditional_block |
TableLaporan.ts | <?php
declare(strict_types=1);
namespace tlm\his\FatmaPharmacy\views\IkiDokterUi;
use tlm\libs\LowEnd\components\DateTimeException;
use Yii;
use yii\db\Exception;
/**
* @copyright PT Affordable App (Jl Mampang Prapatan VI no. 15B, Tegal Parang, Mampang, Jakarta Selatan, Jakarta, Indonesia)
* @license Affordabl... | () {
minTanggalMulai = this._value;
},
...tlm.dateWidgetSetting
});
const tanggalSelesaiWgt = new spl.DateTimeWidget({
element: divElm.querySelector(".tanggalSelesaiFld"),
// numberOfMonths: 1,
onBeforeOpenDatetimePicker() {
... | onBeforeCloseDatetimePicker | identifier_name |
TableLaporan.ts | <?php
declare(strict_types=1);
namespace tlm\his\FatmaPharmacy\views\IkiDokterUi;
use tlm\libs\LowEnd\components\DateTimeException;
use Yii;
use yii\db\Exception;
/**
* @copyright PT Affordable App (Jl Mampang Prapatan VI no. 15B, Tegal Parang, Mampang, Jakarta Selatan, Jakarta, Indonesia)
* @license Affordabl... | ,
onBeforeCloseDatetimePicker() {
minTanggalMulai = this._value;
},
...tlm.dateWidgetSetting
});
const tanggalSelesaiWgt = new spl.DateTimeWidget({
element: divElm.querySelector(".tanggalSelesaiFld"),
// numberOfMonths: 1,
... | {
this._maxDate = maksTanggalSelesai;
} | identifier_body |
ItemView.js | /**
* @file View that builds the map by showing the items' images at their specified locations.
*/
"use strict";
/**
* @class ItemView
*/
function ItemView() {
// Private variables
// These are jQuery objects corresponding to elements
let $mapImage;
let $carpet;
let $backArrow;
let $forw... | // The angle of the direction we take to get to the item. Used to rotate the carpet accordingly
const angle = Math.atan2(delta_y, delta_x) * (180 / Math.PI);
if (performAnimations) {
// Rotating the carpet
$carpet.velocity({ trans... | // Differences in x and y we need to travel to get to the item from the current position
const delta_x = (currentLeft - positionItemToVisitNext.left);
const delta_y = (currentTop - positionItemToVisitNext.top);
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.