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 |
|---|---|---|---|---|
console.js | /* console.js is part of Aloha Editor project http://aloha-editor.org
*
* Aloha Editor is a WYSIWYG HTML5 inline editing library and editor.
* Copyright (c) 2010-2012 Gentics Software GmbH, Vienna, Austria.
* Contributors http://aloha-editor.org/contribution.php
*
* Aloha Editor is free software; you can redis... | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1... | * but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
console.js | /* console.js is part of Aloha Editor project http://aloha-editor.org
*
* Aloha Editor is a WYSIWYG HTML5 inline editing library and editor.
* Copyright (c) 2010-2012 Gentics Software GmbH, Vienna, Austria.
* Contributors http://aloha-editor.org/contribution.php
*
* Aloha Editor is free software; you can redis... |
// now check whether the log level is activated
if (!Aloha.settings.logLevels[level]) {
return;
}
component = component || "Unkown Aloha Component";
this.addToLogHistory({
'level':level,
'component':component,
'message':message,
'date':new Date()... | {
return;
} | conditional_block |
SearchForm.js | // CITATION: https://heartbeat.fritz.ai/build-and-validate-forms-in-react-native-using-formik-and-yup-6489e2dff6a2
import React, { Fragment } from 'react'
import { StyleSheet, SafeAreaView, View, Alert, Picker, TouchableHighlight, Text } from 'react-native'
import { GooglePlacesAutocomplete } from 'react-native-google-... | (store_id){
let response = await fetch('http://192.168.1.24:8081/stores/' + store_id + "/services/", {
method: "GET",
headers: {
'Content-type': 'application/json'
},
// credentials: 'include'
})
.then(function(response){
if(response.status!==200){
// throw an... | getServices | identifier_name |
SearchForm.js | // CITATION: https://heartbeat.fritz.ai/build-and-validate-forms-in-react-native-using-formik-and-yup-6489e2dff6a2
import React, { Fragment } from 'react'
import { StyleSheet, SafeAreaView, View, Alert, Picker, TouchableHighlight, Text } from 'react-native'
import { GooglePlacesAutocomplete } from 'react-native-google-... |
}}
getDefaultValue={() => ''}
query={{
// available options: https://developers.google.com/places/web-service/autocomplete
key: '', // Does work, supply with Google API Key for use
language: 'en', // language of th... | {
console.log(data)
} | conditional_block |
SearchForm.js | // CITATION: https://heartbeat.fritz.ai/build-and-validate-forms-in-react-native-using-formik-and-yup-6489e2dff6a2
import React, { Fragment } from 'react'
import { StyleSheet, SafeAreaView, View, Alert, Picker, TouchableHighlight, Text } from 'react-native'
import { GooglePlacesAutocomplete } from 'react-native-google-... | onSelectedItemsChangeDistance = selectedItemPassed => {
this.setState({
selectedItemDistance: selectedItemPassed
})
};
async getPictures(prefixPassed) {
const response = await fetch('http://192.168.1.24:8081/getImages', {
method: "POST",
headers: {
'Content-type': 'a... | })
};
| random_line_split |
instance.go | /*
Copyright 2020 FUJITSU CLOUD TECHNOLOGIES LIMITED. 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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... | s.scope.V(2).Info("Try to terminate instance", "instance-id", instanceID)
input := &computing.TerminateInstancesInput{
InstanceId: []string{instanceID},
}
if _, err := s.scope.NifcloudClients.Computing.TerminateInstances(context.TODO(), input); err != nil {
return fmt.Errorf("failed to termiante instance with ... | func (s *Service) TerminateInstance(instanceID string) error { | random_line_split |
instance.go | /*
Copyright 2020 FUJITSU CLOUD TECHNOLOGIES LIMITED. 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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... |
func (s *Service) GetRunningInstanceByTag(scope *scope.MachineScope) (*infrav1alpha2.Instance, error) {
s.scope.V(2).Info("Looking for existing machine instance by tags")
input := &computing.DescribeInstancesInput{}
out, err := s.scope.NifcloudClients.Computing.DescribeInstances(context.TODO(), input)
switch {
... | {
if id == nil {
s.scope.Info("Instance does not have an instance id")
return nil, nil
}
s.scope.V(2).Info("Looking for instance by id", "instance-id", *id)
input := &computing.DescribeInstancesInput{
InstanceId: []string{nifcloud.StringValue(id)},
}
out, err := s.scope.NifcloudClients.Computing.DescribeI... | identifier_body |
instance.go | /*
Copyright 2020 FUJITSU CLOUD TECHNOLOGIES LIMITED. 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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... |
input.SecurityGroups = append(input.SecurityGroups, ids...)
// set SSH key
input.SSHKeyName = defaultSSHKeyName
if scope.NifcloudMachine.Spec.KeyName != "" {
input.SSHKeyName = scope.NifcloudMachine.Spec.KeyName
} else {
input.SSHKeyName = defaultSSHKeyName
}
s.scope.V(2).Info("Running instance", "machine... | {
return nil, err
} | conditional_block |
instance.go | /*
Copyright 2020 FUJITSU CLOUD TECHNOLOGIES LIMITED. 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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... | (instance *computing.InstancesSetItem) []corev1.NodeAddress {
addresses := []corev1.NodeAddress{}
for _, ni := range instance.NetworkInterfaceSet {
privateDNSAddress := corev1.NodeAddress{
Type: corev1.NodeInternalDNS,
Address: *ni.PrivateDnsName,
}
privateIPAddress := corev1.NodeAddress{
Type: core... | getInstanceAddresses | identifier_name |
king.py | """
KING
A strategy game where the player is the king.
Ported to Python by Martin Thoma in 2022
"""
import sys
from dataclasses import dataclass
from random import randint, random
FOREST_LAND = 1000
INITIAL_LAND = FOREST_LAND + 1000
COST_OF_LIVING = 100
COST_OF_FUNERAL = 9
YEARS_IN_TERM = 8
POLLUTION_CONTROL_FACTOR... |
if message <= 10:
print("HAVE ALSO BEEN DECLARED NATIONAL FINK.")
sys.exit()
def handle_third_died(self) -> None:
print()
print()
print("OVER ONE THIRD OF THE POPULTATION HAS DIED SINCE YOU")
print("WERE ELECTED TO OFFICE. THE PEOPLE (REMAINING)")
... | print("HAVE ALSO GAINED A VERY BAD REPUTATION.") | conditional_block |
king.py | """
KING
A strategy game where the player is the king.
Ported to Python by Martin Thoma in 2022
"""
import sys
from dataclasses import dataclass
from random import randint, random
FOREST_LAND = 1000
INITIAL_LAND = FOREST_LAND + 1000
COST_OF_LIVING = 100
COST_OF_FUNERAL = 9
YEARS_IN_TERM = 8
POLLUTION_CONTROL_FACTOR... | state.handle_harvest(planted_sq)
state.handle_tourist_trade()
if state.died_contrymen > 200:
state.handle_too_many_deaths()
if state.countrymen < 343:
state.handle_third_died()
elif (
state.rallods / 100
) > 5 and state.died_contrymen ... | sm_sell_to_industry, distributed_rallods, polltion_control_spendings
) | random_line_split |
king.py | """
KING
A strategy game where the player is the king.
Ported to Python by Martin Thoma in 2022
"""
import sys
from dataclasses import dataclass
from random import randint, random
FOREST_LAND = 1000
INITIAL_LAND = FOREST_LAND + 1000
COST_OF_LIVING = 100
COST_OF_FUNERAL = 9
YEARS_IN_TERM = 8
POLLUTION_CONTROL_FACTOR... |
def handle_deaths(
self, distributed_rallods: int, pollution_control_spendings: int
) -> None:
starved_countrymen = max(
0, int(self.countrymen - distributed_rallods / COST_OF_LIVING)
)
if starved_countrymen > 0:
print(f"{starved_countrymen} COUNTRYMEN ... | print(f"\n\nYOU NOW HAVE {self.rallods} RALLODS IN THE TREASURY.")
print(f"{int(self.countrymen)} COUNTRYMEN, ", end="")
if self.foreign_workers > 0:
print(f"{int(self.foreign_workers)} FOREIGN WORKERS, ", end="")
print(f"AND {self.land} SQ. MILES OF LAND.")
print(
... | identifier_body |
king.py | """
KING
A strategy game where the player is the king.
Ported to Python by Martin Thoma in 2022
"""
import sys
from dataclasses import dataclass
from random import randint, random
FOREST_LAND = 1000
INITIAL_LAND = FOREST_LAND + 1000
COST_OF_LIVING = 100
COST_OF_FUNERAL = 9
YEARS_IN_TERM = 8
POLLUTION_CONTROL_FACTOR... | (self) -> None:
print(f"\n\n\n{self.died_contrymen} COUNTRYMEN DIED IN ONE YEAR!!!!!")
print("\n\n\nDUE TO THIS EXTREME MISMANAGEMENT, YOU HAVE NOT ONLY")
print("BEEN IMPEACHED AND THROWN OUT OF OFFICE, BUT YOU")
message = randint(0, 10)
if message <= 3:
print("ALSO H... | handle_too_many_deaths | identifier_name |
mod.rs | mod menus;
mod mouse;
mod keys;
mod popup;
mod layout;
use minifb::{self, Scale, WindowOptions};
use core::view_plugins::{ViewHandle, ViewPlugins};
use core::backend_plugin::{BackendHandle, BackendPlugins};
use core::session::{Session, SessionHandle, Sessions};
use core::reader_wrapper::ReaderWrapper;
use super::viewd... |
let ui = &instance.ui;
Imgui::init_state(ui.api);
let pos = ui.get_window_pos();
let size = ui.get_window_size();
Imgui::mark_show_popup(ui.api, is_inside(mouse, pos, size) && show_context_menu);
// Draw drag zone
if let &Some((handle, rect)) = overlay {
... | {
Imgui::begin_window_child("tabs", 20.0);
let mut borders = Vec::with_capacity(tab_names.len());
// TODO: should repeated window names be avoided?
for (i, name) in tab_names.iter().enumerate() {
if Imgui::tab(name,
i == ws_co... | conditional_block |
mod.rs | mod menus;
mod mouse;
mod keys;
mod popup;
mod layout;
use minifb::{self, Scale, WindowOptions};
use core::view_plugins::{ViewHandle, ViewPlugins};
use core::backend_plugin::{BackendHandle, BackendPlugins};
use core::session::{Session, SessionHandle, Sessions};
use core::reader_wrapper::ReaderWrapper;
use super::viewd... | session: &mut Session,
show_context_menu: bool,
mouse: (f32, f32),
overlay: &Option<(DockHandle, Rect)>)
-> WindowState {
let ws_container = match ws.root_area
.as_mut()
.and_then(|root| root.... | }
fn update_view(ws: &mut Workspace,
view_plugins: &mut ViewPlugins,
handle: ViewHandle, | random_line_split |
mod.rs | mod menus;
mod mouse;
mod keys;
mod popup;
mod layout;
use minifb::{self, Scale, WindowOptions};
use core::view_plugins::{ViewHandle, ViewPlugins};
use core::backend_plugin::{BackendHandle, BackendPlugins};
use core::session::{Session, SessionHandle, Sessions};
use core::reader_wrapper::ReaderWrapper;
use super::viewd... | (&self, view_plugins: &mut ViewPlugins) -> bool {
// TODO: Use setting for this name
for handle in self.ws.get_docks() {
if let Some(plugin) = view_plugins.get_view(ViewHandle(handle.0)) {
if plugin.name == "Source Code View" {
return true;
... | has_source_code_view | identifier_name |
mod.rs | mod menus;
mod mouse;
mod keys;
mod popup;
mod layout;
use minifb::{self, Scale, WindowOptions};
use core::view_plugins::{ViewHandle, ViewPlugins};
use core::backend_plugin::{BackendHandle, BackendPlugins};
use core::session::{Session, SessionHandle, Sessions};
use core::reader_wrapper::ReaderWrapper;
use super::viewd... |
pub fn pre_update(&mut self) {
self.update_imgui_mouse();
self.update_imgui_keys();
}
pub fn update(&mut self,
sessions: &mut Sessions,
view_plugins: &mut ViewPlugins,
backend_plugins: &mut BackendPlugins) {
// Update minifb w... | {
let options = WindowOptions {
resize: true,
scale: Scale::X1,
..WindowOptions::default()
};
let win = try!(minifb::Window::new("ProDBG", width, height, options));
let ws = Workspace::new(Rect::new(0.0, 0.0, width as f32, (height - 20) as f32));
... | identifier_body |
stack.rs | // Copyright 2017-2018 the authors. See the 'Copyright and license' section of the
// README.md file at the top-level directory of this repository.
//
// Licensed under the Apache License, Version 2.0 (the LICENSE-APACHE file) or
// the MIT license (the LICENSE-MIT file) at your option. This file may not be
// copied, ... | (&self) -> Option<NonNull<SlabHeader>> {
self.next
}
fn prev(&self) -> Option<NonNull<SlabHeader>> {
self.prev
}
fn set_next(&mut self, next: Option<NonNull<SlabHeader>>) {
self.next = next;
}
fn set_prev(&mut self, prev: Option<NonNull<SlabHeader>>) {
self.prev =... | next | identifier_name |
stack.rs | // Copyright 2017-2018 the authors. See the 'Copyright and license' section of the
// README.md file at the top-level directory of this repository.
//
// Licensed under the Apache License, Version 2.0 (the LICENSE-APACHE file) or
// the MIT license (the LICENSE-MIT file) at your option. This file may not be
// copied, ... | loop {
let candidate = num_obj + 1;
// total_hdr_size = size of header, post-header padding, and stack
let total_hdr_size = stack_begin_offset + Stack::<usize>::bytes_for(candidate);
// Padding between the pointer stack and the array of objects. NOTE:
... | let stack_begin_offset = hdr_size + pre_stack_padding;
// Find the largest number of objects we can fit in the slab. array_begin_offset is the
// offset from the beginning of the slab of the array of objects.
let (mut num_obj, mut array_begin_offset) = (0, 0); | random_line_split |
stack.rs | // Copyright 2017-2018 the authors. See the 'Copyright and license' section of the
// README.md file at the top-level directory of this repository.
//
// Licensed under the Apache License, Version 2.0 (the LICENSE-APACHE file) or
// the MIT license (the LICENSE-MIT file) at your option. This file may not be
// copied, ... | else {
break;
}
}
if num_obj == 0 {
return None;
}
assert!(array_begin_offset > 0);
let unused_space = slab_size - array_begin_offset - (num_obj * obj_size);
let l = Layout {
num_obj: num_obj,
layout: layou... | {
num_obj = candidate;
array_begin_offset = total_hdr_size + post_stack_padding;
} | conditional_block |
stack.rs | // Copyright 2017-2018 the authors. See the 'Copyright and license' section of the
// README.md file at the top-level directory of this repository.
//
// Licensed under the Apache License, Version 2.0 (the LICENSE-APACHE file) or
// the MIT license (the LICENSE-MIT file) at your option. This file may not be
// copied, ... |
}
pub struct SlabHeader {
stack: Stack<usize>, // note: this is only the metadata; the real stack comes after this header
color: Color, // extra padding added before array beginning
next: Option<NonNull<SlabHeader>>,
prev: Option<NonNull<SlabHeader>>,
}
impl Linkable for SlabHeader {
fn ne... | {
unsafe {
let slab = self.data.ptr_to_slab(self.alloc.layout().size(), obj);
let was_empty = (*slab.as_ptr()).stack.size() == 0;
let stack_data_ptr = self.layout.stack_begin(slab);
(*slab.as_ptr())
.stack
.push(stack_data_ptr, I::... | identifier_body |
Total_ALE.py | """
This code was implemented by Vojtech Kubac as a part of his Master Thesis that will be defended
on February 2020. At the Faculty of Mathematics and Physics of Charles University in Prague.
"""
"""
This code solves FSI2 and FSI3 Bencmarks from
"S. Turek and J. Hron, “Proposal for numerical benchmarking of fluid... | # approximate time derivatives
du = (1.0/self.dt)*(self.u - self.u0)
dv = (1.0/self.dt)*(self.v - self.v0)
# compute velocuty part of Cauchy stress tensor for fluid
self.T_f = -self.p*I + 2*self.mu_f*sym(Grad(self.v, self.FF))
self.T_f0 = -self.p*I + 2*self.mu_f*sym(Grad(s... | tr( Grad(f, F) )
| identifier_body |
Total_ALE.py | """
This code was implemented by Vojtech Kubac as a part of his Master Thesis that will be defended
on February 2020. At the Faculty of Mathematics and Physics of Charles University in Prague.
"""
"""
This code solves FSI2 and FSI3 Bencmarks from
"S. Turek and J. Hron, “Proposal for numerical benchmarking of fluid... |
# name of mesh
mesh_name = options.mesh_name
relative_path_to_mesh = 'meshes/'+mesh_name+'.h5'
# time step size
dt = options.dt
# time stepping scheme
dt_scheme = options.dt_scheme
# choose theta according to dt_scheme
if dt_scheme in ['BE', 'BE_CN']:
theta = Constant(1.0)
elif dt_scheme == 'CN':
theta = Co... |
# name of benchmark
benchmark = options.benchmark | random_line_split |
Total_ALE.py | """
This code was implemented by Vojtech Kubac as a part of his Master Thesis that will be defended
on February 2020. At the Faculty of Mathematics and Physics of Charles University in Prague.
"""
"""
This code solves FSI2 and FSI3 Bencmarks from
"S. Turek and J. Hron, “Proposal for numerical benchmarking of fluid... | low.solve(t, dt)
flow.save(t)
t += float(dt)
if dt_scheme == 'BE_CN': flow.theta.assign(0.5)
while t < t_end:
if my_rank == 0:
info("t = %.4f, t_end = %.1f" % (t, t_end))
flow.solve(t, dt)
flow.save(t)
t += float(dt)
| t = %.4f, t_end = %.1f" % (t, t_end))
f | conditional_block |
Total_ALE.py | """
This code was implemented by Vojtech Kubac as a part of his Master Thesis that will be defended
on February 2020. At the Faculty of Mathematics and Physics of Charles University in Prague.
"""
"""
This code solves FSI2 and FSI3 Bencmarks from
"S. Turek and J. Hron, “Proposal for numerical benchmarking of fluid... | : return dot( grad(f), inv(F) )
def Div(f, F): return tr( Grad(f, F) )
# approximate time derivatives
du = (1.0/self.dt)*(self.u - self.u0)
dv = (1.0/self.dt)*(self.v - self.v0)
# compute velocuty part of Cauchy stress tensor for fluid
self.T_f = -self.p*I + 2*self.mu_... | , F) | identifier_name |
iscsi.go | /*
Copyright The Accelerated Container Image 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 ... |
// loadBackingStoreConfig loads OverlayBD backing store config.
func (o *snapshotter) loadBackingStoreConfig(ctx context.Context, snKey string) (*OverlayBDBSConfig, error) {
id, _, _, err := storage.GetInfo(ctx, snKey)
if err != nil {
return nil, errors.Wrapf(err, "failed to get info of snapshot %s", snKey)
}
... | {
id, info, _, err := storage.GetInfo(ctx, key)
if err != nil {
return errors.Wrapf(err, "failed to get info for snapshot %s", key)
}
stype, err := o.identifySnapshotStorageType(id, info)
if err != nil {
return errors.Wrapf(err, "failed to identify storage of snapshot %s", key)
}
configJSON := OverlayBDBSC... | identifier_body |
iscsi.go | /*
Copyright The Accelerated Container Image 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 ... | maxAttachAttempts = 10
defaultRollbackTimeout = 30 * time.Second
)
// OverlayBDBSConfig is the config of OverlayBD backing store in open-iscsi target.
type OverlayBDBSConfig struct {
RepoBlobURL string `json:"repoBlobUrl"`
Lowers []OverlayBDBSConfigLower `json:"lowers"`
Upper Ove... |
defaultInitiatorAddress = "127.0.0.1"
defaultInitiatorPort = "3260"
defaultPortal = defaultInitiatorAddress + ":" + defaultInitiatorPort
| random_line_split |
iscsi.go | /*
Copyright The Accelerated Container Image 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 ... |
}
defer func() {
// NOTE(fuweid): Basically, do login only once. The rollback doesn't impact other running portal.
if retErr != nil {
deferCtx, deferCancel := rollbackContext()
defer deferCancel()
out, err = exec.CommandContext(deferCtx, "iscsiadm", "-m", "node", "-p", defaultPortal, "-T", targetIqn, "... | {
return errors.Wrapf(err, "failed to login a portal on a target %s: %s", targetIqn, out)
} | conditional_block |
iscsi.go | /*
Copyright The Accelerated Container Image 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 ... | (dir string) error {
dir = filepath.Clean(dir)
m, err := mountinfo.GetMounts(mountinfo.SingleEntryFilter(dir))
if err != nil {
return errors.Wrapf(err, "failed to find the mount info for %q", dir)
}
if len(m) == 0 {
return errors.Errorf("failed to find the mount info for %q", dir)
}
return nil
}
func roll... | lookup | identifier_name |
cdk.py | from aws_cdk import (
aws_lambda as _lambda,
aws_s3_notifications as _s3notification,
aws_lambda_event_sources as _lambda_event_source,
aws_s3 as _s3,
aws_cognito as _cognito,
aws_sqs as _sqs,
aws_apigateway as _apigw,
aws_iam as _iam,
aws_events as _events,
aws_events_targets as... |
def add_cors_options(self, apigw_resource):
apigw_resource.add_method('OPTIONS', _apigw.MockIntegration(
integration_responses=[{
'statusCode': '200',
'responseParameters': {
'method.response.header.Access-Control-Allow-Headers': "'Content-Ty... | super().__init__(scope, id, **kwargs)
### S3 core
imagesS3Bucket = _s3.Bucket(self, "VAQUITA_IMAGES")
imagesS3Bucket.add_cors_rule(
allowed_methods=[_s3.HttpMethods.POST],
allowed_origins=["*"] # add API gateway web resource URL
)
### SQS core
i... | identifier_body |
cdk.py | from aws_cdk import (
aws_lambda as _lambda,
aws_s3_notifications as _s3notification,
aws_lambda_event_sources as _lambda_event_source,
aws_s3 as _s3,
aws_cognito as _cognito,
aws_sqs as _sqs,
aws_apigateway as _apigw,
aws_iam as _iam,
aws_events as _events,
aws_events_targets as... | (self, apigw_resource):
apigw_resource.add_method('OPTIONS', _apigw.MockIntegration(
integration_responses=[{
'statusCode': '200',
'responseParameters': {
'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorizatio... | add_cors_options | identifier_name |
cdk.py | from aws_cdk import (
aws_lambda as _lambda,
aws_s3_notifications as _s3notification,
aws_lambda_event_sources as _lambda_event_source,
aws_s3 as _s3,
aws_cognito as _cognito,
aws_sqs as _sqs,
aws_apigateway as _apigw,
aws_iam as _iam,
aws_events as _events,
aws_events_targets as... | allowed_o_auth_flows_user_pool_client=True,
explicit_auth_flows=["ALLOW_REFRESH_TOKEN_AUTH"])
userPoolDomain = _cognito.UserPoolDomain(self, "VAQUITA_USERS_POOL_DOMAIN",
user_pool=usersPool,
cognito_domain=_cognito.CognitoDomainOptions(domain_prefix="vaquita"))... | supported_identity_providers=["COGNITO"],
allowed_o_auth_flows=["implicit"],
allowed_o_auth_scopes=["phone", "email", "openid", "profile"],
user_pool_id=usersPool.user_pool_id,
callback_ur_ls=[apiGatewayLandingPageResource.url], | random_line_split |
Tablemodels.py |
def curspatial(self):
from pysqlite2 import dbapi2 as sql
self.sql_connection = sql.Connection(self.mainDB) # This is the path to the database. If it doesn't exist, it will be created, though, of course, without the require tables
self.cursorspatial = sql.Cursor(self.sql_connection)
self.sql... |
return partsList
def reverseParseGeo(self, shpReader):
geomtype = find_key(self.fieldTypes, shpReader.shapeType )
if geomtype == 'POINT':
WKTlist = []
WKTtemplate = 'POINT(%f %f)'
shapes = shpReader.shapes()
for sha... | partsList = []
geom = geometry.split('((')[1].replace('))','')
partSplit = geom.split('), (')
for part in partSplit:
geomlist = []
geomsplit = part.split(', ')
for COUNTER,geoms in enumerate(geomsplit):
... | conditional_block |
Tablemodels.py | def curspatial(self):
from pysqlite2 import dbapi2 as sql
self.sql_connection = sql.Connection(self.mainDB) # This is the path to the database. If it doesn't exist, it will be created, though, of course, without the require tables
self.cursorspatial = sql.Cursor(self.sql_connection)
self.sql_con... | WKTlist.append(WKT)
return WKTlist
def unit(self):
def shapeRowsGen(self):
def exportRows(self,row):
def getCreateStatment(self):
create = self.sqlCreate, self.name
def multiplier(self):
... | WKT += str(coords[0]) + ' '+ str(coords[1])+ ')'
| random_line_split |
Tablemodels.py |
def curspatial(self):
from pysqlite2 import dbapi2 as sql
self.sql_connection = sql.Connection(self.mainDB) # This is the path to the database. If it doesn't exist, it will be created, though, of course, without the require tables
self.cursorspatial = sql.Cursor(self.sql_connection)
self.sql... | (self, params, args, where=None):
newparams = ''
for param in params:
if count == len(params)-1:
newparams = self.sqlSet.format(param) + ','
else:
newparams = self.sqlSet.format(param)
if where:
... | update | identifier_name |
Tablemodels.py |
def curspatial(self):
from pysqlite2 import dbapi2 as sql
self.sql_connection = sql.Connection(self.mainDB) # This is the path to the database. If it doesn't exist, it will be created, though, of course, without the require tables
self.cursorspatial = sql.Cursor(self.sql_connection)
self.sql... |
def valuesGen(self,params,min=0,max=None):
'get selected rows of data'
self.rows=[]
if max == None:
params = (fields, self.name)
select = self.sqlSelect, params
else:
params = (fields, self.name)
args= min, max
... | 'adjust recorded order of fields'
return | identifier_body |
refract.py | # Module refract.py
import math
def refdry(nu, T, Pdry, Pvap):
# From Miriad: Determine the complex refractivity of the dry components
# of the atmosphere.
#
# Input:
# nu = observing frequency (Hz)
# T = temperature (K)
# Pdry = partial pressure of dry components (Pa)
# Pvap = part... | 0.8, 0.1, 0.5, 0.7, -1.0, 5.8,
2.9, 2.3, 0.9, 2.2, 2.0, 2.0,
1.8, 1.9, 1.8, 1.8, 1.7, 1.8,
1.7, 1.7, 1.7, 1.7, 1.7, 0.9,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ]
# Convert to the units of Liebe.
theta = 300.0 / T
e = 0.001 * Pvap
... | a6 = [ 1.7, 1.7, 1.7, 1.7, 1.8, 1.8,
1.8, 1.9, 1.8, 2.0, 1.9, 2.1,
2.1, 0.9, 2.3, 2.5, 3.7, -3.1, | random_line_split |
refract.py | # Module refract.py
import math
def refdry(nu, T, Pdry, Pvap):
# From Miriad: Determine the complex refractivity of the dry components
# of the atmosphere.
#
# Input:
# nu = observing frequency (Hz)
# T = temperature (K)
# Pdry = partial pressure of dry components (Pa)
# Pvap = part... |
def calcOpacity(freq, el, t0, p0, h0):
# From Miriad; Compute sky brightness and opacity of a model atmosphere.
# Returns the transmissivity of the atmosphere given frequency, elevation
# angle and meteorological data. This uses a simple model of the atmosphere
# and Liebe's model (1985) of the comple... | HMKS = 6.6260755e-34 # Planck constant, J.s
KMKS = 1.380658e-23 # Boltzmann constant, J/K
CMKS = 299792458 # Speed of light, m/s
tau = 0.0
Tb = HMKS * nu / (KMKS * (math.exp(HMKS * nu / (KMKS * T0)) - 1))
Ldry = 0.0
Lvap = 0.0
snell = math.sin(el)
for i in xrange(n, 0, -1):
if ... | identifier_body |
refract.py | # Module refract.py
import math
def refdry(nu, T, Pdry, Pvap):
# From Miriad: Determine the complex refractivity of the dry components
# of the atmosphere.
#
# Input:
# nu = observing frequency (Hz)
# T = temperature (K)
# Pdry = partial pressure of dry components (Pa)
# Pvap = part... |
# Return the result.
return complex(nr, ni)
def pvapsat(T):
# From Miriad; Determine the saturation pressure of water vapour.
# Input:
# T = temperature (K)
#
# Output:
# vapour saturation pressure (Pa)
if (T > 215):
theta = 300.0 / T
return 1e5 / (41.51 * (... | S = b1[i] * e * theta ** 3.5 * math.exp(b2[i] * (1.0 - theta))
gamma = b3[i] * (p * theta ** 0.8 + 4.80 * e * theta)
x = (mnu0[i] - f) * (mnu0[i] - f) + gamma * gamma
y = (mnu0[i] + f) * (mnu0[i] + f) + gamma * gamma
z = (mnu0[i] + gamma * gamma / mnu0[i])
nr = nr + S * ((z - f) ... | conditional_block |
refract.py | # Module refract.py
import math
def refdry(nu, T, Pdry, Pvap):
# From Miriad: Determine the complex refractivity of the dry components
# of the atmosphere.
#
# Input:
# nu = observing frequency (Hz)
# T = temperature (K)
# Pdry = partial pressure of dry components (Pa)
# Pvap = part... | (t, pdry, pvap, z, n, nu, T0, el):
# From Miriad; Compute refractive index for an atmosphere.
# Determine the sky brightness and excess path lengths for a parallel
# slab atmosphere. Liebe's model (1985) is used to determine the complex
# refractive index of air.
#
# Input:
# n = the number... | refract | identifier_name |
admin.js |
Meteor.methods({
finduser: function(x){
if (Meteor.isServer){
if (Accounts.findUserByUsername(x)){
console.log("Server found: " + Accounts.findUserByUsername(x).username);
return true;
} else {
return false;
}
}
},
playerSetup: function(user){
if (Meteor.isServer){
console.log("player... |
stub.drinks.recd.forEach(findsender);
if (typeof(res)==="number"){
temp.position=res;
temp.drink=stub.drinks.recd[res];
return temp;
}
else return false;
} else if (job==="movedrink"){
var recd = Meteor.users.find({username:user}).fetch()[0].shadow.drinks.recd[input];
Meteor.u... | {
if (element.sender.toLowerCase()===input){
res=index;
}
} | identifier_body |
admin.js |
Meteor.methods({
finduser: function(x){
if (Meteor.isServer){
if (Accounts.findUserByUsername(x)){
console.log("Server found: " + Accounts.findUserByUsername(x).username);
return true;
} else {
return false;
}
}
},
playerSetup: function(user){
if (Meteor.isServer){
console.log("player... | (element,index,array){
if (element.sender.toLowerCase()===input){
res=index;
}
}
stub.drinks.recd.forEach(findsender);
if (typeof(res)==="number"){
temp.position=res;
temp.drink=stub.drinks.recd[res];
return temp;
}
else return false;
} else if (job==="movedrink"){
... | findsender | identifier_name |
admin.js |
Meteor.methods({
finduser: function(x){
if (Meteor.isServer) |
},
playerSetup: function(user){
if (Meteor.isServer){
console.log("playerSetup checkin");
var temp = shadowprofile;
temp.profileStarted = monthday;
Meteor.users.update({username: user},{$set: {shadow: temp}});
Meteor.users.update({username: user},{$set: {"bank.deposit": 0}});
console.log("NEW USE... | {
if (Accounts.findUserByUsername(x)){
console.log("Server found: " + Accounts.findUserByUsername(x).username);
return true;
} else {
return false;
}
} | conditional_block |
admin.js | Meteor.methods({
finduser: function(x){
if (Meteor.isServer){
if (Accounts.findUserByUsername(x)){
console.log("Server found: " + Accounts.findUserByUsername(x).username);
return true;
} else {
return false;
}
}
},
playerSetup: function(user){
if (Meteor.isServer){
console.log("playerS... | Meteor.users.update({username:player},{$push:{"shadow.duel.old":temp[i]}});
// Shadow.update({username:player},{$push:{"profile.duel.old":temp[i]}});
}
Meteor.users.update({username:player},{$set:{"shadow.duel.new":[]}});
// Shadow.update({username:player},{$set:{"profile.duel.new":[]}});
} els... | // Shadow.update({username:player},{$set:{"profile.duelflag":false}});
var temp = Meteor.users.find({username:player}).fetch()[0].shadow.duel.new;
for (i=0;i<temp.length;i++){ | random_line_split |
universal_cluster.go | package framework
import (
"net"
"os"
"path/filepath"
"time"
"github.com/gruntwork-io/terratest/modules/k8s"
"github.com/gruntwork-io/terratest/modules/retry"
"github.com/gruntwork-io/terratest/modules/testing"
"github.com/pkg/errors"
"go.uber.org/multierr"
"github.com/kumahq/kuma/pkg/config/core"
core_me... | KumaCp UniversalNetworking `json:"kumaCp"`
}
type UniversalCluster struct {
t testing.TestingT
name string
controlplane *UniversalControlPlane
apps map[string]*UniversalApp
verbose bool
deployments map[string]Deployment
defaultTimeout time.Duration
defaultRetr... |
type UniversalNetworkingState struct {
ZoneEgress UniversalNetworking `json:"zoneEgress"`
ZoneIngress UniversalNetworking `json:"zoneIngress"` | random_line_split |
universal_cluster.go | package framework
import (
"net"
"os"
"path/filepath"
"time"
"github.com/gruntwork-io/terratest/modules/k8s"
"github.com/gruntwork-io/terratest/modules/retry"
"github.com/gruntwork-io/terratest/modules/testing"
"github.com/pkg/errors"
"go.uber.org/multierr"
"github.com/kumahq/kuma/pkg/config/core"
core_me... |
func (c *UniversalCluster) DeleteApp(appname string) error {
app, ok := c.apps[appname]
if !ok {
return errors.Errorf("App %s not found for deletion", appname)
}
if err := app.Stop(); err != nil {
return err
}
delete(c.apps, appname)
return nil
}
func (c *UniversalCluster) DeleteMesh(mesh string) error {
... | {
return c.apps[appName]
} | identifier_body |
universal_cluster.go | package framework
import (
"net"
"os"
"path/filepath"
"time"
"github.com/gruntwork-io/terratest/modules/k8s"
"github.com/gruntwork-io/terratest/modules/retry"
"github.com/gruntwork-io/terratest/modules/testing"
"github.com/pkg/errors"
"go.uber.org/multierr"
"github.com/kumahq/kuma/pkg/config/core"
core_me... | () UniversalNetworking {
return c.networking[Config.ZoneIngressApp]
}
func (c *UniversalCluster) GetZoneEgressNetworking() UniversalNetworking {
return c.networking[Config.ZoneEgressApp]
}
func (c *UniversalCluster) AddNetworking(networking UniversalNetworking, name string) error {
c.networking[name] = networking
... | GetZoneIngressNetworking | identifier_name |
universal_cluster.go | package framework
import (
"net"
"os"
"path/filepath"
"time"
"github.com/gruntwork-io/terratest/modules/k8s"
"github.com/gruntwork-io/terratest/modules/retry"
"github.com/gruntwork-io/terratest/modules/testing"
"github.com/pkg/errors"
"go.uber.org/multierr"
"github.com/kumahq/kuma/pkg/config/core"
core_me... |
path = filepath.Join(path, "kuma-cp.conf")
if err := os.WriteFile(path, []byte(c.opts.yamlConfig), 0o600); err != nil {
return err
}
dockerVolumes = append(dockerVolumes, path+":/kuma/kuma-cp.conf")
}
cmd := []string{"kuma-cp", "run", "--config-file", "/kuma/kuma-cp.conf"}
if mode == core.Zone {
zoneN... | {
return err
} | conditional_block |
request.go | package request
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2020-01-01/containerservice"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/g... |
stsClient := sts.New(sess)
request, _ := stsClient.GetCallerIdentityRequest(&sts.GetCallerIdentityInput{})
request.HTTPRequest.Header.Add("x-k8s-aws-id", clusterID)
presignedURLString, err := request.Presign(60)
if err != nil {
return "", err
}
return fmt.Sprintf(`{"token": "k8s-aws-v1.%s"}`, base64.RawURL... | {
return "", err
} | conditional_block |
request.go | package request
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2020-01-01/containerservice"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/g... | (discoveryURL, clientID, clientSecret, redirectURL, code string) (string, error) {
ctx := context.Background()
provider, err := oidc.NewProvider(ctx, discoveryURL)
if err != nil {
return "", err
}
oauth2Config := oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,... | OIDCGetRefreshToken | identifier_name |
request.go | package request
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2020-01-01/containerservice"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/g... |
// AzureGetClusters return all Kubeconfigs for all AKS clusters for the provided subscription and resource group.
func AzureGetClusters(subscriptionID, clientID, clientSecret, tenantID, resourceGroupName string, admin bool) (string, error) {
ctx := context.Background()
client := containerservice.NewManagedClustersC... | {
cred := credentials.NewStaticCredentials(accessKeyId, secretAccessKey, "")
sess, err := session.NewSession(&aws.Config{Region: aws.String(region), Credentials: cred})
if err != nil {
return "", err
}
stsClient := sts.New(sess)
request, _ := stsClient.GetCallerIdentityRequest(&sts.GetCallerIdentityInput{})
... | identifier_body |
request.go | package request
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2020-01-01/containerservice"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/g... | cert, err := tls.X509KeyPair([]byte(clientCertificateData), []byte(clientKeyData))
if err != nil {
return nil, err
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
tlsConfig.InsecureSkipVerify = insecureSkipTLSVerify
return &tlsConfig, nil
}
// AWSGetClusters returns all EKS clusters from AWS.
fun... | random_line_split | |
quantize_model.py | # Copyright (c) 2023 Intel Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... |
def wrap_outputs(retval):
return wrap_nncf_model_outputs_with_objwalk(retval)
def create_dummy_forward_fn(data_loader, device):
def dummy_forward(model):
with no_nncf_trace():
data_item = next(iter(data_loader))
args, kwargs = data_loader.get_inputs... | return wrap_nncf_model_inputs_with_objwalk(args, kwargs) | identifier_body |
quantize_model.py | # Copyright (c) 2023 Intel Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... | flow graph nodes to be ignored during quantization.
:param advanced_parameters: Advanced quantization parameters for
fine-tuning the quantization algorithm.
:return: NNCFConfig for the quantization algorithm.
"""
if model_type is None:
compression_config = _get_default_quantizati... | statistics used for quantization.
:param model_type: Model type is needed to specify additional patterns
in the model.
:param ignored_scope: An ignored scope that defined the list of model control | random_line_split |
quantize_model.py | # Copyright (c) 2023 Intel Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... | (iterable) -> int:
length = 0
for _ in iterable:
length = length + 1
return length
def _get_transformer_quantization_config(subset_size: int) -> Dict[str, Any]:
"""
Returns the quantization config for transformer-based models.
:param subset_size: Size of a subset to c... | _get_length | identifier_name |
quantize_model.py | # Copyright (c) 2023 Intel Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... |
nncf_config = _create_nncf_config(
preset, target_device, subset_size, model_type, ignored_scope, advanced_parameters
)
calibration_data_loader = CalibrationDataLoader(calibration_dataset)
nncf_config.register_extra_structs(
[
QuantizationRangeInitArgs(data_loader=calibrat... | raise RuntimeError("target_device == CPU_SPR is not supported") | conditional_block |
be_sr.js | 'use strict'; /*jshint -W100, browser:true, es5:true*/
define(function(){
var E = {
"DJ": {message: "Џибути"},
"JM": {message: "Јамајка"},
"AT": {message: "Аустрија"},
"Want Hola on other devices? (Xbox, PS, Apple TV, iPhone...). Click here": {message: "Желите Хола на другим уређајима? (Ксбок, ПС, Аппле... | "CA": {message: "Канада"},
"Starting...": {message: "Покретање ..."},
"CM": {message: "Камерун"},
"Hola": {message: "Хола"},
"NP": {message: "Непал"},
"PL": {message: "Пољска"},
"GA": {message: "Габон"},
"TM": {message: "Туркменистан"},
"KY": {message: "Кајманска Острва"},
"LA": ... | "PT": {message: "Португал"}, | random_line_split |
api_op_GetCredentials.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package redshiftserverless
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
... | (ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
re... | HandleSerialize | identifier_name |
api_op_GetCredentials.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package redshiftserverless
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
... |
func newServiceMetadataMiddleware_opGetCredentials(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "redshift-serverless",
OperationName: "GetCredentials",
}
}
type opGetCredentialsResolveE... | {
err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetCredentials{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetCredentials{}, middleware.After)
if err != nil {
return err
}
if err = addlegacyEndpointContextSetter(stack, options); err != nil {
... | identifier_body |
api_op_GetCredentials.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package redshiftserverless
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
... | else {
signingName = *v4Scheme.SigningName
}
if v4Scheme.SigningRegion == nil {
signingRegion = m.BuiltInResolver.(*builtInResolver).Region
} else {
signingRegion = *v4Scheme.SigningRegion
}
if v4Scheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initi... | {
signingName = "redshift-serverless"
} | conditional_block |
api_op_GetCredentials.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package redshiftserverless
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
... |
// Returns a database user name and temporary password with temporary
// authorization to log in to Amazon Redshift Serverless. By default, the temporary
// credentials expire in 900 seconds. You can optionally specify a duration between
// 900 seconds (15 minutes) and 3600 seconds (60 minutes). The Identity and Acces... | "time"
) | random_line_split |
api.ts | import request from './request'
import { path } from 'src/config'
import { doInitWxApp, localGet, getOpenId } from 'src/services/wx_auth'
import { UrlParse } from 'src/common/functions'
import MP from 'MP'
import storage from 'storage'
import Cookie from 'cookie'
// 延迟函数 需要在APP lanunch方法结束之后再发起其他的请求
// 因为code2session的... | identifier_name | ||
api.ts | import request from './request'
import { path } from 'src/config'
import { doInitWxApp, localGet, getOpenId } from 'src/services/wx_auth'
import { UrlParse } from 'src/common/functions'
import MP from 'MP'
import storage from 'storage'
import Cookie from 'cookie'
// 延迟函数 需要在APP lanunch方法结束之后再发起其他的请求
// 因为code2session的... | Interface {
openid: string,
avatarUrl: string,
city: string,
country: string,
gender: number,
language: string,
nickName: string,
province: string
}
export const useropenid = () => {
}
export const weixinSign = function(param) {
return request({ url: path + 'common/weixinSign', data: param, method: '... | delayWhenAppLaunchLoaded: function() {
let self = this
return new Promise(function(resolve) {
if (self.loaded) {
resolve()
}
if (mpvuePlatform === 'h5') {
resolve()
} else {
let appLaunchId = setInterval(function() {
if (self.loaded... | identifier_body |
api.ts | import request from './request'
import { path } from 'src/config'
import { doInitWxApp, localGet, getOpenId } from 'src/services/wx_auth'
import { UrlParse } from 'src/common/functions'
import MP from 'MP'
import storage from 'storage'
import Cookie from 'cookie'
// 延迟函数 需要在APP lanunch方法结束之后再发起其他的请求
// 因为code2session的... | return result
}
// 微信小程序 微信授权登录 保存用户信息
export const saveWxUserInfoServer = async function(param) {
const result = await request({ url: path + 'common/saveWxUserInfoServer', data: param, method: 'POST' })
return result
}
export const getCity = async function() {
const result = await request({ url: path + 'tjapi... |
export const code2session = async function(appid, code) {
const result: Code2sessionResult = await request({ url: path + 'tjapi/user/wxCodeLogin', data: { appid, code }, method: 'POST' }) | random_line_split |
api.ts | import request from './request'
import { path } from 'src/config'
import { doInitWxApp, localGet, getOpenId } from 'src/services/wx_auth'
import { UrlParse } from 'src/common/functions'
import MP from 'MP'
import storage from 'storage'
import Cookie from 'cookie'
// 延迟函数 需要在APP lanunch方法结束之后再发起其他的请求
// 因为code2session的... | launchQueue()
// 获取用户类型
export interface UserInfoInterface {
openid: string,
avatarUrl: string,
city: string,
country: string,
gender: number,
language: string,
nickName: string,
province: string
}
export const useropenid = () => {
}
export const weixinSign = function(param) {
return request({ url: ... | }, 100)
}
})
}
}
}
export const appLaunchQueue = | conditional_block |
german_traffic_pytorch.py | # -*- coding: utf-8 -*-
"""German_traffic_PyTorch.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1FC0V5Jk3eXeLksRQBsGfzT1Kyc8PO65R
"""
# Jovian Commit Essentials
# Please retain and execute this cell without modifying the contents for `jovian.co... |
model = Resnet(3,numClasses)
model = to_device(model, device)
# Function to count the number of parameters in the model
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
# Print model
print(model)
# Print number of trainable parameters in the model
print(f'The mode... | def __init__(self,in_channels, output_dim):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(in_channels, out_channels=16, kernel_size=3, stride=1, padding=1),
nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1),
nn.ReLU(... | identifier_body |
german_traffic_pytorch.py | # -*- coding: utf-8 -*-
"""German_traffic_PyTorch.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1FC0V5Jk3eXeLksRQBsGfzT1Kyc8PO65R
"""
# Jovian Commit Essentials
# Please retain and execute this cell without modifying the contents for `jovian.co... |
else:
return torch.device('cpu')
def to_device(data, device):
"""Move tensor(s) to chosen device"""
if isinstance(data, (list,tuple)):
return [to_device(x, device) for x in data]
return data.to(device, non_blocking=True)
class DeviceDataLoader():
"""Wrap a dataloader to move d... | return torch.device('cuda') | conditional_block |
german_traffic_pytorch.py | # -*- coding: utf-8 -*-
"""German_traffic_PyTorch.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1FC0V5Jk3eXeLksRQBsGfzT1Kyc8PO65R
"""
# Jovian Commit Essentials
# Please retain and execute this cell without modifying the contents for `jovian.co... |
import jovian
project_name="01-German_traffic"
jovian.commit(project=project_name)
"""## For GPU"""
def get_default_device():
"""Pick GPU if available, else CPU"""
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu')
def to_device(data, device):... | break
show_batch(train_loader) | random_line_split |
german_traffic_pytorch.py | # -*- coding: utf-8 -*-
"""German_traffic_PyTorch.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1FC0V5Jk3eXeLksRQBsGfzT1Kyc8PO65R
"""
# Jovian Commit Essentials
# Please retain and execute this cell without modifying the contents for `jovian.co... | (self, x):
x = self.features(x)
x = x.view(x.shape[0], -1)
x = self.classifier(x)
return x
model = Resnet(3,numClasses)
model = to_device(model, device)
# Function to count the number of parameters in the model
def count_parameters(model):
return sum(p.numel() for p in model.paramet... | forward | identifier_name |
format.go | package types
import (
"bytes"
"fmt"
"io"
"sort"
"strconv"
"strings"
"unicode/utf8"
"github.com/lyraproj/issue/issue"
"github.com/lyraproj/puppet-evaluator/errors"
"github.com/lyraproj/puppet-evaluator/eval"
"github.com/lyraproj/puppet-evaluator/utils"
)
type (
format struct {
alt bool
l... | }
var DEFAULT_ARRAY_FORMAT = basicFormat('a', `,`, '[', nil)
var DEFAULT_HASH_FORMAT = basicFormat('h', ` => `, '{', nil)
var DEFAULT_OBJECT_FORMAT = basicFormat('p', ` => `, '(', nil)
var DEFAULT_ARRAY_CONTAINER_FORMAT = basicFormat('p', `,`, '[', nil)
var DEFAULT_HASH_CONTAINER_FORMAT = basicFormat('p', ` => `, '{'... | eval.NewFormatContext3 = newFormatContext3
eval.NewIndentation = newIndentation
eval.NewFormat = newFormat
eval.PRETTY_EXPANDED = eval.PRETTY.WithProperties(map[string]string{`expanded`: `true`}) | random_line_split |
format.go | package types
import (
"bytes"
"fmt"
"io"
"sort"
"strconv"
"strings"
"unicode/utf8"
"github.com/lyraproj/issue/issue"
"github.com/lyraproj/puppet-evaluator/errors"
"github.com/lyraproj/puppet-evaluator/eval"
"github.com/lyraproj/puppet-evaluator/utils"
)
type (
format struct {
alt bool
l... |
if f.Precision() >= 0 {
fmt.Fprintf(bld, `.%d`, f.Precision())
}
bld.WriteByte('s')
fmt.Fprintf(b, bld.String(), str)
} else {
if quoted {
utils.PuppetQuote(b, str)
} else {
io.WriteString(b, str)
}
}
}
func (f *format) Width() int {
return f.width
}
func (f *format) Precision() int {
retu... | {
fmt.Fprintf(bld, `%d`, f.Width())
} | conditional_block |
format.go | package types
import (
"bytes"
"fmt"
"io"
"sort"
"strconv"
"strings"
"unicode/utf8"
"github.com/lyraproj/issue/issue"
"github.com/lyraproj/puppet-evaluator/errors"
"github.com/lyraproj/puppet-evaluator/eval"
"github.com/lyraproj/puppet-evaluator/utils"
)
type (
format struct {
alt bool
l... | () bool {
return f.left || f.width >= 0 || f.prec >= 0
}
func (f *format) ApplyStringFlags(b io.Writer, str string, quoted bool) {
if f.HasStringFlags() {
bld := bytes.NewBufferString(``)
if quoted {
utils.PuppetQuote(bld, str)
str = bld.String()
bld.Truncate(0)
}
bld.WriteByte('%')
if f.IsLeft() ... | HasStringFlags | identifier_name |
format.go | package types
import (
"bytes"
"fmt"
"io"
"sort"
"strconv"
"strings"
"unicode/utf8"
"github.com/lyraproj/issue/issue"
"github.com/lyraproj/puppet-evaluator/errors"
"github.com/lyraproj/puppet-evaluator/eval"
"github.com/lyraproj/puppet-evaluator/utils"
)
type (
format struct {
alt bool
l... |
type stringReader struct {
i int
text string
}
func (r *stringReader) Next() (rune, bool) {
if r.i >= len(r.text) {
return 0, false
}
c := rune(r.text[r.i])
if c < utf8.RuneSelf {
r.i++
return c, true
}
c, size := utf8.DecodeRuneInString(r.text[r.i:])
if c == utf8.RuneError {
panic(`invalid unico... | {
nf := &format{}
*nf = *f
nf.width = -1
nf.left = false
nf.zeroPad = false
nf.alt = false
nf.origFmt = nf.unParse()
return nf
} | identifier_body |
text.rs | use std::cmp::max;
use std::collections::HashMap;
use std::string::ToString;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::render::{BlendMode, Canvas, Texture, TextureCreator, WindowCanvas};
use sdl2::surface::Surface;
use sdl2::ttf::Font as Sdl2Font;
use sdl2::video::WindowContext;
use crate::ui::types::{... |
pub fn draw(&mut self, screen_txt: ScreenText, cvs: &mut WindowCanvas) -> Result<(), String> {
let cache_key = screen_txt.text.to_string();
if let Some((ref mut tex, w, h)) = self.cached_texts.get_mut(&cache_key) {
let (tw, th) = scale_dim(screen_txt.scale, *w, *h);
let Sc... | {
let mut total_width = 0;
let mut total_height = 0;
let mut glyphs: Vec<GlyphRegion> = Vec::new();
let mut space_advance = 0;
for c in ASCII.chars() {
if let Some(metric) = font.find_glyph_metrics(c) {
let (w, h) = font.size_of_char(c).map_err(to_str... | identifier_body |
text.rs | use std::cmp::max;
use std::collections::HashMap;
use std::string::ToString;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::render::{BlendMode, Canvas, Texture, TextureCreator, WindowCanvas};
use sdl2::surface::Surface;
use sdl2::ttf::Font as Sdl2Font;
use sdl2::video::WindowContext;
use crate::ui::types::{... | line_height: total_height,
space_advance,
texture_creator,
cached_texts: HashMap::new(),
})
}
pub fn draw(&mut self, screen_txt: ScreenText, cvs: &mut WindowCanvas) -> Result<(), String> {
let cache_key = screen_txt.text.to_string();
if l... | font_canvas: font_canvas,
glyphs, | random_line_split |
text.rs | use std::cmp::max;
use std::collections::HashMap;
use std::string::ToString;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::render::{BlendMode, Canvas, Texture, TextureCreator, WindowCanvas};
use sdl2::surface::Surface;
use sdl2::ttf::Font as Sdl2Font;
use sdl2::video::WindowContext;
use crate::ui::types::{... | (scale_factor: f32, w: u32, h: u32) -> (u32, u32) {
(
(w as f32 * scale_factor).round() as u32,
(h as f32 * scale_factor).round() as u32,
)
}
fn align_line_horizontal(a: Align, line_width: u32, text_width: u32) -> i32 {
match a {
Align::TopLeft => 0,
Align::MidCenter => (tex... | scale_dim | identifier_name |
text.rs | use std::cmp::max;
use std::collections::HashMap;
use std::string::ToString;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::render::{BlendMode, Canvas, Texture, TextureCreator, WindowCanvas};
use sdl2::surface::Surface;
use sdl2::ttf::Font as Sdl2Font;
use sdl2::video::WindowContext;
use crate::ui::types::{... | else {
return Err(format!("Unsupported character: {}", c));
}
}
let mut font_canvas = Surface::new(
total_width,
total_height,
texture_creator.default_pixel_format(),
)?
.into_canvas()?;
let font_texture_creator =... | {
let (w, h) = font.size_of_char(c).map_err(to_string)?;
glyphs.push(GlyphRegion {
start: total_width as i32,
width: w,
height: h,
advance: metric.advance,
});
if c == ' ' {
... | conditional_block |
rest.go | package rest
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/lorenyeung/go-files/auth"
"github.com/lorenyeung/go-files/helpers"
log "github.com/sirupsen/logrus"
)
//GetFilesDetails get file details, sort by date and print
func Get... |
if strings.Contains(download+filesList.Children[i].URI, "%") {
log.Warn("Encoding charactrer % detected in file URL, ", download+filesList.Children[i].URI, ", skipping")
return
}
if !strings.Contains(fileDetail.DownloadURI, url) {
log.Debug("Debug, url details:", fileDetail.DownloadURI, " :", url,... | json.Unmarshal([]byte(data2), &fileDetail)
log.Debug("Debug before, url details:", fileDetail.DownloadURI, " :", url, " :data:", fileDetail, " download uri:", download+filesList.Children[i].URI) | random_line_split |
rest.go | package rest
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/lorenyeung/go-files/auth"
"github.com/lorenyeung/go-files/helpers"
log "github.com/sirupsen/logrus"
)
//GetFilesDetails get file details, sort by date and print
func Get... | else if strings.Contains(download, "-") {
//parse ranges
words = nil
numbers := strings.Split(download, " ")
for i := 0; i < len(numbers); i++ {
if strings.Contains(numbers[i], "-") {
log.Info("found number with dash ", numbers[i])
splitNumbers := strings.Split(numbers[i], "-")
first, err := str... | {
log.Info("zero detected, downloading everything")
words = nil
for i := 0; i < sortedSize; i++ {
t := strconv.Itoa(i + 1)
words = append(words, t)
}
} | conditional_block |
rest.go | package rest
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/lorenyeung/go-files/auth"
"github.com/lorenyeung/go-files/helpers"
log "github.com/sirupsen/logrus"
)
//GetFilesDetails get file details, sort by date and print
func Get... |
func DetectDetailsFile(readme, masterKey string) {
if _, err := os.Stat(readme); os.IsNotExist(err) {
log.Info("Readme does not exist, creating")
fmt.Println("Readme Title:")
reader := bufio.NewReader(os.Stdin)
readmeTitleIn, _ := reader.ReadString('\n')
readmeTitle := strings.TrimSuffix(readmeTitleIn, "\... | {
sortedSize := len(sorted)
fmt.Println("Which files do you wish to download? Please separate each number by a space. Use a '-' for ranges, like: 1 3-6 11-12:")
reader := bufio.NewReader(os.Stdin)
downloadIn, _ := reader.ReadString('\n')
download := strings.TrimSuffix(downloadIn, "\n")
words := strings.Fields(do... | identifier_body |
rest.go | package rest
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/lorenyeung/go-files/auth"
"github.com/lorenyeung/go-files/helpers"
log "github.com/sirupsen/logrus"
)
//GetFilesDetails get file details, sort by date and print
func | (username, apiKey, url, repo, download string) helpers.TimeSlice {
//create map of all file details from list of files
var unsorted = make(map[int]helpers.FileStorageJSON)
var filesList helpers.StorageJSON
var data, _ = auth.GetRestAPI(url+"/api/storage/"+repo+"/"+download+"/", username, apiKey, "", "")
json.Unma... | GetFilesDetails | identifier_name |
common.rs | use std::collections::HashSet;
pub type PlayerId = usize;
/// Represent a player during a game.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Player {
/// An integer that uniquely identifies each player during a game
pub id: PlayerId,
/// Number of tiles the player currently owns
#[serde(s... | Up,
Down,
}
#[derive(Copy, Clone, Debug, PartialEq)]
/// Outcome of a move
pub enum MoveOutcome {
/// Outcome when a move resulted in a general being captured. The player ID is the ID of the
/// defeated player.
GeneralCaptured(PlayerId),
/// Outcome when a move resulted in an open tile or a ci... | Right,
Left, | random_line_split |
common.rs | use std::collections::HashSet;
pub type PlayerId = usize;
/// Represent a player during a game.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Player {
/// An integer that uniquely identifies each player during a game
pub id: PlayerId,
/// Number of tiles the player currently owns
#[serde(s... |
InvalidMove::SourceTileNotOwned => {
"the source tile does not belong to the player making the move"
}
}
}
fn cause(&self) -> Option<&Error> {
None
}
}
impl fmt::Display for InvalidMove {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
... | {
"the source tile is either a mountain or not on the map"
} | conditional_block |
common.rs | use std::collections::HashSet;
pub type PlayerId = usize;
/// Represent a player during a game.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Player {
/// An integer that uniquely identifies each player during a game
pub id: PlayerId,
/// Number of tiles the player currently owns
#[serde(s... | (&mut self, player: PlayerId) {
let was_visible = self.visible_by.remove(&player);
if was_visible {
self.dirty_for.insert(player);
}
}
/// Mark the tile as visible for the given player, updating the source and destination tiles
/// state if necessary (number of units, ow... | hide_from | identifier_name |
common.rs | use std::collections::HashSet;
pub type PlayerId = usize;
/// Represent a player during a game.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Player {
/// An integer that uniquely identifies each player during a game
pub id: PlayerId,
/// Number of tiles the player currently owns
#[serde(s... |
/// Return the owner of the tile, if any
pub fn owner(&self) -> Option<PlayerId> {
self.owner
}
/// Return the number of units occupying the tile
pub fn units(&self) -> u16 {
self.units
}
/// Return whether the tile is open. A tile is open if it's not a city, a general or... | {
if self.is_mountain() {
return Err(InvalidMove::FromInvalidTile);
}
if dst.is_mountain() {
return Err(InvalidMove::ToInvalidTile);
}
if self.units() < 2 {
return Err(InvalidMove::NotEnoughUnits);
}
let attacker = self.owner.ok... | identifier_body |
from_str.rs | use fen4::{Position, PositionParseError};
use std::str::FromStr;
use crate::types::*;
use thiserror::Error;
#[derive(Error, PartialEq, Clone, Debug)]
pub enum MoveError {
#[error("Basic move is malformed.")]
Other,
#[error("A move starts with O-O, but is not a correct type of move.")]
Castle,
#[e... | (string: &str) -> Result<(Turn, &str), IntermediateError> {
use IntermediateError::*;
let trimmed = string.trim_start();
let dot_loc = trimmed.find('.').ok_or(TurnNumber(trimmed.len()))?;
let (number_str, dots) = trimmed.split_at(dot_loc);
let number = if number_str == "" {
0
} else {
... | parse_turn | identifier_name |
from_str.rs | use fen4::{Position, PositionParseError};
use std::str::FromStr;
use crate::types::*;
use thiserror::Error;
#[derive(Error, PartialEq, Clone, Debug)]
pub enum MoveError {
#[error("Basic move is malformed.")]
Other,
#[error("A move starts with O-O, but is not a correct type of move.")]
Castle,
#[e... |
_ => Normal(string.parse::<BasicMove>()?),
})
}
}
struct MovePair {
main: Move,
modifier: Option<Move>,
stalemate: bool,
}
impl FromStr for MovePair {
type Err = MoveError;
fn from_str(string: &str) -> Result<Self, Self::Err> {
let mut stalemate = false;
le... | {
let mateless = s.trim_end_matches('#');
let mates = s.len() - mateless.len();
match mateless {
"O-O-O" => QueenCastle(mates),
"O-O" => KingCastle(mates),
_ => return Err(MoveError::Castle),
}
... | conditional_block |
from_str.rs | use fen4::{Position, PositionParseError};
use std::str::FromStr;
use crate::types::*;
use thiserror::Error;
#[derive(Error, PartialEq, Clone, Debug)]
pub enum MoveError {
#[error("Basic move is malformed.")]
Other,
#[error("A move starts with O-O, but is not a correct type of move.")]
Castle,
#[e... | },
rest,
))
}
fn parse_turn(string: &str) -> Result<(Turn, &str), IntermediateError> {
use IntermediateError::*;
let trimmed = string.trim_start();
let dot_loc = trimmed.find('.').ok_or(TurnNumber(trimmed.len()))?;
let (number_str, dots) = trimmed.split_at(dot_loc);
let number =... | alternatives, | random_line_split |
base.rs | use std::borrow::Cow;
use std::fmt;
use std::iter::FromIterator;
use std::ops::{Bound, Deref, RangeBounds};
use std::str::FromStr;
use symbolic_common::{clean_path, join_path, Arch, CodeId, DebugId, Name};
use crate::sourcebundle::SourceFileDescriptor;
pub(crate) trait Parse<'data>: Sized {
type Error;
fn p... |
}
/// A dynamically dispatched iterator over items with the given lifetime.
pub type DynIterator<'a, T> = Box<dyn Iterator<Item = T> + 'a>;
/// A stateful session for interfacing with debug information.
///
/// Debug sessions can be obtained via [`ObjectLike::debug_session`]. Since computing a session may
/// be a c... | {
f.debug_struct("Function")
.field("address", &format_args!("{:#x}", self.address))
.field("size", &format_args!("{:#x}", self.size))
.field("name", &self.name)
.field(
"compilation_dir",
&String::from_utf8_lossy(self.compilation_d... | identifier_body |
base.rs | use std::borrow::Cow;
use std::fmt;
use std::iter::FromIterator;
use std::ops::{Bound, Deref, RangeBounds};
use std::str::FromStr;
use symbolic_common::{clean_path, join_path, Arch, CodeId, DebugId, Name};
use crate::sourcebundle::SourceFileDescriptor;
pub(crate) trait Parse<'data>: Sized {
type Error;
fn p... | impl<'data> FileInfo<'data> {
/// Creates a `FileInfo` with a given directory and the file name.
#[cfg(feature = "dwarf")]
pub fn new(dir: Cow<'data, [u8]>, name: Cow<'data, [u8]>) -> Self {
FileInfo { name, dir }
}
/// Creates a `FileInfo` from a joined path by trying to split it.
#[cf... | /// Path to the file.
dir: Cow<'data, [u8]>,
}
| random_line_split |
base.rs | use std::borrow::Cow;
use std::fmt;
use std::iter::FromIterator;
use std::ops::{Bound, Deref, RangeBounds};
use std::str::FromStr;
use symbolic_common::{clean_path, join_path, Arch, CodeId, DebugId, Name};
use crate::sourcebundle::SourceFileDescriptor;
pub(crate) trait Parse<'data>: Sized {
type Error;
fn p... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FileInfo")
.field("compilation_dir", &self.compilation_dir_str())
.field("name", &self.name_str())
.field("dir", &self.dir_str())
.finish()
}
}
impl<'data> Deref for FileEntry<'data> {
t... | fmt | identifier_name |
mediaScan.go | package fs
import (
"database/sql"
"errors"
"fmt"
"os"
"path"
"strconv"
"sync"
"time"
"github.com/eHoward1996/aiomst/db"
"github.com/eHoward1996/aiomst/util"
"github.com/karrick/godirwalk"
)
// MediaScan is a filesystem task that scans the given path for new media
type MediaScan struct {
baseFolder str... |
return nil, err
}
func handleAudio(cPath string, info os.FileMode, folder *db.Folder) error {
song, err := db.SongFromFile(cPath)
if err != nil {
return err
}
data, err := os.Stat(cPath)
if err != nil {
return err
}
if data.Size() == 0 {
return errors.New("Audio File Size is 0")
}
song.Path = cPath
... | {
data, err := os.Stat(cPath)
if err != nil {
return nil, err
}
md.FolderID = folder.ID
md.FileSize = data.Size()
md.LastModified = data.ModTime().Unix()
if err := md.Save(); err != nil {
return nil, err
}
metadataCount++
return md, nil
} | conditional_block |
mediaScan.go | package fs
import (
"database/sql"
"errors"
"fmt"
"os"
"path"
"strconv"
"sync"
"time"
"github.com/eHoward1996/aiomst/db"
"github.com/eHoward1996/aiomst/util"
"github.com/karrick/godirwalk"
)
// MediaScan is a filesystem task that scans the given path for new media
type MediaScan struct {
baseFolder str... |
// SetFolders sets the base and sub folders for scanning
func (fs *MediaScan) SetFolders(baseFolder, subFolder string) {
fs.baseFolder = baseFolder
fs.subFolder = subFolder
}
// Verbose is whether scanning has verbose output or not
func (fs *MediaScan) Verbose(v bool) {
fs.verbose = v
}
// WhoAmI returns Media ... | {
return fs.baseFolder, fs.subFolder
} | identifier_body |
mediaScan.go | package fs
import (
"database/sql"
"errors"
"fmt"
"os"
"path"
"strconv"
"sync"
"time"
"github.com/eHoward1996/aiomst/db"
"github.com/eHoward1996/aiomst/util"
"github.com/karrick/godirwalk"
)
// MediaScan is a filesystem task that scans the given path for new media
type MediaScan struct {
baseFolder str... | (cPath string, info os.FileMode, folder *db.Folder) error {
song, err := db.SongFromFile(cPath)
if err != nil {
return err
}
data, err := os.Stat(cPath)
if err != nil {
return err
}
if data.Size() == 0 {
return errors.New("Audio File Size is 0")
}
song.Path = cPath
song.FileSize = data.Size()
song.La... | handleAudio | identifier_name |
mediaScan.go | package fs
import (
"database/sql"
"errors"
"fmt"
"os"
"path"
"strconv"
"sync"
"time"
"github.com/eHoward1996/aiomst/db"
"github.com/eHoward1996/aiomst/util"
"github.com/karrick/godirwalk"
)
// MediaScan is a filesystem task that scans the given path for new media
type MediaScan struct {
baseFolder str... | if isMetadata {
md, err := handleMetadata(osPathname, folder)
if err != nil {
return fmt.Errorf(
"FS: Media Scan: Error handling Metadata: %s", err)
}
currentVal := folderAttachables[folder.ID]
currentVal.md = md
folderAttachables[folder.ID] = currentVal
return nil
... | folderAttachables[folder.ID] = currentVal
return nil
}
| random_line_split |
widgets.js | // Template.widgetsDemo
// This template is for internal documentation only.
Template.widgetsDemo.onCreated(function () {
let instance = this;
instance.error = new ReactiveVar({
header: "I am a header",
message: "You did something very wrong.",
});
});
Template.widgetsDemo.helpers({
fakeObject() {
... |
},
});
// Template.jobWrapper
Template.jobWrapper.onCreated(function () {
let instance = this;
// subscribe and keep up to date
instance.autorun(function () {
instance.subscribe("specificJob", Template.currentData().job_id);
});
});
Template.jobWrapper.helpers({
getJob() {
return Jobs.findOne(t... | {
deleteClicked.set(true);
// if they click elsewhere, cancel remove
// wait until propogation finishes before registering event handler
Meteor.defer(() => {
$("html").one("click", () => {
deleteClicked.set(false);
});
});
} | conditional_block |
widgets.js | // Template.widgetsDemo
// This template is for internal documentation only.
Template.widgetsDemo.onCreated(function () {
let instance = this;
instance.error = new ReactiveVar({
header: "I am a header",
message: "You did something very wrong.",
});
});
Template.widgetsDemo.helpers({
fakeObject() {
... | capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
},
buttonClass() {
if (this.job.status === "done") { return "primary"; }
else if (this.job.status === "error") { return "negative"; }
else if (this.job.status === "running") { return "secondary"; }
// else { return "" }
},
... |
Template.viewJobButton.helpers({ | random_line_split |
widgets.js | // Template.widgetsDemo
// This template is for internal documentation only.
Template.widgetsDemo.onCreated(function () {
let instance = this;
instance.error = new ReactiveVar({
header: "I am a header",
message: "You did something very wrong.",
});
});
Template.widgetsDemo.helpers({
fakeObject() {
... | () {
return [ "args.gene_set_id" ];
},
permissionLikelyDenied() {
return Template.instance().permissionLikelyDenied.get();
},
});
// Template.recordsDownloadButton
Template.recordsDownloadButton.events({
"click .download-hot-data"(event, instance) {
let { hotPassback, filename } = instance.data;
... | extraFields | identifier_name |
widgets.js | // Template.widgetsDemo
// This template is for internal documentation only.
Template.widgetsDemo.onCreated(function () {
let instance = this;
instance.error = new ReactiveVar({
header: "I am a header",
message: "You did something very wrong.",
});
});
Template.widgetsDemo.helpers({
fakeObject() {
... | ,
});
// Template.showErrorMessage
Template.showErrorMessage.helpers({
getError: function () {
return Template.instance().data.get();
},
});
Template.showErrorMessage.events({
"click .close-error-message": function (event, instance) {
instance.data.set(null);
},
});
// Template.contactUsButton
Temp... | {
return Template.instance().randomId;
} | identifier_body |
binder.go | package config
import (
"errors"
"fmt"
"go/token"
"go/types"
"strings"
"golang.org/x/tools/go/packages"
"github.com/99designs/gqlgen/internal/code"
"github.com/vektah/gqlparser/v2/ast"
)
var ErrTypeNotFound = errors.New("unable to find type")
// Binder connects graphql types to golang types using static an... | func (ref *TypeReference) UnmarshalFunc() string {
if ref.Definition == nil {
panic(errors.New("Definition missing for " + ref.GQL.Name()))
}
if !ref.Definition.IsInputType() {
return ""
}
return "unmarshal" + ref.UniquenessKey()
}
func (ref *TypeReference) IsTargetNilable() bool {
return IsNilable(ref.Tar... | if ref.Definition == nil {
panic(errors.New("Definition missing for " + ref.GQL.Name()))
}
if ref.Definition.Kind == ast.InputObject {
return ""
}
return "marshal" + ref.UniquenessKey()
}
| identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.