file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
full-site.js | var failCount = 0;
var onLogoutRemoveIds = [];
var reoloadPageForChat = false;
/**
* @author Gehad Mohamed
*/
function showLoginPopUp(){
if(!isLoggedIn){
$('#login-popup').lightcase('start',{
href: "#login-popup",
liveResize:true,
maxHeight:1000,
onClo... | () {
$('#choices-modal').modal('hide');
}
function userStateChange(data, triggerLoginEvent) {
var data = typeof data == "undefined" ? null : data;
// $('.alert-danger').remove();
$('.login-slid-div').slideUp(300);
if (data) {
if(data.user.avatar){
$(".userImage").html('<i><img sr... | closeDialog | identifier_name |
full-site.js | var failCount = 0;
var onLogoutRemoveIds = [];
var reoloadPageForChat = false;
/**
* @author Gehad Mohamed
*/
function showLoginPopUp(){
if(!isLoggedIn){
$('#login-popup').lightcase('start',{
href: "#login-popup",
liveResize:true,
maxHeight:1000,
onClo... |
}
function showAuthError(error) {
if (++failCount >= 3 || error.indexOf("Captcha") != -1) {
location.href = loginUrl;
} else {
showNotification('error',error);
// $('.dev-login-li').find('.alert').remove();
// $('.dev-login-li').prepend('<div class="alert alert-danger remove-5s">... | {
$('.dev-user-profile').html("");
// $('[type="password"]').val("");
$('.dev-anon-container').removeClass('hide');
$('.dev-login-in').addClass('hide');
$('#dev-material-create').addClass('hide');
$('#dev-backend-control').addClass('hide');
$('#dev-comics-create').... | conditional_block |
embeddings.rs | use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::iter::Enumerate;
use std::slice;
use failure::Error;
use ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
/// A word similarity.
///
/// This data structure is used to store a pair con... | self.words.push(word.clone());
self.embeddings.push(embedding);
Ok(())
}
}
/// Word embeddings.
///
/// This data structure stores word embeddings (also known as *word vectors*)
/// and provides some useful methods on the embeddings, such as similarity
/// and analogy queries.
pub struct E... | Entry::Vacant(vacant) => vacant.insert(self.words.len()),
Entry::Occupied(_) => bail!(BuilderError::DuplicateWord { word: word }),
};
| random_line_split |
embeddings.rs | use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::iter::Enumerate;
use std::slice;
use failure::Error;
use ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
/// A word similarity.
///
/// This data structure is used to store a pair con... |
/// Get an iterator over pairs of words and the corresponding embeddings.
pub fn iter(&self) -> Iter {
Iter {
embeddings: self,
inner: self.words.iter().enumerate(),
}
}
/// Normalize the embeddings using their L2 (euclidean) norms.
///
/// **Note:** wh... | {
&self.indices
} | identifier_body |
embeddings.rs | use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::iter::Enumerate;
use std::slice;
use failure::Error;
use ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
/// A word similarity.
///
/// This data structure is used to store a pair con... |
}
}
impl<'a> PartialOrd for WordSimilarity<'a> {
fn partial_cmp(&self, other: &WordSimilarity) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> Eq for WordSimilarity<'a> {}
impl<'a> PartialEq for WordSimilarity<'a> {
fn eq(&self, other: &WordSimilarity) -> bool {
self.cmp(oth... | {
self.word.cmp(other.word)
} | conditional_block |
embeddings.rs | use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::iter::Enumerate;
use std::slice;
use failure::Error;
use ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
/// A word similarity.
///
/// This data structure is used to store a pair con... | {
#[fail(
display = "invalid embedding shape, expected: {}, got: {}",
expected_len, len
)]
InvalidEmbeddingLength { expected_len: usize, len: usize },
#[fail(display = "word not unique: {}", word)]
DuplicateWord { word: String },
}
/// Builder for word embedding matrices.
///
/// T... | BuilderError | identifier_name |
utils.rs | use std::cmp::Ordering;
use std::collections::HashSet;
use crate::id;
use serde::{Deserialize, Serialize};
use swc_core::common::{Mark, Span, SyntaxContext, DUMMY_SP};
use swc_core::ecma::ast::{self, Id};
use swc_core::ecma::atoms::{js_word, JsWord};
pub fn match_member_expr(expr: &ast::MemberExpr, idents: Vec<&str>,... | BailoutReason::NonStaticAccess => (
"Non-static access of an `import` or `require`. This causes tree shaking to be disabled for the resolved module.",
"https://parceljs.org/features/scope-hoisting/#dynamic-member-accesses"
),
}
}
}
#[macro_export]
macro_rules! fold_member_expr_skip_pr... | "https://parceljs.org/features/scope-hoisting/#dynamic-imports"
), | random_line_split |
utils.rs | use std::cmp::Ordering;
use std::collections::HashSet;
use crate::id;
use serde::{Deserialize, Serialize};
use swc_core::common::{Mark, Span, SyntaxContext, DUMMY_SP};
use swc_core::ecma::ast::{self, Id};
use swc_core::ecma::atoms::{js_word, JsWord};
pub fn match_member_expr(expr: &ast::MemberExpr, idents: Vec<&str>,... | (specifier: swc_core::ecma::atoms::JsWord) -> ast::CallExpr {
let mut normalized_specifier = specifier;
if normalized_specifier.starts_with("node:") {
normalized_specifier = normalized_specifier.replace("node:", "").into();
}
ast::CallExpr {
callee: ast::Callee::Expr(Box::new(ast::Expr::Ident(ast::Iden... | create_require | identifier_name |
utils.rs | use std::cmp::Ordering;
use std::collections::HashSet;
use crate::id;
use serde::{Deserialize, Serialize};
use swc_core::common::{Mark, Span, SyntaxContext, DUMMY_SP};
use swc_core::ecma::ast::{self, Id};
use swc_core::ecma::atoms::{js_word, JsWord};
pub fn match_member_expr(expr: &ast::MemberExpr, idents: Vec<&str>,... |
}
MemberProp::Ident(Ident { ref sym, .. }) => sym,
_ => return false,
};
if prop != expected {
return false;
}
match &*member.obj {
Expr::Member(m) => member = m,
Expr::Ident(id) => {
return idents.len() == 1 && &id.sym == idents.pop().unwrap() && !decls.co... | {
return false;
} | conditional_block |
inotify_linux_2.go | //+build linux
package fsnotify
// watcher tracks the following events:
// - dir create, delete, move
// - file write, delete, move
//
// configFile changes and directory moves always trigger a full reload.
// It's not incremental.
//
// Also, any incremental changes to page files (*.page.*) will recreate
// st... |
// Watcher implements a watch service.
// It allows user to handle events natively, but does
// management of event bus and delivery.
// User just provides a callback function.
type Watcher struct {
sl time.Duration
fd int
closed uint32
wds map[int32]string
flags map[string]uint32... | {
s := make([]string, 0, 4)
x := e.Mask
if x&syscall.IN_ISDIR != 0 {
s = append(s, "IN_ISDIR")
}
if x&syscall.IN_CREATE != 0 {
s = append(s, "IN_CREATE")
}
if x&syscall.IN_CLOSE_WRITE != 0 {
s = append(s, "IN_CLOSE_WRITE")
}
if x&syscall.IN_MOVED_TO != 0 {
s = append(s, "IN_MOVED_TO")
}
if x&syscall.... | identifier_body |
inotify_linux_2.go | //+build linux
package fsnotify
// watcher tracks the following events:
// - dir create, delete, move
// - file write, delete, move
//
// configFile changes and directory moves always trigger a full reload.
// It's not incremental.
//
// Also, any incremental changes to page files (*.page.*) will recreate
// st... | const useNonBlock = true
type WatchEvent struct {
syscall.InotifyEvent
Path string
Name string
}
func (e *WatchEvent) String() string {
s := make([]string, 0, 4)
x := e.Mask
if x&syscall.IN_ISDIR != 0 {
s = append(s, "IN_ISDIR")
}
if x&syscall.IN_CREATE != 0 {
s = append(s, "IN_CREATE")
}
if x&syscall.I... | const useSelect = true
// Use non-block, so we don't block on read. | random_line_split |
inotify_linux_2.go | //+build linux
package fsnotify
// watcher tracks the following events:
// - dir create, delete, move
// - file write, delete, move
//
// configFile changes and directory moves always trigger a full reload.
// It's not incremental.
//
// Also, any incremental changes to page files (*.page.*) will recreate
// st... | (fpath string, flags uint32) error {
if atomic.LoadUint32(&w.closed) != 0 {
return ClosedErr
}
w.mu.Lock()
defer w.mu.Unlock()
return w.add(fpath, flags)
}
func (w *Watcher) add(fpath string, flags uint32) error {
if flags == 0 {
flags =
// delete: false
syscall.IN_CREATE |
syscall.IN_CLOSE_WRITE |... | Add | identifier_name |
inotify_linux_2.go | //+build linux
package fsnotify
// watcher tracks the following events:
// - dir create, delete, move
// - file write, delete, move
//
// configFile changes and directory moves always trigger a full reload.
// It's not incremental.
//
// Also, any incremental changes to page files (*.page.*) will recreate
// st... |
wevs = append(wevs, wev)
offset += syscall.SizeofInotifyEvent + raw.Len
}
select {
case w.ev <- wevs:
case <-time.After(10 * time.Millisecond):
// drop if after 30 milliseconds and no one to accept
}
}
}
func (w *Watcher) handleEvents() {
for x := range w.ev {
w.fn(x)
}
}
| {
bs := (*[syscall.PathMax]byte)(unsafe.Pointer(&buf[offset+syscall.SizeofInotifyEvent]))
wev.Name = strings.TrimRight(string(bs[0:raw.Len]), "\000")
} | conditional_block |
utils.go | // Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license... | (timeout time.Duration) error {
return task.waitStatus(timeout, "RUNNING")
}
func (task *TestTask) WaitStopped(timeout time.Duration) error {
return task.waitStatus(timeout, "STOPPED")
}
func (task *TestTask) ExpectErrorType(containerName, errType string, timeout time.Duration) error {
task.WaitStopped(timeout)
... | WaitRunning | identifier_name |
utils.go | // Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license... |
}
if agent.Version == "" {
agent.Version = "UNKNOWN"
}
agent.t.Logf("Found agent metadata: %+v", localMetadata)
return nil
}
func (agent *TestAgent) Cleanup() {
agent.StopAgent()
if agent.t.Failed() {
agent.t.Logf("Preserving test dir for failed test %s", agent.TestDir)
} else {
agent.t.Logf("Removing t... | {
agent.Version = string(versionNumberStr[1])
} | conditional_block |
utils.go | // Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license... |
func (agent *TestAgent) StartTaskWithOverrides(t *testing.T, task string, overrides []*ecs.ContainerOverride) (*TestTask, error) {
td, err := GetTaskDefinition(task)
if err != nil {
return nil, err
}
t.Logf("Task definition: %s", td)
resp, err := ECS.StartTask(&ecs.StartTaskInput{
Cluster: &agent... | {
tasks, err := agent.StartMultipleTasks(t, task, 1)
if err != nil {
return nil, err
}
return tasks[0], nil
} | identifier_body |
utils.go | // Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license... | if len(taskResp.Containers) == 0 {
return "", errors.New("No containers in task response")
}
for _, container := range taskResp.Containers {
if container.Name == containerName {
return container.DockerId, nil
}
}
return "", errors.New("No containers matched given name")
}
func (agent *TestAgent) WaitStop... | err = json.Unmarshal(*bodyData, &taskResp)
if err != nil {
return "", err
} | random_line_split |
script.js | // 1 zadanie
var exe = document.querySelector('#root');
var newElem = document.createElement('div');
newElem.innerHTML = 'To jest nowy element';
exe.appendChild(newElem);
// 2 zadanie
const myTab = ["Jabłko", "Pomarańcza", "Banan", "Wiśnia", "Granat", "Arbuz"];
const myList = document.createElement('ol');
... |
lists.forEach((ul, i) => {
if (ul.childElementCount <= 1) {
buttons[i].disabled = true;
} else {
buttons[i].disabled = false;
}
})
}
lists.forEach((ul, i) => {
buttons[i].innerText = 'MOVE';
buttons[i].addEventListener('click', () => {
... | ButtonDisabled() {
| identifier_name |
script.js | // 1 zadanie
var exe = document.querySelector('#root');
var newElem = document.createElement('div');
newElem.innerHTML = 'To jest nowy element';
exe.appendChild(newElem);
// 2 zadanie
const myTab = ["Jabłko", "Pomarańcza", "Banan", "Wiśnia", "Granat", "Arbuz"];
const myList = document.createElement('ol');
... | owManyLetters;
}
function showAvg(summ){
var average = summ / tabWithWords.length;
return average;
}
function sum(howManyLetters){
var summ = howManyLetters.reduce((prev,curr) => prev += curr);
return summ;
}
var tabWithWords = ['Mornings','are','for','coffee','and', 'contemplation', '... | ManyLetters[i] = stringArr[i].length;
}
return h | conditional_block |
script.js | // 1 zadanie
var exe = document.querySelector('#root');
var newElem = document.createElement('div');
newElem.innerHTML = 'To jest nowy element';
exe.appendChild(newElem);
// 2 zadanie
const myTab = ["Jabłko", "Pomarańcza", "Banan", "Wiśnia", "Granat", "Arbuz"];
const myList = document.createElement('ol');
... |
function moreFields(){
nameTab.push(yourName.value);
lastnameTab.push(lastname.value);
ageTab.push(age.value);
kidsTab.push(howManyKids.value);
yourName.value = '';
lastname.value = '';
age.value = '';
howManyKids.value = '';
}
document.querySelector('#more').addEventListen... | var kidsTab = [];
| random_line_split |
script.js | // 1 zadanie
var exe = document.querySelector('#root');
var newElem = document.createElement('div');
newElem.innerHTML = 'To jest nowy element';
exe.appendChild(newElem);
// 2 zadanie
const myTab = ["Jabłko", "Pomarańcza", "Banan", "Wiśnia", "Granat", "Arbuz"];
const myList = document.createElement('ol');
... | nt.querySelector('#more').addEventListener('click', moreFields);
function createTable(){
nameTab.push(yourName.value);
lastnameTab.push(lastname.value);
ageTab.push(age.value);
kidsTab.push(howManyKids.value);
yourName.value = '';
lastname.value = '';
age.value = '';
howManyKi... | ameTab.push(yourName.value);
lastnameTab.push(lastname.value);
ageTab.push(age.value);
kidsTab.push(howManyKids.value);
yourName.value = '';
lastname.value = '';
age.value = '';
howManyKids.value = '';
}
docume | identifier_body |
main.go | package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"sync"
"time"
"os/signal"
"go-learning/aliyunkafka"
"github.com/Shopify/sarama"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/bsm/sarama-cluster"
"github.com/gogo/protobuf/proto... | fmt.Printf("GetLogStore success, retry:%d, name: %s, ttl: %d, shardCount: %d, createTime: %d, lastModifyTime: %d\n", retry_times, logstore.Name, logstore.TTL, logstore.ShardCount, logstore.CreateTime, logstore.LastModifyTime)
l.m.Lock()
l.logstores[logstoreName] = logstore
l.m.Unlock()
return logstore, n... | random_line_split | |
main.go | package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"sync"
"time"
"os/signal"
"go-learning/aliyunkafka"
"github.com/Shopify/sarama"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/bsm/sarama-cluster"
"github.com/gogo/protobuf/proto... | () {
for {
select {
case msg, more := <-consumer.Messages():
if more {
fmt.Printf("kafka consumer msg: (topic:%s) (partition:%d) (offset:%d) (%s): (%s)\n", msg.Topic, msg.Partition, msg.Offset, msg.Key, msg.Value)
loghub.Input() <- msg
// consumer.MarkOffset(msg, "completed") // mark message as proc... | consume | identifier_name |
main.go | package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"sync"
"time"
"os/signal"
"go-learning/aliyunkafka"
"github.com/Shopify/sarama"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/bsm/sarama-cluster"
"github.com/gogo/protobuf/proto... |
func main() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
Start()
select {
case s := <-signals:
Stop(s)
}
}
type Config struct {
Name string
LogProject struct {
Name string
Endpoint string
AccessKeyID string
AccessKeySecret string
}
Messa... | {
fmt.Println("Recived kafka consumer stop signal...")
sig <- s
fmt.Println("kafka consumer stopped!!!")
} | identifier_body |
main.go | package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"sync"
"time"
"os/signal"
"go-learning/aliyunkafka"
"github.com/Shopify/sarama"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/bsm/sarama-cluster"
"github.com/gogo/protobuf/proto... | .dispatch()
}
func (l *Loghub) Input() chan<- *sarama.ConsumerMessage {
return l.messages
}
// dispatchToTopic
func (l *Loghub) dispatchToTopic(logstoreName string) {
// TODO: 处理消息, 分配到不同的topic
channelBuffer := l.getLogstoreLogsBufferChannel(logstoreName)
for {
select {
case log := <-channelBuffer:
l.mlogs... | := l.getLogstore(lsn)
if err != nil {
fmt.Printf("Loghub Start failed (logstoreName=%s). err: %v\n", lsn, err)
panic(err)
}
// 分配到topic
go l.dispatchToTopic(lsn)
for _, tp := range l.topics {
go l.processTopicMsg(lsn, tp)
}
}
// 分配消息
go l | conditional_block |
projectstate.rs | use std::collections::HashMap;
use std::fmt;
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use serde::de::DeserializeOwned;
use url::Url;
use uuid::Uuid;
use config::AortaConfig;
use event::StoreChangeset;... |
/// Returns the time of the last config fetch.
pub fn last_config_fetch(&self) -> Option<DateTime<Utc>> {
self.current_snapshot
.read()
.as_ref()
.map(|x| x.last_fetch.clone())
}
/// Returns the time of the last config change.
pub fn last_config_change(... | {
*self.last_event.read()
} | identifier_body |
projectstate.rs | use std::collections::HashMap;
use std::fmt;
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use serde::de::DeserializeOwned;
use url::Url;
use uuid::Uuid;
use config::AortaConfig;
use event::StoreChangeset;... | {
/// URLs that are permitted for cross original JavaScript requests.
pub allowed_domains: Vec<String>,
}
/// The project state snapshot represents a known server state of
/// a project.
///
/// This is generally used by an indirection of `ProjectState` which
/// manages a view over it which supports concurre... | ProjectConfig | identifier_name |
projectstate.rs | use std::collections::HashMap;
use std::fmt;
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use serde::de::DeserializeOwned;
use url::Url;
use uuid::Uuid;
use config::AortaConfig;
use event::StoreChangeset;... | .and_then(|x| x.last_change.clone())
}
/// Requests an update to the project config to be fetched.
pub fn request_updated_project_config(&self) {
if self.requested_new_snapshot
.compare_and_swap(false, true, Ordering::Relaxed)
{
return;
}
... | random_line_split | |
exportAnswersToXLSX.py | #!/usr/bin/env python3
# This is a tool to export the WA framework answers to a XLSX file
#
# This code is only for use in Well-Architected labs
# *** NOT FOR PRODUCTION USE ***
#
# Licensed under the Apache 2.0 and MITnoAttr License.
#
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Lice... | (
waclient,
workloadId,
lensAlias
):
answers = []
# Due to a bug in some lenses, I have to iterate over each pillar in order to
# retrieve the correct results.
for pillar in PILLAR_PARSE_MAP:
logger.debug("Grabbing answers for %s %s" % (lensAlias, pillar))
# Find a quest... | findAllQuestionId | identifier_name |
exportAnswersToXLSX.py | #!/usr/bin/env python3
# This is a tool to export the WA framework answers to a XLSX file
#
# This code is only for use in Well-Architected labs
# *** NOT FOR PRODUCTION USE ***
#
# Licensed under the Apache 2.0 and MITnoAttr License.
#
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Lice... | main() | conditional_block | |
exportAnswersToXLSX.py | #!/usr/bin/env python3
# This is a tool to export the WA framework answers to a XLSX file
#
# This code is only for use in Well-Architected labs
# *** NOT FOR PRODUCTION USE ***
#
# Licensed under the Apache 2.0 and MITnoAttr License.
#
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Lice... | 'text_wrap': False,
'indent': 100
})
lineBhidden = workbook.add_format({
'border': 0,
'left': 1,
'right': 1,
'border_color': 'black',
'bg_color': '#E4EFDC',
'align': 'top',
'text_wrap': False,
'indent': 100
})
sub_heading = workbook.add_format()
sub_heading.... | 'bg_color': '#E0EBF6',
'align': 'top', | random_line_split |
exportAnswersToXLSX.py | #!/usr/bin/env python3
# This is a tool to export the WA framework answers to a XLSX file
#
# This code is only for use in Well-Architected labs
# *** NOT FOR PRODUCTION USE ***
#
# Licensed under the Apache 2.0 and MITnoAttr License.
#
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Lice... |
def FindWorkload(
waclient,
workloadName
):
# Finding your WorkloadId
try:
response=waclient.list_workloads(
WorkloadNamePrefix=workloadName
)
except botocore.exceptions.ParamValidationError as e:
logger.error("ERROR - Parameter validation error: %s" % e)
ex... | try:
response=waclient.create_workload(
WorkloadName=workloadName,
Description=description,
ReviewOwner=reviewOwner,
Environment=environment,
AwsRegions=awsRegions,
Lenses=lenses,
NonAwsRegions=nonAwsRegions,
ArchitecturalDesign=architecturalDesign... | identifier_body |
network_context.rs | // Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::{
convert::TryFrom,
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
time::{Duration, SystemTime},
};
use crate::blocks::{FullTipset, Tipset, TipsetKeys};
use crate::libp2p::{
chain_exchange... |
/// Helper function to handle the peer retrieval if no peer supplied as well
/// as the logging and updating of the peer info in the `PeerManager`.
async fn handle_chain_exchange_request<T>(
&self,
peer_id: Option<PeerId>,
tsk: &TipsetKeys,
request_len: u64,
options... | {
// Check if what we are fetching over Bitswap already exists in the
// database. If it does, return it, else fetch over the network.
if let Some(b) = self.db.get_cbor(&content).map_err(|e| e.to_string())? {
return Ok(b);
}
let (tx, rx) = flume::bounded(1);
... | identifier_body |
network_context.rs | // Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::{
convert::TryFrom,
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
time::{Duration, SystemTime},
};
use crate::blocks::{FullTipset, Tipset, TipsetKeys};
use crate::libp2p::{
chain_exchange... | (
network_send: flume::Sender<NetworkMessage>,
peer_manager: Arc<PeerManager>,
db: Arc<DB>,
) -> Self {
Self {
network_send,
peer_manager,
db,
}
}
/// Returns a reference to the peer manager of the network context.
pub fn peer_... | new | identifier_name |
network_context.rs | // Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::{
convert::TryFrom,
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
time::{Duration, SystemTime},
};
use crate::blocks::{FullTipset, Tipset, TipsetKeys};
use crate::libp2p::{
chain_exchange... |
}
}
Err(e) => {
network_failures.fetch_add(1, Ordering::Relaxed);
debug!("Failed chain_exchange request to peer {peer_id:?}: {e}");
Err... | {
lookup_failures.fetch_add(1, Ordering::Relaxed);
debug!("Failed chain_exchange response: {e}");
Err(e)
} | conditional_block |
network_context.rs | // Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::{
convert::TryFrom,
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
time::{Duration, SystemTime}, | use crate::blocks::{FullTipset, Tipset, TipsetKeys};
use crate::libp2p::{
chain_exchange::{
ChainExchangeRequest, ChainExchangeResponse, CompactedMessages, TipsetBundle, HEADERS,
MESSAGES,
},
hello::{HelloRequest, HelloResponse},
rpc::RequestResponseError,
NetworkMessage, PeerId, Pee... | };
| random_line_split |
model.py | import time
import os
import boto3
from zipfile import ZipFile
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, Conv2DTranspose, Reshape
from keras.layers import Flatten, BatchNormalization, Dense, Activation
... | (generated_images, epoch, batch_number):
plt.figure(figsize=(8, 8), num=2)
gs1 = gridspec.GridSpec(8, 8)
gs1.update(wspace=0, hspace=0)
for i in range(64):
ax1 = plt.subplot(gs1[i])
ax1.set_aspect('equal')
image = generated_images[i, :, :, :]
image += 1
image *=... | save_generated_images | identifier_name |
model.py | import time
import os
import boto3
from zipfile import ZipFile
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, Conv2DTranspose, Reshape
from keras.layers import Flatten, BatchNormalization, Dense, Activation
... |
def main():
aws_secret = ''
aws_access = ''
dataset_path = '/home/jupyter/tutorials/generative-crystals/model/raw'
batch_size = 64
image_shape = (128, 128, 3)
epochs = 100
train_dcgan(aws_access, aws_secret, batch_size, epochs,
image_shape, dataset_path)
if __name__ ==... | generator = construct_generator()
discriminator = construct_discriminator(image_shape)
gan = Sequential()
# Only false for the adversarial model
discriminator.trainable = False
gan.add(generator)
gan.add(discriminator)
optimizer = Adam(lr=0.00015, beta_1=0.5)
gan.compile(loss='binary_c... | identifier_body |
model.py | import time
import os
import boto3
from zipfile import ZipFile
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, Conv2DTranspose, Reshape
from keras.layers import Flatten, BatchNormalization, Dense, Activation
... |
time_elapsed = time.time() - start_time
# Display and plot the results
print(" Batch " + str(batch_number + 1) + "/" +
str(number_of_batches) +
" generator loss | discriminator loss : " +
str(g_loss) + " | " + str(d_loss) +... | save_generated_images(generated_images, epoch, batch_number) | conditional_block |
model.py | import time | import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, Conv2DTranspose, Reshape
from keras.layers import Flatten, BatchNormalization, Dense, Activation
from keras.layers.advanced_activations import LeakyReLU
from ke... | import os
import boto3
from zipfile import ZipFile | random_line_split |
index.d.ts | declare module fng {
var formsAngular: angular.IModule;
/*
Type definitions for types that are used on both the client and the server
*/
/*
IInternalLookupreference makes it possible to look up from a list (of key / value pairs) in the current record. For example
var ShelfSchema = new Schema({
lo... | label: string;
options?: any;
ids?: any;
hidden?: boolean;
tab?: string;
add? : string;
ref? : any;
link? : any;
linktext?: string;
linklabel?: boolean;
form?: string; // the form that is linked to
select2? : any; // deprecated
schema?: IFormInstruc... | rows? : number; | random_line_split |
world.py | from __future__ import print_function
import numpy as np
import numdifftools as nd
from scipy.optimize import minimize, minimize_scalar
from scipy.linalg import eigh, inv, norm
from scipy.constants import e as qe # Charge of electron in Coulomb
from matplotlib import pyplot as plt
from .SH import funcSHexp
fr... |
def compute_dc_potential_frequencies(self, r):
'''
As always, this is valid only at the trapping position. Return frequency (not angular frequency)
'''
H = self.compute_dc_hessian(r)
hessdiag, eigvec = eigh(H)
hessdiag /= self.__scale**2
# # hessdiag = nd.Hessdiag( self.compute_total... | '''
This is only valid if xp, yp, zp is the trapping position. Return frequency (i.e. omega/(2*pi))
'''
hessdiag = nd.Hessdiag(self.compute_pseudopot,step=1e-6)(r)/(self.__scale**2)
'''
Now d2Udx2 has units of J/m^2. Then w = sqrt(d2Udx2/(mass)) has units of angular frequency
'''
return np.sqrt(qe*... | identifier_body |
world.py | from __future__ import print_function
import numpy as np
import numdifftools as nd
from scipy.optimize import minimize, minimize_scalar
from scipy.linalg import eigh, inv, norm
from scipy.constants import e as qe # Charge of electron in Coulomb
from matplotlib import pyplot as plt
|
class World:
'''
A General, Brand New World
Units:
(potential) energy: eV
length: __scale
frequency: Hz
Axis convention in consistance with <class Electrode>
z: axial
* It doesn't matter whether z is parallel or vertical to the surface or not
Attributes:
__scale :: the typical length in meter. L... |
from .SH import funcSHexp
from .utils import quadru2hess, intersectBounds
amu = 1.66054e-27
| random_line_split |
world.py | from __future__ import print_function
import numpy as np
import numdifftools as nd
from scipy.optimize import minimize, minimize_scalar
from scipy.linalg import eigh, inv, norm
from scipy.constants import e as qe # Charge of electron in Coulomb
from matplotlib import pyplot as plt
from .SH import funcSHexp
fr... | (self, e, name, kind, volt):
"""
Add an electrode to the World. Name it with `name.
If kind == 'rf', then add this electrode to the rf electrode dict
as well as to the general electrode dict
"""
e.volt = volt
self.electrode_dict[name] = (kind, e)
if kind=='dc':
self.dc_electrode_list.append(... | add_electrode | identifier_name |
world.py | from __future__ import print_function
import numpy as np
import numdifftools as nd
from scipy.optimize import minimize, minimize_scalar
from scipy.linalg import eigh, inv, norm
from scipy.constants import e as qe # Charge of electron in Coulomb
from matplotlib import pyplot as plt
from .SH import funcSHexp
fr... |
n_mult = sum([len(pos_ctrl_mult[1]) for pos_ctrl_mult in pos_ctrl_mults])
n_elec = len(ctrl_electrodes)
if n_mult > n_elec:
raise ValueError("Number of multipoles %d exceeds number of controlled electrodes %d"%(n_mult, n_elec))
multipole_arr = np.empty((n_mult, n_elec), 'd')
pt = 0
for pos,... | pos_ctrl_mults = [pos_ctrl_mults] | conditional_block |
train.py | import argparse
import random
import numpy as np
import torch
import torch.distributed as dist
from torch.optim import Adam, AdamW, SGD
from torch.optim.adagrad import Adagrad
from torch.nn.parallel import DistributedDataParallel
from torch.utils.data import DataLoader, TensorDataset
from torch.utils.data.distributed i... |
model.to(config.DEVICE)
model = DistributedDataParallel(model, device_ids=None)
if saved_data:
model.load_state_dict(saved_data["model_state"])
return model
def get_optimizer(model, args, saved_data=None):
if args.optim == "sgd":
optim = SGD(model.parameters(), lr=args.learning_r... | raise ValueError(f"Unrecognized model argument: {args.model}") | conditional_block |
train.py | import argparse
import random
import numpy as np
import torch
import torch.distributed as dist
from torch.optim import Adam, AdamW, SGD
from torch.optim.adagrad import Adagrad
from torch.nn.parallel import DistributedDataParallel
from torch.utils.data import DataLoader, TensorDataset
from torch.utils.data.distributed i... | parser.add_argument("--max_grad_norm", default=50.0, type=float, help="Max gradient norm.")
parser.add_argument("--batch_size", default=1000, type=int, help="Batch size.")
parser.add_argument("--eval_batch_size", default=100, type=int, help="Eval batch size. Has impact only on memory")
parser.add_argume... | parser.add_argument("--weight_decay", default=0.00, type=float, help="L2 Regularization.")
parser.add_argument("--val_every", default=5, type=int, help="Runs validation every n epochs.")
parser.add_argument("--patience", default=50, type=int, help="Epochs of patience for scheduler and early stop.") | random_line_split |
train.py | import argparse
import random
import numpy as np
import torch
import torch.distributed as dist
from torch.optim import Adam, AdamW, SGD
from torch.optim.adagrad import Adagrad
from torch.nn.parallel import DistributedDataParallel
from torch.utils.data import DataLoader, TensorDataset
from torch.utils.data.distributed i... |
def build_data_loader(split, batch_size, shuffle, args):
"""
:param split: torch.LongTensor b x 3 with triples (h, r, t)
:param batch_size: int
:param shuffle: bool
:param args:
:return: torch DataLoader set up with distributed sampler
"""
tensor_dataset = TensorDataset(split)
sam... | patience = round(args.patience / args.val_every)
factor = 1 / float(args.reduce_factor)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=patience, factor=factor, mode="max")
if saved_data:
scheduler.load_state_dict(saved_data["scheduler_state"])
return scheduler | identifier_body |
train.py | import argparse
import random
import numpy as np
import torch
import torch.distributed as dist
from torch.optim import Adam, AdamW, SGD
from torch.optim.adagrad import Adagrad
from torch.nn.parallel import DistributedDataParallel
from torch.utils.data import DataLoader, TensorDataset
from torch.utils.data.distributed i... | (parser):
# Data options
parser.add_argument("--data", required=True, type=str, help="Name of data set folder")
parser.add_argument("--run_id", required=True, type=str, help="Name of model/run to export")
# Model
parser.add_argument("--model", default="tgattnspd", type=str, help="Model type: tgspd, ... | config_parser | identifier_name |
feffpath.py | #!/usr/bin/python
"""
Feff85L EXAFS Scatternig Path for Python
"""
from __future__ import print_function
import os
import sys
import ctypes
from ctypes import POINTER, pointer, c_int, c_long, c_char_p, c_double
import numpy as np
def load_feff8lpath():
dllform = 'lib{:s}.so'
pathsep = ':'
loadlib = ctypes.... |
if __name__ == '__main__':
path = ScatteringPath(phase_file='phase.pad')
path.set_absorber( x=0.01, y=0.1, z=0.01)
path.add_scatterer(x=1.8058, y=0.005, z=1.8063, ipot=1)
path.degen = 12
path.calculate_xafs()
print('# Calculate EXAFS with PhaseFile: {:s}'.format(path.phase_file))
prin... | class args: pass
# strings / char*. Note fixed length to match Fortran
args.phase_file = (self.phase_file + ' '*256)[:256]
args.exch_label = str2bytes(' '*8)
args.genfmt_version = str2bytes(' '*30)
# integers, including booleans
for attr in ('index', 'nleg', 'g... | identifier_body |
feffpath.py | #!/usr/bin/python
"""
Feff85L EXAFS Scatternig Path for Python
"""
from __future__ import print_function
import os
import sys
import ctypes
from ctypes import POINTER, pointer, c_int, c_long, c_char_p, c_double
import numpy as np
def load_feff8lpath():
dllform = 'lib{:s}.so'
pathsep = ':'
loadlib = ctypes.... |
"""
def __init__(self, phase_file=None):
self.phase_file = phase_file
self.clear()
def clear(self):
"""reset all path data"""
self.index = 1
self.degen = 1.
self.nnnn_out = False
self.json_out = False
self.verbose = False
self.i... | # calculate basic (unaltered) XAFS contributions
path.calcuate_xafs() | random_line_split |
feffpath.py | #!/usr/bin/python
"""
Feff85L EXAFS Scatternig Path for Python
"""
from __future__ import print_function
import os
import sys
import ctypes
from ctypes import POINTER, pointer, c_int, c_long, c_char_p, c_double
import numpy as np
def load_feff8lpath():
dllform = 'lib{:s}.so'
pathsep = ':'
loadlib = ctypes.... |
print("Path settings: degen=%10.5f, xmu=%10.5f, kf=%10.5f" % (path.degen, path.xmu, path.kf))
npts = 1 + max(np.where(path.kfeff > 0)[0])
print("# k rep real_phc phase_feff mag_feff red_factor lambda ")
fmt = " %6.3f %11.7f %11.7f %11.7f %11.7f %11.7f %11.7f"
f... | print("# {:8s} = {:s} ".format(attr, getattr(path, attr))) | conditional_block |
feffpath.py | #!/usr/bin/python
"""
Feff85L EXAFS Scatternig Path for Python
"""
from __future__ import print_function
import os
import sys
import ctypes
from ctypes import POINTER, pointer, c_int, c_long, c_char_p, c_double
import numpy as np
def load_feff8lpath():
dllform = 'lib{:s}.so'
pathsep = ':'
loadlib = ctypes.... | (*args, **keywords):
"needs phase_file"
phase_file = keywords.get('phase_file', None)
if phase_file is None:
phase_file = getattr(args[0], 'phase_file', None)
if phase_file is None:
raise AttributeError(errmsg % fcn.__name__)
else:
seta... | wrapper | identifier_name |
main.rs | use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use rand::Rng;
use serde::Serialize;
use std::cmp::Ordering;
use std::io;
fn index() -> impl Responder {
let my_string = String::from("Rust Async");
// first_word works on slices of `String`s
let _word = first_word(&my_string[..]);
let m... | // }
//// Item is the placeholder type.
///
// 4. Fully Qualified Syntax for Disambiguation: Calling Methods with the Same Name
trait Pilot {
fn fly(&self);
}
trait Wizard {
fn fly(&self);
}
struct Human;
impl Pilot for Human {
fn fly(&self) {
println!("This is your captain speaking. Pilot!");
... | random_line_split | |
main.rs | use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use rand::Rng;
use serde::Serialize;
use std::cmp::Ordering;
use std::io;
fn index() -> impl Responder {
let my_string = String::from("Rust Async");
// first_word works on slices of `String`s
let _word = first_word(&my_string[..]);
let m... | );
}
struct Duck();
impl Quack for Duck {
fn quack(&self) {
println!("quack!");
}
}
struct RandomBird {
is_a_parrot: bool,
}
impl Quack for RandomBird {
fn quack(&self) {
if !self.is_a_parrot {
println!("quack!");
} else {
println!("squawk!");
... | self | identifier_name |
main.rs | use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use rand::Rng;
use serde::Serialize;
use std::cmp::Ordering;
use std::io;
fn index() -> impl Responder {
let my_string = String::from("Rust Async");
// first_word works on slices of `String`s
let _word = first_word(&my_string[..]);
let m... | i = 100;
println!("change i: {}", i);
// const declare
const MAX_POINTS: u32 = 100_000;
println!("constant variable MAX_POINT: {}", MAX_POINTS);
//shadowing
let x = 5;
let x = x + 1;
let x = x * 2;
println!("The value of x is: {}", x);
let spaces = " ";
let spaces = sp... | e {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("rect1 area: {}", rect1.area());
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
println!("re... | identifier_body |
loadtest_types.go | /*
Copyright 2020 gRPC authors.
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 writing, software
d... | // LoadTestStatus defines the observed state of LoadTest
type LoadTestStatus struct {
// State identifies the current state of the load test. It is
// important to note that this state is level-based. This means its
// transition is non-deterministic.
State LoadTestState `json:"state"`
// Reason is a camel-case s... |
// KubernetesError is the reason string when an issue occurs with Kubernetes
// that is not known to be directly related to a load test.
var KubernetesError = "KubernetesError"
| random_line_split |
loadtest_types.go | /*
Copyright 2020 gRPC authors.
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 writing, software
d... | () {
SchemeBuilder.Register(&LoadTest{}, &LoadTestList{})
}
| init | identifier_name |
loadtest_types.go | /*
Copyright 2020 gRPC authors.
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 writing, software
d... | {
SchemeBuilder.Register(&LoadTest{}, &LoadTestList{})
} | identifier_body | |
tgsw.rs | use crate::numerics::Torus32;
use crate::polynomial::{IntPolynomial, Polynomial, TorusPolynomial};
use crate::tlwe::{TLweKey, TLweParameters, TLweSample};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct TGswParams {
/// Decompositi... |
#[cfg(test)]
mod tests {
use super::*;
use crate::polynomial::TorusPolynomial;
fn generate_parameters() -> Vec<TGswParams> {
vec![
TGswParams::new(4, 8, TLweParameters::new(512, 1, 0f64, 1f64)),
TGswParams::new(3, 10, TLweParameters::new(512, 2, 0f64, 1f64)),
TGswParams::new(3, 10, TLwePa... | {
let n = params.tlwe_params.n;
let l = params.l;
let bg_bit = params.bg_bit;
let mask_mod = params.mask_mod;
let half_bg = params.half_bg;
let offset = params.offset;
// First, add offset to everyone
let buf: Vec<i32> = sample
.coefs
.iter()
.map(|c| c.wrapping_add(offset as i32))
.col... | identifier_body |
tgsw.rs | use crate::numerics::Torus32;
use crate::polynomial::{IntPolynomial, Polynomial, TorusPolynomial};
use crate::tlwe::{TLweKey, TLweParameters, TLweSample};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct TGswParams {
/// Decompositi... | () {
for params in generate_parameters() {
let mut sample = TGswSample::new(¶ms);
let kpl = params.kpl;
let l = params.l;
let k = params.tlwe_params.k;
let n = params.tlwe_params.n;
let h = ¶ms.h;
let alpha = 4.2;
fully_random_tgsw(&mut sample, alpha, ¶ms... | test_add_h | identifier_name |
tgsw.rs | use crate::numerics::Torus32;
use crate::polynomial::{IntPolynomial, Polynomial, TorusPolynomial};
use crate::tlwe::{TLweKey, TLweParameters, TLweSample};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct TGswParams {
/// Decompositi... |
assert_eq!(
new_polynomial.coefs[0], // Should this be i == u?
old_polynomial.coefs[0] + (if j == u { dbg!(h[i]) } else { 0 })
);
assert_eq!(new_polynomial.coefs[1..], old_polynomial.coefs[1..]);
}
}
}
}
}
}
| {
assert!(new_polynomial
.coefs
.iter()
.zip_eq(old_polynomial.coefs.iter())
.all(|(a, b)| a == b));
} | conditional_block |
tgsw.rs | use crate::numerics::Torus32;
use crate::polynomial::{IntPolynomial, Polynomial, TorusPolynomial};
use crate::tlwe::{TLweKey, TLweParameters, TLweSample};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct TGswParams {
/// Decompositi... | // );
// }
} else {
assert!(new_polynomial
.coefs
.iter()
.zip_eq(old_polynomial.coefs.iter())
.all(|(a, b)| a == b));
}
assert_eq!(
new_polynomial.coefs[0], // Shoul... | random_line_split | |
trie.rs | use std::fmt::Debug;
use super::bit_cache::BitCache;
use crate::double_array::DoubleArray;
use bincode;
use serde::Serialize;
use serde::de::DeserializeOwned;
struct Node<T> {
key : u8,
values: Vec<T>,
nexts : Vec<Node<T>>,
}
/// トライ木の実装。
/// ダブル配列は直接構築することはできないので、トライ木を構築してから変換することで構築する。
///
/// # Exa... | while !stack.is_empty() {
let (curr_idx, mut node) = stack.pop().unwrap();
bit_cache.update_start();
// base値を探索・セット
if !node.values.is_empty() {
// valuesが存在する場合はkey=255のノードとして計算する
node.nexts.push(Node { key: u8::max_value(), valu... | let mut stack: Vec<(usize, Node<T>)> = Vec::with_capacity(self.len);
if !self.root.nexts.is_empty() {
stack.push((1, self.root));
}
| random_line_split |
trie.rs | use std::fmt::Debug;
use super::bit_cache::BitCache;
use crate::double_array::DoubleArray;
use bincode;
use serde::Serialize;
use serde::de::DeserializeOwned;
struct Node<T> {
key : u8,
values: Vec<T>,
nexts : Vec<Node<T>>,
}
/// トライ木の実装。
/// ダブル配列は直接構築することはできないので、トライ木を構築してから変換することで構築する。
///
/// # Exa... | or> {
let max_key = u8::max_value() as usize + 1; // keyが取りうる値のパターン
let mut len = if max_key > (4 * self.len) { max_key } else { 4 * self.len };
let mut base_arr: Vec<u32> = vec![0; len];
let mut check_arr: Vec<u32> = vec![0; len];
let mut data_arr: Vec<u8> = Vec::with_ca... | > {
return None;
}
}
}
if node.values.is_empty() {
None
} else {
Some(&node.values)
}
}
/// トライ木をダブル配列に変換する
///
/// # Panics
/// dataをバイト列に変換できなかった場合にpanicする。
///
/// # Errors
///
... | identifier_body |
trie.rs | use std::fmt::Debug;
use super::bit_cache::BitCache;
use crate::double_array::DoubleArray;
use bincode;
use serde::Serialize;
use serde::de::DeserializeOwned;
struct Node<T> {
key : u8,
values: Vec<T>,
nexts : Vec<Node<T>>,
}
/// トライ木の実装。
/// ダブル配列は直接構築することはできないので、トライ木を構築してから変換することで構築する。
///
/// # Exa... | identifier_name | ||
trie.rs | use std::fmt::Debug;
use super::bit_cache::BitCache;
use crate::double_array::DoubleArray;
use bincode;
use serde::Serialize;
use serde::de::DeserializeOwned;
struct Node<T> {
key : u8,
values: Vec<T>,
nexts : Vec<Node<T>>,
}
/// トライ木の実装。
/// ダブル配列は直接構築することはできないので、トライ木を構築してから変換することで構築する。
///
/// # Exa... | o::Error> {
let max_key = u8::max_value() as usize + 1; // keyが取りうる値のパターン
let mut len = if max_key > (4 * self.len) { max_key } else { 4 * self.len };
let mut base_arr: Vec<u32> = vec![0; len];
let mut check_arr: Vec<u32> = vec![0; len];
let mut data_arr: Vec<u8> = Vec::w... | ray(self) -> Result<DoubleArray<T>, std::i | conditional_block |
doctype.py | # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
#
# MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without lim... | for r in res:
# Cheat! Mask Custom Field as DocField
custom_field = webnotes.model.doc.Document(fielddata=r)
self.mask_custom_field(custom_field, doc_type)
custom_doclist.append(custom_field)
return custom_doclist
def mask_custom_field(self, custom_field, doc_type):
"""
Masks doctype and parent ... | WHERE dt = %s AND docstatus < 2""", doc_type, as_dict=1) | random_line_split |
doctype.py | # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
#
# MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without lim... |
def change_idx(self, doclist, docfields, doc_type):
for d in doclist:
if d.fieldname and d.fieldname in docfields and d.parent == doc_type:
d.idx = docfields.index(d.fieldname) + 1
def add_code(self, doc):
"""add js, css code"""
import os
from webnotes.modules import scrub, get_module_path
imp... | """
"""
temp_dict = prev_field_dict.get(doc_type)
if not temp_dict: return
prev_field = 'None' in temp_dict and 'None' or docfields[0]
i = 0
while temp_dict:
get_next_docfield = True
cur_field = temp_dict.get(prev_field)
if cur_field and cur_field in docfields:
try:
del temp_dict[prev... | identifier_body |
doctype.py | # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
#
# MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without lim... |
from webnotes.utils import cint
prop_updates = []
for prop in doctype_property_dict.get(cstr(d.fieldname)):
if prop.get('property')=='previous_field': continue
if prop.get('property_type') == 'Check' or \
prop.get('value') in ['0', '1']:
prop_updates.append([prop.get('property'), cint(prop.get(... | return | conditional_block |
doctype.py | # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
#
# MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without lim... | (self, doc_type):
"""
Gets a list of custom field docs masked as type DocField
"""
custom_doclist = []
res = webnotes.conn.sql("""SELECT * FROM `tabCustom Field`
WHERE dt = %s AND docstatus < 2""", doc_type, as_dict=1)
for r in res:
# Cheat! Mask Custom Field as DocField
custom_field = webnotes.mo... | get_custom_fields | identifier_name |
MotionTrackingLK.py | import tensorflow as tf
import cv2 as cv
import numpy as np
import math
def gaussian(x, sigma):
return 1/(sigma*math.sqrt(2*math.pi))*math.e**(-1/2*(x/sigma)**2)
def | (w, h, lx, ly):
devx = lx * w/2 + w/2
devy = ly * h/2 + h/2
return int(devx), int(devy)
def device_to_logical(w, h, devx, devy):
lx = (devx - w/2)/(w/2)
ly = (devy - h/2)/(h/2)
return lx, ly
def display_tracks(imgs, batch_tracks):
imgs = np.copy(imgs)
_,_,h,w,c = imgs.shape
imgs_... | logical_to_device | identifier_name |
MotionTrackingLK.py | import tensorflow as tf
import cv2 as cv
import numpy as np
import math
def gaussian(x, sigma):
return 1/(sigma*math.sqrt(2*math.pi))*math.e**(-1/2*(x/sigma)**2)
def logical_to_device(w, h, lx, ly):
devx = lx * w/2 + w/2
devy = ly * h/2 + h/2
return int(devx), int(devy)
def device_to_logical(w, h, d... |
VxVy = tf.matmul(ATA_1, ATb)
return VxVy
def iterative_LK(self, sampler, frames, iterations):
out = self.sample_ntracks_from_2frames(sampler, frames)
first_frame = out[:, 0]
factor = 1.0
VxVy = self.calc_velocity_2frames_ntracks_LK(first_frame, out[:, 1])*factor
... | ATb = tf.matmul(A, b, transpose_a=True) | random_line_split |
MotionTrackingLK.py | import tensorflow as tf
import cv2 as cv
import numpy as np
import math
def gaussian(x, sigma):
return 1/(sigma*math.sqrt(2*math.pi))*math.e**(-1/2*(x/sigma)**2)
def logical_to_device(w, h, lx, ly):
devx = lx * w/2 + w/2
devy = ly * h/2 + h/2
return int(devx), int(devy)
def device_to_logical(w, h, d... |
_, sampler, _, tot_VxVy = tf.while_loop(
cond, iterate, [i, sampler, imgs, tot_VxVy],
shape_invariants=[i.get_shape(), sampler.get_shape(), imgs.get_shape(), tf.TensorShape([None, self.num_tracks, None, 2])]
)
tot_VxVy = tf.reshape(tot_VxVy, [-1, self.num_track... | sampler, sum_VxVy = self.iterative_LK(sampler, imgs[:, i:i+2], self.iterations)
sum_VxVy = tf.reshape(sum_VxVy, [-1, self.num_tracks, 1, 2])
prev = tf.reshape(tot_VxVy[:, :, i], [-1, self.num_tracks, 1, 2])
tot_VxVy = tf.concat([tot_VxVy, sum_VxVy+prev], axis=2)
i += 1
... | identifier_body |
MotionTrackingLK.py | import tensorflow as tf
import cv2 as cv
import numpy as np
import math
def gaussian(x, sigma):
return 1/(sigma*math.sqrt(2*math.pi))*math.e**(-1/2*(x/sigma)**2)
def logical_to_device(w, h, lx, ly):
devx = lx * w/2 + w/2
devy = ly * h/2 + h/2
return int(devx), int(devy)
def device_to_logical(w, h, d... |
imgs_with_tracks.append(img)
return np.asfarray(imgs_with_tracks)
class MotionTrackingLK(tf.keras.layers.Layer):
def __init__(self, num_tracks, window_pixel_wh=21, sigma=2, iterations=5, **kwargs):
self.sigma = sigma
assert(num_tracks > 1)
assert(window_pixel_wh >= 3)
s... | for t_seq in range(1, len(track)):
lx_p, ly_p = track[t_seq-1]
x_p, y_p = logical_to_device(w, h, lx_p, ly_p)
lx, ly = track[t_seq]
x, y = logical_to_device(w, h, lx, ly)
img = cv.arrowedLine(img, (x_p, y_p), (x, y), (255, 0, 0)) | conditional_block |
main.rs | extern crate jemallocator;
extern crate num_cpus;
extern crate quick_protobuf;
mod osm_pbf;
use crossbeam_channel::{bounded, unbounded};
use crossbeam_utils::thread;
use memmap::MmapOptions;
use osm_pbf::{Blob, BlobHeader, DenseNodes, Info, Node, PrimitiveBlock, Relation, Way};
use quick_protobuf::{BytesReader, Messa... | {
timestamp_min: i64,
timestamp_max: i64,
nodes: u64,
ways: u64,
relations: u64,
lon_min: f64,
lon_max: f64,
lat_min: f64,
lat_max: f64,
}
fn main() {
let args: Vec<_> = std::env::args_os().collect();
let filename = &args[1];
let orig_handler = panic::take_hook();
... | OsmStats | identifier_name |
main.rs | extern crate jemallocator;
extern crate num_cpus;
extern crate quick_protobuf;
mod osm_pbf;
use crossbeam_channel::{bounded, unbounded};
use crossbeam_utils::thread;
use memmap::MmapOptions;
use osm_pbf::{Blob, BlobHeader, DenseNodes, Info, Node, PrimitiveBlock, Relation, Way};
use quick_protobuf::{BytesReader, Messa... | let (sender, receiver) = bounded::<Blob>(WORK_BOUND);
let (return_sender, return_received) = unbounded::<OsmStats>();
thread::scope(|s| {
for _ in 0..thread_count {
let cloned_receiver = receiver.clone();
let cloned_return_sender = return_sender.clone();
s.spawn(... | random_line_split | |
main.rs | extern crate jemallocator;
extern crate num_cpus;
extern crate quick_protobuf;
mod osm_pbf;
use crossbeam_channel::{bounded, unbounded};
use crossbeam_utils::thread;
use memmap::MmapOptions;
use osm_pbf::{Blob, BlobHeader, DenseNodes, Info, Node, PrimitiveBlock, Relation, Way};
use quick_protobuf::{BytesReader, Messa... |
received_messages += 1;
}
Ok(format!("{:#?}", osm_stats))
})
.unwrap()
}
fn handle_block(mut osm_stats: &mut OsmStats, blob: &Blob, buffer: &mut Vec<u8>) {
let zlib_data_ref = blob.zlib_data.as_ref();
let tried_block = if blob.raw.is_some() {
let bytes = blob.raw.as... | {
osm_stats.lon_min = worker_stats.lon_min
} | conditional_block |
main.rs | extern crate jemallocator;
extern crate num_cpus;
extern crate quick_protobuf;
mod osm_pbf;
use crossbeam_channel::{bounded, unbounded};
use crossbeam_utils::thread;
use memmap::MmapOptions;
use osm_pbf::{Blob, BlobHeader, DenseNodes, Info, Node, PrimitiveBlock, Relation, Way};
use quick_protobuf::{BytesReader, Messa... |
fn handle_latitude(osm_stats: &mut OsmStats, latitude: i64, primitive: &PrimitiveBlock) {
let latitude_f =
0.000000001 * ((primitive.lat_offset + ((primitive.granularity as i64) * latitude)) as f64);
if latitude_f < osm_stats.lat_min {
osm_stats.lat_min = latitude_f
}
if latitude_f > o... | {
let millisec_stamp = timestamp * (date_granularity as i64);
if millisec_stamp < osm_stats.timestamp_min {
osm_stats.timestamp_min = millisec_stamp
}
if millisec_stamp > osm_stats.timestamp_max {
osm_stats.timestamp_max = millisec_stamp
}
} | identifier_body |
provider.go | // Copyright 2016-2021, Pulumi Corporation.
package provider
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"runtime/debug"
"strings"
"time"
"github.com/golang/protobuf/ptypes/empty"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/jpillora/backoff... |
func getPulumiVersion() string {
if bi, ok := debug.ReadBuildInfo(); ok {
for _, dep := range bi.Deps {
if strings.HasPrefix(dep.Path, "github.com/pulumi/pulumi/pkg") {
return strings.TrimPrefix(dep.Version, "v")
}
}
}
// We should never get here but let's not panic and return something sensible if w... | {
result := p.getConfig("partnerName", "GOOGLE_PARTNER_NAME")
if result != "" {
return result
} else {
disablePartner := p.getConfig("disablePartnerName", "GOOGLE_DISABLE_PARTNER_NAME")
if disablePartner == "true" {
return ""
}
}
return "Pulumi"
} | identifier_body |
provider.go | // Copyright 2016-2021, Pulumi Corporation.
package provider
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"runtime/debug"
"strings"
"time"
"github.com/golang/protobuf/ptypes/empty"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/jpillora/backoff... | (_ context.Context, _ *rpc.ConstructRequest) (*rpc.ConstructResponse, error) {
return nil, status.Error(codes.Unimplemented, "Construct is not yet implemented")
}
// Call dynamically executes a method in the provider associated with a component resource.
func (p *googleCloudProvider) Call(_ context.Context, _ *rpc.Ca... | Construct | identifier_name |
provider.go | // Copyright 2016-2021, Pulumi Corporation.
package provider
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"runtime/debug"
"strings"
"time"
"github.com/golang/protobuf/ptypes/empty"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/jpillora/backoff... | return nil, err
}
// Deserialize the last known state.
oldState, err := plugin.UnmarshalProperties(req.GetOlds(), plugin.MarshalOptions{
Label: fmt.Sprintf("%s.oldState", label), SkipNulls: true,
})
if err != nil {
return nil, errors.Wrapf(err, "reading resource state")
}
resourceKey := string(urn.Type()... | inputs, err := plugin.UnmarshalProperties(req.GetNews(), plugin.MarshalOptions{
Label: fmt.Sprintf("%s.properties", label), SkipNulls: true,
})
if err != nil { | random_line_split |
provider.go | // Copyright 2016-2021, Pulumi Corporation.
package provider
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"runtime/debug"
"strings"
"time"
"github.com/golang/protobuf/ptypes/empty"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/jpillora/backoff... |
if err = uncompressed.Close(); err != nil {
return nil, errors.Wrap(err, "closing uncompress stream for metadata")
}
return &resourceMap, nil
}
// Configure configures the resource provider with "globals" that control its behavior.
func (p *googleCloudProvider) Configure(ctx context.Context,
req *rpc.ConfigureR... | {
return nil, errors.Wrap(err, "unmarshalling resource map")
} | conditional_block |
fetcher_default.go | // Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package rule
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/url"
"path/filepath"
"strings"
"sync"
"time"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"gocloud.dev/blob"
_ "gocloud.dev/blob/azureb... | // we force reading the files
done, err := w.DispatchNow()
if err != nil {
f.registry.Logger().WithError(err).WithField("file", fp).Error("Unable to read file, ignoring it.")
continue
}
go func() { <-done }() // we do not need to wait here, but we need to clear the channel
} else {
// keep w... |
f.registry.Logger().WithError(err).WithField("file", fp).Error("Unable to watch file, ignoring it.")
continue
}
| conditional_block |
fetcher_default.go | // Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package rule
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/url"
"path/filepath"
"strings"
"sync"
"time"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"gocloud.dev/blob"
_ "gocloud.dev/blob/azureb... | if err := f.updateRulesFromCache(ctx); err != nil {
f.registry.Logger().WithError(err).WithField("event_source", "local repo change").Error("Unable to update access rules.")
}
}
}
func (f *FetcherDefault) Watch(ctx context.Context) error {
f.watchLocalFiles(ctx)
getRemoteRepos := func() map[url.URL]struct{}... | f.registry.Logger().WithField("repos", f.config.Get(configuration.AccessRuleRepositories)).Info("Detected access rule repository change, processing updates.") | random_line_split |
fetcher_default.go | // Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package rule
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/url"
"path/filepath"
"strings"
"sync"
"time"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"gocloud.dev/blob"
_ "gocloud.dev/blob/azureb... |
func (f *FetcherDefault) fetchFromStorage(source url.URL) ([]Rule, error) {
ctx := context.Background()
bucket, err := f.mux.OpenBucket(ctx, source.Scheme+"://"+source.Host)
if err != nil {
return nil, err
}
defer bucket.Close()
r, err := bucket.NewReader(ctx, source.Path[1:], nil)
if err != nil {
return n... |
b, err := io.ReadAll(r)
if err != nil {
return nil, errors.WithStack(err)
}
var ks []Rule
if json.Valid(b) {
d := json.NewDecoder(bytes.NewReader(b))
d.DisallowUnknownFields()
if err := d.Decode(&ks); err != nil {
return nil, errors.WithStack(err)
}
return ks, nil
}
if err := yaml.Unmarshal(b,... | identifier_body |
fetcher_default.go | // Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package rule
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/url"
"path/filepath"
"strings"
"sync"
"time"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"gocloud.dev/blob"
_ "gocloud.dev/blob/azureb... | ctx context.Context, oldRepos, newRepos map[url.URL]struct{}) error {
repoChanged := false
for repo := range newRepos {
if _, ok := f.cache[repo.String()]; !ok {
repoChanged = true
f.registry.Logger().WithField("repo", repo.String()).Info("New repo detected, fetching access rules.")
rules, err := f.fetch(... | rocessRemoteRepoUpdate( | identifier_name |
tunnel.py | import sys
import os
import socket
import time
import struct
import select
import logging
from threading import Thread
from threading import Lock
from threading import Condition
from lowpan import util
import lowpan
##@todo Find a better home for these identifiers (controller)
RCV_SIZE_DEFAULT = 32768
LISTEN_QUEUE_S... | (self):
print(str(self))
def sample_handler(controller, msg, pkt):
"""
Sample message handler
This is the prototype for functions registered with the controller
class for packet reception
@param controller The controller calling the handler
@param msg The parsed message object
@pa... | show | identifier_name |
tunnel.py | import sys
import os
import socket
import time
import struct
import select
import logging
from threading import Thread
from threading import Lock
from threading import Condition
from lowpan import util
import lowpan
##@todo Find a better home for these identifiers (controller)
RCV_SIZE_DEFAULT = 32768
LISTEN_QUEUE_S... |
def show(self):
print(str(self))
def sample_handler(controller, msg, pkt):
"""
Sample message handler
This is the prototype for functions registered with the controller
class for packet reception
@param controller The controller calling the handler
@param msg The parsed message ... | string = "Controller:\n"
string += " state " + self.dbg_state + "\n"
string += " switch_addr " + str(self.switch_addr) + "\n"
string += " pending pkts " + str(len(self.packets)) + "\n"
string += " total pkts " + str(self.packets_total) + "\n"
string += "... | identifier_body |
tunnel.py | import sys
import os
import socket
import time
import struct
import select
import logging
from threading import Thread
from threading import Lock
from threading import Condition
from lowpan import util
import lowpan
##@todo Find a better home for these identifiers (controller)
RCV_SIZE_DEFAULT = 32768
LISTEN_QUEUE_S... |
if resp is None:
self.logger.warning("No response for xid " + str(self.xid))
return (resp, pkt)
def message_send(self, msg):
"""
Send the message to the switch
@param msg A string or OpenFlow message object to be forwarded to
the switch.
"""
... | (resp, pkt) = (None, None) | conditional_block |
tunnel.py | import sys
import os
import socket
import time
import struct
import select
import logging
from threading import Thread
from threading import Lock
from threading import Condition
from lowpan import util
import lowpan
##@todo Find a better home for these identifiers (controller)
RCV_SIZE_DEFAULT = 32768
LISTEN_QUEUE_S... | Class abstracting the control interface to the switch.
For receiving messages, two mechanism will be implemented. First,
query the interface with poll. Second, register to have a
function called by message type. The callback is passed the
message type as well as the raw packet (or message object... | class VirtualTunnel(Thread):
""" | random_line_split |
data.py | #!/usr/bin/env python2.7
import re
import string
from collections import defaultdict, namedtuple
from functools import partial
from itertools import count
from progressbar import ProgressBar
from hashlib import sha1
from math import log10
import os
import sys
LOGZERO = -sys.maxint - 1
exp = partial(pow, 10)
log = lamb... | s = float(sum(a))
for i in a:
a[i] /= s | identifier_body | |
data.py | #!/usr/bin/env python2.7
import re
import string
from collections import defaultdict, namedtuple
from functools import partial
from itertools import count
from progressbar import ProgressBar
from hashlib import sha1
from math import log10
import os
import sys
LOGZERO = -sys.maxint - 1
exp = partial(pow, 10)
log = lamb... | log_prob = log(gram_count) - log(prev_gram_count)
elif self.smoothing == 'ls':
log_prob = log(gram_count + self.lmbd) - log(prev_gram_count + self.lmbd * self.voc_size)
elif self.smoothing == 'wb':
z = self.voc_size - num_types_after
if gram_count == 0... | else: | random_line_split |
data.py | #!/usr/bin/env python2.7
import re
import string
from collections import defaultdict, namedtuple
from functools import partial
from itertools import count
from progressbar import ProgressBar
from hashlib import sha1
from math import log10
import os
import sys
LOGZERO = -sys.maxint - 1
exp = partial(pow, 10)
log = lamb... | (x, y):
x,y = max(x,y), min(x,y)
if y <= LOGZERO:
return x
negdiff = y-x
return x + log(1 + exp(negdiff))
class LanguageModel(object):
def __init__(self, n):
self.smoothing = None
self.interpolate = False
self.lmbd = 0
self.models = defaultdict(dict)
... | add_log | identifier_name |
data.py | #!/usr/bin/env python2.7
import re
import string
from collections import defaultdict, namedtuple
from functools import partial
from itertools import count
from progressbar import ProgressBar
from hashlib import sha1
from math import log10
import os
import sys
LOGZERO = -sys.maxint - 1
exp = partial(pow, 10)
log = lamb... |
else:
log_prob = log(gram_count) - log(num_tokens_after + num_types_after)
else:
raise Exception('Invalid smoothing %s' % self.smoothing)
return log_prob
def _calculate_interpolated_prob(self, gram, log_lmbds):
return reduce(add_log, (log_lmbds[k] +... | if num_types_after == 0:
log_prob = LOGZERO
else:
log_prob = log(num_types_after) - (log(z) + log(num_tokens_after + num_types_after)) | conditional_block |
lptim.rs | //! Low-Power Timer (LPTIM) support.
use crate::gpio::{self, gpiob};
use crate::hal;
use crate::pac::LPTIM;
use crate::pwr::PWR;
use crate::rcc::{Enable, Rcc, Reset};
use cast::{u32, u64};
use core::convert::TryFrom;
use core::marker::PhantomData;
use embedded_time::duration::Microseconds;
use embedded_time::rate::Her... | {
/// Drive LPTIM with APB1 clock.
Apb1 = 0b00,
/// Drive LPTIM with Low-Speed Internal (LSI) clock.
///
/// The user has to ensure that the LSI clock is running, or the timer won't
/// start counting.
Lsi = 0b01,
/// Drive LPTIM with Internal 16 MHz clock.
Hsi16 = 0b10,
/// ... | ClockSrc | identifier_name |
lptim.rs | //! Low-Power Timer (LPTIM) support.
use crate::gpio::{self, gpiob};
use crate::hal;
use crate::pac::LPTIM;
use crate::pwr::PWR;
use crate::rcc::{Enable, Rcc, Reset};
use cast::{u32, u64};
use core::convert::TryFrom;
use core::marker::PhantomData;
use embedded_time::duration::Microseconds;
use embedded_time::rate::Her... |
}
impl LpTimer<Encoder> {
/// Initializes the Low-Power Timer in encoder mode.
///
/// The `start` method must be called to enable the encoder input.
pub fn init_encoder(
lptim: LPTIM,
pwr: &mut PWR,
rcc: &mut Rcc,
clk: ClockSrc,
(pb5, pb7): (gpiob::PB5<gpio::An... | {
Self::init(lptim, pwr, rcc, clk)
} | identifier_body |
lptim.rs | //! Low-Power Timer (LPTIM) support.
use crate::gpio::{self, gpiob};
use crate::hal;
use crate::pac::LPTIM;
use crate::pwr::PWR;
use crate::rcc::{Enable, Rcc, Reset};
use cast::{u32, u64};
use core::convert::TryFrom;
use core::marker::PhantomData;
use embedded_time::duration::Microseconds;
use embedded_time::rate::Her... | // The slowest LPTIM clock source is LSE at 32768 Hz, the fastest CPU clock is ~80 MHz. At
// these conditions, one cycle of the LPTIM clock takes 2500 CPU cycles, so sleep for 5000.
cortex_m::asm::delay(5000);
// ARR can only be changed while the timer is *en*abled
self.lptim.a... |
self.lptim.cr.write(|w| w.enable().set_bit());
// "After setting the ENABLE bit, a delay of two counter clock is needed before the LPTIM is
// actually enabled." | random_line_split |
thread.go | package runtime
import (
"errors"
"sync"
"unsafe"
)
// ThreadStatus is the type of a thread status
type ThreadStatus uint
// Available statuses for threads.
const (
ThreadOK ThreadStatus = 0 // Running thread
ThreadSuspended ThreadStatus = 1 // Thread has yielded and is waiting to be resumed
ThreadDead ... |
t.caller = caller
t.status = ThreadOK
t.mux.Unlock()
caller.mux.Unlock()
t.sendResumeValues(args, nil, nil)
return caller.getResumeValues()
}
// Close a suspended thread. If successful, its status switches to dead. The
// boolean returned is true if it was possible to close the thread (i.e. it was
// suspende... | {
panic("Caller of thread to resume is not running")
} | conditional_block |
thread.go | package runtime
import (
"errors"
"sync"
"unsafe"
)
// ThreadStatus is the type of a thread status
type ThreadStatus uint
// Available statuses for threads.
const (
ThreadOK ThreadStatus = 0 // Running thread
ThreadSuspended ThreadStatus = 1 // Thread has yielded and is waiting to be resumed
ThreadDead ... |
// Truncate the close stack to size h, calling the __close metamethods in the
// context of the given continuation c and feeding them with the given error.
func (t *Thread) cleanupCloseStack(c Cont, h int, err error) error {
closeStack := &t.closeStack
for closeStack.size() > h {
v, _ := closeStack.pop()
if Tru... | {
sz := len(s.stack)
if sz > h {
s.stack = s.stack[:h]
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.