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
nmap.py
except FileNotFoundError: pass def import_nmap(result, tag, check_function=all_hosts, import_services=False): """ Imports the given nmap result. """ host_search = HostSearch(arguments=False) service_search = ServiceSearch()
parser = NmapParser() report = parser.parse_fromstring(result) imported_hosts = 0 imported_services = 0 for nmap_host in report.hosts: if check_function(nmap_host): imported_hosts += 1 host = host_search.id_to_object(nmap_host.address) host.status = nmap_h...
random_line_split
nmap.py
except FileNotFoundError: pass def import_nmap(result, tag, check_function=all_hosts, import_services=False): """ Imports the given nmap result. """ host_search = HostSearch(arguments=False) service_search = ServiceSearch() parser = NmapParser() report = parser.parse_froms...
(): """ Scans available smb services in the database for smb signing and ms17-010. """ service_search = ServiceSearch() services = service_search.get_services(ports=['445'], tags=['!smb_vulnscan'], up=True) services = [service for service in services] service_dict = {} for service in...
nmap_smb_vulnscan
identifier_name
nmap.py
map_host.hostnames: return True return False def include_up_hosts(nmap_host): """ Includes only hosts that have the status 'up' """ if nmap_host.status == 'up': return True return False def nmap(nmap_args, ips): """ Start an nmap process with the given args on...
for script_result in nmap_host.scripts_results: script_result = script_result.get('elements', {}) host = host_dict[str(nmap_host.address)] if 'fqdn' in script_result: host.hostname.append(script_result['fqdn']) if 'os' in script_result...
conditional_block
nmap.py
except FileNotFoundError: pass def import_nmap(result, tag, check_function=all_hosts, import_services=False): """ Imports the given nmap result. """ host_search = HostSearch(arguments=False) service_search = ServiceSearch() parser = NmapParser() report = parser.pars...
def include_up_hosts(nmap_host): """ Includes only hosts that have the status 'up' """ if nmap_host.status == 'up': return True return False def nmap(nmap_args, ips): """ Start an nmap process with the given args on the given ips. """ config = Config() argume...
""" Function to filter out hosts with hostnames """ if nmap_host.hostnames: return True return False
identifier_body
tool.py
else: sec = str(se) yymmdd = yy+mm+dd hhmmss = hour+mini+sec return yymmdd, hhmmss #------------------------------------------------------------ def detection(name, ra, dec, time, location): import numpy as np import os, glob, sys from astropy import units as u from astropy.time import Time from astro...
sec = '0'+str(se)
conditional_block
tool.py
ERROR: type should be large_string, got "\thttps://cpuu.postype.com/post/23066\n\tCode reference\n\thttps://kimdoky.github.io/python/2017/07/21/smtplib_email.html\n\tFile attach\n\thttps://brunch.co.kr/@jk-lab/31\n\t'''\n\timport smtplib\n\tfrom email.mime.text import MIMEText\n\timport codecs\n\temail_text = codecs.open(filename, 'rb', 'utf-8')\n\tmsg = MIMEText(email_text.read())\n\temail_text.close()\n\tmsg['Subject']\t= subject\n\tmsg['From']\t\t= sendID\n\tsmtp_gmail\t\t= smtplib.SMTP_SSL('smtp.gmail.com', 465)\n\tsmtp_gmail.login(sendID, sendPW)\n\tsmtp_gmail.sendmail(sendID, reciver, msg.as_string())\n\tsmtp_gmail.quit()\n\tcomment\t= 'Send '+filename+'\\n'+'From '+sendID+' To '+reciver; print(comment)\n#------------------------------------------------------------\ndef send_gmail(subject, contents, fromID, fromPW, toIDs, ccIDs=None, path=None):\n\t'''\n\tSEND GMAIL\n\tSecurity reference\n\thttps://cpuu.postype.com/post/23066\n\tCode reference\n\thttps://kimdoky.github.io/python/2017/07/21/smtplib_email.html\n\tFile attach\n\thttps://brunch.co.kr/@jk-lab/31\n\t'''\n\timport os\n\timport smtplib\n\tfrom email.mime.base import MIMEBase\n\tfrom email.mime.text import MIMEText\n\tfrom email.mime.multipart import MIMEMultipart\n\tfrom email.header import Header \n\t#msg\t\t= MIMEBase('mixed')\n\t#msg\t\t= MIMEText(contents, 'plain', 'utf-8')\n\tmsg\t\t= MIMEMultipart()\n\tmsg['Subject']\t= Header(s=subject, charset=\"utf-8\")\n\tmsg['From']\t\t= fromID\n\tmsg['To']\t\t= toIDs\n\tif ccIDs != None:\n\t\tmsg['Cc']\t\t= ccIDs\n\tmsg.attach(MIMEText(contents, 'plain', 'utf-8'))\n\t#\tATTACH TEXT FILE ON MAIL\n\tif path != None:\n\t\tif type(path) != list:\n\t\t\tfilelist\t= []\n\t\t\tfilelist.append(path)\n\t\telse:\n\t\t\tfilelist\t= path\n\n\t\tfor file in filelist:\n\t\t\tpart\t= MIMEBase(\"application\", \"octet-stream\")\n\t\t\tpart.set_payload(open(file, 'rb').read())\n\t\t\tpart.add_header(\t'Content-Disposition',\n\t\t\t\t\t\t\t\t'attachment; filename=\"%s\"'% os.path.basename(file))\n\t\t\tmsg.attach(part)\n\t\n\n\n\t#\tACCESS TO GMAIL & SEND MAIL\n\tsmtp_gmail\t\t= smtplib.SMTP_SSL('smtp.gmail.com', 465)\n\tsmtp_gmail.login(fromID, fromPW)\n\tsmtp_gmail.sendmail(msg[\"From\"], msg[\"To\"].split(\",\") + msg[\"Cc\"].split(\",\"), msg.as_string())\n\tsmtp_gmail.quit()\n\tcomment\t= 'Send '+str(path)+'\\nFrom\\t'+fromID+'\\nTo'; print(comment); print(toIDs)\n#------------------------------------------------------------\ndef abs2app(mag, magerr, gwdist, gwdiststd):\n\timport numpy as np\n\tapp\t\t= 5*np.log10(gwdist)-5+mag\n\tapperr\t= 5*gwdiststd/(gwdist*np.log(10))\n\treturn app, apperr\n#------------------------------------------------------------\ndef GW170817_like(gwdist, gwdiststd):\n\timport numpy as np\n\tm0\t\t= 17.476\t#\t[AB] in i-band (t0+10h)\n\tm0err\t= 0.018\t\n\tdist0\t= 38.4\t\t#\t[MPC]\tIm et al. 2017\n\tdist0err= 8.9\n\tm\t\t= m0+5.*np.log10(gwdist/dist0)\n\tmerr\t= np.sqrt( (m0err)**2 + ((5.*gwdiststd)/(gwdist*np.log(10)))**2 + ((5.*dist0err)/(dist0*np.log(10)))**2 )\n\treturn m, merr\n#------------------------------------------------------------\ndef func_linear(a, x, scaling=[0, 0]):\n\txpt, ypt= scaling[0], scaling[1]\n\tydel\t= ypt - (-1*a*xpt)\n\treturn -1*a*x + ydel\n#------------------------------------------------------------\ndef calc_app(mag, magerr, gwdist0, gwdiststd0, gwdist1, gwdiststd1):\n\timport numpy as np\n\tapp\t\t= mag+5*np.log10(gwdist1/gwdist0)\n\tapperr\t= np.sqrt( (magerr)**2 + ((5*gwdiststd1)/(np.log(5)*gwdist1))**2 + ((5*gwdiststd0)/(np.log(5)*gwdist0))**2 )\n\treturn app, apperr\n#------------------------------------------------------------\ndef ds9regmaker(filename, name, ra, dec):\n\timport os,sys\n\timport string\n\tfrom astropy.io import ascii \n\timport numpy as np\n\timport math\n\t'''\n\tracol\t\t= 'ALPHA_J2000'\n\tdeccol\t\t= 'DELTA_J2000'\n\tname\t\t= 'NUMBER'\n\tintbl\t\t= ascii.read(filename)\n\t'''\n\tradius\t= \"\"\" 5\" \"\"\"\n\tcolor\t= \"green\"\n\tf\t\t= open(filename, 'w')\n\n\thead1\t= \"# Region file format: DS9 version 4.1\\n\"\n\thead2\t= \"\"\"global color=green dashlist=8 3 width=1 font=\"helvetica 10 normal roman\" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\\n\"\"\"\n\thead3\t= \"fk5\\n\"\n\n\tf.write(head1)\n\tf.write(head2)\n\tf.write(head3)\n\n\tfor n in range(len(ra)):\n\t\tbody=\"circle(\"+str(ra[n])+\",\"+str(dec[n])+\",\"+radius+\") # color=\"+color+\" text={\"+str(name[n])+\"}\\n\"\t\n\t\tf.write(body)\n\tf.close()\n#------------------------------------------------------------\ndef rtsmaker(observatory, headname, save_path, obspath, catpath, start, end, altlimit=30., moonseperation=40., sunlimit='-18', numlimit=100):\n\timport pytz\n\timport jdcal\n\timport ephem\n\t#from numpy import *\n\timport numpy as np\n\timport os, sys\n\timport string\n\timport datetime\n\timport astropy.units as u\n\tfrom astropy.io import ascii\n\timport mskpy.observing as obs\n\timport astropy.coordinates as coord\n\tfrom astropy import units as u\n\tfrom astropy.coordinates import SkyCoord\n\n\t#------------------------------------------------------------#\n\t#\tINPUT SAMPLE\n\t#------------------------------------------------------------#\n\t'''\n\tobservatory\t\t= 'SAO'\n\tsave_path\t\t= './'\n\tobspath\t\t\t= \"/home/gw/Research/observatory.txt\"\n\tcatpath\t\t\t= 'MS181101ab_Preliminary-all_candidates.txt'\n\tstart\t\t\t= '2019/04/17'\n\tend\t\t\t\t= '2019/04/19'\n\t#altitute limit and moon seperation, moon serperation is a little bit close (2~3 deg)\n\tnumlimit\t\t= 100\n\taltlimit\t\t= 30.\n\tmoonseperation\t= 40.\n\tsunlimit\t\t= '-18'\n\t'''\n\t#------------------------------------------------------------#\n\t#\tOBSERVATORY INFO.\n\t#------------------------------------------------------------#\n\tobsinfo\t\t\t= ascii.read(obspath)\n\tobsname \t= np.copy(obsinfo['name'])\n\tobsindex\t\t= np.where(obsname == observatory)[0]\n\tobslat\t\t\t= (np.copy(obsinfo['latitude(N+)'])[obsindex])[0]\n\tobslon\t\t\t= (np.copy(obsinfo['longitude(E+)'])[obsindex])[0]\n\tobsalt\t\t\t= (np.copy(obsinfo['altitude'])[obsindex])[0]\n\tobstz\t\t\t= (np.copy(obsinfo['timezone'])[obsindex])[0]\n\ttz\t\t\t\t= pytz.timezone(obstz)\n\t#------------------------------------------------------------#\n\tobserv\t\t\t= ephem.Observer()\n\tobserv.lat\t\t= str(obslat)\n\tobserv.lon\t\t= str(obslon)\n\tobserv.elevation= obsalt\n\tobserv.horizon\t= sunlimit\n\t#------------------------------------------------------------#\n\t#objects from catalog file\n\ttdata\t\t\t= ascii.read(catpath)\n\tobjname\t\t\t= tdata['name']\n\tra\t\t\t\t= tdata['ra']\n\tdec\t\t\t\t= tdata['dec']\n\tprior\t\t\t= tdata['sort']\n\trank\t\t\t= tdata['rank']\t\t\t\n\tdist\t\t\t= tdata['dist']\n\n\tRA\t\t\t\t= coord.Angle(ra, unit = u.deg)\n\tDec\t\t\t\t= coord.Angle(dec, unit = u.deg)\n\n\tradd\t\t\t= RA.value\n\trad\t\t\t\t= RA.hour\n\tdecd\t\t\t= Dec.value\n\tdecdd\t\t\t= Dec.degree\n\n\t#angular distance calculation\n\tdef angsep(ra1deg, dec1deg, ra2deg,"
#------------------------------------------------------------ def sendmail(filename, subject, sendID, sendPW, reciver): ''' Security reference
random_line_split
tool.py
(): ''' CONVERT 'TIME' TO YYMMDD, HHMMSS FORM. INPUT : NONE OUTPUT : STRIG FORM OF 'YYMMDD', 'HHMMSS' ''' import numpy as np import time now = time.gmtime(time.time()) y, m, d = now.tm_year, now.tm_mon, now.tm_mday ho, mi, se = now.tm_hour, now.tm_min, now.tm_sec yy = str(y)[2:] if len(str(m)) < 2:...
timename
identifier_name
tool.py
') msg = MIMEText(email_text.read()) email_text.close() msg['Subject'] = subject msg['From'] = sendID smtp_gmail = smtplib.SMTP_SSL('smtp.gmail.com', 465) smtp_gmail.login(sendID, sendPW) smtp_gmail.sendmail(sendID, reciver, msg.as_string()) smtp_gmail.quit() comment = 'Send '+filename+'\n'+'From '+sendID+' ...
save_path = './' obspath = "/home/gw/Research/observatory.txt" catpath = 'MS181101ab_Preliminary-all_candidates.txt' start = '2019/04/17' end = '2019/04/19' #altitute limit and moon seperation, moon serperation is a little bit close (2~3 deg) numlimit = 100 altlimit = 30. moonseperation = 40. sunl...
import pytz import jdcal import ephem #from numpy import * import numpy as np import os, sys import string import datetime import astropy.units as u from astropy.io import ascii import mskpy.observing as obs import astropy.coordinates as coord from astropy import units as u from astropy.coordinates import ...
identifier_body
retina_loss.py
(image_shape,stride): ''' transfor one fmap coords to orig coords Args featurn [batch_size,h,w,c] stride int Returns coords [n,2] ''' h,w= image_shape shifts_x = torch.arange(0, w * stride, stride, dtype=torch.float32) shifts_y = torch.arange(0, h * stride, stride, dtype=torc...
coords_fmap2orig
identifier_name
retina_loss.py
W) return shift_anchor: (H*W*num,4) """ ori_coords = coords_fmap2orig(image_shape, stride) # (H*W, 4) 4:(x,y,x,y) ori_coords = ori_coords.to(device=anchors.device) shift_anchor = ori_coords[:, None, :] + anchors[None, :, :] return shift_anchor.reshape(-1, 4) def calc...
super(LOSS, self).__init__() self.reg_mode = reg_mode
identifier_body
retina_loss.py
areas = anchors[:, 2] * anchors[:, 3] # (9,) # fix the ratios of w, h anchors[:, 2] = np.sqrt(areas / np.repeat(ratios, len(scales))) # (9,) anchors[:, 3] = anchors[:, 2] * np.repeat(ratios, len(scales)) # (9,) # transfrom from(0 ,0, w, h ) to ( x1, y1, x2, y2) ancho...
reg_loss = torch.tensor(0).float().cuda() else: reg_loss = torch.tensor(0).float() return reg_loss def compute_giou_loss(boxes1, boxes2): """ boxes1 :(N,4) (x1,y1,x2,y2) boxes2: (N,4) (x1,y1,x2,y2) """ x1y1 = torch.max(boxes1[:, :2], boxes2[:, :2]) x2y2 = ...
preds_boxes = torch.stack([pred_x1,pred_y1,pred_x2,pred_y2], dim=0).t() #(num_pos,4) reg_loss = compute_giou_loss(gt_boxes, preds_boxes) else: if torch.cuda.is_available():
random_line_split
retina_loss.py
areas = anchors[:, 2] * anchors[:, 3] # (9,) # fix the ratios of w, h anchors[:, 2] = np.sqrt(areas / np.repeat(ratios, len(scales))) # (9,) anchors[:, 3] = anchors[:, 2] * np.repeat(ratios, len(scales)) # (9,) # transfrom from(0 ,0, w, h ) to ( x1, y1, x2, y2) ancho...
else: reg_loss = torch.tensor(0).float() return reg_loss def compute_giou_loss(boxes1, boxes2): """ boxes1 :(N,4) (x1,y1,x2,y2) boxes2: (N,4) (x1,y1,x2,y2) """ x1y1 = torch.max(boxes1[:, :2], boxes2[:, :2]) x2y2 = torch.min(boxes1[:, 2:], boxes2[:, 2:]) wh = torc...
reg_loss = torch.tensor(0).float().cuda()
conditional_block
preprocess_lidc1.py
() def threadsafe_generator(f): """A decorator that takes a generator function and makes it thread-safe. """ def g(*a, **kw): return threadsafe_iter(f(*a, **kw)) return g def plot(vol,x,y,z): corner1 = np.array([x,y,z])-np.array(CROP_SHAPE)/2 corner2 = corner1+np.array(CROP_SHAPE) ...
cluster_group=[] for ann in cluster: diameter = ann.estimate_diameter() features = ann.feature_vals() c = ann.centroid() c[:2]=c[:2]*np.array(spacing[:2]) c[2] = c[2]-z0 c = c/np.array(NEW_SPACING) b = ann.bbox() ...
for cluster in clusters:
random_line_split
preprocess_lidc1.py
() def threadsafe_generator(f): """A decorator that takes a generator function and makes it thread-safe. """ def g(*a, **kw): return threadsafe_iter(f(*a, **kw)) return g def plot(vol,x,y,z): corner1 = np.array([x,y,z])-np.array(CROP_SHAPE)/2 corner2 = corner1+np.array(CROP_SHAPE) ...
def shift_radius(shift): r = 100 while r > shift: v = np.random.uniform(-shift,high=shift,size=(3,)) r = np.linalg.norm(v) vox_shift = (v/np.array(NEW_SPACING)).astype(int) return vox_shift def find_nodule(annotation,min_agreement): good_clusters = [cluster for cluster in annotation if len(clus...
Focus_radius = 30 # mm dist = np.linalg.norm( (np.array(pos)-np.array(centroid))*np.array(NEW_SPACING))/Focus_radius return max(1-dist,0)
identifier_body
preprocess_lidc1.py
() def threadsafe_generator(f): """A decorator that takes a generator function and makes it thread-safe. """ def g(*a, **kw): return threadsafe_iter(f(*a, **kw)) return g def plot(vol,x,y,z): corner1 = np.array([x,y,z])-np.array(CROP_SHAPE)/2 corner2 = corner1+np.array(CROP_SHAPE) ...
perm = range(len(annotations)) random.shuffle(perm) data = [data[i] for i in perm] annotations= [annotations[i] for i in perm] data=np.asarray(data) return data,annotations def soft_focus(pos,centroid): Focus_radius = 30 # mm dist = np.linalg.norm( (np.array(pos)-np.array(centroid))*n...
data.append(np.load(name)) annotation_file_name = '.'.join(name.split('.')[:-1])+'annotation.txt' with open(annotation_file_name,'r') as pickle_file: annotations.append(pickle.load(pickle_file))
conditional_block
preprocess_lidc1.py
() def threadsafe_generator(f): """A decorator that takes a generator function and makes it thread-safe. """ def g(*a, **kw): return threadsafe_iter(f(*a, **kw)) return g def plot(vol,x,y,z): corner1 = np.array([x,y,z])-np.array(CROP_SHAPE)/2 corner2 = corner1+np.array(CROP_SHAPE) ...
(shift): r = 100 while r > shift: v = np.random.uniform(-shift,high=shift,size=(3,)) r = np.linalg.norm(v) vox_shift = (v/np.array(NEW_SPACING)).astype(int) return vox_shift def find_nodule(annotation,min_agreement): good_clusters = [cluster for cluster in annotation if len(cluster)>=min_agreement...
shift_radius
identifier_name
kinematics.py
def tableread(filelist, start, frames, onlyinclude=''): """ Read a list of lists, from a Nexus CSV export, to extract vector data. Output is a dictionary of lists. Inputs:- filelist = the data start = the row number where data to be read starts frames = dict of Start and End fra...
""" thisfile = open(file) thisreader = csv.reader(thisfile) filelist = np.array(list(thisreader)) return filelist
random_line_split
kinematics.py
filewidth = len(filelist[start-2])-1 output = {} startframe = start - int(filelist[start][0]) + 1 for col in range(2,filewidth): # Name the datatype in each column if filelist[start-3][col]: tmp = filelist[start-3][col]+filelist[start-2][col] elif filelist[star...
if m % cut == 0 and m != 0: line[m] = 'del'
conditional_block
kinematics.py
frames = dict of Start and End frames for strides onlyinclude = optional argument, only columns where title includes this will be included """ filewidth = len(filelist[start-2])-1 output = {} startframe = start - int(filelist[start][0]) + 1 for col in range(2,filewidth): # Name t...
(array): """ Make numpy array rows the same length by shortening long ones. """ lengths = [len(x) for x in array] #shortindex = lengths.index(min(lengths)) shortest = min(lengths) for n in range(len(array)): line = array[n] if len(array[n]) != shortest: ...
arraycleaner
identifier_name
kinematics.py
frames = dict of Start and End frames for strides onlyinclude = optional argument, only columns where title includes this will be included """ filewidth = len(filelist[start-2])-1 output = {} startframe = start - int(filelist[start][0]) + 1 for col in range(2,filewidth): # Name t...
def arraycleaner(array): """ Make numpy array rows the same length by shortening long ones. """ lengths = [len(x) for x in array] #shortindex = lengths.index(min(lengths)) shortest = min(lengths) for n in range(len(array)): line = array[n] if len(array[n]) != sho...
""" Returns the minimum foot clearance in middle of swing in marked stride. Inputs: Toe marker Z (list), Start frame, foot off frame, end frame, start fraction of mid swing, end fraction of mid swing. Output: minimum clearance, frame it occurs at. """ swing = ToeZ[FootOff:EndFrame] ground ...
identifier_body
client.py
PILToWX(self, pil_image): #"convert a PIL imageto a wxImage" if pil_image.mode != 'RGB': # SetData() requires an RGB image pil_image = pil_image.convert('RGB') imageData = pil_image.tostring('raw', 'RGB') imageWx = wx.EmptyImage(pil_image.size[0], pil_image.size[1]) imageWx.SetData(imageData) return ima...
OnSaveConf, button1) self.Bind(wx.EVT_BUTTON, self.OnCancel, button2) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox3 = wx.BoxSizer(wx.HORIZONTAL) hbox4 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(ipLabel,flag=wx.LEFT,border=8) hbox1.Add(self.ipT...
identifier_body
client.py
.RIGHT|wx.EXPAND, border=10) vbox.Add((-1, 10)) hbox4.Add(button3,flag=wx.ALIGN_RIGHT|wx.RIGHT,border=10) #save hbox4.Add(button2,wx.RIGHT,border=10) #exit vbox.Add(hbox4,flag=wx.ALIGN_RIGHT|wx.RIGHT|wx.BOTTOM,border=10) #sizer.Add(button1, 0) #0่กจ็คบๆฏ”ไพ‹ #sizer.Add(button2, 3) #sizer.Add(button3, 5,wx.BOTTO...
text) fh.close() def On
conditional_block
client.py
a wxImage" if pil_image.mode != 'RGB': # SetData() requires an RGB image pil_image = pil_image.convert('RGB') imageData = pil_image.tostring('raw', 'RGB') imageWx = wx.EmptyImage(pil_image.size[0], pil_image.size[1]) imageWx.SetData(imageData) return imageWx #bitmap = wx.BitmapFromImage(image) def OnIc...
vbox.Add((-1, 50)) hbox4.Add(button1,flag=wx.LEFT,border=18)
random_line_split
client.py
=content.split('\n') for ln in lines: if ln.find('##<img src=') >=0: print ln pat=re.compile(r'##<img src="(.*?)"/>##') try: img_src=pat.findall(ln)[0] print 'find img_src:',img_src catalog=self.catalogText.GetValue().strip() url='http://'+self.host+'/dl?'+self.user+'/'+catalog+img_...
veConf,
identifier_name
ftp_manage.py
# print(request) msg = "ๅฝ“ๅ‰่ทฏๅพ„๏ผš%s" % self.current_path # self.conn.send(msg.encode('utf-8')) return msg.encode('utf-8') def mkdir(self, request): print(request) new_dir = request.split()[1] abs_path = os.path.join(settings.BaseDir, self.current_path) if...
ze": file_size } self.conn.send(pickle.dumps(res)) # ๆŽฅๆ”ถๅฎขๆˆท็ซฏๅผ€ๅง‹ไผ ่พ“็š„ๆŒ‡ไปค
conditional_block
ftp_manage.py
pickle.dump(user_info, user_obj) # pickle.dump() class FtpManage(): def __init__(self, conn): # ่ฏปๅ–ๆ•ฐๆฎๅบ“ # self.name = None self.conn = conn self.is_certified = False # ๆ˜ฏๅฆๅทฒ็ป่ฎค่ฏ self.current_path = None # ๅฝ“ๅ‰่ทฏๅพ„ # self.db_file = os.path.join(settings.db...
self.user_info = get_info(self.name) # print(self.user_info.__dict__) if self.user_info.password == password: self.is_certified = True self.current_path = self.user_info.current_path send_data['response']['msg'] = "่ฎค่ฏๆˆๅŠŸ๏ผ" el...
random_line_split
ftp_manage.py
pickle.dump(user_info, user_obj) # pickle.dump() class FtpManage(): def __init__(self, conn): # ่ฏปๅ–ๆ•ฐๆฎๅบ“ # self.name = None self.conn = conn self.is_certified = False # ๆ˜ฏๅฆๅทฒ็ป่ฎค่ฏ self.current_path = None # ๅฝ“ๅ‰่ทฏๅพ„ # self.db_file = os.path.join(settings.db, name)...
def pwd(self, request): # print(request) msg = "ๅฝ“ๅ‰่ทฏๅพ„๏ผš%s" % self.current_p ath # self.conn.send(msg.encode('utf-8')) return msg.encode('utf-8') def mkdir(self, request): print(request) new_dir = request.split()[1] abs_path = os.path.join(settings.BaseDir, ...
ame = request['name'] password = request['password'] send_data = {} send_data['action'] = 'login' send_data['response'] = {} if self.name in os.listdir(settings.db): self.user_info = get_info(self.name) # print(self.user_info.__dict__) if self....
identifier_body
ftp_manage.py
pickle.dump(user_info, user_obj) # pickle.dump() class
(): def __init__(self, conn): # ่ฏปๅ–ๆ•ฐๆฎๅบ“ # self.name = None self.conn = conn self.is_certified = False # ๆ˜ฏๅฆๅทฒ็ป่ฎค่ฏ self.current_path = None # ๅฝ“ๅ‰่ทฏๅพ„ # self.db_file = os.path.join(settings.db, name) self.db_file = None self.user_info = None # ็”จๆˆท็™ป้™† ...
FtpManage
identifier_name
rows.go
err != nil { return nil, err } return slice, nil } // CollectOneRow calls fn for the first row in rows and returns the result. If no rows are found returns an error where errors.Is(ErrNoRows) is true. // CollectOneRow is to CollectRows as QueryRow is to Query. func CollectOneRow[T any](rows Rows, fn RowToFunc[T]...
{ sf := dstElemType.Field(i) if sf.PkgPath != "" && !sf.Anonymous { // Field is unexported, skip it. continue } // Handle anoymous struct embedding, but do not try to handle embedded pointers. if sf.Anonymous && sf.Type.Kind() == reflect.Struct { scanTargets, err = rs.appendScanTargets(dstElemValue.F...
conditional_block
rows.go
pgconn.CommandTag, error) { defer rows.Close() for rows.Next() { err := rows.Scan(scans...) if err != nil { return pgconn.CommandTag{}, err } err = fn() if err != nil { return pgconn.CommandTag{}, err } } if err := rows.Err(); err != nil { return pgconn.CommandTag{}, err } return rows.Comm...
for i, desc := range fldDescs {
random_line_split
rows.go
make([]pgtype.ScanPlan, len(values)) rows.scanTypes = make([]reflect.Type, len(values)) for i := range dest { rows.scanPlans[i] = m.PlanScan(fieldDescriptions[i].DataTypeOID, fieldDescriptions[i].Format, dest[i]) rows.scanTypes[i] = reflect.TypeOf(dest[i]) } } for i, dst := range dest { if dst == nil ...
{ dst := rs.ptrToStruct dstValue := reflect.ValueOf(dst) if dstValue.Kind() != reflect.Ptr { return fmt.Errorf("dst not a pointer") } dstElemValue := dstValue.Elem() scanTargets := rs.appendScanTargets(dstElemValue, nil) if len(rows.RawValues()) > len(scanTargets) { return fmt.Errorf("got %d values, but ds...
identifier_body
rows.go
returned. Rows will be closed // when ForEachRow returns. func ForEachRow(rows Rows, scans []any, fn func() error) (pgconn.CommandTag, error) { defer rows.Close() for rows.Next() { err := rows.Scan(scans...) if err != nil { return pgconn.CommandTag{}, err } err = fn() if err != nil { return pgconn....
fieldPosByName
identifier_name
build.py
openssl' OPENSSL_OQS_BRANCH = 'OpenSSL_1_0_2-stable' OPENSSL_OQS_COMMIT = '01f211920aea41640c647f462e9d7c4c106e3240' OPENVPN_TGZ_NAME = '/tmp/openvpn-2.4.4.tar.gz' OPENVPN_GUI_TGZ_NAME = '/tmp/openvpn-gui-11.tar.gz' OPENVPN_REPO_DIRNAME = 'openvpn-2.4.4' OPENVPN_INSTALL_EXE_NAME = 'openvpn-install-2.4.4-I601.exe' OPEN...
cmd.append(repo_url) if local_name: cmd.append(local_name) run_command(cmd) if commit is not None: if local_name: os.chdir(local_name) else: print "git_clone with a commit ID only valid with a local_name" sys.exit(1) cmd = [...
cmd.extend(['--branch', branch])
conditional_block
build.py
' OPENSSL_OQS_BRANCH = 'OpenSSL_1_0_2-stable' OPENSSL_OQS_COMMIT = '01f211920aea41640c647f462e9d7c4c106e3240' OPENVPN_TGZ_NAME = '/tmp/openvpn-2.4.4.tar.gz' OPENVPN_GUI_TGZ_NAME = '/tmp/openvpn-gui-11.tar.gz' OPENVPN_REPO_DIRNAME = 'openvpn-2.4.4' OPENVPN_INSTALL_EXE_NAME = 'openvpn-install-2.4.4-I601.exe' OPENVPN_GUI...
If the error is for another reason it re-raises the error. Usage : ``shutil.rmtree(path, onerror=onerror)`` """ import stat if not os.access(path, os.W_OK): # Is the error an access error ? os.chmod(path, stat.S_IWUSR) func(path) else: raise def build_openvpn_...
random_line_split
build.py
' OPENSSL_OQS_BRANCH = 'OpenSSL_1_0_2-stable' OPENSSL_OQS_COMMIT = '01f211920aea41640c647f462e9d7c4c106e3240' OPENVPN_TGZ_NAME = '/tmp/openvpn-2.4.4.tar.gz' OPENVPN_GUI_TGZ_NAME = '/tmp/openvpn-gui-11.tar.gz' OPENVPN_REPO_DIRNAME = 'openvpn-2.4.4' OPENVPN_INSTALL_EXE_NAME = 'openvpn-install-2.4.4-I601.exe' OPENVPN_GUI...
(cmd): print '***** Running command: %s' % ' '.join(map(str,cmd)) p = subprocess.Popen(cmd) p.wait() # Clone a git repo, using the default name, in the CWD # If branch is specified, clone that branch def git_clone(repo_url, branch, local_name, commit=None): r = re.compile(".*/(.*)$") m = r.match(re...
run_command
identifier_name
build.py
' OPENSSL_OQS_BRANCH = 'OpenSSL_1_0_2-stable' OPENSSL_OQS_COMMIT = '01f211920aea41640c647f462e9d7c4c106e3240' OPENVPN_TGZ_NAME = '/tmp/openvpn-2.4.4.tar.gz' OPENVPN_GUI_TGZ_NAME = '/tmp/openvpn-gui-11.tar.gz' OPENVPN_REPO_DIRNAME = 'openvpn-2.4.4' OPENVPN_INSTALL_EXE_NAME = 'openvpn-install-2.4.4-I601.exe' OPENVPN_GUI...
# Start the x64 build os.chdir('..') os.chdir('openssl-oqs-win-x64') run_command(['perl', 'Configure', 'VC-WIN64A', 'no-asm', 'enable-static-engine']) run_command(['ms\\do_win64a.bat']) mycwd = os.getcwd() # Before running nmake, we have to run vcvarsall...
if platform.system() == 'Windows': # Create source trees for x86 and x64 # Note that there's no way to clean up one tree and re-use it for a different arch git_clone(OPENSSL_OQS_REPO, OPENSSL_OQS_BRANCH, 'openssl-oqs-win-x86', OPENSSL_OQS_COMMIT) shutil.copytree('openssl-oqs-win-x86', 'o...
identifier_body
utils.py
Indices.csv') VALIDATION_MASK_FILE_NAME = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_mask.csv') AUX = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_first.csv') META_VALIDATION_FILE_NAME = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_se...
(data, use_three_way): masked_data = np.copy(data) if use_three_way: mask_file = VALIDATION_MASK_FILE_NAME else: mask_file = VALIDATION_FILE_NAME mask_indices = get_indices_from_file(mask_file) for row_index, col_index in mask_indices: masked_data[row_index][col_index] = 0 ...
mask_validation
identifier_name
utils.py
/validationIndices.csv') VALIDATION_MASK_FILE_NAME = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_mask.csv') AUX = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_first.csv') META_VALIDATION_FILE_NAME = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validatio...
for i in range(reconstruction.shape[0]): stacked_ratings = [] for neighbor in neighbors[i]: stacked_ratings.append(reconstruction[neighbor]) stacked_ratings = np
similarities = ones - distances weights = np.square(np.square(similarities)) smoothed_data = np.zeros(reconstruction.shape) aggregated_neighbor_ratings = np.zeros(reconstruction.shape)
random_line_split
utils.py
Indices.csv') VALIDATION_MASK_FILE_NAME = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_mask.csv') AUX = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_first.csv') META_VALIDATION_FILE_NAME = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_se...
return indices_to_predict def write_ratings(predictions, submission_file): with open(submission_file, 'w') as file: file.write('Id,Prediction\n') for i, j, prediction in predictions: file.write('r%d_c%d,%f\n' % (i, j, prediction)) def reconstruction_to_predictions( reconst...
key, _ = line.split(",") row_string, col_string = key.split("_") i = int(row_string[1:]) - 1 j = int(col_string[1:]) - 1 indices_to_predict.append((i, j))
conditional_block
utils.py
Indices.csv') VALIDATION_MASK_FILE_NAME = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_mask.csv') AUX = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_first.csv') META_VALIDATION_FILE_NAME = os.path.join( ROOT_DIR, 'data/train_valid_80_10_10/validationIndices_se...
def clip(data): data[data > 5] = 5 data[data < 1] = 1 return data def ampute_reconstruction(reconstruction, data): observed_indices = get_observed_indices(data) for row_index, col_index in observed_indices: reconstruction[row_index][col_index] = data[row_index][col_index] def impute_by_a...
reconstruction_to_predictions( reconstruction, ROOT_DIR + 'data/meta_training_' + name + '_stacking' + datetime.now().strftime('%Y-%b-%d-%H-%M-%S') + '.csv', indices_to_predict=get_validation_indices(use_three_way=True)) reconstruction_to_predictions( reconstruction, ROOT_DIR + 'data...
identifier_body
Q_Learner.py
Q self.dueling = dueling self.perMemory = perMemory self.rendering = watch pass print ("POSSIBLE ACTIONS :", self.actions) if training: self.updates = 0 self.totalLoss = 0.0 self.countL = 0 self.minibatch = AgentSetting.minibatch self.replay_memorySize = AgentSetting.replay_memory self....
(self,sess,reloadM): self.env.reset(sess) if not reloadM: print ('Initializing my experience memory...') else: print('Restoring my experience memory (naive solution!)...') state = self.state_process.get_state(sess) done = False for v in tqdm(range(self.replay_strt_size)): if not reloadM: ...
fill_memory
identifier_name
Q_Learner.py
', dtype=tf.float32) #4- current state chosen action value self.actionBatchHolder = tf.placeholder(dtype=tf.uint8) self.chosenAction = tf.one_hot(indices=self.actionBatchHolder, depth=self.num_action, axis=-1, dtype=tf.float32, on_value=1.0, off_value=0.0) self.curState_qValueSe...
self.summaries(sess) break #end of episode
random_line_split
Q_Learner.py
self.replay_memorySize = AgentSetting.replay_memory self.t_net_update_freq = AgentSetting.t_net_update_freq self.discount_factor = AgentSetting.discount_factor self.update_freq = AgentSetting.update_freq self.momentum = AgentSetting.momentum self.e_greedy_init = AgentSetting.e_greedy_init self.e_...
self.totalLoss =0.0 self.countL = 0 self.totalReward = 0.0 self.countR = 0 self.updates = 0 self.startTime = time.time() self.env.reset(sess) state = self.state_process.get_state(sess) no_op = 0 for _ in itertools.count(): #take action action = self.behaviour_e_policy(state,sess) #step a...
identifier_body
Q_Learner.py
Q self.dueling = dueling self.perMemory = perMemory self.rendering = watch pass print ("POSSIBLE ACTIONS :", self.actions) if training: self.updates = 0 self.totalLoss = 0.0 self.countL = 0 self.minibatch = AgentSetting.minibatch self.replay_memorySize = AgentSetting.replay_memory self....
else: print('Restoring my experience memory (naive solution!)...') state = self.state_process.get_state(sess) done = False for v in tqdm(range(self.replay_strt_size)): if not reloadM: #select an action randomly action = self.env.takeRandomAction() else: action = self.behaviour_e_policy(...
print ('Initializing my experience memory...')
conditional_block
scripts.js
} // =================================================================== // Function to gather all of the search criteria and submit the page // =================================================================== function petSearch() { $('#sidebar .controls button').click(function () { var search = {}; ...
$me = $(this); if (!$me.hasClass('active')) { if ($('.faq .question.active').length > 0) { $('.faq .active').removeClass('active').next().hide(); } $me.addClass('active').next().slideDown(); ...
$i.on('click', function () {
random_line_split
scripts.js
} // =================================================================== // Function to gather all of the search criteria and submit the page // =================================================================== function petSearch() { $('#sidebar .controls button').click(function () { var search = {}; ...
() { // mobile menu clicks $('#burger').on('click', function () { $('#menu').toggleClass('open'); $('#burger').toggleClass('open'); $('html').toggleClass('scroll-lock'); }); } function popVideo(id) { $tar = $('#videobox'); $tar.addClass('on'); $str = '<div class="video-f...
menu
identifier_name
scripts.js
// =================================================================== // Function to gather all of the search criteria and submit the page // =================================================================== function petSearch() { $('#sidebar .controls button').click(function () { var search = {}; ...
// mobile menu function menu() { // mobile menu clicks $('#burger').on('click', function () { $('#menu').toggleClass('open'); $('#burger').toggleClass('open'); $('html').toggleClass('scroll-lock'); }); } function popVideo(id) { $tar = $('#videobox'); $tar.addClass('on'); ...
{ var $frame = $('iframe'); var width = $('.video').width(); $frame.attr('width', width); $frame.attr('height', (width * 3 / 5)); }
identifier_body
scripts.js
} // =================================================================== // Function to gather all of the search criteria and submit the page // =================================================================== function petSearch() { $('#sidebar .controls button').click(function () { var search = {}; ...
else { url += '&' + key + '=' + value; } }); // Use "search" variable to record events if desired window.location = DOMAIN + '/adoption/' + url; }); } // =================================================================== // Function to initialize Featured Pe...
{ url = '?' + key + '=' + value; }
conditional_block
queued.rs
permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT...
(&self) -> Box<dyn PipelineHook> { Box::new(self.clone()) } fn get_pipelined_cap(&self, ops: &[PipelineOp]) -> Box<dyn ClientHook> { self.get_pipelined_cap_move(ops.into()) } fn get_pipelined_cap_move(&self, ops: Vec<PipelineOp>) -> Box<dyn ClientHook> { if let Some(p) = &self.i...
add_ref
identifier_name
queued.rs
permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT...
client_resolution_queue: SenderQueue<(), Box<dyn ClientHook>>, } impl ClientInner { pub fn resolve(state: &Rc<RefCell<Self>>, result: Result<Box<dyn ClientHook>, Error>) { assert!(state.borrow().redirect.is_none()); let client = match result { Ok(clienthook) => clienthook, ...
// delivered after calls made earlier), but *before* any queued calls return (because it might // confuse the application if a queued call returns before the capability on which it was made // resolves). Luckily, we know that queued calls will involve, at the very least, an // eventLoop.evalLater.
random_line_split
framework.rs
Result)") .expect("couldn't create ImageBitmapRenderingContext (Option)") .dyn_into::<ImageBitmapRenderingContext>() .expect("couldn't convert into ImageBitmapRenderingContext"); offscreen_canvas_setup = Some(OffscreenCanvasSetup { ...
fn run_until_stalled(&self) { while self.executor.try_tick() {} } }
random_line_split
framework.rs
let level: log::Level = parse_url_query_string(&query_string, "RUST_LOG") .and_then(|x| x.parse().ok()) .unwrap_or(log::Level::Error); console_log::init_with_level(level).expect("could not initialize logger"); std::panic::set_hook(Box::new(console_error_panic_hook::hook))...
{ #[cfg(not(target_arch = "wasm32"))] { env_logger::init(); }; let event_loop = EventLoop::new(); let mut builder = winit::window::WindowBuilder::new(); builder = builder.with_title(title); #[cfg(windows_OFF)] // TODO { use winit::platform::windows::WindowBuilderExtWindo...
identifier_body
framework.rs
could not initialize logger"); std::panic::set_hook(Box::new(console_error_panic_hook::hook)); // On wasm, append the canvas to the document body web_sys::window() .and_then(|win| win.document()) .and_then(|doc| doc.body()) .and_then(|body| { b...
}; let view = frame.texture.create_view(&w
{ surface.configure(&device, &config); surface .get_current_texture() .expect("Failed to acquire next surface texture!") }
conditional_block
framework.rs
= wgpu::Instance::new(wgpu::InstanceDescriptor { backends, dx12_shader_compiler, gles_minor_version, }); let (size, surface) = unsafe { let size = window.inner_size(); #[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))] let surface = instance.crea...
run
identifier_name
main.rs
}); let server = Server::bind(&addr).serve(make_svc); // Run this server for... forever! if let Err(e) = server.await { eprintln!("server error: {}", e); } } async fn request_handler(req: Request<Body>) -> Result<Response<Body>, Box<dyn std::error::Error + Send + Sync>> { crate::githu...
cmds.push(format!("--end={}", end)); println!("{:?}", &cmds); push_job(&reply_to, comment_id, &cmds, &code).await?; } None => {} } Ok(()) } async fn push_job(reply_to: &ReplyTo, job_id: &str, bisect_cmds: &[String], repro: &str) -> reqwest::Result<()> { ...
}
random_line_split
main.rs
}); let server = Server::bind(&addr).serve(make_svc); // Run this server for... forever! if let Err(e) = server.await { eprintln!("server error: {}", e); } } async fn request_handler(req: Request<Body>) -> Result<Response<Body>, Box<dyn std::error::Error + Send + Sync>> { crate::githu...
else if part.starts_with("end=") { if end.is_some() { return Err(format!("end range specified twice")); } end = Some(part["end=".len()..].to_string()); } else { ...
{ if start.is_some() { return Err(format!("start range specified twice")); } start = Some(part["start=".len()..].to_string()); }
conditional_block
main.rs
MIT_HEADER, user_id) } } } fn from_commit_message(message: &str) -> Result<Self, ()> { for line in message.lines() { let line = line.trim(); if !line.starts_with(Self::COMMIT_HEADER) { continue; } let header = line[Self...
TreeEntry
identifier_name
probe_bert.py
, "scheduler.pt"))) if args.fp16: try: from apex import amp except ImportError: raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level) ...
(args, model, prefix=""): # Loop to handle MNLI double evaluation (matched, mis-matched) eval_task_names = ("mnli", "mnli-mm") if args.task_name == "mnli" else (args.task_name,) eval_outputs_dirs = (args.output_dir, args.output_dir + "-MM") if args.task_name == "mnli" else (args.output_dir,) results = ...
evaluate
identifier_name
probe_bert.py
_path, "scheduler.pt"))) if args.fp16: try: from apex import amp except ImportError: raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_lev...
best_val_loss = results["loss"] output_ckpt_file = os.path.join(output_dir, "best_loss.txt") with open(output_ckpt_file, "w+") as writer: for key in sorted(results.keys()): writer.write("...
train_steps = global_step / len(train_domain_dataloader) # Save model checkpoint output_dir = os.path.join(args.output_dir, "checkpoint".format(train_steps)) if not os.path.exists(output_dir): ...
conditional_block
probe_bert.py
")[0]) epochs_trained = global_step // (len(train_domain_dataloader) // args.gradient_accumulation_steps) steps_trained_in_current_epoch = global_step % ( len(train_domain_dataloader) // args.gradient_accumulation_steps) logger.info(" Continuing training from checkpoint, will s...
if ( os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train and not args.overwrite_output_dir ): raise ValueError( "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format( ...
identifier_body
probe_bert.py
(eval_task_names, eval_outputs_dirs): eval_dataset = load_domain_examples(args, eval_task, args.aux_name, mode="dev") if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]: os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, arg...
args = parser.parse_args() config = train_options(args.input) # Merge the input arguments with the configuration yaml
random_line_split
dri.go
os.Stat(i915FramebufferFile); err != nil { return nil } return &I915Backend{} } // Round rounds up value for the Intel platforms and all codecs. func (g I915Backend) Round(value int) int { const i915Alignment = 16 // Inspired by Chromium's base/bits.h:Align() function. return (value + i915Alignment - 1) & ^(i9...
readStableObjectCount
identifier_name
dri.go
of framebuffers of width // and height dimensions allocated by the Backend. ReadFramebufferCount(ctx context.Context, width, height int) (framebuffers int, err error) } // I915Backend implements Backend for the Intel i915 case. type I915Backend struct{} func i915Backend() *I915Backend
// Round rounds up value for the Intel platforms and all codecs. func (g I915Backend) Round(value int) int { const i915Alignment = 16 // Inspired by Chromium's base/bits.h:Align() function. return (value + i915Alignment - 1) & ^(i915Alignment - 1) } // ReadFramebufferCount tries to open the i915FramebufferFile an...
{ if _, err := os.Stat(i915FramebufferFile); err != nil { return nil } return &I915Backend{} }
identifier_body
dri.go
number of framebuffers of width // and height dimensions allocated by the Backend. ReadFramebufferCount(ctx context.Context, width, height int) (framebuffers int, err error) } // I915Backend implements Backend for the Intel i915 case. type I915Backend struct{}
if _, err := os.Stat(i915FramebufferFile); err != nil { return nil } return &I915Backend{} } // Round rounds up value for the Intel platforms and all codecs. func (g I915Backend) Round(value int) int { const i915Alignment = 16 // Inspired by Chromium's base/bits.h:Align() function. return (value + i915Alignmen...
func i915Backend() *I915Backend {
random_line_split
dri.go
of framebuffers of width // and height dimensions allocated by the Backend. ReadFramebufferCount(ctx context.Context, width, height int) (framebuffers int, err error) } // I915Backend implements Backend for the Intel i915 case. type I915Backend struct{} func i915Backend() *I915Backend { if _, err := os.Stat(i915F...
text, err := ioutil.ReadAll(f) if err != nil { return framebuffers, errors.Wrap(err, "failed to read dri file") } lines := strings.Split(string(text), "\n") for _, line := range lines { // The line we're looking for looks like "...size=1920x1080" var fbWidth, fbHeight int if _, err := fmt.Sscanf(line, " ...
{ return framebuffers, errors.Wrap(err, "failed to open dri file") }
conditional_block
context.rs
(pub u64); #[derive(Copy, Clone, Debug, Hash, PartialEq)] pub struct PassHandle(pub u64); #[derive(Copy, Clone, Debug, Hash, PartialEq)] pub struct ImageHandle(pub u64); #[derive(Copy, Clone, Debug, Hash, PartialEq)] pub struct ShaderHandle(pub u64); pub struct Context { window: winit::window::Window, event_lo...
GraphHandle
identifier_name
context.rs
.expect("Failed to wait device idle.") }; // Recreate swapchain self.facade.destroy(&mut self.image_list); self.facade = Facade::new( &self.basis, &self.gpu, &self.window,
&mut self.image_list, &self.debug_utils, ); // Recreate the images which depend on the resolution of the swapchain for i in 0..self.image_list.list.len() { let (_, internal_image) = &mut self.image_list.list[i]; if let ImageKind::RelativeSized { sc...
random_line_split
context.rs
|| swapchain_height != physical_size.height { resize_needed = true; } } _ => {} }, Event::MainEventsCleared => { *control_fl...
{ self.image_list.new_image_from_file( name, path, &self.gpu, self.command_pool, &self.debug_utils, ) }
identifier_body
context.rs
.expect("Failed to wait device idle.") }; // Recreate swapchain self.facade.destroy(&mut self.image_list); self.facade = Facade::new( &self.basis, &self.gpu, &self.window, &mut self.image_list, &self.debug_utils, ); ...
_ => (), } }); // This mechanism is need on Windows: if resize_needed { self.recreate_resolution_dependent_state(); } // This mechanism suffices on Linux: // Acquiring the swapchain image fails if the window has been resized. If ...
{ *control_flow = ControlFlow::Exit; }
conditional_block
ner.rs
no_run //! use rust_bert::pipelines::common::ModelType; //! use rust_bert::pipelines::ner::NERModel; //! use rust_bert::pipelines::token_classification::TokenClassificationConfig; //! use rust_bert::resources::RemoteResource; //! use rust_bert::roberta::{ //! RobertaConfigResources, RobertaModelResources, RobertaVo...
let tokens = self.token_classification_model.predict(input, true, false); let mut entities: Vec<Vec<Entity>> = Vec::new(); for sequence_tokens in tokens { entities.push(Self::consolidate_entities(&sequence_tokens)); } entities }
identifier_body
ner.rs
:|:----: //! English| XLM_ROBERTA_NER_EN | //! German| XLM_ROBERTA_NER_DE | //! Spanish| XLM_ROBERTA_NER_ES | //! Dutch| XLM_ROBERTA_NER_NL | use crate::common::error::RustBertError; use crate::pipelines::common::TokenizerOption; use crate::pipelines::token_classification::{ Token, TokenClassificationConfig, Token...
if let Some((_, previous_tag, previous_label)) = self.previous_node { if (previous_tag == Tag::End) | (previous_tag == Tag::Single) | (previous_label != label) { let entity = self.flush_and_r...
conditional_block
ner.rs
: Box::new(RemoteResource::from_pretrained( //! RobertaConfigResources::XLM_ROBERTA_NER_DE, //! )), //! vocab_resource: Box::new(RemoteResource::from_pretrained( //! RobertaVocabResources::XLM_ROBERTA_NER_DE, //! )), //! lower_case: false, //! device: Device::cuda_if_available(), //!...
andle_current_tag(
identifier_name
ner.rs
```no_run //! # use rust_bert::pipelines::ner::Entity; //! # use rust_tokenizers::Offset; //! # let output = //! [ //! [ //! Entity { //! word: String::from("Amy"), //! score: 0.9986, //! label: String::from("I-PER"), //! offset: Offset { begin: 11, end: 14 }...
//! device: Device::cuda_if_available(), //! ..Default::default() //! }; //! //! let ner_model = NERModel::new(ner_config)?; //! //! // Define input //! let input = [ //! "Mein Name ist Amรฉlie. Ich lebe in Paris.", //! "Paris ist eine Stadt in Frankreich.", //! ]; //! let output = ner_model.predict(&...
//! lower_case: false,
random_line_split
membership.go
} else { continue } } currentHeartbeat++ logfTrace("%d - hosts=%d (announce=%d forward=%d)", currentHeartbeat, len(randomAllNodes), emitCount(), pingRequestCount()) PingNode(node) pingCounter++ time.Sleep(time.Millisecond * time.Duration(GetHeartbeatMillis())) if ...
{ logDebug("Forgetting dead node", node.Address()) deadNodeRetries.Lock() delete(deadNodeRetries.m, node.Address()) deadNodeRetries.Unlock() RemoveNode(node) continue }
conditional_block
membership.go
} for { c, err := net.DialUDP("udp", laddr, address) if err != nil { logError(err) return err } // Compose and send the multicast announcement msgBytes := encodeMulticastAnnounceBytes() _, err = c.Write(msgBytes) if err != nil { logError(err) return err } logfTrace("Sent announcement mu...
{ return transmitVerbGenericUDP(node, nil, verbAck, code) }
identifier_body
membership.go
time.Duration(GetHeartbeatMillis())) if knownNodesModifiedFlag { knownNodesModifiedFlag = false break } } if pingCounter == 0 { logDebug("No nodes to ping. So lonely. :(") time.Sleep(time.Millisecond * time.Duration(GetHeartbeatMillis())) } } } // PingNode can be used to explicitly ping a...
filteredNodes := getTargetNodes(pingRequestCount(), thisHost, pack.node) if len(filteredNodes) == 0 { logDebug(thisHost.Address(), "Cannot forward ping request: no more nodes") updateNodeStatus(pack.node, StatusDead, currentHeartbeat, thisHost) } else { for i, n := range filteredNodes { logfDebug("(%d/%d)...
return name, msgBytes, nil } func doForwardOnTimeout(pack *pendingAck) {
random_line_split
membership.go
buf[0:n]) } } func listenUDPMulticast(port int) error { addr := GetMulticastAddress() if addr == "" { addr = guessMulticastAddress() } listenAddress, err := net.ResolveUDPAddr("udp", addr+":"+strconv.FormatInt(int64(port), 10)) if err != nil { return err } /* Now listen at selected port */ iface, err :...
transmitVerbGenericUDP
identifier_name
connection.go
c.SendJSON(msg); err != nil { return err } return nil } // reason ใฎ้•ทใ•ใŒไธๅๅˆ†ใใ†ใชๅ ดๅˆใฏ CloseMessage ใงใฏใชใ TextMessage ใ‚’ไฝฟ็”จใ™ใ‚‹ใ‚ˆใ†ใซๅค‰ๆ›ดใ™ใ‚‹ func (c *connection) sendCloseMessage(code int, reason string) error { deadline := time.Now().Add(writeWait) closeMessage := websocket.FormatCloseMessage(code, reason) return c.wsConn.Wri...
c.errLog().Err(err).Caller().Msg("FailedSendRejectMessage") return err } return err
random_line_split
connection.go
} return nil } func (c *connection) sendPingMessage() error { msg := &pingMessage{ Type: "ping", } if err := c.SendJSON(msg); err != nil { return err } return nil } // reason ใฎ้•ทใ•ใŒไธๅๅˆ†ใใ†ใชๅ ดๅˆใฏ CloseMessage ใงใฏใชใ TextMessage ใ‚’ไฝฟ็”จใ™ใ‚‹ใ‚ˆใ†ใซๅค‰ๆ›ดใ™ใ‚‹ func (c *connection) sendCloseMessage(code int, reason string) error { ...
turn err
identifier_name
connection.go
return nil } // reason ใฎ้•ทใ•ใŒไธๅๅˆ†ใใ†ใชๅ ดๅˆใฏ CloseMessage ใงใฏใชใ TextMessage ใ‚’ไฝฟ็”จใ™ใ‚‹ใ‚ˆใ†ใซๅค‰ๆ›ดใ™ใ‚‹ func (c *connection) sendCloseMessage(code int, reason string) error { deadline := time.Now().Add(writeWait) closeMessage := websocket.FormatCloseMessage(code, reason) return c.wsConn.WriteControl(websocket.CloseMessage, closeMessage,...
c (c *connection) sendPingMessage() error { msg := &pingMessage{ Type: "ping", } if err := c.SendJSON(msg); err != nil { return err }
identifier_body
connection.go
err := c.SendJSON(msg); err != nil { return err } return nil } // reason ใฎ้•ทใ•ใŒไธๅๅˆ†ใใ†ใชๅ ดๅˆใฏ CloseMessage ใงใฏใชใ TextMessage ใ‚’ไฝฟ็”จใ™ใ‚‹ใ‚ˆใ†ใซๅค‰ๆ›ดใ™ใ‚‹ func (c *connection) sendCloseMessage(code int, reason string) error { deadline := time.Now().Add(writeWait) closeMessage := websocket.FormatCloseMessage(code, reason) return c.wsC...
-MESSAGE") } break loop } if err := c.wsConn.WriteMessage(websocket.TextMessage, forward.rawMessage); err != nil { c.errLog().Err(err).Msg("FailedWriteMessage") // ้€ใ‚Œใชใ‹ใฃใŸใ‚‰้–‰ใ˜ใ‚‹ใƒกใƒƒใ‚ปใƒผใ‚ธใ‚‚้€ใ‚Œใชใ„ใฎใง return return } } } // ใ“ใกใ‚‰ใฎ้ƒฝๅˆใง็ต‚ไบ†ใ™ใ‚‹ใฎใง Websocket ็ต‚ไบ†ใฎใŠ็Ÿฅใ‚‰ใ›ใ‚’้€ใ‚‹ if err := c.sendCloseMessage(websocket.C...
r != nil { c.errLog().Err(err).Msg("FailedSendByeMessage") // ้€ใ‚Œใชใ‹ใฃใŸใ‚‰้–‰ใ˜ใ‚‹ใƒกใƒƒใ‚ปใƒผใ‚ธใ‚‚้€ใ‚Œใชใ„ใฎใง return return } c.debugLog().Msg("SENT-BYE
conditional_block
images.go
Returns image ID and nil on success. func (i *ImagesModel) CreateImage( metaConstructor *images.SoftwareImageMetaConstructor, imageReader io.Reader) (string, error) { if metaConstructor == nil { return "", controller.ErrModelMissingInputMetadata } if imageReader == nil { return "", controller.ErrModelMissingI...
{ return nil, errors.Wrap(err, "Cannot get update files:") }
conditional_block
images.go
governing permissions and // limitations under the License. package model import ( "io" "io/ioutil" "time" "github.com/mendersoftware/deployments/resources/images" "github.com/mendersoftware/deployments/resources/images/controller" "github.com/mendersoftware/mender-artifact/metadata" "github.com/mendersof...
// DeleteImage removes metadata and image file // Noop for not exisitng images // Allowed to remove image only if image is not scheduled or in progress for an updates - then image file is needed // In case of already finished updates only image file is not needed, metadata is attached directly to device deployment //...
{ image, err := i.imagesStorage.FindByID(id) if err != nil { return nil, errors.Wrap(err, "Searching for image with specified ID") } if image == nil { return nil, nil } return image, nil }
identifier_body
images.go
return "", controller.ErrModelMissingInputArtifact } artifactID, err := i.handleArtifact(metaConstructor, imageReader) // try to remove artifact file from file storage on error if err != nil { if cleanupErr := i.fileStorage.Delete(artifactID); cleanupErr != nil { return "", errors.Wrap(err, cleanupErr.Error(...
random_line_split
images.go
governing permissions and // limitations under the License. package model import ( "io" "io/ioutil" "time" "github.com/mendersoftware/deployments/resources/images" "github.com/mendersoftware/deployments/resources/images/controller" "github.com/mendersoftware/mender-artifact/metadata" "github.com/mendersof...
(imageID string, expire time.Duration) (*images.Link, error) { found, err := i.imagesStorage.Exists(imageID) if err != nil { return nil, errors.Wrap(err, "Searching for image with specified ID") } if !found { return nil, nil } found, err = i.fileStorage.Exists(imageID) if err != nil { return nil, errors...
DownloadLink
identifier_name
file.go
name, link := logName(prefix, t) fname := filepath.Join(dir, name) // Open the file os.O_APPEND|os.O_CREATE rather than use os.Create. // Append is almost always more efficient than O_RDRW on most modern file systems. f, err = os.OpenFile(fname, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0664) if err == nil { symlink...
{ match = true }
conditional_block
file.go
dir = absDir } l.Lock() defer l.Unlock() l.name = dir return nil } // Type implements the flag.Value interface. func (l *DirName) Type() string { return "string" } // String implements the flag.Value interface. func (l *DirName) String() string { l.Lock() defer l.Unlock() return l.name } func (l *DirName) ...
func (l *loggingT) listLogFiles() ([]FileInfo, error) { var results []FileInfo dir, err := logging.logDir.get() if err != nil { // No log directory configured: simply indicate that there are no // log files. return nil, nil } infos, err := ioutil.ReadDir(dir) if err != nil { return results, err } // T...
{ return logging.listLogFiles() }
identifier_body
file.go
dir = absDir } l.Lock() defer l.Unlock() l.name = dir return nil } // Type implements the flag.Value interface. func (l *DirName) Type() string { return "string" } // String implements the flag.Value interface. func (l *DirName) String() string { l.Lock() defer l.Unlock() return l.name } func (l *DirName)...
(prefix string, t time.Time) (name, link string) { // Replace the ':'s in the time format with '_'s to allow for log files in // Windows. tFormatted := strings.Replace(t.Format(time.RFC3339), ":", "_", -1) name = fmt.Sprintf("%s.%s.%s.%s.%06d.log", removePeriods(prefix), removePeriods(host), removePeriods(us...
logName
identifier_name
file.go
// LogFileMaxSize is the maximum size of a log file in bytes. var LogFileMaxSize int64 = 10 << 20 // 10MiB // LogFilesCombinedMaxSize is the maximum total size in bytes for log // files. Note that this is only checked when log files are created, // so the total size of log files per severity might temporarily be up /...
"github.com/cockroachdb/cockroach/pkg/util/syncutil" "github.com/cockroachdb/cockroach/pkg/util/timeutil" )
random_line_split
guidestar.py
) return target def set_geometry(self,healpix=True): from astropy_healpix import HEALPix from astropy.coordinates import SkyCoord import astropy.coordinates as cc from numpy import unique if self.lifu: self.g_dx = 3.75 self.g_dy = 4.0...
to_xml
identifier_name
guidestar.py
'%(self.cache_dir) os.system(cmd) if not os.path.isfile(self.xml_template): self.wget(self.xml_template_url) def get_guide(self,annular_fail=True,as_xml=True,print_xml=False): """ Master function to return a guide star once the object is ins...
else: t0 = tabs[0] for t in tabs[1:]: for g in t: t0.add_row(g) self.guides = t0 return def select_target(self,annular=False): import numpy from operator import indexOf fro...
self.guides = tabs[0]
conditional_block
guidestar.py
= self.dec + ((0.5*self.g_dy)/60.0) self.dec_min = self.dec - ((0.5*self.g_dy)/60.0) self.ra_gc0 = self.ra + (27.7/60.0) self.dec_gc0 = self.dec else: self.ra_min = self.ra - 1.0 self.ra_max = self.ra + 1.0 self.dec_min = self.dec - 1.0 ...
self.new_xml() xml_target = self.targets_base[0].cloneNode(True) guide_ra = guide['GAIA_RA'] guide_dec = guide['GAIA_DEC'] dx = (self.ra - guide_ra)*self.plate_scale dy = (self.dec - guide_dec)*self.plate_scale xml_target.setAttribute('targx',str(dx)) xml_target....
identifier_body
guidestar.py
s'%(self.cache_dir) os.system(cmd) if not os.path.isfile(self.xml_template): self.wget(self.xml_template_url) def get_guide(self,annular_fail=True,as_xml=True,print_xml=False): """ Master function to return a guide star once the object is in...
if rnd_dist > r_min: if rnd_dist < r_max: self.healpix_indices.append(hp.skycoord_to_healpix(SkyCoord(rnd_ra,rnd_dec,unit='deg'))) in_annulus.append([rnd_ra,rnd_dec]) #print len(in_annulus) print '....done' self.healpix_...
rnd_ra = self.ra+(2*(random.random()-0.5)*radius) rnd_dec = self.dec+(2*(random.random()-0.5)*radius) rnd_dist = (((rnd_ra-self.ra)**2)+((rnd_dec-self.dec)**2))**0.5
random_line_split
detours.rs
::once; use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; // Copied from winapi-rs since we are having issues with macro-use macro_rules! DEF_STRUCT { {$(#[$attrs:meta])* nodebug struct $name:ident { $($field:ident: $ftype:ty,)+ }} => { #[repr(C)] $(#[$attrs])* pub struct $name { ...
{ module: HMODULE, } impl Module { #[allow(dead_code)] pub fn target(moduleName: &str) -> Option<Module> { let mut library = Module { module: 0 as HMODULE }; let wModuleName: Vec<u16> = OsStr::new(moduleName) .encode_wide() .chain(once(0)) .collect(); ...
Module
identifier_name
detours.rs
::once; use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; // Copied from winapi-rs since we are having issues with macro-use macro_rules! DEF_STRUCT { {$(#[$attrs:meta])* nodebug struct $name:ident { $($field:ident: $ftype:ty,)+ }} => { #[repr(C)] $(#[$attrs])* pub struct $name { ...
// TODO: Think about adding support for IMAGE_FILE_MACHINE_AMD64 later return None; } let import_desc_array: PIMAGE_IMPORT_DESCRIPTOR = unsafe { mem::transmute::<PBYTE, PIMAGE_IMPORT_DESCRIPTOR>( base_addr.offset((*nt_hdr).OptionalHeader.DataDirectory...
{ let base_addr: PBYTE = unsafe { mem::transmute::<HMODULE, PBYTE>(self.module) }; let dos_hdr: PIMAGE_DOS_HEADER = unsafe { mem::transmute::<HMODULE, PIMAGE_DOS_HEADER>(self.module) }; if unsafe { (*dos_hdr).e_magic } != IMAGE_DOS_SIGNATURE { return None; } ...
identifier_body
detours.rs
::once; use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; // Copied from winapi-rs since we are having issues with macro-use macro_rules! DEF_STRUCT { {$(#[$attrs:meta])* nodebug struct $name:ident { $($field:ident: $ftype:ty,)+ }} => { #[repr(C)] $(#[$attrs])* pub struct $name { ...
if (orig_thunk.u1 & IMAGE_ORDINAL_FLAG) != 0 { continue; } let import: PIMAGE_IMPORT_BY_NAME = unsafe { mem::transmute::<PBYTE, PIMAGE_I...
{ break; }
conditional_block
detours.rs
windows::ffi::OsStrExt; // Copied from winapi-rs since we are having issues with macro-use macro_rules! DEF_STRUCT { {$(#[$attrs:meta])* nodebug struct $name:ident { $($field:ident: $ftype:ty,)+ }} => { #[repr(C)] $(#[$attrs])* pub struct $name { $(pub $field: $ftype,)+ } ...
#[test] fn test_intercept() { let target = Module::self_target();
random_line_split
amap.go
"` Pname string `json:"pname"` Poiweight []interface{} `json:"poiweight"` Postcode []interface{} `json:"postcode"` Recommend string `json:"recommend"` Shopid []interface{} `json:"shopid"` Shopinfo string `json:"shopinfo"` Tag []interface{} `json:"tag"` Tel string ...
pois = result.Pois return } func minRecPagesPois(minRecPages []minRecPage) (pois []Poi) { for _, minRecPage := range minRecPages { pagePois, err := minRecPagePois(minRecPage) if err == nil { pois = append(pois, pagePois...) } else { fmt.Println(minRecPages, err) } } return } func minRecPages(mRec ...
{ return }
conditional_block
amap.go
"` Pname string `json:"pname"` Poiweight []interface{} `json:"poiweight"` Postcode []interface{} `json:"postcode"` Recommend string `json:"recommend"` Shopid []interface{} `json:"shopid"` Shopinfo string `json:"shopinfo"` Tag []interface{} `json:"tag"` Tel string ...
func recRequest(para map[string]string) (result PoiResult, err error) { para["key"] = key resp, err := resty. SetTimeout(10 * time.Second). SetRetryCount(5). SetRetryWaitTime(10 * time.Second). SetRetryMaxWaitTime(65 * time.Second). R(). SetQueryParams(para). Get(gaoDePolygonURL) if err != nil { re...
{ pages := recTypePages(rec, types) pois = minRecPagesPois(pages) return }
identifier_body
amap.go
/detail/get/detail" var key = "aaa8abdaf05433e3702eae99964cc8c6" // var key = "935c7385f239000f98ade53bbbc002e7" func cutRec(rec Rectangle, types string) (recCutresult []minRec) { count, err := recCount(rec, types) if err != nil { fmt.Println(rec, types, count, err) recCutresult = append(recCutresult, minRec{r...
random_line_split