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
graph.rs
/// Returns the end node. pub fn get_end_node(&self) -> Index { self.end_node } /// Resets the frame graph by removing all nodes and sets up a new end node. pub fn reset(&mut self) { let mut nodes = self.node_arena.write(); let end_node_impl = nodes.get(self.end_node).unwrap().node.clone(); n...
{ buffers.push(buffer); }
conditional_block
signature_format.py
_48000 = 6 class FrequencyBand(IntEnum): # Enum keys are frequency ranges in Hz _0_250 = -1 # Nothing above 250 Hz is actually stored _250_520 = 0 _520_1450 = 1 _1450_3500 = 2 _3500_5500 = 3 # This one (3.5 KHz - 5.5 KHz) should not be used in legacy mode class RawSignatureHeader(Little...
"_seconds": frequency_peak.get_seconds() } for frequency_peak in frequency_peaks ] for frequency_band, frequency_peaks in sorted(self.frequency_band_to_sound_peaks.items()) } } def encode_to_bina...
"fft_pass_number": frequency_peak.fft_pass_number, "peak_magnitude": frequency_peak.peak_magnitude, "corrected_peak_frequency_bin": frequency_peak.corrected_peak_frequency_bin, "_frequency_hz": frequency_peak.get_frequency_h...
random_line_split
signature_format.py
48000 = 6 class FrequencyBand(IntEnum): # Enum keys are frequency ranges in Hz _0_250 = -1 # Nothing above 250 Hz is actually stored _250_520 = 0 _520_1450 = 1 _1450_3500 = 2 _3500_5500 = 3 # This one (3.5 KHz - 5.5 KHz) should not be used in legacy mode class RawSignatureHeader(LittleEn...
self.number_samples = int(header.number_samples_plus_divided_sample_rate - self.sample_rate_hz * 0.24) # Read the type-length-value sequence that follows the header # The first chunk is fixed and has no value, but instead just repeats # the length of the message size mi...
self = cls() buf = BytesIO(data) buf.seek(8) checksummable_data = buf.read() buf.seek(0) # Read and check the header header = RawSignatureHeader() buf.readinto(header) assert header.magic1 == 0xcafe2580 assert h...
identifier_body
signature_format.py
48000 = 6 class FrequencyBand(IntEnum): # Enum keys are frequency ranges in Hz _0_250 = -1 # Nothing above 250 Hz is actually stored _250_520 = 0 _520_1450 = 1 _1450_3500 = 2 _3500_5500 = 3 # This one (3.5 KHz - 5.5 KHz) should not be used in legacy mode class RawSignatureHeader(LittleEn...
(self) -> float: return (self.fft_pass_number * 128) / self.sample_rate_hz # ^ Assume that new FFT bins are emitted every 128 samples, on a # standard 16 KHz sample rate basis. class DecodedMessage: sample_rate_hz : int = None number_samples : in...
get_seconds
identifier_name
signature_format.py
1 _1450_3500 = 2 _3500_5500 = 3 # This one (3.5 KHz - 5.5 KHz) should not be used in legacy mode class RawSignatureHeader(LittleEndianStructure): _pack = True _fields_ = [ ('magic1', c_uint32), # Fixed 0xcafe2580 - 80 25 fe ca ('crc32', c_uint32), # CRC-32 for all of the ...
peaks_buf = BytesIO() fft_pass_number = 0 # NOTE: Correctly filtering and sorting the peaks within the members # of "self.frequency_band_to_sound_peaks" is the responsability of the # caller for frequency_peak...
conditional_block
mp3.py
None, 'deselected_color': background} def __init__(self, **kwargs): global RootApp super(Mp3PiAppLayout, self).__init__(**kwargs) RootApp = self self.ids['search_results_list'].adapter.bind(on_selection_change=self.change_selection) self.ids.volume_slider.value = Alsa.get_mixe...
def infinite_loop(self, url): iteration = 0 self.proc = subprocess.Popen(["mpg123","-o", "alsa", "-@", url], stderr=subprocess.PIPE, bufsize = 0) line = [] while True: if self.stop.is_set(): Logger.info("Player: stopping thread") self.stop.clear() return ...
Logger.info("Player: already playing")
conditional_block
mp3.py
== True: # stop playing if self.proc is not None: if self.mythread.isAlive(): print("set stop") self.stop.set() #self.proc.kill() ?? Logger.info("mpg123: killing %s" % self.proc.pid) os.kill(self.proc.pid, SIGTERM) self.proc = None self.isPlayi...
# if net['ssid'] is Network.ssid: # self.ids['wlan_list'].text = net[Network.ssid] # self.ids['wlan_list'].values = networklist
random_line_split
mp3.py
: stopping thread") self.stop.clear() return while (select.select([self.proc.stderr], [], [], 0)[0]): # check if mpg123 is died #print(self.proc.returncode) #print(self.proc.pid) if self.proc.returncode is not None: print("died") return ...
global RootApp #print(Mp3PiAppClass) def do_GET(self): if self.path == "/": self.page = markup.page() self.page.init(title="Title") self.page.table(border="true") firstline = True for row in RootApp.search_results.adapter.data: if firstline is True: ...
identifier_body
mp3.py
None, 'deselected_color': background} def __init__(self, **kwargs): global RootApp super(Mp3PiAppLayout, self).__init__(**kwargs) RootApp = self self.ids['search_results_list'].adapter.bind(on_selection_change=self.change_selection) self.ids.volume_slider.value = Alsa.get_mixe...
(self): global ConfigObject connection = NMCLI.current_connection() while True: if self.statusthread_stop.is_set(): self.statusthread_stop.clear() return if not int(time.time()) % 5: connection = NMCLI.current_connection() ip = NMCLI.get_ip() ...
status_thread
identifier_name
base.py
ElementSymbolError(MalformedError): def __init__(self, malformed_element_symbol): self.malformed_element_symbol = malformed_element_symbol def __str__(self): return ('Expecting an atomic symbol (e.g. Fe) - supplied {0}').format( self.malformed_element_symbol) class MalformedQuant...
(nu, T): """ Calculate the intensity of a black-body according to the following formula .. math:: I(\\nu, T) = \\frac{2h\\nu^3}{c^2}\frac{1} {e^{h\\nu \\beta_\\textrm{rad}} - 1} Parameters ---------- nu : float Frequency of light T : float Temperature in kel...
intensity_black_body
identifier_name
base.py
str File name for the synpp yaml shell_no : int, optional(default = 0) Number of shells lines_db : file, optional(default = None) Raises ------ ValueError If the current dataset does not contain necessary reference files """ logger.warning('Currently only works wit...
raise ValueError('Both start and stop need to be quantities with a ' 'unit attribute')
random_line_split
base.py
light """ #BAD STYLE change to parse quantity distance = u.Unit(distance) wavelength, flux = np.loadtxt(spec_fname, usecols=(wavelength_column, flux_column), unpack=True) flux_density = np.trapz(flux, wavelength) * (flux_unit * wavelength_unit) luminosity = (flux_density * 4 * np.pi * distanc...
""" Reformat the string so the first letter is uppercase and all subsequent letters lowercase. Parameters ---------- element_string : str Inputted element symbol Returns ------- str Returned reformatted element symbol """ return element_string[0].upper() + ele...
identifier_body
base.py
formedElementSymbolError(MalformedError): def __init__(self, malformed_element_symbol): self.malformed_element_symbol = malformed_element_symbol def __str__(self): return ('Expecting an atomic symbol (e.g. Fe) - supplied {0}').format( self.malformed_element_symbol) class Malforme...
relevant_synpp_refs = radial1d_mdl.atom_data.synpp_refs[ radial1d_mdl.atom_data.synpp_refs['ref_log_tau'] > -50] with open(synpp_default_yaml_fname) as stream: yaml_reference = yaml.load(stream, Loader=yaml.CLoader) if lines_db is not None: yaml_reference['opacity']['line_dir'] ...
try: radial1d_mdl.atom_data.synpp_refs['ref_log_tau'].loc[key] = np.log10( radial1d_mdl.plasma.tau_sobolevs[0].loc[value['line_id']]) except KeyError: pass
conditional_block
profiling_data.go
.GetColumns() numSliceRows := slicesQueryResult.GetNumRecords() slices := make([]*service.ProfilingData_GpuSlices_Slice, numSliceRows) groupParentLookup := map[api.CmdSubmissionKey]*service.ProfilingData_GpuSlices_Group{} groups := []*service.ProfilingData_GpuSlices_Group{} groupIds := make([]int32, numSliceRows) ...
{ counterTracksQueryResult, err := processor.Query(counterTracksQuery) if err != nil { return nil, log.Errf(ctx, err, "SQL query failed: %v", counterTracksQuery) } // t.id, name, unit, description, ts, value tracksColumns := counterTracksQueryResult.GetColumns() numTracksRows := counterTracksQueryResult.GetNumR...
identifier_body
profiling_data.go
" ) func ProcessProfilingData(ctx context.Context, processor *perfetto.Processor, capture *path.Capture, desc *device.GpuCounterDescriptor, handleMapping *map[uint64][]service.VulkanHandleMappingItem, syncData *sync.Data) (*service.ProfilingData, error) { slices, err := processGpuSlices(ctx, processor, capture, handl...
(ctx context.Context, replayHandles *[]int64, replayHandleType string, handleMapping *map[uint64][]service.VulkanHandleMappingItem) { for i, v := range *replayHandles { handles, ok := (*handleMapping)[uint64(v)] if !ok { log.E(ctx, "%v not found in replay: %v", replayHandleType, v) continue } found := f...
extractTraceHandles
identifier_name
profiling_data.go
) func ProcessProfilingData(ctx context.Context, processor *perfetto.Processor, capture *path.Capture, desc *device.GpuCounterDescriptor, handleMapping *map[uint64][]service.VulkanHandleMappingItem, syncData *sync.Data) (*service.ProfilingData, error) { slices, err := processGpuSlices(ctx, processor, capture, handleM...
if !found { log.E(ctx, "Incorrect Handle type for %v: %v", replayHandleType, v) } } } func fixContextIds(contextIDs []int64) { // This is a workaround a QC bug(b/192546534) // that causes first deviceID to be zero after a // renderpass change in the same queue submit. // So, we fill the zero devices with...
{ if handle.HandleType == replayHandleType { (*replayHandles)[i] = int64(handle.TraceValue) found = true break } }
conditional_block
profiling_data.go
"github.com/google/gapid/gapis/perfetto" perfetto_service "github.com/google/gapid/gapis/perfetto/service" "github.com/google/gapid/gapis/service" "github.com/google/gapid/gapis/service/path" "github.com/google/gapid/gapis/trace/android/profile" "github.com/google/gapid/gapis/trace/android/utils" ) var ( slices...
random_line_split
config.js
License. */ define([], function () { return { // This file contains various configuration settings for esri template // // Use this file to perform the following: // // 1. Customize application settings here - [ Tag(s) to look for: ApplicationSettings ] ...
}, { Title: "Layout", WidgetPath: "widgets/layout/layout" }, { Title: "Sign In", WidgetPath: "widgets/portalSignin/portalSignin" }], // -------------------------------------------------------------------------------------------------------...
Title: "Info", WidgetPath: "widgets/info/info" }, { Title: "Sort By", WidgetPath: "widgets/sortby/sortby"
random_line_split
manager.go
) // create election directory if it does not exist c.client.Set(ctx, key, c.address, &client.SetOptions{ Dir: false, TTL: ServiceTTL, }) // create watcher watcher := c.client.Watcher(c.dir.Election, &client.WatcherOptions{ AfterIndex: 0, Recursive: true, }) go func() { for { select { case <-c.c...
{ return "" }
conditional_block
manager.go
return leader } // SetupDirectory - setup directory for service func (c *Client) SetupDirectory() { v := reflect.ValueOf(c.dir) if v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() != reflect.Struct { log.Fatal("only accepts structs") } for i := 0; i < v.NumField(); i++ { key := v.Field(i).String() c...
{ return models.SetupEnvironment( c.GetServiceHostname(), c.GetServiceIP(), c.GetRunningNodes(), ) }
identifier_body
manager.go
case "delete": if leader := c.Leader(); leader.Key == resp.Node.Key { c.events <- &models.Event{Type: EventElection, Group: GroupWorker} go c.LeaderDiscovery() } } } } // RegisterNode - register node to etcd func (c *Client) RegisterNode(dir string) { c.client.Set(context.Background(), dir, c.addre...
Connect
identifier_name
manager.go
AfterIndex: 0, Recursive: true, }) go func() { for { select { case <-c.cancel: if !isCancelled { cancel() isCancelled = true } return } } }() // observe election changes for { resp, err := watcher.Next(ctx) if err != nil { panic(err) } if resp.Node.Dir { continu...
continue // loopback interface } addrs, err := iface.Addrs() if err != nil {
random_line_split
main.rs
: u16, boost: u16, initiative: i8, attack: AttackTypes, immunity: AttackTypes, weakness: AttackTypes, } impl Group { fn effective_power(&self) -> u32 { self.units * (self.damages as u32 + self.boost as u32) }
fn calc_hit(&self, enemy: &Group) -> u32 { match ( self.immunity.to(enemy.attack), self.weakness.to(enemy.attack), ) { (false, false) => enemy.effective_power(), (true, false) => 0, (false, true) => enemy.effective_power() * 2, (true, true) => unreachable!(), } } ...
fn is_alive(&self) -> bool { self.units > 0 }
random_line_split
main.rs
: u16, boost: u16, initiative: i8, attack: AttackTypes, immunity: AttackTypes, weakness: AttackTypes, } impl Group { fn effective_power(&self) -> u32 { self.units * (self.damages as u32 + self.boost as u32) } fn is_alive(&self) -> bool { self.units > 0 } fn calc_hit(&self, enemy: &Group) ...
} #[derive(Default, Clone)] struct Army<'a> { groups: Vec<Group>, name: &'a str, } impl Army<'_> { fn sort_for_attack(&self) -> Vec<u16> { let mut ids: Vec<u16> = (0..self.groups.len() as u16).collect(); ids.sort_by_key(|i| // descending sort ( !self.groups[*i as usize].is_alive(), ...
{ let org_units = self.units; let units_kill = points / self.hits; self.units = self.units.saturating_sub(units_kill); let units_lost = org_units - self.units; dbg_print!("Units lost: {}\n", units_lost); units_lost }
identifier_body
main.rs
damages: u16, boost: u16, initiative: i8, attack: AttackTypes, immunity: AttackTypes, weakness: AttackTypes, } impl Group { fn
(&self) -> u32 { self.units * (self.damages as u32 + self.boost as u32) } fn is_alive(&self) -> bool { self.units > 0 } fn calc_hit(&self, enemy: &Group) -> u32 { match ( self.immunity.to(enemy.attack), self.weakness.to(enemy.attack), ) { (false, false) => enemy.effective_pow...
effective_power
identifier_name
types.ts
5_password_reset: string; }; website_status: { mt5_status: TMt5StatusServer; dx_trade_status: TDXTraderStatusServerType }; email: string; setVerificationCode: (code: string, action: string) => void; updateAccountStatus: () => Promise<void>; is_authentication_needed: boolean; authentication_s...
onClickCancel: (contract_id?: number) => void; onClickSell: (contract_id?: number) => void; onMount: () => void; positions: TPortfolioPosition[]; removePositionById: (id: number) => void;
random_line_split
socket.rs
(&self, non_blocking: bool) -> Result<()> { let mut non_blocking = non_blocking as libc::c_int; let res = unsafe { libc::ioctl(self.0, libc::FIONBIO, &mut non_blocking) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Connect the socket to t...
set_non_blocking
identifier_name
socket.rs
_blocking as libc::c_int; let res = unsafe { libc::ioctl(self.0, libc::FIONBIO, &mut non_blocking) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Connect the socket to the given address. Netlink is a connection-less protocol, so a socket can commu...
// a pointer to it. let addrlen_ptr = &mut addrlen as *mut usize as *mut libc::socklen_t; let chunk = buf.chunk_mut(); // Cast the *mut u8 into *mut void. // This is equivalent to casting a *char into *void // ...
// also a sockaddr_in, a sockaddr_in6, or even the generic sockaddr_storage that can store // any address. let mut addrlen = mem::size_of_val(&addr); // recvfrom does not take the address length by value (see [thread]), so we need to create
random_line_split
socket.rs
as libc::c_int; let res = unsafe { libc::ioctl(self.0, libc::FIONBIO, &mut non_blocking) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Connect the socket to the given address. Netlink is a connection-less protocol, so a socket can communicate wi...
// almost never returns EINPROGRESS and so for now, we just return whatever libc::connect // returns. If it returns EINPROGRESS, the caller will have to handle the error themself // // Refs: // // - https://stackoverflow.com/a/14046386/1836144 // - https://lists.i...
{ // FIXME: // // Event though for SOCK_DGRAM sockets there's no IO, if our socket is non-blocking, // connect() might return EINPROGRESS. In theory, the right way to treat EINPROGRESS would // be to ignore the error, and let the user poll the socket to check when it becomes ...
identifier_body
socket.rs
is copied into `buf`. If `buf` is too small, the datagram is truncated. The /// supported flags are the `MSG_*` described in `man 2 recvmsg` /// /// # Warning /// /// In datagram oriented protocols, `recv` and `recvfrom` receive normally only ONE datagram, but this seems not to /// be always tr...
{ 1 }
conditional_block
context.go
s) } providers, err = resourceProviderFactories(opts.ProviderResolver, reqd) if err != nil { return nil, err } } else { providers = make(map[string]ResourceProviderFactory) } diff := opts.Diff if diff == nil { diff = &Diff{} } return &Context{ components: &basicComponentFactory{ providers: ...
// The input graph is just a slightly modified plan graph fallthrough case GraphTypeValidate: // The validate graph is just a slightly modified plan graph fallthrough case GraphTypePlan: // Create the plan graph builder p := &PlanGraphBuilder{ Module: c.module, State: c.state, Providers: c...
{ if opts == nil { opts = &ContextGraphOpts{Validate: true} } log.Printf("[INFO] terraform: building graph: %s", typ) switch typ { case GraphTypeApply: return (&ApplyGraphBuilder{ Module: c.module, Diff: c.diff, State: c.state, Providers: c.components.ResourceProviders(), ...
identifier_body
context.go
Error asking for %s: %s", n, err) } if value == "" && v.Required() { // Redo if it is required, but abort if we keep getting // blank entries if retry > 2 { return fmt.Errorf("missing required value for %q", n) } retry++ continue } break } // no value provide...
SetVariable
identifier_name
context.go
s) } providers, err = resourceProviderFactories(opts.ProviderResolver, reqd) if err != nil { return nil, err } } else { providers = make(map[string]ResourceProviderFactory) } diff := opts.Diff if diff == nil { diff = &Diff{} } return &Context{ components: &basicComponentFactory{ providers: ...
} break } // no value provided, so don't set the variable at all if value == "" { continue } decoded, err := parseVariableAsHCL(n, value, valueType) if err != nil { return err } if decoded != nil { c.variables[n] = decoded } } } if mode&InputModeProvider != 0 { ...
{ var err error value, err = c.uiInput.Input(&InputOpts{ Id: fmt.Sprintf("var.%s", n), Query: fmt.Sprintf("var.%s", n), Description: v.Description, }) if err != nil { return fmt.Errorf( "Error asking for %s: %s", n, err) } if value == "" && v.Required() ...
conditional_block
context.go
Redo if it is required, but abort if we keep getting // blank entries if retry > 2 { return fmt.Errorf("missing required value for %q", n) } retry++ continue } break } // no value provided, so don't set the variable at all if value == "" { continue } decoded...
func (c *Context) acquireRun(phase string) func() {
random_line_split
workshopSteps.py
), 1)] #lets spawn a food by passing in the food list and snake coordinates spawnSingleFood(food, snake.x, snake.y) while end != 1: #Lets comment these out now and start from the beginning now for the loop that will run endlessly #keyPressed = getPressedKey() #screen.fill(backgroun...
#STEP 7 #Lets create a function to move the snake def move(self): #So we're going to calculate the length of the snake - 1, since arrays start from 0 the last index will be #the length of the snake - 1 lastCell = len(self.bodyStack) - 1 #We're going to write a while loop ...
self.x = x self.y = y self.direction = KEY["RIGHT"] #We're going to create a list to hold all the snakes body self.bodyStack = [] #adding the first snake cell to the list of cells self.bodyStack.append(self) #We're going to create an end cell to separate the bod...
identifier_body
workshopSteps.py
), 1)] #lets spawn a food by passing in the food list and snake coordinates spawnSingleFood(food, snake.x, snake.y) while end != 1: #Lets comment these out now and start from the beginning now for the loop that will run endlessly #keyPressed = getPressedKey() #screen.fill(backgroun...
: def __init__(self,x,y): #So we initalize the snakes x and y location to the x and y passed in and #set the direction of the snake to right self.x = x self.y = y self.direction = KEY["RIGHT"] #We're going to create a list to hold all the snakes body self.bod...
Snake
identifier_name
workshopSteps.py
), 1)] #lets spawn a food by passing in the food list and snake coordinates spawnSingleFood(food, snake.x, snake.y) while end != 1: #Lets comment these out now and start from the beginning now for the loop that will run endlessly #keyPressed = getPressedKey() #screen.fill(backgroun...
#We're going to write a function to draw the food #parameters are going to be self and a screen #lets draw a rect using the screen the self.color and the x, y coordinates and the food size and a 0 width def draw(self,screen): pygame.draw.rect(screen, self.color, (self.x, self.y, FOOD_SIZE, FOOD_...
random_line_split
workshopSteps.py
), 1)] #lets spawn a food by passing in the food list and snake coordinates spawnSingleFood(food, snake.x, snake.y) while end != 1: #Lets comment these out now and start from the beginning now for the loop that will run endlessly #keyPressed = getPressedKey() #screen.fill(backgroun...
#If a key was pressed we try to change the direction of the snake then we move again if(keyPressed): snake.changeDirection(keyPressed) snake.move() #We fill the screen in again with the color screen.fill(background_color) #we check for all the food and if ...
spawnSingleFood(food, snake.bodyStack[0].x, snake.bodyStack[0].y) eaten_food = False
conditional_block
glove.py
for list_ in self._lists: vocab.update(list_) self._logger.info("Done building vocab from corpus.") if top is not None and top < len(vocab): words = sorted(vocab.items(), key=lambda x: -x[1])[:top] else: words = vocab.items() self._vocabular...
# indexing speed; we'll convert into a list later cooccurrences = sparse.lil_matrix((vocab_size, vocab_size), dtype=np.float64) for i, list_ in enumerate(self._lists): if i % 1000 == 0: self._logger.info("Building cooccurrenc...
vocab_size = len(self._vocabulary) # Collect cooccurrences internally as a sparse matrix for passable
random_line_split
glove.py
.id2word[i]][1] < self._min_count: continue for data_idx, j in enumerate(row): if self._min_count is not None and self._vocabulary[self.id2word[j]][1] < self._min_count: continue yield i, j, data[data_idx] def _run_iter(self, data): ...
test_lists = [ ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['woda', 'chleb'], ['woda', 'chleb'], ['woda', 'c...
conditional_block
glove.py
def fit(self): space = self._train() merged_space = self._merge_main_context(space) return merged_space def setup_logger(self, name_='GloVe'): # TODO redirect to file self._logger = logging.getLogger(name_) stream_logger = logging.StreamHandler() stre...
self.setup_logger() self.build_vocab() self.build_id2word()
identifier_body
glove.py
(self): self.setup_logger() self.build_vocab() self.build_id2word() def fit(self): space = self._train() merged_space = self._merge_main_context(space) return merged_space def setup_logger(self, name_='GloVe'): # TODO redirect to file self._logg...
setup
identifier_name
printer.rs
, "css"), // In HTTPie part of this behavior is gated behind the --json flag // But it does JSON formatting even without that flag, so doing // this check unconditionally is fine ContentType::Text | ContentType::JavaScript if valid_json(body) => { self.pri...
{ let content_type = get_content_type(request.headers()); if let Some(body) = request.body_mut() { let body = body.buffer()?; if body.contains(&b'\0') { self.buffer.print(BINARY_SUPPRESSOR)?; } else { self.print_body_text(content_type, ...
identifier_body
printer.rs
(url) { headers.insert(COOKIE, cookie); } // See https://github.com/seanmonstar/reqwest/issues/1030 // reqwest and hyper add certain headers, but only in the process of // sending the request, which we haven't done yet if let Some(body) = request.body().and_then(Body...
{ None }
conditional_block
printer.rs
.print_syntax_text(body, "html"), ContentType::Css => self.print_syntax_text(body, "css"), // In HTTPie part of this behavior is gated behind the --json flag // But it does JSON formatting even without that flag, so doing // this check unconditionally is fine ...
(&self, headers: &HeaderMap, version: Version) -> String { let as_titlecase = match version { Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11 => true, Version::HTTP_2 | Version::HTTP_3 => false, _ => false, }; let mut headers: Vec<(&HeaderName, &HeaderV...
headers_to_string
identifier_name
printer.rs
let mut highlighter = self.get_highlighter("json"); let mut buf = Vec::new(); while let Some(lines) = guard.read_lines()? { formatter.format_buf(lines, &mut buf)?; for line in buf.split_inclusive(|&b| b == b'\n') { highlighter.highlight_bytes(...
Ok(_) => {
random_line_split
graham_scan.py
, idx_start, count = np.unique(sorted_polar_angle_arr, return_counts=True, return_index=True) res = np.split(idx_sorted_pang, idx_start[1:]) #filter them with respect to their size, keeping only items occurring more than once final_points =[] for each in res: # print("len(each)...
s.pop()
conditional_block
graham_scan.py
clidean_distance_v2(point, ref_point): # print('Calculating dist between',point,' and ',ref_point,end='') # print(sqrt((ref_point[0]-point[0])**2 +(ref_point[1]-point[1])**2)) return sqrt((ref_point[0]-point[0])**2 +(ref_point[1]-point[1])**2) def polar_angle(points): """Returns list of polar angle between -p...
(n): """Returns random points for input choice 1 from menu screen Input:n(int) : size of input Output: points array """ return [(random.randint(0,n),random.randint(0,n)) for i in range(n)] def points_on_circumference(center=(0, 0), r=50, n=100): """ Returns points around the boundary of circle with random d...
create_random_points
identifier_name
graham_scan.py
clidean_distance_v2(point, ref_point): # print('Calculating dist between',point,' and ',ref_point,end='') # print(sqrt((ref_point[0]-point[0])**2 +(ref_point[1]-point[1])**2)) return sqrt((ref_point[0]-point[0])**2 +(ref_point[1]-point[1])**2) def polar_angle(points): """Returns list of polar angle between -p...
final_points.append(check_points[max_far_idx]) elif len(each) == 1: final_points.append(points[each.tolist()[0]]) return final_points def cross_product(p0,p1,p2): """Returns the cross product of points of p0,p1 and p2. The value returned is +ve, -ve or 0 """ return (((p1[0]-p0[0])*(p2[1]-p...
for j in i: check_points.append(points[j]) check_points_arr = np.asarray(check_points) max_far_idx = np.argmax(euclidean_distance(check_points,P0))
random_line_split
graham_scan.py
clidean_distance_v2(point, ref_point): # print('Calculating dist between',point,' and ',ref_point,end='') # print(sqrt((ref_point[0]-point[0])**2 +(ref_point[1]-point[1])**2)) return sqrt((ref_point[0]-point[0])**2 +(ref_point[1]-point[1])**2) def polar_angle(points): """Returns list of polar angle between -p...
def create_export_files(n,input_choice,timing,min_hull_per): """Creates folder analysis if not exists in current directory and creates results.csv file Input: n(int): size of input input_choice(int): choice of input from menu timing(decimal): Timing in sec of algo min_hull_per(int): perc...
""" Returns points around the boundary of circle with random distribution It is called when choice of input entered is 2 """ return [ ( center[0]+(cos(2 * pi / n * x) * r), center[1] + (sin(2 * pi / n * x) * r) ) for x in range(0, n + 1)]
identifier_body
dataset.py
idx.logic_box=BoxNi(PointNi.zero(dims.getPointDim()),dims) else: raise Exception("please specify dimensions or source data") # add fields if "fields" in args: for field in args["fields"]: idx.fields.push_back(field) elif buffer: idx.fields.push_back(Field.fromString("DATA {} default_layout(row_...
if not access: access=self.db.createAccess() def NoGenerator(): if not self.db.executeBoxQuery(access, query): raise Exception("query error {0}".format(query.errormsg)) # i cannot be sure how the numpy will be used outside or when the query will dealllocate the buffer data=Array.to...
raise Exception("begin query failed {0}".format(query.errormsg))
conditional_block
dataset.py
idx.logic_box=BoxNi(PointNi.zero(dims.getPointDim()),dims) else: raise Exception("please specify dimensions or source data") # add fields if "fields" in args: for field in args["fields"]: idx.fields.push_back(field) elif buffer: idx.fields.push_back(Field.fromString("DATA {} default_layout(row_...
# readBlock def readBlock(self, block_id, time=None, field=None, access=None, aborted=Aborted()): Assert(access) field=self.getField() if field is None else self.getField(field) time = self.getTime() if time is None else time read_block = self.db.createBlockQuery(block_id, field, time, ord('r'), abo...
return self.db.createAccess()
identifier_body
dataset.py
idx.logic_box=BoxNi(PointNi.zero(dims.getPointDim()),dims) else: raise Exception("please specify dimensions or source data") # add fields if "fields" in args: for field in args["fields"]: idx.fields.push_back(field) elif buffer: idx.fields.push_back(Field.fromString("DATA {} default_layout(row_...
(object): # constructor def __init__(self,db): self.db = db # __getattr__ def __getattr__(self,attr): return getattr(self.db, attr) # getPointDim def getPointDim(self): return self.db.getPointDim() # getMaxResolution def getMaxResolution(self): return self.db.getMaxResolution() ...
PyDataset
identifier_name
dataset.py
field in idx.fields: TOT+=field.dtype.getByteSize(idx.logic_box.size()) # blocks per file if "blocksperfile" in args: idx.blocksperfile=int(args["blocksperfile"]) elif "data" in args or TOT<2*(1024*1024*1024): idx.blocksperfile=-1 # all blocks in one file else: idx.blocksperfile==0 # open...
logic_box=BoxNi(PointNi(logic_box[0]),PointNi(logic_box[1]))
random_line_split
imitation_ddpg_model.py
="relu")(concat) out = layers.Dense(256, activation="relu")(out) outputs = layers.Dense(1)(out) # Outputs single value for give state-action model = tf.keras.Model([state_input, action_input], outputs) return model def policy(state, noise_object): sampled_actions = tf.squeeze(actor_model(sta...
random_line_split
imitation_ddpg_model.py
# Takes (s,a,r,s') obervation tuple as input def record(self, obs_tuple): # Set index to zero if buffer_capacity is exceeded, # replacing old records index = self.buffer_counter % self.buffer_capacity self.state_buffer[index] = obs_tuple[0] self.action_buffer[index] = ...
self.buffer_capacity = buffer_capacity # Num of tuples to train on. self.batch_size = batch_size # Its tells us num of times record() was called. self.buffer_counter = 0 # Instead of list of tuples as the exp.replay concept go # We use different np.arrays for each tuple...
identifier_body
imitation_ddpg_model.py
esseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract' std_dev = 0.2 ou_noise = OUActionNoise(mean=np.zeros(1), std_deviation=float(std_dev) * np.ones(1)) actor_model = get_actor() critic_model = get_critic() target_actor = get_actor() target_critic = get_critic() # Making the weights equal initially ...
lient, car_controls = sim_start() break prev_state = state ep_reward_list.append(episodic_reward) # Mean of last 40 episodes avg_reward = np.mean(ep_reward_list[-40:]) print("Episode * {} * Avg Reward is ==> {}".format(ep + 1, avg_reward)) avg_reward_list.append(avg_reward) ...
conditional_block
imitation_ddpg_model.py
(self): if self.x_initial is not None: self.x_prev = self.x_initial else: self.x_prev = np.zeros_like(self.mean) class Buffer: def __init__(self, buffer_capacity=100000, batch_size=64): # Number of "experiences" to store at max self.buffer_capacity = buffer_...
reset
identifier_name
reading.rs
, RecordWitness, SBucket, SectorId, }; use subspace_erasure_coding::ErasureCoding; use subspace_proof_of_space::{Quality, Table, TableGenerator}; use thiserror::Error; use tracing::debug; /// Errors that happen during reading #[derive(Debug, Error)] pub enum ReadingError { /// Wrong sector size #[error("Wrong ...
Ok(record_chunks) } /// Read metadata (commitment and witness) for record pub(crate) fn read_record_metadata( piece_offset: PieceOffset, pieces_in_sector: u16, sector: &[u8], ) -> Result<RecordMetadata, ReadingError> { if sector.len() != sector_size(pieces_in_sector) { return Err(ReadingE...
{ return Err(ReadingError::WrongRecordSizeAfterDecoding { expected: Record::NUM_CHUNKS, actual: record_chunks.len(), }); }
conditional_block
reading.rs
, RecordWitness, SBucket, SectorId, }; use subspace_erasure_coding::ErasureCoding; use subspace_proof_of_space::{Quality, Table, TableGenerator}; use thiserror::Error; use tracing::debug; /// Errors that happen during reading #[derive(Debug, Error)] pub enum ReadingError { /// Wrong sector size #[error("Wrong ...
ReadingError::InvalidChunk { s_bucket, encoded_chunk_used, chunk_location, error, } })?); Ok::<_, ReadingError>(()) }, )?; let...
); } maybe_record_chunk.replace(Scalar::try_from(record_chunk).map_err(|error| {
random_line_split
reading.rs
, RecordWitness, SBucket, SectorId, }; use subspace_erasure_coding::ErasureCoding; use subspace_proof_of_space::{Quality, Table, TableGenerator}; use thiserror::Error; use tracing::debug; /// Errors that happen during reading #[derive(Debug, Error)] pub enum ReadingError { /// Wrong sector size #[error("Wrong ...
<PosTable>( piece_offset: PieceOffset, sector_id: &SectorId, sector_metadata: &SectorMetadataChecksummed, sector: &[u8], erasure_coding: &ErasureCoding, table_generator: &mut PosTable::Generator, ) -> Result<Piece, ReadingError> where PosTable: Table, { let pieces_in_sector = sector_meta...
read_piece
identifier_name
reading.rs
, RecordWitness, SBucket, SectorId, }; use subspace_erasure_coding::ErasureCoding; use subspace_proof_of_space::{Quality, Table, TableGenerator}; use thiserror::Error; use tracing::debug; /// Errors that happen during reading #[derive(Debug, Error)] pub enum ReadingError { /// Wrong sector size #[error("Wrong ...
/// Read metadata (commitment and witness) for record pub(crate) fn read_record_metadata( piece_offset: PieceOffset, pieces_in_sector: u16, sector: &[u8], ) -> Result<RecordMetadata, ReadingError> { if sector.len() != sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { ...
{ // Restore source record scalars let record_chunks = erasure_coding .recover_source(sector_record_chunks) .map_err(|error| ReadingError::FailedToErasureDecodeRecord { piece_offset, error, })?; // Required for safety invariant below if record_chunks.len(...
identifier_body
api_op_UpdateMatchmakingConfiguration.go
the matchmaking configuration to update. You can use // either the configuration name or ARN value. // // This member is required. Name *string // A flag that indicates whether a match that was created with this configuration // must be accepted by the matched players. To require acceptance, set to TRUE. // Wi...
{ if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { return next.HandleSerialize(ctx, in) } req, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) } if m.EndpointResolver == nil { return out, metadata, fmt.Errorf("expected endpoint re...
identifier_body
api_op_UpdateMatchmakingConfiguration.go
identifier for the matchmaking configuration to update. You can use // either the configuration name or ARN value. // // This member is required. Name *string // A flag that indicates whether a match that was created with this configuration // must be accepted by the matched players. To require acceptance, set ...
(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "gamelift", OperationName: "UpdateMatchmakingConfiguration", } } type opUpdateMatchmakingConfigurationResolveEndpointMiddleware struct { End...
newServiceMetadataMiddleware_opUpdateMatchmakingConfiguration
identifier_name
api_op_UpdateMatchmakingConfiguration.go
identifier for the matchmaking configuration to update. You can use // either the configuration name or ARN value. // // This member is required. Name *string // A flag that indicates whether a match that was created with this configuration // must be accepted by the matched players. To require acceptance, set ...
} if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addUpdateMatchmakingConfigurationResolveEndpointMiddleware(stack, options); err != nil { return err } if err = addOpUpda...
random_line_split
api_op_UpdateMatchmakingConfiguration.go
assignments, in a MatchmakingSucceeded (https://docs.aws.amazon.com/gamelift/latest/flexmatchguide/match-events.html#match-events-matchmakingsucceeded) // event. // - WITH_QUEUE - FlexMatch forms matches and uses the specified Amazon GameLift // queue to start a game session for the match. FlexMatchMode type...
{ // The signer sets an equivalent value at client initialization time. // Setting this context value will cause the signer to extract it // and override the value set at client initialization time. ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) }
conditional_block
graph.rs
Option<Box<Fn(f64) -> [String; 4]>>, labels_layout_width: i32, } impl Graph { // If `max` is `None`, the graph will expect values between 0 and 1. // // If `keep_max` is set to `true`, then this value will never go down, meaning that graphs // won't rescale down. It is not taken into account if `m...
(&mut self, d: RotateVec<f64>, s: &str, override_color: Option<usize>) { let c = if let Some(over) = override_color { Color::generate(over) } else { Color::generate(self.data.len() + 11) }; let l = gtk::Label::new(Some(s)); l.override_color(StateFlags::fro...
push
identifier_name
graph.rs
: Option<Box<Fn(f64) -> [String; 4]>>, labels_layout_width: i32, } impl Graph { // If `max` is `None`, the graph will expect values between 0 and 1. // // If `keep_max` is set to `true`, then this value will never go down, meaning that graphs // won't rescale down. It is not taken into account if `...
pub fn invalidate(&self) { if let Some(t_win) = self.area.get_window() { let (x, y) = self.area.translate_coordinates(&self.area, 0, 0) .expect("translate_coordinates failed"); let rect = gdk::Rectangle { x: x, y: y, width: self.area....
}
random_line_split
graph.rs
label_callbacks: Option<Box<Fn(f64) -> [String; 4]>>) { self.label_callbacks = label_callbacks; } pub fn set_display_labels(&self, display_labels: bool) { *self.display_labels.borrow_mut() = display_labels; if display_labels == true { self.scroll_layout.show_all(); ...
{ let s = self.clone(); if let Some(parent) = self.borrow().horizontal_layout.get_toplevel() { // TODO: ugly way to resize drawing area, I should find a better way parent.connect_configure_event(move |w, _| { let need_diff = s.borrow().initial_diff.is_none(); ...
identifier_body
graph.rs
_layout_width = labels_layout_width as i32; } pub fn set_label_callbacks(&mut self, label_callbacks: Option<Box<Fn(f64) -> [String; 4]>>) { self.label_callbacks = label_callbacks; } pub fn set_display_labels(&self, display_labels: bool) { *self.display_labels.borrow_mut() = display_lab...
{ // TODO: ugly way to resize drawing area, I should find a better way parent.connect_configure_event(move |w, _| { let need_diff = s.borrow().initial_diff.is_none(); if need_diff { let mut s = s.borrow_mut(); let parent_wid...
conditional_block
train_and_deploy.py
-whole-word-masking') def seed_torch(seed=42): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.device_count() > 1: torch.cuda.manual_seed_all(seed) else:
torch.backends.cudnn.deterministic = True # Converting the lines to BERT format # Thanks to https://www.kaggle.com/httpwwwfszyc/bert-in-keras-taming def convert_lines(example, max_seq_length, tokenizer): max_seq_length -= 2 all_tokens = [] longer = 0 for text in tqdm(example): tokens_a = ...
torch.cuda.manual_seed(seed)
conditional_block
train_and_deploy.py
-whole-word-masking') def seed_torch(seed=42): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.device_count() > 1: torch.cuda.manual_seed_all(seed) else: torch.cuda.manual_seed(seed) torch.backends.cudnn....
def train(train_loader, model, optimizer, is_distributed): model.train() avg_loss = 0. avg_accuracy = 0. tk0 = tqdm(enumerate(train_loader), total=len(train_loader), leave=False) optimizer.zero_grad() for i, (x_batch, y_batch) in tk0: y_pred = model(x_batch.to(DEVI...
size = float(dist.get_world_size()) for param in model.parameters(): dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM) param.grad.data /= size
identifier_body
train_and_deploy.py
-whole-word-masking') def seed_torch(seed=42): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.device_count() > 1: torch.cuda.manual_seed_all(seed) else: torch.cuda.manual_seed(seed) torch.backends.cudnn....
# Load pre-trained bert model model = BertForSequenceClassification.from_pretrained('cl-tohoku/bert-base-japanese-whole-word-masking', num_labels=1) model.zero_grad() model = model.to(DEVICE) param_optimizer = list(model.named_paramete...
random_line_split
train_and_deploy.py
-whole-word-masking') def seed_torch(seed=42): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.device_count() > 1: torch.cuda.manual_seed_all(seed) else: torch.cuda.manual_seed(seed) torch.backends.cudnn....
(train_loader, model, optimizer, is_distributed): model.train() avg_loss = 0. avg_accuracy = 0. tk0 = tqdm(enumerate(train_loader), total=len(train_loader), leave=False) optimizer.zero_grad() for i, (x_batch, y_batch) in tk0: y_pred = model(x_batch.to(DEVICE), ...
train
identifier_name
windows_aligned_file_reader.rs
FileReader { pub fn new(fname: &str) -> ANNResult<Self> { let reader: WindowsAlignedFileReader = WindowsAlignedFileReader { file_name: fname.to_string(), ctx_map: Lazy::new(|| ShardedLock::new(HashMap::new())), }; reader.register_thread()?; Ok(reader) } ...
.chunks_exact(std::mem::size_of::<f32>()) .map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap())) .collect();
random_line_split
windows_aligned_file_reader.rs
Err(ANNError::log_index_error(format!( "unable to find IOContext for thread_id {:?}", id ))), } } // Read the data from the file by sending concurrent io requests in batches. pub fn read<T>(&self, read_requests: &mut [AlignedRead<T>], ctx: &IOContext) ->...
test_get_ctx
identifier_name
windows_aligned_file_reader.rs
(std::mem::size_of_val(aligned_buf))?; Ok(Self { offset, aligned_buf, }) } fn assert_is_aligned(val: usize) -> ANNResult<()> { match val % DISK_IO_ALIGNMENT { 0 => Ok(()), _ => Err(ANNError::log_disk_io_request_alignment_error(format!( ...
} pub struct WindowsAlignedFileReader { file_name: String, // ctx_map is the mapping from thread id to io context. It is hashmap behind a sharded lock to allow concurrent access from multiple threads. // ShardedLock: shardedlock provides an implementation of a reader-writer lock that offers concurrent re...
{ self.aligned_buf }
identifier_body
sm2.go
x2, y2 := curve.ScalarMult(pub.X, pub.Y, k.Bytes()) x1Buf := x1.Bytes() y1Buf := y1.Bytes() x2Buf := x2.Bytes() y2Buf := y2.Bytes() if n := len(x1Buf); n < 32 { x1Buf = append(zeroByteSlice()[:32-n], x1Buf...) } if n := len(y1Buf); n < 32 { y1Buf = append(zeroByteSlice()[:32-n], y1Buf...) } ...
identifier_name
sm2.go
).ModInverse(d1, N) s.Mul(s, d1Inv) s.Mod(s, N) if s.Sign() != 0 { break } } return } func hashMsg(za, msg []byte) (*big.Int, error) { e := sm3.New() e.Write(za) e.Write(msg) return new(big.Int).SetBytes(e.Sum(nil)[:32]), nil } // Verify verifies the signature in r, s of hash using the public k...
eturn t, nil } type zr struct { io.Reader } func (z
conditional_block
sm2.go
1 := new(big.Int).Add(priv.D, ONE) d1Inv := new(big.Int).ModInverse(d1, N) s.Mul(s, d1Inv) s.Mod(s, N) if s.Sign() != 0 { break } } return } func hashMsg(za, msg []byte) (*big.Int, error) { e := sm3.New() e.Write(za) e.Write(msg) return new(big.Int).SetBytes(e.Sum(nil)[:32]), nil } // Verify ...
tm = append(tm, y2Buf...) h := sm3.Sum(tm) if bytes.Compare(h, ciphertext[64:96]) != 0 { return t, errors.New("Decrypt: failed to decrypt") }
random_line_split
sm2.go
) { if len(IDA) <= 0 { IDA = default_IDA } entlenA := len(IDA) if entlenA >= 8192 { return []byte{}, errors.New("SM2: uid too large") } sm2util :=sm2P256Util{} ENTLA := uint16(8*entlenA) ZA := sm3.New() ZA.Write([]byte{byte((ENTLA >> 8) & 0xFF)}) ZA.Write([]byte{byte(ENTLA & 0xFF)}) ZA.Write(IDA) ZA.W...
byte, sign []byte) bool { var sm2Sign sm2Signature _, err := asn1.Unmarshal(sign, &sm2Sign) if err != nil { return false } return SM2Verify(pub, msg, nil, sm2Sign.R, sm2Sign.S) } // ---------------------------------------------------------------- // func (pub *PublicKey) Encrypt(data []byte) ([]byte, error)...
nil { return nil, err } return asn1.Marshal(sm2Signature{r, s}) } // ---------------------------------------------------------------- // func (pub *PublicKey) Verify(msg []
identifier_body
varausohjelmajs.js
Box.selectedIndex].innerHTML; selectedTimeIndex = selectBox.options[selectBox.selectedIndex].index; selectedTimeIndex2 = selectedTimeIndex; aika = selectedValue; elokuvanNimi = document.getElementById("usrInputNimi").value; updateHTMLBlock(); } $("td").change(function() { ...
for (var i = 0; i < ataglist.length; i++){ $( ataglist[i] ).removeClass("active"); } $( tablelist[room] ).toggle(true); $(tablelist[room]).siblings().toggle( false ); };
identifier_body
varausohjelmajs.js
// tarkistetaan onko yhtaan kayttajaa kirjattu sisaan tassa sessiossa if (loginArray == null || loginArray == undefined){ loginError.style.display = 'block'; RegisterErrorText.innerHTML = "ERROR: No readable users registered"; return; } var x = document.forms["loginForm"]["log...
} function updateHTMLBlock(){ elokuvaBlokki = stringElementti1 + rowspanElementti + stringElementti2 + elokuvanNimi + stringElementti3 + sali + stringElementti4 + aika + stringElementti5; } var asda = document.getElementsByName function tarkistaKoko(){ if (parseInt(rowspanKokoSallija, 10) < (selectedT...
{ this.classList.add("selected"); $(this).addClass('selected') this.style.backgroundColor = "green"; }
conditional_block
varausohjelmajs.js
function updateSelectedtd(){ for (var k = 0; k < checklist.length; k++) { checklist[k].style.backgroundColor = "#492079"; if ($(checklist[k]).hasClass('selected')){ checklist[k].classList.remove("selected"); } else if ($(checklist[k]).hasClass('selectedForAnnihilati...
illArray(
identifier_name
varausohjelmajs.js
// tarkistetaan onko yhtaan kayttajaa kirjattu sisaan tassa sessiossa if (loginArray == null || loginArray == undefined){ loginError.style.display = 'block'; RegisterErrorText.innerHTML = "ERROR: No readable users registered"; return; } var x = document.forms["loginForm"]["log...
return true; } } function tarkistaKokoKonfliktit(){ while(selectedTimeIndex2 > 0) { if (!$(seuraavanLapsitdt2[rowspanKohta]).hasClass('no-events')){ alert("Asettamasi aika on konfliktissa toisen ajan kanssa"); return false; } seuraavanLapsitdt2 = seuraavanLapsitdt2[0].pa...
function tarkistaKoko(){ if (parseInt(rowspanKokoSallija, 10) < (selectedTimeIndex +1)) { return false; } else {
random_line_split
openfoodfacts.py
eu lieu. Attention, en fonction du nombre de pages web à scrapper, le temps de computation peut vite exploser. """ def scrap_openfoodfacts(nb_pages = 50) : """ Il s'agit de la fonction principale du module. Cette dernière crée dans votre espace de travail un DataFrame Pandas contenant les informations scrapé...
r = re.compile('^Quan.*$') quantity = list(filter(r.match, infos))[0].split(':')[-1] except : quantity = error try : r = re.compile('^Conditionnement.*$') conditionnement = list(filter(r.match, infos))[0...
except: pass try :
conditional_block
openfoodfacts.py
eu lieu. Attention, en fonction du nombre de pages web à scrapper, le temps de computation peut vite exploser. """ def scrap_openfoodfacts(nb_pages = 50) : """ Il s'agit de la fonction principale du module. Cette dernière crée dans votre espace de travail un DataFrame Pandas contenant les informations scrapé...
except : sucre = error try : sel = liste_repères_nutri[3] sel = [float(elt) for elt in sel.split() if elt.replace('.', '').isdigit()].pop() except : sel = error ...
sucre = liste_repères_nutri[2] sucre = [float(elt) for elt in sucre.split() if elt.replace('.', '').isdigit()].pop()
random_line_split
openfoodfacts.py
eu lieu. Attention, en fonction du nombre de pages web à scrapper, le temps de computation peut vite exploser. """ def scrap_openfoodfacts(nb_pages = 50) : """ Il s'a
#Initialisation de la valeur des erreurs à implémenter dans le DataSet error = np.NaN # On récupère l'url de chaque produit sur le nombre de pages souhaitées for i in range(1,nb_pages+1) : r = requests.get(('https://fr.openfoodfacts.org/' + str(i))) soup = BeautifulSoup(r.text, 'ht...
git de la fonction principale du module. Cette dernière crée dans votre espace de travail un DataFrame Pandas contenant les informations scrapées sur le site OpenFoodFacts. L'argument "nb_pages" permet de régler le nombre de page à scraper. Veuillez ne pas trop l'augmenter afin que l'opération prenne un tem...
identifier_body
openfoodfacts.py
eu lieu. Attention, en fonction du nombre de pages web à scrapper, le temps de computation peut vite exploser. """ def scrap_open
= 50) : """ Il s'agit de la fonction principale du module. Cette dernière crée dans votre espace de travail un DataFrame Pandas contenant les informations scrapées sur le site OpenFoodFacts. L'argument "nb_pages" permet de régler le nombre de page à scraper. Veuillez ne pas trop l'augmenter afin que l'o...
foodfacts(nb_pages
identifier_name
hexformat.go
return true, false } } return false, false case EndOfFile: return false, true case ExtendedSegmentAddress: //16 bit addr length := converted[0] if length != 2 { print("!ESA value has too many bytes:", length, "\n") return true, false } esaAddr := uint32(converted[4])*256 + uint32(converted[...
{ i := int(index) total := uint8(0) switch buffer[i] { case '0': case '1': total += 16 * 1 case '2': total += 16 * 2 case '3': total += 16 * 3 case '4': total += 16 * 4 case '5': total += 16 * 5 case '6': total += 16 * 6 case '7': total += 16 * 7 case '8':
identifier_body
hexformat.go
processing line %x -> %x %+v", addr, val, converted) } if !bb.Write(addr, val) { return true, false } } return false, false case EndOfFile: return false, true case ExtendedSegmentAddress: //16 bit addr length := converted[0] if length != 2 { print("!ESA value has too many bytes:", length, "\...
(index uint16, buffer []byte) (uint8, bool) { i := int(index) total := uint8(0) switch buffer[i] { case '0': case '1': total += 16 * 1 case '2': total += 16 * 2 case '3': total += 16 * 3 case '4': total += 16 * 4 case '5': total += 16 * 5 case '6
bufferValue
identifier_name
hexformat.go
(converted[6])*0x100 + uint32(converted[7]) bb.SetBigBaseAddr(t) return false, false case ExtensionBigEntryPoint: //32 bit int which is the HIGH order of 64bit pointer length := converted[0] if length != 4 { print("!extension big linear address has wrong length:", length, "\n") return true, false } t...
return buf.String() } func EncodeBigEntry(entry uint32) string { buf := bytes.Buffer{}
random_line_split
hexformat.go
processing line %x -> %x %+v", addr, val, converted) } if !bb.Write(addr, val) { return true, false } } return false, false case EndOfFile: return false, true case ExtendedSegmentAddress: //16 bit addr length := converted[0] if length != 2 { print("!ESA value has too many bytes:", length, "\...
converted := make([]byte, (l-1)/2) //skip first colon for i := uint16(1); i < l; i += 2 { v, ok := bufferValue(i, raw) if !ok { return nil // they already sent the error to the other side } converted[(i-1)/2] = v } return converted } // this hits buffer[i] and buffer[i+1] to convert an ascii byte // r...
{ print("!bad payload, expected even number of hex bytes but got:", l-1, "\n") return nil }
conditional_block
columnar.rs
_offset.to_usize() )); } } if let Some(last_val_offset) = self.val_offsets.last() { if last_val_offset.to_usize() != self.val_data.len() { return Err(format!( "expected {} bytes of val data got {}", last_val_...
{ let ((key, val), ts, diff) = record; // Check size invariants ahead of time so we stay atomic when we can't // add the record. if !self.can_fit(key, val, KEY_VAL_DATA_MAX_LEN) { return false; } // NB: We should never hit the following expects because we ch...
identifier_body
columnar.rs
* self.diffs.len() } /// Read the record at `idx`, if there is one. /// /// Returns None if `idx >= self.len()`. pub fn get<'a>(&'a self, idx: usize) -> Option<((&'a [u8], &'a [u8]), [u8; 8], [u8; 8])> { self.borrow().get(idx) } /// Borrow Self as a [ColumnarRecordsRef]. fn bo...
/// Borrow Self as a [ColumnarRecordsRef]. fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> { let ret = ColumnarRecordsRef { len: self.len,
random_line_split
columnar.rs
self.val_offsets.last() { if last_val_offset.to_usize() != self.val_data.len() { return Err(format!( "expected {} bytes of val data got {}", last_val_offset, self.val_data.len() )); } } i...
finish
identifier_name
columnar.rs
< usize::MAX (so len+1 can fit in a usize) /// - key_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + key_data.len() <= KEY_VAL_DATA_MAX_LEN /// - key_offsets.len() == len + 1 /// - key_offsets are non-decreasing /// - Each key_offset is <= key_data.len() /// - key_offsets.first().unwrap() == 0 /// - key_offsets.last().unwr...
if let Some(first_val_offset) = self.val_offsets.first() { if first_val_offset.to_usize() != 0 { return Err(format!( "expected first val offset to be 0 got {}", first_val_offset.to_usize() )); } } if...
{ return Err(format!( "expected {} val_offsets got {}", self.len + 1, self.val_offsets.len() )); }
conditional_block
Transformer_prac.py
# [ 0, 0, 12]]) 이런식으로 표현된다 subsequent_mask = torch.from_numpy(subsequent_mask).byte() # numpy에서 torch로 텐서 버전을 바꾼다 return subsequent_mask class ScaledDotProduct(nn.Module): def __init__(self): super(ScaledDotProduct,self).__init__() self.softmax = nn.Softmax(dim = -1) # sof...
ut, enc_output, dec_self_attn_mask, dec_enc_attn_mask) dec_self_attn.append(dec_self_attn) dec_enc_attn.append(dec_enc_attn) return dec_output, dec_self_attn, dec_enc_attn, dec_enc_attn class Transformer(nn.Module): def __init__(self): super(Transformer, self).__init_...
identifier_body
Transformer_prac.py
.LongTensor(input_batch)), Variable(torch.LongTensor(output_batch)), Variable(torch.LongTensor(target_batch)) # Variable = autograd : 디폴트 requires_grad = False, tensor로 정의된 모든 API를 지원한다 # x = Variable(torch.ones(2,2), requries_grad = True) 일때 # 모델 파라미터 x를 학습하기위해 loss함수로 계산된 loss를 저장하기 위해 variable loss사용 ...
과 dim1이 서로 바꿘다 score.masked_fill_(att_mask, -1e9) # masked! # masked_fill_(mask, value) mask는 boolean으로, 마스크가 true인 곳에 value를 채움 attn = self.softmax(score) # attn = attention distribution context = torch.matmul(attn, V) return context, attn ###############################...
anpose: 주어진 dim0
identifier_name
Transformer_prac.py
(ScaledDotProduct,self).__init__() self.softmax = nn.Softmax(dim = -1) # softmax의 dim? 소프트맥스계산되는 디멘션 # NLLLoss 에는 Logsoftmax를 사용한다 self.const = np.sqrt(d_k) # d_k는? def forward(self, Q, K, V, att_mask): # att_mask는 score = torch.matmul(Q,K.transpose(-1,-2))/self.const # tranpo...
parameters(), lr = 0.001) for epoch in range(20): optimizer.zero_grad() enc_input, dec_input, target_batch = make_batch(sentence) outputs, enc_self_attns, dec_self_attns, dec_enc_attns = m
conditional_block