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 |
|---|---|---|---|---|
pipeline.py | (img):
new_img = cv2.GaussianBlur(img, (3,3), 0)
#new_img = cv2.cvtColor(new_img, cv2.COLOR_YUV2RGB)
new_img = cv2.cvtColor(new_img, cv2.COLOR_RGB2HSV)
new_img = np.array(new_img, dtype = np.float64)
#Generate new random brightness
random_bright = .5+random.uniform(0.3,1.0)
new_img[:,:,2] = random_... | augment_image | identifier_name | |
pipeline.py | 1, 2, or "ALL"
spatial_size = (32, 32) # Spatial binning dimensions
hist_bins = 32 # Number of histogram bins
spatial_feat = True # Spatial features on or off
hist_feat = True # Histogram features on or off
hog_feat = True # HOG features on or off
y_start_stop = [400, 656] # Min and max in y to search in slide_windo... | output = "tracked2_" + video
input_clip = VideoFileClip(video)
clip = input_clip.fl_image(find_vehicles_in_frame)
#clip = input_clip.fl_image(save_image)
clip.write_videofile(output, audio=False) | identifier_body | |
pipeline.py | 1.0)
new_img[:,:,2] = random_bright*new_img[:,:,2]
new_img[:,:,2][new_img[:,:,2]>255] = 255
new_img = np.array(new_img, dtype = np.uint8)
#Convert back to RGB colorspace
new_img = cv2.cvtColor(new_img, cv2.COLOR_HSV2RGB)
#new_img = cv2.cvtColor(new_img, cv2.COLOR_RGB2YUV)
return new_img
# Rea... |
if history:
hist3 = history.popleft()
if history:
hist4 = history.popleft()
if | hist2 = history.popleft() | conditional_block |
pipeline.py | 1.0)
new_img[:,:,2] = random_bright*new_img[:,:,2]
new_img[:,:,2][new_img[:,:,2]>255] = 255
new_img = np.array(new_img, dtype = np.uint8)
#Convert back to RGB colorspace
new_img = cv2.cvtColor(new_img, cv2.COLOR_HSV2RGB)
#new_img = cv2.cvtColor(new_img, cv2.COLOR_RGB2YUV)
return new_img
# Rea... |
#hot_windows = search_windows(image, windows, svc, X_scaler, color_space=color_space,
# spatial_size=spatial_size, hist_bins=hist_bins,
# orient=orient, pix_per_cell=pix_per_cell,
# cell_per_block=cell_per_block,
# hog_chan... | # image you are searching is a .jpg (scaled 0 to 255)
#image = image.astype(np.float32)/255
#windows = slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop,
# xy_window=(96, 96), xy_overlap=(0.5, 0.5)) | random_line_split |
app.rs | Entry
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Action {
About,
Quit,
ClickToggle(ToggleButtonState)
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ToggleButtonState {
State1,
State2,
}
impl<'a> From<&'a glib::Variant> for ToggleButtonState {
fn from(v: &glib::Variant) ... |
}
impl Action {
// The full action name as is used in e.g. menu models
pub fn full_name(self) -> &'static str {
match self {
Action::About => "app.about",
Action::Quit => "app.quit",
Action::ClickToggle(_) => "app.toggle",
}
}
// Create our applica... | {
eprintln!("Shutting down the whole thing");
} | identifier_body |
app.rs | ::Entry
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Action {
About,
Quit,
ClickToggle(ToggleButtonState)
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ToggleButtonState {
State1,
State2,
}
impl<'a> From<&'a glib::Variant> for ToggleButtonState {
fn from(v: &glib::Variant... | let payload_row = gtk::Box::new(gtk::Orientation::Horizontal, 5);
payload_row.set_sensitive(false);
payload_row.add(&payload_title);
payload_row.pack_start(&payload_input, true, true, 0);
// when POST is selected, activate the payload input box
// TODO: why don't I need ... | let payload_title = gtk::Label::new(None);
payload_title.set_markup("<big>Payload</big>");
let payload_input = gtk::Entry::new();
payload_input.insert_text(r#"ex. {"k": "key","v": "val"}"#, &mut 0);
payload_input.set_sensitive(false); | random_line_split |
app.rs | ::Entry
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Action {
About,
Quit,
ClickToggle(ToggleButtonState)
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ToggleButtonState {
State1,
State2,
}
impl<'a> From<&'a glib::Variant> for ToggleButtonState {
fn | (v: &glib::Variant) -> ToggleButtonState {
v.get::<bool>().expect("Invalid record state type").into()
}
}
impl From<bool> for ToggleButtonState {
fn from(v: bool) -> ToggleButtonState {
match v {
false => ToggleButtonState::State1,
true => ToggleButtonState::State2,
... | from | identifier_name |
footprint_analysis.rs | an instruction
register_writes_ignored: HashSet<Name>,
/// A store is any instruction with a WriteMem event
is_store: bool,
/// A load is any instruction with a ReadMem event
is_load: bool,
/// A branch is any instruction with a Branch event
is_branch: bool,
/// An exclusive is any even... |
}
impl Cacheable for Footprint {
type Key = Footprintkey;
}
impl Footprint {
fn new() -> Self {
Footprint {
write_data_taints: (HashSet::new(), false),
mem_addr_taints: (HashSet::new(), false),
branch_addr_taints: (HashSet::new(), false),
register_reads... | {
format!("opcode_{}", self.opcode)
} | identifier_body |
footprint_analysis.rs | an instruction
register_writes_ignored: HashSet<Name>,
/// A store is any instruction with a WriteMem event
is_store: bool,
/// A load is any instruction with a ReadMem event
is_load: bool,
/// A branch is any instruction with a Branch event
is_branch: bool,
/// An exclusive is any even... | <B: BV>(from: usize, to: usize, instrs: &[B], footprints: &HashMap<B, Footprint>) -> bool {
if from >= to {
return false;
}
let touched = touched_by(from, to, instrs, footprints);
for reg in &footprints.get(&instrs[to]).unwrap().write_data_taints.0 {
if touched.contains(reg) {
... | data_dep | identifier_name |
footprint_analysis.rs | an instruction
register_writes_ignored: HashSet<Name>,
/// A store is any instruction with a WriteMem event
is_store: bool,
/// A load is any instruction with a ReadMem event
is_load: bool,
/// A branch is any instruction with a Branch event
is_branch: bool,
/// An exclusive is any even... |
let to_footprint = footprints.get(&instrs[to]).unwrap();
to_footprint.is_exclusive && to_footprint.is_store
}
/// The set of registers that could be (syntactically) touched by the
/// first instruction before reaching the second.
#[allow(clippy::needless_range_loop)]
fn touched_by<B: BV>(
from: usize,
... | random_line_split | |
footprint_analysis.rs | an instruction
register_writes_ignored: HashSet<Name>,
/// A store is any instruction with a WriteMem event
is_store: bool,
/// A load is any instruction with a ReadMem event
is_load: bool,
/// A branch is any instruction with a Branch event
is_branch: bool,
/// An exclusive is any even... |
}
let to_footprint = footprints.get(&instrs[to]).unwrap();
to_footprint.is_exclusive && to_footprint.is_store
}
/// The set of registers that could be (syntactically) touched by the
/// first instruction before reaching the second.
#[allow(clippy::needless_range_loop)]
fn touched_by<B: BV>(
from: usi... | {
return false;
} | conditional_block |
express.js | eg2_query_parameter = () => {
app.get('/', (req, res) => {
console.log('query: all')
console.log('--------------------')
console.log(req.query)
console.log('query: one by one')
console.log('--------------------')
for (const key in req.query) {
console.log... | else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.get('/with-cors', cors(corsOptions), (req, res, next) => {
res.json({ msg: 'WHOAH with CORS it works!' });
});
app.listen(3000, () => console.log('Server ready'))
};
eg9_prefligth = () => {
//al... | {
callback(null, true)
} | conditional_block |
express.js | eg2_query_parameter = () => {
app.get('/', (req, res) => {
console.log('query: all')
console.log('--------------------')
console.log(req.query)
console.log('query: one by one')
console.log('--------------------')
for (const key in req.query) {
console.log... | res.end()
});
app.listen(3000)
};
eg3_post_query = () => {
// for Content-Type: application/json
// if header =
app.use(express.json());
// for Content-Type: application/x-www-form-urlencoded
// if header =
app.use(express.urlencoded());
app.post('/form', (req, res) => {
... | console.log('--------------------') | random_line_split |
orchestrator.go | actual workload is. It then tries to fix the delta.
//
// The expected task list can be altered via AddTask, RemoveTask and
// UpdateTasks. Each method is safe to be called on multiple go-routines.
type Orchestrator struct {
log Logger
s func(TermStats)
timeout time.Duration
mu sync.Mutex
wo... | {
return
} | conditional_block | |
orchestrator.go | Actual(ctx)
toAdd, toRemove := o.delta(actual)
// Rebalance tasks among workers.
toAdd, toRemove = rebalance(toAdd, toRemove, actual)
counts := counts(actual, toRemove)
for worker, tasks := range toRemove {
for _, task := range tasks {
// Remove the task from the workers.
removeCtx, _ := context.WithTime... | {
o.mu.Lock()
defer o.mu.Unlock()
o.expectedTasks = tasks
} | identifier_body | |
orchestrator.go | to the cluster
// to see what the actual workload is. It then tries to fix the delta.
//
// The expected task list can be altered via AddTask, RemoveTask and
// UpdateTasks. Each method is safe to be called on multiple go-routines.
type Orchestrator struct {
log Logger
s func(TermStats)
timeout time.Durat... | }
o.s(TermStats{
WorkerCount: len(actual),
})
}
// collectActual reaches out to each worker and gets their state of the world.
// Each worker is queried in parallel. If a worker returns an error while
// trying to list the tasks, it will be logged and not considered for what
// workers should be assigned work.
f... | history,
)
} | random_line_split |
orchestrator.go | .Printf("Error trying to list tasks from %s: %s", err.worker, err.err)
case <-t.C:
o.log.Printf("Communicator timeout. Using results available...")
break
}
}
o.lastActual = state
return actual
}
// delta finds what should be added and removed to make actual match the
// expected.
func (o *Orchestrator) d... | contains | identifier_name | |
warnings.go | 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
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See... | func isOldEnough(t time.Time, threshold time.Duration) bool {
return t.UTC().Add(threshold).Before(time.Now().UTC())
}
func completionWarning(credentials string, recommendedCompletionInterval time | }
return isOldEnough(lastInitiationFinishedTime.Time, threshold)
}
| random_line_split |
warnings.go | utils "github.com/gardener/gardener/pkg/utils/version"
)
// GetWarnings returns warnings for the provided shoot.
func GetWarnings(_ context.Context, shoot, oldShoot *core.Shoot, credentialsRotationInterval time.Duration) []string {
if shoot == nil {
return nil
}
var warnings []string
if pointer.BoolDeref(shoot... | {
if !helper.IsWorkerless(shoot) && shoot.Spec.Kubernetes.KubeAPIServer != nil {
for _, plugin := range shoot.Spec.Kubernetes.KubeAPIServer.AdmissionPlugins {
if plugin.Name == "PodSecurityPolicy" && pointer.BoolDeref(plugin.Disabled, false) {
return ""
}
}
}
return "you should consider migrating to P... | identifier_body | |
warnings.go | 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
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See... |
return warnings
}
func getWarningsForDueCredentialsRotations(shoot *core.Shoot, credentialsRotationInterval time.Duration) []string {
if !isOldEnough(shoot.CreationTimestamp.Time, credentialsRotationInterval) {
return nil
}
if shoot.Status.Credentials == nil || shoot.Status.Credentials.Rotation == nil {
ret... | {
warnings = append(warnings, fmt.Sprintf("annotation %v is deprecated. Use field `.spec.systemComponents.nodeLocalDNS.forceTCPToUpstreamDNS` in Shoot instead.", v1beta1constants.AnnotationNodeLocalDNSForceTcpToUpstreamDns))
} | conditional_block |
warnings.go | 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
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See... | (shoot *core.Shoot, credentialsRotationInterval time.Duration) []string {
if !isOldEnough(shoot.CreationTimestamp.Time, credentialsRotationInterval) {
return nil
}
if shoot.Status.Credentials == nil || shoot.Status.Credentials.Rotation == nil {
return []string{"you should consider rotating the shoot credentials... | getWarningsForDueCredentialsRotations | identifier_name |
train_gcn.py | permissions and
#limitations under the License.
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
import glob
import functools
import pickle
import argparse
import numpy as np
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.python.keras.o... | loss_weights[0] = args.seg_weight | conditional_block | |
train_gcn.py | KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
import glob
import functools
import pickle
import argparse
import numpy as np
from sklearn.model_sel... | """# Build the model"""
model = DeformNet(args.batch_size, img_shape, mesh_info, amplify_factor=args.amplify_factor,num_mesh=len(args.mesh_ids), num_seg=args.num_seg)
unet_gcn = model.build_keras()
unet_gcn.summary(line_length=150)
adam = Adam(lr=args.lr, beta_1=0.9, beta_2=0.999, epsilon=None, decay=1e-6, amsgrad=Tru... | num_train_examples = train_ds_num[np.argmax(train_data_weights)]/np.max(train_data_weights)
num_val_examples = val_ds_num[np.argmax(val_data_weights)]/np.max(val_data_weights)
print("Number of train, val samples after reweighting: ", num_train_examples, num_val_examples)
| random_line_split |
mod.rs | following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// F... | &self, new_origin: Vector3<f32>) {
self.origin.set(new_origin);
}
pub fn set_left_ear(&self, new_origin: Vector3<f32>) {
self.left_ear.set(new_origin);
}
pub fn set_right_ear(&self, new_origin: Vector3<f32>) {
self.right_ear.set(new_origin);
}
pub fn attenuate(
... | et_origin( | identifier_name |
mod.rs | following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// F... | };
use thiserror::Error;
use chrono::Duration;
pub const DISTANCE_ATTENUATION_FACTOR: f32 = 0.001;
const MAX_ENTITY_CHANNELS: usize = 128;
#[derive(Error, Debug)]
pub enum SoundError {
#[error("No such music track: {0}")]
NoSuchTrack(String),
#[error("I/O error: {0}")]
Io(#[from] io::Error),
#[err... | use cgmath::{InnerSpace, Vector3};
use rodio::{
source::{Buffered, SamplesConverter},
Decoder, OutputStreamHandle, Sink, Source, | random_line_split |
mod.rs | following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// F... |
// keep track of which sound started the earliest
match self.channels[oldest] {
Some(ref o) => {
if chan.start_time < o.start_time {
oldest = i;
}
... |
let mut oldest = 0;
for (i, channel) in self.channels.iter().enumerate() {
match *channel {
Some(ref chan) => {
// if this channel is free, return it
if !chan.channel.in_use() {
return i;
}
... | identifier_body |
mod.rs | following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// F... |
// replace sounds on the same entity channel
if ent_channel != 0
&& chan.ent_id == ent_id
&& (chan.ent_channel == ent_channel || ent_channel == -1)
{
return i;
}
... |
return i;
}
| conditional_block |
dropck.rs | cx, self_type_node_id);
tcx.infer_ctxt(None, Some(impl_param_env), Reveal::NotSpecializable).enter(|infcx| {
let tcx = infcx.tcx;
let mut fulfillment_cx = traits::FulfillmentContext::new();
let named_type = tcx.lookup_item_type(self_type_did).ty;
let named_type = named_type.subst(tc... | // definition yields the instantiated assumptions:
//
// ['y : 'z]
//
// We then check all of the predicates of the Drop impl:
//
// ['y:'z, 'x:'y]
//
// and ensure each is in the list of instantiated
// assumptions. Here, `'y:'z` is present, but `'x:'y` is
// absent.... | // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
//
// Applying this to the predicates (i.e. assumptions) provided by the item | random_line_split |
dropck.rs | if let Err(_) = infcx.eq_types(true, infer::TypeOrigin::Misc(drop_impl_span),
named_type, fresh_impl_self_ty) {
let item_span = tcx.map.span(self_type_node_id);
struct_span_err!(tcx.sess, drop_impl_span, E0366,
"Implemen... | {
let tcx = ccx.tcx;
let drop_impl_node_id = tcx.map.as_local_node_id(drop_impl_did).unwrap();
let self_type_node_id = tcx.map.as_local_node_id(self_type_did).unwrap();
// check that the impl type can be made to match the trait type.
let impl_param_env = ty::ParameterEnvironment::for_item(tcx, sel... | identifier_body | |
dropck.rs | specialized")
.span_note(item_span,
"Use same sequence of generic type and region \
parameters that is on the struct/enum definition")
.emit();
return Err(());
}
if let Err(ref errors) = fulfillment_cx.s... | Error | identifier_name | |
dropck.rs | _necessary<'a, 'gcx, 'tcx>(
rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>,
typ: ty::Ty<'tcx>,
span: Span,
scope: region::CodeExtent)
{
debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}",
typ, scope);
let parent_scope = rcx.tcx.region_maps.opt_encl_scope(scope).unwrap_or_el... | {
def.is_dtorck(tcx)
} | conditional_block | |
views.py | .objects.filter(username=username).first() # 当前对象
print('user', user)
if not user: # 判断是否已经存在
return render(request, 'not_exit.html', locals())
# 当前站点对象
blog = user.blog
# 查询当前站点的每一个分类名称以及对应文章数
c_articles = Category.objects.filter(blog_id=blog.nid).values('title').annotate(c=Count('art... | if validcode.upper() == valid_code.upper(): # 首先校验验证码,验证码不区分大小写
ret = auth.authenticate(username=user, password=pwd) | random_line_split | |
views.py | _articles,t_articles,c_t_articles,articles
:param request:
:param username:
:return:
"""
user = UserInfo.objects.filter(username=username).first() # 当前对象
print('user', user)
if not user: # 判断是否已经存在
return render(request, 'not_exit.html', locals())
# 当前站点对象
blog = user.blog
... | .filter(user_id=user_id, article_id=article_id).first()
response = {'state': False, 'msg': None}
if not obj: # 该用户没对本文章进行操作
ArticleUpDown.objects.create(is_up=is_up, article_id=article_id, user_id=user_id)
queryset = Article.objects.filter(pk=article_id)
if is_up: # 更新文章的数据
... | render(request, 'article_detail.html', locals())
def digg(request):
"""
点赞
:param request:
:return:
"""
is_up = json.loads(request.POST.get('is_up')) # 反序列化
user_id = request.user.pk
article_id = request.POST.get('article_id')
obj = ArticleUpDown.objects | identifier_body |
views.py | ,t_articles,c_t_articles,articles
:param request:
:param username:
:return:
"""
user = UserInfo.objects.filter(username=username).first() # 当前对象
print('user', user)
if not user: # 判断是否已经存在
return render(request, 'not_exit.html', locals())
# 当前站点对象
blog = user.blog
# 查询当... | ticle_edit(request, article_id):
"""
编辑修改某一篇文章
:param request:
:return:
"""
article_id = article_id
article_obj = Article.objects.filter(nid=article_id).first()
return render(request, 'article_edit.html', locals())
def article_update(request):
username = request.user.username
i... |
def ar | identifier_name |
views.py | if condition == 'category':
articles = Article.objects.filter(user=user).filter(category__title=param)
if condition == 'tag':
articles = Article.objects.filter(user=user).filter(tags__title=param)
if condition == 'archive':
year, month ... | conditional_block | ||
ui.rs | : i32);
fn set_progress_enabled(&mut self, enabled: bool);
// Environment information
fn program_name(&self) -> &str;
// Write/Print interface
fn will_print(&self, verbosity: i32) -> bool;
fn print(&self, verbosity: i32, message: &str) -> Fallible<()>;
fn print_error(&self, err: &Error) ->... |
Ok(())
}
fn println_interactive(&self, message: &str) -> Fallible<()> {
if self.will_print(INTERACTIVE_VERBOSITY) {
writeln!(self.output.borrow_mut(), "{}", message)?;
}
Ok(())
}
fn println_progress(&self, verbosity: i32, message: &str, finish: bool) -> Fal... | {
writeln!(self.output.borrow_mut(), "{}: {}", self.program_name, err)?;
} | conditional_block |
ui.rs | : i32);
fn set_progress_enabled(&mut self, enabled: bool);
// Environment information
fn program_name(&self) -> &str;
// Write/Print interface
fn will_print(&self, verbosity: i32) -> bool;
fn print(&self, verbosity: i32, message: &str) -> Fallible<()>;
fn print_error(&self, err: &Error) ->... |
pub fn expect_prompt(
self,
matcher: impl AsRef<str>,
reply: Result<impl AsRef<str>, Error>,
) -> Self {
self.prompt_replies.borrow_mut().push_back((
Some(matcher.as_ref().to_string()),
reply.map(|s| s.as_ref().to_string()... | {
TestUI {
..Default::default()
}
} | identifier_body |
ui.rs | : i32);
fn set_progress_enabled(&mut self, enabled: bool);
// Environment information
fn program_name(&self) -> &str;
// Write/Print interface
fn will_print(&self, verbosity: i32) -> bool;
fn print(&self, verbosity: i32, message: &str) -> Fallible<()>;
fn print_error(&self, err: &Error) ->... | }
}
impl UI for TestUI {
fn set_verbosity(&mut self, _verbosity: i32) {}
fn set_progress_enabled(&mut self, _enabled: bool) {}
fn program_name(&self) -> &str {
"rypt"
}
// Write interface
fn will_print(&self, _verbosity: i32) -> bool {
... | }
printed_lines.extend(line_tuples);
Ok(()) | random_line_split |
ui.rs | : i32);
fn set_progress_enabled(&mut self, enabled: bool);
// Environment information
fn program_name(&self) -> &str;
// Write/Print interface
fn will_print(&self, verbosity: i32) -> bool;
fn print(&self, verbosity: i32, message: &str) -> Fallible<()>;
fn print_error(&self, err: &Error) ->... | (&self) -> bool {
self.input.borrow().is_some()
&& self.input_is_tty
&& self.output_is_tty
&& self.will_print(INTERACTIVE_VERBOSITY)
}
fn read_prompt(&self, prompt: &str) -> Fallible<String> {
ensure!(self.can_read(), "Can't read from a non-TTY input");
... | can_read | identifier_name |
electronics.py | -connector.length
for z in posses:
self.surface.blit(con2,(z,0))#top
self.surface.blit(con4,(z,self.dis))#bottom
self.surface.blit(con3, (0, z))#left
self.surface.blit(con1, (self.dis, z))#right
self.interfaces = poss... |
ys = min(levels)
ye = size[1]#max(levels)+chiplength
bar = repeat(tilemap["v"], (5, ye-ys+minstraight))
for x in barlines:
self.surface.blit(bar, (x-1, ys-minstraight))
######Chips######
[self.surface.blit(chip.surface, pos) for pos in self.chipposs]
... | self.surface.blit(bar, (xs-minstraight, y-1)) | conditional_block |
electronics.py | -connector.length
for z in posses:
self.surface.blit(con2,(z,0))#top
self.surface.blit(con4,(z,self.dis))#bottom
self.surface.blit(con3, (0, z))#left
self.surface.blit(con1, (self.dis, z))#right
self.interfaces = poss... | def save_images(self):
for name, surface in self.tiles.items():
P.image.save(surface, "_ |
def __getitem__(self, key):
return self.tiles[key]
| random_line_split |
electronics.py |
con1,con2,con3,con4 = connector.surfaces
posses = tuple(range(connector.indent+rest//2, connector.indent+innerlength-rest//2, ele))
self.dis = length-connector.length
for z in posses:
self.surface.blit(con2,(z,0))#top
self.surface.blit(co... | def __init__(self, length, connector, innercolor = P.Color(50,50,50), deviation = 3, bordercolor = P.Color(150,150,150)):
size = length,length
rect = P.Rect((0,0), size)
innerrect = rect.inflate(-connector.indent*2,-connector.indent*2)
self.surface = P.Surface(size, flags = P.SR... | identifier_body | |
electronics.py | -connector.length
for z in posses:
self.surface.blit(con2,(z,0))#top
self.surface.blit(con4,(z,self.dis))#bottom
self.surface.blit(con3, (0, z))#left
self.surface.blit(con1, (self.dis, z))#right
self.interfaces = poss... | ():
def __init__(self, grid,amount, speed, color = (250,250,100)):
self.grid = grid
connections = []
for node in grid.nodes.values():
connections.extend(node.connections)
for c in connections:
c.direction.length = speed
c.scale_time(speed)... | AnimFizzle | identifier_name |
SL1_ImportData.py | -----------<<< Setting constant values that are to be used inside function >>>----------- #
DatasetName = config['BigQueryConfig']['DatasetName']
SIDs = ast.literal_eval(config['DomainConfig']['SIDs'])
DataGrabMethodology = config['DomainConfig']['UseStaticOrDynamicCurrentDay']
LevBasedPrint('Inside ... | for i in range(1000): ##even if the bin size is as small as an hour, BQ has a limitation of accessing upto a max of 1000 Table, so this is the max possible limit
ll_insec = int(i*BinSizeBasedOnPeriod_Hr *3600)
ul_insec = int((i+1)*BinSizeBasedOnPeriod_Hr *3600 - 1)
GroupsToI... | '''
Incase if dataset size is too large then this function will enable the extraction of whole dataset by getting the data in chunks
'''
# -----------<<< Setting constant values that are to be used inside function >>>----------- #
ModuleSetting = config['Config']['ModuleSettingRuleName']
BQ_Cred =... | identifier_body |
SL1_ImportData.py | -----------<<< Setting constant values that are to be used inside function >>>----------- #
DatasetName = config['BigQueryConfig']['DatasetName']
SIDs = ast.literal_eval(config['DomainConfig']['SIDs']) | StaDataWindow = ast.literal_eval(config['IfStatic']['DataGrabWindow_Days'])
elif DataGrabMethodology == 'dynamic':
DynDataWindow = int(ast.literal_eval(config['IfDynamic']['DataGrabWindow_Hr']))
else:
txt = 'Exception: Wrong Configuration has been passed in "UseStaticOrDynamicCurrentDay"... | DataGrabMethodology = config['DomainConfig']['UseStaticOrDynamicCurrentDay']
LevBasedPrint('Inside "'+GenerateTableNames.__name__+'" function and configurations for this has been set.',3,1)
LevBasedPrint('Data collection methodology that has been selected : ' + str(DataGrabMethodology),3)
if DataGrabMet... | random_line_split |
SL1_ImportData.py | -----------<<< Setting constant values that are to be used inside function >>>----------- #
DatasetName = config['BigQueryConfig']['DatasetName']
SIDs = ast.literal_eval(config['DomainConfig']['SIDs'])
DataGrabMethodology = config['DomainConfig']['UseStaticOrDynamicCurrentDay']
LevBasedPrint('Inside ... | (config):
"""
Can be used to import data from either storage or BQ
Extracts any size data from any SID of any number of days.
Works in Two Configuration(config['IterationAim']['CycleType']), namely 'TrainTest' & 'GlTest'
'TrainTest' is for models training purpose where This Dataset is... | ImportData | identifier_name |
SL1_ImportData.py | -----------<<< Setting constant values that are to be used inside function >>>----------- #
DatasetName = config['BigQueryConfig']['DatasetName']
SIDs = ast.literal_eval(config['DomainConfig']['SIDs'])
DataGrabMethodology = config['DomainConfig']['UseStaticOrDynamicCurrentDay']
LevBasedPrint('Inside ... |
except Exception as error:
txt = 'Exception: In importing data from BQ was thrown!\nLimit used: ' + str(i) + '\n' + str(error)
LevBasedPrint(txt, 2)
AddRecommendation(txt, config)
# raise Exception(txt)
# ----------------------------... | LevBasedPrint('Setting used in extracting data from BQ:\tNo. of obs. extracted per cycle (limit) = ' + str(i) + '\tOffset = ' + str(offcurr),2)
QueryToUse = query.format(BinToUse = GroupsToInclude, TableToInclude = TableToInclude, lim = str(i), off = str(offcurr))
tempDF = Exec_B... | conditional_block |
resnet.rs | , osize, osize], x!(bias(i0)));
// let b = f.comp("B", x![oc, osize, osize, ic, kern, kern], x!(0f32));
// b.set_expr(x!(a_pad(i3, i1 * stride + i4, i2 * stride + i5) * w(i0, i3, i4, i5) + b(i0, i1, i2, i3, i4, i5)));
// let (b_final, add) = if add != 0 { // add-relu
// let add = f.buf("ADD", F32, In, x![oc, ... | > (im | identifier_name | |
resnet.rs | _i, ff_o_i, ff_i, yy_o_o_o, yy_o_o_i, yy_o_i, yy_i, xx_o_o_o, xx_o_o_i, xx_o_i, xx_i
b_final.reorder_n(&[(0, 0), (1, 4), (2, 8), (3, 1), (4, 5), (5, 9), (6, 2), (7, 6), (8, 10), (9, 3), (10, 7), (11, 11), ]);
// ff_o_o_o, yy_o_o_o, xx_o_o_o, ff_o_o_i, yy_o_o_i, xx_o_o_i, ff_o_i, yy_o_i, xx_o_i, ff_i, yy_i, xx_i... | let f = Func::new("avgpool");
let a = f.buf("A", F32, In, x![chan, size, size]);
let buf_b = f.buf("B", F32, Out, x![chan,]); | random_line_split | |
resnet.rs | bias, x, *b].as_ptr()); } else { (lib.f)([i, *w, *bias, *b].as_ptr()); }
}, b1)
}
// naive版本,能跑但很慢
// fn conv(ic: u32, oc: u32, size: u32, kern: u32, stride: u32, pad: u32, add: u32, relu: u32)
// -> (impl Fn(M, Option<M>), M) {
// println!("ic: {}, oc: {}, size: {}, kern: {}, stride: {}, pad: {}", ic, oc, size,... | conditional_block | ||
resnet.rs | a(i0, i1 - pad, i2 - pad) } else { 0f32 }));
// a_pad.set_inline(true);
//
// let b_init = f.comp("B_init", x![oc, osize, osize], x!(bias(i0)));
// let b = f.comp("B", x![oc, osize, osize, ic, kern, kern], x!(0f32));
// b.set_expr(x!(a_pad(i3, i1 * stride + i4, i2 * stride + i5) * w(i0, i3, i4, i5) + b(i0, i1,... | anes != planes * expansion;
if bottleneck {
let (f1, b1) = conv(inplanes, planes, size, 1, stride, 0, 0, 1);
let (f2, b2) = conv(planes, planes, size / stride, 3, 1, 1, 0, 1);
let (f3, b3) = conv(planes, planes * expansion, size / stride, 1, 1, 0, 1, 1);
let f4 = if downsample { Some(conv(inplanes, pl... | identifier_body | |
ClassifierAdapter.py | .DataObjects import *
def get_emotion_by_id(id):
if id == 1:
return 'Anger'
elif id == 2:
return 'Disgust'
elif id == 3:
return 'Sad'
elif id == 4:
return 'Happy'
elif id == 5:
return 'Surprise'
else:
return 'Fear'
author_columns = ['name', 'dom... | (self,text):
emo = te.get_emotion(text)
return max(emo, key=emo.get) # The output we received,
def _trends_to_csv(self, trends_dict, path="C:/fake-news-framework_Py3/data/input/tryout/"):
topics = []
tweets = []
authors = []
topic_tweet_connection = []
for ... | get_emotion | identifier_name |
ClassifierAdapter.py | .DataObjects import *
def get_emotion_by_id(id):
if id == 1:
return 'Anger'
elif id == 2:
return 'Disgust'
elif id == 3:
return 'Sad'
elif id == 4:
return 'Happy'
elif id == 5:
return 'Surprise'
else:
return 'Fear'
author_columns = ['name', 'dom... |
def _trends_to_csv(self, trends_dict, path="C:/fake-news-framework_Py3/data/input/tryout/"):
topics = []
tweets = []
authors = []
topic_tweet_connection = []
for trend in trends_dict.keys():
for topic in trends_dict[trend].claims:
topics.append(... | emo = te.get_emotion(text)
return max(emo, key=emo.get) # The output we received, | identifier_body |
ClassifierAdapter.py | .DataObjects import *
def get_emotion_by_id(id):
if id == 1:
return 'Anger'
elif id == 2:
return 'Disgust'
elif id == 3:
return 'Sad'
elif id == 4:
return 'Happy'
elif id == 5:
return 'Surprise'
else:
return 'Fear'
author_columns = ['name', 'dom... | print(f"add tweet {tweet} to the topic {topic}")
print(f"save the topic {topic}, with the list of tweets: {tweets}")
processed_data[trend].append(Claim(topic.name, tweets,topic.id))
time.sleep(1)
results['pred'] = results['pred'].apply(lambda x:"True... | print("start trend {}".format(trend))
if trend not in processed_data:
processed_data[trend] = list()
for topic in trends_dict[trend].claims:
tweets = list()
for tweet in topic.tweets:
rand = randrange(100)
if... | conditional_block |
ClassifierAdapter.py | Manager.DataObjects import *
def get_emotion_by_id(id):
if id == 1:
return 'Anger'
elif id == 2:
return 'Disgust'
elif id == 3:
return 'Sad'
elif id == 4:
return 'Happy'
elif id == 5:
return 'Surprise'
else:
return 'Fear'
author_columns = ['name... | results['pred'] = results['pred'].apply(lambda x:"True" if x else "Fake")
return callback(processed_data, trends_dict,results)
def analyze_snopes(self, data, callback): # data is type of dict {<claim name> : list <tweets>}
# print(data)
# processed_data = {}
# for key in da... | time.sleep(1) | random_line_split |
MapScreen.js | constructor(props) {
super(props);
this.state = {
startValue: 'Start',
initialCoords:[
{latitude:34.073026, longitude:-118.465619},
{latitude:34.067223, longitude:-118.410851}
],
coordinates: [
{
latitude: 34.06279,
longitude: -118.44390,
... | () {
const { modalVisible } = this.state;
let button;
button=
<TouchableOpacity style={Buttons.brownbuttonSmall}
onPress={() => this.setModalVisible(!modalVisible)}>
<Text style={{color:'white', alignSelf: "center"}}>Save</Text>
</TouchableOpacity>
return (
<V... | render | identifier_name |
MapScreen.js | -118.44390,
},
{
latitude: 34.06241,
longitude: -118.44375,
},
],
clocation: {
latitude: 34.06637,
longitude:-118.44524,
},
dur: null,
dis: null,
saveWalk:{
startingLocation: null,
destinationLocation: null,... | data={this.state.walks}
renderItem={({item}) => (
<TouchableOpacity style={styles.item}
onPress={() => this.setPremadePath(item)}> | random_line_split | |
MapScreen.js | constructor(props) {
super(props);
this.state = {
startValue: 'Start',
initialCoords:[
{latitude:34.073026, longitude:-118.465619},
{latitude:34.067223, longitude:-118.410851}
],
coordinates: [
{
latitude: 34.06279,
longitude: -118.44390,
... |
else{
this.setState({
startValue:'Start'
});
this.mapView.fitToCoordinates(this.state.initialCoords,{
edgePadding: {
right: width,
bottom: height,
left: width,
top: height
}
}
);
}
}
// Saves user's walks to da... | {
this.setState({
startValue:'Stop'
});
this.mapView.fitToCoordinates(this.state.forZoom.coordinates,{
edgePadding: {
right: (width / 10),
bottom: (height / 20),
left: (width / 10),
top: (height / 20),
}
}
);
} | conditional_block |
yolov5_trt12.py | ), int(hand_['2']['y']+y)), colors[0], thick)
cv2.line(img_, (int(hand_['2']['x']+x), int(hand_['2']['y']+y)),(int(hand_['3']['x']+x), int(hand_['3']['y']+y)), colors[0], thick)
cv2.line(img_, (int(hand_['3']['x']+x), int(hand_['3']['y']+y)),(int(hand_['4']['x']+x), int(hand_['4']['y']+y)), colors[0], thick)
... | shape)
print(io_info)
d_buffers = trt_engine.allocate_io_buffers(i2shape, True)
print(io_info[1][2])
d_buffers[0] = data.cuda()
bindings = [t.data_ptr() for | ine.get_io_info(i2 | identifier_name |
yolov5_trt12.py | ), int(hand_['2']['y']+y)), colors[0], thick)
cv2.line(img_, (int(hand_['2']['x']+x), int(hand_['2']['y']+y)),(int(hand_['3']['x']+x), int(hand_['3']['y']+y)), colors[0], thick)
cv2.line(img_, (int(hand_['3']['x']+x), int(hand_['3']['y']+y)),(int(hand_['4']['x']+x), int(hand_['4']['y']+y)), colors[0], thick)
... | print(output.shape,len(result_boxes))
# Draw rectangles and labels on the original image
for i in range(len(result_boxes)):
box = result_boxes[i]
print("box>>>",box)
# 截出手的部位
image_hand = image_raw[int(box[1]):int(box[3]),int(box[0]):int(box[2])]
... | e preprocess
input_image, image_raw, origin_h, origin_w = self.preprocess_image(image_path)
self.buffers[0] = torch.from_numpy(input_image.ravel()).cuda()
bindings = [t.data_ptr() for t in self.buffers]
self.trt_yolo.execute(bindings, BATCH_SIZE)
host_outputs = self.buffers[... | identifier_body |
yolov5_trt12.py | int(hand_['7']['x']+x), int(hand_['7']['y']+y)),(int(hand_['8']['x']+x), int(hand_['8']['y']+y)), colors[1], thick)
cv2.line(img_, (int(hand_['0']['x']+x), int(hand_['0']['y']+y)),(int(hand_['9']['x']+x), int(hand_['9']['y']+y)), colors[2], thick)
cv2.line(img_, (int(hand_['9']['x']+x), int(hand_['9']['y']+y)),... | image_raw: the original image
h: original height
w: original width
""" | random_line_split | |
yolov5_trt12.py | ), int(hand_['2']['y']+y)), colors[0], thick)
cv2.line(img_, (int(hand_['2']['x']+x), int(hand_['2']['y']+y)),(int(hand_['3']['x']+x), int(hand_['3']['y']+y)), colors[0], thick)
cv2.line(img_, (int(hand_['3']['x']+x), int(hand_['3']['y']+y)),(int(hand_['4']['x']+x), int(hand_['4']['y']+y)), colors[0], thick)
... |
draw_bd_handpose(img, pts_hand, 0, 0) # 绘制关键点连线
# ------------- 绘制关键点
for i in range(int(outputs.shape[0] / 2)):
x = (outputs[i * 2 + 0] * float(img_width))
y = (outputs[i * 2 + 1] * float(img_height))
cv2.circle(img, (int(x), int(y)), 3, (255, 50, 60), -1)
cv2.circle(img... | x = (outputs[i * 2 + 0] * float(img_width))
y = (outputs[i * 2 + 1] * float(img_height))
pts_hand[str(i)] = {}
pts_hand[str(i)] = {
"x": x,
"y": y,
} | conditional_block |
game.js | // jetpack
this.jetpack = false;
this.jetpackTimer = 5000;
this.fireTick = 0; // tick to control fire frequency
var that = this;
var chkCol = function(t, h, e){
// check collision with map
// or with enemy
if(t == "map"){
var yBelow = Math.ceil(that.y)-1;
var xBelow1 = Math.floor(that.... | { // x, y, sx, sy,
this.s = sprite;
this.frame = 0; // start frame
// movement tick
this.xtick = 0;
this.ytick = 0;
// variables to restrict movement to given platform
// xs = xStart, xe = xEnd. They correspond to tile
// start and tile end positions
this.xs = typeof(group[0]) !== 'number' ? group[... | identifier_body | |
game.js | callback;
this.image.src = rImage;
};
this.draw = function(sprite, x, y, frame){
var s = this.data[sprite]; //this sprite
frame = !frame ? 0 : frame; //default frame is 0
cx.drawImage(this.image, s.sx + frame * s.w, s.sy, s.w, s.h, x, y, s.w*s.dimM, s.h*s.dimM);
};
};
/***********************/
/... | that.cx.fillStyle=txtColor;
that.cx.font = "48px verdana";
that.cx.fillText("Game Over", that.w/2, that.h/2 - 100);
that.cx.font = "16px verdana";
that.cx.fillText("You completed " + (that.currLevel - 1) + " levels in " + (totalTime/1000).toFixed(2) + " seconds.", that.w/2, that.h/2 -50);
that.c... | var scoreMsg = score > 0 ? ". Well done." : ". Opps, better luck next time."
| random_line_split |
game.js | );
that.cx.font = "16px verdana";
that.cx.fillText("You completed " + (that.currLevel - 1) + " levels in " + (totalTime/1000).toFixed(2) + " seconds.", that.w/2, that.h/2 -50);
that.cx.fillText("Your score is " + score + scoreMsg, that.w/2, that.h/2 -20);
that.cx.font = "12px verdana";
that.cx.fillT... | Enemy | identifier_name | |
game.js | ;
this.image.src = rImage;
};
this.draw = function(sprite, x, y, frame){
var s = this.data[sprite]; //this sprite
frame = !frame ? 0 : frame; //default frame is 0
cx.drawImage(this.image, s.sx + frame * s.w, s.sy, s.w, s.h, x, y, s.w*s.dimM, s.h*s.dimM);
};
};
/***********************/
/* private... | else{
// check collision with object h and object e
var abs = Math.abs;
return (abs(h.x - e.x) * 2 < (1)) && (abs(h.y - e.y) * 2 < (1));
}
};
this.update = function(i){
// add interval to all ticks
this.xTick += i;
this.yTick += i;
this.fireTick += i;
// check if any relevant keys ar... | {
var yBelow = Math.ceil(that.y)-1;
var xBelow1 = Math.floor(that.x);
var xBelow2 = Math.ceil(that.x);
// check collision with tiles below
// and on either side of hero
var tileBelow1 = game.levelObj.getTile(xBelow1, yBelow);
var tileBelow2 = game.levelObj.getTile(xBelow2, yBelow);
if(... | conditional_block |
terminal.rs | <Share<TermOut>>>,
input: Fwd<Key>, | termout: Share<TermOut>,
glue: Glue,
disable_output: bool,
paused: bool,
inbuf: Vec<u8>,
check_enable: bool,
force_timer: MaxTimerKey,
check_timer: MaxTimerKey,
cleanup: Vec<u8>,
panic_hook: Arc<Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>>,
}
impl Terminal {
/// Set ... | random_line_split | |
terminal.rs | Share<TermOut>>>,
input: Fwd<Key>,
termout: Share<TermOut>,
glue: Glue,
disable_output: bool,
paused: bool,
inbuf: Vec<u8>,
check_enable: bool,
force_timer: MaxTimerKey,
check_timer: MaxTimerKey,
cleanup: Vec<u8>,
panic_hook: Arc<Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + ... |
/// Resume terminal output and input handling. Switches to raw
/// mode and sends a resize message to trigger a full redraw.
pub fn resume(&mut self, cx: CX![]) {
if self.paused {
self.paused = false;
self.glue.input(true);
self.termout.rw(cx).discard();
... | {
if !self.paused {
fwd!([self.resize], None);
self.glue.input(false);
self.termout.rw(cx).discard();
self.termout.rw(cx).bytes(&self.cleanup[..]);
self.termout.rw(cx).flush();
self.flush(cx);
self.paused = true;
sel... | identifier_body |
terminal.rs | Share<TermOut>>>,
input: Fwd<Key>,
termout: Share<TermOut>,
glue: Glue,
disable_output: bool,
paused: bool,
inbuf: Vec<u8>,
check_enable: bool,
force_timer: MaxTimerKey,
check_timer: MaxTimerKey,
cleanup: Vec<u8>,
panic_hook: Arc<Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + ... | (&mut self, cx: CX![]) {
if !self.paused {
fwd!([self.resize], None);
self.glue.input(false);
self.termout.rw(cx).discard();
self.termout.rw(cx).bytes(&self.cleanup[..]);
self.termout.rw(cx).flush();
self.flush(cx);
self.paused ... | pause | identifier_name |
terminal.rs | Share<TermOut>>>,
input: Fwd<Key>,
termout: Share<TermOut>,
glue: Glue,
disable_output: bool,
paused: bool,
inbuf: Vec<u8>,
check_enable: bool,
force_timer: MaxTimerKey,
check_timer: MaxTimerKey,
cleanup: Vec<u8>,
panic_hook: Arc<Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + ... |
}
/// Resume terminal output and input handling. Switches to raw
/// mode and sends a resize message to trigger a full redraw.
pub fn resume(&mut self, cx: CX![]) {
if self.paused {
self.paused = false;
self.glue.input(true);
self.termout.rw(cx).discard();
... | {
fwd!([self.resize], None);
self.glue.input(false);
self.termout.rw(cx).discard();
self.termout.rw(cx).bytes(&self.cleanup[..]);
self.termout.rw(cx).flush();
self.flush(cx);
self.paused = true;
self.update_panic_hook();
... | conditional_block |
importNet.js | 8086/query?db=mydb/";
const dataS = "q=SELECT+value,region+FROM+cpu+WHERE+value=0.64" ;
$.ajax({
url: "http://localhost:8086/query?db=mydb",
headers:{
'Authorization': 'Basic ' + btoa('admin:admin'),
},
type: 'POST',
data: {
q:"SELECT+value,region+FROM+cpu+WHERE+value=0.64",
},
... | se if (!inputModel.info) {
inputModel.info = 'Select a ' + input.pluginName + ' data source';
}
inputModel.options = sources.map(val => {
return { text: val.name, value: val.name };
});
}
inputValueChanged() {
this.inputsValid = true;
... | inputModel.info = 'No data sources of type ' + input.pluginName + ' found';
} el | conditional_block |
importNet.js | :8086/query?db=mydb/";
const dataS = "q=SELECT+value,region+FROM+cpu+WHERE+value=0.64" ;
$.ajax({
url: "http://localhost:8086/query?db=mydb",
headers:{
'Authorization': 'Basic ' + btoa('admin:admin'),
},
type: 'POST',
data: {
q:"SELECT+value,region+FROM+cpu+WHERE+value=0.64",
},... |
this.hasNameValidationError = true;
this.nameValidationError = err.message;
});
}
uidChanged(initial) {
this.uidExists = false;
this.hasUidValidationError = false;
if (initial === true && this.dash.uid) {
... | random_line_split | |
importNet.js | :8086/query?db=mydb/";
const dataS = "q=SELECT+value,region+FROM+cpu+WHERE+value=0.64" ;
$.ajax({
url: "http://localhost:8086/query?db=mydb",
headers:{
'Authorization': 'Basic ' + btoa('admin:admin'),
},
type: 'POST',
data: {
q:"SELECT+value,region+FROM+cpu+WHERE+value=0.64",
},... | states.push(net.nodi[i].stati);
probs.push(net.nodi[i].probs);
}
/*
return influx.insert(nodes,states,probs)
.then(()=>console.info("inserted"));
*/
influx.insert(nodes,states,probs)
.then(()=>con... | this.network = net; //per l'html
//riceverò sempre una net, gli devo aggiungere il template della dashboard
ImportNetCtrl.initProbs(net);
structure.title = net.rete;
structure.network = net; //attacco il pezzo che ricevo al template
console.info("onUpload Rete: ");
... | identifier_body |
importNet.js | admin'),
},
type: 'POST',
data: {
q:"SELECT+value,region+FROM+cpu+WHERE+value=0.64",
},
success: function(data) { //we got the response
console.log(data);
},
error: function(test, status, exception) {
console.log("Error: " + exception);
}
});
/*
let query = 'cpu,... | alid() | identifier_name | |
dataset_RAF.py | 9": 3,
"70+":4
},
"race": {
"Caucasian": 0,
"African-American": 1,
"Asian": 2
}
}
# converted labels
rafDBmeta = defaultdict(dict)
# multitask labels
rafDBpartition = dict() # dict({id:partition or None}) # for partitioning purpose
rafDBdata = None # dict({image_path: ... ... | (gender):
if gender == 'male':
return LABELS["gender"]["male"]
elif gender == 'female':
return LABELS["gender"]["female"]
return MASK_VALUE
def get_age_group_label(age_group_text):
return rafdb_labels["age_group"][age_group_text]
def get_ethnicity_label(ethnicity_text):
return rafd... | get_gender_label | identifier_name |
dataset_RAF.py | 9": 3,
"70+":4
},
"race": {
"Caucasian": 0,
"African-American": 1,
"Asian": 2
}
}
# converted labels
rafDBmeta = defaultdict(dict)
# multitask labels
rafDBpartition = dict() # dict({id:partition or None}) # for partitioning purpose
rafDBdata = None # dict({image_path: ... ... | self.preprocessing = preprocessing
print('Loading %s data...' % partition)
num_samples = "_" + str(debug_max_num_samples) if debug_max_num_samples is not None else ''
cache_task = "{}{}{}_emotion".format(
"_withgender" if include_gender else "",
"_withagegroup" i... | def __init__(self,
partition='train',
imagesdir='data/RAF-DB/basic/Image/{aligned}',
csvmeta='data/RAF-DB/basic/multitask/{part}.multitask_rafdb.csv',
target_shape=(112, 112, 3),
augment=True,
custom_augmentation=None,
... | identifier_body |
dataset_RAF.py | 9": 3,
"70+":4
},
"race": {
"Caucasian": 0,
"African-American": 1,
"Asian": 2
}
}
# converted labels
rafDBmeta = defaultdict(dict)
# multitask labels
rafDBpartition = dict() # dict({id:partition or None}) # for partitioning purpose
rafDBdata = None # dict({image_path: ... ... | output_dict[row[0]]["gender"] = row[1]
output_dict[row[0]]["age_group"] = row[2]
output_dict[row[0]]["race"] = row[3]
output_dict[row[0]]["emotion"] = row[4]
output_dict[row[0]]["identity"] = row[0].split("_")[1]
def get_partition(identity_label):
global rafDBpartition
... | def _load_meta_from_csv(csv_meta, output_dict):
data = readcsv(csv_meta)
for row in data: | random_line_split |
dataset_RAF.py | 9": 3,
"70+":4
},
"race": {
"Caucasian": 0,
"African-American": 1,
"Asian": 2
}
}
# converted labels
rafDBmeta = defaultdict(dict)
# multitask labels
rafDBpartition = dict() # dict({id:partition or None}) # for partitioning purpose
rafDBdata = None # dict({image_path: ... ... |
# Labelling
def get_gender_label(gender):
if gender == 'male':
return LABELS["gender"]["male"]
elif gender == 'female':
return LABELS["gender"]["female"]
return MASK_VALUE
def get_age_group_label(age_group_text):
return rafdb_labels["age_group"][age_group_text]
def get_ethnicity_lab... | print("Gender errors", errors["gender"])
print("Age errors", errors["age"])
print("Ethnicity errors", errors["ethnicity"]) | conditional_block |
mod.rs | _at_mut(degree * OUT_LEN);
// Recurse! This uses multiple threads if the "rayon" feature is enabled.
let (left_n, right_n) = J::join(
|| compress_parents_wide::<J>(left, key, flags, platform, left_out),
|| compress_parents_wide::<J>(right, key, flags, platform, right_out),
left.len(),
... | ///
/// [`update`]: #method.update
/// [`update_with_join`]: #method.update_with_join
/// [`GpuControl`]: struct.GpuControl.html
pub fn update_from_gpu<J: Join>(&mut self, chunk_count: u64, parents: &mut [u8]) -> &mut Self {
assert_eq!(self.chunk_state.len(), 0, "leftover buffered bytes");
... | /// same as the chunk counter in the [`GpuControl`] passed to the shader,
/// otherwise it will lead to a wrong hash output.
///
/// Note: on a big-endian host, this method will swap the endianness of the
/// shader output in-place. | random_line_split |
mod.rs | .new_derive_key).
#[inline]
pub fn new_derive_key(context: &str) -> Self {
Self {
inner: Hasher::new_derive_key(context),
}
}
/// Obtain the [`GpuControl`](struct.GpuControl.html) to hash full chunks starting with `chunk_counter`
/// or parent nodes.
pub fn gpu_contr... | {
include_bytes!("shaders/blake3-chunk-be.spv")
} | identifier_body | |
mod.rs | (&self) -> u8 {
self.d as u8
}
/// Returns the bytes to be copied to the control uniform in the GPU.
///
/// The contents of the returned slice are opaque and should be interpreted
/// only by the shader.
#[inline]
pub fn as_bytes(&self) -> &[u8] {
// According to the specif... | flags | identifier_name | |
transfer_leads.py | sends to Certify SFDC instance
result_dict = send_to_certify(standardized_list)
print(result_dict)
#posts notification to Slack upon failure to insert to Certify SFDC
if(result_dict[0].get('success') == False):
message = f"LEAD TRANSFER TO CERTIFY FAILURE \n"
message += f"failed lea... | (lead_dict):
cr_industry = lead_dict.get('Industry')
cert_industry = lead_dict.get('Industry')
if(cr_industry == 'Accounting'):
cert_industry = 'Business Services'
elif(cr_industry == 'Advertising'):
cert_industry = 'Business Services'
elif(cr_industry == 'Apparel'):
cert_ind... | standardize_industry | identifier_name |
transfer_leads.py | ['cr_sf_username'], password=os.environ['cr_sf_password'], security_token=os.environ['cr_sf_token'],domain=os.environ['cr_sf_host'])
sf_data = sf.query_all(query_string)
return sf_data['records']
def create_new_dict(lead_dict):
new_dict = {}
new_dict['FirstName'] = lead_dict.get('FirstName')
n... | cert_state = None | conditional_block | |
transfer_leads.py | file within S3
s3 = boto3.client('s3')
s3.delete_object(Bucket=bucket,Key=key)
return {
'statusCode': 200,
'body': json.dumps('Transfer complete')
}
def _get_lead_list(idList):
query_string = "SELECT ID,FirstName,LastName,Company,Phone,MobilePhone,Email,Fax,Link... | cr_country = lead_dict.get('Country')
cert_country = lead_dict.get('Country')
if(cr_country == 'Bolivia'):
cert_country = 'Bolivia, Plurinational State of'
elif(cr_country == 'Iran'):
cert_country = 'Iran, Islamic Republic of'
elif(cr_country == 'North Korea'):
cert_country = 'Ko... | identifier_body | |
transfer_leads.py | message += f"Returned error log from Salesforce: \n"
message += result_dict[0].get('errors')[0].get('message')
_publish_alert(message)
else:
#deletes JSON file within S3
s3 = boto3.client('s3')
s3.delete_object(Bucket=bucket,Key=key)
return {
'statusCode'... | random_line_split | ||
caclient.go | {
// Uri is access point for fabric-ca server. Port number and scheme must be provided.
// for example http://127.0.0.1:7054
Url string
// SkipTLSVerification define how connection must handle invalid TLC certificates.
// if true, all verifications are skipped. This value is overwritten by Transport property, if ... | createAuthToken | identifier_name | |
caclient.go | :"max_enrollments,omitempty"`
// Affiliation associates identity with particular organisation.
// for example org1.department1 makes this identity part of organisation `org1` and department `department1`
Affiliation string `json:"affiliation"`
// Attrs are attributes associated with this identity
Attrs []*CARegist... |
return result, nil
}
// Enroll execute enrollment request for registered user in fabric-ca server.
// On success new Identity with ECert is returned
func (f *FabricCAClientImpl) Enroll(enrollmentId, password string) (*Identity, []byte, error) {
if len(enrollmentId) < 1 {
return nil, nil, ErrEnrollmentIdMissing
}... | {
return nil, err
} | conditional_block |
caclient.go | reason for revocation. See https://godoc.org/golang.org/x/crypto/ocsp for
// valid values. The default value is 0 (ocsp.Unspecified).
Reason int `json:"reason,omitempty"`
}
// CAResponse represents response message from fabric-ca server
type CAResponse struct {
Success bool `json:"succes... | random_line_split | ||
caclient.go | used
// It is responsibility of the user to provide proper TLS/certificate setting in TLS communication.
Transport *http.Transport
}
// enrollmentResponse is response from fabric-ca server for enrolment that contains created Ecert
type enrollmentResponse struct {
Success bool `json:"success"`
... | {
encPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: identity.Certificate.Raw})
encCert := base64.StdEncoding.EncodeToString(encPem)
body := base64.StdEncoding.EncodeToString(request)
sigString := body + "." + encCert
sig, err := f.Crypto.Sign([]byte(sigString), identity.PrivateKey)
if err != n... | identifier_body | |
machine_amd64.go | () error {
var (
kernelSystemRegs systemRegs
kernelUserRegs userRegs
)
// Set base control registers.
kernelSystemRegs.CR0 = c.CR0()
kernelSystemRegs.CR4 = c.CR4()
kernelSystemRegs.EFER = c.EFER()
// Set the IDT & GDT in the registers.
kernelSystemRegs.IDT.base, kernelSystemRegs.IDT.limit = c.IDT()
ker... | initArchState | identifier_name | |
machine_amd64.go | )
// Set base control registers.
kernelSystemRegs.CR0 = c.CR0()
kernelSystemRegs.CR4 = c.CR4()
kernelSystemRegs.EFER = c.EFER()
// Set the IDT & GDT in the registers.
kernelSystemRegs.IDT.base, kernelSystemRegs.IDT.limit = c.IDT()
kernelSystemRegs.GDT.base, kernelSystemRegs.GDT.limit = c.GDT()
kernelSystemReg... |
// If tsc scaling is not supported, fallback to legacy mode.
if !c.machine.tscControl {
return c.setSystemTimeLegacy()
}
// First, scale down the clock frequency to the lowest value allowed by
// the API itself. How low we can go depends on the underlying
// hardware, but it is typically ~1/2^48 for Intel, ... | {
return err
} | conditional_block |
machine_amd64.go | )
// Set base control registers.
kernelSystemRegs.CR0 = c.CR0()
kernelSystemRegs.CR4 = c.CR4()
kernelSystemRegs.EFER = c.EFER()
// Set the IDT & GDT in the registers.
kernelSystemRegs.IDT.base, kernelSystemRegs.IDT.limit = c.IDT()
kernelSystemRegs.GDT.base, kernelSystemRegs.GDT.limit = c.GDT()
kernelSystemRe... | } else {
info.Code | }
}
if !accessType.Write && !accessType.Execute {
info.Code = 1 // SEGV_MAPERR. | random_line_split |
machine_amd64.go | here, in which
// case we simply don't use PCID support (see below). In
// practice, this should not happen, however.
c.PCIDs = pagetables.NewPCIDs(fixedKernelPCID+1, poolPCIDs)
}
// Set the CPUID; this is required before setting system registers,
// since KVM will reject several CR4 bits if the CPUID does n... | {
// Check for canonical addresses.
if regs := switchOpts.Registers; !ring0.IsCanonical(regs.Rip) {
return nonCanonical(regs.Rip, int32(unix.SIGSEGV), info)
} else if !ring0.IsCanonical(regs.Rsp) {
return nonCanonical(regs.Rsp, int32(unix.SIGBUS), info)
} else if !ring0.IsCanonical(regs.Fs_base) {
return nonC... | identifier_body | |
main.py | mean square error between the prediction and time-integrator
'''
model.train()
loss_total = 0
mse_total = 0
# Mini-batch loop
for batch_idx, input in enumerate(train_loader):
# input [b, 2, x, y]
# Expand input to match model in channels
dims = torch.ones(len(input.shap... |
input = input[:,-2*int(args.nic-1):,:].detach()
input0 = uPred.detach()
input = torch.cat([input, input0], dim=1)
return u_out, u_target
def testSample(args, swag_nn, test_loader, tstep=100, n_samples=10, test_every=2):
'''
Tests the samples of the Bayesi... | u_out[bidx*mb_size:(bidx+1)*mb_size, (t_idx+1)//test_every,:,:,:] = uPred | conditional_block |
main.py | mean square error between the prediction and time-integrator
'''
model.train()
loss_total = 0
mse_total = 0
# Mini-batch loop
for batch_idx, input in enumerate(train_loader):
# input [b, 2, x, y]
# Expand input to match model in channels
dims = torch.ones(len(input.shap... | init_features=args.init_features,
bn_size=args.bn_size,
drop_rate=args.drop_rate,
bottleneck=False,
out_activation=None).to(args.device)
# Bayesian neural network
bayes_nn = BayesNN(args, den... | blocks=args.blocks,
growth_rate=args.growth_rate, | random_line_split |
main.py | mean square error between the prediction and time-integrator
'''
model.train()
loss_total = 0
mse_total = 0
# Mini-batch loop
for batch_idx, input in enumerate(train_loader):
# input [b, 2, x, y]
# Expand input to match model in channels
dims = torch.ones(len(input.shap... | model.eval()
for bidx, (input0, uTarget0) in enumerate(test_loader):
# Expand input to match model in channels
dims = torch.ones(len(input0.shape))
dims[1] = args.nic
input = input0.repeat(toTuple(toNumpy(dims).astype(int))).to(args.device)
... | '''
Tests the samples of the Bayesian SWAG model
Args:
args (argparse): object with programs arguements
model (PyTorch model): DenseED model to be tested
test_loader (dataloader): dataloader with test cases (use createTestingLoader)
tstep (int): number of timesteps to predict for... | identifier_body |
main.py | (args, model, burgerInt, train_loader, optimizer, tsteps, tback, tstart, dt=0.1):
'''
Trains the model
Args:
args (argparse): object with programs arguements
model (PyTorch model): SWAG DenseED model to be tested
burgerInt (BurgerIntegrate): 1D Burger system time integrator
t... | train | identifier_name | |
index.js | delete all active tokens, by clearing discordUserId2token and token2nethzHash
WARNING: this leads to unexpected behaviour from the point of view of users who are pending verification...
\`!purgemarks\` (admin only): unmark all nethzs, by clearing verifiedNethzHashs.
WARNING: doing this is rarely a good idea...
... | const welcomeMsg = (guildName) => `Hello! I see you just joined the server **${guildName}**.
You are currently not verified as an ETH student on **${guildName}**, so you only have access to a restricted number of channels.
To verify yourself as an ETH student,
1. please tell me your nethz (i.e ETH username) in the fo... | random_line_split | |
index.js | delete all active tokens, by clearing discordUserId2token and token2nethzHash
WARNING: this leads to unexpected behaviour from the point of view of users who are pending verification...
\`!purgemarks\` (admin only): unmark all nethzs, by clearing verifiedNethzHashs.
WARNING: doing this is rarely a good idea...
... |
}
} else if (command === 'mark') {
if (!args.length) {
return message.channel.send(`You didn't provide any nethz! Usage: e.g \`!mark ${sampleNethz}\``);
} else if (args.length > 1) {
return message.channel.send(`You provided too many arguments... Usage: e.g \`!mark ${sampleNethz}\``);
} else {
... | {
await verifiedNethzHashs.delete(nethzHash);
return message.channel.send(`Unmarked nethz ${nethz} as "already used for verification".`);
} | conditional_block |
index.js | (mention) {
// The id is the first and only match found by the RegEx.
const matches = mention.match(/^<@!?(\d+)>$/);
// If supplied variable was not a mention, matches will be null instead of an array.
if (!matches) return;
// However the first element in the matches array will be the entire mention, not just the ... | getUserFromMention | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.