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
parser.py
<=\"'#;" _ATTRIB_SPECIALS = "]\"'" class HsdParser: """Event based parser for the HSD format. Arguments: eventhandler: Object which should handle the HSD-events triggered during parsing. When not specified, HsdEventPrinter() is used. Examples: >>> from io import StringIO ...
(self, text): stripped = text.strip() if stripped: if self._has_child: self._error(SYNTAX_ERROR, (self._currline, self._currline)) self._eventhandler.add_text(stripped) self._has_text = True def _starttag(self, tagname, closeprev): txt = ...
_text
identifier_name
parser.py
<=\"'#;" _ATTRIB_SPECIALS = "]\"'" class HsdParser: """Event based parser for the HSD format. Arguments: eventhandler: Object which should handle the HSD-events triggered during parsing. When not specified, HsdEventPrinter() is used. Examples: >>> from io import StringIO ...
else: self._error(SYNTAX_ERROR, (self._currline, self._currline)) line = after def _text(self, text): stripped = text.strip() if stripped: if self._has_child: self._error(SYNTAX_ERROR, (self._currline, self._currline)) ...
txtinc = after.startswith("<<") hsdinc = after.startswith("<+") if txtinc: self._text("".join(self._buffer) + before) self._buffer = [] self._eventhandler.add_text(self._include_txt(after[2:])) break ...
conditional_block
parser.py
b { ... Scc = Yes ... Filling = Fermi { ... Temperature [Kelvin] = 100 ... } ... } ... } ... \"\"\") >>> parser.parse(hsdfile) >>> dictbuilder.hsddict {'Hamiltonian': {'Dftb': {'Scc': True, 'Filling':...
fname = common.unquote(fname.strip()) parser = HsdParser(eventhandler=self._eventhandler) parser.parse(fname)
identifier_body
parser.py
<=\"'#;" _ATTRIB_SPECIALS = "]\"'" class HsdParser: """Event based parser for the HSD format. Arguments: eventhandler: Object which should handle the HSD-events triggered during parsing. When not specified, HsdEventPrinter() is used. Examples: >>> from io import StringIO ...
def __init__(self, eventhandler: Optional[HsdEventHandler] = None): """Initializes the parser. Args: eventhandler: Instance of the HsdEventHandler class or its children. """ if eventhandler is None: self._eventhandler = HsdEventPrinter() else: ...
{'Temperature': 100, 'Temperature.attrib': 'Kelvin'}}}}} """
random_line_split
main.py
encoded state for the Forward Model and the encoded next state to train the forward model! optimizing the Inverse model by the loss between actual action taken by the current policy and the predicted action by the inverse model """ def __init__(self, action_size, enc_state_size, hidden_size=64): s...
# Intrinsic Curiosity Calculation state1_batch = torch.cat(state_batch)
random_line_split
main.py
.net = nn.Sequential(nn.Linear(input_shape, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, output_shape), n...
(state1, action, state2, forward_scale=1., inverse_scale=1e4): """ """ state1_hat = encoder(state1) state2_hat = encoder(state2) state2_hat_pred = forwardM(state1_hat.detach(), action.detach()) forward_pred_err = forward_scale * forward_loss(state2_hat_pred, state2_hat.detach()).sum(dim=1).unsqueeze(dim=1...
ICM
identifier_name
main.py
.net = nn.Sequential(nn.Linear(input_shape, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, output_shape), n...
ratio = torch.exp(new_logprobs - old_logprobs.detach()) surr = ratio * advantage_i clip = torch.clamp(ratio, 1.0 - eps_clip, 1.0 + eps_clip) a_loss = - (torch.min(surr, clip*advantage_i).mean()) + ENTROPY_BONUS * entropy #clip_grad_norm_(actor.parameters(),CLIP_GRAD) #a_loss.backwar...
for states_i, old_actions, old_logprobs, advantage_i, discounted_reward_i, cur_loss in ppo_iter(mini_batch_size, states, actions, log_probs, advantage, discounted_rewards, curiosity_loss): optimizer.zero_grad() #c_optimizer.zero_grad() #tran critic new_value = critic(states_i.to(device)) ...
conditional_block
main.py
.net = nn.Sequential(nn.Linear(input_shape, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, output_shape), n...
def ICM(state1, action, state2, forward_scale=1., inverse_scale=1e4): """ """ state1_hat = encoder(state1) state2_hat = encoder(state2) state2_hat_pred = forwardM(state1_hat.detach(), action.detach()) forward_pred_err = forward_scale * forward_loss(state2_hat_pred, state2_hat.detach()).sum(dim=1).unsqu...
""" Gets as inputs the aciton taken from the policy and the encoded state by the encoder in the inverse model. The froward model trys to predict the encoded next state. Returns the predicted encoded next state. Gets optimized by the MSE between the actual encoded next state and the predi...
identifier_body
TimeSlotGroup.js
izer' import { elementType, dateFormat } from './utils/propTypes' import EventSlot from './EventSlot'; import { DropTarget } from 'react-dnd'; import MasterListSlot from './MasterListSlot'; import moment from 'moment'; import Modal from '../../Modal/index'; import Button from "../../Button"; const squareTarget = { ...
const isViewTrainer = (freeTrainers && freeTrainers.idEvent === this.props.value.getTime()) ? true : false;//не OK если таместь freeTrainers const currentEvent = this.renderEvent(); let cellClass = cn('rbc-timeslot-group', flag && !isViewTrainer && !currentEvent ? 'rbc-timeslot-group-OK' : 'rbc-time...
const { connectDropTarget, hovered, item} = this.props; const backgroundColor= hovered ? '#e8f8fc ' : 'white'; const {intervals, value, freeTrainers, isAdmin} = this.props; let valuetM = value.getTime(); const flag = Array.isArray(intervals) ? intervals.some(el => { if(Array.isArray...
identifier_body
TimeSlotGroup.js
izer' import { elementType, dateFormat } from './utils/propTypes' import EventSlot from './EventSlot'; import { DropTarget } from 'react-dnd'; import MasterListSlot from './MasterListSlot'; import moment from 'moment'; import Modal from '../../Modal/index'; import Button from "../../Button"; const squareTarget = { ...
(props) { props.transferTraining(props.value); // drag and drop console.log('DROP props :', props); //moveKnight(props.x, props.y); }, // hover(props, monitor, component) { // // This is fired very often and lets you perform side effects // // in response to the hover. You can't handle enter an...
drop
identifier_name
TimeSlotGroup.js
izer' import { elementType, dateFormat } from './utils/propTypes' import EventSlot from './EventSlot'; import { DropTarget } from 'react-dnd'; import MasterListSlot from './MasterListSlot'; import moment from 'moment'; import Modal from '../../Modal/index'; import Button from "../../Button"; const squareTarget = { ...
return connectDropTarget( <div className={cellClass} style={{backgroundColor}} onClick={(e) => modalTransferEvent(value.getTime())}> {this.renderSlices()} {currentEvent} </div> ) } return ( <div className={cellClass} style={{backgroundColor}} onClick={(e...
if(flag && !isViewTrainer && !currentEvent){
random_line_split
semaphore.rs
[crate documentation](index.html) for usage. // This implementation encodes state (the available counter, acquire queue, and cancel queue) into // multiple atomic variables and linked lists. Concurrent acquires (and concurrent cancels) synchronize // by pushing onto a stack with an atomic swap. Releases synchronize wi...
} } } } /// Like [acquire](#method.acquire), but takes an [`Arc`] `<Semaphore>` and returns a guard that is `'static`, [`Send`] and [`Sync`]. /// # Examples /// ``` /// # use async_weighted_semaphore::{Semaphore, PoisonError, SemaphoreGuardArc}; /// # use st...
{ return Ok(SemaphoreGuard::new(self, amount)); }
conditional_block
semaphore.rs
[crate documentation](index.html) for usage. // This implementation encodes state (the available counter, acquire queue, and cancel queue) into // multiple atomic variables and linked lists. Concurrent acquires (and concurrent cancels) synchronize // by pushing onto a stack with an atomic swap. Releases synchronize wi...
(&self, amount: usize) -> Result<SemaphoreGuard, TryAcquireError> { let mut current = self.acquire.load(Acquire); loop { match current { Queued(_) => return Err(TryAcquireError::WouldBlock), Available(available) => { let available = availab...
try_acquire
identifier_name
semaphore.rs
[crate documentation](index.html) for usage. // This implementation encodes state (the available counter, acquire queue, and cancel queue) into // multiple atomic variables and linked lists. Concurrent acquires (and concurrent cancels) synchronize // by pushing onto a stack with an atomic swap. Releases synchronize wi...
} impl Semaphore { /// The maximum number of permits that can be made available. This is slightly smaller than /// [`usize::MAX`]. If the number of available permits exceeds this number, it may poison the /// semaphore. /// # Examples /// ``` /// # use async_weighted_semaphore::{Semaphore, Se...
{ match self.acquire.load(Relaxed) { Available(available) => write!(f, "Semaphore::Ready({:?})", available)?, Queued(_) => match self.release.load(Relaxed) { Unlocked(available) => write!(f, "Semaphore::Blocked({:?})", available)?, _ => write!(f, "Semaphor...
identifier_body
semaphore.rs
[crate documentation](index.html) for usage. // This implementation encodes state (the available counter, acquire queue, and cancel queue) into // multiple atomic variables and linked lists. Concurrent acquires (and concurrent cancels) synchronize // by pushing onto a stack with an atomic swap. Releases synchronize wi...
pub fn acquire_arc(self: &Arc<Self>, amount: usize) -> AcquireFutureArc { AcquireFutureArc { arc: self.clone(), inner: unsafe { mem::transmute::<AcquireFuture, AcquireFuture>(self.acquire(amount)) }, } } /// Like [try_acquire](#method.try_acquire), but takes an [`Ar...
/// ```
random_line_split
14.rs
on until the last row, flqrgnkx-127. // The output of a knot hash is traditionally represented by 32 hexadecimal digits; each of these digits correspond to 4 bits, for a total of 4 * 32 = 128 bits. To convert to bits, turn each hexadecimal digit to its equivalent binary value, high-bit first: 0 becomes 0000, 1 beco...
(size: u32, occupied: &Vec<Vec<bool>>) { for row in occupied.iter().take(size as usize) { println!("\n{}", row.iter().take(size as usize).map(|c| match c { &true => "#", &false => ".", }) .collect::<Vec<&str>>() .join(" ")); } } /* This algo...
print_small_grid
identifier_name
14.rs
how many squares are used? // Your puzzle input is jxqlasbh. #![feature(conservative_impl_trait)] #![feature(entry_and_modify)] // #![feature(nll)] extern crate advent2017; use advent2017::knot::{Knot}; use std::io::Cursor; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vac...
{ clusters.new_cluster(Loc(i, j)); }
conditional_block
14.rs
until the last row, flqrgnkx-127. // The output of a knot hash is traditionally represented by 32 hexadecimal digits; each of these digits correspond to 4 bits, for a total of 4 * 32 = 128 bits. To convert to bits, turn each hexadecimal digit to its equivalent binary value, high-bit first: 0 becomes 0000, 1 becomes...
fn bitcount_hash(hash: &str) -> u32 { let mut bitsum = 0; for j in 0..32 { let slice = &hash[j..j+1]; let num = u32::from_str_radix(slice, 16).unwrap(); bitsum += num.count_ones(); } bitsum } fn count_hash_seed(s: &str) -> u32 { let mut bitsum = 0; for ha...
{ (0..128) .map(|i| format!("{}-{}", seed, i)) .map(|plaintext| { let mut knot = Knot::new(); knot.hash(Cursor::new(plaintext)) }) .collect() }
identifier_body
14.rs
on until the last row, flqrgnkx-127. // The output of a knot hash is traditionally represented by 32 hexadecimal digits; each of these digits correspond to 4 bits, for a total of 4 * 32 = 128 bits. To convert to bits, turn each hexadecimal digit to its equivalent binary value, high-bit first: 0 becomes 0000, 1 beco...
} fn new_cluster(&mut self, loc: Loc) { let id = self.next_id; self.next_id += 1; self.add_to_cluster(loc, id); } fn add_to_cluster(&mut self, loc: Loc, id: ClusterId) { self.add_grid(&loc, id); match self.index.entry(id) { Occupied(mut e) => ...
random_line_split
tsne2.js
= zeros(N * N); // allocate contiguous array for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { const d = computeVectorDistance(X[i], X[j]); dist[(i * N) + j] = d; dist[(j * N) + i] = d; } } return dist; } // helper function function sign(x) { if (x > 0) { return 1; } if (x < 0) { ...
t solution getSolution() { return this.solution; }, // perform a single step of optimization to improve the embedding step() { this.iter += 1; const N = this.N; const cg = this.costAndGradient(this.solution); // evaluate gradient const cost = cg.cost; const grad = cg.grad; /
identifier_body
tsne2.js
; } // compute L2 distance between two vectors function computeVectorDistance(x1, x2) { const D = x1.length; let d = 0; for (let i = 0; i < D; i++) { const x1i = x1[i]; const x2i = x2[i]; d += (x1i - x2i) * (x1i - x2i); } return d; } // compute pairwise distance in all vectors in X function
(X) { const N = X.length; const dist = zeros(N * N); // allocate contiguous array for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { const d = computeVectorDistance(X[i], X[j]); dist[(i * N) + j] = d; dist[(j * N) + i] = d; } } return dist; } // helper function function sign(x) { if (x ...
pairwiseDistances
identifier_name
tsne2.js
// utilitity that creates contiguous vector of zeros of size n function zeros(n) { if (typeof (n) === 'undefined' || isNaN(n)) { return []; } if (typeof ArrayBuffer === 'undefined') { // lacking browser support const arr = new Array(n); for (let i = 0; i < n; i++) { arr[i] = 0; } return arr; } return new F...
const tsnejs = window.tsnejs || { REVISION: 'ALPHA' }; function assert(condition, message) { if (!condition) { throw message || 'Assertion failed'; } }
random_line_split
tsne2.js
} // utilitity that creates contiguous vector of zeros of size n function zeros(n) { if (typeof (n) === 'undefined' || isNaN(n)) { return []; } if (typeof ArrayBuffer === 'undefined') { // lacking browser support const arr = new Array(n); for (let i = 0; i < n; i++) { arr[i] = 0; } return arr; } return ne...
{ throw message || 'Assertion failed'; }
conditional_block
fiUnam.py
es un inode ya que estamos guardando el nombre del archivo en él y eso no pasa en los verdaderos inodes y obviamente tampoco estamos guardando permisos ni propietarios porque NO los tenemos """ offset_fname = 15 offset_fsize = 8 offset_fcluster = 5 offset_fcreated = 14 ...
def date_format(self,date): months={'01':'Jan','02':'Feb','03':'March','04':'Apr','05':'May', '06':'Jun','07':'Jul','08':'Aug','09':'Sept','10':'Oct','11':'Nov','12':'Dec'} a=date[0:4] m=months.get(date[4:6]) d=date[6:8] hh=date[8:10] mm=date[10:12] ...
= self.sb.size_cluster + self.sb.size_dentry*i.numdir self.fs_map[prtb:prtb + i.offset_fname] = bytes(self.dentry_notused).encode('utf-8')
conditional_block
fiUnam.py
: """ El superbloque para este sistema de archivos ocupa el primer cluster del mismo, es decir, ocupa 2048 """ f = open('fiunamfs.img','r+b') fs_map = mmap.mmap(f.fileno(),0,access=mmap.ACCESS_READ) # Información de superbloque name = fs_map[0:8].decode('utf-8') ...
SuperBlock
identifier_name
fiUnam.py
es un inode ya que estamos guardando el nombre del archivo en él y eso no pasa en los verdaderos inodes y obviamente tampoco estamos guardando permisos ni propietarios porque NO los tenemos """ offset_fname = 15 offset_fsize = 8 offset_fcluster = 5 offset_fcreated = 14 ...
def defrag(self): inodes=self.inodes() if(len(inodes)!=0): if inodes[0].finit_cluster != 5: self.cpint(inodes[0],5) self.over(inodes[0],5) inodes[0].finit_cluster=5 for j in range(0,len(inodes)-1): i_lastcluster...
s.path.isfile(fe): if len(fe)<15: if self.search(fe)!=None: print('Ya existe un archivo con el mismo nombre, renombrar') else: self.cp(fe) else: print("cpin: " + fe + ": file name too large") else: ...
identifier_body
fiUnam.py
numdir_cluster = int(fs_map[47:49].decode('utf-8')) # 04 total_cluster = int(fs_map[52:60].decode('utf-8')) # 00000720 size_dentry = 64 # size dir entry f.close() fs_map.close() class DIRENTRY : """ De hecho, estrictamente esta clase no es un i...
random_line_split
boilerplate.py
): self.__add(name, value, type='val') def _add_train_performance(self, name, value): self.__add(name, value, type='train') def add_performance(self, metric_name, train_value, val_value): self._add_train_performance(metric_name, train_value ) self._add_val_performance(metric_na...
class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += ...
current_win = self.__win_dict.get(metric_name, None) train_values = self.__metrics['train'][metric_name] val_values = self.__metrics['val'][metric_name] epochs = max(len(train_values), len(val_values)) values_for_plot = np.column_stack((np.array(train_values), np.array(val_values))) ...
identifier_body
boilerplate.py
self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def adjust_learning_rate_by_schedule(config, op...
batch_time.update(time.time() - end)
random_line_split
boilerplate.py
): self.__add(name, value, type='val') def _add_train_performance(self, name, value): self.__add(name, value, type='train') def add_performance(self, metric_name, train_value, val_value): self._add_train_performance(metric_name, train_value ) self._add_val_performance(metric_na...
logger.info('early_stop_counter: %d', self.__early_stop_counter) if (self.warm_up_epochs and self.__descrease_times == 0 and self.__warm_up and epoch >= self.warm_up_epochs - 1 ) or \ (self.__lr_changed <= epoch - self.patience and \ (self.__early_stop_counter is not No...
logger.info('Early stopping, regress for %d iterations', self.__early_stop_counter) to_break = True
conditional_block
boilerplate.py
): self.__add(name, value, type='val') def _add_train_performance(self, name, value): self.__add(name, value, type='train') def add_performance(self, metric_name, train_value, val_value): self._add_train_performance(metric_name, train_value ) self._add_val_performance(metric_na...
(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def adjust_learning_rate_by_sche...
__init__
identifier_name
hangman.py
= loadWords() def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' count = 0 # C...
lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' count = 0 #Count method takes a single agument, element whose count is to be found. Starting a 0 letters, ...
''' secretWord: string, the word the user is guessing
random_line_split
hangman.py
loadWords() def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' count = 0 # Cou...
return removeduplicate(lettersGuessed, alphabet2) #This will sshow what letters are available. #Alphabet2 becomes L2. So the letter starts off from the alphabet and as each letter is guessed, it is removed from #the list and then all the letters left are displayed. # Hint: You might consider usin...
L1Start = L1[:]# Have to make sure to make a copy of the first list, to be able to modify the second. for e in L1:#For an element, or letter in the first argument. if e in L1Start:#If the leter in LIStart is there, which also implies it is in the first argument L2.remove(e) #then the...
identifier_body
hangman.py
the lettersguessed that is in the secretWord. This will force the loop to start over until the amount of letters in the secretWord. if count == len(secretWord): #Once the loop is done. If the amount of counts equal the amount of letters in the secretWord return True #Then you return True because ...
print(("Oops! You've already guessed that letter: ") + getGuessedWord(secretWord, lettersGuessed)) print(('------------'))
conditional_block
hangman.py
(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r') # line: string line = ...
loadWords
identifier_name
mn-map.component.ts
() color:string; @Input() size:string; @Input() data:any; @Input() set geo_data(value){ if (value){ this.data = value; this.parent.redraw(); } } @Output() datachange = new EventEmitter<any>(); constructor(@Inject(forwardRef(() => MarkerLayer)) private parent:MarkerLayer){} addMark...
getLayer():Promise<L.Layer>{ return new Promise<L.Layer>((resolve, react) =>{ this.bms.setPaging(false).setActiveApp("spaces/"+this.mappingSpace+"/styles").getAll().then(s=>{ this.styles = s; for(let style of this.styles){ this.int_styles[style.slug] = style; } co...
super(); }
identifier_body
mn-map.component.ts
export abstract class LeafLayerBase implements LeafLayer{ abstract getLayer():L.Layer|Promise<L.Layer>; abstract isBase():boolean; protected name:string; getName():string{ return this.name; } addToMap(m, bls, dls){ let l = this.getLayer(); m.addLayer(l); if(this.isBase()) bls[this.get...
random_line_split
mn-map.component.ts
() color:string; @Input() size:string; @Input() data:any; @Input() set geo_data(value){ if (value){ this.data = value; this.parent.redraw(); } } @Output() datachange = new EventEmitter<any>(); constructor(@Inject(forwardRef(() => MarkerLayer)) private parent:MarkerLayer){} addMark...
{ return false; } addToMap(m, bls, dls){ this.getLayer().then(x=>{ m.addLayer(x); dls["CityOS"] = x; }); } } @Component({ selector: '[mn-map]', templateUrl: './mn-map.component.html', styleUrls: ['./mn-map.component.css'], }) export class MnMapComponent { private makeid() { ...
Base()
identifier_name
world.py
`-. `./ / |/_.'") print(" | |//") print(" |_ /") print(" |- |") print(" | =|") print(" | |")...
class TraderTile(MapTile): def __init__(self, x, y): self.trader = npc.Trader() super().__init__(x, y) def trade(self, buyer, seller): if buyer.name == "Trader": action = "sell" buyer_char = "Trader" else: action = "buy" buyer_c...
if self.enemy.is_alive(): dex_mod = decimal.Decimal(player.dex_stat / 100) dodge_chance = decimal.Decimal(random.random()) * dex_mod miss_chance = decimal.Decimal(random.random()) * dex_mod if miss_chance > 0.98: print("The {} missed!".format(self.enemy.n...
identifier_body
world.py
(self): print("\n v . ._, |_ .,") print(" `-._\\/ . \\ / |/_") print(" \\ _\\, y | \\//") print(" _\\_.___\\, \\/ -.\\||") print(" `7-,--.`._|| /...
intro_text
identifier_name
world.py
if self.enemy.is_alive(): print("\n ___________.___ ________ ___ ___ ___________._.") print(" \\_ _____/| | / _____/ / | \\ \\__ ___/| |") print(" | __) | |/ \\ ___ / ~ \\ | | | |") print(" | \\ | |\\ \\_\\ \\\\ ...
break
random_line_split
world.py
This is a very boring part of the forest. Fuck all happens here") class VictoryTile(MapTile): def modify_player(self, player): player.victory = True exit() def intro_text(self): print("\n .''.") print(" .''. *''*...
print("Here's whats available to buy:\n") self.trade(buyer=player, seller=self.trader)
conditional_block
types.rs
chain account by the `X-REQUEST-SENDER-ADDRESS` header value. /// * Could not find the compliance key of the onchain account found by the /// `X-REQUEST-SENDER-ADDRESS` header value. /// * The compliance key found from the onchain account by `X-REQUEST-SENDER-ADDRESS` is not a /// valid ED25519 publ...
: PaymentObject) -> Self { Self { object_type: ObjectType::PaymentCommand, payment, } } pub fn payment(&self) -> &PaymentObject { &self.payment } pub fn into_payment(self) -> PaymentObject { self.payment } } /// A `PaymentActorObject` repres...
ent
identifier_name
types.rs
} } #[derive(Deserialize, Serialize)] pub struct CommandRequestObject { #[serde(deserialize_with = "ObjectType::deserialize_request")] #[serde(rename = "_ObjectType")] object_type: ObjectType, #[serde(flatten)] command: Command, cid: Uuid, } impl CommandRequestObject { pub fn new(comm...
{ Err(D::Error::custom(format_args!("expected {:?}", variant))) }
conditional_block
types.rs
chain account by the `X-REQUEST-SENDER-ADDRESS` header value. /// * Could not find the compliance key of the onchain account found by the /// `X-REQUEST-SENDER-ADDRESS` header value. /// * The compliance key found from the onchain account by `X-REQUEST-SENDER-ADDRESS` is not a /// valid ED25519 publ...
b fn into_payment(self) -> PaymentObject { self.payment } } /// A `PaymentActorObject` represents a participant in a payment - either sender or receiver. It /// also includes the status of the actor, indicates missing information or willingness to settle /// or abort the payment, and the Know-Your-Customer...
&self.payment } pu
identifier_body
types.rs
payment - either sender or receiver. It /// also includes the status of the actor, indicates missing information or willingness to settle /// or abort the payment, and the Know-Your-Customer information of the customer involved in the /// payment. #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct P...
random_line_split
PhaseOne.js
position: "absolute", top: 0, left: 0, bottom: 0, right: 0, display: "flex", justifyContent: "center", alignItems: "center", backgroundColor: "rgba(0,0,0,0.5)", "& *": { color: "white", }, "&.front": { backgroundColor: "lightblue", "& *": { color: "black", }, },
}, biddingStatus: { border: "1px solid #aaa", padding: theme.spacing(1), backgroundColor: "#eee", }, coinImage: { width: "60px", cursor: "pointer", borderRadius: "100%", "&.selected": { border: "2px solid orange", boxShadow: "0 0 10px orange", }, }, coinStatusTable: { borderTop: `1px solid...
}, activePlayerName: { color: theme.palette.error.dark, fontWeight: "bold",
random_line_split
PhaseOne.js
position: "absolute", top: 0, left: 0, bottom: 0, right: 0, display: "flex", justifyContent: "center", alignItems: "center", backgroundColor: "rgba(0,0,0,0.5)", "& *": { color: "white", }, "&.front": { backgroundColor: "lightblue", "& *": { color: "black", }, }, }, activePlaye...
if ( gameState && activePlayer && gameState.players.find((player) => player.userId === activePlayer.userId) .bidding == null ) { passAudio.currentTime = 0; passAudio.play(); } const active = gameState?.players.find((player) => player.isTurn); const me = gameState?.players.find( (player...
{ coinAudio.currentTime = 0; coinAudio.play(); }
conditional_block
main.go
.*?)"`) func reformatObjectId(objectId string) string { fmt.Println("objectID passed in: ", objectId) var idStringBeginning = "ObjectId(" var idStringEnd = ")" id := ObjectIdRegEx.FindString(objectId) if id == "" { fmt.Println("Error in reformatObjectId") return "" } return idStringBeginning + id + idStr...
nonceSize := gcm.NonceSize() nonce, cipherText := encLastIdByteArray[:nonceSize], encLastIdByteArray[nonceSize:] decryptedLastId, err := gcm.Open(nil, []byte(nonce), []byte(cipherText), nil) if err != nil { fmt.Println("Error in gcm.Open: ", err) } fmt.Println("Ending decryptLastId()") return string(dec...
{ fmt.Println("Error in encryptLastId(): ", err) }
conditional_block
main.go
// Construct aggregation "pipeline" to return 1 random document from entire collection pipeline := []bson.D{bson.D{{"$sample", bson.D{{"size", 1}}}}} cursor, _ := s.col.Aggregate(context.Background(), pipeline) var result Message for cursor.Next(context.Background()) { cursorErr := cursor.Decode(&result) ...
stripPhotoPath
identifier_name
main.go
{{"$sample", bson.D{{"size", 1}}}}} cursor, _ := s.col.Aggregate(context.Background(), pipeline) var result Message for cursor.Next(context.Background()) { cursorErr := cursor.Decode(&result) if cursorErr != nil { log.Fatal("Error in random() cursor") } fmt.Println("Result: ", result) } if ...
{ splitString := strings.SplitAfter(path, "/photos/") return splitString[len(splitString)-1] }
identifier_body
main.go
"(.*?)"`) func reformatObjectId(objectId string) string { fmt.Println("objectID passed in: ", objectId) var idStringBeginning = "ObjectId(" var idStringEnd = ")" id := ObjectIdRegEx.FindString(objectId) if id == "" { fmt.Println("Error in reformatObjectId") return "" } return idStringBeginning + id + idS...
} sender := senderQ[0] if sender == "" { responseObject := createEmptyServerResponseWithError(SenderEmpty) return "", "", responseObject } startingIdQ := query["startAt"] var startingId string if len(startingIdQ) == 0 { startingId = "" } else { startingId = startingIdQ[0] } return sender, starting...
if len(senderQ) == 0 { responseObject := createEmptyServerResponseWithError(SenderEmpty) return "", "", responseObject
random_line_split
clientlib-promoengine.js
("/content/vmware/vmware-published-sites")>-1){i=i.replace("/content/vmware/vmware-published-sites/",""); c=i.split("/")[0] }else{if(h.indexOf("/content/vmware/vmware-preview-sites")>-1){i=h.replace("/content/vmware/vmware-preview-sites/",""); redirect_locale=i.split("/")[0] }else{if(h.indexOf("/content/vmware/vmware-p...
{s+='<div class="col-xs-1 col-md-1 col-sm-1 cntClk"><i class="fa fa-plus-square detail-toggle"></i></div>' }
conditional_block
clientlib-promoengine.js
||c===""){var i=d; if(i.indexOf("/content/vmware/vmware-preview-sites")>-1){i=i.replace("/content/vmware/vmware-preview-sites/",""); c=i.split("/")[0] }else{if(i.indexOf("/content/vmware/vmware-published-sites")>-1){i=i.replace("/content/vmware/vmware-published-sites/",""); c=i.split("/")[0] }else{if(h.indexOf("/conten...
if(!(y==="false")){var p=U=="true"?"_self":"_blank"; C+="<a "+G+' class="learn_more" href='+ac+" target="+p+'><img src="/content/dam/digitalmarketing/vmware/global-icons/play_icon.png" alt="Video Play Icon" /></a>' }else{var p=U=="true"?"_self":"_blank"; C+="<a "+G+' class="learn_more" href='+ac+" target="+p+'><img sr...
}else{var p=U=="true"?"_self":"_blank"; C+="<a "+G+' class="learn_more" href='+ac+" target="+p+'><img src="/content/dam/digitalmarketing/vmware/global-icons/dark-play-icon.png" alt="Video Play Icon" /></a>' }}else{if(aa==="fa fa-video-camera"){var C='<div class="thumb-img alt-background" id="'+x+'" style="background-i...
random_line_split
clientlib-promoengine.js
(b,e,f){function a(){var l=new Date(); var k=l.getTimezoneOffset(); k=(k/60)*-1; var j=l.getTime(); if(k!==0){return(j+(3600000*k)) }return j }var d=$('[name="resolvedPath"]').val(); var h=$('[name="pagePath"]').attr("content"); var g=[]; $("body").find(".hcontentcard.parbase").each(function(){var j=$(this).find("input...
hcontentCarddisplay
identifier_name
clientlib-promoengine.js
var d=$('[name="resolvedPath"]').val(); var h=$('[name="pagePath"]').attr("content"); var g=[]; $("body").find(".hcontentcard.parbase").each(function(){var j=$(this).find("input#promotionalContent").val(); var l=$(this).find("input#promoposition").val(); var k=$(this).find("input#IsMbox").val(); if(j==="true"&&l!=""&&l...
{var l=new Date(); var k=l.getTimezoneOffset(); k=(k/60)*-1; var j=l.getTime(); if(k!==0){return(j+(3600000*k)) }return j }
identifier_body
image_pyramid.py
_image,width,height): """Resizing the image @param input_image: The source image. @param width:Width of new image @param height:Height of new image @return The resized image """ #Resizing the image output_image=cv2.resize(input_image,None,fx=width,fy=heigh...
def get_transmission(self,img, atmosphere, *, size, omega, radius, epsilon): """Estimate transmission map of an image. @param img: The source image. @param atmosphere: The atmospheric light for the image. @param omega: Factor to preserve minor amounts of haze [1]. @param rad...
"""Estimate atmospheric light for an image. @param img: the source image. @param size: Patch size for calculating the dark channel. @param percent: Percentage of brightest pixels in the dark channel considered for the estimation. @return The estimated atmospheric light. "...
identifier_body
image_pyramid.py
,width,height): """Resizing the image @param input_image: The source image. @param width:Width of new image @param height:Height of new image @return The resized image """ #Resizing the image output_image=cv2.resize(input_image,None,fx=width,fy=height) ...
flat_img = img.reshape(m * n, 3) flat_dark = self.get_dark_channel(img, size=size).ravel() count = math.ceil(m * n * percent / 100) indices = np.argpartition(flat_dark, -count)[:-count] return np.amax(np.take(flat_img, indices, axis=0), axis=0) def get_transmission(self,img...
random_line_split
image_pyramid.py
_image,width,height): """Resizing the image @param input_image: The source image. @param width:Width of new image @param height:Height of new image @return The resized image """ #Resizing the image output_image=cv2.resize(input_image,None,fx=width,fy=heigh...
(self,img, atmosphere, *, size, omega, radius, epsilon): """Estimate transmission map of an image. @param img: The source image. @param atmosphere: The atmospheric light for the image. @param omega: Factor to preserve minor amounts of haze [1]. @param radius: (default: 40) Radius...
get_transmission
identifier_name
image_pyramid.py
_image,width,height): """Resizing the image @param input_image: The source image. @param width:Width of new image @param height:Height of new image @return The resized image """ #Resizing the image output_image=cv2.resize(input_image,None,fx=width,fy=heigh...
else: sys.stderr.write('Skipping %s, not RGB' % basename) continue #Extract haze from the scene and then save the image dehazed = self.get_scene_radiance(image) cv2.imwrite(os.path.join(resultdir, basename), dehazed...
print('Processing %s ...' % basename)
conditional_block
node.py
(i.e. immutable list) of `pge.Node` objects representing the nodes that have control edges to this node. """ raise NotImplementedError("This method should be implemented by " "subclasses.") @property def device(self): """ Returns: TensorFlow device placeme...
def clear_attrs(self): """ Remove any attributes that are attached to this node. """ self._attributes.clear() def _attr_names(self): return [a[0] for a in self._attributes] @Node.inputs.getter def inputs(self) -> Tuple[tensor.Tensor]: return tuple(self._inputs) def set_inputs(self...
return tuple([p[0] for p in self._attributes])
identifier_body
node.py
key: str) -> Any: """ Retrieve the value of an attribute by name. Args: key: Key under which the node's attribute is stored Returns: Current value of the attribute as an appropriate native Python type (NOT a `tf.AttrValue` protobuf) or None if no value was found. Raises: ...
to_node_def
identifier_name
node.py
raise ValueError("Tensor {} points to graph {}, but this node is in a " "different graph {}".format(t, t.graph, self.graph)) self._inputs = list(new_inputs) self._graph.increment_version_counter() # New edges added to graph def set_control_inputs(self, new_control_inputs: Iterable[...
return tf.DType(attr_value.type)
conditional_block
node.py
ValueError("Node {} has more than one attribute " "under key '{}'".format(self, key)) ret = matches[0] if isinstance(ret, tf.AttrValue): return _attr_value_to_python_type(ret) else: return ret def get_attr_keys(self) -> Tuple[str]: return tuple([p[0] for p in self....
else: raise ValueError("Don't know how to convert a {} to "
random_line_split
goto_definition.rs
Ref(n) => Some(AstPtr::new(n.syntax())), ast::Name(n) => Some(AstPtr::new(n.syntax())), ast::Literal(n) => Some(AstPtr::new(n.syntax())), _ => None, } } })?; let source_map = db.source_map(file_id); let expr_id = source_map.expr_for_node(p...
#[track_caller] fn check(fixture: &str, expect: Expect) { let (db, f) = TestDB::from_fixture(fixture).unwrap(); assert_eq!(f.markers().len(), 1, "Missing markers"); let mut got = match goto_definition(&db, f[0]).expect("No definition") { GotoDefinitionResult::Path(path) => ...
{ let (db, f) = TestDB::from_fixture(fixture).unwrap(); assert_eq!(f.markers().len(), 1, "Missing markers"); assert_eq!(goto_definition(&db, f[0]), None); }
identifier_body
goto_definition.rs
Ref(n) => Some(AstPtr::new(n.syntax())), ast::Name(n) => Some(AstPtr::new(n.syntax())), ast::Literal(n) => Some(AstPtr::new(n.syntax())), _ => None, } } })?; let source_map = db.source_map(file_id); let expr_id = source_map.expr_for_node(p...
full_range: with_header, }) }) .collect() } // Currently builtin names cannot "goto-definition". ResolveResult::Builtin(_) => return None, }; Some(GotoDefinitionResult::Targets(targets)) } fn goto_flake_input(...
{ withs .iter() .filter_map(|&with_expr| { // with expr; body // ^--^ focus // ^--------^ full let with_node = source_map .node_for_expr(with_expr) ...
conditional_block
goto_definition.rs
Ref(n) => Some(AstPtr::new(n.syntax())), ast::Name(n) => Some(AstPtr::new(n.syntax())), ast::Literal(n) => Some(AstPtr::new(n.syntax())), _ => None, } } })?; let source_map = db.source_map(file_id); let expr_id = source_map.expr_for_node(p...
(fixture: &str, expect: Expect) { let (db, f) = TestDB::from_fixture(fixture).unwrap(); assert_eq!(f.markers().len(), 1, "Missing markers"); let mut got = match goto_definition(&db, f[0]).expect("No definition") { GotoDefinitionResult::Path(path) => format!("file://{}", path.display(...
check
identifier_name
goto_definition.rs
::Ref(n) => Some(AstPtr::new(n.syntax())), ast::Name(n) => Some(AstPtr::new(n.syntax())), ast::Literal(n) => Some(AstPtr::new(n.syntax())), _ => None, } } })?; let source_map = db.source_map(file_id); let expr_id = source_map.expr_for_node...
expect!["<a> = a;"], ); check( "let a = $0a; in rec { inherit a; b = a; }", expect!["<a> = a;"], ); } #[test] fn left_and_right() { check("let a = 1; in $0a ", expect!["<a> = 1;"]); check("let a = 1; in a$0 ", expect!["<a> = 1;"]);...
expect!["inherit <a>;"], ); check( "let a = a; in rec { inherit $0a; b = a; }",
random_line_split
sink_test.go
, cancel := context.WithTimeout(ctx, time.Millisecond) defer cancel() if err := sink.Flush(timeoutCtx); !testutils.IsError( err, `context deadline exceeded`, ) { t.Fatalf(`expected "context deadline exceeded" error got: %+v`, err) } } go func() { p.successesCh <- m1 }() if err := sink.Flush(ctx); err !...
require.NoError(t, sink.EmitRow(ctx, barTopic, []byte(`kbar`), []byte(`v0`), zeroTS)) require.NoError(t, sink.EmitRow(ctx, fooTopic, []byte(`kfoo`), []byte(`v1`), zeroTS))
random_line_split
sink_test.go
func (p *asyncProducerMock) Close() error { close(p.inputCh) close(p.successesCh) close(p.errorsCh) return nil } // consumeAndSucceed consumes input messages and sends them to successes channel. // Returns function that must be called to stop this consumer // to clean up. The cleanup function must be called befor...
{ panic(`unimplemented`) }
identifier_body
sink_test.go
p *asyncProducerMock) acknowledge(n int, ch chan *sarama.ProducerMessage) { for n > 0 { var outstanding []*sarama.ProducerMessage p.mu.Lock() outstanding = append(outstanding, p.mu.outstanding...) p.mu.outstanding = p.mu.outstanding[:0] p.mu.Unlock() for _, m := range outstanding
n -= len(outstanding) } } // outstanding returns the number of un-acknowledged messages. func (p *asyncProducerMock) outstanding() int { p.mu.Lock() defer p.mu.Unlock() return len(p.mu.outstanding) } func topic(name string) tableDescriptorTopic { return tableDescriptorTopic{tabledesc.NewBuilder(&descpb.TableD...
{ ch <- m }
conditional_block
sink_test.go
p *asyncProducerMock) acknowledge(n int, ch chan *sarama.ProducerMessage) { for n > 0 { var outstanding []*sarama.ProducerMessage p.mu.Lock() outstanding = append(outstanding, p.mu.outstanding...) p.mu.outstanding = p.mu.outstanding[:0] p.mu.Unlock() for _, m := range outstanding { ch <- m } n -= l...
() int { p.mu.Lock() defer p.mu.Unlock() return len(p.mu.outstanding) } func topic(name string) tableDescriptorTopic { return tableDescriptorTopic{tabledesc.NewBuilder(&descpb.TableDescriptor{Name: name}).BuildImmutableTable()} } const memoryUnlimited int64 = math.MaxInt64 const noTopicPrefix = "" const defaultTo...
outstanding
identifier_name
amqp.rs
020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writ...
(&mut self, _signal: Event) -> ResultVec { //self.drain_fatal_errors()?; Ok(Vec::new()) } fn is_active(&self) -> bool { true } fn auto_ack(&self) -> bool { false } async fn terminate(&mut self) { if let Some(channel) = self.channel.as_ref() { i...
on_signal
identifier_name
amqp.rs
020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writ...
impl ConfigImpl for Config {} /// Amqp offramp connector pub(crate) struct Amqp { sink_url: TremorUrl, config: Config, postprocessors: Postprocessors, reply_channel: Sender<sink::Reply>, channel: Option<Channel>, error_rx: Receiver<()>, error_tx: Sender<()>, } impl fmt::Debug for Amqp { ...
} } }
random_line_split
amqp.rs
020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writ...
} #[async_trait::async_trait] impl Sink for Amqp { async fn on_event( &mut self, _input: &str, codec: &mut dyn Codec, _codec_map: &HashMap<String, Box<dyn Codec>>, event: Event, ) -> ResultVec { self.handle_channel().await?; let ingest_ns = event.ingest_...
{ while let Ok(()) = self.error_rx.try_recv() { self.channel = None; } if self.channel.is_none() { match self.config.channel().await.await { Ok(channel) => self.channel = Some(channel), Err(error) => return Err(error.into()), } ...
identifier_body
amqp.rs
020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writ...
Confirmation::Nack(err) => { if let Some(e) = err { error!( "[Sink::{}] failed to send message: {} {}", &self.sink_url, e.reply_code, e.reply_text ...
{ if event.transactional { let mut insight = insight_event.clone(); insight.cb = CbAction::Ack; // we hopefully enver wait more then u64 ... if we do we got // bigg...
conditional_block
mod.rs
) -> InputHandle { InputHandle { name: name.to_os_string(), inner: Box::new(inner), read_only: true, digest: Default::default(), origin, ever_read: false, did_unhandled_seek: false, } } pub fn name(&self) -> &O...
/// Open the "primary" input file, which in the context of TeX is the main /// input that it's given. When the build is being done using the /// filesystem and the input is a file on the filesystem, this function /// isn't necesssarily that important, but those conditions don't always /// hold. ...
OpenResult::NotAvailable }
identifier_body
mod.rs
Result, erroring if the item was not available. pub fn must_exist(self) -> Result<T> { match self { OpenResult::Ok(t) => Ok(t), OpenResult::Err(e) => Err(e), OpenResult::NotAvailable => { Err(io::Error::new(io::ErrorKind::NotFound, "not found").into()) ...
_ => {} } }
random_line_split
mod.rs
: &[u8]) -> io::Result<usize> { let n = self.inner.write(buf)?; self.digest.input(&buf[..n]); Ok(n) } fn flush(&mut self) -> io::Result<()> { self.inner.flush() } } // An Io provider is a source of handles. One wrinkle is that it's good to be // able to distinguish between ...
OpenResult::Err(e.into()) } }
conditional_block
mod.rs
) -> InputHandle { InputHandle { name: name.to_os_string(), inner: Box::new(inner), read_only: true, digest: Default::default(), origin, ever_read: false, did_unhandled_seek: false, } } pub fn name(&self) -> &O...
: 'static + Write>(name: &OsStr, inner: T) -> OutputHandle { OutputHandle { name: name.to_os_string(), inner: Box::new(inner), digest: digest::create(), } } pub fn name(&self) -> &OsStr { self.name.as_os_str() } /// Consumes the object and re...
w<T
identifier_name
backend_helper.go
-csi-driver/client/apis/xuanwu/v1" ) const ( ApiVersion = "v1" XuanWuApiVersion = "xuanwu.huawei.io/v1" KindSecret = "Secret" KindConfigMap = "ConfigMap" KindStorageBackendClaim = "StorageBackendClaim" YamlSeparator = "---" ) // BackendConfiguration backend c...
(claim xuanwuv1.StorageBackendClaim) *BackendShowWide { b.Namespace = claim.Namespace b.Name = claim.Name if claim.Status != nil { b.StorageType = claim.Status.StorageType b.Protocol = claim.Status.Protocol b.Status = string(claim.Status.Phase) } return b } // ToBackendShow convert BackendShowWide to Backen...
ShowWithClaimOption
identifier_name
backend_helper.go
"` NameSpace string `json:"namespace,omitempty" yaml:"namespace"` Storage string `json:"storage,omitempty" yaml:"storage"` VstoreName string `json:"vstoreName,omitempty" yaml:"vstoreName"` AccountName string ...
{ backends, err = LoadMultipleBackendFromConfigmap(jsonStr) }
conditional_block
backend_helper.go
by executing the oceanctl get backend -o wide type BackendShowWide struct { Namespace string `show:"NAMESPACE"` Name string `show:"NAME"` Protocol string `show:"PROTOCOL"` StorageType string `show:"STORAGETYPE"` Sn string `...
{ config := struct { Backends []*BackendConfiguration `json:"backends"` }{} if err := json.Unmarshal([]byte(jsonStr), &config); err != nil { return nil, err } return config.Backends, nil }
identifier_body
backend_helper.go
awei-csi-driver/client/apis/xuanwu/v1" ) const ( ApiVersion = "v1" XuanWuApiVersion = "xuanwu.huawei.io/v1" KindSecret = "Secret" KindConfigMap = "ConfigMap" KindStorageBackendClaim = "StorageBackendClaim" YamlSeparator = "---" ) // BackendConfiguration backe...
} // BackendShow the content echoed by executing the oceanctl get backend type BackendShow struct { Namespace string `show:"NAMESPACE"` Name string `show:"NAME"` Protocol string `show:"PROTOCOL"` StorageType string `show:"STORAGETYPE"` Sn string `show:"SN"` Status string `show:"STATUS"`...
Url string `show:"Url"` VendorName string `show:"VENDORNAME"` StorageBackendContentName string `show:"STORAGEBACKENDCONTENTNAME"`
random_line_split
drawing_support.py
:param Color color: Three or four byte RGBA color :param float transparency: Transparency """ return color[0], color[1], color[2], transparency def rotate_point(x: float, y: float, cx: float, cy: float, angle_degrees: float) -> List[float]: """ Rotate a point around a ce...
max_y = point.y
conditional_block
drawing_support.py
points = (r1_x, r1_y), (r2_x, r2_y), (r4_x, r4_y), (r3_x, r3_y) return points def get_four_byte_color(color: Color) -> RGBA: """ Given a RGB list, it will return RGBA. Given a RGBA list, it will return the same RGBA. :param Color color: Three or four byte tuple :returns: retu...
r2_y = start_y - normal_y * line_width / 2 r3_x = end_x + normal_x * line_width / 2 r3_y = end_y + normal_y * line_width / 2 r4_x = end_x - normal_x * line_width / 2 r4_y = end_y - normal_y * line_width / 2
random_line_split
drawing_support.py
_y = end_y + normal_y * line_width / 2 r4_x = end_x - normal_x * line_width / 2 r4_y = end_y - normal_y * line_width / 2 points = (r1_x, r1_y), (r2_x, r2_y), (r4_x, r4_y), (r3_x, r3_y) return points def get_four_byte_color(color: Color) -> RGBA: """ Given a RGB list, it will return RG...
def rotate_point(x: float, y: float, cx: float, cy: float, angle_degrees: float) -> List[float]: """ Rotate a point around a center. :param x: x value of the point you want to rotate :param y: y value of the point you want to rotate :param cx: x value of the center poi...
""" Given a RGB color, along with an alpha, returns a RGBA color tuple. :param Color color: Three or four byte RGBA color :param float transparency: Transparency """ return color[0], color[1], color[2], transparency
identifier_body
drawing_support.py
= end_y + normal_y * line_width / 2 r4_x = end_x - normal_x * line_width / 2 r4_y = end_y - normal_y * line_width / 2 points = (r1_x, r1_y), (r2_x, r2_y), (r4_x, r4_y), (r3_x, r3_y) return points def get_four_byte_color(color: Color) -> RGBA: """ Given a RGB list, it will return RGBA...
(image: Image, hit_box_detail: float = 4.5): """ Given an image, this returns points that make up a hit box around it. Attempts to trim out transparent pixels. :param Image image: Image get hit box from. :param int hit_box_detail: How detailed to make the hit box. There's a ...
calculate_hit_box_points_detailed
identifier_name
groupspec.pb.go
func init() { proto.RegisterFile("akash/deployment/v1beta2/groupspec.proto", fileDescriptor_8afb9070f2e843b2) } var fileDescriptor_8afb9070f2e843b2 = []byte{ // 351 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0xbf, 0x4e, 0xc3, 0x30, 0x10, 0xc6, 0...
{ proto.RegisterType((*GroupSpec)(nil), "akash.deployment.v1beta2.GroupSpec") }
identifier_body
groupspec.pb.go
0xed, 0x29, 0x8d, 0xa3, 0x3e, 0xce, 0x23, 0xec, 0x15, 0x49, 0xfd, 0x5d, 0x3b, 0xe5, 0xf0, 0x9a, 0x0e, 0x39, 0xe4, 0x02, 0xc2, 0x68, 0x74, 0x55, 0xab, 0xed, 0xdc, 0x90, 0x72, 0x9d, 0x7c, 0xbc, 0x7a, 0x11, 0xf2, 0x18, 0xd1, 0xa0, 0xa0, 0xbc, 0x9d, 0x02, 0xb7, 0x37, 0xcf, 0x90, 0xb2, 0xce, 0xd0, 0x5e, 0x9b, 0x4d, 0x86...
return ErrInvalidLengthGroupspec } if postIndex > l { return io.ErrUnexpectedEOF
random_line_split
groupspec.pb.go
1, 0x94, 0x56, 0x4d, 0xea, 0x60, 0x3b, 0x15, 0xe5, 0x09, 0x18, 0x79, 0x84, 0x6e, 0xbc, 0x4a, 0xc7, 0x8e, 0x4c, 0x11, 0x6a, 0x17, 0xd4, 0xb1, 0x4f, 0x80, 0xf2, 0x8f, 0xb6, 0x43, 0x37, 0xdf, 0xf9, 0x77, 0xf7, 0xdd, 0x7d, 0xa7, 0x59, 0x74, 0x44, 0xc5, 0xc0, 0x7e, 0x81, 0x24, 0x62, 0xd3, 0x18, 0xc6, 0xd2, 0x9e, 0xdc, 0...
{ i -= len(m.Name) copy(dAtA[i:], m.Name) i = encodeVarintGroupspec(dAtA, i, uint64(len(m.Name))) i-- dAtA[i] = 0xa }
conditional_block
groupspec.pb.go
() { proto.RegisterFile("akash/deployment/v1beta2/groupspec.proto", fileDescriptor_8afb9070f2e843b2) } var fileDescriptor_8afb9070f2e843b2 = []byte{ // 351 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0xbf, 0x4e, 0xc3, 0x30, 0x10, 0xc6, 0x93, 0x16, ...
init
identifier_name
main.go
Attributes.Defense } func (u Unit) Strength() int { return u.Crunch().currentAttributes.Strength } func (u Unit) Accuracy() int { return u.Crunch().currentAttributes.Accuracy } func (u Unit) Vitality() int { return u.Crunch().currentAttributes.Vitality } func (u Unit) Willpower() int { return u.Crunch().current...
type order struct { Name string Speed int } func getPlayOrder(units []Unit) []string { var orders []order for _, u := range units { orders = append(orders, order{u.Name, u.Speed()}) } return handleOrders(orders) } func handleOrders(orders []order) []string { ordered := []string{} for { if allAcco...
{ teams := make(map[int]bool) for _, cbt := range cbts { if cbt.Hp > 0 { teams[cbt.Team] = true } } if len(teams) < 2 { return true } return false }
identifier_body
main.go
(i int) Unit { u.combatAttrMods.Accuracy += i return u } func (u Unit) ModVitality(i int) Unit { u.combatAttrMods.Vitality += i return u } func (u Unit) ModSpeed(i int) Unit { u.combatAttrMods.Speed += i return u } func (u Unit) ModWillpower(i int) Unit { u.combatAttrMods.Willpower += i return u } func (u Unit)...
ModAccuracy
identifier_name
main.go
runch().currentAttributes.Strength } func (u Unit) Accuracy() int { return u.Crunch().currentAttributes.Accuracy } func (u Unit) Vitality() int { return u.Crunch().currentAttributes.Vitality } func (u Unit) Willpower() int { return u.Crunch().currentAttributes.Willpower } func (u Unit) Resistance() int { return...
{ switch result.Attr { case "strength": unit = unit.ModStrength(result.Damange) case "defense": unit = unit.ModDefense(result.Damange) case "speed": unit = unit.ModSpeed(result.Damange) case "accuracy": unit = unit.ModAccuracy(result.Damange) case "fatigue": u...
conditional_block
main.go
return player } func CreateUnit(name string, attrs Attributes) Unit { unit := Unit{ Name: name, BaseAttributes: attrs, Attacks: []Attack{getAttacks()[0]}, } unit = unit.Crunch() unit.Hp = unit.BaseStats.MaxHp return unit } func readAttr(msg string) string { raw := read(msg) if !c...
} }
random_line_split
execution.rs
/// # Note /// /// - This is the key where storage allocation, pushing and pulling is rooted /// using the `SpreadLayout` and `SpreadAllocate` traits primarily. /// - This trait is automatically implemented by the ink! codegen. /// - The existence of this trait allows to customize the root key in future /// version...
} /// Trait used to convert return types of contract initializer routines. /// /// Only `()` and `Result<(), E>` are allowed contract initializer return types. /// For `WrapReturnType<C>` where `C` is the contract type the trait converts /// `()` into `C` and `Result<(), E>` into `Result<C, E>`. pub trait Initializer...
{ &self.0 }
identifier_body
execution.rs
allible or is fallible but succeeded. // // This requires us to sync back the changes of the contract storage. let root_key = <Contract as ContractRootKey>::ROOT_KEY; push_spread_root::<Contract>(contract, &root_key); if config.dynamic_storage_alloc { ...
{ alloc::finalize(); }
conditional_block
execution.rs
/// # Note /// /// - This is the key where storage allocation, pushing and pulling is rooted /// using the `SpreadLayout` and `SpreadAllocate` traits primarily. /// - This trait is automatically implemented by the ink! codegen. /// - The existence of this trait allows to customize the root key in future /// version...
<Contract, F, R>( initializer: F, ) -> <R as InitializerReturnType<Contract>>::Wrapped where Contract: ContractRootKey + SpreadAllocate, F: FnOnce(&mut Contract) -> R, R: InitializerReturnType<Contract>, { let mut key_ptr = KeyPtr::from(<Contract as ContractRootKey>::ROOT_KEY); let mut instance ...
initialize_contract
identifier_name
execution.rs
/// /// # Note /// /// - This is the key where storage allocation, pushing and pulling is rooted /// using the `SpreadLayout` and `SpreadAllocate` traits primarily. /// - This trait is automatically implemented by the ink! codegen. /// - The existence of this trait allows to customize the root key in future /// ver...
/// where `E` is some unspecified error type. /// If the contract initializer returns `Result::Err` the utility /// method that is used to initialize an ink! smart contract will /// revert the state of the contract instantiation. pub trait ConstructorReturnType<C>: private::Sealed { /// Is `true` if `Self` is `Resu...
random_line_split