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
mod.rs
{ pub(crate) path: PathBuf, #[visit(skip)] pub(crate) mapping: NodeMapping, #[visit(skip)] scene: Scene, } impl TypeUuidProvider for Model { fn type_uuid() -> Uuid { MODEL_RESOURCE_UUID } } /// Type alias for model resources. pub type ModelResource = Resource<Model>; /// Extensio...
Model
identifier_name
hypersonic.go
Bomb(myX, myY-1, bomb, turnLimit, numTurns+1, reach, bombs, floor) {return true} // in danger, no where to go return false } func willIDieHere(x int, y int, bombs []Bomb, floor [WIDTH][HEIGHT]int) bool { for _, bomb := range bombs { if canIEscapeThisBomb(x, y, bomb, bomb.time, 0, bomb.reach, bombs,...
{ if x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT {return false} return true }
identifier_body
hypersonic.go
] >= BOX {score++} } if floor[x][y] > BOX {score++} // there's an item in the box return Cell{score: score, distance: moves} } func scoreTheFloor(myX int, myY int, bombsOnTheFloor []Bomb, myReach int, floor [WIDTH][HEIGHT]int) [WIDTH][HEIGHT]Cell{ scoreFloor := [WIDTH][HEIGHT]Cell{} for i := 0; i <...
{buffer.WriteString("E")}
conditional_block
hypersonic.go
TOO_FAR}} // does not account for time left on the bomb, could optimize here rather than walling it off score := 0 for i := 0; i < myReach; i++ { if x+i < WIDTH && floor[x+i][y] >= BOX {score++} if x-i > 0 && floor[x-i][y] >= BOX {score++} if y+i < HEIGHT && floor[x][y+i] >= BOX {score+...
buffer.WriteString(distanceStr) buffer.WriteString("]") } buffer.WriteString("\n") }
random_line_split
hypersonic.go
myX = x myY = y } if entityType == BOMB { // don't bother going here (get x,y and affect their score somehow) bombsOnTheFloor = append(bombsOnTheFloor, Bomb{x: x, y: y, time: param1, reach: param2}) } } // ...
(myX int, myY int, bombsOnTheFloor []Bomb, myReach int, floor [WIDTH][HEIGHT]int) [WIDTH][HEIGHT]Cell{ scoreFloor := [WIDTH][HEIGHT]Cell{} for i := 0; i < WIDTH; i++ { for j := 0; j < HEIGHT; j++ { scoreFloor[i][j] = scoreACell(i, j, myX, myY, bombsOnTheFloor, myReach, floor) } }...
scoreTheFloor
identifier_name
util.py
_interface_mixin, self) return tuple(base.__getitem__(i) for i in range(len(self))) def items(self): keys = self.keys() values = self.values() return tuple((keys[i], values[i]) for i in range(len(self))) def __str__(self): return self.__class__.__name__ + "(" + ", ".joi...
def fitarg_rename(fitarg, ren): """Rename variable names in ``fitarg`` with rename function. :: #simple renaming fitarg_rename({'x':1, 'limit_x':1, 'fix_x':1, 'error_x':1}, lambda pname: 'y' if pname=='x' else pname) #{'y':1, 'limit_y':1, 'fix_y
:ref:`function-sig-label` """ return better_arg_spec(f, verbose)
random_line_split
util.py
_repr_html_(self): return "\n".join([x._repr_html_() for x in self.values()]) def __str__(self): return "\n".join([str(x) for x in self.values()]) def _repr_pretty_(self, p, cycle): if cycle: p.text("MErrors(...)") else: p.text(str(self)) class FMin(d...
extract_error
identifier_name
util.py
_parameters has_accurate_covar " "has_posdef_covar has_made_posdef_covar hesse_failed has_covariance is_above_max_edm " "has_reached_call_limit")): """Function minimum status object.""" __slots__ = () def _repr_html_(self): return repr_html.fmin(self) def __str__(self): return...
"""Exclude variable in exclude list from b.""" return dict((k, v) for k, v in b.items() if param_name(k) not in exclude)
identifier_body
util.py
.""" def __init__(self, seq, merrors): list.__init__(self, seq) self.merrors = merrors def _repr_html_(self): return repr_html.params(self) def __str__(self): return repr_text.params(self) def _repr_pretty_(self, p, cycle): if cycle: p.text("[...]"...
if k.startswith(p): vn = k[len(p):] pf = p
conditional_block
properties.ts
scaleType, scalePadding, scalePaddingInner, domain: specifiedScale.domain, domainMin: specifiedScale.domainMin, domainMax: specifiedScale.domainMax, markDef, config, hasNestedO...
{ const {bandPaddingOuter, bandWithNestedOffsetPaddingOuter} = scaleConfig; if (hasNestedOffsetScale) { return bandWithNestedOffsetPaddingOuter; } // Padding is only set for X and Y by default. // Basically it doesn't make sense to add padding for color and size. if (scaleType === ScaleTyp...
conditional_block
properties.ts
(model: Model, property: Exclude<keyof (Scale | ScaleComponentProps), 'range'>) { if (isUnitModel(model)) { parseUnitScaleProperty(model, property); } else { parseNonUnitScaleProperty(model, property); } } function parseUnitScaleProperty(model: UnitModel, property: Exclude<keyof (Scale | ScaleComponentPr...
parseScaleProperty
identifier_name
properties.ts
localScaleCmpt = localScaleComponents[channel]; const mergedScaleCmpt = model.getScaleComponent(channel); const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]) as ScaleFieldDef<string, Type> | ScaleDatumDef; const specifiedValue = specifiedScale[property]; const scaleType = mergedScaleCmpt.get...
switch (property) { case 'range': // For step, prefer larger step if (v1.step && v2.step) { return v1.step - v2.step; } return 0; // TODO: precedence rule for other properties } ...
valueWithExplicit, childValueWithExplicit, property, 'scale', tieBreakByComparing<VgScale, any>((v1, v2) => {
random_line_split
properties.ts
// If there is a specified value, check if it is compatible with scale type and channel if (!supportedByScaleType) { log.warn(log.message.scalePropertyNotWorkWithScaleType(scaleType, property, channel)); } else if (channelIncompatability) { // channel log.warn(channelIncompatability...
{ if (paddingValue !== undefined) { // If user has already manually specified "padding", no need to add default paddingInner. return undefined; } if (isXorY(channel)) { // Padding is only set for X and Y by default. // Basically it doesn't make sense to add padding for color and size. // pad...
identifier_body
io.rs
} } fn next(&mut self) -> Result<Option<H>, Error> { let size = std::mem::size_of::<H>(); if self.queue.is_empty() { let mut buf = vec![0; size * Self::BATCH_SIZE]; let from = self.file.seek(io::SeekFrom::Start(self.index))?; match self.file.read_exact(&mu...
Err(err) => return Err(err.into()), } self.index += buf.len() as u64; let items = buf.len() / size; let mut cursor = io::Cursor::new(buf); let mut item = vec![0; size]; for _ in 0..items { cursor.read_exact(&mut i...
{ self.file.seek(io::SeekFrom::Start(from))?; let n = self.file.read_to_end(&mut buf)?; buf.truncate(n); }
conditional_block
io.rs
} } fn next(&mut self) -> Result<Option<H>, Error> { let size = std::mem::size_of::<H>(); if self.queue.is_empty() { let mut buf = vec![0; size * Self::BATCH_SIZE]; let from = self.file.seek(io::SeekFrom::Start(self.index))?; match self.file.read_ex...
} } Ok(self.queue.pop_front()) } } /// An iterator over block headers in a file. #[derive(Debug)] pub struct Iter<H> { height: Height, file: FileReader<H>, } impl<H: Decodable> Iter<H> { fn new(file: fs::File) -> Self { Self { file: FileReader::new(file)...
for _ in 0..items { cursor.read_exact(&mut item)?; let item = H::consensus_decode(&mut item.as_slice())?; self.queue.push_back(item);
random_line_split
io.rs
} } fn next(&mut self) -> Result<Option<H>, Error> { let size = std::mem::size_of::<H>(); if self.queue.is_empty() { let mut buf = vec![0; size * Self::BATCH_SIZE]; let from = self.file.seek(io::SeekFrom::Start(self.index))?; match self.file.read_ex...
(&mut self) -> Option<Self::Item> { let height = self.height; assert!(height > 0); match self.file.next() { // If we hit this branch, it's because we're trying to read passed the end // of the file, which means there are no further headers remaining. Err(Err...
next
identifier_name
tweet_utils.py
length of generated query strings, depending on account type it might be 400 or 1000 :additional_query_parameters :return :list[string] of generated query strings ''' queries = [] query = keywords[0] for keyword in keywords[1:]: tmp_query = '{} OR "{}"'.format(query, keywor...
else: print('No results....') dfs[n] = dfs[n].append(pd.DataFrame()) breakOut = True
random_line_split
tweet_utils.py
removeNoisyTerms(df,noisyTerms = ['veteran','truce']): ''' Removes a set of noisy terms from DataFrame with all declined keywords Returns @df ''' removeNoisy = input('Remove noisy terms? ({:s}) (Y/n)'.format(','.join(noisyTerms))) if removeNoisy == 'n': removeNoisy = False ...
ue): ''' Function to take a DataFrame of keywords and combine with OR operators to make a series of queries under 1024 characters. Optionally write the queries to a series of files ''' n = 0 lastN = 0 nFile = 0 tempQ = '' qs = [] print('Splitting queries') ...
eToFile = Tr
identifier_name
tweet_utils.py
declensionsDf[0] = parseOperators(declensionsDf) while n < declensionsDf.shape[0]: tempQ = ' OR '.join(declensionsDf[0].values[lastN:n]) if len(tempQ) > 1024: qs.append(' OR '.join(declensionsDf[0].values[lastN:n-1])) if writeToFile: p...
t match a string ''' matches = [] tokens = t.lower().split() for q in qs: for kw in q.split(' OR '): if kw in tokens: #print('MATCHED',kw) matches.append(kw) return matches def queryToList(q): ''' Conv
identifier_body
tweet_utils.py
NoisyTerms(df,noisyTerms = ['veteran','truce']): ''' Removes a set of noisy terms from DataFrame with all declined keywords Returns @df ''' removeNoisy = input('Remove noisy terms? ({:s}) (Y/n)'.format(','.join(noisyTerms))) if removeNoisy == 'n': removeNoisy = False print(...
eclined keywords...') fileName = '' fileName = input('Enter file path for keywords(default: {:s}_declensions.csv)'.format(prefix)) if fileName == '': fileName = '{:s}_declensions.csv'.format(prefix) print('Reading declined keywords file...') declensionsDf = pd.read_csv(fileName,...
if prefix == '': prefix = 'az' print(prefix+' chosen') print('Getting list of d
conditional_block
dataset_data_particle.py
be unique # for all data particles. Best practice is to access this variable using the accessor method: # data_particle_type() _data_particle_type = None def __init__(self, raw_data, port_timestamp=None, internal_timestamp=None, preferred_timestamp=N...
self.raw_data = raw_data self._values = None def __eq__(self, arg): """ Quick equality check for testing purposes. If they have the same raw data, timestamp, they are the same enough for this particle """ allowed_diff = .000001 if self._data_particle...
""" Build a particle seeded with appropriate information @param raw_data The raw data used in the particle """ if new_sequence is not None and not isinstance(new_sequence, bool): raise TypeError("new_sequence is not a bool") self.contents = { DataParticleKey.PKT...
identifier_body
dataset_data_particle.py
be unique # for all data particles. Best practice is to access this variable using the accessor method: # data_particle_type() _data_particle_type = None def __init__(self, raw_data, port_timestamp=None, internal_timestamp=None, preferred_timestamp=N...
Build the base/header information for an output structure. Follow on methods can then modify it by adding or editing values. @return A fresh copy of a core structure to be exported """ result = dict(self.contents) # clean out optional fields that were missing if ...
"""
random_line_split
dataset_data_particle.py
if unix_time is not None: timestamp = ntplib.system_to_ntp_time(unix_time) # Do we want this to happen here or in down stream processes? if not self._check_timestamp(timestamp): raise InstrumentParameterException("invalid timestamp") self.contents[DataParticleKey.PORT_...
raise SampleException("raw data not a complete port agent packet. missing %s" % param)
conditional_block
dataset_data_particle.py
be unique # for all data particles. Best practice is to access this variable using the accessor method: # data_particle_type() _data_particle_type = None def __init__(self, raw_data, port_timestamp=None, internal_timestamp=None, preferred_timestamp=N...
(self, timestamp=None, unix_time=None): """ Set the internal timestamp @param timestamp: NTP timestamp to set @param unit_time: Unix time as returned from time.time() @raise InstrumentParameterException if timestamp or unix_time not supplied """ if timestamp is No...
set_internal_timestamp
identifier_name
perception.py
Perception(RobotPart): def __init__(self, robot_name, tf_listener): super(Perception, self).__init__(robot_name=robot_name, tf_listener=tf_listener) self._camera_lazy_sub = None self._camera_cv = Condition() self._camera_last_image = None self._annotate_srv = self.create_se...
else: return self._get_faces(image).recognitions @staticmethod def get_best_face_recognition(recognitions, desired_label, probability_threshold=4.0): """ Returns the Recognition with the highest probability of having the desired_label. Assumes that the probability d...
return self._get_faces(image).recognitions, image.header.stamp
conditional_block
perception.py
=tf_listener) self._camera_lazy_sub = None self._camera_cv = Condition() self._camera_last_image = None self._annotate_srv = self.create_service_client('/' + robot_name + '/face_recognition/annotate', Annotate) self._recognize_srv = self.create_service_client('/' + robot_name + ...
""" clearing all faces from the OpenFace node. :return: no return """ rospy.loginfo('clearing all learned faces') self._clear_srv()
identifier_body
perception.py
Perception(RobotPart): def __init__(self, robot_name, tf_listener): super(Perception, self).__init__(robot_name=robot_name, tf_listener=tf_listener) self._camera_lazy_sub = None self._camera_cv = Condition() self._camera_last_image = None self._annotate_srv = self.create_se...
def clear_face(self):
return best_recognition if best_recognition.categorical_distribution.probabilities[0].probability > probability_threshold else None else: return None # TODO: Maybe so something smart with selecting a recognition where the desired_label is not the most probable for a recognition?
random_line_split
perception.py
Perception(RobotPart): def __init__(self, robot_name, tf_listener): super(Perception, self).__init__(robot_name=robot_name, tf_listener=tf_listener) self._camera_lazy_sub = None self._camera_cv = Condition() self._camera_last_image = None self._annotate_srv = self.create_se...
(self, image): self._camera_cv.acquire() self._camera_last_image = image self._camera_cv.notify() self._camera_cv.release() def get_image(self, timeout=5): # lazy subscribe to the kinect if not self._camera_lazy_sub: # for test with tripod kinect ...
_image_cb
identifier_name
routeOperator.go
ile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { tep := new(netv1alpha1.TunnelEndpoint) var err error if err = rc.Get(ctx, req.NamespacedName, tep); err != nil && !k8sApiErrors.IsNotFound(err) { klog.Errorf("unable to fetch resource {%s} :%v", req.String(), err) return result, err } // In case...
{ resourceToBeProccesedPredicate := predicate.Funcs{ DeleteFunc: func(e event.DeleteEvent) bool { // Finalizers are used to check if a resource is being deleted, and perform there the needed actions // we don't want to reconcile on the delete of a resource. return false }, } return ctrl.NewControllerMan...
identifier_body
routeOperator.go
" netv1alpha1 "github.com/liqotech/liqo/apis/net/v1alpha1" liqoconst "github.com/liqotech/liqo/pkg/consts" "github.com/liqotech/liqo/pkg/liqonet/overlay" liqorouting "github.com/liqotech/liqo/pkg/liqonet/routing" liqonetutils "github.com/liqotech/liqo/pkg/liqonet/utils" ) var ( result = ctrl.Result{} ) // Rout...
} } }() return nil } // cleanUp removes all the routes, rules and devices (if any) from the // node inserted by the operator. It is called at exit time. func (rc *RouteController) cleanUp() { if rc.firewallChan != nil { // send signal to clean firewall rules and close the go routine. rc.firewallChan <- t...
{ select { case <-ticker.C: // every five seconds we enforce the firewall rules. for i := range fwRules { if err := addRule(iptHandler, &fwRules[i]); err != nil { klog.Errorf("unable to insert firewall rule {%s}: %v", fwRules[i].String(), err) } else { klog.V(5).Infof("firewall rule {%s}...
conditional_block
routeOperator.go
" netv1alpha1 "github.com/liqotech/liqo/apis/net/v1alpha1" liqoconst "github.com/liqotech/liqo/pkg/consts" "github.com/liqotech/liqo/pkg/liqonet/overlay" liqorouting "github.com/liqotech/liqo/pkg/liqonet/routing" liqonetutils "github.com/liqotech/liqo/pkg/liqonet/utils" ) var ( result = ctrl.Result{} ) // Rout...
(podIP string, vxlanDevice *overlay.VxlanDevice, router liqorouting.Routing, er record.EventRecorder, cl client.Client) *RouteController { r := &RouteController{ Client: cl, Routing: router, vxlanDev: vxlanDevice, EventRecorder: er, podIP: podIP, } return r } // cluster-role // ...
NewRouteController
identifier_name
routeOperator.go
concile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { tep := new(netv1alpha1.TunnelEndpoint) var err error if err = rc.Get(ctx, req.NamespacedName, tep); err != nil && !k8sApiErrors.IsNotFound(err) { klog.Errorf("unable to fetch resource {%s} :%v", req.String(), err) return result, err } // In ...
random_line_split
th_logistic_regression.py
\frac{1}{|\mathcal{D}|} \mathcal{L} (\theta=\{W,b\}, \mathcal{D}) = \frac{1}{|\mathcal{D}|} \sum_{i=0}^{|\mathcal{D}|} \log(P(Y=y^{(i)}|x^{(i)}, W,b)) \\ \ell (\theta=\{W,b\}, \mathcal{D}) :type y: theano.tensor.TensorType :param y: corresponds ...
best_validation_loss = this_validation_loss # test it on the test set test_losses = [test_model(i) for i in xrange(n_test_batches
patience = max(patience, iter * patience_increase)
conditional_block
th_logistic_regression.py
= LogisticRegression(input=x, n_in=32 * 32, n_out=2) # the cost we minimize during training is the negative log likelihood of the model in symbolic format cost = classifier.negative_log_likelihood(y) # compiling a Theano function that computes the mistakes that are made by the model on a minibatch ...
# Y_test = np.array(Y_test)
random_line_split
th_logistic_regression.py
self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b) # symbolic description of how to compute prediction as class whose probability is maximal self.y_pred = T.argmax(self.p_y_given_x, axis=1) # end-snippet-1 # parameters of the model self.params = [se...
""" Initialize the parameters of the logistic regression :type input: theano.tensor.TensorType :param input: symbolic variable that describes the input of the architecture (one minibatch) :type n_in: int :param n_in: number of input units, the dimension of the space in which the data...
identifier_body
th_logistic_regression.py
(self, input, n_in, n_out): """ Initialize the parameters of the logistic regression :type input: theano.tensor.TensorType :param input: symbolic variable that describes the input of the architecture (one minibatch) :type n_in: int :param n_in: number of input units, the dim...
__init__
identifier_name
schema.go
} parsed2, err := url.Parse(*r.ref) if err != nil { return nil, fmt.Errorf("parse $ref: %w", err) } return loader.Load(ctx, referer.Src.ResolveReference(parsed2)) } // Schema is the core representation of the JSONSchema meta schema. type Schema struct { // this could be a ref Ref *string `json:"$ref,omitemp...
{ return "" }
conditional_block
schema.go
"" { r.ref = &ref.Ref return nil } r.schema = new(Schema) return json.Unmarshal(b, r.schema) } // Resolve either returns the schema if set or else resolves the reference using the referer schema and loader. func (r *RefOrSchema) Resolve(ctx context.Context, referer *Schema, loader Loader) (*Schema, error) { i...
random_line_split
schema.go
} *t = append(*t, typ) } return nil } return fmt.Errorf("unable to unmarshal %T into TypeField", val) } // convenience method to draw out the first token; if this errs, later calls will err anyway so discards // the err func peekToken(data []byte) json.Token { tok, _ := json.NewDecoder(bytes.NewReader(data))...
(k string) (s string) { _, _ = t.Unmarshal(k, &s) return } // Read unmarshals the json at the provided key into the provided interface (which should be a pointer amenable to // json.Read. If the key is not present, the pointer will be untouched, and false and nil will be returned. If the // deserialization fails, an...
GetString
identifier_name
schema.go
} *t = append(*t, typ) } return nil } return fmt.Errorf("unable to unmarshal %T into TypeField", val) } // convenience method to draw out the first token; if this errs, later calls will err anyway so discards // the err func peekToken(data []byte) json.Token { tok, _ := json.NewDecoder(bytes.NewReader(data))...
// Schema is the core representation of the JSONSchema meta schema. type Schema struct { // this could be a ref Ref *string `json:"$ref,omitempty"` // meta ID *url.URL `json:"-"` // set either from "$id", "id", or calculated based on parent (see IDCalc); never nil IDCalc bool `json:"-"` // whether this ...
{ if r.ref == nil { return r.schema, nil } parsed2, err := url.Parse(*r.ref) if err != nil { return nil, fmt.Errorf("parse $ref: %w", err) } return loader.Load(ctx, referer.Src.ResolveReference(parsed2)) }
identifier_body
policy.go
// Deadlines are immutable when the challenge window is open, and during // the previous challenge window. immutableWindow := 2 * WPoStChallengeWindow // We want to reserve at least one deadline's worth of time to compact a // deadline. minCompactionWindow := WPoStChallengeWindow // Make sure we have enough t...
{ // Check that the challenge windows divide the proving period evenly. if WPoStProvingPeriod%WPoStChallengeWindow != 0 { panic(fmt.Sprintf("incompatible proving period %d and challenge window %d", WPoStProvingPeriod, WPoStChallengeWindow)) } // Check that WPoStPeriodDeadlines is consistent with the proving perio...
identifier_body
policy.go
ity so there's always some time to dispute bad proofs. if WPoStDisputeWindow <= ChainFinality
// A deadline becomes immutable one challenge window before it's challenge window opens. // The challenge lookback must fall within this immutability period. if WPoStChallengeLookback > WPoStChallengeWindow { panic("the challenge lookback cannot exceed one challenge window") } // Deadlines are immutable when ...
{ panic(fmt.Sprintf("the proof dispute period %d must exceed finality %d", WPoStDisputeWindow, ChainFinality)) }
conditional_block
policy.go
than finality so there's always some time to dispute bad proofs. if WPoStDisputeWindow <= ChainFinality { panic(fmt.Sprintf("the proof dispute period %d must exceed finality %d", WPoStDisputeWindow, ChainFinality)) } // A deadline becomes immutable one challenge window before it's challenge window opens. // The...
const ProveReplicaUpdatesMaxSize = PreCommitSectorBatchMaxSize // Maximum delay between challenge and pre-commitment. // This prevents a miner sealing sectors far in advance of committing them to the chain, thus committing to a // particular chain. var MaxPreCommitRandomnessLookback = builtin.EpochsInDay + ChainFinali...
random_line_split
policy.go
{}, } // Checks whether a PoSt proof type is supported for new miners. func CanWindowPoStProof(s abi.RegisteredPoStProof) bool { _, ok := WindowPoStProofTypes[s] return ok } // List of proof types which may be used when pre-committing a new sector. // This is mutable to allow configuration of testing and developme...
QAPowerForSector
identifier_name
yuva_info.rs
1, and V is in channel 1 of plane 1. Channel ordering /// within a pixmap/texture given the channels it contains: /// A: 0:A /// Luminance/Gray: 0:Gray /// Luminance/Gray + Alpha: 0:Gray, 1:A /// RG 0:R, 1:G /// RGB 0:R, 1:G, 2:B /// RGBA ...
(&self, plane_index: usize) -> (i32, i32) { plane_subsampling_factors(self.plane_config(), self.subsampling(), plane_index) } /// Dimensions of the full resolution image (after planes have been oriented to how the image /// is displayed as indicated by fOrigin). pub fn dimensions(&self) -> ISiz...
plane_subsampling_factors
identifier_name
yuva_info.rs
1, and V is in channel 1 of plane 1. Channel ordering /// within a pixmap/texture given the channels it contains: /// A: 0:A /// Luminance/Gray: 0:Gray /// Luminance/Gray + Alpha: 0:Gray, 1:A /// RG 0:R, 1:G /// RGB 0:R, 1:G, 2:B /// RGBA ...
/// Number of Y, U, V, A channels in the ith plane for a given [PlaneConfig] (or [None] if i is /// invalid). pub fn num_channels_in_plane(config: PlaneConfig, i: usize) -> Option<usize> { (i < num_planes(config)).if_true_then_some(|| { unsafe { sb::C_SkYUVAInfo_NumChannelsInPlane(config, i.try_into().unw...
{ unsafe { sb::C_SkYUVAInfo_NumPlanes(config) } .try_into() .unwrap() }
identifier_body
yuva_info.rs
1, and V is in channel 1 of plane 1. Channel ordering /// within a pixmap/texture given the channels it contains: /// A: 0:A /// Luminance/Gray: 0:Gray /// Luminance/Gray + Alpha: 0:Gray, 1:A /// RG 0:R, 1:G /// RGB 0:R, 1:G, 2:B /// RGBA ...
pub fn has_alpha(&self) -> bool { has_alpha(self.plane_config()) } /// Returns the dimensions for each plane. Dimensions are as stored in memory, before /// transformation to image display
random_line_split
labstats-subscriber.py
Will delete daemon's pidfile if --daemon was specified def clean_quit(): if options.daemon: daemon.delpid() exit(1) # If collector is killed manually, clean up and quit def sigterm_handler(signal, frame): error_output("Subscriber killed via SIGTERM") output_checkins() clean_quit() # If SI...
verbose_print("Reaped "+str(deleted)+" items from check-ins") output_checkins(last_check, new_dict) return (last_check, new_dict) ############################################################################### # Output the json into a log file in /var/log/labstats def output_log(to_write): if not os.p...
new_dict[hostname] = timestamp
conditional_block
labstats-subscriber.py
delete daemon's pidfile if --daemon was specified def clean_quit(): if options.daemon: daemon.delpid() exit(1) # If collector is killed manually, clean up and quit def sigterm_handler(signal, frame): error_output("Subscriber killed via SIGTERM") output_checkins() clean_quit() # If SIGHUP ...
signal.signal(signal.SIGTERM, sigterm_handler) signal.signal(signal.SIGHUP, sighup_handler) ''' Reaper functions: check timestamps, read in/out checked-in machines. By default, the reaper will write out its state every recv() and will check that all checked-in machines are no older than 20 minutes (by default) every...
error_output("Collector received a SIGHUP") context.destroy() time.sleep(5) main(options.retries, 2000, options.tlimit)
identifier_body
labstats-subscriber.py
Will delete daemon's pidfile if --daemon was specified def clean_quit(): if options.daemon: daemon.delpid() exit(1) # If collector is killed manually, clean up and quit def sigterm_handler(signal, frame): error_output("Subscriber killed via SIGTERM") output_checkins() clean_quit() # If SI...
def outdated(curtime, timestamp): # pass in type datetime, datetime verbose_print("Checking timestamp "+timestamp.strftime(timeformat)+" against current time") timeobj = datetime.fromtimestamp(mktime(timestamp.timetuple())) diff = curtime - timeobj # type timedelta return diff >= timedelta(minutes = op...
# Returns True if timestamp is outdated
random_line_split
labstats-subscriber.py
delete daemon's pidfile if --daemon was specified def clean_quit(): if options.daemon: daemon.delpid() exit(1) # If collector is killed manually, clean up and quit def sigterm_handler(signal, frame): error_output("Subscriber killed via SIGTERM") output_checkins() clean_quit() # If SIGHUP ...
(ntries, ntime, tlimit): last_check, check_ins = read_checkins() # Set up ZMQ sockets and connections context = zmq.Context() subscriber = context.socket(zmq.SUB) subscriber.setsockopt(zmq.SUBSCRIBE,'') pushsocket = context.socket(zmq.PUSH) try: subscriber.connect('tcp://%s:5556...
main
identifier_name
gocomics.py
fe'), cls('CattitudeDoggonit', 'cattitude-doggonit'), cls('CestLaVie', 'cestlavie'), cls('CheerUpEmoKid', 'cheer-up-emo-kid'), cls('ChipBok', 'chipbok'), cls('ChrisBritt', 'chrisbritt'), cls('ChuckDrawsThings', 'chuck-draws-things'), cl...
cls('KidBeowulf', 'kid-beowulf'), cls('KitchenCapers', 'kitchen-capers'), cls('Kliban', 'kliban'), cls('KlibansCats', 'klibans-cats'), cls('LaCucaracha', 'lacucaracha'), cls('LaCucarachaEnEspanol', 'la-cucaracha-en-espanol', 'es'), cls(...
cls('JunkDrawer', 'junk-drawer'), cls('JustoYFranco', 'justo-y-franco', 'es'), cls('KevinKallaugher', 'kal'), cls('KevinNecessaryEditorialCartoons', 'kevin-necessary-editorial-cartoons'),
random_line_split
gocomics.py
def namer(self, image_url, page_url): prefix, year, month, day = page_url.rsplit('/', 3) return "%s_%s%s%s.gif" % (self.shortname, year, month, day) def getIndexStripUrl(self, index): return '{}/{}'.format(self.url, index) def shouldSkipUrl(self, url, data): """Skip pages...
self.lang = lang
conditional_block
gocomics.py
return '{}/{}'.format(self.url, index) def shouldSkipUrl(self, url, data): """Skip pages without images.""" return data.xpath('//img[contains(@src, "content-error-missing")]') @classmethod def getmodules(cls): # noqa: CFQ001 return ( # old comics removed from t...
url = 'https://www.gocomics.com/' imageSearch = '//picture[d:class("item-comic-image")]/img' prevSearch = '//a[d:class("js-previous-comic")]' latestSearch = '//div[d:class("gc-deck--cta-0")]//a' starter = indirectStarter help = 'Index format: yyyy/mm/dd' def __init__(self, name, path, lang=None...
identifier_body
gocomics.py
(self, url, data): """Skip pages without images.""" return data.xpath('//img[contains(@src, "content-error-missing")]') @classmethod def getmodules(cls): # noqa: CFQ001 return ( # old comics removed from the listing cls('HeavenlyNostrils', 'heavenly-nostrils'), ...
shouldSkipUrl
identifier_name
PushForm.js
type: PropTypes.number.isRequired, deviceType: PropTypes.number.isRequired, countryList: PropTypes.array.isRequired, }; static defaultProp = { countryList: [] } componentWillMount() { const { actions, countryList } = this.props; if (!countryList || countryList.length < 1) { actions.getStaticDataByCode...
} else { console.log('需要精确到分钟____________', moment(data.get(pushTimeDatePickerFN)).format('YYYYMMDD') + moment(data.get(pushTimeTimePickerFN)).format('HHmm')); data.set('pushTime', moment(data.get(pushTimeDatePickerFN)).format('YYYYMMDD') + moment(data.get(pushTimeTimePickerFN)).format('HHmmss')); con...
.get(targetValueFN)) { MsgUtil.showwarning('指定wenwenId信息不正确'); return; } if (data.get(targetFN) === 'ALL') { data.set(targetValueFN, 'ALL'); } //设置推送时间 if (data.get(isSetPushTimeFN) === 'true') { if (!data.get(pushTimeDatePickerFN) || !data.get(pushTimeTimePickerFN)) { MsgUtil.showwa...
conditional_block
PushForm.js
type: PropTypes.number.isRequired, deviceType: PropTypes.number.isRequired, countryList: PropTypes.array.isRequired, }; static defaultProp = { countryList: [] } componentWillMount() { const {
, countryList } = this.props; if (!countryList || countryList.length < 1) { actions.getStaticDataByCodeType(Constant.USER_COUNTRY_ATTR_CODE); } } onPushBigTypeChange = (evt) => { const { getFieldValue, setFieldsValue } = this.props.form; setFieldsValue(pushTypeFN, pushType[getFieldValue(pushBigTypeFN)][...
actions
identifier_name
PushForm.js
(!data.get(pushTimeDatePickerFN) || !data.get(pushTimeTimePickerFN)) { MsgUtil.showwarning('推送日期不允许为空'); return; } else { console.log('需要精确到分钟____________', moment(data.get(pushTimeDatePickerFN)).format('YYYYMMDD') + moment(data.get(pushTimeTimePickerFN)).format('HHmm')); data.set('pushTime', m...
} else { contentPanelBoxLabel = '消息'; } return (
random_line_split
app.js
'bootstrap', 'legend', 'panoramio', 'geolocation', 'core', 'wirecloud', 'angular-gettext', 'translations'], function(angular, ol, toolbar, layermanager) { var modules_to_load = [ 'hs.toolbar', 'hs.layermanager', 'hs.map', 'hs.ows', 'hs.query', ...
//Create feature if necessary. Set the attribute values for the feature var feature = null; if (location_feature_ids[data[id_attr_name]]) { feature = location_feature_ids[data[id_attr_name]]; feature.setGeometry(attributes.geometry); ...
{ //Get settings from configuration var id_attr_name = MashupPlatform.prefs.get('id_attr_name'); var coordinates_attr_name = MashupPlatform.prefs.get('coordinates_attr_name'); var measurements_attr_names = MashupPlatform.prefs.get('measurements_attr_names').split(','); ...
identifier_body
app.js
'hs.legend', 'hs.geolocation', 'hs.core', 'hs.wirecloud', 'gettext', 'hs.sidebar' ]; if (typeof MashupPlatform !== 'undefined') { modules_to_load = eval(MashupPlatform.prefs.get('modules_to_load')); } var module = angular.module('hs', modules_to_load); ...
return module;
random_line_split
app.js
'bootstrap', 'legend', 'panoramio', 'geolocation', 'core', 'wirecloud', 'angular-gettext', 'translations'], function(angular, ol, toolbar, layermanager) { var modules_to_load = [ 'hs.toolbar', 'hs.layermanager', 'hs.map', 'hs.ows', 'hs.query', ...
(numOfSteps, step, opacity) { // based on http://stackoverflow.com/a/7419630 // This function generates vibrant, "evenly spaced" colours (i.e. no clustering). This is ideal for creating easily distiguishable vibrant markers in Google Maps and other apps. // Adam Cole, 2011-Sept-14 ...
rainbow
identifier_name
app.js
'bootstrap', 'legend', 'panoramio', 'geolocation', 'core', 'wirecloud', 'angular-gettext', 'translations'], function(angular, ol, toolbar, layermanager) { var modules_to_load = [ 'hs.toolbar', 'hs.layermanager', 'hs.map', 'hs.ows', 'hs.query', ...
} module.value('config', { default_layers: [ new ol.layer.Tile({ source: new ol.source.OSM(), show_in_manager: true, title: "Base layer", base: true }), location_l...
{ location_feature_ids[data.unit].tags[data.id] = data; var max_temp = -273.15; var timestamp = ""; for (var tag in location_feature_ids[data.unit].tags) { var t = parseFloat(location_feature_ids[data.unit].tags[tag].temperature); ...
conditional_block
main.py
7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6], [ 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14], [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]], 5: [[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11], [10, 15, 4...
key_bits = hexToBinary(key) if len(key_bits) != 64: print("Incorrect key provided.") sys.exit() key_up = [] for i in range (56): key_up.append(key_bits[PC1[i]-1]) key_up = ''.join(key_up) print("The initial key is {}".format(key_bits)) print("They permuted key is {}".format(key_up)) subkeys...
identifier_body
main.py
11, 14, 1, 7, 6, 0, 8, 13]], 6: [[ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1], [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6], [ 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2], [ 6, 11, 13, 8, 1, 4...
row = int(splitList[i][0] + splitList[i][-1],2) col = int(splitList[i][1] + splitList[i][2] + splitList[i][3] + splitList[i][4],2) newVal = SBOXES[int(i)][row][col] bits = str(format(newVal,"b")).zfill(4) reducedR.append(bits)
conditional_block
main.py
4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1] # Substituting back to get a 32 bit value # Done by splitting the 48 bit ...
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]], 2: [[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8], [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1], [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10,...
random_line_split
main.py
[ 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]]} # Permutes the sbox value for the final 32 bit value that is then added on top of the L_n-1 value P = [16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, ...
test
identifier_name
data.go
Payload.FPort != nil && *ctx.MACPayload.FPort > 0 { return publishDataUp(ctx.NodeSession, ctx.RXPacket, *ctx.MACPayload) } return nil } func handleChannelReconfiguration(ctx *DataUpContext) error { // handle channel configuration // note that this must come before ADR! if err := channels.HandleChannelReconfigu...
{ var cids []lorawan.CID blocks := make(map[lorawan.CID]maccommand.Block) // group mac-commands by CID for _, cmd := range commands { block, ok := blocks[cmd.CID] if !ok { block = maccommand.Block{ CID: cmd.CID, FRMPayload: frmPayload, } cids = append(cids, cmd.CID) } block.MACComma...
identifier_body
data.go
} func decryptFRMPayloadMACCommands(ctx *DataUpContext) error { // only decrypt when FPort is equal to 0 if ctx.MACPayload.FPort != nil && *ctx.MACPayload.FPort == 0 { if err := ctx.RXPacket.PHYPayload.DecryptFRMPayload(ctx.NodeSession.NwkSKey); err != nil { return errors.Wrap(err, "decrypt FRMPayload error") ...
Time: rxInfo.Time.Format(time.RFC3339Nano), Rssi: int32(rxInfo.RSSI), LoRaSNR: rxInfo.LoRaSNR, }) } _, err := common.Controller.HandleRXInfo(context.Background(), &rxInfoReq) if err != nil { return fmt.Errorf("publish rxinfo to network-controller error: %s", err) } log.WithFields(log.Fields{ ...
copy(mac, rxInfo.MAC[:]) rxInfoReq.RxInfo = append(rxInfoReq.RxInfo, &nc.RXInfo{ Mac: mac,
random_line_split
data.go
} func decryptFRMPayloadMACCommands(ctx *DataUpContext) error { // only decrypt when FPort is equal to 0 if ctx.MACPayload.FPort != nil && *ctx.MACPayload.FPort == 0 { if err := ctx.RXPacket.PHYPayload.DecryptFRMPayload(ctx.NodeSession.NwkSKey); err != nil { return errors.Wrap(err, "decrypt FRMPayload error") ...
log.WithFields(log.Fields{ "dev_eui": ns.DevEUI, }).Info("rx info sent to network-controller") return nil } func publishDataUp(ns session.NodeSession, rxPacket models.RXPacket, macPL lorawan.MACPayload) error { publishDataUpReq := as.HandleDataUpRequest{ AppEUI: ns.AppEUI[:], DevEUI: ns.DevEUI[:], FCnt: ...
{ return fmt.Errorf("publish rxinfo to network-controller error: %s", err) }
conditional_block
data.go
} func decryptFRMPayloadMACCommands(ctx *DataUpContext) error { // only decrypt when FPort is equal to 0 if ctx.MACPayload.FPort != nil && *ctx.MACPayload.FPort == 0 { if err := ctx.RXPacket.PHYPayload.DecryptFRMPayload(ctx.NodeSession.NwkSKey); err != nil { return errors.Wrap(err, "decrypt FRMPayload error") ...
(ctx *DataUpContext) error { // TODO: only log in case of error? if !ctx.MACPayload.FHDR.FCtrl.ACK { return nil } _, err := common.Application.HandleDataDownACK(context.Background(), &as.HandleDataDownACKRequest{ AppEUI: ctx.NodeSession.AppEUI[:], DevEUI: ctx.NodeSession.DevEUI[:], FCnt: ctx.NodeSession....
handleUplinkACK
identifier_name
kaart-teken-laag.component.ts
"../kaart-elementen"; import { VeldInfo } from "../kaart-elementen"; import { KaartInternalMsg, kaartLogOnlyWrapper, tekenWrapper, VerwijderTekenFeatureMsg, } from "../kaart-internal-messages"; import * as prt from "../kaart-protocol"; import { KaartComponent } from "../kaart.component"; import { asStyleSelect...
this.source.removeFeature(feature); } }); // Hou de subject bij. this.bindToLifeCycle( this.kaartModel$.pipe( distinctUntilChanged( (k1, k2) => k1.geometryChangedSubj === k2.geometryChangedSubj ), // map((kwi) => kwi.geometryChangedSubj) ) )....
{ this.dispatch(prt.VerwijderOverlaysCmd([tooltip])); }
conditional_block
kaart-teken-laag.component.ts
"../kaart-elementen"; import { VeldInfo } from "../kaart-elementen"; import { KaartInternalMsg, kaartLogOnlyWrapper, tekenWrapper, VerwijderTekenFeatureMsg, } from "../kaart-internal-messages"; import * as prt from "../kaart-protocol"; import { KaartComponent } from "../kaart.component"; import { asStyleSelect...
(tekenSettings: ke.TekenSettings): void { if (this.tekenen) { this.stopMetTekenen(); } this.source = option.fold( () => new ol.source.Vector(), (geom: ol.geom.Geometry) => { const source = new ol.source.Vector(); source.addFeature(new ol.Feature(geom)); return sour...
startMetTekenen
identifier_name
kaart-teken-laag.component.ts
import { VeldInfo } from "../kaart-elementen"; import { KaartInternalMsg, kaartLogOnlyWrapper, tekenWrapper, VerwijderTekenFeatureMsg, } from "../kaart-internal-messages"; import * as prt from "../kaart-protocol"; import { KaartComponent } from "../kaart.component"; import { asStyleSelector, toStylish } from "....
import { forEach } from "../../util/option"; import { KaartChildDirective } from "../kaart-child.directive"; import * as ke from "../kaart-elementen";
random_line_split
kaart-teken-laag.component.ts
"../kaart-elementen"; import { VeldInfo } from "../kaart-elementen"; import { KaartInternalMsg, kaartLogOnlyWrapper, tekenWrapper, VerwijderTekenFeatureMsg, } from "../kaart-internal-messages"; import * as prt from "../kaart-protocol"; import { KaartComponent } from "../kaart.component"; import { asStyleSelect...
private createLayer( source: ol.source.Vector, tekenSettings: ke.TekenSettings ): ke.VectorLaag { return { type: ke.VectorType, titel: TekenLaagNaam, source: source, clusterDistance: option.none, styleSelector: pipe( tekenSettings.laagStyle, option.alt(() ...
{ if (this.tekenen) { this.dispatch(prt.VerwijderInteractieCmd(this.drawInteraction)); this.dispatch(prt.VerwijderInteractieCmd(this.modifyInteraction)); this.dispatch(prt.VerwijderInteractieCmd(this.snapInteraction)); this.dispatch(prt.VerwijderOverlaysCmd(this.overlays)); this.dispat...
identifier_body
commands.py
reg = re.compile('(.*)') if not pattern == None: try: cmd = re.search(reg, pattern) try: cmd = cmd.group(1).replace("$", "").replace("\\", "").replace("^", "") except: pass try: ...
args["func"] = lambda e: e.via_bot_id is None stack = inspect.stack() previous_stack_frame = stack[1] file_test = Path(previous_stack_frame.filename) file_test = file_test.stem.replace(".py", "") pattern = args.get("pattern", None) allow_sudo = args.get("allow_sudo", None...
identifier_body
commands.py
(**args): args["func"] = lambda e: e.via_bot_id is None stack = inspect.stack() previous_stack_frame = stack[1] file_test = Path(previous_stack_frame.filename) file_test = file_test.stem.replace(".py", "") pattern = args.get("pattern", None) allow_sudo = args.get(...
zzaacckkyy
identifier_name
commands.py
bool(args["incoming"]): args["outgoing"] = False try: if pattern is not None and not pattern.startswith('(?i)'): args['pattern'] = '(?i)' + pattern except: pass reg = re.compile('(.*)') if not pattern == None: try: ...
else: import ub.events import sys import importlib from pathlib import Path path = Path(f"ub/modules/{shortname}.py") name = "ub.modules.{}".format(shortname) spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_sp...
name = "ub.modules.{}".format(shortname) spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) print("Successfully (re)imported "+shortname)
random_line_split
commands.py
path = Path(f"ub/modules/{shortname}.py") name = "ub.modules.{}".format(shortname) spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) print("Successfully (re)imported "+shortname) else: ...
/= power raised_to_pow += 1
conditional_block
kuberuntime_sandbox.go
(ctx context.Context, pod *v1.Pod, attempt uint32) (string, string, error) { podSandboxConfig, err := m.generatePodSandboxConfig(pod, attempt) if err != nil { message := fmt.Sprintf("Failed to generate sandbox config for pod %q: %v", format.Pod(pod), err) klog.ErrorS(err, "Failed to generate sandbox config for po...
createPodSandbox
identifier_name
kuberuntime_sandbox.go
pod %q: %v", format.Pod(pod), err) klog.ErrorS(err, "Failed to create log directory for pod", "pod", klog.KObj(pod)) return "", message, err } runtimeHandler := "" if m.runtimeClassManager != nil { runtimeHandler, err = m.runtimeClassManager.LookupRuntimeHandler(pod.Spec.RuntimeClassName) if err != nil { ...
for idx := range containerPortMappings { port := containerPortMappings[idx] hostPort := int32(port.HostPort) containerPort := int32(port.ContainerPort) protocol := toRuntimeProtocol(port.Protocol) portMappings = append(portMappings, &runtimeapi.PortMapping{ HostIp: port.HostIP, HostPort...
portMappings := []*runtimeapi.PortMapping{} for _, c := range pod.Spec.Containers { containerPortMappings := kubecontainer.MakePortMappings(&c)
random_line_split
kuberuntime_sandbox.go
pod %q: %v", format.Pod(pod), err) klog.ErrorS(err, "Failed to create log directory for pod", "pod", klog.KObj(pod)) return "", message, err } runtimeHandler := "" if m.runtimeClassManager != nil { runtimeHandler, err = m.runtimeClassManager.LookupRuntimeHandler(pod.Spec.RuntimeClassName) if err != nil { ...
if sc.SupplementalGroups != nil { for _, sg := range sc.SupplementalGroups { lc.SecurityContext.SupplementalGroups = append(lc.SecurityContext.SupplementalGroups, int64(sg)) } } if sc.SELinuxOptions != nil && runtime.GOOS != "windows" { lc.SecurityContext.SelinuxOptions = &runtimeapi.SELinuxOption{ ...
{ sc := pod.Spec.SecurityContext if sc.RunAsUser != nil && runtime.GOOS != "windows" { lc.SecurityContext.RunAsUser = &runtimeapi.Int64Value{Value: int64(*sc.RunAsUser)} } if sc.RunAsGroup != nil && runtime.GOOS != "windows" { lc.SecurityContext.RunAsGroup = &runtimeapi.Int64Value{Value: int64(*sc.RunAsGr...
conditional_block
kuberuntime_sandbox.go
pod %q: %v", format.Pod(pod), err) klog.ErrorS(err, "Failed to create log directory for pod", "pod", klog.KObj(pod)) return "", message, err } runtimeHandler := "" if m.runtimeClassManager != nil { runtimeHandler, err = m.runtimeClassManager.LookupRuntimeHandler(pod.Spec.RuntimeClassName) if err != nil { ...
return nil, fmt.Errorf("pod must not contain both HostProcess and non-HostProcess containers") } if !kubecontainer.IsHostNetworkPod(pod) { return nil, fmt.Errorf("hostNetwork is required if Pod contains HostProcess containers") } wc.SecurityContext.HostProcess = true } sc := pod.Spec.SecurityContext ...
{ wc := &runtimeapi.WindowsPodSandboxConfig{ SecurityContext: &runtimeapi.WindowsSandboxSecurityContext{}, } if utilfeature.DefaultFeatureGate.Enabled(features.WindowsHostNetwork) { wc.SecurityContext.NamespaceOptions = &runtimeapi.WindowsNamespaceOption{} if kubecontainer.IsHostNetworkPod(pod) { wc.Securi...
identifier_body
JsonLogparser.py
)): if (str(dic[i]["last_update"]) >= from_t): if (i!=0): from_index = i else: from_index = i break i = i + 1 i = 0 if (dic[len(dic)-1]["last_update"]==to_t): to_t = len(dic)-1 else: while (i < len(dic)): ...
array = np.array(array) array = array.T if (all): for i in range(len(array)): pp.plot(array[i], label="Thruster " + str(i)) else: for i in indexes: try: pp.plot(array[i],label="Thruster " + str(i)) except: print ("\nUnab...
starttime = starttime + 1
random_line_split
JsonLogparser.py
pp.show() def print1dim( dic, key, label, starttime, endtime): # helper function for non nested keys i.e. 1 dimensional array haha print("\n"+label) while (starttime < endtime): print (dic[starttime]["last_update"]," : ",dic[starttime][key]) starttime = starttime + 1 def print2dim(d...
print1dim(data,'cameras','Camera',fromtime,totime)
conditional_block
JsonLogparser.py
)): if (str(dic[i]["last_update"]) >= from_t): if (i!=0): from_index = i else: from_index = i break i = i + 1 i = 0 if (dic[len(dic)-1]["last_update"]==to_t): to_t = len(dic)-1 else: while (i < len(dic)): ...
(dic, key, key2, label, starttime, endtime): # helper function for nested keys i.e. 2 dimensional only # add similar helper function for more nested keys if need be print("\n" + label) while (starttime < endtime): print (dic[starttime]["last_update"]," : ",dic[starttime][key][key2]) sta...
print2dim
identifier_name
JsonLogparser.py
)): if (str(dic[i]["last_update"]) >= from_t): if (i!=0): from_index = i else: from_index = i break i = i + 1 i = 0 if (dic[len(dic)-1]["last_update"]==to_t): to_t = len(dic)-1 else: while (i < len(dic)): ...
def print2dim(dic, key, key2, label, starttime, endtime): # helper function for nested keys i.e. 2 dimensional only # add similar helper function for more nested keys if need be print("\n" + label) while (starttime < endtime): print (dic[starttime]["last_update"]," : ",dic[starttime][key][ke...
print("\n"+label) while (starttime < endtime): print (dic[starttime]["last_update"]," : ",dic[starttime][key]) starttime = starttime + 1
identifier_body
mikes-modal.min.js
: (b.corners * b.width >> 1) + "px" }) } var g = 0, i; for (; g < b.lines; g++)i = h(d(), { position: "absolute", top: 1 + ~(b.width / 2) + "px", transform: b.hwaccel ? "translate3d(0,0,0)" : "", opacity...
{ this.opts = e(this.opts, this), this.bindLoaded = e(this.bindLoaded, this), this.bindOpened = e(this.bindOpened, this), this.modalBox = a, this.bindOpened(), this.bindLoaded() }
identifier_body
mikes-modal.min.js
#000"), {top: "2px"})), e(a, e(i, c(b.color, "0 0 1px rgba(0,0,0,.1)"))); return a }, opacity: function (a, b, c) { b < a.childNodes.length && (a.childNodes[b].style.opacity = c) } }), function () { function a(a, b) { return d("<" + a + ' xmlns="urn:schem...
}, a.prototype.opts = function () { return { lines: 9, length: 30,
random_line_split
mikes-modal.min.js
++) { var d = arguments[b]; for (var e in d)a[e] === c && (a[e] = d[e]) } return a } function j(a) { var b = {x: a.offsetLeft, y: a.offsetTop}; while (a = a.offsetParent)b.x += a.offsetLeft, b.y += a.offsetTop; return b } var k = ["webkit...
(a) { this.addClose = e(this.addClose, this), this.marginLeft = e(this.marginLeft, this), this.marginTop = e(this.marginTop, this), this.imageMaxHeight = e(this.imageMaxHeight, this), this.imageMaxWidth = e(this.imageMaxWidth, this), this.triggerClose = e(this.triggerClose, this), this.imagePosition = e(thi...
b
identifier_name
metadb_test.go
ch <- errors.New(r.(string)) default: ch <- nil } } }() fn() }() return <-ch } // RunWithDB runs a closure passing it a database handle which is disposed of // afterward. func RunWithDB(fn func(*sql.DB)) { db, err := sql.Open("sqlite3", TestDBPath) if err != nil { panic(err) } fn(db...
// TestExists ensures that Instance.Exists is accurate. func TestExists(t *testing.T) { RunWithInstance(func(instance *Instance) { InsertFixtures(instance, []EntryFixture{ {Name: "foo", Value: "bar", ValueType: 3}, }) if instance.Exists("bar") { t.Error("Instance.Exists: got 'true' expected 'false'") ...
{ if _, err := NewInstance(nil); err == nil { t.Error("NewInstance: expected error with nil database handle") } RunWithDB(func(db *sql.DB) { if _, err := NewInstance(db); err != nil { t.Fatal("NewInstance: got error:\n", err) } }) }
identifier_body
metadb_test.go
ch <- errors.New(r.(string)) default: ch <- nil } } }() fn() }() return <-ch } // RunWithDB runs a closure passing it a database handle which is disposed of // afterward. func RunWithDB(fn func(*sql.DB)) { db, err := sql.Open("sqlite3", TestDBPath) if err != nil { panic(err) } fn(db...
if err := os.Remove(TestDBPath); err != nil { panic(err) } } // RunWithInstance runs a closure passing it an Instance. func RunWithInstance(fn func(*Instance)) { RunWithDB(func(db *sql.DB) { if instance, err := NewInstance(db); err != nil { panic(err) } else { fn(instance) } }) } // EntryFixture c...
{ panic(err) }
conditional_block
metadb_test.go
: ch <- errors.New(r.(string)) default: ch <- nil } } }() fn() }() return <-ch } // RunWithDB runs a closure passing it a database handle which is disposed of // afterward. func RunWithDB(fn func(*sql.DB)) { db, err := sql.Open("sqlite3", TestDBPath) if err != nil { panic(err) } fn(...
func RunWithInstance(fn func(*Instance)) { RunWithDB(func(db *sql.DB) { if instance, err := NewInstance(db); err != nil { panic(err) } else { fn(instance) } }) } // EntryFixture contains the basic data required for a metadata entry. type EntryFixture struct { Name string Value interface{} Val...
// RunWithInstance runs a closure passing it an Instance.
random_line_split
metadb_test.go
ch <- errors.New(r.(string)) default: ch <- nil } } }() fn() }() return <-ch } // RunWithDB runs a closure passing it a database handle which is disposed of // afterward. func RunWithDB(fn func(*sql.DB)) { db, err := sql.Open("sqlite3", TestDBPath) if err != nil { panic(err) } fn(db...
(t *testing.T) { RunWithInstance(func(instance *Instance) { InsertFixtures(instance, []EntryFixture{ {Name: "bool", Value: true, ValueType: 0}, {Name: "invalidBool", Value: "maybe", ValueType: 0}, {Name: "int", Value: 239, ValueType: 1}, {Name: "invalidInt", Value: "not a number", ValueType: 1}, {Name...
TestFromBlobString
identifier_name
memcache_zipserve.py
if type(zip_files[num_items - 1]).__name__ != 'list': zip_files[num_items - 1] = [zip_files[num_items-1]] num_items -= 1 else: raise ValueError('File name arguments must be a list') class HandlerWrapper(MemcachedZipHandler): """Simple wrapper for an instance of MemcachedZipHandler. ...
"""Factory method to create a MemcachedZipHandler instance. Args: zip_files: A list of file names, or a list of lists of file name, first member of file mappings. See MemcachedZipHandler documentation for more information about using the list of lists format max_age: The maximum client-side c...
identifier_body
memcache_zipserve.py
urlLangName = None retry = False isValidIntl = False isStripped = False # Try to retrieve the user's lang pref from the cookie. If there is no # lang pref cookie in the request, add set-cookie to the response with the # default value of 'en'. try: langName = self.request.cookies['an...
self.StoreOrUpdateInCache(name, resp_data) elif isValidIntl: # couldn't find the intl doc. Try to fall through to English. #logging.info(' Retrying with base uri...') return False else: logging.info(' Adding %s to negative cache, serving 404', name) ...
resp_data = self.GetFromStore(name) # IF we have the file, put it in the memcache # ELSE put it in the negative cache if resp_data is not None:
random_line_split
memcache_zipserve.py
urlLangName = None retry = False isValidIntl = False isStripped = False # Try to retrieve the user's lang pref from the cookie. If there is no # lang pref cookie in the request, add set-cookie to the response with the # default value of 'en'. try: langName = self.request.cookies['an...
def RedirToIntl(self, name, intlString, langName): """Redirect an incoming request to the appropriate intl uri. For non-en langName, builds the intl/lang string from a base (en) string and redirects (302) the request to look for a version of the file in langName. For en langName, simply ...
return name
conditional_block
memcache_zipserve.py
urlLangName = None retry = False isValidIntl = False isStripped = False # Try to retrieve the user's lang pref from the cookie. If there is no # lang pref cookie in the request, add set-cookie to the response with the # default value of 'en'. try: langName = self.request.cookies['an...
(self, name, langName, isValidIntl, resetLangCookie): """Process the url and form a response, if appropriate. Attempts to retrieve the requested file (name) from cache, negative cache, or store (zip) and form the response. For intl requests that are not found (in the localized tree), ...
CreateResponse
identifier_name
chart.js
Update]').click(function () { getTopRevs(); getBotRevs(); }); $('[name=chartUpdate]').click(function () { var whichChart = $('[name=chartSelector]').val(); if (whichChart == "In Total") { drawPie('#myChart'); } else { drawBar('#myChart'); } }); }); } function getAuthorAnalyticsPage()...
//clears the .active class from the menu bar function resetMenuBar() { $('#Overview').removeClass("active"); $('#ArticleAnalytics').removeClass("active"); $('#AuthorAnalytics').removeClass("active"); } /****************** LOAD THE CHART DATA *******************/ function drawPie(where) { console.log(wher...
{ $('#main').empty(); $('#main').load('views/authorAnalytics.html', null, function () { $('#authorSearchButton').click(function () { getAuthorArticleList(); }) }); }
identifier_body
chart.js
Update]').click(function () { getTopRevs(); getBotRevs(); }); $('[name=chartUpdate]').click(function () { var whichChart = $('[name=chartSelector]').val(); if (whichChart == "In Total") { drawPie('#myChart'); } else { drawBar('#myChart'); } }); });
$('#authorSearchButton').click(function () { getAuthorArticleList(); }) }); } //clears the .active class from the menu bar function resetMenuBar() { $('#Overview').removeClass("active"); $('#ArticleAnalytics').removeClass("active"); $('#AuthorAnalytics').removeClass("active"); } /****************** LO...
} function getAuthorAnalyticsPage() { $('#main').empty(); $('#main').load('views/authorAnalytics.html', null, function () {
random_line_split
chart.js
Update]').click(function () { getTopRevs(); getBotRevs(); }); $('[name=chartUpdate]').click(function () { var whichChart = $('[name=chartSelector]').val(); if (whichChart == "In Total") { drawPie('#myChart'); } else { drawBar('#myChart'); } }); }); } function getAuthorAnalyticsPage()...
() { var destination = 'getNewestArticles'; console.log('here'); $.get(destination, null, function (data) { console.log(data); $('#newestArticles').empty(); for (var x = 0; x < data.length; x++) { var num = x + 1; num = num + '. '; var appendMe = $('<li>' + num + data[x]._id + '</li>'); $('#newes...
getNewestArticles
identifier_name