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 |
|---|---|---|---|---|
get.go | page.
http.Redirect(w, req, "/page/1", http.StatusSeeOther)
return
}
n, err := posts.GetOffset(u.LastViewed)
if err != nil {
// There's no value or we can't read from it, so we'll just sent the user to the first page.
http.Redirect(w, req, "/page/1", http.StatusSeeOther)
return
}
pn := utility.Compute... | (w http.ResponseWriter, req *http.Request) {
templates.SignIn.Execute(w, nil)
}
func SignOutGetHandler(w http.ResponseWriter, req *http.Request) {
// Destroy session
c, err := req.Cookie(session.GetKey())
if err != nil {
}
sid, err := cookie.Decode(c)
if err != nil {
http.Error(w, err.Error(), http.StatusIn... | SignInGetHandler | identifier_name |
get.go | page.
http.Redirect(w, req, "/page/1", http.StatusSeeOther)
return
}
n, err := posts.GetOffset(u.LastViewed)
if err != nil {
// There's no value or we can't read from it, so we'll just sent the user to the first page.
http.Redirect(w, req, "/page/1", http.StatusSeeOther)
return
}
pn := utility.Compute... | sessions = append(sessions, s)
}
obEmail := utility.ObfuscateEmail(u.Email) // we'll obfuscate the email address for privacy
pppOptions := viper.GetStringSlice("ppp_options")
// To display a list of radio buttons for users to select the expiry time for 2FA sessions.
durationOpts := viper.Get("two_factor_auth.... | {
data := utility.ParseUserAgent(ss[i].UserAgent)
var ip string
// Running locally, an IP is displayed like "[::1]:57305". Ergo, if we're running locally,
// just pass the IP unchanged. Otherwise, split off the port from the IP address and only
// display that to the user.
if ss[i].IP[0] == '[' {
ip = ... | conditional_block |
get.go | first page.
http.Redirect(w, req, "/page/1", http.StatusSeeOther)
return
}
n, err := posts.GetOffset(u.LastViewed)
if err != nil {
// There's no value or we can't read from it, so we'll just sent the user to the first page.
http.Redirect(w, req, "/page/1", http.StatusSeeOther)
return
}
pn := utility.C... | id := chi.URLParam(req, "num")
if len(id) == 0 {
http.Error(w, "routes: ID cannot be empty", http.StatusBadRequest)
return
}
p, err := posts.GetByID(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if p.Author != u.ID {
msg := fmt.Sprintf("routes: user %q canno... |
// BUG: Due to some weirdness in Chi, the param here is "num", but we're actually getting supplied
// a post ID. We can't change the route param name due to this.
// See: https://github.com/pressly/chi/issues/78 | random_line_split |
get.go | page.
http.Redirect(w, req, "/page/1", http.StatusSeeOther)
return
}
n, err := posts.GetOffset(u.LastViewed)
if err != nil {
// There's no value or we can't read from it, so we'll just sent the user to the first page.
http.Redirect(w, req, "/page/1", http.StatusSeeOther)
return
}
pn := utility.Compute... | var sessions []sessionData
// Load the user's timezone setting so we can provide correct post timestamps.
loc, err := time.LoadLocation(u.Timezone)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
now := time.Now()
for i := range ss {
data := utility.ParseUserAgent(ss[... | {
u := users.FromContext(req.Context())
if u == nil {
http.Error(w, "Could not read user data from request context", http.StatusInternalServerError)
return
}
ss, err := session.GetByUser(u.ID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Reduce the session data... | identifier_body |
vm.rs | x8, x, y, 0x7) => self.subn_vx_vy(x, y),
(0x8, x, y, 0xE) => self.shl_vx_vy(x, y),
(0x9, x, y, 0x0) => self.sne_vx_vy(x, y),
(0xA, _, _, _) => self.ld_i_addr(op & 0x0FFF),
(0xB, _, _, _) => {
let v0 = self.v[0] as u16; // sacrifice to the god of borrows
... | /// store the (wrapped) result in register VX.
/// Set V_FLAG to 0x1 if a borrow occurs, and to 0x0 otherwise. | random_line_split | |
vm.rs | waiting for a key pressed that a key has been pressed.
pub fn end_wait_for_key(&mut self, key_index: usize) {
if !self.is_waiting_for_key() {
warn!(concat!(
"Chip8::end_wait_for_key_press called but the VM ",
"wasn't waiting for a key press - ignoring"
... | (0x4, x, _, _) => self.sne_vx_nn(x, (op & 0x00FF) as u8),
(0x5, x, y, 0x0) => self.se_vx_vy(x, y),
(0x6, x, _, _) => self.ld_vx_nn(x, (op & 0x00FF) as u8),
(0x7, x, _, _) => self.add_vx_nn(x, (op & 0x00FF) as u8),
(0x8, x, y, 0x0) => self.ld_vx_vy(x, y),
... | {
// For easier matching, get the values (nibbles) A, B, C, D
// if the opcode is 0xABCD.
let opcode_tuple = (
((op & 0xF000) >> 12) as u8,
((op & 0x0F00) >> 8) as u8,
((op & 0x00F0) >> 4) as u8,
(op & 0x000F) as u8,
);
//println!(... | identifier_body |
vm.rs | (&mut self, b: bool) {
self.shift_op_use_vy = b;
}
/// Is the CPU waiting for a key press ?
pub fn is_waiting_for_key(&self) -> bool {
self.wait_for_key.0
}
/// Called by the emulator application to inform the virtual machine
/// waiting for a key pressed that a key has been pr... | should_shift_op_use_vy | identifier_name | |
base-command.ts | import AWS, { Organizations, STS } from 'aws-sdk';
import { AssumeRoleRequest } from 'aws-sdk/clients/sts';
import { SharedIniFileCredentialsOptions } from 'aws-sdk/lib/credentials/shared_ini_file_credentials';
import { Command } from 'commander';
import { existsSync, readFileSync } from 'fs';
import * as ini from 'ini... | try {
await storageProvider.create(region);
} catch (err) {
if (err && err.code === 'BucketAlreadyOwnedByYou') {
return storageProvider;
}
throw err;
}
return storageProvider;
}
protected async getStateBucket(comman... | const storageProvider = await this.getStateBucket(command); | random_line_split |
base-command.ts | import AWS, { Organizations, STS } from 'aws-sdk';
import { AssumeRoleRequest } from 'aws-sdk/clients/sts';
import { SharedIniFileCredentialsOptions } from 'aws-sdk/lib/credentials/shared_ini_file_credentials';
import { Command } from 'commander';
import { existsSync, readFileSync } from 'fs';
import * as ini from 'ini... |
public async generateDefaultTemplate(): Promise<DefaultTemplate> {
const organizations = new Organizations({ region: 'us-east-1' });
const awsReader = new AwsOrganizationReader(organizations);
const awsOrganization = new AwsOrganization(awsReader);
const writer = new DefaultTempla... | {
if (command !== undefined && name !== undefined) {
this.command = command.command(name);
if (description !== undefined) {
this.command.description(description);
}
this.command.allowUnknownOption(false);
this.addOptions(this.command);
... | identifier_body |
base-command.ts | import AWS, { Organizations, STS } from 'aws-sdk';
import { AssumeRoleRequest } from 'aws-sdk/clients/sts';
import { SharedIniFileCredentialsOptions } from 'aws-sdk/lib/credentials/shared_ini_file_credentials';
import { Command } from 'commander';
import { existsSync, readFileSync } from 'fs';
import * as ini from 'ini... |
}
}
return parameters;
}
private async customInitializationIncludingMFASupport(command: ICommandArgs) {
const profileName = command.profile ? command.profile : 'default';
const homeDir = require('os').homedir();
// todo: add support for windows?
if... | {
const key = parameterAttributes.find((x) => x.startsWith('ParameterKey='));
const value = parameterAttributes.find((x) => x.startsWith('ParameterValue='));
if (key === undefined || value === undefined) {
throw new OrgFormationError(`e... | conditional_block |
base-command.ts | import AWS, { Organizations, STS } from 'aws-sdk';
import { AssumeRoleRequest } from 'aws-sdk/clients/sts';
import { SharedIniFileCredentialsOptions } from 'aws-sdk/lib/credentials/shared_ini_file_credentials';
import { Command } from 'commander';
import { existsSync, readFileSync } from 'fs';
import * as ini from 'ini... | (command?: Command, name?: string, description?: string, firstArgName?: string) {
if (command !== undefined && name !== undefined) {
this.command = command.command(name);
if (description !== undefined) {
this.command.description(description);
}
thi... | constructor | identifier_name |
converter.go | flushInterval time.Duration
// maxFlushCount defines what's the amount of entries in the buffer that
// will trigger a flush of log entries.
maxFlushCount uint
// flushChan is an internal channel used for transporting batched pdata.Logs.
flushChan chan pdata.Logs
// data holds currently converted and aggregated... | anID(buffer))
}
if ent.TraceFlags != nil {
// The 8 least significant bits are the trace flags as defined in W3C Trace
// Context specification. Don't override the 24 reserved bits.
flags := dest.Flags()
flags = flags & 0xFFFFFF00
flags = flags | uint32(ent.TraceFlags[0])
dest.SetFlags(flags)
}
}
func i... | identifier_body | |
converter.go | // │ by marshaled Resource and based on flush interval │
// │ and maxFlushCount decides whether to send the │
// │ aggregated buffer to flushChan │
// └───────────────────────────┬─────────────────────────┘
// │
// ... | random_line_split | ||
converter.go | │
// │ aggregated buffer to flushChan │
// └───────────────────────────┬─────────────────────────┘
// │
// ▼
// ┌─────────────────────────────────────────────────────┐
// │ flushLoop() ... | pLogs = pdata.NewLogs()
logs := pLogs.ResourceLogs()
logs.Resize(1)
rls := logs.At(0)
resource := rls.Resource()
resourceAtts := resource.Attributes()
resourceAtts.EnsureCapacity(len(wi.Resource))
for k, v := range wi.Resource {
resourceAtts.InsertString(k, v)
}
ills := rl... | } else {
| identifier_name |
converter.go | NewConverter(opts ...ConverterOption) *Converter {
c := &Converter{
workerChan: make(chan *entry.Entry),
workerCount: int(math.Max(1, float64(runtime.NumCPU()/4))),
batchChan: make(chan *workerItem),
data: make(map[string]pdata.Logs),
pLogsChan: make(chan pdata.Logs),
stopChan: ... | obsMap map[string]interface{}) pdata.AttributeValue {
attVal := pdata.NewAttributeValueMap()
attMap := attVal.MapVal()
attMap.EnsureCapacity(len(obsMap))
for k, v := range obsMap {
switch t := v.(type) {
case bool:
attMap.InsertBool(k, t)
case string:
| conditional_block | |
hospital-info.component.ts | : VegaBarchartService,
private i18nService: I18nService,
private diviRepo: QualitativeDiviDevelopmentRepository,
private hospitalUtil: HospitalUtilService
) {
}
ngOnInit(): void {
this.updateData();
}
private async updateData() {
this.tempChartSpecs$ = und... | random_line_split | ||
hospital-info.component.ts | {
contact: string;
url: boolean;
contactMsg: string;
public eBedType = BedType;
@Input()
mode: 'dialog' | 'tooltip';
private _data: SingleHospitalOut<QualitativeTimedStatus> | AggregatedHospitalOut<QualitativeTimedStatus>;
private _options: BedGlyphOptions | BedBackgroundOptions;
@Input()
se... | ): Observable<any[]> {
return of(true)
.pipe(
map(() => {
const bedStati = this.glyphLegendColors;
const colors = [];
for (const bedStatus of bedStati) {
colors.push(this.getCapacityStateColor(bedStatus));
}
const specs = [];
let maxNum = 0;
... | etTemporalCharts( | identifier_name |
hospital-info.component.ts | {
contact: string;
url: boolean;
contactMsg: string;
public eBedType = BedType;
@Input()
mode: 'dialog' | 'tooltip';
private _data: SingleHospitalOut<QualitativeTimedStatus> | AggregatedHospitalOut<QualitativeTimedStatus>;
private _options: BedGlyphOptions | BedBackgroundOptions;
@Input()
se... |
const tenDaysAgo = moment().subtract(10, 'day');
// const data = this.fullData.developments.filter(d => tenDaysAgo.isBefore(moment(d.timestamp)));
for (const bedAccessor of this.bedAccessors) {
let summedbedcounts = 0;
const dataValues = [];
if (this.firstTimestam... |
return of(true)
.pipe(
map(() => {
const bedStati = this.glyphLegendColors;
const colors = [];
for (const bedStatus of bedStati) {
colors.push(this.getCapacityStateColor(bedStatus));
}
const specs = [];
let maxNum = 0;
let maxNumSlices... | identifier_body |
hospital-info.component.ts | }, "legend": false}
}
};
tempChartSpecs$: Observable<any[]>;
barChartSpecs$: Observable<any[]>;
bedAccessors = ['icu_low_state', 'icu_high_state', 'ecmo_state'];
bedAccessorsMapping = {'icu_low_state': 'ICU - Low Care', 'icu_high_state': 'ICU - High Care', 'ecmo_state': 'ECMO'};
isSingleHospital =... |
spec.mark.interpolate = 'step-after';
spec.encoding.y.axis.title = this.translationService.translate('Anzahl KH');
spec.encoding.x.axis.tickCount = 5;
// spec.width = 370;
} | conditional_block | |
mod.rs | hash = md5::compute(hash_source.as_bytes()).to_hex();
// println!("hash computed {} from {}",
// hash.chars().take(4).collect::<String>(),
// hash_source);
let mut i = hash.chars();
let first = i.next().unwrap();
let second = i.next().unwrap();
let third = i.next().unwra... | (passcode: String) -> Maze {
Maze {
width: 4,
height: 4,
destination: Point { x: 3, y: 3 },
calculated: HashMap::new(),
passcode: passcode,
}
}
/// have we visited this room and had this set of doors before?
fn have_visited(&mut se... | new | identifier_name |
mod.rs | hash = md5::compute(hash_source.as_bytes()).to_hex();
// println!("hash computed {} from {}",
// hash.chars().take(4).collect::<String>(),
// hash_source);
let mut i = hash.chars();
let first = i.next().unwrap();
let second = i.next().unwrap();
let third = i.next().unwra... | // println!("Previous doors here {:?}", previous_door_sets_here);
previous_door_sets_here.into_iter().any(|d| d.clone() == doors)
}
None => false,
};
result
}
fn get_doors_for(&mut self, room: Point, path: Vec<Dir>) -> Vec<Dir> {
i... | random_line_split | |
mod.rs | hash = md5::compute(hash_source.as_bytes()).to_hex();
// println!("hash computed {} from {}",
// hash.chars().take(4).collect::<String>(),
// hash_source);
let mut i = hash.chars();
let first = i.next().unwrap();
let second = i.next().unwrap();
let third = i.next().unwra... |
fn find_longest_route(&self, pos: Point, path: &Vec<Dir>, steps: usize) -> usize {
// based on the nicely elegant C solution by GitHub user rhardih
let doors = open_doors_here(&self.passcode, path);
let mut longest = 0;
let can_up = doors.contains(&Dir::Up) && !self.is_wall(pos.cl... | {
let room = self.calculated.get(&self.destination);
match room {
None => Vec::new(),
Some(r) => r.keys().cloned().collect(),
}
} | identifier_body |
frame.go | , fmt.Errorf("frame body length can not be less than 0: %d", head.BodyLength)
} else if head.BodyLength > maxFrameSize {
// need to free up the connection to be used again
logp.Err("head length is too large")
return nil, ErrFrameTooBig
}
headSize := f.r.BufferConsumed()
head.HeadLength = headSize
debugf("h... | parseResultPrepared | identifier_name | |
frame.go | framer is responsible for reading, writing and parsing frames on a single stream
type Framer struct {
proto byte
compres Compressor
isCompressed bool
// if this frame was read then the header will be here
Header *frameHeader
r *streambuf.Buffer
decoder Decoder
}
func NewFramer(r *streambuf.Buffer, compres... |
case errWriteTimeout:
cl := decoder.ReadConsistency()
received := decoder.ReadInt()
blockfor := decoder.ReadInt()
writeType := decoder.ReadString()
detail["read_consistency"] = cl.String()
detail["received"] = received
detail["blockfor"] = blockfor
detail["write_type"] = writeType
case errReadTimeo... | {
decoder := f.decoder
code := decoder.ReadInt()
msg := decoder.ReadString()
errT := ErrType(code)
data = make(map[string]interface{})
data["code"] = code
data["msg"] = msg
data["type"] = errT.String()
detail := map[string]interface{}{}
switch errT {
case errUnavailable:
cl := decoder.ReadConsistency()
... | identifier_body |
frame.go | amer is responsible for reading, writing and parsing frames on a single stream
type Framer struct {
proto byte
compres Compressor
isCompressed bool
// if this frame was read then the header will be here
Header *frameHeader
r *streambuf.Buffer
decoder Decoder
}
func NewFramer(r *streambuf.Buffer, compressor... |
if f.Header.Flags&flagCustomPayload == flagCustomPayload {
debugf("hit custom payload flags")
f.Header.CustomPayload = decoder.ReadBytesMap()
}
if f.Header.Flags&flagCompress == flagCompress {
//decompress data and switch to use bytearray decoder
if f.compres == nil {
logp.Err("hit compress flag, but ... | {
debugf("hit warning flags")
warnings := decoder.ReadStringList()
// dealing with warnings
data["warnings"] = warnings
} | conditional_block |
frame.go | v", head)
f.Header = head
return head, nil
}
// reads a frame form the wire into the framers buffer
func (f *Framer) ReadFrame() (data map[string]interface{}, err error) {
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
err = r.(error)
}
}()
decoder :... | }
result["resp_meta"] = f.parseResultMetadata(false)
| random_line_split | |
gameentity.py | if name is None:
GameEntity.COUNTER += 1
self.name = "Entity ".format(GameEntity.COUNTER)
# Image settings
self.z_level = z_level # The depth. Default is 2, min is 0.
self.image_ref = image_ref
self.image = None
self.animated = False
self... | # This is the case for the special visual effect
self.image = self.image_ref
else:
image = GLOBAL.img(self.image_ref)
if type(image) is tuple:
# for decode purpose
self.image = Surface(TILESIZE_SCREEN)
self.image.fil... | :return: Nothing
"""
if type(self.image_ref) is Surface: | random_line_split |
gameentity.py | if name is None:
GameEntity.COUNTER += 1
self.name = "Entity ".format(GameEntity.COUNTER)
# Image settings
self.z_level = z_level # The depth. Default is 2, min is 0.
self.image_ref = image_ref
self.image = None
self.animated = False
self... |
# success
self.x += dx
self.y += dy
if self.animated and (dx != 0 or dy != 0):
self.last_direction = (dx, dy)
GLOBAL.game.invalidate_fog_of_war = True
# self.game.ticker.ticks_to_advance += self.speed_cost_for(c.AC_ENV_MOVE)
... | if entity != self and entity.blocks and entity.x == self.x + dx and entity.y == self.y + dy:
return False | conditional_block |
gameentity.py | .image_ref)
if type(image) is tuple:
# for decode purpose
self.image = Surface(TILESIZE_SCREEN)
self.image.fill(image)
elif type(image) is list or type(image) is dict:
self.animated = True
self.current_frame = 0
... | WanderingAIEntity | identifier_name | |
gameentity.py | if name is None:
GameEntity.COUNTER += 1
self.name = "Entity ".format(GameEntity.COUNTER)
# Image settings
self.z_level = z_level # The depth. Default is 2, min is 0.
self.image_ref = image_ref
self.image = None
self.animated = False
self.curren... |
def assign_entity_to_region(self, region):
self.add(region.all_groups[self.z_level])
self.current_region_name = region.name
self._current_region = region
region.region_entities.add(self)
if self.ai is not None:
region.ticker.schedule_turn(self.ai.speed, self.ai)... | self.rect = self.image.get_rect()
self.rect.centerx = self.x * TILESIZE_SCREEN[0] + int(TILESIZE_SCREEN[1] / 2) # initial position for the camera
self.rect.centery = self.y * TILESIZE_SCREEN[0] + int(TILESIZE_SCREEN[1] / 2) | identifier_body |
engine.math2d.js | {
return (radians * 180 / Math2D.PI);
},
/**
* Perform AAB (axis-aligned box) to AAB collision testing, returning <tt>true</tt>
* if the two boxes overlap.
*
* @param box1 {Rectangle2D} The collision box of object 1
* @param box2 {Rectangle2D} The collision box of object 2
... | (point0, point1, point2) {
var p0 = point0.get(), p1 = point1.get(), p2 = point2.get();
return (p1.x - p0.x)*(p2.y - p0.y) - (p2.x - p0.x)*(p1.y - p0.y);
}
var Bin = Base.extend({
B: null,
constructor: function(size) {
this.B = [];
for (var i = 0; i < size; i++) {
this.B.push(... | isLeft | identifier_name |
engine.math2d.js | {
return (radians * 180 / Math2D.PI);
},
/**
* Perform AAB (axis-aligned box) to AAB collision testing, returning <tt>true</tt>
* if the two boxes overlap.
*
* @param box1 {Rectangle2D} The collision box of object 1
* @param box2 {Rectangle2D} The collision box of object 2
... | xmax = cP.x;
maxmin = maxmax = i;
} else { // another xmax
if (cP.y < points[maxmin | random_line_split | |
engine.math2d.js | {
return (radians * 180 / Math2D.PI);
},
/**
* Perform AAB (axis-aligned box) to AAB collision testing, returning <tt>true</tt>
* if the two boxes overlap.
*
* @param box1 {Rectangle2D} The collision box of object 1
* @param box2 {Rectangle2D} The collision box of object 2
... |
var Bin = Base.extend({
B: null,
constructor: function(size) {
this.B = [];
for (var i = 0; i < size; i++) {
this.B.push({
min: 0,
max: 0
});
}
}
});
var NONE = -1;
var minmin=0, minmax=0,
maxmin=0, maxmax=0,
xmin = points[0].get().x, ... | {
var p0 = point0.get(), p1 = point1.get(), p2 = point2.get();
return (p1.x - p0.x)*(p2.y - p0.y) - (p2.x - p0.x)*(p1.y - p0.y);
} | identifier_body |
client.go | ing requests,
// a state handler and a list of supported profiles (optional).
//
// You may create a simple new server by using these default values:
//
// s := ocppj.NewClient(ws.NewClient(), nil, nil)
//
// The wsClient parameter cannot be nil. Refer to the ws package for information on how to create and
// customize... | // The read/write routines are run on dedicated goroutines, so the main thread can perform other operations.
//
// In case of disconnection, the client handles re-connection automatically.
// The client will attempt to re-connect to the server forever, until it is stopped by invoking the Stop method.
//
// An error may... | //
// If the connection is established successfully, the function returns control to the caller immediately. | random_line_split |
client.go | ing requests,
// a state handler and a list of supported profiles (optional).
//
// You may create a simple new server by using these default values:
//
// s := ocppj.NewClient(ws.NewClient(), nil, nil)
//
// The wsClient parameter cannot be nil. Refer to the ws package for information on how to create and
// customize... | err = ocppErr
// Send error to other endpoint if a message ID is available
if ocppErr.MessageId != "" {
err2 := c.SendError(ocppErr.MessageId, ocppErr.Code, ocppErr.Description, nil)
if err2 != nil {
return err2
}
}
log.Error(err)
return err
}
if message != nil {
switch message.GetMessageTy... | {
parsedJson, err := ParseRawJsonMessage(data)
if err != nil {
log.Error(err)
return err
}
log.Debugf("received JSON message from server: %s", string(data))
message, err := c.ParseMessage(parsedJson, c.RequestState)
if err != nil {
ocppErr := err.(*ocpp.Error)
messageID := ocppErr.MessageId
// Support a... | identifier_body |
client.go | ing requests,
// a state handler and a list of supported profiles (optional).
//
// You may create a simple new server by using these default values:
//
// s := ocppj.NewClient(ws.NewClient(), nil, nil)
//
// The wsClient parameter cannot be nil. Refer to the ws package for information on how to create and
// customize... |
jsonMessage, err := callError.MarshalJSON()
if err != nil {
return ocpp.NewError(GenericError, err.Error(), requestId)
}
if err = c.client.Write(jsonMessage); err != nil {
log.Errorf("error sending response error [%s]: %v", callError.UniqueId, err)
return ocpp.NewError(GenericError, err.Error(), requestId)
... | {
return err
} | conditional_block |
client.go | ing requests,
// a state handler and a list of supported profiles (optional).
//
// You may create a simple new server by using these default values:
//
// s := ocppj.NewClient(ws.NewClient(), nil, nil)
//
// The wsClient parameter cannot be nil. Refer to the ws package for information on how to create and
// customize... | (handler func(response ocpp.Response, requestId string)) {
c.responseHandler = handler
}
// Registers a handler for incoming error messages.
func (c *Client) SetErrorHandler(handler func(err *ocpp.Error, details interface{})) {
c.errorHandler = handler
}
// SetInvalidMessageHook registers an optional hook for incom... | SetResponseHandler | identifier_name |
sourcefit.py | (self,map,src_lst,burnin=2500,runtime=1000,fit_radius=15*u.arcmin,Nwalker=50):
# load map in Jy/pix units
MAP, WCS = map.convert_unit(units=u.Jy/(u.pixel**2),update=False)
# ensure src_lst is a list of sources and retrieve coordinates of each one
if type(src_lst) is astroSrc:
... | run | identifier_name | |
sourcefit.py |
x_cutout = coords_cutout.l.degree
y_cutout = coords_cutout.b.degree
dx_cutout = x_cutout-s.COORD.l.degree
dy_cutout = y_cutout-s.COORD.b.degree
dr_cutout = np.sqrt(dx_cutout**2 + dy_cutout**2)*u.degree
fitting_area = dr_cutout<fit_radius
... | MAP, WCS = map.convert_unit(units=u.Jy/(u.pixel**2),update=False)
# ensure src_lst is a list of sources and retrieve coordinates of each one
if type(src_lst) is astroSrc:
src_lst = [src_lst]
map_skyCoord = map.rtn_coords()
map_noise = 0.01
for _s,s in enumerate(src_... | identifier_body | |
sourcefit.py | 0.0, # slope_x
0.0, # slope_y
1, # Amplitude
0.0, # x_mean
0.0, # y_mean
5/(60*np.sqrt(8*np.log(2))), # x_stddev... | x_pc,y_pc = wcs.utils.skycoord_to_pixel(s.COORD,map.WCS)
x_pc,y_pc = int(x_pc),int(y_pc)
D=int(abs(fit_radius.to(u.degree).value/WCS.wcs.cdelt[0])+3)
map_cutout = MAP[y_pc-D:y_pc+D+1,x_pc-D:x_pc+D+1].value
coords_cutout = map.rtn_coords()[y_pc-D:y_pc+D+1,x_pc-D:x_pc+D+1]
... | conditional_block | |
sourcefit.py | .WCS)
x_pc,y_pc = int(x_pc),int(y_pc)
D=int(abs(fit_radius.to(u.degree).value/WCS.wcs.cdelt[0])+3)
map_cutout = MAP[y_pc-D:y_pc+D+1,x_pc-D:x_pc+D+1].value
coords_cutout = map.rtn_coords()[y_pc-D:y_pc+D+1,x_pc-D:x_pc+D+1]
wcs_cutout = wcs.WCS(naxis=2)
... | chains[:,:,8][chains[:,:,8]>cval+np.pi/2] -= np.pi
def create_filter(chain,n,thresh=1.5):
final_amps = chain[:,-1,n]
q1 = np.percentile(final_amps, 25, interpolation='midpoint')
q3 = np.percentile(final_amps, 75, interpolation='midpoint')
... | random_line_split | |
main.rs | followed by the application of a second one to the result of the first.
* Once the second part has generated all possible candidate for a potentially misspelled word,
* it picks the most frequently used one from the training corpus. If none of the candidates is a correct word,
* correct reports a failure.
*
* ... | if let Some(currtrie) = trie.children.get(&curchar){
let counter = 0;
cur.push(curchar);
<<<<<<< HEAD
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
temp = find(currtrie,path,&mut temppath,cur,counter)... | temppath = pathclone.clone();
temppath.remove(0);
curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar){
let counter = op-1;
cur.push(curchar);
<<<<<<< HEAD
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0... | conditional_block |
main.rs | followed by the application of a second one to the result of the first.
* Once the second part has generated all possible candidate for a potentially misspelled word,
* it picks the most frequently used one from the training corpus. If none of the candidates is a correct word,
* correct reports a failure.
*
... | *
* Input : trie: The trie made from corpus.txt, contains all the word
* path: The misspelled word
* pathclone: The remained string need to match
* cur: The trie path
* op: The edit times left for current matching
*
* The stop condition is that current trie path consist a word and match... | * This is the main search function for this program. We implement the DFS(Depth-First-Search)+Regression
* Algorithm to travel the whole trie and find all the candidate word, then pick the most frequently one. | random_line_split |
main.rs | followed by the application of a second one to the result of the first.
* Once the second part has generated all possible candidate for a potentially misspelled word,
* it picks the most frequently used one from the training corpus. If none of the candidates is a correct word,
* correct reports a failure.
*
* ... | }
cur.pop();
}
//deletion
//if we can get a word after deleting current character
if op > 0{
if pathclone.len()==1 && trie.value>0{
temp= Result{
value: trie.value,
... | n()==0 && trie.value>0 {
return Result{
value: trie.value,
key: cur.clone(),
}
}
else{
let mut max= Result::new();
let mut temp: Result;
let mut temppath =pathclone.clone();
let mut currtrie :&Trie;
if pathclone.len()>0{
let mut curchar = tempp... | identifier_body |
main.rs | followed by the application of a second one to the result of the first.
* Once the second part has generated all possible candidate for a potentially misspelled word,
* it picks the most frequently used one from the training corpus. If none of the candidates is a correct word,
* correct reports a failure.
*
* ... | h: & String,pathclone: & mut String,cur: & mut String, op: i64)-> Result{
if pathclone.len()==0 && trie.value>0 {
return Result{
value: trie.value,
key: cur.clone(),
}
}
else{
let mut max= Result::new();
let mut temp: Result;
let mut temppath =pathclone.clone();
let mut c... | pat | identifier_name |
sheet.py | _enabled = fields.Bool(data_key="criticalPathEnabled")
display_summary_tasks = fields.Bool(data_key="displaySummaryTasks")
@attr.s(auto_attribs=True, repr=False, kw_only=True)
class UserSettings(Object):
critical_path_enabled: bool
display_summary_tasks: bool
class UserPermissionsSchema(Schema):
sum... | cell_image_upload_enabled = fields.Bool(data_key="cellImageUploadEnabled")
user_settings = fields.Nested(UserSettingsSchema, data_key="userSettings")
user_permissions = fields.Nested(UserPermissionsSchema, data_key="userPermissions")
has_summary_fields = fields.Bool(data_key="hasSummaryFields")
is_m... | resource_management_enabled = fields.Bool(data_key="resourceManagementEnabled") | random_line_split |
sheet.py | _enabled = fields.Bool(data_key="criticalPathEnabled")
display_summary_tasks = fields.Bool(data_key="displaySummaryTasks")
@attr.s(auto_attribs=True, repr=False, kw_only=True)
class UserSettings(Object):
critical_path_enabled: bool
display_summary_tasks: bool
class UserPermissionsSchema(Schema):
sum... |
for row in self.rows:
row._update_index(self)
def get_row(
self,
row_num: Optional[int] = None,
row_id: Optional[int] = None,
filter: Optional[Dict[str, Any]] = None,
) -> Optional[RowT]:
"""Returns Row object by row number or ID
Either row... | columns = index["columns"]
unique = index["unique"]
self.indexes[columns] = {"index": {}, "unique": unique} | conditional_block |
sheet.py | ="userPermissions")
has_summary_fields = fields.Bool(data_key="hasSummaryFields")
is_multi_picklist_enabled = fields.Bool(data_key="isMultiPicklistEnabled")
columns = fields.List(fields.Nested(ColumnSchema))
rows = fields.List(fields.Nested(RowSchema))
workspace = fields.Nested(WorkspaceSchema)
... | as_dataframe | identifier_name | |
sheet.py | (data_key="createdAt")
modified_at = fields.DateTime(data_key="modifiedAt")
version = fields.Int()
total_row_count = fields.Int(data_key="totalRowCount")
effective_attachment_options = fields.List(
fields.Str(), data_key="effectiveAttachmentOptions"
)
gantt_enabled = fields.Bool(data_ke... | """Creates a Cell object for an existing column
Args:
column_title: title of an existing column
field_value: value of the cell
Returns:
Cell object
"""
column = self.get_column(column_title)
if column is None:
raise ValueError(
... | identifier_body | |
lisplike.rs | 0));
assert_eq!(eval(symt, read("(id 123)")), ~Num(123.0));
assert_eq!(eval(symt, read("(id (id (id 123)))")), ~Num(123.0));
// should fail: assert_eq!(eval(&mut symt, read("(1 2 3)")), ~List(~[Num(1.0), Num(2.0), Num(3.0)]));
}
#[test]
fn test_str() {
let mut symt = Rc::new(new_symt());
init_std(symt);
... | {
let mut symt = Rc::new(new_symt());
init_std(symt);
eval(symt, read("(def fac (fn (n) (cond ((= n 0) 1) (true (* n (fac (- n 1)))))))"));
assert_eq!(eval(symt, read("(fac 10)")), ~Num(3628800.0));
} | identifier_body | |
lisplike.rs | () -> SymbolTable {
HashMap::new()
}
/// Binds a symbol in the symbol table. Replaces if it already exists.
pub fn bind(symt: Rc<SymbolTable>, name: ~str, value: ~LispValue) {
symt.borrow().insert(name, value);
}
/// Look up a symbol in the symbol table. Fails if not found.
pub fn lookup(symt: Rc<SymbolTable>, name... | new_symt | identifier_name | |
lisplike.rs |
// XXX: this is ugly but it won't automatically derive Eq because of the extern fn
impl Eq for LispValue {
fn eq(&self, other: &LispValue) -> bool {
match (self.clone(), other.clone()) {
(BIF(ref x, _, _, _), BIF(ref y, _, _, _)) if *x == *y => true,
(Str(ref x), Str(ref y)) if *x == *y => true,
(Num(ref x... | } | random_line_split | |
client.go | subscriptions
type SubscriptionProcessor func(subscription Subscription)
// SubscriptionValidator - callback method type to validate subscription for processing
type SubscriptionValidator func(subscription Subscription) bool
// Client - interface
type Client interface {
PublishService(serviceBody ServiceBody) (*v1a... |
return "", reqErr
}
// Get the email
var platformUserInfo PlatformUserInfo
err = json.Unmarshal | {
return "", ErrNoAddressFound.FormatError(id)
} | conditional_block |
client.go | process subscriptions
type SubscriptionProcessor func(subscription Subscription)
// SubscriptionValidator - callback method type to validate subscription for processing
type SubscriptionValidator func(subscription Subscription) bool
// Client - interface
type Client interface {
PublishService(serviceBody ServiceBod... | }
}
// Check that appropriate settings for the API server are set
err = c.checkAPIServerHealth()
if err != nil {
s = hc.Status{
Result: hc.FAIL,
Details: err.Error(),
}
}
// Return our response
return &s
}
func (c *ServiceClient) checkPlatformHealth() error {
_, err := c.tokenRequester.GetToken(... | if err != nil {
s = hc.Status{
Result: hc.FAIL,
Details: err.Error(), | random_line_split |
client.go | process subscriptions
type SubscriptionProcessor func(subscription Subscription)
// SubscriptionValidator - callback method type to validate subscription for processing
type SubscriptionValidator func(subscription Subscription) bool
// Client - interface
type Client interface {
PublishService(serviceBody ServiceBod... | if webCfg != nil && webCfg.IsConfigured() {
serviceClient.DefaultSubscriptionApprovalWebhook = webCfg
}
serviceClient.subscriptionMgr = newSubscriptionManager(serviceClient)
hc.RegisterHealthcheck(serverName, "central", serviceClient.healthcheck)
return serviceClient
}
// mapToTagsArray -
func (c *ServiceCli... | {
tokenURL := cfg.GetAuthConfig().GetTokenURL()
aud := cfg.GetAuthConfig().GetAudience()
priKey := cfg.GetAuthConfig().GetPrivateKey()
pubKey := cfg.GetAuthConfig().GetPublicKey()
keyPwd := cfg.GetAuthConfig().GetKeyPassword()
clientID := cfg.GetAuthConfig().GetClientID()
authTimeout := cfg.GetAuthConfig().GetTi... | identifier_body |
client.go | (p *platformTokenGetter) GetToken() (string, error) {
return p.requester.GetToken()
}
// New -
func New(cfg corecfg.CentralConfig) Client {
tokenURL := cfg.GetAuthConfig().GetTokenURL()
aud := cfg.GetAuthConfig().GetAudience()
priKey := cfg.GetAuthConfig().GetPrivateKey()
pubKey := cfg.GetAuthConfig().GetPublicK... | getTeam | identifier_name | |
git.go | appear in the box when the user presses 'back'. Thus we use a
hidden field in the form. However, there's no way to stop the
non-hidden text box from also submitting a value unless we move
it outside of the form
<input type="search" id="codesearchQuer... | a couple of restricts to the query before submitting. If we just
add the restricts to the text box before submitting, then they | random_line_split | |
base.py | random import randint
from Products.Five.browser import BrowserView
from Products.CMFCore.utils import getToolByName
from collective.sendaspdf import transforms
from collective.sendaspdf.utils import find_filename, update_relative_url
from collective.sendaspdf.utils import md5_hash
from collective.sendaspdf.utils i... | for x in reversed(opt_val):
options.append(str(x))
else:
options.append(str(opt_val))
options.append('--%s' % opt_name)
break
return options
def generate_pdf_file(self, source):
""" Gen... | random_line_split | |
base.py | random import randint
from Products.Five.browser import BrowserView
from Products.CMFCore.utils import getToolByName
from collective.sendaspdf import transforms
from collective.sendaspdf.utils import find_filename, update_relative_url
from collective.sendaspdf.utils import md5_hash
from collective.sendaspdf.utils i... |
return mtool.getAuthenticatedMember()
def get_user_fullname(self):
""" Returns the currently logged-in user's fullname.
"""
member = self.get_user()
if member:
return member.getProperty('fullname')
def get_user_email(self):
""" Returns the currentl... | return | conditional_block |
base.py | random import randint
from Products.Five.browser import BrowserView
from Products.CMFCore.utils import getToolByName
from collective.sendaspdf import transforms
from collective.sendaspdf.utils import find_filename, update_relative_url
from collective.sendaspdf.utils import md5_hash
from collective.sendaspdf.utils i... |
def get_user_email(self):
""" Returns the currently logged-in user's email.
"""
member = self.get_user()
if member:
return member.getProperty('email')
def generate_filename_prefix(self):
""" Returns the user's email hashed in md5 followed
by an unde... | """ Returns the currently logged-in user's fullname.
"""
member = self.get_user()
if member:
return member.getProperty('fullname') | identifier_body |
base.py | random import randint
from Products.Five.browser import BrowserView
from Products.CMFCore.utils import getToolByName
from collective.sendaspdf import transforms
from collective.sendaspdf.utils import find_filename, update_relative_url
from collective.sendaspdf.utils import md5_hash
from collective.sendaspdf.utils i... | (self, fieldname):
""" Returns the class that should be applied to a field
in the forms displayed by the product.
"""
base_class = 'field'
error_class = ' error'
if not fieldname in self.error_mapping:
if fieldname in self.errors:
base_class +=... | class_for_field | identifier_name |
apply.rs | }
fn into_inner(self) -> &'a T {
self.inner()
}
fn is_patched(&self) -> bool {
match self {
ImageLine::Unpatched(_) => false,
ImageLine::Patched(_) => true,
}
}
}
impl<T: ?Sized> Copy for ImageLine<'_, T> {}
impl<T: ?Sized> Clone for ImageLine<'_, ... | ;
// If any of these lines have already been patched then we can't match at this position
if image.iter().any(ImageLine::is_patched) {
return false;
}
pre_image(lines).eq(image.iter().map(ImageLine::inner))
}
#[derive(Debug)]
struct Interleave<I, J> {
a: iter::Fuse<I>,
b: iter::Fuse<J... | {
return false;
} | conditional_block |
apply.rs | ,
}
}
}
impl<T: ?Sized> Copy for ImageLine<'_, T> {}
impl<T: ?Sized> Clone for ImageLine<'_, T> {
fn clone(&self) -> Self {
*self
}
}
#[derive(Debug)]
pub struct ApplyOptions {
max_fuzzy: usize,
}
impl Default for ApplyOptions {
fn default() -> Self {
ApplyOptions::new()
... | next | identifier_name | |
apply.rs |
fn into_inner(self) -> &'a T {
self.inner()
}
fn is_patched(&self) -> bool {
match self {
ImageLine::Unpatched(_) => false,
ImageLine::Patched(_) => true,
}
}
}
impl<T: ?Sized> Copy for ImageLine<'_, T> {}
impl<T: ?Sized> Clone for ImageLine<'_, T> {
... | {
match self {
ImageLine::Unpatched(inner) | ImageLine::Patched(inner) => inner,
}
} | identifier_body | |
apply.rs | }
fn into_inner(self) -> &'a T {
self.inner()
}
fn is_patched(&self) -> bool {
match self {
ImageLine::Unpatched(_) => false,
ImageLine::Patched(_) => true,
}
}
}
impl<T: ?Sized> Copy for ImageLine<'_, T> {}
impl<T: ?Sized> Clone for ImageLine<'_, ... | }
/// Apply a non-utf8 `Patch` to a base image
pub fn apply_bytes(base_image: &[u8], patch: &Patch<'_, [u8]>) -> Result<Vec<u8>, ApplyError> {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
for (i, hunk) in patch.hunks().iter().enumerate() {
ap... | random_line_split | |
views.py | TajweedEvaluationSerializer, EvaluationSerializer
from restapi.models import AnnotatedRecording
from quran.models import Ayah, AyahWord, Translation
# Python
import io
import json
import os
import random
# =============================================== #
# Constant Global Definitions #
# ========... |
class EvaluationViewSet(viewsets.ModelViewSet):
"""API to handle query parameters
Example: v1/evaluations/?surah=114&ayah=1&evaluation=correct
"""
serializer_class = EvaluationSerializer
queryset = Evaluation.objects.all()
filter_backends = (filters.DjangoFilterBackend,)
filter_class = Ev... | """Custom filter based on surah, ayah, evaluation type or recording."""
EVAL_CHOICES = (
('correct', 'Correct'),
('incorrect', 'Incorrect')
)
surah = filters.NumberFilter(field_name='associated_recording__surah_num')
ayah = filters.NumberFilter(field_name='associated_recording__ayah_num... | identifier_body |
views.py | TajweedEvaluationSerializer, EvaluationSerializer
from restapi.models import AnnotatedRecording
from quran.models import Ayah, AyahWord, Translation
# Python
import io
import json
import os
import random
# =============================================== #
# Constant Global Definitions #
# ========... | (surah_num=0, ayah_num=0, random_rule=False):
"""If random_rule is true then we get a random tajweed rule. Otherwise returns a
specific rule. Both options return the text and word index.
:return: A tuple with the surah & ayah number, text, rule, and word position
:rtype: tuple(int, int, str, str, int) o... | get_tajweed_rule | identifier_name |
views.py | TajweedEvaluationSerializer, EvaluationSerializer
from restapi.models import AnnotatedRecording
from quran.models import Ayah, AyahWord, Translation
# Python
import io
import json
import os
import random
# =============================================== #
# Constant Global Definitions #
# ========... | along with its words, url and recording ID.
:rtype: dict
"""
# Get recordings with a file.
if surah_num is not None and ayah_num is not None:
recording_evals = AnnotatedRecording.objects.filter(
surah_num=surah_num, ayah_num=ayah_num, file__gt='',
file__isnull... | """Finds a recording with the lowest number of evaluations
:returns: A random AnnotatedRecording object which has the minimum evaluations | random_line_split |
views.py | TajweedEvaluationSerializer, EvaluationSerializer
from restapi.models import AnnotatedRecording
from quran.models import Ayah, AyahWord, Translation
# Python
import io
import json
import os
import random
# =============================================== #
# Constant Global Definitions #
# ========... |
return Response(new_evaluation.errors, status=status.HTTP_400_BAD_REQUEST)
# ===================================== #
# Static Page Views #
# ===================================== #
@api_view(('GET',))
@renderer_classes((JSONRenderer,))
def get_evaluations_count(request, format=None):
... | new_evaluation.save()
return Response(new_evaluation.data, status=status.HTTP_201_CREATED) | conditional_block |
memory.rs | type, the method return `None`.
//!
//! # Accessing the memory
//! Memory can be accessed in two ways:
//! - via _keys_
//! - via _paths_ (methods prefixed with `path_`)
//!
//! In both cases, if the value requested is `undefined`, `null`, or even just
//! of the wrong type, the method returns `None`.
//!
//! ## Acc... | return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
/// Get a dictionary value or create it if it does not exist.
///
/// If the value exists but is a different type, this will return `None`.
pub fn dict_or_create(&self, key: &str) -> Result<MemoryReference, Unexpe... | random_line_split | |
memory.rs | type, the method return `None`.
//!
//! # Accessing the memory
//! Memory can be accessed in two ways:
//! - via _keys_
//! - via _paths_ (methods prefixed with `path_`)
//!
//! In both cases, if the value requested is `undefined`, `null`, or even just
//! of the wrong type, the method returns `None`.
//!
//! ## Acc... | else {
Some(val.try_into()).transpose()
}
}
pub fn set<T>(&self, key: &str, value: T)
where
T: JsSerialize,
{
js! { @(no_return)
(@ | {
Ok(None)
} | conditional_block |
memory.rs | type, the method return `None`.
//!
//! # Accessing the memory
//! Memory can be accessed in two ways:
//! - via _keys_
//! - via _paths_ (methods prefixed with `path_`)
//!
//! In both cases, if the value requested is `undefined`, `null`, or even just
//! of the wrong type, the method returns `None`.
//!
//! ## Acc... | (&self, key: &str) -> Result<Option<f64>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_f64(&self, path: &str) -> Result<Option<f64>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})... | f64 | identifier_name |
memory.rs | ();
//! let cpu_used_last_tick = mem.i32("cpu_used_last_tick").unwrap();
//! ```
//!
//! ## Accessing memory with a _path_
//! A quality of life improvement upon the key access is through full path. In
//! javascript, it is possible to query a value with a full path:
//! ```javascript
//! var creep_time = Memory.creeps... | {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
} | identifier_body | |
crud.go | 8s/labels"
"github.com/okteto/okteto/pkg/log"
"github.com/okteto/okteto/pkg/model"
appsv1 "k8s.io/api/apps/v1"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
//List returns the list of deployments
func List(namespace string, c kubernetes.Interface) ([]app... |
for _, c := range d.Status.Conditions {
if c.Type == appsv1.DeploymentReplicaFailure && c.Reason == "FailedCreate" && c.Status == apiv1.ConditionTrue {
if strings.Contains(c.Message, "exceeded quota") {
log.Infof("%s: %s", errors.ErrQuota, c.Message)
return nil, errors.ErrQuota
}
return nil, fmt.E... | {
if waitUntilDeployed && errors.IsNotFound(err) {
return nil, nil
}
return nil, err
} | conditional_block |
crud.go | /k8s/labels"
"github.com/okteto/okteto/pkg/log"
"github.com/okteto/okteto/pkg/model"
appsv1 "k8s.io/api/apps/v1"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
//List returns the list of deployments
func List(namespace string, c kubernetes.Interface) ([]a... | Tolerations: dev.Tolerations,
Replicas: *d.Spec.Replicas,
Rules: []*model.TranslationRule{rule},
}
}
return nil
}
//Deploy creates or updates a deployment
func Deploy(d *appsv1.Deployment, forceCreate bool, client *kubernetes.Clientset) error {
if forceCreate {
if err := create(d, client); ... | {
for _, s := range dev.Services {
d, err := Get(s, dev.Namespace, c)
if err != nil {
return err
}
rule := s.ToTranslationRule(dev)
if _, ok := result[d.Name]; ok {
result[d.Name].Rules = append(result[d.Name].Rules, rule)
continue
}
result[d.Name] = &model.Translation{
Name: dev.Na... | identifier_body |
crud.go | /k8s/labels"
"github.com/okteto/okteto/pkg/log"
"github.com/okteto/okteto/pkg/model"
appsv1 "k8s.io/api/apps/v1"
apiv1 "k8s.io/api/core/v1" | //List returns the list of deployments
func List(namespace string, c kubernetes.Interface) ([]appsv1.Deployment, error) {
dList, err := c.AppsV1().Deployments(namespace).List(metav1.ListOptions{})
if err != nil {
return nil, err
}
return dList.Items, nil
}
//Get returns a deployment object given its name and nam... | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
| random_line_split |
crud.go | /k8s/labels"
"github.com/okteto/okteto/pkg/log"
"github.com/okteto/okteto/pkg/model"
appsv1 "k8s.io/api/apps/v1"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
//List returns the list of deployments
func List(namespace string, c kubernetes.Interface) ([]a... | (dev *model.Dev, c *kubernetes.Clientset, waitUntilDeployed bool) (*appsv1.Deployment, error) {
d, err := Get(dev, dev.Namespace, c)
if err != nil {
if waitUntilDeployed && errors.IsNotFound(err) {
return nil, nil
}
return nil, err
}
for _, c := range d.Status.Conditions {
if c.Type == appsv1.Deployment... | GetRevisionAnnotatedDeploymentOrFailed | identifier_name |
appinfo.pyi | OR_NAME_REGEX: str
ALTERNATE_HOSTNAME_SEPARATOR: str
BUILTIN_NAME_PREFIX: str
RUNTIME_RE_STRING: str
API_VERSION_RE_STRING: str
ENV_RE_STRING: str
SOURCE_LANGUAGE_RE_STRING: str
HANDLER_STATIC_FILES: str
HANDLER_STATIC_DIR: str
HANDLER_SCRIPT: str
HANDLER_API_ENDPOINT: str
LOGIN_OPTIONAL: str
LOGIN_REQUIRED: str
LOGIN_... | def Get(self, header_name): ...
def __setitem__(self, key, value) -> None: ...
class URLMap(HandlerBase):
ATTRIBUTES: Any
COMMON_FIELDS: Any
ALLOWED_FIELDS: Any
def GetHandler(self): ...
def GetHandlerType(self): ...
def CheckInitialized(self) -> None: ...
def AssertUniqueContentTyp... | VALUE_VALIDATOR: Any | random_line_split |
Website_Version.py | run the Website_Server.py file to get to the website.
# Imported modules
from datetime import datetime
from pyzbar import pyzbar
import webbrowser
import cv2
# Item scanner:
# This function scans the QR- or barcode and writes its contents into a file.
def read_barcodes(frame):
barcodes = pyzba... |
elif drug == "Lozenges":
webbrowser.open("https://www.amavita.ch/de/solmucol-erkaltungshusten-lutschtabl-100-mg-24-stk.html")
elif drug == "Dextromethorphan":
webbrowser.open("https://www.amavita.ch/de/bisolvon-dextromethorphan-pastillen-10-5-mg-20-stk.html")
elif drug == "Effervesce... | webbrowser.open("https://www.amavita.ch/de/otrivin-natural-plus-mit-eukalyptus-spray-20-ml.html") | conditional_block |
Website_Version.py | the Website_Server.py file to get to the website.
# Imported modules
from datetime import datetime
from pyzbar import pyzbar
import webbrowser
import cv2
# Item scanner:
# This function scans the QR- or barcode and writes its contents into a file.
def read_barcodes(frame):
barcodes = pyzbar.de... | webbrowser.open("https://www.amavita.ch/de/siesta-1-brausesalz-150-g.html")
elif drug == "Lactease":
webbrowser.open("https://www.amavita.ch/de/lactease-4500-fcc-kautabl-40-stk.html")
elif drug == "Glycerin":
webbrowser.open("https://www.amavita.ch/de/glycerin-elk-pharma-supp-18-st... | webbrowser.open("https://www.amavita.ch/de/bisolvon-dextromethorphan-pastillen-10-5-mg-20-stk.html")
elif drug == "Effervescent salt":
| random_line_split |
Website_Version.py | run the Website_Server.py file to get to the website.
# Imported modules
from datetime import datetime
from pyzbar import pyzbar
import webbrowser
import cv2
# Item scanner:
# This function scans the QR- or barcode and writes its contents into a file.
def read_barcodes(frame):
barcodes = pyzba... | elif drug == "Effervescent tablets":
webbrowser.open("https://www.amavita.ch/de/nasobol-inhalo-brausetabl-30-stk.html")
elif drug == "Bandage":
webbrowser.open("https://www.amavita.ch/de/emosan-medi-ellbogen-bandage-l.html")
elif drug == "Syrup":
webbrowser.open("https://www.ama... | if drug == "Aspirin":
webbrowser.open("https://www.amavita.ch/de/aspirin-s-tabl-500-mg-20-stk.html")
elif drug == "Ibuprofen":
webbrowser.open("https://www.amavita.ch/de/amavita-ibuprofen-filmtabl-400-mg-10-stk.html")
elif drug == "Eye drops":
webbrowser.open("https://www.amavita.ch... | identifier_body |
Website_Version.py | run the Website_Server.py file to get to the website.
# Imported modules
from datetime import datetime
from pyzbar import pyzbar
import webbrowser
import cv2
# Item scanner:
# This function scans the QR- or barcode and writes its contents into a file.
def read_barcodes(frame):
barcodes = pyzba... | (drug_inventory):
for drug in drug_inventory:
drug.purchase_date = datetime.strptime(drug.purchase_date, "%Y-%m-%d %H:%M:%S")
drug.expiry_date = datetime.strptime(drug.expiry_date, "%Y-%m-%d %H:%M:%S")
return drug_inventory
# Redirection to pharmacy website:
# This function redirects t... | transform_dates | identifier_name |
utils.py | spiral_matrix = np.zeros([N, N], dtype=np.int)
spiral_line_tril = np.zeros(int(N * (N + 1) / 2), dtype=np.int)
last_num = 0
ln = 0
for n in range(N):
if (n % 2) == 0:
# assigns the inverted rows
val_n = N - int(n / 2)
spiral_matrix[N - 1 - int(n / 2), :N - in... | print(f'Runtime: {t1 - t0}')
return ret
| random_line_split | |
utils.py | np.concatenate([d1[k], d2[k]], axis=0) for k in d1}
def dict_tf2numpy(self):
'''
Transform a dictionary of list of tensor into a dict or list of numpy objects.
The single objects transformations happens through .numpy method.
:param self: Any dict or list of objects with a .numpy method
:type sel... |
return ret
class indexes_librarian:
'''
A single class that collects different set of indexes, useful to gather ndarrays.
'''
def __init__(self, N):
self.spiral_diag, self.spiral_udiag, self.spiral_tril, self.spiral_matrix, self.spiral_line = spiral_indexes(N)
self.diag = np.diag... | print(x)
ret[np.isnan(ret)] = 0.0 | conditional_block |
utils.py | .concatenate([d1[k], d2[k]], axis=0) for k in d1}
def dict_tf2numpy(self):
'''
Transform a dictionary of list of tensor into a dict or list of numpy objects.
The single objects transformations happens through .numpy method.
:param self: Any dict or list of objects with a .numpy method
:type self: ... | :
'''
A single class that collects different set of indexes, useful to gather ndarrays.
'''
def __init__(self, N):
self.spiral_diag, self.spiral_udiag, self.spiral_tril, self.spiral_matrix, self.spiral_line = spiral_indexes(N)
self.diag = np.diag_indices(N)
self.udiag = np.tril_... | indexes_librarian | identifier_name |
utils.py | np.concatenate([d1[k], d2[k]], axis=0) for k in d1}
def dict_tf2numpy(self):
'''
Transform a dictionary of list of tensor into a dict or list of numpy objects.
The single objects transformations happens through .numpy method.
:param self: Any dict or list of objects with a .numpy method
:type sel... |
def spiral_indexes(N):
'''
return the indexes of a line vector that corresponds to the elements of a triangular matrix.
spiral means that the elements in the matrix are inserted using a spiral sequence (as tensorflow.fill_triangular does).
'''
spiral_matrix = np.zeros([N, N], dtype=np.int)
sp... | '''
generates T x N data, with par_p VAR structure, cov_wn noise covariance and a vector of constant terms cont_terms.
'''
p = int(par_p.shape[0] / N)
eps = np.random.multivariate_normal(np.zeros(N), cov_wn, size=T)
y = np.zeros([T, N])
last_y = np.zeros([p, N])
ylag = np.zeros([T, N * ... | identifier_body |
main.py | tns_fmt=tns_fmt)
elif task == 'smile':
dataset = TensorPredictionData(tensor_data_dir, goal_data_dir,
pred_smile=True, tns_fmt=tns_fmt)
elif task == 'race':
dataset = TensorPredictionData(tensor_data_dir, goal_data_dir,
... |
def save_images(input_imgs, output_imgs, epoch, path, img_nums, offset=0, batch_size=64):
"""
"""
input_prefix = "inp_"
output_prefix = "out_"
out_folder = "{}/{}".format(path, epoch)
out_folder = os.path.abspath(out_folder)
if not os.path.isdir(out_folder):
os.makedirs(o... | """
data is normalized with mu and sigma, this function puts it back
"""
if dataset == "cifar10":
c_std = [0.247, 0.243, 0.261]
c_mean = [0.4914, 0.4822, 0.4466]
elif dataset == "imagenet":
c_std = [0.229, 0.224, 0.225]
c_mean = [0.485, 0.456, 0.406]
for i in... | identifier_body |
main.py | tns_fmt=tns_fmt)
elif task == 'smile':
dataset = TensorPredictionData(tensor_data_dir, goal_data_dir,
pred_smile=True, tns_fmt=tns_fmt)
elif task == 'race':
dataset = TensorPredictionData(tensor_data_dir, goal_data_dir,
... | (path):
if not os.path.isdir(path):
os.makedirs(path)
for file_ in glob(r'./*.py'):
copy2(file_, path)
copytree("clients/", path + "clients/")
def main(architecture, task, goal_data_dir, tensor_data_dir, img_fmt, tns_fmt,
loss_fn, train_split, batch_size, num_epochs, trai... | copy_source_code | identifier_name |
main.py | 229, 0.224, 0.225]
c_mean = [0.485, 0.456, 0.406]
for i in [0, 1, 2]:
img[i] = img[i] * c_std[i] + c_mean[i]
return img
def save_images(input_imgs, output_imgs, epoch, path, img_nums, offset=0, batch_size=64):
"""
"""
input_prefix = "inp_"
output_prefix = "out_"
o... | parser.add_argument('--batch_size', type=int, default=32, help='size of each image batch')
# parser.add_argument('--optimizer_pick', type=str, default="Adam", help='choose optimizer between Adam and SGD')
| random_line_split | |
main.py | tns_fmt=tns_fmt)
elif task == 'smile':
dataset = TensorPredictionData(tensor_data_dir, goal_data_dir,
pred_smile=True, tns_fmt=tns_fmt)
elif task == 'race':
dataset = TensorPredictionData(tensor_data_dir, goal_data_dir,
... |
dataset_size = len(dataset)
indices = list(range(dataset_size))
split = int(np.floor(train_split * dataset_size))
np.random.seed(random_seed)
np.random.shuffle(indices)
train_indices, test_indices = indices[:split], indices[split:]
train_sampler = SubsetRandomSampler(train_indices)
... | trainTransform = transforms.Compose([transforms.ToTensor(),])
dataset = ImageTensorFolder(img_path=goal_data_dir, tensor_path=tensor_data_dir,
img_fmt=img_fmt, tns_fmt=tns_fmt, transform=trainTransform) | conditional_block |
rsa-fdh-vrf.rs | // STEP 1 and 2
let hash_string = SUITE_STRING.concat(&TWO.concat(pi_string));
// STEP 3
ByteSeqResult::Ok(sha256(&hash_string).slice(0,32))
}
// Based on section 4.3 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn verify(pk: PK, alpha: &ByteSeq, pi_string: &ByteSeq) -> ByteSeqResult {... | }
// Based on section 4.2 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn proof_to_hash(pi_string: &ByteSeq) -> ByteSeqResult { | random_line_split | |
rsa-fdh-vrf.rs | (sk: SK, alpha: &ByteSeq) -> ByteSeqResult {
let (n, _d) = sk.clone();
// STEP 1 and 2
let em = vrf_mgf1(n, alpha)?;
// STEP 3
let m = os2ip(&em);
// STEP 4
let s = rsasp1(sk, m)?;
// STEP 5 and 6
i2osp(s, BYTE_SIZE)
}
// Based on section 4.2 of https://datatracker.ietf.org/doc/... | prove | identifier_name | |
rsa-fdh-vrf.rs |
// Based on section 4.3 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn verify(pk: PK, alpha: &ByteSeq, pi_string: &ByteSeq) -> ByteSeqResult {
let (n, _e) = pk.clone();
// STEP 1
let s = os2ip(pi_string);
// STEP 2
let m = rsavp1(pk, s)?;
// STEP 3 and 4
let em_prime = ... | {
// STEP 1 and 2
let hash_string = SUITE_STRING.concat(&TWO.concat(pi_string));
// STEP 3
ByteSeqResult::Ok(sha256(&hash_string).slice(0,32))
} | identifier_body | |
rsa-fdh-vrf.rs | else {
ByteSeqResult::Err(Error::VerificationFailed)
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_bigint::{BigInt,Sign};
use glass_pumpkin::prime;
use quickcheck::*;
// RSA key generation
// Taken from https://asecuritysite.com/rust/rsa01/
fn modinv(a0: BigInt, m0: Big... | {
proof_to_hash(pi_string)
} | conditional_block | |
sgt.py | ):
var(r^{*}_T) ≈ (r + 1)^2 (N_{r+1}/N_r^2) (1 + N_{r+1}/N_r)
"""
N = self.N
return (r + 1)**2 * (N[r+1] / N[r]**2) * (1 + N[r+1] / N[r])
def linear_rstar_unnorm(self, r):
"""
Linear Good-Turing estimate of r* for given r:
log(N_r) = a + b log(r)
... | elf):
with self.assertRaises(AssertionError):
estimator = Estimator(N=self.input)
class ChinesePluralsTest(unittest.TestCase):
max_r = 1918
maxDiff = None
input = collections.defaultdict(lambda:0)
input.update([
(1, 268),
(2, 112),
(3, 70),
(4, 41),
... | st_failure(s | identifier_name |
sgt.py | ):
var(r^{*}_T) ≈ (r + 1)^2 (N_{r+1}/N_r^2) (1 + N_{r+1}/N_r)
"""
N = self.N
return (r + 1)**2 * (N[r+1] / N[r]**2) * (1 + N[r+1] / N[r])
def linear_rstar_unnorm(self, r):
"""
Linear Good-Turing estimate of r* for given r:
log(N_r) = a + b log(r)
... | if places is None:
# Six significant figures
places = 5 - int(floor(log(abs(right)) / log(10)))
unittest.TestCase.assertAlmostEqual(
self, left, right, msg=msg, places=places)
def test_unnorm_output(self):
estimator = Estimator(N=self.input)
keys = s... | g = msg + (" (%r ≠ %r)" % (left, right))
| conditional_block |
sgt.py |
def _find_cutoff(self):
"""
Find first r value s.t. the linear and turing estimates of r* are not
significantly different.
"""
cutoff = 1
while ((self.linear_rstar_unnorm(cutoff) -
self.turing_rstar_unnorm(cutoff))**2
> self.approx_tu... | """
Perform linear regression on the given points in loglog space, return
result
"""
# Make a set of the nonempty points in log scale
x, y = zip(*[(log(r), log(Z[r]))
for r in range(1, self.max_r + 1) if Z[r]])
self.x, self.y = x, y
... | identifier_body | |
sgt.py | Compute the approximate variance of the turing estimate for r* given r,
using the approximation given in (Gale):
var(r^{*}_T) ≈ (r + 1)^2 (N_{r+1}/N_r^2) (1 + N_{r+1}/N_r)
"""
N = self.N
return (r + 1)**2 * (N[r+1] / N[r]**2) * (1 + N[r+1] / N[r])
def linear_rstar_u... | return cutoff
def approx_turing_variance(self, r):
""" | random_line_split | |
trab05.py | nção que constrói a matriz de co-ocorrências de intensidade diagonalmente conectadas
def diag_coocurrence_mat(image, b):
mat_size = 2 ** b #O tamanho da matriz é igual à quantidade de intensidades diferentes da imagem
mat = np.zeros((mat_size, mat_size), dtype=int)
#Essa será a lista de todas as co-ocorrên... | _ = np.histogram(image, bins=2 ** bits)
norm_hist = hist / np.sum(hist)
return norm_hist / np.linalg.norm(norm_hist)
#Fu | identifier_body | |
trab05.py | orrências de intensidade diagonalmente conectadas
def diag_coocurrence_mat(image, b):
mat_size = 2 ** b #O tamanho da matriz é igual à quantidade de intensidades diferentes da imagem
mat = np.zeros((mat_size, mat_size), dtype=int)
#Essa será a lista de todas as co-ocorrências diagonais da imagem
#Para ... | c * factors
) / c.size
) #c.size == N² == número de elementos da matriz de co-ocorrencias
#Correlation
#Para o cálculo vetorizado, computamos todos os valores separadamente para cada linha e coluna
#O resultado final será uma matriz, em que cada elemento (i, j) é o valor da correlaç... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.