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
console.js
the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * Aloha Editor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULA...
// 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
Picker, TouchableHighlight, Text } from 'react-native' import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; import MultiSelect from 'react-native-multiple-select'; import categories from '../components/Categories' // CITATION: https://stackoverflow.com/questions/37230555/get-with-query-...
(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
Picker, TouchableHighlight, Text } from 'react-native' import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; import MultiSelect from 'react-native-multiple-select'; import categories from '../components/Categories' // CITATION: https://stackoverflow.com/questions/37230555/get-with-query-...
}} 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
Picker, TouchableHighlight, Text } from 'react-native' import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; import MultiSelect from 'react-native-multiple-select'; import categories from '../components/Categories' // CITATION: https://stackoverflow.com/questions/37230555/get-with-query-...
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
ifcloudClients.Computing.DescribeInstances(context.TODO(), input) switch { case nferrors.IsNotFound(err): return nil, nil case err != nil: return nil, fmt.Errorf("failed to describe instance[%q]: %w", *id, err) } for _, rs := range out.ReservationSet { if len(rs.InstancesSet) == 0 { break } instance ...
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
if len(rs.InstancesSet) == 0 { break } instance := rs.InstancesSet[0] if nifcloud.StringValue(id) != nifcloud.StringValue(instance.InstanceId) { continue } return s.SDKToInstance(out.ReservationSet[0].InstancesSet[0]) } return nil, nil } func (s *Service) GetRunningInstanceByTag(scope *scope.Machi...
{ 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
cloudClients.Computing.DescribeInstances(context.TODO(), input) switch { case nferrors.IsNotFound(err): return nil, nil case err != nil: return nil, fmt.Errorf("failed to describe instance[%q]: %w", *id, err) } for _, rs := range out.ReservationSet { if len(rs.InstancesSet) == 0 { break } instance :=...
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
ok { filtered = append(filtered, v) } } return filtered } func (s *Service) CreateInstance(scope *scope.MachineScope) (*infrav1alpha2.Instance, error) { s.scope.V(2).Info("Creating an instance for a machine") instanceID := scope.GetInstanceIDConved() input := &infrav1alpha2.Instance{ ID: i...
getInstanceAddresses
identifier_name
king.py
S {self.planting_cost} RALLODS " "PER SQUARE MILE TO PLANT.\n" ) 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 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
IMPEACHED AND THROWN OUT OF OFFICE, BUT YOU") message = randint(0, 10) if message <= 3: print("ALSO HAD YOUR LEFT EYE GOUGED OUT!") if message <= 6: print("HAVE ALSO GAINED A VERY BAD REPUTATION.") if message <= 10: print("HAVE ALSO BEEN DECLARED NATI...
sm_sell_to_industry, distributed_rallods, polltion_control_spendings )
random_line_split
king.py
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
S {self.planting_cost} RALLODS " "PER SQUARE MILE TO PLANT.\n" ) def handle_deaths( self, distributed_rallods: int, pollution_control_spendings: int ) -> None: starved_countrymen = max( 0, int(self.countrymen - distributed_rallods / COST_OF_LIVING) ) ...
(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
32, f32))>, pub statusbar: Statusbar, pub custom_menu_height: f32, /// Backend that is currently being configured. pub config_backend: Option<BackendHandle>, /// View currently being renamed view_rename_state: ViewRenameState, } impl Window { pub fn new(width: usize, height: usize) -> m...
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
32, f32))>, pub statusbar: Statusbar, pub custom_menu_height: f32, /// Backend that is currently being configured. pub config_backend: Option<BackendHandle>, /// View currently being renamed view_rename_state: ViewRenameState, } impl Window { pub fn new(width: usize, height: usize) -> m...
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
self, sessions: &mut Sessions, view_plugins: &mut ViewPlugins, backend_plugins: &mut BackendPlugins) { // Update minifb window to get current window size self.win.update(); // Update menus first to find out size of self-drawn menus (if any...
has_source_code_view
identifier_name
mod.rs
32, f32))>, pub statusbar: Statusbar, pub custom_menu_height: f32, /// Backend that is currently being configured. pub config_backend: Option<BackendHandle>, /// View currently being renamed view_rename_state: ViewRenameState, } impl Window { pub fn new(width: usize, height: usize) -> m...
context_menu_data: None, statusbar: Statusbar::new(), custom_menu_height: 0.0, config_backend: None, view_rename_state: ViewRenameState::None, }; res.initialize_workspace_state(); Ok(res) } pub fn pre_update(&mut self) { ...
{ 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
list constructed from headers on each object instead of a stack of pointers. //! //! This implementation is generic in that it does not prescribe a method for mapping objects to //! their containing slabs, but instead requires that an implementation of this functionality be //! provided (see the `ConfigData` trait). T...
(&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
list constructed from headers on each object instead of a stack of pointers. //! //! This implementation is generic in that it does not prescribe a method for mapping objects to //! their containing slabs, but instead requires that an implementation of this functionality be //! provided (see the `ConfigData` trait). T...
loop { let candidate = num_obj + 1; // total_hdr_size = size
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
//! This is due largely to the fact that slab size cannot be known at compile time, and must //! instead be computed at runtime. Why this is a problem will become apparent shortly. //! //! The layout in memory of stack-based slabs is as follows: //! //! ```text //! <header> <pre-stack padding> <stack> <post-stack paddi...
{ num_obj = candidate; array_begin_offset = total_hdr_size + post_stack_padding; }
conditional_block
stack.rs
constructed from headers on each object instead of a stack of pointers. //! //! This implementation is generic in that it does not prescribe a method for mapping objects to //! their containing slabs, but instead requires that an implementation of this functionality be //! provided (see the `ConfigData` trait). The `a...
} 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
""" Write boundary conditions, equations and create the files for solution. """ self.mesh = mesh self.dt = Constant(dt) self.theta = theta self.t = 0.0 self.v_max = v_max self.mu_f = mu_f self.rho_f = rho_f self.lam...
# 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
\ + alpha*inner(du - (self.theta*self.v + (1.0 - self.theta)*self.v0), u_)*dx(1) dF_solid = derivative(self.F_solid, self.w) dF_fluid = derivative(self.F_fluid, self.w) self.problem = Problem(self.F_fluid, self.F_solid, dF_fluid, dF_solid, self.bcs_mesh, self.bcs) ...
# name of benchmark benchmark = options.benchmark
random_line_split
Total_ALE.py
2, p) = self.w.split() v.rename("v", "velocity") u.rename("u", "displacement") p.rename("p", "pressure") self.vfile.write(v, t) self.ufile.write(u, t) self.pfile.write(p, t) P = assemble(self.p*ds(_OUTFLOW))/gW PI = assemble(abs(jump(self.p))*dS(_FSI)) ...
t = %.4f, t_end = %.1f" % (t, t_end)) f
conditional_block
Total_ALE.py
""" Write boundary conditions, equations and create the files for solution. """ self.mesh = mesh self.dt = Constant(dt) self.theta = theta self.t = 0.0 self.v_max = v_max self.mu_f = mu_f self.rho_f = rho_f self.lam...
: 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
); err != nil { return errors.Wrapf(err, "failed to umount %s", mountPoint) } // logout portal targetIqn := o.tgtTargetIqn(snID, snKey) out, err := exec.CommandContext(ctx, "iscsiadm", "-m", "node", "-p", defaultPortal, "-T", targetIqn, "--logout").CombinedOutput() if err != nil { exiterr, ok := err.(*exec.Ex...
return err } configJSON.Lowers = parentConfJSON.Lowers } switch stype { case storageTypeRemoteBlock: if writable { return errors.Errorf("remote block device is readonly, not support writable") } blobSize, err := strconv.Atoi(info.Labels[labelKeyOverlayBDBlobSize]) if err != nil { return errors...
{ 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
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
); err != nil { return errors.Wrapf(err, "failed to umount %s", mountPoint) } // logout portal targetIqn := o.tgtTargetIqn(snID, snKey) out, err := exec.CommandContext(ctx, "iscsiadm", "-m", "node", "-p", defaultPortal, "-T", targetIqn, "--logout").CombinedOutput() if err != nil { exiterr, ok := err.(*exec.Ex...
} 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
s", targetIqn) } if len(hostToSessionID) != 1 { return errors.Errorf("unexpected hostNumber->SessionID mapping result %v for %s", hostToSessionID, targetIqn) } // The device doesn't show up instantly. Need retry here. var lastErr error = nil var mountPoint = o.tgtTargetMountpoint(snID) for i := 1; i <= maxAt...
lookup
identifier_name
cdk.py
apiGatewayResource = apiGateway.root.add_resource('vaquita') apiGatewayLandingPageResource = apiGatewayResource.add_resource('web') apiGatewayGetSignedUrlResource = apiGatewayResource.add_resource('signedUrl') apiGatewayImageSearchResource = apiGatewayResource.add_resource('search') ...
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
Integration = _apigw.LambdaIntegration( getSignedUrlFunction, proxy=True, integration_responses=[{ 'statusCode': '200', 'responseParameters': { 'method.response.header.Access-Control-Allow-Origin': "'*'", } ...
add_cors_options
identifier_name
cdk.py
3, "queue": imageDeadletterQueue }) ### api gateway core apiGateway = _apigw.RestApi(self, 'VAQUITA_API_GATEWAY', rest_api_name='VaquitaApiGateway') apiGatewayResource = apiGateway.root.add_resource('vaquita') apiGatewayLandingPageResource = apiGatewayResourc...
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
.database = db self.connect = connection self.cursor = cursor self.valueDic = {} self.rows = [] self.fields = [] self.fieldTypeDic = {} self.fieldTypes = {'DOUBLE': 'D', 'FLOAT':'F', 'INTEGER':...
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
dictionary' fields = self.sqlFieldInfo, self.name self.curX(fields) retFields = self.curAll() for field in retFields: fieldval = field[1] typeval = field[2] self.fieldTypeDic[fieldval] = typeval self.fields.append(fieldval) ...
WKT += str(coords[0]) + ' '+ str(coords[1])+ ')'
random_line_split
Tablemodels.py
.database = db self.connect = connection self.cursor = cursor self.valueDic = {} self.rows = [] self.fields = [] self.fieldTypeDic = {} self.fieldTypes = {'DOUBLE': 'D', 'FLOAT':'F', 'INTEGER':...
(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
.database = db self.connect = connection self.cursor = cursor self.valueDic = {} self.rows = [] self.fields = [] self.fieldTypeDic = {} self.fieldTypes = {'DOUBLE': 'D', 'FLOAT':'F', 'INTEGER':...
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
.220, 6.000, 6.840, 7.740, 8.690, 9.690, 10.720, 11.830, 0.000, 0.020, 0.011, 0.011, 0.089, 0.079, 0.079 ] a3 = [ 8.40E-3, 8.50E-3, 8.60E-3, 8.70E-3, 8.90E-3, 9.20E-3, 9.40E-3, 9.70E-3, 10.00E-3, 10.20E-3, 10.50E-3, 10.79E-3, 11.10E-3, 16.46E-3, 11...
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
504.482692, 556.936002, 620.700807, 658.006500, 752.033227, 841.073593, 859.865000, 899.407000, 902.555000, 906.205524, 916.171582, 970.315022, 987.926764 ] b1 = [ 0.1090, 0.0011, 0.0007, 2.3000, 0.0464, 1.5400, 0.0010, 11.9000, 0.0044, 0.0637, 0.9210, 0.1940, ...
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
f / gamma0) ** 2) - 1.0) * p * theta * theta ni = (2.0 * 3.07e-4 / (gamma0 * (1.0 + (f / gamma0) ** 2) * (1.0 + (f / 60.0) ** 2)) + ap * p * theta ** 2.5) * f * p * theta * theta # Sum the contributions of the lines. for i in xrange(0, len(nu0)): S = a1[i] * p * theta ** 3 * math.exp(a2[i...
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
] * (1.0 - theta)) gamma = a3[i] * (p * theta ** (0.8 - a4[i])) + 1.1 * e * theta delta = a5[i] * p * theta ** a6[i] x = (nu0[i] - f) * (nu0[i] - f) + gamma * gamma y = (nu0[i] + f) * (nu0[i] + f) + gamma * gamma z = (nu0[i] + gamma * gamma / nu0[i]) nr = nr + S * ((z - f...
refract
identifier_name
admin.js
; } } }, playerUpdate: function(user, x){ if (Meteor.isServer){ var result = Meteor.users.update({username: user}, {$set: {profile: x}}); return result; } }, grabRecord: function(user){ if (Meteor.isServer){ var result = Meteor.users.find({username: user}).fetch()[0].profile; console.log("se...
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
; } } }, playerUpdate: function(user, x){ if (Meteor.isServer){ var result = Meteor.users.update({username: user}, {$set: {profile: x}}); return result; } }, grabRecord: function(user){ if (Meteor.isServer){ var result = Meteor.users.find({username: user}).fetch()[0].profile; console.log("se...
(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
}, 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
} } }, playerUpdate: function(user, x){ if (Meteor.isServer){ var result = Meteor.users.update({username: user}, {$set: {profile: x}}); return result; } }, grabRecord: function(user){ if (Meteor.isServer){ var result = Meteor.users.find({username: user}).fetch()[0].profile; console.log("serv...
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
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
_ZONE_GLOBAL_ADDRESS"] = c.opts.globalAddress } if c.opts.hdsDisabled { env["KUMA_DP_SERVER_HDS_ENABLED"] = "false" } if Config.XDSApiVersion != "" { env["KUMA_BOOTSTRAP_SERVER_API_VERSION"] = Config.XDSApiVersion } if Config.CIDR != "" { env["KUMA_DNS_SERVER_CIDR"] = Config.CIDR } var dockerVolumes []...
{ return c.apps[appName] }
identifier_body
universal_cluster.go
.opts.apiHeaders, c.opts.setupKumactl) if err != nil { return err } for name, updateFuncs := range c.opts.meshUpdateFuncs { for _, f := range updateFuncs { Logf("applying update function to mesh %q", name) err := c.controlplane.kumactl.KumactlUpdateObject("mesh", name, func(resource core_model.Resourc...
GetZoneIngressNetworking
identifier_name
universal_cluster.go
!= nil { errs = multierr.Append(errs, err) } } for name, deployment := range c.deployments { if err := deployment.Delete(c); err != nil { errs = multierr.Append(errs, err) } delete(c.deployments, name) } return errs } func (c *UniversalCluster) Verbose() bool { return c.verbose } func (c *Universa...
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
Kind string `json:"kind"` APIVersion string `json:"apiVersion"` Status string `json:"status"` Message string `json:"message"` Reason string `json:"reason"` Code int `json:"code"` } // Do runs the given HTTP request. func Do(method, url, body, certificateAuthorityData, clientCertificateD...
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
{ Kind string `json:"kind"` APIVersion string `json:"apiVersion"` Status string `json:"status"` Message string `json:"message"` Reason string `json:"reason"` Code int `json:"code"` } // Do runs the given HTTP request. func Do(method, url, body, certificateAuthorityData, clientCertifica...
(discoveryURL
OIDCGetRefreshToken
identifier_name
request.go
Kind string `json:"kind"` APIVersion string `json:"apiVersion"` Status string `json:"status"` Message string `json:"message"` Reason string `json:"reason"` Code int `json:"code"` } // Do runs the given HTTP request. func Do(method, url, body, certificateAuthorityData, clientCertificateD...
// 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
{ Kind string `json:"kind"` APIVersion string `json:"apiVersion"` Status string `json:"status"` Message string `json:"message"` Reason string `json:"reason"` Code int `json:"code"` } // Do runs the given HTTP request. func Do(method, url, body, certificateAuthorityData, clientCertifica...
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
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 the License for the specific language governing permissions and # limitations under the License. from copy import deepcopy from typing import Any...
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
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 the License for the specific language governing permissions and # limitations under the License. from copy import deepcopy from typing ...
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
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 the License for the specific language governing permissions and # limitations under the License. from copy import deepcopy from typing imp...
(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
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 the License for the specific language governing permissions and # limitations under the License. from copy import deepcopy from typing import Any...
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
GM": {message: "Гамбија"}, "LV": {message: "Летонија"}, "RU": {message: "Русија"}, "FI": {message: "Финска"}, "Get Hola Plus for un-interrupted, ad-free service.": {message: "Набавите Хола плус за УН-прекида, без реклама сервиса."}, "LU": {message: "Луксембург"}, "VE": {message: "Венецуела"}, ...
"PT": {message: "Португал"},
random_line_split
api_op_GetCredentials.go
" ) // 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 A...
(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
" ) // 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 A...
} if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { return err } if err = addRetryMiddlewares(stack, options); err != nil { return err } if err = addHTTPSignerV4Middleware(stack, options); err != nil { retu...
{ 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
" ) // 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 A...
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
// 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
return request({ url: path + 'tjapi/user/publicAccountCodeLogin', data: {channel, subChannel, identity, ...param}, method: 'POST' }) } /*** 退出 */ export const doLoginOut = function(param) { return request({ url: path + 'tjapi/user/logout', data: param, method: 'POST' }) } /*** 账户 */ export const mine = function(para...
identifier_name
api.ts
} export const appLaunchQueue = launchQueue() // 获取用户类型 export interface UserInfo Interface { openid: string, avatarUrl: string, city: string, country: string, gender: number, language: string, nickName: string, province: string } export const useropenid = () => { } export const weixinSign = function...
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
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: 'POST' }) } export const getUserInfo: (payload: obje...
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
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
import DataLoader import torchvision.transforms as T from torch.utils.data import random_split import torch.utils.data as data from torchvision.utils import make_grid import torch.optim as optim import matplotlib import matplotlib.pyplot as plt # %matplotlib inline matplotlib.rcParams['figure.facecolor'] = '#ffffff'...
self.classifier = nn.Sequential( nn.Linear(128*8*8, 512), nn.ReLU(inplace=True), nn.Dropout(0.5), nn.Linear(in_features=512, out_features=output_dim) ) def forward(self, x): x = self.features(x) x = x.view(x.sh...
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
import DataLoader import torchvision.transforms as T from torch.utils.data import random_split import torch.utils.data as data from torchvision.utils import make_grid import torch.optim as optim import matplotlib import matplotlib.pyplot as plt # %matplotlib inline matplotlib.rcParams['figure.facecolor'] = '#ffffff'...
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
import DataLoader import torchvision.transforms as T from torch.utils.data import random_split import torch.utils.data as data from torchvision.utils import make_grid import torch.optim as optim import matplotlib import matplotlib.pyplot as plt # %matplotlib inline matplotlib.rcParams['figure.facecolor'] = '#ffffff'...
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
import DataLoader import torchvision.transforms as T from torch.utils.data import random_split import torch.utils.data as data from torchvision.utils import make_grid import torch.optim as optim import matplotlib import matplotlib.pyplot as plt # %matplotlib inline matplotlib.rcParams['figure.facecolor'] = '#ffffff'...
(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
} 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
Entry, h.Len()) h.EachWithIndex(func(elem eval.Value, idx int) { entry := elem.(*HashEntry) pt := entry.Key().(eval.Type) v := entry.Value() if s, ok := v.(stringValue); ok { result[idx] = WrapHashEntry(pt, newFormat(s.String())) } else { result[idx] = WrapHashEntry(pt, FormatFromHash(v.(*HashValue))) ...
{ fmt.Fprintf(bld, `%d`, f.Width()) }
conditional_block
format.go
return 12 case *EnumType: return 11 case *PatternType: return 10 case *ArrayType: return 4 case *TupleType: return 3 case *HashType: return 2 case *StructType: return 1 } return 0 } var TYPE_STRING_FORMAT_TYPE_HASH = NewHashType(DefaultTypeType(), NewVariantType(DefaultStringType(), DefaultHashTy...
HasStringFlags
identifier_name
format.go
(c *formatContext) Property(key string) (string, bool) { if c.properties != nil { pv, ok := c.properties[key] return pv, ok } return ``, false } func (c *formatContext) Properties() map[string]string { return c.properties } func (c *formatContext) SetProperty(key, value string) { if c.properties == nil { ...
{ 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
font: Sdl2Font, ) -> Result<Self, String>
total_width += w; total_height = h; } else { return Err(format!("Unsupported character: {}", c)); } } let mut font_canvas = Surface::new( total_width, total_height, texture_creator.default_pixel...
{ 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
font: Sdl2Font, ) -> Result<Self, String> { 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) { ...
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
, h)) = self.cached_texts.get_mut(&cache_key) { let (tw, th) = scale_dim(screen_txt.scale, *w, *h); let ScreenPos(x, y) = screen_txt.pos.align(screen_txt.align, tw, th); tex.set_alpha_mod(screen_txt.alpha); cvs.copy(tex, Rect::new(0, 0, *w, *h), Rect::new(x, y, tw, th))?...
scale_dim
identifier_name
text.rs
font: Sdl2Font, ) -> Result<Self, String> { 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)
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
{} //should help with the concurrent map writes issue var wg sync.WaitGroup //multi threading the GET details request wg.Add(len(filesList.Children)) for i := 0; i < len(filesList.Children); i++ { go func(i int) { defer wg.Done() var fileDetail helpers.FileStorageJSON var data2, _ = auth.GetRestAPI(ur...
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
{} //should help with the concurrent map writes issue var wg sync.WaitGroup //multi threading the GET details request wg.Add(len(filesList.Children)) for i := 0; i < len(filesList.Children); i++ { go func(i int) { defer wg.Done() var fileDetail helpers.FileStorageJSON var data2, _ = auth.GetRestAPI(ur...
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
{} //should help with the concurrent map writes issue var wg sync.WaitGroup //multi threading the GET details request wg.Add(len(filesList.Children)) for i := 0; i < len(filesList.Children); i++ { go func(i int) { defer wg.Done() var fileDetail helpers.FileStorageJSON var data2, _ = auth.GetRestAPI(ur...
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 := strconv.Atoi(splitNumbers[0]) helpers.Check(err, true, "floor check", helpers.Trace()) second, err := strconv.A...
{ 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
(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
-> bool { !self.defeated() && self.owned_tiles > 0 } } /// Represent an action a player can perform. #[derive(Copy, Clone, Debug, Deserialize, Serialize)] #[serde(tag = "type")] #[serde(rename_all = "lowercase")] pub enum Action { /// Resign Resign, /// Cancel all the moves already queued for ...
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
kind: TileKind, /// List of players that can see the tile. To be able to see an open tile, a player must own a /// tile that touches it. #[serde(skip)] visible_by: HashSet<PlayerId>, /// Players that had visibility on this tile when it changed. #[serde(skip)] dirty_for: HashSet<PlayerI...
{ "the source tile is either a mountain or not on the map" }
conditional_block
common.rs
-> bool { !self.defeated() && self.owned_tiles > 0 } } /// Represent an action a player can perform. #[derive(Copy, Clone, Debug, Deserialize, Serialize)] #[serde(tag = "type")] #[serde(rename_all = "lowercase")] pub enum Action { /// Resign Resign, /// Cancel all the moves already queued for ...
(&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
-> bool { !self.defeated() && self.owned_tiles > 0 } } /// Represent an action a player can perform. #[derive(Copy, Clone, Debug, Deserialize, Serialize)] #[serde(tag = "type")] #[serde(rename_all = "lowercase")] pub enum Action { /// Resign Resign, /// Cancel all the moves already queued for ...
// The attacker has more units. Capture the tile. else { dst.units = self.units - 1 - dst.units; dst.owner = self.owner; // We're capturing a general if dst.kind == TileKind::General { ...
{ 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
checkless.len(); let (two_pos, promotion) = if let Some(equals) = checkless.find('=') { let (left_over, promote) = checkless.split_at(equals); let mut iter = promote.chars(); if iter.next() != Some('=') { return Err(MoveError::Other); } ...
(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
checkless.len(); let (two_pos, promotion) = if let Some(equals) = checkless.find('=') { let (left_over, promote) = checkless.split_at(equals); let mut iter = promote.chars(); if iter.next() != Some('=') { return Err(MoveError::Other); } ...
_ => 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
- checkless.len(); let (two_pos, promotion) = if let Some(equals) = checkless.find('=') { let (left_over, promote) = checkless.split_at(equals); let mut iter = promote.chars(); if iter.next() != Some('=') { return Err(MoveError::Other); } ...
}, 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
key); // Compute sizes of consecutive symbols if the size has not been provided by the symbol // iterator. In the same go, drop all but the first symbols at any given address. We do // not rely on the size of symbols in this case, since the ranges might still be // overl...
{ 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
FileFormat::Pdb, "pe" => FileFormat::Pe, "sourcebundle" => FileFormat::SourceBundle, "wasm" => FileFormat::Wasm, "portablepdb" => FileFormat::PortablePdb, _ => return Err(UnknownFileFormatError), }) } } /// A symbol from a symbol table. #[derive(...
/// Path to the file. dir: Cow<'data, [u8]>, }
random_line_split
base.rs
0) => None, Err(next_index) => { let symbol = &self.symbols[next_index - 1]; if symbol.contains(address) { Some(symbol) } else { None } } } } /// Looks up a symbol by its star...
fmt
identifier_name
mediaScan.go
go func(haltWalk bool) { // Wait until signal recieved <- walkCancelChan // Halt fs walk mutex.Lock() haltWalk = true mutex.Unlock() }(haltWalk) // Track metrics artCount = 0 artistCount = 0 albumCount = 0 songCount = 0 songUpdate = 0 folderCount = 0 metadataC...
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
// 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
false go func(haltWalk bool) { // Wait until signal recieved <- walkCancelChan // Halt fs walk mutex.Lock() haltWalk = true mutex.Unlock() }(haltWalk) // Track metrics artCount = 0 artistCount = 0 albumCount = 0 songCount = 0 songUpdate = 0 folderCount = 0 met...
(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
false go func(haltWalk bool) { // Wait until signal recieved <- walkCancelChan // Halt fs walk mutex.Lock() haltWalk = true mutex.Unlock() }(haltWalk) // Track metrics artCount = 0 artistCount = 0 albumCount = 0 songCount = 0 songUpdate = 0 folderCount = 0 met...
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
{ type }), "id"); // we're rarely going to have more than 2 // collaborators, so indexOf is fine resultsParent.results = _.filter(results, (result) => { return existingIdsOfType.indexOf(result.id) === -1; }); ...
{ 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
one has a random id assigned so the jquery doesn't interfere instance.randomId = Random.id(); }); Template.addCollaboratorSearch.onRendered(function () { let instance = this; const searchJquery = `.${instance.randomId}.collaboration-search`; // only initialize the collaboration search when the user is logge...
Template.viewJobButton.helpers({
random_line_split
widgets.js
} more features`]); } } }, tooManyToShowAll() { return this.featureLabels.length > 1000; }, }); Template.listFeaturesButton.events({ "click .toggle-list"(event, instance) { instance.showMore.set(!instance.showMore.get()); }, "click .download-list"(event, instance) { let text = instanc...
extraFields
identifier_name
widgets.js
.instance().waitingForServer.get(); }, collabsList() { return Template.instance().collabsList; }, collectionName() { return Session.get("editCollaborationsCollection"); }, mongoIds() { return Session.get("editCollaborationsMongoIds"); }, }); // Template.listCollaborators Template.listCollaborators.onCreated(fun...
, }); // 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
) (types.Type, error) { models := b.cfg.Models[name].Model if len(models) == 0 { return nil, fmt.Errorf(name + " not found in typemap") } if models[0] == "map[string]interface{}" { return MapType, nil } if models[0] == "interface{}" { return InterfaceType, nil } pkgName, typeName := code.PkgAndType(mod...
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
binder.go
) (types.Type, error) { models := b.cfg.Models[name].Model if len(models) == 0 { return nil, fmt.Errorf(name + " not found in typemap") } if models[0] == "map[string]interface{}" { return MapType, nil } if models[0] == "interface{}" { return InterfaceType, nil } pkgName, typeName := code.PkgAndType(mod...
types.Type) (types.Type, bool) { if t == nil { return t, false } named, ok := t.(*types.Named) if !ok { return t, false } if named.Origin().String() != "github.com/99designs/gqlgen/graphql.Omittable[T any]" { return t, false } return named.TypeArgs().At(0), true } func (b *Binder) TypeReference(schemaTy...
wrapOmittable(t
identifier_name