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
lib.rs
!( $($tail)* ).put($k.into(), $v.into()) }; } #[macro_export] macro_rules! try_opt { ($expr:expr) => { match $expr { Ok(val) => val, Err(err) => return Err(err), } }; } #[doc(hidden)] pub struct Client { _private: (), } /// Clickhouse client handle. pub struct ...
Box::pin(f(self)) } }
conditional_block
git_ftp.js
1); //remove values from array } } while(index > 0); return this; }; grunt.util = grunt.util || grunt.utils; var session = {}, async = grunt.util.async, log = grunt.log, _ = grunt.util._, file = grunt.file, fs = require('fs'), path = require('path'), FtpClient = require('f...
log.ok('Uploaded from: ' + filepath + ' >> ' + host.blue + '@' + path.normalize(remoteRootPath + '/' + filepath).green); ftp.end(); nextArray(); }); },function(err){ cb(null); }); }else{ cb(true,'error while uploading file');...
{ cb(true,err); throw err; }
conditional_block
git_ftp.js
untGitFtp = function(){ this.hostConfig = null; return this; }; /* * Get host file and parse json */ GruntGitFtp.prototype.getHostFile = function(hostName,filename){ //check if file exist if(fs.existsSync(filename)){ //check key value if(hostName != null){ ...
random_line_split
main.rs
//! below. //! //! ### Linux / OS X //! //! You have two options, place `cargo-count` into a directory that is already //! located in your `$PATH` variable (To see which directories those are, open //! a terminal and type `echo "${PATH//:/\n}"`, the quotation marks are //! important), or you can add a custom directory...
{ debugln!("executing; cmd=execute;"); verboseln!(cfg, "{}: {:?}", Format::Warning("Excluding"), cfg.exclude); verbose!( cfg, "{}", if cfg.exts.is_some() { format!( "{} including files with extension: {}\n", Format::Warning("Only"), ...
identifier_body
main.rs
327,792 3,163 //! (0.96%) //! C 54 9,962 1,445 1,492 7,025 7,025 //! (100.00%) //! CSS 4 1,266 149 52 1,065 //! JavaScript 4 1,118 131 166 821 //! Python 31 4,797 843 585 3,369 //! C Header 13 ...
extern crate clap; #[cfg(feature = "color")] extern crate ansi_term; extern crate gitignore; extern crate glob; extern crate regex; extern crate tabwriter; #[cfg(feature = "debug")] use std::env; use clap::{App, AppSettings, Arg, SubCommand}; use config::Config; use count::Counts; use error::{CliError, CliResult}; u...
)] #[macro_use]
random_line_split
main.rs
terminal and type `echo "${PATH//:/\n}"`, the quotation marks are //! important), or you can add a custom directory to your `$PATH` //! //! **Option 1** //! If you have write permission to a directory listed in your `$PATH` or you //! have root permission (or via `sudo`), simply copy the `cargo-count` to that //! dire...
{ Ok(()) }
conditional_block
main.rs
that is already //! located in your `$PATH` variable (To see which directories those are, open //! a terminal and type `echo "${PATH//:/\n}"`, the quotation marks are //! important), or you can add a custom directory to your `$PATH` //! //! **Option 1** //! If you have write permission to a directory listed in your `$...
single_char
identifier_name
route.rs
diags); attr.path.query.as_ref().map(|q| dup_check(&mut segments, q.iter().cloned(), &mut diags)); dup_check(&mut segments, attr.data.clone().map(|s| s.value.0).into_iter(), &mut diags); // Check the validity of function arguments. let mut inputs = vec![]; let mut fn_segments: IndexSet<Segment> = ...
#[allow(non_snake_case, unreachable_patterns, unreachable_code)] let #ident: #ty = #expr; } } fn data_expr(ident: &syn::Ident, ty: &syn::Type) -> TokenStream2 { define_vars_and_mods!(req, data, FromData, Outcome, Transform); let span = ident.span().unstable().join(ty.span()).unwrap().into()...
}; quote! {
random_line_split
route.rs
{ #[meta(naked)] method: SpanWrapped<Method>, path: RoutePath, data: Option<SpanWrapped<DataSegment>>, format: Option<MediaType>, rank: Option<isize>, } /// The raw, parsed `#[method]` (e.g, `get`, `put`, `post`, etc.) attribute. #[derive(Debug, FromMeta)] struct MethodRouteAttribute { #[m...
RouteAttribute
identifier_name
route.rs
dup_check(&mut segments, attr.path.path.iter().cloned(), &mut diags); attr.path.query.as_ref().map(|q| dup_check(&mut segments, q.iter().cloned(), &mut diags)); dup_check(&mut segments, attr.data.clone().map(|s| s.value.0).into_iter(), &mut diags); // Check the validity of function arguments. let...
{ for segment in iter.filter(|s| s.kind != Kind::Static) { let span = segment.span; if let Some(previous) = set.replace(segment) { diags.push(span.error(format!("duplicate parameter: `{}`", previous.name)) .span_note(previous.span, "previous parameter ...
identifier_body
sendmail.rs
); } if strlen(answer) <= 3i32 as libc::c_ulong || '-' as i32 != *answer.offset(3) as libc::c_int { break; } free(answer as *mut libc::c_void); } if !answer.is_null() { let mut n: libc::c_int = atoi(answer); if (*ptr_to_globals).timeout != 0 { alarm(0i32 as libc::c_uint); ...
{ let mut answer: *mut libc::c_char = 0 as *mut libc::c_char; let mut msg: *mut libc::c_char = send_mail_command(fmt, param); loop // read stdin // if the string has a form NNN- -- read next string. E.g. EHLO response // parse first bytes to a number // if code = -1 then just return this number // if co...
identifier_body
sendmail.rs
, a.offset(1), ); } } } // N.B. list == NULL here //bb_error_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv); // connect to server // connection helper ordered? -> if (*ptr_to_globals).opts & OPT_H as libc::c_int as libc::c_uint != 0 { let mut delay: ...
{ current_block = 16252544171633782868; }
conditional_block
sendmail.rs
libc::c_char = send_mail_command(fmt, param); loop // read stdin // if the string has a form NNN- -- read next string. E.g. EHLO response // parse first bytes to a number // if code = -1 then just return this number // if code != -1 then checks whether the number equals the code // if not equal -> die sa...
(mut list: *const libc::c_char) { let mut free_me: *mut libc::c_char = xstrdup(list); let mut str: *mut libc::c_char = free_me; let mut s: *mut libc::c_char = free_me; let mut prev: libc::c_char = 0i32 as libc::c_char; let mut in_quote: libc::c_int = 0i32; while *s != 0 { let fresh0 = s; s = s.offse...
rcptto_list
identifier_name
sendmail.rs
32 { bb_simple_error_msg_and_die(b"SMTP init failed\x00" as *const u8 as *const libc::c_char); } } else { // vanilla connection let mut fd: libc::c_int = 0; fd = create_and_connect_stream_or_die(opt_connect, 25i32); // and make ourselves a simple IO filter xmove_fd(fd, 0i32); xdup2(0...
b"Bcc:\x00" as *const u8 as *const libc::c_char, s, 4i32 as libc::c_ulong, )
random_line_split
replicaset.go
// the controller needs to create a new template status for it newTemplate := v1alpha1.TemplateStatus{ Name: template.Name, CollisionCount: new(int32), } // Matching ReplicaSet is not equal - increment the collisionCount in the ExperimentStatus // and requeue the Experiment. preCollisionCo...
scaleReplicaSet
identifier_name
replicaset.go
"github.com/argoproj/argo-rollouts/pkg/apis/rollouts/v1alpha1" "github.com/argoproj/argo-rollouts/utils/conditions" "github.com/argoproj/argo-rollouts/utils/defaults" experimentutil "github.com/argoproj/argo-rollouts/utils/experiment" "github.com/argoproj/argo-rollouts/utils/hash" logutil "github.com/argoproj/arg...
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" patchtypes "k8s.io/apimachinery/pkg/types" labelsutil "k8s.io/kubernetes/pkg/util/labels"
random_line_split
replicaset.go
.MergePatchType, []byte(patch), metav1.PatchOptions{}) ec.log.WithField("patch", patch).Debug("Applied Patch") if patchErr != nil { ec.log.Errorf("Error patching service %s", err.Error()) return nil, patchErr } ec.log.Warnf("Found a hash collision - bumped collisionCount (%d->%d) to resolve it", preCollis...
{ ctx := context.TODO() oldScale := *(rs.Spec.Replicas) sizeNeedsUpdate := oldScale != newScale scaled := false var err error if sizeNeedsUpdate { rsCopy := rs.DeepCopy() *(rsCopy.Spec.Replicas) = newScale rs, err = ec.kubeclientset.AppsV1().ReplicaSets(rsCopy.Namespace).Update(ctx, rsCopy, metav1.UpdateOpt...
identifier_body
replicaset.go
!= nil { return nil, err } templateDefined := func(name string) bool { for _, tmpl := range experiment.Spec.Templates { if tmpl.Name == name { return true } } return false } templateToRS := make(map[string]*appsv1.ReplicaSet) for _, rs := range rsList { controllerRef := metav1.GetControllerOf(...
if templateDefined(templateName) { templateToRS[templateName] = rs logCtx := log.WithField(logutil.ExperimentKey, experiment.Name).WithField(logutil.NamespaceKey, experiment.Namespace) logCtx.Infof("Claimed ReplicaSet '%s' for template '%s'", rs.Name, templateName) } } } return templateToRS, nil...
{ return nil, fmt.Errorf("multiple ReplicaSets match single experiment template: %s", templateName) }
conditional_block
TongitzApi.ts
store in var let players = p.map((x,i) => { return { id:i+1, name:x, turn:i+1, hand:[] } as domain.playerStatus }) //make deck, shuffle, store in var let deck = this.shuffle(this.generateDeck()); ...
let gameDiscards = this._svc.getDiscards(gameId); proposedHand.push(gameDiscards[gameDiscards.length-1]);//last discard gamePlayer.hand.filter(x => playerCardIds.indexOf(x.id) != -1).forEach(x => proposedHand.push(x));//hand card to combine // playerCardIds.map(x => gamePlayer.hand[game...
//get lastDiscard as card
random_line_split
TongitzApi.ts
(gameId?:number,...p: string[]) : void//: gameStateResource { { gameId = gameId || 1; if(p.length < 2 || p.length > 3) throw "500","error"; //set gameId, turn, phase this._svc.addGame(gameId,1,domain.turnPhaseEnum.play); //make players, set name,turn,id , store in var ...
NewGame
identifier_name
TongitzApi.ts
in var let players = p.map((x,i) => { return { id:i+1, name:x, turn:i+1, hand:[] } as domain.playerStatus }) //make deck, shuffle, store in var let deck = this.shuffle(this.generateDeck()); /...
// playerCardIds.map(x => gamePlayer.hand[gamePlayer.hand.map(x => x.id).indexOf(x)]).forEach(x => proposedHand.push(x));// same, just cool this.validateCombination(proposedHand); //new house let gameHouses = this._svc.getHouses(gameId); let newHouse:domain.house = new domain.hou...
{ this.validateGameOnGoing(this._svc.getWinMethod(gameId)); if(playerCardIds.length < 2) //check if there are at least 2 cards { throw "badRequest:can't form a house with less than 3 cards" } let gameTurn = this._svc.getTurn(gameId); let gamePhase = this._svc....
identifier_body
TongitzApi.ts
in var let players = p.map((x,i) => { return { id:i+1, name:x, turn:i+1, hand:[] } as domain.playerStatus }) //make deck, shuffle, store in var let deck = this.shuffle(this.generateDeck()); /...
this._svc.applyState(gameId); } public Play(gameId:number, playerId: number, playCards: resource.playRequestResource){ this.validateGameOnGoing(this._svc.getWinMethod(gameId)); //discard is required if(!(playCards ? !isNaN(playCards.discard) ? true : false : false)) ...
{ this._svc.setWinner(gameId,playerId,domain.winMethodEnum.noHand); }
conditional_block
cookie_article_parser.py
if short_date == "Jun": return 6 if short_date == "Jul": return 7 if short_date == "Aug": return 8 if short_date == "Sep": return 9 if short_date == "Oct": return 10 if short_date == "Nov": return 11 if short_date == "Dec": return 12 return -1 def load_secret(): fname = "secret_sauce.d...
def load_creds_login(): fname="wsjcreds.dat" f = open(fname,"r") uname = f.readline().split(' ')[1] pw = f.readline().split(' ')[1] f.close() # Input username loginID = browser.find_element_by_id("username").send_keys(uname) # Input password loginPass = browser.find_el...
db.close()
identifier_body
cookie_article_parser.py
if short_date == "Jun": return 6 if short_date == "Jul": return 7 if short_date == "Aug": return 8 if short_date == "Sep": return 9 if short_date == "Oct": return 10 if short_date == "Nov": return 11 if short_date == "Dec": return 12 return -1 def load_secret(): fname = "secret_sauce.d...
(): options = Options() #options.add_argument("--headless") browser = webdriver.Firefox(firefox_options=options, executable_path='/home/shelbyt/geckodriver') return browser def profile_comment_load(browser): #for i in range(0,3): # print "range" # load_more = browser.find_element_...
sel_init
identifier_name
cookie_article_parser.py
if short_date == "Jun": return 6 if short_date == "Jul": return 7 if short_date == "Aug": return 8 if short_date == "Sep": return 9 if short_date == "Oct": return 10 if short_date == "Nov": return 11 if short_date == "Dec": return 12 return -1 def load_secret(): fname = "secret_sauce.d...
return len(profile_url) def insert_article_user_comments(browser, db, cursor): login_flag = 0 for profile in profile_url: print "Trying to load = " + profile browser.get(profile) if login_flag == 0: load_creds_login() login_flag = 1 profile_comment
if user not in profile_url: # Get the actual users profile url here # TODO(shelbyt): Fix bad naming user is a userblock match = re.search('.*\/(.*)\?',user.get_attribute("href")) # Returns a user_id which we can match with the database list article_user_id = s...
conditional_block
cookie_article_parser.py
if short_date == "Jun": return 6 if short_date == "Jul": return 7 if short_date == "Aug": return 8 if short_date == "Sep": return 9 if short_date == "Oct": return 10 if short_date == "Nov": return 11 if short_date == "Dec": return 12 return -1 def load_secret(): fname = "secret_sauc...
db_date = datetime.datetime(int(real_t_arr[2]), int(month_to_num(real_t_arr[0])),int(real_t_arr[1])).date().strftime("%Y-%m-%d") db_time=t_format # without this str encoding i get a 'latin-1 codec cant encode character' # use ascii ignore to remove any weird characters ...
################## INSERT EVERYTHING INTO THE GLOBAL DB STRINGS ############## # just use the date part of date_time
random_line_split
pylon.go
nil { return nil, err } m.Route = RegexRoute{ Regex: reg, } } else if s.Prefix != "" { m.Route = PrefixRoute{ Prefix: s.Prefix, } } else { return nil, ErrServiceNoRoute } maxCon := defaultMaxCon if s.MaxCon > 0 { maxCon = s.MaxCon } var weightSum float32 = 0.0 for _...
random_line_split
pylon.go
MicroService returns a new MicroService object given a Service func NewMicroService(s *Service) (*MicroService, error) { m := &MicroService{} if s.Pattern != "" { reg, err := regexp.Compile(s.Pattern) if err != nil { return nil, err } m.Route = RegexRoute{ Regex: reg, } } else if s.Prefix ...
{ if lastNonNil != -1 { return lastNonNil, nil } return -1, ErrFailedRoundRobin }
conditional_block
pylon.go
var weight float32 = 1 if inst.Weight > 0 { weight = inst.Weight } weightSum += weight m.Instances = append(m.Instances, &Instance{ inst.Host, weight, make(chan int, maxCon), NewSharedInt(0), }) } m.Name = s.Name m.Strategy = s.Strategy m.Mutex = &sync.RWMutex{} m.BlackLi...
{ minLoad := maxFloat32 idx := 0 for i, inst := range instances { if inst == nil { continue } load := float32(len(inst.ReqCount)) / inst.Weight if load < minLoad { minLoad = load idx = i } } return idx }
identifier_body
pylon.go
RegexRoute struct { Regex *regexp.Regexp } type PrefixRoute struct { Prefix string } func (r RegexRoute) Type() RouteType { return Regex } func (r RegexRoute) Data() interface{} { return r.Regex } func (p PrefixRoute)
() RouteType { return Prefix } func (p PrefixRoute) Data() interface{} { return p.Prefix } // ListenAndServe tries to parse the config at the given path and serve it func ListenAndServe(p string) error { jsonParser := JSONConfigParser{} c, err := jsonParser.ParseFromPath(p) if err != nil { return ...
Type
identifier_name
trial_purpose.py
plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'trialPurpose_{}.qm'.format(locale)) if os.path.exists(...
return shortest
random_line_split
trial_purpose.py
.py import resources # Import the code for the dialog from trial_purpose_dialog import trialPurposeDialog import os.path from qgis.core import QgsMapLayerRegistry from qgis.core import QgsVectorLayer, QgsDataSourceURI from qgis.core import * from PyQt4.QtGui import * import qgis from PyQt4.QtSql import QSqlDatabase f...
(self): print('onClickBtn2') aptName = self.dlg.q2combo.currentText() # Reuse the path to DB to set database name uri = QgsDataSourceURI() uri.setDatabase('F:/UTA/SEM 5/Adv DB/UTA_Final_DB/test.sqlite') db = QSqlDatabase.addDatabase('QSPATIALITE'); ...
onClickBtn2
identifier_name
trial_purpose.py
.py import resources # Import the code for the dialog from trial_purpose_dialog import trialPurposeDialog import os.path from qgis.core import QgsMapLayerRegistry from qgis.core import QgsVectorLayer, QgsDataSourceURI from qgis.core import * from PyQt4.QtGui import * import qgis from PyQt4.QtSql import QSqlDatabase f...
def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path ...
"""Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspe...
identifier_body
trial_purpose.py
using Python3 so QString is not defined QString = type("") rbDict = {} class trialPurpose: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you ...
query = db.exec_("Select id from Final_poly where name='{0}'".format(aptName)); while query.next(): record = query.record() myList.append(record.value(0)) print(myList) selectedLayerIndex = "final_poly" self.iface.setActiveLayer(QgsMapLaye...
conditional_block
key_bundle_v2.go
bfscrypto.TLFEphemeralPublicKey{}, fmt.Errorf("Invalid key in %s with index %d >= %d", keyLocation, index, keyCount) } return keyLocation, index, publicKeys[index], nil } // DeviceKeyInfoMapV2 is a map from a user devices (identified by the // KID of the corresponding device CryptPublicKey) to the // TLF's s...
() DevicePublicKeys { publicKeys := make(DevicePublicKeys, len(dkimV2)) for kid := range dkimV2 { publicKeys[kbfscrypto.MakeCryptPublicKey(kid)] = true } return publicKeys } // UserDeviceKeyInfoMapV2 maps a user's keybase UID to their // DeviceKeyInfoMapV2. type UserDeviceKeyInfoMapV2 map[keybase1.UID]DeviceKeyI...
toPublicKeys
identifier_name
key_bundle_v2.go
) { serverHalves = make(DeviceKeyServerHalves, len(updatedDeviceKeys)) // TODO: parallelize for k := range updatedDeviceKeys { // Skip existing entries, and only fill in new ones. if _, ok := dkimV2[k.KID()]; ok { continue } clientInfo, serverHalf, err := splitTLFCryptKey( uid, tlfCryptKey, ePrivKey, ...
if err != nil { return TLFWriterKeyBundleV2{}, TLFWriterKeyBundleV3{}, err }
random_line_split
key_bundle_v2.go
info for any device that is not // contained in the given map of users and devices. func (udkimV2 UserDeviceKeyInfoMapV2) RemoveDevicesNotIn( updatedUserKeys UserDevicePublicKeys) ServerHalfRemovalInfo { removalInfo := make(ServerHalfRemovalInfo) for uid, dkim := range udkimV2 { userRemoved := false deviceServe...
return KeyGen(len(rkg)) } /
identifier_body
key_bundle_v2.go
it is initially created (so // those devices can get access to existing data), we track // multiple ephemeral public keys; the one used by a // particular device is specified by EPubKeyIndex in its // TLFCryptoKeyInfo struct. TLFEphemeralPublicKeys kbfscrypto.TLFEphemeralPublicKeys `codec:"ePubKey"` codec.Unkno...
rkbV3.TLFEphemeralPublicKeys = append(rkbV3.TLFEphemeralPublicKeys, ePubKey) // TODO: This index depends on // map iteration order, which // varies. Impose a consistent // order on these indices. newIndex = len(rkbV3.TLFEphemeralPublicKeys) - 1 pubKeyIndicesMap[index] = newIndex ...
conditional_block
redisstore.go
conn := rs.GetConn() defer conn.Close() //Todo protect for duped names memberKey := rs.keyJoiner(rs.runContext, "_redis", "_member", config.MyMachineID) leader, err := rs.LeaderName() utils.HandleError(err) if leader == config.MyMachineID { rs.runContext.Lock() config.MyType = types.TypeSporeLeader rs.run...
return }
random_line_split
redisstore.go
string { items := append(runContext.NamespacePrefixParts(), parts...) return strings.Join(items, ":") } func (rs RedisStore) typeKey(runContext *types.RunContext, v interface{}, parts ...string) string { meta, err := types.NewMeta(v) utils.HandleError(err) parts = append([]string{meta.TypeName}, parts...) retur...
(server string) *redis.Pool { return &redis.Pool{ MaxIdle: 10, IdleTimeout: 240 * time.Second, Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", server) if err != nil { return nil, err } return c, err }, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do(...
newRedisConnPool
identifier_name
redisstore.go
string
func (rs RedisStore) typeKey(runContext *types.RunContext, v interface{}, parts ...string) string { meta, err := types.NewMeta(v) utils.HandleError(err) parts = append([]string{meta.TypeName}, parts...) return rs.keyJoiner(runContext, parts...) } func (rs *RedisStore) runLeaderElection() { config := rs.runConte...
{ items := append(runContext.NamespacePrefixParts(), parts...) return strings.Join(items, ":") }
identifier_body
redisstore.go
string { items := append(runContext.NamespacePrefixParts(), parts...) return strings.Join(items, ":") } func (rs RedisStore) typeKey(runContext *types.RunContext, v interface{}, parts ...string) string { meta, err := types.NewMeta(v) utils.HandleError(err) parts = append([]string{meta.TypeName}, parts...) retur...
wasSet, err := redis.Int(conn.Do(op, typeKey, id, data)) if err != nil { return wrapError(err) } if wasSet == 1 || update { meta, err := types.NewMeta(v) utils.HandleError(err) action := types.StoreActionUpdate if !update { action = types.StoreActionCreate } types.StoreEvent(action, meta).EmitAll(...
{ op = "HSETNX" }
conditional_block
InteractiveFormsTest.go
Page.AnnotPushBack(signature1) // CheckBox Widget Creation // Create a check box widget that is not checked. check1 := CheckBoxWidgetCreate(doc, NewRect(140.0, 490.0, 170.0, 520.0)) check1.RefreshAppearance() blankPage.AnnotPushBack(check1) // Create a check box widget that is checked. chec...
{ fmt.Println("Field search for " + f.GetName() + " was successful") }
conditional_block
InteractiveFormsTest.go
()) stm := writer.End() // Set the bounding box stm.PutRect("BBox", 0.0, 0.0, 101.0, 37.0) stm.PutName("Subtype","Form") return stm } func
(){ PDFNetInitialize() // The map (vector) used to store the name and count of all fields. // This is used later on to clone the fields fieldNames:= make(map[string]int) //---------------------------------------------------------------------------------- // Example 1: Programatically create ne...
main
identifier_name
InteractiveFormsTest.go
()) stm := writer.End() // Set the bounding box stm.PutRect("BBox", 0.0, 0.0, 101.0, 37.0) stm.PutName("Subtype","Form") return stm } func main(){ PDFNetInitialize() // The map (vector) used to store the name and count of all fields. // This is used later on to clone t...
radiobutton1.RefreshAppearance() radiobutton2 := radioGroup.Add(NewRect(310.0, 410.0, 360.0, 460.0)) radiobutton2.SetBackgroundColor(NewColorPt(0.0, 1.0, 0.0), 3) radiobutton2.RefreshAppearance() radiobutton3 := radioGroup.Add(NewRect(480.0, 410.0, 530.0, 460.0)) // Enable the third radio button...
// RadioButton Widget Creation // Create a radio button group and Add three radio buttons in it. radioGroup := RadioButtonGroupCreate(doc, "RadioGroup") radiobutton1 := radioGroup.Add(NewRect(140.0, 410.0, 190.0, 460.0)) radiobutton1.SetBackgroundColor(NewColorPt(1.0, 1.0, 0.0), 3)
random_line_split
InteractiveFormsTest.go
if buttonDown{ element.SetTextMatrix(1.0, 0.0, 0.0, 1.0, 33.0, 10.0) }else{ element.SetTextMatrix(1.0, 0.0, 0.0, 1.0, 30.0, 13.0) } writer.WriteElement(element) writer.WritePlacedElement(build.CreateTextEnd()) stm := writer.End() // Set the bounding box stm.PutRe...
{ // Create a button appearance stream ------------------------------------ build := NewElementBuilder() writer := NewElementWriter() writer.Begin(doc.GetSDFDoc()) // Draw background element := build.CreateRect(0.0, 0.0, 101.0, 37.0) element.SetPathFill(true) element.SetPathStroke(f...
identifier_body
agollo.go
ReleaseKey(cachedReleaseKey.(string)), ) if err != nil { return true } if status == http.StatusOK { oldValue := a.getNamespace(namespaceStr) a.cache.Store(namespace, config.Configurations) a.releaseKeyMap.Store(namespace, config.ReleaseKey) if err = a.backup(namespaceStr, config.Configurations); ...
req, "ServerResponseStatus", status, "Error", err, "Action", "LongPoll") return nil,
conditional_block
agollo.go
Namespace", namespace, "Action", "Backup", "Error", err) } a.sendWatchCh(namespaceStr, oldValue, config.Configurations) a.notificationMap.Store(namespaceStr, config.ReleaseKey) } return true }) } func (a *agollo) shouldStop() bool { select { case <-a.stopCh: return true default: return false ...
random_line_split
agollo.go
取备份 if a.opts.FailTolerantOnBackupExists { backupConfig, lerr := a.loadBackupByNamespace(namespace) if lerr != nil { a.log("BackupFile", a.opts.BackupFile, "Namespace", namespace, "Action", "loadBackupByNamespace", "Error", lerr) return } a.cache.Store(namespace, backupConfig) conf = back...
RL有点蛋疼 func (a *agollo) sendErrorsCh(configServerURL string, notifications []Notification, namespace string, err error) { longPollerError := &LongPollerError{ ConfigServerURL: configServerURL, AppID: a.opts.AppID, Cluster: a.opts.Cluster, Notifications
identifier_body
agollo.go
的修改,返回notifications为空数组,遍历空数组跳过 for _, notification := range notifications { // 读取旧缓存用来给监听队列 oldValue := a.getNamespace(notification.NamespaceName) // 更新namespace status, newValue, err := a.reloadNamespace(notification.NamespaceName) if err == nil { // Notifications 有更新,但是 GetConfigsFromNonCache 返回 304,...
identifier_name
main.js
a plugin (remember note) */ //Validation - Email $('input.email').each(function() { initializeInput($('input.email'), $("input.email").formance('validate_email')); }); $('input.email').on('keyup change', function() { validate($(this), $(this).formance('validate_email'), "has-warning", $("#invalid-email")...
element.append($match); } } //Dialog function messageDialog(type, message) { switch(type) { case "success": $("#dialog-message") .removeClass("error") .text(message) .addClass("success"); $(".bs-example-modal-sm").modal("show"); break; case "error": $("#dialog-message") .removeClass("success"...
random_line_split
main.js
plugin (remember note) */ //Validation - Email $('input.email').each(function() { initializeInput($('input.email'), $("input.email").formance('validate_email')); }); $('input.email').on('keyup change', function() { validate($(this), $(this).formance('validate_email'), "has-warning", $("#invalid-email").t...
} } function initializeInput(input, isValid) { if (input.parent().parent().parent().children().hasClass("error")) { if (isValid) { input.parent().addClass("has-success"); input.siblings().fadeIn(); } else { input.parent().prev().show(); input.parent().addClass('has-error'); input.siblings().fadeO...
{ input.parent().prev().html(message); input.parent().prev().fadeIn(); }
conditional_block
main.js
plugin (remember note) */ //Validation - Email $('input.email').each(function() { initializeInput($('input.email'), $("input.email").formance('validate_email')); }); $('input.email').on('keyup change', function() { validate($(this), $(this).formance('validate_email'), "has-warning", $("#invalid-email").t...
// Returns boolean whether the input has the minimum size required function inBounds(actual, min) { if (actual < min) return false; else return true; } function confirmPass(actual, current) { if (actual != current || current == "") return false; else return true; } //Fills options with flags only funct...
{ if (input.parent().parent().parent().children().hasClass("error")) { if (isValid) { input.parent().addClass("has-success"); input.siblings().fadeIn(); } else { input.parent().prev().show(); input.parent().addClass('has-error'); input.siblings().fadeOut(); } } }
identifier_body
main.js
plugin (remember note) */ //Validation - Email $('input.email').each(function() { initializeInput($('input.email'), $("input.email").formance('validate_email')); }); $('input.email').on('keyup change', function() { validate($(this), $(this).formance('validate_email'), "has-warning", $("#invalid-email").t...
(element) { var ddData = []; for (var i in teams) { if (teams[i].id == 7) ddData.push( { text: teams[i].name, value: teams[i].id, imageSrc: "assets/images/external/flags/" + teams[i].logo, selected: true } ); else ddData.push( { text: teams[i].name, value: teams[i].id, imageSrc: "assets/images/external/fla...
teamOptionLabel
identifier_name
atm.py
else : print('Masukan tidak valid.') else: print('Saldo tidak cukup') return saldo #Deklarasi Fungsi Pulsa def pulsa(saldo,history,namakartu): #Program menampilkan menu pilihan pengisian pulsa #KAMUS LOKAL #saldo, kodepulsa : int #history : 3d matriks of integer and string #namakartun: string #ALGORITMA ...
# Pembayaran listrik, air, pendidikan, pulsa(Allief Nuriman) elif transaksi == 2 : print("1. Listrik") print("2. Air") print("3. Pendidikan") print("4. Pulsa") tujuantrf = int(input("Masukkan kode tujuan transfer : ")) #Pembayaran Listrik if tujuantrf == 1 : norek = int(input("Silakan masuk...
print(history[indeksorang][i][j],end=' | ' ) print()
random_line_split
atm.py
(data): #Registrasi digunakan untuk menambahkan user baru pada database #KAMUS LOKAL #databaru : array of integer #ALGORITMA FUNGSI databaru=[0 for i in range (3)] databaru[0]=input('Masukkan nama: ') databaru[1]=input('Masukkan PIN anda (Terdiri dari 6 digit angka): ') while((databaru[1].isdigit()==False)or(...
registrasi
identifier_name
atm.py
else : print('Masukan tidak valid.') else: print('Saldo tidak cukup') return saldo #Deklarasi Fungsi Pulsa def pulsa(saldo,history,namakartu): #Program menampilkan menu pilihan pengisian pulsa #KAMUS LOKAL #saldo, kodepulsa : int #history : 3d matriks of integer and string #namakartun: string #ALGORITMA ...
# ALGORITMA UTAMA jumlahorang=4 data=[[0 for j in range (3)] for i in range (jumlahorang)] history=[[[0 for j in range (2)] for i in range (3)] for k in range(jumlahorang)] atmbarunyala=True #Kolom pertama berisi nama #Kolom kedua berisi PIN #Kolom ketiga berisi saldo #Deklarasi database awal data[0][0]='Theodore J...
print('Anda akan mengisi pulsa kartu',namakartu) print('Pilih nominal yang anda inginkan') print('1. 50.000') print('2. 100.000') print('3. 150.000') print('4. 200.000') kodepulsa=int(input()) print('Masukkan nomor HP Anda') nohp=int(input()) for i in range (4): if i+1==kodepulsa : saldo=konfirmasipulsa(s...
identifier_body
atm.py
else : print('Masukan tidak valid.') else: print('Saldo tidak cukup') return saldo #Deklarasi Fungsi Pulsa def pulsa(saldo,history,namakartu): #Program menampilkan menu pilihan pengisian pulsa #KAMUS LOKAL #saldo, kodepulsa : int #history : 3d matriks of integer and string #namakartun: string #ALGORITMA ...
if(pinangkasemua==False)and (coba<2): print('Pin harus berupa kombinasi dari 6 digit angka') print('Silahkan masukkan ulang PIN anda') elif((pinadadidatabase==False)and(coba<2)): print('Pin anda salah, silahkan masukkan ulang PIN anda') coba+=1 if((coba==3)and(pinangkasemua!=True)and(pinadadidat...
if(int(data[indeksorang][1])==int(pin)): pinadadidatabase=True
conditional_block
service.go
any async callbacks func (ac *asyncCallbacksHandler) push(f func()) { ac.cbQueue <- f } func (ac *asyncCallbacksHandler) close() { close(ac.cbQueue) } func (c *Config) valid() error { if !nameRegexp.MatchString(c.Name) { return fmt.Errorf("%w: service name: name should not be empty and should consist of alphanu...
{ endpointSubject = subject }
conditional_block
service.go
`json:"name"` // Endpoint is an optional endpoint configuration. // More complex, multi-endpoint services can be configured using // Service.AddGroup and Service.AddEndpoint methods. Endpoint *EndpointConfig `json:"endpoint"` // Version is a SemVer compatible version string. Version string `json:"version...
service: s, prefix: name, } } // dispatch is responsible for calling any async callbacks func (ac *asyncCallbacksHandler) run() { for { f := <-ac.cbQueue if f == nil { return } f() } } // dispatch is responsible for calling any async callbacks func (ac *asyncCallbacksHandler) push(f func()) { ac.c...
} func (s *service) AddGroup(name string) Group { return &group{
random_line_split
service.go
// this regular expression is suggested regexp for semver validation: https://semver.org/ semVerRegexp = regexp.MustCompile(`^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$`) nameRegexp...
matchEndpointSubject
identifier_name
service.go
0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$`) nameRegexp = regexp.MustCompile(`^[A-Za-z0-9\-_]+$`) subjectRegexp = regexp.MustCompile(`^[^ >]*[>]?$`) ) // Common errors returned by the Service framework. var ( // ErrConfigValidation is returned when service configuration is invalid ErrConfigVa...
{ subjectTokens := strings.Split(literalSubject, ".") endpointTokens := strings.Split(endpointSubject, ".") if len(endpointTokens) > len(subjectTokens) { return false } for i, et := range endpointTokens { if i == len(endpointTokens)-1 && et == ">" { return true } if et != subjectTokens[i] && et != "*" {...
identifier_body
game_tree.rs
at that point in time. /// Uses lazy evaluation to avoid storing the entire data structure /// in memory. See the LazyGameTree struct for more info. /// /// Note that there is no case when a player is stuck; we simply /// skip their turn if they have no moves and move /// to the next Turn state. #[derive(Debug)] pub ...
(&self) -> &GameState { match self { GameTree::Turn { state, .. } => state, GameTree::End(state) => state, } } /// Returns a mutable reference to the GameState of the current node of the GameTree pub fn get_state_mut(&mut self) -> &mut GameState { match self ...
get_state
identifier_name
game_tree.rs
at that point in time. /// Uses lazy evaluation to avoid storing the entire data structure /// in memory. See the LazyGameTree struct for more info. /// /// Note that there is no case when a player is stuck; we simply /// skip their turn if they have no moves and move /// to the next Turn state. #[derive(Debug)] pub ...
GameTree::Turn { valid_moves, .. } => { valid_moves.get_mut(&move_).map(|lazy_game| lazy_game.get_evaluated()) }, GameTree::End(_) => None, } } /// Returns the `GameTree` that would be produced as a result of taking the given Move. /// If the move...
/// If the move is invalid (not in valid_moves or self is `End`) then None is returned pub fn get_game_after_move(&mut self, move_: Move) -> Option<&mut GameTree> { match self {
random_line_split
game_tree.rs
at that point in time. /// Uses lazy evaluation to avoid storing the entire data structure /// in memory. See the LazyGameTree struct for more info. /// /// Note that there is no case when a player is stuck; we simply /// skip their turn if they have no moves and move /// to the next Turn state. #[derive(Debug)] pub ...
#[test] fn test_new() { // valid_moves generated correctly // - have expected moves, check if same as generated // starting gamestate is same as one passed to new let game = start_game(); let mut valid_moves = game.get_state().get_valid_moves(); let mut expec...
{ let mut expected_valid_moves = vec![]; let state = game.get_state(); let occupied_tiles = state.get_occupied_tiles(); for penguin in state.current_player().penguins.iter() { let current_tile = state.get_tile(penguin.tile_id.unwrap()).unwrap(); for tile in curre...
identifier_body
fundvalue.py
'fid TEXT,' 'date TEXT,' 'asset INTEGER,' # Data_assetAllocation or Data_fluctuationScale 'share INTEGER,' 'holder_company REAL,' # % 'holder_individual REAL,' # % 'holder_internal REAL,' # % 'stock_ratio REAL,' # % ...
'data'] for r in jsgraph['series']))):
conditional_block
fundvalue.py
(d): keys, values = zip(*d.items()) return ' AND '.join(k + '=?' for k in keys), values def update_partial(cursor, table, keys, values): inskeys, qms, vals = make_insert(keys) cursor.execute("INSERT OR IGNORE INTO %s (%s) VALUES (%s)" % ( table, inskeys, qms), vals) setkeys, vals1 = make_up...
make_where
identifier_name
fundvalue.py
: if errors == 'literal_eval': result[name] = ast.literal_eval(value) elif errors == 'ignore': result[name] = None else: raise return result def parse_worktime(s): if not s: return None yearspl = s.split('年') if...
'manager INTEGER,' 'updated TEXT,' 'PRIMARY KEY (fid, manager)' ')') cur.execute('CREATE TABLE IF NOT EXISTS fund_simrank (' 'fid TEXT,' 'date TEXT,' 'rank INTEGER,' 'total INTEGER,' 'PRIMARY KEY (fid, date)'...
'perf_time REAL,' # 择时能力 'pic TEXT' ')') cur.execute('CREATE TABLE IF NOT EXISTS fund_managers (' 'fid TEXT,'
random_line_split
fundvalue.py
if errors == 'literal_eval': result[name] = ast.literal_eval(value) elif errors == 'ignore': result[name] = None else: raise return result def parse_worktime(s): if not s: return None yearspl = s.split('年') if l...
'totalval INTEGER,' # * 10000, 货币基金为7日年化 'rate INTEGER,' # * 10000 (100%) 'rate_em INTEGER,' # * 10000 (100%) 'minval INTEGER,' # * 100 'return_1m REAL,' 'return_3m REAL,' 'return_6m REAL,' 'return_1y REAL,' # % ...
f __init__(self, db='funds.db'): self.db = sqlite3.connect(db) self.init_db() self.session = requests.Session() self.session.headers.update(HEADERS) self.executor = concurrent.futures.ThreadPoolExecutor(6) def init_db(self): cur = self.db.cursor() cur.execute...
identifier_body
ej4.py
=='max': img += learning_rate * grads elif max_or_min=='min': img -= learning_rate * grads else: print('invalid selection of learning') return return loss, img def initialize_image(): # We start from a gray image with some random noise img = tf.random.unif...
(img): # Normalize array: center on 0., ensure variance is 0.15 img -= img.mean() img /= img.std() + 1e-5 img *= 0.15 # Center crop img = img[25:-25, 25:-25, :] # Clip to [0, 1] img += 0.5 img = np.clip(img, 0, 1) # Convert to RGB array img *= 255 img = ...
deprocess_image
identifier_name
ej4.py
random inputs to [-0.125, +0.125] return (img - 0.5) * 0.25 def visualize_filter(index, it=30, lr=10, layer='filter', max_or_min='max', type_img='noise', filename=None): # We run gradient ascent for 20 steps iterations = it learning_rate = lr if type_img=='noise': img = initializ...
arning_rate * grads els
conditional_block
ej4.py
@tf.function def gradient_ascent_step(img, index, learning_rate, layer, max_or_min): with tf.GradientTape() as tape: tape.watch(img) loss = compute_loss(img, index, layer) # Compute gradients. grads = tape.gradient(loss, img) # Normalize gradients. grads = tf.math.l2_no...
activation = feature_extractor(input_image) if layer=='filter': filter_activation = activation[:, 2:-2, 2:-2, index] elif layer=='class': filter_activation = activation[:, index] print(filter_activation) else: print('invalid class') return print(tf.reduce...
identifier_body
ej4.py
0, 1) # Convert to RGB array img *= 255 img = np.clip(img, 0, 255).astype("uint8") return img img_width = 400 img_height = 400 layer_name = "conv5_block3_out" model = keras.applications.ResNet50V2(weights="imagenet", include_top=True) layer = model.get_layer(name=layer_name) feature_...
return loss, img def deprocess_image(img): # Normalize array: center on 0., ensure variance is 0.15
random_line_split
admission.go
10,000 routes, need to wait up to 30 seconds for caches to sync timeToWaitForCacheSync = 20 * time.Second hstsAnnotation = "haproxy.router.openshift.io/hsts_header" ) func Register(plugins *admission.Plugins) { plugins.Register(pluginName, func(_ io.Reader) (admission.Interface, error) { return NewReq...
func NewRequiredRouteAnnotations() *requiredRouteAnnotations { return &requiredRouteAnnotations{ Handler: admission.NewHandler(admission.Create, admission.Update), } } func (o *requiredRouteAnnotations) SetOpenShiftRouteInformers(informers routeinformers.SharedInformerFactory) { o.cachesToSync = append(o.caches...
{ if o.ingressLister == nil { return fmt.Errorf(pluginName + " plugin needs an ingress lister") } if o.routeLister == nil { return fmt.Errorf(pluginName + " plugin needs a route lister") } if o.nsLister == nil { return fmt.Errorf(pluginName + " plugin needs a namespace lister") } if len(o.cachesToSync) < 3...
identifier_body
admission.go
RouteAnnotations{}) var _ = openshiftapiserveradmission.WantsOpenShiftRouteInformers(&requiredRouteAnnotations{}) var maxAgeRegExp = regexp.MustCompile(`max-age=(\d+)`) // Validate ensures that routes specify required annotations, and returns nil if valid. // The admission handler ensures this is only called for Crea...
{ return fmt.Errorf(HSTSIncludeSubDomainsMustNotError) }
conditional_block
admission.go
10,000 routes, need to wait up to 30 seconds for caches to sync timeToWaitForCacheSync = 20 * time.Second hstsAnnotation = "haproxy.router.openshift.io/hsts_header" ) func Register(plugins *admission.Plugins) { plugins.Register(pluginName, func(_ io.Reader) (admission.Interface, error) { return NewReq...
(ctx context.Context) bool { syncCtx, cancelFn := context.WithTimeout(ctx, timeToWaitForCacheSync) defer cancelFn() if !o.cacheSyncLock.hasSynced() { if !cache.WaitForCacheSync(syncCtx.Done(), o.cachesToSync...) { return false } o.cacheSyncLock.setSynced() } return true } func (o *requiredRouteAnnotation...
waitForSyncedStore
identifier_name
admission.go
with 10,000 routes, need to wait up to 30 seconds for caches to sync timeToWaitForCacheSync = 20 * time.Second hstsAnnotation = "haproxy.router.openshift.io/hsts_header" ) func Register(plugins *admission.Plugins) { plugins.Register(pluginName, func(_ io.Reader) (admission.Interface, error) { return N...
return nil } type hstsConfig struct { maxAge int32 preload bool includeSubDomains bool } const ( HSTSMaxAgeMissingOrWrongError = "HSTS max-age must be set correctly in HSTS annotation" HSTSMaxAgeGreaterError = "HSTS max-age is greater than maximum age %ds" HSTSMaxAgeLessThan...
} // None of the requirements matched this route's domain/namespace, it is automatically allowed
random_line_split
netlink_linux.go
func (f *ipvsFlags) Serialize() []byte { return (*(*[unsafe.Sizeof(*f)]byte)(unsafe.Pointer(f)))[:] } func (f *ipvsFlags) Len() int { return int(unsafe.Sizeof(*f)) } func setup() { ipvsOnce.Do(func() { var err error if out, err := exec.Command("modprobe", "-va", "ip_vs").CombinedOutput(); err != nil { log...
{ return int(unsafe.Sizeof(*hdr)) }
identifier_body
netlink_linux.go
tAttrChild(cmdAttr, ipvsDestAttrWeight, nl.Uint32Attr(uint32(d.Weight))) nl.NewRtAttrChild(cmdAttr, ipvsDestAttrUpperThreshold, nl.Uint32Attr(d.UpperThreshold)) nl.NewRtAttrChild(cmdAttr, ipvsDestAttrLowerThreshold, nl.Uint32Attr(d.LowerThreshold)) return cmdAttr } func (i *Handle) doCmdwithResponse(s *Service, d ...
} return 0, fmt.Errorf("no family id in the netlink response") } func rawIPData(ip net.IP) []byte { family := nl.GetIPFamily(ip) if family == nl.FAMILY_V4 { return ip.To4() } return ip } func newIPVSRequest(cmd uint8) *nl.NetlinkRequest { return newGenlRequest(ipvsFamily, cmd) } func newGenlRequest(family...
{ switch int(attr.Attr.Type) { case genlCtrlAttrFamilyID: return int(native.Uint16(attr.Value[0:2])), nil } }
conditional_block
netlink_linux.go
uint8) ([][]byte, error) { req := newIPVSRequest(cmd) req.Seq = atomic.AddUint32(&i.seq, 1) if s == nil { req.Flags |= syscall.NLM_F_DUMP // Flag to dump all messages req.AddData(nl.NewRtAttr(ipvsCmdAttrService, nil)) // Add a dummy attribute } else { req.AddData(fillService(s)) } if d...
doCmdWithoutAttr
identifier_name
netlink_linux.go
tAttrChild(cmdAttr, ipvsDestAttrWeight, nl.Uint32Attr(uint32(d.Weight))) nl.NewRtAttrChild(cmdAttr, ipvsDestAttrUpperThreshold, nl.Uint32Attr(d.UpperThreshold)) nl.NewRtAttrChild(cmdAttr, ipvsDestAttrLowerThreshold, nl.Uint32Attr(d.LowerThreshold)) return cmdAttr } func (i *Handle) doCmdwithResponse(s *Service, d ...
func newGenlRequest(familyID int, cmd uint8) *nl.NetlinkRequest { req := nl.NewNetlinkRequest(familyID, syscall.NLM_F_ACK) req.AddData(&genlMsgHdr{cmd: cmd, version: 1}) return req } func execute(s *nl.NetlinkSocket, req *nl.NetlinkRequest, resType uint16) ([][]byte, error) { if err := s.Send(req); err != nil { ...
random_line_split
sgr.go
RCube213 SGRCube214 SGRCube215 SGRCube216 SGRCube217 SGRCube218 SGRCube219 SGRCube220 SGRCube221 SGRCube222 SGRCube223 SGRCube224 SGRCube225 SGRCube226 SGRCube227 SGRCube228 SGRCube229 SGRCube230 SGRCube231 // 8-bit color space: 24 shades of gray; see colors.go. SGRGray1 SGRGray2 SGRGray3 SGRGra...
Diff
identifier_name
sgr.go
6 SGRCube17 SGRCube18 SGRCube19 SGRCube20 SGRCube21
SGRCube23 SGRCube24 SGRCube25 SGRCube26 SGRCube27 SGRCube28 SGRCube29 SGRCube30 SGRCube31 SGRCube32 SGRCube33 SGRCube34 SGRCube35 SGRCube36 SGRCube37 SGRCube38 SGRCube39 SGRCube40 SGRCube41 SGRCube42 SGRCube43 SGRCube44 SGRCube45 SGRCube46 SGRCube47 SGRCube48 SGRCube49 SGRCube50 SGRCube51 ...
SGRCube22
random_line_split
sgr.go
RCube71 SGRCube72 SGRCube73 SGRCube74 SGRCube75 SGRCube76 SGRCube77 SGRCube78 SGRCube79 SGRCube80 SGRCube81 SGRCube82 SGRCube83 SGRCube84 SGRCube85 SGRCube86 SGRCube87 SGRCube88 SGRCube89 SGRCube90 SGRCube91 SGRCube92 SGRCube93 SGRCube94 SGRCube95 SGRCube96 SGRCube97 SGRCube98 SGRCube99 SGR...
{ return c }
conditional_block
sgr.go
GRCube61 SGRCube62 SGRCube63 SGRCube64 SGRCube65 SGRCube66 SGRCube67 SGRCube68 SGRCube69 SGRCube70 SGRCube71 SGRCube72 SGRCube73 SGRCube74 SGRCube75 SGRCube76 SGRCube77 SGRCube78 SGRCube79 SGRCube80 SGRCube81 SGRCube82 SGRCube83 SGRCube84 SGRCube85 SGRCube86 SGRCube87 SGRCube88 SGRCube89 SG...
{ if c&sgrColor24 == 0 { c = Palette8Colors[c&0xff] } return uint8(c), uint8(c >> 8), uint8(c >> 16) }
identifier_body
async_queue.js
log from './log'; import { Deferred } from './promise'; import { Code, FirestoreError } from './error'; /** * Wellknown "timer" IDs used when scheduling delayed operations on the * AsyncQueue. These IDs can then be used from tests to check for the presence * of operations or to run them early. * * The string valu...
/** * Adds a new operation to the queue. Returns a promise that will be resolved * when the promise returned by the new operation is (with its value). */ AsyncQueue.prototype.enqueue = function (op) { var _this = this; this.verifyNotFailed(); var newTail = this.tail.then(...
{ // The last promise in the queue. this.tail = Promise.resolve(); // Operations scheduled to be queued in the future. Operations are // automatically removed after they are run or canceled. this.delayedOperations = []; // Flag set while there's an outstanding AsyncQueue ...
identifier_body
async_queue.js
log from './log'; import { Deferred } from './promise'; import { Code, FirestoreError } from './error'; /** * Wellknown "timer" IDs used when scheduling delayed operations on the * AsyncQueue. These IDs can then be used from tests to check for the presence * of operations or to run them early. * * The string valu...
}; /** * Verifies there's an operation currently in-progress on the AsyncQueue. * Unfortunately we can't verify that the running code is in the promise chain * of that operation, so this isn't a foolproof check, but it should be enough * to catch some bugs. */ AsyncQueue.prototype....
{ fail('AsyncQueue is already failed: ' + (this.failure.stack || this.failure.message)); }
conditional_block
async_queue.js
as log from './log'; import { Deferred } from './promise'; import { Code, FirestoreError } from './error'; /** * Wellknown "timer" IDs used when scheduling delayed operations on the * AsyncQueue. These IDs can then be used from tests to check for the presence * of operations or to run them early. * * The string v...
// Operations scheduled to be queued in the future. Operations are // automatically removed after they are run or canceled. this.delayedOperations = []; // Flag set while there's an outstanding AsyncQueue operation, used for // assertion sanity-checks. this.operationInPro...
function AsyncQueue() { // The last promise in the queue. this.tail = Promise.resolve();
random_line_split
async_queue.js
log from './log'; import { Deferred } from './promise'; import { Code, FirestoreError } from './error'; /** * Wellknown "timer" IDs used when scheduling delayed operations on the * AsyncQueue. These IDs can then be used from tests to check for the presence * of operations or to run them early. * * The string valu...
() { // The last promise in the queue. this.tail = Promise.resolve(); // Operations scheduled to be queued in the future. Operations are // automatically removed after they are run or canceled. this.delayedOperations = []; // Flag set while there's an outstanding AsyncQue...
AsyncQueue
identifier_name
daemon.go
, err } // NB we could use the messages too if we decide to change the // signature of the API to include it. revs := make([]string, len(commits)) for i, commit := range commits { revs[i] = commit.Revision } return revs, nil } func (d *Daemon) GitRepoConfig(ctx context.Context, regenerate bool) (v6.GitConfig,...
latestValidRevision
identifier_name
daemon.go
var res []v6.ControllerStatus for _, workload := range clusterWorkloads { readOnly := v6.ReadOnlyOK repoIsReadonly := d.Repo.Readonly() var policies policy.Set if resource, ok := resources[workload.ID.String()]; ok { policies = resource.Policies() } switch { case policies == nil: readOnly = mis...
{ return nil, err }
conditional_block
daemon.go
Ask the daemon how far it's got applying things; in particular, is it // past the given commit? Return the list of commits between where // we have applied (the sync tag) and the ref given, inclusive. E.g., if you send HEAD, // you'll get all the commits yet to be applied. If you send a hash // and it's applied at or ...
{ types := map[string]struct{}{} for p := range u.Add { switch { case p == policy.Automated: types[event.EventAutomate] = struct{}{} case p == policy.Locked: types[event.EventLock] = struct{}{} default: types[event.EventUpdatePolicy] = struct{}{} } } for p := range u.Remove { switch { case p...
identifier_body
daemon.go
nil, errors.Wrap(err, "getting images for workloads") } var res []v6.ImageStatus for _, workload := range workloads { workloadContainers, err := getWorkloadContainers(workload, imageRepos, resources[workload.ID.String()], opts.OverrideContainerFields) if err != nil { return nil, err } res = append(res, ...
if err != nil { return result, err } head, err := d.Repo.BranchHead(ctx) if err != nil { return result, err } if d.GitVerifySignaturesMode != sync.VerifySignaturesModeNone { var latestValidRev string if latestValidRev, _, err = latestValidRevision(ctx, d.Repo, d.SyncState, d.GitVerifySignaturesM...
err := d.Repo.Refresh(ctx)
random_line_split
WSU-PDF_process_incoming_to_Fedora_152.py
return item_ID_list # change permissions en bulk def permissionsChange(item_ID_list): for item_ID in item_ID_list: os.system(Template("chmod -R 755 /processing/$item_ID").substitute(item_ID=item_ID)) #try to get MODS file # remove PDF artifacts (PNGs), renames images to match item_ID def fileRename(item_ID): ...
pre_item_ID_list = os.listdir('/processing') if len(pre_item_ID_list) == 0: print "Nothing to do!" else: print "Processing these items: ",pre_item_ID_list #prepare normalized list item_ID_list = [] for item_ID in pre_item_ID_list: #apostrophes item_ID_handle = re.sub("'","\\'", item_ID) n_item_ID = ...
identifier_body
WSU-PDF_process_incoming_to_Fedora_152.py
image in images: # get image type image_type = image.split(".") image_type = image_type[len(image_type)-1] # contruct image name new_image_name = item_ID + str(image_num).zfill(5) + "." + image_type # rename file os.system(Template("mv /processing/$item_ID/$image /processing/$item_ID/$new_image_name")...
im.thumbnail((max_width, max_height), Image.ANTIALIAS) # converts to RGB if necessary... if im.mode != "RGB": im = im.convert("RGB") im.save(Template('/processing/$item_ID/$image_basename.jpg').substitute(item_ID=item_ID, image_basename=image_basename)) print image,"resized to: ",im.size,",...
else: print Template("Portait - resizing from $orig_width to 1700").substitute(orig_width=width)
random_line_split
WSU-PDF_process_incoming_to_Fedora_152.py
in images: # get image type image_type = image.split(".") image_type = image_type[len(image_type)-1] # contruct image name new_image_name = item_ID + str(image_num).zfill(5) + "." + image_type # rename file os.system(Template("mv /processing/$item_ID/$image /processing/$item_ID/$new_image_name").subst...
(item_ID): # get number of files images = os.listdir("/processing/"+item_ID+"/images") leaf_count = len(images) - 1 #accounts for /thumbs directory in there # get dimensions of cover and create cover image cover_path = Template('/processing/$item_ID/images/$item_ID').substitute(item_ID=item_ID) + "00001.jpg" i...
createMetadata
identifier_name
WSU-PDF_process_incoming_to_Fedora_152.py
/$new_image_name").substitute(item_ID=item_ID, image=image, new_image_name=new_image_name)) #bumps counters if count == 3: count = 0 image_num = image_num + 1 else: count = count + 1 def imageResize (item_ID): images = os.listdir("/processing/"+item_ID) for image in images: # accepted_image_ty...
html_concat = html_concat + unicode(block)
conditional_block
render.py
super(ZoomGroup, self).__init__(parent) self.zoom = zoom def set_state(self): pyglet.gl.glPushMatrix() pyglet.gl.glScalef(self.zoom, self.zoom, 1) def unset_state(self): pyglet.gl.glPopMatrix() def __eq__(self, other): return ( self....
tile = renderable.tile break else: continue # always add floor, because we wanna draw walls above floor vertices.extend((x1, y1, x2, y1, x2, y2, x1, y2)) tex_coords.extend(floor_te...
for entity in self._level.position_system.get_entities_at(x, y): renderable = entity.get(LayoutRenderable) if renderable:
random_line_split
render.py
super(ZoomGroup, self).__init__(parent) self.zoom = zoom def set_state(self): pyglet.gl.glPushMatrix() pyglet.gl.glScalef(self.zoom, self.zoom, 1) def unset_state(self): pyglet.gl.glPopMatrix() def __eq__(self, other): return ( self....
def remove_entity(self, entity): sprite = self._sprites.pop(entity) sprite.delete() entity.unlisten('image_change', self._on_image_change) entity.unlisten('move', self._on_move) def _on_image_change(self, entity): self._sprites[entity].image = entity.get(Rende...
image = entity.get(Renderable).image pos = entity.get(Position) group = pyglet.graphics.OrderedGroup(pos.order, self._level_group) sprite = pyglet.sprite.Sprite(image, pos.x * 8, pos.y * 8, batch=self._batch, group=group) self._sprites[entity] = sprite entity.listen('image_c...
identifier_body
render.py
super(ZoomGroup, self).__init__(parent) self.zoom = zoom def set_state(self): pyglet.gl.glPushMatrix() pyglet.gl.glScalef(self.zoom, self.zoom, 1) def unset_state(self): pyglet.gl.glPopMatrix() def __eq__(self, other): return ( self....
else: continue # always add floor, because we wanna draw walls above floor vertices.extend((x1, y1, x2, y1, x2, y2, x1, y2)) tex_coords.extend(floor_tex.tex_coords) if tile == LayoutGenerator.TILE_WALL: ...
renderable = entity.get(LayoutRenderable) if renderable: tile = renderable.tile break
conditional_block