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
client_enum_component_type.go
package bungo import ( "errors" "fmt" ) const ( ComponentsNoneKey = 0 ComponentsProfilesKey = 100 ComponentsVendorReceiptsKey = 101 ComponentsProfileInventoriesKey = 102 ComponentsProfileCurrenciesKey = 103 ComponentsProfileProgressionKey = 104 ComponentsPlatfor...
return "Collectibles", description, nil case ComponentsRecordsKey: description := ` Returns summary status information about all "Records" also known in the game as "Triumphs". I know, it's confusing because there's also "Moments of Triumph" that will themselves be represented as "Triumphs." ` return "Records",...
These are records of what items you've discovered while playing Destiny, and some other basic information. For detailed information, you will have to call a separate endpoint devoted to the purpose. `
random_line_split
client_enum_component_type.go
package bungo import ( "errors" "fmt" ) const ( ComponentsNoneKey = 0 ComponentsProfilesKey = 100 ComponentsVendorReceiptsKey = 101 ComponentsProfileInventoriesKey = 102 ComponentsProfileCurrenciesKey = 103 ComponentsProfileProgressionKey = 104 ComponentsPlatfor...
(key int) (ComponentType, string, error) { switch key { case ComponentsNoneKey: return "None", "", nil case ComponentsProfilesKey: description := ` Profiles is the most basic component, only relevant when calling GetProfile. This returns basic information about the profile, which is almost nothing: - a list of c...
ComponentTypesE
identifier_name
client_enum_component_type.go
package bungo import ( "errors" "fmt" ) const ( ComponentsNoneKey = 0 ComponentsProfilesKey = 100 ComponentsVendorReceiptsKey = 101 ComponentsProfileInventoriesKey = 102 ComponentsProfileCurrenciesKey = 103 ComponentsProfileProgressionKey = 104 ComponentsPlatfor...
return out } func ComponentTypes(key int) ComponentType { out, _, _ := ComponentTypesE(key) return out } func ComponentTypesE(key int) (ComponentType, string, error) { switch key { case ComponentsNoneKey: return "None", "", nil case ComponentsProfilesKey: description := ` Profiles is the most basic compone...
{ eout, _, _ := ComponentTypesE(key) out = append(out, eout) }
conditional_block
client_enum_component_type.go
package bungo import ( "errors" "fmt" ) const ( ComponentsNoneKey = 0 ComponentsProfilesKey = 100 ComponentsVendorReceiptsKey = 101 ComponentsProfileInventoriesKey = 102 ComponentsProfileCurrenciesKey = 103 ComponentsProfileProgressionKey = 104 ComponentsPlatfor...
{ switch key { case ComponentsNoneKey: return "None", "", nil case ComponentsProfilesKey: description := ` Profiles is the most basic component, only relevant when calling GetProfile. This returns basic information about the profile, which is almost nothing: - a list of characterIds, - some information about the...
identifier_body
mysql.rs
mod conversion; mod error; use mysql_async::{self as my, prelude::Queryable as _}; use percent_encoding::percent_decode; use std::{borrow::Cow, future::Future, path::Path, time::Duration}; use tokio::time::timeout; use url::Url; use crate::{ ast::{ParameterizedValue, Query}, connector::{metrics, queryable::*,...
} impl TransactionCapable for Mysql {} impl Queryable for Mysql { fn query<'a>(&'a self, q: Query<'a>) -> DBIO<'a, ResultSet> { let (sql, params) = visitor::Mysql::build(q); DBIO::new(async move { self.query_raw(&sql, &params).await }) } fn execute<'a>(&'a self, q: Query<'a>) -> DBIO<'a,...
{ match self.socket_timeout { Some(duration) => match timeout(duration, f).await { Ok(Ok(result)) => Ok(result), Ok(Err(err)) => Err(err.into()), Err(to) => Err(to.into()), }, None => match f.await { Ok(result) =...
identifier_body
mysql.rs
mod conversion; mod error; use mysql_async::{self as my, prelude::Queryable as _}; use percent_encoding::percent_decode; use std::{borrow::Cow, future::Future, path::Path, time::Duration}; use tokio::time::timeout; use url::Url; use crate::{ ast::{ParameterizedValue, Query}, connector::{metrics, queryable::*,...
() { let conn = Quaint::new(&CONN_STR).await.unwrap(); let _ = conn.raw_cmd("DROP TABLE test_null_constraint_violation").await; conn.raw_cmd("CREATE TABLE test_null_constraint_violation (id1 int not null, id2 int not null)") .await .unwrap(); // Error code 1364...
test_null_constraint_violation
identifier_name
mysql.rs
mod conversion; mod error; use mysql_async::{self as my, prelude::Queryable as _};
use url::Url; use crate::{ ast::{ParameterizedValue, Query}, connector::{metrics, queryable::*, ResultSet, DBIO}, error::{Error, ErrorKind}, visitor::{self, Visitor}, }; /// A connector interface for the MySQL database. #[derive(Debug)] pub struct Mysql { pub(crate) pool: my::Pool, pub(crate) ...
use percent_encoding::percent_decode; use std::{borrow::Cow, future::Future, path::Path, time::Duration}; use tokio::time::timeout;
random_line_split
Bijlage_D.py
# ------------------------------------------- # MODULES # ------------------------------------------- import sys import platform if(platform.system()== "Windows"): dir_sep = "\\" else: dir_sep = "/" import time import os import numpy as np import subprocess import math from mathutils import Vector try: from CifFi...
# Panel to display add-on in Blender environment class Panel(bpy.types.Panel): bl_idname = "CDTB_Panel" bl_label = "CDTB_Panel" bl_space_type = "VIEW_3D" bl_region_type = "TOOLS" bl_context = "objectmode" bl_category = "CDTB" def draw(self,context): scn = context.scene lay...
int("Unregistered class: %s " % cls.bl_label)
identifier_body
Bijlage_D.py
# ------------------------------------------- # MODULES # ------------------------------------------- import sys import platform if(platform.system()== "Windows"): dir_sep = "\\" else: dir_sep = "/" import time import os import numpy as np import subprocess import math from mathutils import Vector try: from CifFi...
elf,o1, o2, scn): curve = bpy.data.curves.new("link", 'CURVE') curve.dimensions = '3D' spline = curve.splines.new('BEZIER') spline.bezier_points.add(1) p0 = spline.bezier_points[0] p1 = spline.bezier_points[1] # p0.co = o1.location p0.handle_right_type =...
okCurve(s
identifier_name
Bijlage_D.py
# ------------------------------------------- # MODULES # ------------------------------------------- import sys import platform if(platform.system()== "Windows"): dir_sep = "\\" else: dir_sep = "/" import time import os import numpy as np import subprocess import math from mathutils import Vector try: from CifFi...
# draw lines for i,j in zip([0,0,0,1,1,2,2,3,4,4,5,6],[1,2,4,3,5,3,6,7,5,6,7,7]): cell_edges.append(self.drawLine(cell_corners[i].location,cell_corners[j].location)) # select all line and corners for i in cell_corners: i.select_set(action="SELECT") for i in...
r k in range(2): bpy.ops.mesh.primitive_uv_sphere_add(size=lattice_size,location=toCarth(self.ftoc,[i,j,k])) activeObject = bpy.context.active_object # Set active object to variable cell_corners.append(activeObject) mat = bpy.data.materials...
conditional_block
Bijlage_D.py
# ------------------------------------------- # MODULES # ------------------------------------------- import sys import platform if(platform.system()== "Windows"): dir_sep = "\\" else: dir_sep = "/" import time import os import numpy as np import subprocess import math from mathutils import Vector try: from CifFi...
r[2, 1] = float(0) r[2, 2] = float(volume / (a*b*sing)) return r def drawCrystal(self): if draw_lattice: self.drawCell() print("Lattice drawn after {:.3f} seconds".format((time.time()-self.start))) self.drawAtoms() print("Atoms drawn after {...
random_line_split
gopro.py
import argparse import csv import json from datetime import datetime, timedelta, date import os import subprocess from functools import reduce from json import JSONEncoder from gpxpy.geo import Location import pytz from raw_instr_data import RawInstrData GOPRO_GPMF_BIN = '../gopro_gpmf/cmake-build-debug/gopro_gpmf' ...
(self, sd_card_dir, work_dir): cache_dir = work_dir + os.sep + 'gopro' os.makedirs(cache_dir, exist_ok=True) self.instr_data = [] # Build the list of clips clips = [] print(f'Looking for GOPRO clips in {sd_card_dir} ...') for root, dirs_list, files_list in os.wa...
__init__
identifier_name
gopro.py
import argparse import csv import json from datetime import datetime, timedelta, date import os import subprocess from functools import reduce from json import JSONEncoder from gpxpy.geo import Location import pytz from raw_instr_data import RawInstrData GOPRO_GPMF_BIN = '../gopro_gpmf/cmake-build-debug/gopro_gpmf' ...
if __name__ == '__main__': parser = argparse.ArgumentParser(fromfile_prefix_chars='@') parser.add_argument("--work-dir", help="Working directory", default='/tmp') parser.add_argument("--gopro-dir", help="GoPro SD card directory", default='/Volumes/GOPRO') args = parser.parse_args() gopro = GoPro...
clips = [] for start_idx in range(len(self.clips)): clip = self.clips[start_idx] if clip['start_utc'] <= start_utc <= clip['stop_utc']: in_time = (start_utc - clip['start_utc']).seconds # Now find the clip containing the stop time for stop_...
identifier_body
gopro.py
import argparse import csv import json from datetime import datetime, timedelta, date import os import subprocess from functools import reduce from json import JSONEncoder from gpxpy.geo import Location import pytz from raw_instr_data import RawInstrData GOPRO_GPMF_BIN = '../gopro_gpmf/cmake-build-debug/gopro_gpmf' ...
return clips if __name__ == '__main__': parser = argparse.ArgumentParser(fromfile_prefix_chars='@') parser.add_argument("--work-dir", help="Working directory", default='/tmp') parser.add_argument("--gopro-dir", help="GoPro SD card directory", default='/Volumes/GOPRO') args = parser.parse_ar...
in_time = (start_utc - clip['start_utc']).seconds # Now find the clip containing the stop time for stop_idx in range(start_idx, len(self.clips)): clip = self.clips[stop_idx] if stop_utc <= clip['stop_utc']: # Last clip found ...
conditional_block
gopro.py
import argparse import csv import json from datetime import datetime, timedelta, date import os import subprocess from functools import reduce from json import JSONEncoder from gpxpy.geo import Location import pytz from raw_instr_data import RawInstrData GOPRO_GPMF_BIN = '../gopro_gpmf/cmake-build-debug/gopro_gpmf' ...
ii.sow = h['sow'] ii.hdg = h['hdg'] ii.n2k_epoch = h['n2k_epoch'] ii_list.append(ii) d[k] = ii_list return d class GoPro: def __init__(self, sd_card_dir, work_dir): cache_dir = work_dir + os.sep + 'gopro' os.makedirs(...
ii.twa = h['twa'] ii.tws = h['tws']
random_line_split
Octagoat.py
# Octagoat. 13 December 2019. Author: Mohammed Madi. # Coursework 2 project for COMP16321. # The goat background picture was taken on the # 23rd of November 2019 at Snowdon, Wales by the author. # The goat pixel drawings and the cage were produced # using PixilArt online tool and modified using GIMP. from tkinter i...
# Bosskey reversal button def bossisgone(event): global boss, width canvas.move(boss, 0, -width) def gameover(): global window, Restart, exitb, menub, hit, over, score Restart = Button(window, text="Restart", background="black", foreground="white", activebackground="green", wid...
global boss, width canvas.move(boss, 0, width)
identifier_body
Octagoat.py
# Octagoat. 13 December 2019. Author: Mohammed Madi. # Coursework 2 project for COMP16321. # The goat background picture was taken on the # 23rd of November 2019 at Snowdon, Wales by the author. # The goat pixel drawings and the cage were produced # using PixilArt online tool and modified using GIMP. from tkinter i...
if g4[2] > (width-100): dir4 = "right" if dir4 == "right": mov2 = -mov2 if g2[0] < 100: dir2 = "left" if g2[2] > (width-100): dir2 = "right" if dir2 == "right": mov1 = -mov1 canvas.move(enemy2, ...
dir4 = "left"
conditional_block
Octagoat.py
# Octagoat. 13 December 2019. Author: Mohammed Madi. # Coursework 2 project for COMP16321.
# The goat pixel drawings and the cage were produced # using PixilArt online tool and modified using GIMP. from tkinter import Tk, PhotoImage, Button from tkinter import Menu, messagebox, Canvas, Label from PIL import Image, ImageTk import time # Window dimensions. def setWindowDimensions(w, h): window.title("...
# The goat background picture was taken on the # 23rd of November 2019 at Snowdon, Wales by the author.
random_line_split
Octagoat.py
# Octagoat. 13 December 2019. Author: Mohammed Madi. # Coursework 2 project for COMP16321. # The goat background picture was taken on the # 23rd of November 2019 at Snowdon, Wales by the author. # The goat pixel drawings and the cage were produced # using PixilArt online tool and modified using GIMP. from tkinter i...
(event): global paused if paused == 0: pausetxt = Label(canvas, text="Game paused\ \nReturn?\nThe game will pause for 3 seconds when\ you press p again", font="terminal 15", bg="green") pausetxt.place(x=width/3, y=100) paused += 1 window.after(10000, lambd...
pause
identifier_name
main.py
import math import random import os import shutil from abc import * def howItPrint(): print("hello world") # how to print #-----variables----- def variables(): name = "Ben Rafalski" # can use single or double quotes for a string in python age = 20 height = 250.5 alive = True # booleans...
return sum print(add(5,5,5,5,5,5,5)) #-----**kwargs, packs all arguments into a dictionary----- def hello(**kwargs): print("hello", end = " ") for key,value in kwargs.items(): print(value, end=" ") hello(first="ben", middle = "charles", last = "rafalski") ...
sum += i
conditional_block
main.py
import math import random import os import shutil from abc import * def howItPrint(): print("hello world") # how to print #-----variables----- def variables(): name = "Ben Rafalski" # can use single or double quotes for a string in python age = 20 height = 250.5 alive = True # booleans...
(self): print("this hawk is flying") rabbit, fish, hawk = Rabbit(), Fish(), Hawk() print(rabbit.alive, fish.alive, hawk.alive) fish.eat() hawk.sleep() rabbit.hop() fish.swim() hawk.fly() #-----multiple inheritance----- def multipleInheritance(): class Prey: ...
fly
identifier_name
main.py
import math import random import os import shutil from abc import * def howItPrint():
#-----variables----- def variables(): name = "Ben Rafalski" # can use single or double quotes for a string in python age = 20 height = 250.5 alive = True # booleans start with a capital letter print("hello " + name + " who is: " + str(age) + " years old and " + str(250.5) + "cm tall, is ben...
print("hello world") # how to print
identifier_body
main.py
import math import random import os import shutil from abc import * def howItPrint(): print("hello world") # how to print #-----variables----- def variables(): name = "Ben Rafalski" # can use single or double quotes for a string in python age = 20 height = 250.5 alive = True # booleans...
with open('test.txt', 'w') as file: # open in write mode file.write(text) # ovewrites previous file, use 'a' instead of 'w' for appending instead #-----copying a file, use 'import shutil'----- def copyFile(): shutil.copyfile('test.txt', 'copy.txt') # src,dest #-----moving a file, use 'import os...
text = "this is my written text\nThis is a newline"
random_line_split
client.go
/* Copyright (c) 2023 SAP SE or an SAP affiliate company. 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 app...
for _, obj := range objects { if err := o.Add(obj); err != nil { panic(err) } } cs := &Clientset{Clientset: &k8sfake.Clientset{}} cs.FakeDiscovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake} cs.Fake.AddReactor("*", "*", k8stesting.ObjectReaction(o)) cs.Fake.AddWatchReactor("*", o.watchReactionFunc) ...
}
random_line_split
client.go
/* Copyright (c) 2023 SAP SE or an SAP affiliate company. 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 app...
// Create receives a create event with the object. Not needed for CA. func (t *FakeObjectTracker) Create(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error { return nil } // Update receives an update event with the object func (t *FakeObjectTracker) Update(gvr schema.GroupVersionResource, obj run...
{ var err error if t.fakingOptions.failAll != nil { err = t.fakingOptions.failAll.RunFakeInvocations() if err != nil { return nil, err } } if t.fakingOptions.failAt != nil { if gvr.Resource == "nodes" { err = t.fakingOptions.failAt.Node.Get.RunFakeInvocations() } else if gvr.Resource == "machines" {...
identifier_body
client.go
/* Copyright (c) 2023 SAP SE or an SAP affiliate company. 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 app...
(event *watch.Event) { for _, w := range t.watchers { go w.dispatch(event) } } // Stop terminates tracking of an FakeObjectTracker func (t *FakeObjectTracker) Stop() { if t.FakeWatcher == nil { panic(errors.New("tracker has no watch support")) } t.trackerMutex.Lock() defer t.trackerMutex.Unlock() t.FakeWa...
dispatch
identifier_name
client.go
/* Copyright (c) 2023 SAP SE or an SAP affiliate company. 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 app...
} return t.delegatee.Get(gvr, ns, name) } // Create receives a create event with the object. Not needed for CA. func (t *FakeObjectTracker) Create(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error { return nil } // Update receives an update event with the object func (t *FakeObjectTracker) Up...
{ return nil, err }
conditional_block
xf_numba.py
#! /usr/bin/env python # ============================================================================= # Copyright (c) 2012, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # Written by Joel Bernier <bernier2@llnl.gov> and others. # LLNL-CODE-529294. # All rights res...
@numba.njit def _make_rmat_of_expmap(x, out=None): """ TODO: Test effectiveness of two options: 1) avoid conditional inside for loop and use np.divide to return NaN for the phi = 0 cases, and deal with it later; or 2) catch phi = 0 cases inside the loop and just return squeezed answer ...
""" normalize array of column vectors (hstacked, axis = 0) """ if vec_in.ndim == 1: out = _unit_vector_single(vec_in) elif vec_in.ndim == 2: out = _unit_vector_multi(vec_in) else: raise ValueError( "incorrect arg shape; must be 1-d or 2-d, yours is %d-d" ...
identifier_body
xf_numba.py
#! /usr/bin/env python # ============================================================================= # Copyright (c) 2012, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # Written by Joel Bernier <bernier2@llnl.gov> and others. # LLNL-CODE-529294. # All rights res...
(fn): out = numba.jit(fn) out.__signature__ = get_signature(fn) return out @numba.njit def _angles_to_gvec_helper(angs, out=None): """ angs are vstacked [2*theta, eta, omega], although omega is optional This should be equivalent to the one-liner numpy version: out = np.vstack([[np.cos(0....
xfapi_jit
identifier_name
xf_numba.py
#! /usr/bin/env python # ============================================================================= # Copyright (c) 2012, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # Written by Joel Bernier <bernier2@llnl.gov> and others. # LLNL-CODE-529294. # All rights res...
return out @numba.njit def _unit_vector_multi(a, out=None): out = out if out is not None else np.empty_like(a) n, dim = a.shape for i in range(n): #_unit_vector_single(a[i], out=out[i]) sqr_norm = a[i, 0] * a[i, 0] for j in range(1, dim): sqr_norm += a[i, j]*a[i...
out[:] = a[:]
conditional_block
xf_numba.py
#! /usr/bin/env python # ============================================================================= # Copyright (c) 2012, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # Written by Joel Bernier <bernier2@llnl.gov> and others. # LLNL-CODE-529294. # All rights res...
out = out if out is not None else np.empty_like(a) n, dim = a.shape for i in range(n): #_unit_vector_single(a[i], out=out[i]) sqr_norm = a[i, 0] * a[i, 0] for j in range(1, dim): sqr_norm += a[i, j]*a[i, j] if sqr_norm > cnst.epsf: recip_norm = 1.0 ...
@numba.njit def _unit_vector_multi(a, out=None):
random_line_split
report_errors_service.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto package clouderrorreporting import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "google.golang.org/genproto/googleapis/api/annotations" import go...
() string { return proto.CompactTextString(m) } func (*ReportErrorEventResponse) ProtoMessage() {} func (*ReportErrorEventResponse) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{1} } // An error event which is reported to the Error Reporting system. type ReportedErrorEvent struc...
String
identifier_name
report_errors_service.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto package clouderrorreporting import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "google.golang.org/genproto/googleapis/api/annotations" import go...
func RegisterReportErrorsServiceServer(s *grpc.Server, srv ReportErrorsServiceServer) { s.RegisterService(&_ReportErrorsService_serviceDesc, srv) } func _ReportErrorsService_ReportErrorEvent_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{...
random_line_split
report_errors_service.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto package clouderrorreporting import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "google.golang.org/genproto/googleapis/api/annotations" import go...
return nil } // Response for reporting an individual error event. // Data may be added to this message in the future. type ReportErrorEventResponse struct { } func (m *ReportErrorEventResponse) Reset() { *m = ReportErrorEventResponse{} } func (m *ReportErrorEventResponse) String() string ...
{ return m.Event }
conditional_block
report_errors_service.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto package clouderrorreporting import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "google.golang.org/genproto/googleapis/api/annotations" import go...
var fileDescriptor3 = []byte{ // 490 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0xcd, 0x8a, 0x13, 0x41, 0x10, 0xc7, 0x99, 0xf8, 0xb1, 0x6c, 0x47, 0x54, 0xda, 0x83, 0xc3, 0x20, 0xb8, 0xc6, 0xcb, 0xa2, 0x30, 0x6d, 0xe2, 0xc5, 0xec, 0x22, 0x0b, 0x59...
{ proto.RegisterFile("google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto", fileDescriptor3) }
identifier_body
crunchauto.py
#!/usr/bin/python #import ConfigParser import icalendar,sys,os,datetime import stripe import pytz import urllib import json from dateutil import tz from ..templateCommon import * def utctolocal(dt,endofdate=False): from_zone = tz.gettz('UTC') to_zone = tz.gettz('America/New_York') if isinstance(dt,datetime....
else: if endofdate: dt = datetime.datetime.combine(dt,datetime.time(hour=23,minute=59,second=59,tzinfo=to_zone)) else: dt = datetime.datetime.combine(dt,datetime.time(tzinfo=to_zone)) return dt weekday=['Sun','Mon','Tues','Wed','Thurs','Fri','Sat'] # OUR Sunday=0 Convention!! def crunch_calend...
dt = dt.astimezone(to_zone)
conditional_block
crunchauto.py
#!/usr/bin/python #import ConfigParser import icalendar,sys,os,datetime import stripe import pytz import urllib import json from dateutil import tz from ..templateCommon import * def utctolocal(dt,endofdate=False): from_zone = tz.gettz('UTC') to_zone = tz.gettz('America/New_York') if isinstance(dt,datetime....
errors=[] warnings=[] debug=[] stripe.api_key = current_app.config['globalConfig'].Config.get('autoplot','stripe_token') #stripe.api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" # TEST KEY #print stripe.SKU.list(limit=99) #print stripe.Customer.list(limit=99) debug.append("Process Payment customer {0} Price ...
identifier_body
crunchauto.py
#!/usr/bin/python #import ConfigParser import icalendar,sys,os,datetime import stripe import pytz import urllib import json from dateutil import tz from ..templateCommon import * def utctolocal(dt,endofdate=False): from_zone = tz.gettz('UTC') to_zone = tz.gettz('America/New_York') if isinstance(dt,datetime....
(customer,price,leaseid,description,test=False,pay=False): errors=[] warnings=[] debug=[] stripe.api_key = current_app.config['globalConfig'].Config.get('autoplot','stripe_token') #stripe.api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" # TEST KEY #print stripe.SKU.list(limit=99) #print stripe.Customer.list(l...
do_payment
identifier_name
crunchauto.py
#!/usr/bin/python #import ConfigParser import icalendar,sys,os,datetime import stripe import pytz import urllib import json from dateutil import tz from ..templateCommon import * def utctolocal(dt,endofdate=False): from_zone = tz.gettz('UTC') to_zone = tz.gettz('America/New_York') if isinstance(dt,datetime....
weekstart = weekstart.replace(hour=0,minute=0,second=0,microsecond=0) weekend = weekstart + datetime.timedelta(days=7) weekend = weekend - datetime.timedelta(seconds=1) #print "WEEKSTART",weekstart,"through",weekend errors=[] warnings=[] billables=[] summaries=[] debug=[] data={} debug.append("{2...
dow = (dow+1) %7 #0=Sunday weeknum = int(now.strftime("%U")) #print "weeknum",weeknum,"Weekday",weekday[dow],"DOW",dow weekstart = (now - datetime.timedelta(days=dow))
random_line_split
lib.rs
//! Salak is a multi layered configuration loader and zero-boilerplate configuration parser, with many predefined sources. //! //! 1. [About](#about) //! 2. [Quick Start](#quick-start) //! 3. [Features](#features) //! * [Predefined Sources](#predefined-sources) //! * [Key Convention](#key-convention) //! * [Va...
<T: PrefixedFromEnvironment>(&self) -> Res<T> { self.require::<T>(T::prefix()) } } /// Context for implementing [`FromEnvironment`]. #[allow(missing_debug_implementations)] pub struct SalakContext<'a> { registry: &'a PropertyRegistryInternal<'a>, iorefs: &'a Mutex<Vec<Box<dyn IORefT + Send>>>, ...
get
identifier_name
lib.rs
//! Salak is a multi layered configuration loader and zero-boilerplate configuration parser, with many predefined sources. //! //! 1. [About](#about) //! 2. [Quick Start](#quick-start) //! 3. [Features](#features) //! * [Predefined Sources](#predefined-sources) //! * [Key Convention](#key-convention) //! * [Va...
} /// Parsing value from environment by [`SalakContext`]. pub trait FromEnvironment: Sized { /// Generate object from [`SalakContext`]. /// * `val` - Property value can be parsed from. /// * `env` - Context. /// /// ```no_run /// use salak::*; /// pub struct Config { /// key: String ...
iorefs: &'a Mutex<Vec<Box<dyn IORefT + Send>>>, key: &'a mut Key<'a>,
random_line_split
lib.rs
//! Salak is a multi layered configuration loader and zero-boilerplate configuration parser, with many predefined sources. //! //! 1. [About](#about) //! 2. [Quick Start](#quick-start) //! 3. [Features](#features) //! * [Predefined Sources](#predefined-sources) //! * [Key Convention](#key-convention) //! * [Va...
} /// Context for implementing [`FromEnvironment`]. #[allow(missing_debug_implementations)] pub struct SalakContext<'a> { registry: &'a PropertyRegistryInternal<'a>, iorefs: &'a Mutex<Vec<Box<dyn IORefT + Send>>>, key: &'a mut Key<'a>, } /// Parsing value from environment by [`SalakContext`]. pub trait F...
{ self.require::<T>(T::prefix()) }
identifier_body
core.py
import json import os import random import shutil import subprocess import tempfile import time from dataclasses import asdict, fields from distutils.version import StrictVersion from typing import IO, Any, Dict, List import jinja2 from jmeslog import model from jmeslog.constants import DEFAULT_TEMPLATE, VALID_CHARS ...
(self) -> str: return find_last_released_version(self._change_dir) def query_next_version(self) -> str: changes = load_next_changes(self._change_dir) last_released_version = find_last_released_version(self._change_dir) next_version = determine_next_version( last_released...
query_last_release_version
identifier_name
core.py
import json import os import random import shutil import subprocess import tempfile import time from dataclasses import asdict, fields from distutils.version import StrictVersion from typing import IO, Any, Dict, List import jinja2 from jmeslog import model from jmeslog.constants import DEFAULT_TEMPLATE, VALID_CHARS ...
def query_next_version(self) -> str: changes = load_next_changes(self._change_dir) last_released_version = find_last_released_version(self._change_dir) next_version = determine_next_version( last_released_version, changes.version_bump_type ) return next_version ...
return find_last_released_version(self._change_dir)
identifier_body
core.py
import json import os import random import shutil import subprocess import tempfile import time from dataclasses import asdict, fields from distutils.version import StrictVersion from typing import IO, Any, Dict, List import jinja2 from jmeslog import model from jmeslog.constants import DEFAULT_TEMPLATE, VALID_CHARS ...
f'The "{schema_field.name}" value must be one of: ' f'{", ".join(allowed_values)}, received: "{value}"' ) for key, value in entry_dict.items(): if not value: errors.append(f'The "{key}" value cannot be empty.') if errors: raise ValidationEr...
random_line_split
core.py
import json import os import random import shutil import subprocess import tempfile import time from dataclasses import asdict, fields from distutils.version import StrictVersion from typing import IO, Any, Dict, List import jinja2 from jmeslog import model from jmeslog.constants import DEFAULT_TEMPLATE, VALID_CHARS ...
class EntryFileParser: def parse_contents(self, contents: str) -> model.JMESLogEntry: entry = model.JMESLogEntry.empty() if not contents.strip(): return entry field_names = [f.name for f in fields(entry)] line_starts = tuple([f'{name}:' for name in field_names]) ...
setattr(entry, key, value)
conditional_block
mod.rs
//! TensorFlow Ops use std::collections::HashMap; use std::collections::VecDeque; use std::fmt::Debug; use std::mem; use std::ops::{Index, IndexMut}; #[cfg(feature = "serialize")] use std::result::Result as StdResult; use std::sync::Arc; use analyser::interface::{Solver, TensorsProxy}; use analyser::prelude::*; use op...
(&self) -> &Tensor { match self { &TensorView::Owned(ref m) => &m, &TensorView::Shared(ref m) => m.as_ref(), } } /// Returns a shared copy of the TensorView, turning the one passed /// as argument into a TensorView::Shared if necessary. pub fn share(&mut self) ->...
as_tensor
identifier_name
mod.rs
//! TensorFlow Ops use std::collections::HashMap; use std::collections::VecDeque; use std::fmt::Debug; use std::mem; use std::ops::{Index, IndexMut}; #[cfg(feature = "serialize")] use std::result::Result as StdResult; use std::sync::Arc; use analyser::interface::{Solver, TensorsProxy}; use analyser::prelude::*; use op...
bail!("Streaming is not available for operator {:?}", self) } /// Infers properties about the input and output tensors. /// /// The `inputs` and `outputs` arguments correspond to properties about /// the input and output tensors that are already known. /// /// Returns Err in case of...
fn step( &self, _inputs: Vec<(Option<usize>, Option<TensorView>)>, _buffer: &mut Box<OpBuffer>, ) -> Result<Option<Vec<TensorView>>> {
random_line_split
mod.rs
//! TensorFlow Ops use std::collections::HashMap; use std::collections::VecDeque; use std::fmt::Debug; use std::mem; use std::ops::{Index, IndexMut}; #[cfg(feature = "serialize")] use std::result::Result as StdResult; use std::sync::Arc; use analyser::interface::{Solver, TensorsProxy}; use analyser::prelude::*; use op...
/// Creates a Tensor from a TensorView. pub fn into_tensor(self) -> Tensor { match self { TensorView::Owned(m) => m, TensorView::Shared(m) => m.as_ref().clone(), } } /// Returns a reference to the Tensor wrapped inside a TensorView. pub fn as_tensor(&self) ...
{ match self { TensorView::Owned(m) => TensorView::Shared(Arc::new(m)), TensorView::Shared(_) => self, } }
identifier_body
import.go
package main import ( "bytes" "context" "encoding/json" "flag" "fmt" "github.com/alexashley/terraform-provider-kong/kong/kong" "github.com/google/subcommands" "io/ioutil" "os" "os/exec" "strings" ) type importCommand struct { adminApiUrl string rbacToken string isDryRun bool importFileNam...
func pluginHasSpecificResourceImplementation(plugin *kong.KongPlugin) bool { _, ok := pluginsToResourceImplementations[plugin.Name] return ok }
{ namePrefix := "" if plugin.ServiceId != "" { for _, service := range s.services { if service.Id == plugin.ServiceId { namePrefix = service.Name break } } } else if plugin.RouteId != "" { for _, route := range s.routes { if route.Id == plugin.RouteId { namePrefix = getResourceNameForRout...
identifier_body
import.go
package main import ( "bytes" "context" "encoding/json" "flag" "fmt" "github.com/alexashley/terraform-provider-kong/kong/kong" "github.com/google/subcommands" "io/ioutil" "os" "os/exec" "strings" ) type importCommand struct { adminApiUrl string rbacToken string isDryRun bool importFileNam...
return nil } func (s *kongState) finish(fileName string) error { if data, err := json.Marshal(s.imports); err != nil { return err } else { return ioutil.WriteFile(fileName, data, 0644) } } func getResourceNameForConsumer(consumer *kong.KongConsumer) string { if len(consumer.Username) > 0 { return consume...
{ fmt.Println("\nImporting consumers:") for _, consumer := range s.consumers { resource := &resourceImport{ kongResourceType: "consumer", terraformResourceType: "kong_consumer", resourceName: getResourceNameForConsumer(&consumer), resourceId: consumer.Id, dryRun: ...
conditional_block
import.go
package main import ( "bytes" "context" "encoding/json" "flag" "fmt" "github.com/alexashley/terraform-provider-kong/kong/kong" "github.com/google/subcommands" "io/ioutil" "os" "os/exec" "strings" ) type importCommand struct { adminApiUrl string rbacToken string isDryRun bool importFileNam...
(resourceImport *resourceImport) error { if s.hasResourceBeenImported(resourceImport) { return nil } terraformResourceName := fmt.Sprintf("%s.%s", resourceImport.terraformResourceType, createHclSafeName(resourceImport.resourceName)) if !resourceImport.dryRun { // ex: terraform import -config=examples/import ko...
importResource
identifier_name
import.go
package main import ( "bytes" "context" "encoding/json" "flag" "fmt" "github.com/alexashley/terraform-provider-kong/kong/kong" "github.com/google/subcommands" "io/ioutil" "os" "os/exec" "strings" ) type importCommand struct { adminApiUrl string rbacToken string isDryRun bool importFileNam...
if len(s.consumers) > 0 { fmt.Println("\nImporting consumers:") for _, consumer := range s.consumers { resource := &resourceImport{ kongResourceType: "consumer", terraformResourceType: "kong_consumer", resourceName: getResourceNameForConsumer(&consumer), resourceId: con...
return nil } func (s *kongState) importResources(cmd *importCommand) error {
random_line_split
mtcnn.py
import numpy as np import torch import torch.nn as nn from torch.nn.functional import interpolate from torchvision.ops.boxes import batched_nms class MTCNN(): def __init__(self, device=None, model=None): if device is None: device = 'cuda' if torch.cuda.is_available() else 'cpu' self.device = device url = '...
else: if not isinstance(imgs, (list, tuple)): imgs = [imgs] if any(img.size != imgs[0].size for img in imgs): raise Exception("MTCNN batch processing only compatible with equal-dimension images.") imgs = np.stack([np.uint8(img) for img in imgs]) imgs = torch.as_tensor(imgs, device=device) model_dtype ...
imgs = torch.as_tensor(imgs, device=device) if len(imgs.shape) == 3: imgs = imgs.unsqueeze(0)
conditional_block
mtcnn.py
import numpy as np import torch import torch.nn as nn from torch.nn.functional import interpolate from torchvision.ops.boxes import batched_nms class MTCNN(): def __init__(self, device=None, model=None): if device is None: device = 'cuda' if torch.cuda.is_available() else 'cpu' self.device = device url = '...
(boxes, w, h): boxes = boxes.trunc().int().cpu().numpy() x = boxes[:, 0] y = boxes[:, 1] ex = boxes[:, 2] ey = boxes[:, 3] x[x < 1] = 1 y[y < 1] = 1 ex[ex > w] = w ey[ey > h] = h return y, ey, x, ex def rerec(bboxA): h = bboxA[:, 3] - bboxA[:, 1] w = bboxA[:, 2] - bboxA[:, 0] l = torch.max(w, h) bbox...
pad
identifier_name
mtcnn.py
import numpy as np import torch import torch.nn as nn from torch.nn.functional import interpolate from torchvision.ops.boxes import batched_nms class MTCNN(): def __init__(self, device=None, model=None): if device is None: device = 'cuda' if torch.cuda.is_available() else 'cpu' self.device = device url = '...
def detect_face(imgs, minsize, pnet, rnet, onet, threshold, factor, device): if isinstance(imgs, (np.ndarray, torch.Tensor)): imgs = torch.as_tensor(imgs, device=device) if len(imgs.shape) == 3: imgs = imgs.unsqueeze(0) else: if not isinstance(imgs, (list, tuple)): imgs = [imgs] if any(img.size != im...
def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3) self.prelu1 = nn.PReLU(32) self.pool1 = nn.MaxPool2d(3, 2, ceil_mode=True) self.conv2 = nn.Conv2d(32, 64, kernel_size=3) self.prelu2 = nn.PReLU(64) self.pool2 = nn.MaxPool2d(3, 2, ceil_mode=True) self.conv3 = nn.Conv2d(...
identifier_body
mtcnn.py
import numpy as np import torch import torch.nn as nn from torch.nn.functional import interpolate from torchvision.ops.boxes import batched_nms class MTCNN(): def __init__(self, device=None, model=None): if device is None: device = 'cuda' if torch.cuda.is_available() else 'cpu' self.device = device url = '...
class ONet(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3) self.prelu1 = nn.PReLU(32) self.pool1 = nn.MaxPool2d(3, 2, ceil_mode=True) self.conv2 = nn.Conv2d(32, 64, kernel_size=3) self.prelu2 = nn.PReLU(64) self.pool2 = nn.MaxPool2d(3, 2, ceil_mode=True...
a = self.dense5_1(x) a = self.softmax5_1(a) b = self.dense5_2(x) return b, a
random_line_split
lambdaFunction.go
package lambda import ( "bufio" "container/list" "errors" "fmt" "log" "net/http" "os" "path/filepath" "strings" "time" "github.com/open-lambda/open-lambda/ol/common" "github.com/open-lambda/open-lambda/ol/worker/lambda/packages" "github.com/open-lambda/open-lambda/ol/worker/sandbox" ) // LambdaFunc repr...
{ done := make(chan bool) f.killChan <- done <-done }
identifier_body
lambdaFunction.go
package lambda import ( "bufio" "container/list" "errors" "fmt" "log" "net/http" "os" "path/filepath" "strings" "time" "github.com/open-lambda/open-lambda/ol/common" "github.com/open-lambda/open-lambda/ol/worker/lambda/packages" "github.com/open-lambda/open-lambda/ol/worker/sandbox" ) // LambdaFunc repr...
} func (f *LambdaFunc) newInstance() { if f.codeDir == "" { panic("cannot start instance until code has been fetched") } linst := &LambdaInstance{ lfunc: f, codeDir: f.codeDir, meta: f.meta, killChan: make(chan chan bool, 1), } f.instances.PushBack(linst) go linst.Task() } func (f *LambdaF...
{ select { case <-timeout.C: if f.codeDir == "" { continue } case req := <-f.funcChan: // msg: client -> function // check for new code, and cleanup old code // (and instances that use it) if necessary oldCodeDir := f.codeDir if err := f.pullHandlerIfStale(); err != nil { f.printf("E...
conditional_block
lambdaFunction.go
package lambda import ( "bufio" "container/list" "errors" "fmt" "log" "net/http" "os" "path/filepath" "strings" "time" "github.com/open-lambda/open-lambda/ol/common" "github.com/open-lambda/open-lambda/ol/worker/lambda/packages" "github.com/open-lambda/open-lambda/ol/worker/sandbox" ) // LambdaFunc repr...
() { if f.codeDir == "" { panic("cannot start instance until code has been fetched") } linst := &LambdaInstance{ lfunc: f, codeDir: f.codeDir, meta: f.meta, killChan: make(chan chan bool, 1), } f.instances.PushBack(linst) go linst.Task() } func (f *LambdaFunc) Kill() { done := make(chan boo...
newInstance
identifier_name
lambdaFunction.go
package lambda import ( "bufio" "container/list" "errors" "fmt" "log" "net/http" "os" "path/filepath" "strings" "time" "github.com/open-lambda/open-lambda/ol/common" "github.com/open-lambda/open-lambda/ol/worker/lambda/packages" "github.com/open-lambda/open-lambda/ol/worker/sandbox" ) // LambdaFunc repr...
// this Task receives lambda requests, fetches new lambda code as // needed, and dispatches to a set of lambda instances. Task also // monitors outstanding requests, and scales the number of instances // up or down as needed. // // communication for a given request is as follows (each of the four // transfers are com...
f.codeDir = codeDir f.lastPull = &now return nil }
random_line_split
lib.rs
mod file_log; mod formatter; pub mod log_macro; use std::env; use std::fmt; use std::io::{self, BufWriter}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::thread; use log::{self, SetLoggerError}; use slog::{self, slog_o, Drain, FnValue, Key, OwnedKVList,...
type Err = io::Error; fn log(&self, record: &Record<'_>, values: &OwnedKVList) -> Result<Self::Ok, Self::Err> { let tag = record.tag(); println!("{}", tag); if self.slow.is_some() && tag.starts_with("slow_log") { self.slow.as_ref().unwrap().log(record, values) } else...
random_line_split
lib.rs
mod file_log; mod formatter; pub mod log_macro; use std::env; use std::fmt; use std::io::{self, BufWriter}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::thread; use log::{self, SetLoggerError}; use slog::{self, slog_o, Drain, FnValue, Key, OwnedKVList,...
// Converts `slog::Level` to unified log level format. fn get_unified_log_level(lv: Level) -> &'static str { match lv { Level::Critical => "FATAL", Level::Error => "ERROR", Level::Warning => "WARN", Level::Info => "INFO", Level::Debug => "DEBUG", Level::Trace => "TR...
{ match lv { Level::Critical => "critical", Level::Error => "error", Level::Warning => "warning", Level::Debug => "debug", Level::Trace => "trace", Level::Info => "info", } }
identifier_body
lib.rs
mod file_log; mod formatter; pub mod log_macro; use std::env; use std::fmt; use std::io::{self, BufWriter}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::thread; use log::{self, SetLoggerError}; use slog::{self, slog_o, Drain, FnValue, Key, OwnedKVList,...
(&self, record: &Record<'_>, values: &OwnedKVList) -> Result<Self::Ok, Self::Err> { let tag = record.tag(); println!("{}", tag); if self.slow.is_some() && tag.starts_with("slow_log") { self.slow.as_ref().unwrap().log(record, values) } else { self.normal.log(record...
log
identifier_name
animLib.py
from filesystem import * from common import printInfoStr, printErrorStr from mayaDecorators import d_unifyUndo import maya.cmds as cmd import names import api import apiExtensions __author__ = 'mel@macaronikazoo.com' TOOL_NAME = 'animLib' kEXT = 'clip' VER = 3 #version ### clip types kPOSE = 0 ...
def getPathToLibrary( self, library, locale=LOCAL ): return getPresetDirs(locale, TOOL_NAME)[0] / library def reload( self ): pass #end
global kEXT clips = {LOCAL: [], GLOBAL: []} for locale in LOCAL, GLOBAL: localeClips = clips[locale] for dir in getPresetDirs(locale, TOOL_NAME): dir += library if not dir.exists: continue for f in dir.files(): if f.hasExtension( kEXT ): f = f.setExtension() na...
identifier_body
animLib.py
from filesystem import * from common import printInfoStr, printErrorStr from mayaDecorators import d_unifyUndo import maya.cmds as cmd import names import api import apiExtensions __author__ = 'mel@macaronikazoo.com' TOOL_NAME = 'animLib' kEXT = 'clip' VER = 3 #version ### clip types kPOSE = 0 k...
return self.keys() def generatePreArgs( self ): return tuple() def getObjAttrNames( obj, attrNamesToSkip=() ): #grab attributes objAttrs = cmd.listAttr( obj, keyable=True, visible=True, scalar=True ) or [] #also grab alias' - its possible to pass in an alias name, so we need to test against them a...
''' pass def getObjects( self ):
random_line_split
animLib.py
from filesystem import * from common import printInfoStr, printErrorStr from mayaDecorators import d_unifyUndo import maya.cmds as cmd import names import api import apiExtensions __author__ = 'mel@macaronikazoo.com' TOOL_NAME = 'animLib' kEXT = 'clip' VER = 3 #version ### clip types kPOSE = 0 ...
time = cmd.currentTime(q=True) #make sure the icon is open for edit if its a global clip if preset.locale == GLOBAL and preset.icon.exists: preset.edit() icon = cmd.playblast(st=time, et=time, w=kICON_W_H[0], h=kICON_W_H[1], fo=True, fmt="image", v=0, p=100, orn=0, cf=str(preset.icon.resolve())) ico...
mel.eval("modelEditor -e %s 0 %s;" % (setting, panel))
conditional_block
animLib.py
from filesystem import * from common import printInfoStr, printErrorStr from mayaDecorators import d_unifyUndo import maya.cmds as cmd import names import api import apiExtensions __author__ = 'mel@macaronikazoo.com' TOOL_NAME = 'animLib' kEXT = 'clip' VER = 3 #version ### clip types kPOSE = 0 ...
( self, pct, mapping=None, attributes=None ): BaseBlender.__call__(self, pct, mapping) cmdQueue = api.CmdQueue() if mapping is None: mapping = self.getMapping() if attributes is None: attributes = self.attributes mappingDict = mapping.asDict() for clipAObj, attrDictA in self.clipA.iterit...
__call__
identifier_name
textboardcomponent.js
CARNIVAL.registerComponent('net.meta4vr.textboard', function () { /* Params: textScale backgroundColor width height textLines transparentBackground */ /* There are some subtleties when using transparent backgrounds. The shader discards fragments with alpha <0.9,...
TextBoard.prototype.setText = function (lines) { this.currentTextLines = lines; this.reset(); this.renderTextLines(this.currentTextLines); } TextBoard.prototype.prepare = function () { var board = this; board.drawable.texture = board.getTexture(); bo...
} // this.currentTextLines.push(line); this.reset(); this.renderTextLines(this.currentTextLines); }
random_line_split
textboardcomponent.js
CARNIVAL.registerComponent('net.meta4vr.textboard', function () { /* Params: textScale backgroundColor width height textLines transparentBackground */ /* There are some subtleties when using transparent backgrounds. The shader discards fragments with alpha <0.9,...
board.updateTexture(); } TextBoard.prototype.addTextLines = function (lines) { for (var i = 0; i < lines.length; i++) { this.currentTextLines.push(lines[i]); } // this.currentTextLines.push(line); this.reset(); this.renderTextLines(this.currentTe...
{ var line = textLines[i]; rstate.font = line.font || rstate.font; rstate.fontSize = line.fontSize || rstate.fontSize; rstate.textColor = line.textColor || rstate.textColor; rstate.backgroundColor = line.backgroundColor || rstate.backgroundColor; r...
conditional_block
section_0771_to_0788.rs
//! @ The |align_state| and |preamble| variables are initialized elsewhere. //! //! @<Set init...@>= //! align_ptr:=null; cur_align:=null; cur_span:=null; cur_loop:=null; //! cur_head:=null; cur_tail:=null; //! //! @ Alignment stack maintenance is handled by a pair of trivial routines //! called |push_alignment| and |p...
//! procedure@?align_peek; forward;@t\2@>@/ //! procedure@?normal_paragraph; forward;@t\2@>@/ //! procedure init_align; //! label done, done1, done2, continue; //! var save_cs_ptr:pointer; {|warning_index| value for error messages} //! @!p:pointer; {for short-term temporary use} //! begin save_cs_ptr:=cur_cs; {\.{\\hal...
//! @p @t\4@>@<Declare the procedure called |get_preamble_token|@>@t@>@/
random_line_split
http.rs
//! Simple HTTP implementation which supports both async and traditional execution environments //! with minimal dependencies. This is used as the basis for REST and RPC clients. use chunked_transfer; use serde_json; use std::convert::TryFrom; use std::fmt; #[cfg(not(feature = "tokio"))] use std::io::Write; use std::...
// Decode the chunk header to obtain the chunk size. let mut buffer = Vec::new(); let mut decoder = chunked_transfer::Decoder::new(chunk_header.as_bytes()); decoder.read_to_end(&mut buffer)?; // Read the chunk body. let chunk_size = match decoder.remaining_chunks_size() { ...
{ // Read the terminator chunk since the decoder consumes the CRLF // immediately when this chunk is encountered. reader.read_line(&mut chunk_header).await?; }
conditional_block
http.rs
//! Simple HTTP implementation which supports both async and traditional execution environments //! with minimal dependencies. This is used as the basis for REST and RPC clients. use chunked_transfer; use serde_json; use std::convert::TryFrom; use std::fmt; #[cfg(not(feature = "tokio"))] use std::io::Write; use std::...
if chunk_header == "0\r\n" { // Read the terminator chunk since the decoder consumes the CRLF // immediately when this chunk is encountered. reader.read_line(&mut chunk_header).await?; } // Decode the chunk header to obtain the chunk size. let mut buffer = Vec::new()...
random_line_split
http.rs
//! Simple HTTP implementation which supports both async and traditional execution environments //! with minimal dependencies. This is used as the basis for REST and RPC clients. use chunked_transfer; use serde_json; use std::convert::TryFrom; use std::fmt; #[cfg(not(feature = "tokio"))] use std::io::Write; use std::...
<F>(&mut self, uri: &str, host: &str, auth: &str, content: serde_json::Value) -> std::io::Result<F> where F: TryFrom<Vec<u8>, Error = std::io::Error> { let content = content.to_string(); let request = format!( "POST {} HTTP/1.1\r\n\ Host: {}\r\n\ Authorization: {}\r\n\ Connection: keep-alive\r\n\ ...
post
identifier_name
coref.py
import sys import shelve import numpy as np import tensorflow as tf import time import random import math import os import glob from bs4 import BeautifulSoup starttime = time.time() BATCH_SIZE = 50 def load_dir(Dir): r = Dir + '/' cors = [] cons = [] data = [] genre = [] dirs = [x for x in glo...
soup = BeautifulSoup(f.read(),'lxml') f.close() soup_all = [] stack = [] coreList = [] core_all = [] coref = [] wrapped = False for siru in soup.findAll('coref'): soupList = [] soupList.append(siru.attrs.get('id')) soupList.append(siru.attrs.get('type')) ...
random_line_split
coref.py
import sys import shelve import numpy as np import tensorflow as tf import time import random import math import os import glob from bs4 import BeautifulSoup starttime = time.time() BATCH_SIZE = 50 def
(Dir): r = Dir + '/' cors = [] cons = [] data = [] genre = [] dirs = [x for x in glob.glob(r + '*')] for d in dirs: for _r, _d, files in os.walk(d): for f in files: if f.endswith('_cors'): cors.append([os.path.join(_r, f),d]) ...
load_dir
identifier_name
coref.py
import sys import shelve import numpy as np import tensorflow as tf import time import random import math import os import glob from bs4 import BeautifulSoup starttime = time.time() BATCH_SIZE = 50 def load_dir(Dir): r = Dir + '/' cors = [] cons = [] data = [] genre = [] dirs = [x for x in glo...
elif genre == 'bn': param = 1 elif genre == 'mz': param = 2 elif genre == 'nw': param = 3 elif genre == 'pt': param = 4 elif genre == 'tc': param = 5 elif genre == 'wb': param = 6 return [param] def getWordEmbedding(info_words): dic = she...
param = 0
conditional_block
coref.py
import sys import shelve import numpy as np import tensorflow as tf import time import random import math import os import glob from bs4 import BeautifulSoup starttime = time.time() BATCH_SIZE = 50 def load_dir(Dir): r = Dir + '/' cors = [] cons = [] data = [] genre = [] dirs = [x for x in glo...
nre): print('begin') vector = [] vectors = [] labels = [] costs = [] antecedents = ['NA'] total = len(mentions) print(total) Wembed = Wembedave[0] ave_all = Wembedave[1] for m in mentions: for a in antecedents: if a == 'NA': tm...
pMatch = 1 break return [pMatch] def getInclude(include): if include: return [1] else: return [0] def getVectors(mentions,words,Wembedave,ge
identifier_body
avito-lightgbm-with-ridge-feature-1.py
#Initially forked from Bojan's kernel here: https://www.kaggle.com/tunguz/bow-meta-text-and-dense-features-lb-0-2242/code #improvement using kernel from Nick Brook's kernel here: https://www.kaggle.com/nicapotato/bow-meta-text-and-dense-features-lgbm #Used oof method from Faron's kernel here: https://www.kaggle.com/m...
oof_test[:] = oof_test_skf.mean(axis=0) return oof_train.reshape(-1, 1), oof_test.reshape(-1, 1) def cleanName(text): try: textProc = text.lower() # textProc = " ".join(map(str.strip, re.split('(\d+)',textProc))) #regex = re.compile(u'[^[:alpha:]]') #textProc...
print('\nFold {}'.format(i)) x_tr = x_train[train_index] y_tr = y[train_index] x_te = x_train[test_index] clf.train(x_tr, y_tr) oof_train[test_index] = clf.predict(x_te) oof_test_skf[i, :] = clf.predict(x_test)
conditional_block
avito-lightgbm-with-ridge-feature-1.py
#Initially forked from Bojan's kernel here: https://www.kaggle.com/tunguz/bow-meta-text-and-dense-features-lb-0-2242/code #improvement using kernel from Nick Brook's kernel here: https://www.kaggle.com/nicapotato/bow-meta-text-and-dense-features-lgbm #Used oof method from Faron's kernel here: https://www.kaggle.com/m...
lbl = preprocessing.LabelEncoder() for col in categorical: df[col].fillna('Unknown') df[col] = lbl.fit_transform(df[col].astype(str)) print("\nText Features") # Feature Engineering # Meta Text Features textfeats = ["description", "title"] df['desc_punc'] = df['description'].apply(lambda x: le...
categorical = ["user_id","region","city","parent_category_name","category_name","user_type","image_top_1","param_1","param_2","param_3"] print("Encoding :",categorical) # Encoder:
random_line_split
avito-lightgbm-with-ridge-feature-1.py
#Initially forked from Bojan's kernel here: https://www.kaggle.com/tunguz/bow-meta-text-and-dense-features-lb-0-2242/code #improvement using kernel from Nick Brook's kernel here: https://www.kaggle.com/nicapotato/bow-meta-text-and-dense-features-lgbm #Used oof method from Faron's kernel here: https://www.kaggle.com/m...
da x: x[col_name] ##I added to the max_features of the description. It did not change my score much but it may be worth investigating vectorizer = FeatureUnion([ ('description',TfidfVectorizer( ngram_range=(1, 2), max_features=17000, **tfidf_para, preproces...
rn lamb
identifier_name
avito-lightgbm-with-ridge-feature-1.py
#Initially forked from Bojan's kernel here: https://www.kaggle.com/tunguz/bow-meta-text-and-dense-features-lb-0-2242/code #improvement using kernel from Nick Brook's kernel here: https://www.kaggle.com/nicapotato/bow-meta-text-and-dense-features-lgbm #Used oof method from Faron's kernel here: https://www.kaggle.com/m...
Stage") training = pd.read_csv('../input/train.csv', index_col = "item_id", parse_dates = ["activation_date"]) traindex = training.index testing = pd.read_csv('../input/test.csv', index_col = "item_id", parse_dates = ["activation_date"]) testdex = testing.index ntrain = training.shape[0] ntest = testing.shape[0...
) return np.sqrt(np.mean(np.power((y - y0), 2))) print("\nData Load
identifier_body
uiLibFlexbox.go
package framework import ( "fmt" "sort" "github.com/CCDirectLink/CCUpdaterUI/frenyard" ) // Implements a highly limited subset of flexbox to be extended to full support as-needed. // FlexboxWrapMode describes a type of wrapping mode for Flexbox containers. type FlexboxWrapMode uint8 // FlexboxWrapModeNone disal...
func (slot fyFlexboxRow) fyCalcBasis(cross int32, vertical bool) int32 { return slot.fyMainCrossSizeForMainCrossLimits(frenyard.Vec2i{X: frenyard.SizeUnlimited, Y: cross}, vertical, false).X } func (slot fyFlexboxRow) fyGetOrder() int { return 0 } func (slot fyFlexboxRow) fyRespectMinimumSize() bool { return false }...
random_line_split
uiLibFlexbox.go
package framework import ( "fmt" "sort" "github.com/CCDirectLink/CCUpdaterUI/frenyard" ) // Implements a highly limited subset of flexbox to be extended to full support as-needed. // FlexboxWrapMode describes a type of wrapping mode for Flexbox containers. type FlexboxWrapMode uint8 // FlexboxWrapModeNone disal...
return frenyard.Vec2i{X: maximumMain, Y: presentAreaCross} } func (slot fyFlexboxRow) fyCalcBasis(cross int32, vertical bool) int32 { return slot.fyMainCrossSizeForMainCrossLimits(frenyard.Vec2i{X: frenyard.SizeUnlimited, Y: cross}, vertical, false).X } func (slot fyFlexboxRow) fyGetOrder() int { return 0 } func (s...
{ fmt.Print(" }") }
conditional_block
uiLibFlexbox.go
package framework import ( "fmt" "sort" "github.com/CCDirectLink/CCUpdaterUI/frenyard" ) // Implements a highly limited subset of flexbox to be extended to full support as-needed. // FlexboxWrapMode describes a type of wrapping mode for Flexbox containers. type FlexboxWrapMode uint8 // FlexboxWrapModeNone disal...
() int { return len(sc.slots) } func (sc fyFlexboxSortingCollection) Less(i int, j int) bool { order1 := sc.slots[i].fyGetOrder() order2 := sc.slots[j].fyGetOrder() // Order1 != order2? if order1 < order2 { return true } if order1 > order2 { return false } // No, they're equal. Sort by original index. if ...
Len
identifier_name
uiLibFlexbox.go
package framework import ( "fmt" "sort" "github.com/CCDirectLink/CCUpdaterUI/frenyard" ) // Implements a highly limited subset of flexbox to be extended to full support as-needed. // FlexboxWrapMode describes a type of wrapping mode for Flexbox containers. type FlexboxWrapMode uint8 // FlexboxWrapModeNone disal...
func fyFlexboxSolveLayout(details FlexboxContainer, limits frenyard.Vec2i) []frenyard.Area2i { // Stage 1. Element order pre-processing (DirReverse) slots := make([]fyFlexboxSlotlike, len(details.Slots)) originalToDisplayIndices := make([]int, len(details.Slots)) displayToOriginalIndices := make([]int, len(detail...
{ backup := sc.slots[i] backup2 := sc.originalToDisplayIndices[i] backup3 := sc.displayToOriginalIndices[i] sc.slots[i] = sc.slots[j] sc.originalToDisplayIndices[i] = sc.originalToDisplayIndices[j] sc.displayToOriginalIndices[i] = sc.displayToOriginalIndices[j] sc.slots[j] = backup sc.originalToDisplayIndices...
identifier_body
typegenAutoConfig.ts
import { GraphQLNamedType, GraphQLSchema, isOutputType } from 'graphql' import type { TypegenInfo } from './builder' import type { TypingImport } from './definitions/_types' import { TYPEGEN_HEADER } from './lang' import { nodeImports } from './node' import { getOwnPackage, log, objValues, relativePathTo, typeScriptFil...
} const forceImports = new Set( objValues(sourceTypeMap) .concat(typeof contextType === 'string' ? contextType || '' : '') .map((t) => { const match = t.match(/^(\w+)\./) return match ? match[1] : null }) .filter((f) => f) ) skipTypes.forEach((...
const importsMap: Record<string, [string, boolean]> = {} const sourceTypeMap: Record<string, string> = { ...SCALAR_TYPES, ..._sourceTypeMap,
random_line_split
typegenAutoConfig.ts
import { GraphQLNamedType, GraphQLSchema, isOutputType } from 'graphql' import type { TypegenInfo } from './builder' import type { TypingImport } from './definitions/_types' import { TYPEGEN_HEADER } from './lang' import { nodeImports } from './node' import { getOwnPackage, log, objValues, relativePathTo, typeScriptFil...
} }) if (forceImports.size > 0) { console.error(`Missing required typegen import: ${Array.from(forceImports)}`) } const imports: string[] = [] Object.keys(importsMap) .sort() .forEach((alias) => { const [importPath, glob] = importsMap[alias] const safeImpo...
{ const typeSource = typeSources[i] if (!typeSource) { continue } // If we've specified an array of "onlyTypes" to match ensure the // `typeName` falls within that list. if (typeSource.onlyTypes) { if ( !typeSource.onlyTyp...
conditional_block
typegenAutoConfig.ts
import { GraphQLNamedType, GraphQLSchema, isOutputType } from 'graphql' import type { TypegenInfo } from './builder' import type { TypingImport } from './definitions/_types' import { TYPEGEN_HEADER } from './lang' import { nodeImports } from './node' import { getOwnPackage, log, objValues, relativePathTo, typeScriptFil...
function findTypingForFile(absolutePath: string, pathOrModule: string) { // First try to find the "d.ts" adjacent to the file try { const typeDefPath = absolutePath.replace(nodeImports().path.extname(absolutePath), '.d.ts') require.resolve(typeDefPath) return typeDefPath } catch (e) { console.er...
{ return async (schema: GraphQLSchema, outputPath: string): Promise<TypegenInfo> => { const { headers, skipTypes = ['Query', 'Mutation', 'Subscription'], mapping: _sourceTypeMap, debug, } = options const typeMap = schema.getTypeMap() const typesToIgnore = new Set<string>() ...
identifier_body
typegenAutoConfig.ts
import { GraphQLNamedType, GraphQLSchema, isOutputType } from 'graphql' import type { TypegenInfo } from './builder' import type { TypingImport } from './definitions/_types' import { TYPEGEN_HEADER } from './lang' import { nodeImports } from './node' import { getOwnPackage, log, objValues, relativePathTo, typeScriptFil...
(options: SourceTypesConfigOptions, contextType: TypingImport | undefined) { return async (schema: GraphQLSchema, outputPath: string): Promise<TypegenInfo> => { const { headers, skipTypes = ['Query', 'Mutation', 'Subscription'], mapping: _sourceTypeMap, debug, } = options const ty...
typegenAutoConfig
identifier_name
csbref.go
package main import ( "bufio" "fmt" "math" "math/rand" "os" "strconv" "strings" "time" ) //GAME CONSTANTS const podRSQ = 800 * 800 const cpRSQ = 600 * 600 const podCount = 4 const minImpulse = 120 const frictionVal = 0.85 const checkpointGenerationGap = 30 //MATH CONSTANTS const fullCircle = (2 * math.Pi) co...
ob.s.x += -impulse.x * m2 ob.s.y += -impulse.y * m2 if dd <= 800 { dd -= 800 oa.p.x += (normal.x * -(-dd/2 + EPSILON)) oa.p.y += (normal.y * -(-dd/2 + EPSILON)) ob.p.x += (normal.x * (-dd/2 + EPSILON)) ob.p.y += (normal.y * (-dd/2 + EPSILON)) } } func getAngle(start point, end point) float64 { dx := (e...
impulse := normal impulse.x *= -force impulse.y *= -force oa.s.x += impulse.x * m1 oa.s.y += impulse.y * m1
random_line_split
csbref.go
package main import ( "bufio" "fmt" "math" "math/rand" "os" "strconv" "strings" "time" ) //GAME CONSTANTS const podRSQ = 800 * 800 const cpRSQ = 600 * 600 const podCount = 4 const minImpulse = 120 const frictionVal = 0.85 const checkpointGenerationGap = 30 //MATH CONSTANTS const fullCircle = (2 * math.Pi) co...
} func getAngle(start point, end point) float64 { dx := (end.x - start.x) dy := (end.y - start.y) a := (math.Atan2(dy, dx)) return a } func distance2(p1 point, p2 point) distanceSqType { x := distanceSqType(p2.x - p1.x) x = x * x y := distanceSqType(p2.y - p1.y) y = y * y return x + y } func distance(p1 p...
{ dd -= 800 oa.p.x += (normal.x * -(-dd/2 + EPSILON)) oa.p.y += (normal.y * -(-dd/2 + EPSILON)) ob.p.x += (normal.x * (-dd/2 + EPSILON)) ob.p.y += (normal.y * (-dd/2 + EPSILON)) }
conditional_block
csbref.go
package main import ( "bufio" "fmt" "math" "math/rand" "os" "strconv" "strings" "time" ) //GAME CONSTANTS const podRSQ = 800 * 800 const cpRSQ = 600 * 600 const podCount = 4 const minImpulse = 120 const frictionVal = 0.85 const checkpointGenerationGap = 30 //MATH CONSTANTS const fullCircle = (2 * math.Pi) co...
func outputSetup(m gameMap, players int, laps int) { for player := 0; player < players; player++ { fmt.Printf("###Input %d\n", player) fmt.Println(laps) fmt.Println(len(m)) for _, v := range m { fmt.Println(v.x, v.y) } } } func givePlayerOutput(g *game, player int, m gameMap) { pods := [4]int{0, 1, 2...
{ pm := [2]playerMove{} valid := true fmt.Printf("###Output %d 2\n", player) for i := range pm { if scanner.Scan() == false { os.Exit(0) } var thrust string fmt.Sscanf(scanner.Text(), "%f %f %s\n", &pm[i].target.x, &pm[i].target.y, &thrust) pm[i].thrust = 0 switch thrust { case "SHIELD": pm[i]....
identifier_body
csbref.go
package main import ( "bufio" "fmt" "math" "math/rand" "os" "strconv" "strings" "time" ) //GAME CONSTANTS const podRSQ = 800 * 800 const cpRSQ = 600 * 600 const podCount = 4 const minImpulse = 120 const frictionVal = 0.85 const checkpointGenerationGap = 30 //MATH CONSTANTS const fullCircle = (2 * math.Pi) co...
(m gameMap, players int, laps int) { for player := 0; player < players; player++ { fmt.Printf("###Input %d\n", player) fmt.Println(laps) fmt.Println(len(m)) for _, v := range m { fmt.Println(v.x, v.y) } } } func givePlayerOutput(g *game, player int, m gameMap) { pods := [4]int{0, 1, 2, 3} if player ==...
outputSetup
identifier_name
mod.rs
// Buttplug Rust Source Code File - See https://buttplug.io for more info. // // Copyright 2016-2019 Nonpolynomial Labs LLC. All rights reserved. // // Licensed under the BSD 3-Clause license. See LICENSE file in the project root // for full license information. //! Handling of communication with Buttplug Server. pub ...
(&self) -> Sender<ButtplugRemoteClientConnectorMessage> { self.remote_send.clone() } pub async fn send( &mut self, msg: &ButtplugMessageUnion, state: &ButtplugClientMessageStateShared, ) { self.internal_send.send((msg.clone(), state.clone())).await; } pub as...
get_remote_send
identifier_name
mod.rs
// Buttplug Rust Source Code File - See https://buttplug.io for more info. // // Copyright 2016-2019 Nonpolynomial Labs LLC. All rights reserved. // // Licensed under the BSD 3-Clause license. See LICENSE file in the project root // for full license information. //! Handling of communication with Buttplug Server. pub ...
else { panic!("Can't send message yet!"); } } } } } } }
{ remote_sender.send(buttplug_fut_msg.0.clone()); }
conditional_block
mod.rs
// Buttplug Rust Source Code File - See https://buttplug.io for more info. // // Copyright 2016-2019 Nonpolynomial Labs LLC. All rights reserved. // // Licensed under the BSD 3-Clause license. See LICENSE file in the project root // for full license information. //! Handling of communication with Buttplug Server. pub ...
// We use two Options instead of an enum because we may never // get anything. let mut stream_return: StreamValue = async { match remote_recv.next().await { Some(msg) => StreamValue::Incoming(msg), None =...
loop {
random_line_split
mod.rs
// Buttplug Rust Source Code File - See https://buttplug.io for more info. // // Copyright 2016-2019 Nonpolynomial Labs LLC. All rights reserved. // // Licensed under the BSD 3-Clause license. See LICENSE file in the project root // for full license information. //! Handling of communication with Buttplug Server. pub ...
}
{ // Set up a way to get futures in and out of the sorter, which will live // in our connector task. let event_send = self.event_send.take().unwrap(); // Remove the receivers we need to move into the task. let mut remote_recv = self.remote_recv.take().unwrap(); let mut i...
identifier_body
main.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // 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 r...
; // To allow multiple instances of Habitat application in Kubernetes, // random suffix in metadata_name is needed. let metadata_name = format!( "{}-{}{}", pkg_ident.name, rand::thread_rng() .gen_ascii_chars() .filter(|c| c.is_lowercase() || c.is_numeric()) ...
{ PackageIdent::from_str(pkg_ident_str)? }
conditional_block
main.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // 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 r...
(ui: &mut UI) -> Result<()> { let m = cli().get_matches(); debug!("clap cli args: {:?}", m); if !m.is_present("NO_DOCKER_IMAGE") { gen_docker_img(ui, &m)?; } gen_k8s_manifest(ui, &m) } fn gen_docker_img(ui: &mut UI, matches: &clap::ArgMatches) -> Result<()> { let default_channel = chan...
start
identifier_name