repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.coord_grid | def coord_grid(self):
"""Draw a grid of RA/DEC on Canvas."""
import math,ephem
ra2=math.pi*2
ra1=0
dec1=-1*math.pi/2.0
dec2=math.pi/2.0
## grid space choices
## ra space in hours
ra_grids=["06:00:00",
"03:00:00",
"01:00:00",
"00:30:00",
"00:15:00",
"00:05:00",
"00:01:00",
"00:00:30",
"00:00:15",
"00:00:05"]
dec_grids=["45:00:00",
"30:00:00",
"15:00:00",
"05:00:00",
"01:00:00",
"00:15:00",
"00:05:00",
"00:01:00",
"00:00:30"]
dra=(self.x2-self.x1)/3.0
ddec=(self.y2-self.y1)/3.0
for ra_grid in ra_grids:
if self.hours(ra_grid)<math.fabs(dra):
break
ra_grid=self.hours(ra_grid)
for dec_grid in dec_grids:
if self.degrees(dec_grid)<math.fabs(ddec):
break
dec_grid=self.degrees(dec_grid)
ra=ra1
n=0
import Tkinter,ephem
while (ra<=ra2):
(cx1,cy1)=self.p2c((ra,dec1))
ly=cy1-30
(cx2,cy2)=self.p2c((ra,dec2))
self.create_line(cx1,cy1,cx2,cy2)
lx=cx1
n=n+1
if n==2:
dec=dec1
k=2
while ( dec <= dec2 ):
(lx,ly)=self.p2c((ra,dec))
(cx1,cy1)=self.p2c((ra1,dec))
(cx2,cy2)=self.p2c((ra2,dec))
self.create_line(cx1,cy1,cx2,cy2)
k=k+1
if k==3:
self.create_text(lx-45,ly-12,text=str(ephem.hours(ra)),fill='green')
self.create_text(lx+40,ly-12,text=str(ephem.degrees(dec)),fill='brown')
self.create_point(ra,dec,color='black',size=3)
k=0
dec=dec+dec_grid
n=0
ra=ra+ra_grid | python | def coord_grid(self):
"""Draw a grid of RA/DEC on Canvas."""
import math,ephem
ra2=math.pi*2
ra1=0
dec1=-1*math.pi/2.0
dec2=math.pi/2.0
## grid space choices
## ra space in hours
ra_grids=["06:00:00",
"03:00:00",
"01:00:00",
"00:30:00",
"00:15:00",
"00:05:00",
"00:01:00",
"00:00:30",
"00:00:15",
"00:00:05"]
dec_grids=["45:00:00",
"30:00:00",
"15:00:00",
"05:00:00",
"01:00:00",
"00:15:00",
"00:05:00",
"00:01:00",
"00:00:30"]
dra=(self.x2-self.x1)/3.0
ddec=(self.y2-self.y1)/3.0
for ra_grid in ra_grids:
if self.hours(ra_grid)<math.fabs(dra):
break
ra_grid=self.hours(ra_grid)
for dec_grid in dec_grids:
if self.degrees(dec_grid)<math.fabs(ddec):
break
dec_grid=self.degrees(dec_grid)
ra=ra1
n=0
import Tkinter,ephem
while (ra<=ra2):
(cx1,cy1)=self.p2c((ra,dec1))
ly=cy1-30
(cx2,cy2)=self.p2c((ra,dec2))
self.create_line(cx1,cy1,cx2,cy2)
lx=cx1
n=n+1
if n==2:
dec=dec1
k=2
while ( dec <= dec2 ):
(lx,ly)=self.p2c((ra,dec))
(cx1,cy1)=self.p2c((ra1,dec))
(cx2,cy2)=self.p2c((ra2,dec))
self.create_line(cx1,cy1,cx2,cy2)
k=k+1
if k==3:
self.create_text(lx-45,ly-12,text=str(ephem.hours(ra)),fill='green')
self.create_text(lx+40,ly-12,text=str(ephem.degrees(dec)),fill='brown')
self.create_point(ra,dec,color='black',size=3)
k=0
dec=dec+dec_grid
n=0
ra=ra+ra_grid | [
"def",
"coord_grid",
"(",
"self",
")",
":",
"import",
"math",
",",
"ephem",
"ra2",
"=",
"math",
".",
"pi",
"*",
"2",
"ra1",
"=",
"0",
"dec1",
"=",
"-",
"1",
"*",
"math",
".",
"pi",
"/",
"2.0",
"dec2",
"=",
"math",
".",
"pi",
"/",
"2.0",
"## g... | Draw a grid of RA/DEC on Canvas. | [
"Draw",
"a",
"grid",
"of",
"RA",
"/",
"DEC",
"on",
"Canvas",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L286-L355 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.label | def label(self,x,y,label,offset=[0,0]):
"""Write label at plot coordinates (x,y)"""
(xc,yc)=self.p2c([x,y])
return self.create_text(xc-offset[0],yc-offset[1],text=label) | python | def label(self,x,y,label,offset=[0,0]):
"""Write label at plot coordinates (x,y)"""
(xc,yc)=self.p2c([x,y])
return self.create_text(xc-offset[0],yc-offset[1],text=label) | [
"def",
"label",
"(",
"self",
",",
"x",
",",
"y",
",",
"label",
",",
"offset",
"=",
"[",
"0",
",",
"0",
"]",
")",
":",
"(",
"xc",
",",
"yc",
")",
"=",
"self",
".",
"p2c",
"(",
"[",
"x",
",",
"y",
"]",
")",
"return",
"self",
".",
"create_te... | Write label at plot coordinates (x,y) | [
"Write",
"label",
"at",
"plot",
"coordinates",
"(",
"x",
"y",
")"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L416-L419 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.limits | def limits(self,x1,x2,y1,y2):
"""Set the coordinate boundaries of plot"""
import math
self.x1=x1
self.x2=x2
self.y1=y1
self.y2=y2
self.xscale=(self.cx2-self.cx1)/(self.x2-self.x1)
self.yscale=(self.cy2-self.cy1)/(self.y2-self.y1)
ra1=self.x1
ra2=self.x2
dec1=self.y1
dec2=self.y2
(sx1,sy2)=self.p2c((ra1,dec1))
(sx2,sy1)=self.p2c((ra2,dec2))
self.config(scrollregion=(sx1-self.lgutter,sy1+self.bgutter,sx2+self.rgutter,sy2-self.tgutter)) | python | def limits(self,x1,x2,y1,y2):
"""Set the coordinate boundaries of plot"""
import math
self.x1=x1
self.x2=x2
self.y1=y1
self.y2=y2
self.xscale=(self.cx2-self.cx1)/(self.x2-self.x1)
self.yscale=(self.cy2-self.cy1)/(self.y2-self.y1)
ra1=self.x1
ra2=self.x2
dec1=self.y1
dec2=self.y2
(sx1,sy2)=self.p2c((ra1,dec1))
(sx2,sy1)=self.p2c((ra2,dec2))
self.config(scrollregion=(sx1-self.lgutter,sy1+self.bgutter,sx2+self.rgutter,sy2-self.tgutter)) | [
"def",
"limits",
"(",
"self",
",",
"x1",
",",
"x2",
",",
"y1",
",",
"y2",
")",
":",
"import",
"math",
"self",
".",
"x1",
"=",
"x1",
"self",
".",
"x2",
"=",
"x2",
"self",
".",
"y1",
"=",
"y1",
"self",
".",
"y2",
"=",
"y2",
"self",
".",
"xsca... | Set the coordinate boundaries of plot | [
"Set",
"the",
"coordinate",
"boundaries",
"of",
"plot"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L422-L440 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.reset | def reset(self):
"""Expand to the full scale"""
import ephem, MOPcoord
sun=ephem.Sun()
sun.compute(self.date.get())
self.sun=MOPcoord.coord((sun.ra,sun.dec))
doplot(kbos)
self.plot_pointings() | python | def reset(self):
"""Expand to the full scale"""
import ephem, MOPcoord
sun=ephem.Sun()
sun.compute(self.date.get())
self.sun=MOPcoord.coord((sun.ra,sun.dec))
doplot(kbos)
self.plot_pointings() | [
"def",
"reset",
"(",
"self",
")",
":",
"import",
"ephem",
",",
"MOPcoord",
"sun",
"=",
"ephem",
".",
"Sun",
"(",
")",
"sun",
".",
"compute",
"(",
"self",
".",
"date",
".",
"get",
"(",
")",
")",
"self",
".",
"sun",
"=",
"MOPcoord",
".",
"coord",
... | Expand to the full scale | [
"Expand",
"to",
"the",
"full",
"scale"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L442-L452 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.updateObj | def updateObj(self,event):
"""Put this object in the search box"""
name=w.objList.get("active")
w.SearchVar.set(name)
w.ObjInfo.set(objInfoDict[name])
return | python | def updateObj(self,event):
"""Put this object in the search box"""
name=w.objList.get("active")
w.SearchVar.set(name)
w.ObjInfo.set(objInfoDict[name])
return | [
"def",
"updateObj",
"(",
"self",
",",
"event",
")",
":",
"name",
"=",
"w",
".",
"objList",
".",
"get",
"(",
"\"active\"",
")",
"w",
".",
"SearchVar",
".",
"set",
"(",
"name",
")",
"w",
".",
"ObjInfo",
".",
"set",
"(",
"objInfoDict",
"[",
"name",
... | Put this object in the search box | [
"Put",
"this",
"object",
"in",
"the",
"search",
"box"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L454-L460 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.relocate | def relocate(self):
"""Move to the postion of self.SearchVar"""
name=self.SearchVar.get()
if kbos.has_key(name):
import orbfit,ephem,math
jdate=ephem.julian_date(w.date.get())
try:
(ra,dec,a,b,ang)=orbfit.predict(kbos[name],jdate,568)
except:
return
ra=math.radians(ra)
dec=math.radians(dec)
elif mpc_objs.has_key(name):
ra=mpc_objs[name].ra
dec=mpc_objs[name].dec
self.recenter(ra,dec)
self.create_point(ra,dec,color='blue',size=4) | python | def relocate(self):
"""Move to the postion of self.SearchVar"""
name=self.SearchVar.get()
if kbos.has_key(name):
import orbfit,ephem,math
jdate=ephem.julian_date(w.date.get())
try:
(ra,dec,a,b,ang)=orbfit.predict(kbos[name],jdate,568)
except:
return
ra=math.radians(ra)
dec=math.radians(dec)
elif mpc_objs.has_key(name):
ra=mpc_objs[name].ra
dec=mpc_objs[name].dec
self.recenter(ra,dec)
self.create_point(ra,dec,color='blue',size=4) | [
"def",
"relocate",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"SearchVar",
".",
"get",
"(",
")",
"if",
"kbos",
".",
"has_key",
"(",
"name",
")",
":",
"import",
"orbfit",
",",
"ephem",
",",
"math",
"jdate",
"=",
"ephem",
".",
"julian_date",
"(... | Move to the postion of self.SearchVar | [
"Move",
"to",
"the",
"postion",
"of",
"self",
".",
"SearchVar"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L462-L480 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.__zoom | def __zoom(self,event,scale=2.0):
"""Zoom in"""
import Tkinter,math
## compute the x,y of the center of the screen
sx1=self.cx1+(self.cx2-self.cx1+1.0)/2.0
sy1=self.cy1+(self.cy2-self.cy1+1.0)/2.0
#print sx1,sy1
if not event is None:
sx1=event.x
sy1=event.y
#print sx1,sy1
## translate that into a canvas location and then
## and ra/dec position
(x,y)=self.c2p((self.canvasx(sx1),self.canvasy(sy1)))
#print math.degrees(x),math.degrees(y),sx1, sy1
## reset the width of the display
xw=(self.x2-self.x1)/2.0/scale
yw=(self.y2-self.y1)/2.0/scale
## reset the limits to be centered at x,y with
## area of xw*2,y2*2
self.limits(x-xw,x+xw,y-yw,y+yw)
self.delete(Tkinter.ALL)
doplot(kbos) | python | def __zoom(self,event,scale=2.0):
"""Zoom in"""
import Tkinter,math
## compute the x,y of the center of the screen
sx1=self.cx1+(self.cx2-self.cx1+1.0)/2.0
sy1=self.cy1+(self.cy2-self.cy1+1.0)/2.0
#print sx1,sy1
if not event is None:
sx1=event.x
sy1=event.y
#print sx1,sy1
## translate that into a canvas location and then
## and ra/dec position
(x,y)=self.c2p((self.canvasx(sx1),self.canvasy(sy1)))
#print math.degrees(x),math.degrees(y),sx1, sy1
## reset the width of the display
xw=(self.x2-self.x1)/2.0/scale
yw=(self.y2-self.y1)/2.0/scale
## reset the limits to be centered at x,y with
## area of xw*2,y2*2
self.limits(x-xw,x+xw,y-yw,y+yw)
self.delete(Tkinter.ALL)
doplot(kbos) | [
"def",
"__zoom",
"(",
"self",
",",
"event",
",",
"scale",
"=",
"2.0",
")",
":",
"import",
"Tkinter",
",",
"math",
"## compute the x,y of the center of the screen",
"sx1",
"=",
"self",
".",
"cx1",
"+",
"(",
"self",
".",
"cx2",
"-",
"self",
".",
"cx1",
"+"... | Zoom in | [
"Zoom",
"in"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L505-L530 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.create_ellipse | def create_ellipse(self,xcen,ycen,a,b,ang,resolution=40.0):
"""Plot ellipse at x,y with size a,b and orientation ang"""
import math
e1=[]
e2=[]
ang=ang-math.radians(90)
for i in range(0,int(resolution)+1):
x=(-1*a+2*a*float(i)/resolution)
y=1-(x/a)**2
if y < 1E-6:
y=1E-6
y=math.sqrt(y)*b
ptv=self.p2c((x*math.cos(ang)+y*math.sin(ang)+xcen,y*math.cos(ang)-x*math.sin(ang)+ycen))
y=-1*y
ntv=self.p2c((x*math.cos(ang)+y*math.sin(ang)+xcen,y*math.cos(ang)-x*math.sin(ang)+ycen))
e1.append(ptv)
e2.append(ntv)
e2.reverse()
e1.extend(e2)
self.create_line(e1,fill='red',width=1) | python | def create_ellipse(self,xcen,ycen,a,b,ang,resolution=40.0):
"""Plot ellipse at x,y with size a,b and orientation ang"""
import math
e1=[]
e2=[]
ang=ang-math.radians(90)
for i in range(0,int(resolution)+1):
x=(-1*a+2*a*float(i)/resolution)
y=1-(x/a)**2
if y < 1E-6:
y=1E-6
y=math.sqrt(y)*b
ptv=self.p2c((x*math.cos(ang)+y*math.sin(ang)+xcen,y*math.cos(ang)-x*math.sin(ang)+ycen))
y=-1*y
ntv=self.p2c((x*math.cos(ang)+y*math.sin(ang)+xcen,y*math.cos(ang)-x*math.sin(ang)+ycen))
e1.append(ptv)
e2.append(ntv)
e2.reverse()
e1.extend(e2)
self.create_line(e1,fill='red',width=1) | [
"def",
"create_ellipse",
"(",
"self",
",",
"xcen",
",",
"ycen",
",",
"a",
",",
"b",
",",
"ang",
",",
"resolution",
"=",
"40.0",
")",
":",
"import",
"math",
"e1",
"=",
"[",
"]",
"e2",
"=",
"[",
"]",
"ang",
"=",
"ang",
"-",
"math",
".",
"radians"... | Plot ellipse at x,y with size a,b and orientation ang | [
"Plot",
"ellipse",
"at",
"x",
"y",
"with",
"size",
"a",
"b",
"and",
"orientation",
"ang"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L532-L552 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.get_pointings | def get_pointings(self):
"""Query for some pointings, given a block name"""
import MOPdbaccess,ephem,math
import tkSimpleDialog
result = tkSimpleDialog.askstring("Block Load", "Which Block do you want to plot?")
db = MOPdbaccess.connect('bucket','cfhls',dbSystem='MYSQL')
SQL = """SELECT object,ra,`dec`,status,ccd FROM blocks b
JOIN cfeps.triple_members m ON m.expnum=b.expnum
JOIN cfeps.discovery d ON d.triple=m.triple
JOIN exposure e ON e.expnum=b.expnum
LEFT JOIN cfeps.processing p ON p.triple=m.triple
WHERE p.process='plant' and b.block RLIKE '%s' GROUP BY m.triple,p.ccd """ % (result)
points=[]
c = db.cursor()
r = c.execute(SQL)
rows=c.fetchall()
print len(rows)
geo = camera.geometry['MEGACAM_36']
main_pointing=''
for row in rows:
if main_pointing != row[0]:
# put down the 'full MP FOV' here
c=camera(camera='MEGACAM_1')
if row[4]!= "NULL":
color='pale green'
else:
color='gray'
label={'text': row[0]}
c.ra=ephem.hours(math.radians(float(row[1])))
c.dec=ephem.degrees(math.radians(float(row[2])))
self.pointings.append({"label": label,
"camera": c,
"color": color})
main_pointing=row[0]
if int(row[3]) < 0:
# Create a 'red' box for this CCD
c=camera(camera='MP_CCD')
c.ra = ephem.hours(math.radians(float(row[1])-geo[int(row[4])]["ra"]/math.cos(math.radians(float(row[2])))))
c.dec =ephem.degrees(math.radians(float(row[2])-geo[int(row[4])]["dec"]))
color='red'
label={'text': str(row[4])}
self.pointings.append({"label": label, "camera": c,"color":color})
self.plot_pointings()
return | python | def get_pointings(self):
"""Query for some pointings, given a block name"""
import MOPdbaccess,ephem,math
import tkSimpleDialog
result = tkSimpleDialog.askstring("Block Load", "Which Block do you want to plot?")
db = MOPdbaccess.connect('bucket','cfhls',dbSystem='MYSQL')
SQL = """SELECT object,ra,`dec`,status,ccd FROM blocks b
JOIN cfeps.triple_members m ON m.expnum=b.expnum
JOIN cfeps.discovery d ON d.triple=m.triple
JOIN exposure e ON e.expnum=b.expnum
LEFT JOIN cfeps.processing p ON p.triple=m.triple
WHERE p.process='plant' and b.block RLIKE '%s' GROUP BY m.triple,p.ccd """ % (result)
points=[]
c = db.cursor()
r = c.execute(SQL)
rows=c.fetchall()
print len(rows)
geo = camera.geometry['MEGACAM_36']
main_pointing=''
for row in rows:
if main_pointing != row[0]:
# put down the 'full MP FOV' here
c=camera(camera='MEGACAM_1')
if row[4]!= "NULL":
color='pale green'
else:
color='gray'
label={'text': row[0]}
c.ra=ephem.hours(math.radians(float(row[1])))
c.dec=ephem.degrees(math.radians(float(row[2])))
self.pointings.append({"label": label,
"camera": c,
"color": color})
main_pointing=row[0]
if int(row[3]) < 0:
# Create a 'red' box for this CCD
c=camera(camera='MP_CCD')
c.ra = ephem.hours(math.radians(float(row[1])-geo[int(row[4])]["ra"]/math.cos(math.radians(float(row[2])))))
c.dec =ephem.degrees(math.radians(float(row[2])-geo[int(row[4])]["dec"]))
color='red'
label={'text': str(row[4])}
self.pointings.append({"label": label, "camera": c,"color":color})
self.plot_pointings()
return | [
"def",
"get_pointings",
"(",
"self",
")",
":",
"import",
"MOPdbaccess",
",",
"ephem",
",",
"math",
"import",
"tkSimpleDialog",
"result",
"=",
"tkSimpleDialog",
".",
"askstring",
"(",
"\"Block Load\"",
",",
"\"Which Block do you want to plot?\"",
")",
"db",
"=",
"M... | Query for some pointings, given a block name | [
"Query",
"for",
"some",
"pointings",
"given",
"a",
"block",
"name"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L586-L632 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.load_pointings | def load_pointings(self):
"""Load some pointings"""
import os,re,ephem
import tkFileDialog,tkMessageBox
filename=tkFileDialog.askopenfilename()
if filename is None:
return
f=open(filename)
lines=f.readlines()
f.close()
points=[]
if lines[0][0:5]=="<?xml":
### assume astrores format
### with <DATA at start of 'data' segment
for i in range(len(lines)):
if lines[i][0:5]=='<DATA':
break
for j in range(i+5,len(lines)):
if lines[j][0:2]=="]]":
break
vs=lines[j].split('|')
points.append(vs)
elif lines[0][0:5]=='index':
### Palomar Format
### OK.. ID/NAME/RA /DEC format
for line in lines:
if line[0]=='!' or line[0:5]=='index':
# index is a header line for Palomar
continue
d = line.split()
if len(d)!=9:
import sys
sys.stderr.write("Don't understand pointing format\n%s\n" %( line))
continue
ras="%s:%s:%s" % ( d[2],d[3],d[4])
decs="%s:%s:%s" % ( d[5],d[6],d[7])
points.append((d[1].strip(),ras,decs))
elif lines[0][0:5]=="#SSIM":
### Survey Simulator format
for line in lines[1:]:
d = line.split()
points.append((d[8],d[2],d[3]))
else:
### try name/ ra /dec / epoch
for line in lines:
d=line.split()
if len(d)!=4:
if len(d)!=8:
import sys
sys.stderr.write("Don't understand pointing format\n%s\n" %( line))
continue
line = "%s %s:%s:%s %s:%s:%s %s" % (d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7] )
d=line.split()
import math
f=d[1].count(":")
if ( f > 0 ) :
points.append((d[0],d[1],d[2]))
else:
points.append(('',math.radians(float(d[1])),math.radians(float(d[2]))))
self.plot_points_list(points)
return | python | def load_pointings(self):
"""Load some pointings"""
import os,re,ephem
import tkFileDialog,tkMessageBox
filename=tkFileDialog.askopenfilename()
if filename is None:
return
f=open(filename)
lines=f.readlines()
f.close()
points=[]
if lines[0][0:5]=="<?xml":
### assume astrores format
### with <DATA at start of 'data' segment
for i in range(len(lines)):
if lines[i][0:5]=='<DATA':
break
for j in range(i+5,len(lines)):
if lines[j][0:2]=="]]":
break
vs=lines[j].split('|')
points.append(vs)
elif lines[0][0:5]=='index':
### Palomar Format
### OK.. ID/NAME/RA /DEC format
for line in lines:
if line[0]=='!' or line[0:5]=='index':
# index is a header line for Palomar
continue
d = line.split()
if len(d)!=9:
import sys
sys.stderr.write("Don't understand pointing format\n%s\n" %( line))
continue
ras="%s:%s:%s" % ( d[2],d[3],d[4])
decs="%s:%s:%s" % ( d[5],d[6],d[7])
points.append((d[1].strip(),ras,decs))
elif lines[0][0:5]=="#SSIM":
### Survey Simulator format
for line in lines[1:]:
d = line.split()
points.append((d[8],d[2],d[3]))
else:
### try name/ ra /dec / epoch
for line in lines:
d=line.split()
if len(d)!=4:
if len(d)!=8:
import sys
sys.stderr.write("Don't understand pointing format\n%s\n" %( line))
continue
line = "%s %s:%s:%s %s:%s:%s %s" % (d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7] )
d=line.split()
import math
f=d[1].count(":")
if ( f > 0 ) :
points.append((d[0],d[1],d[2]))
else:
points.append(('',math.radians(float(d[1])),math.radians(float(d[2]))))
self.plot_points_list(points)
return | [
"def",
"load_pointings",
"(",
"self",
")",
":",
"import",
"os",
",",
"re",
",",
"ephem",
"import",
"tkFileDialog",
",",
"tkMessageBox",
"filename",
"=",
"tkFileDialog",
".",
"askopenfilename",
"(",
")",
"if",
"filename",
"is",
"None",
":",
"return",
"f",
"... | Load some pointings | [
"Load",
"some",
"pointings"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L634-L695 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.create_pointing | def create_pointing(self,event):
"""Plot the sky coverage of pointing at event.x,event.y on the canavas"""
import math
(ra,dec)=self.c2p((self.canvasx(event.x),
self.canvasy(event.y)))
this_camera=camera(camera=self.camera.get())
ccds=this_camera.getGeometry(ra,dec)
items=[]
for ccd in ccds:
(x1,y1)=self.p2c((ccd[0],ccd[1]))
(x2,y2)=self.p2c((ccd[2],ccd[3]))
item=self.create_rectangle(x1,y1,x2,y2)
items.append(item)
label={}
label['text']=w.plabel.get()
label['id']=self.label(this_camera.ra,this_camera.dec,label['text'])
self.pointings.append({
"label": label,
"items": items,
"camera": this_camera} )
self.current_pointing(len(self.pointings)-1) | python | def create_pointing(self,event):
"""Plot the sky coverage of pointing at event.x,event.y on the canavas"""
import math
(ra,dec)=self.c2p((self.canvasx(event.x),
self.canvasy(event.y)))
this_camera=camera(camera=self.camera.get())
ccds=this_camera.getGeometry(ra,dec)
items=[]
for ccd in ccds:
(x1,y1)=self.p2c((ccd[0],ccd[1]))
(x2,y2)=self.p2c((ccd[2],ccd[3]))
item=self.create_rectangle(x1,y1,x2,y2)
items.append(item)
label={}
label['text']=w.plabel.get()
label['id']=self.label(this_camera.ra,this_camera.dec,label['text'])
self.pointings.append({
"label": label,
"items": items,
"camera": this_camera} )
self.current_pointing(len(self.pointings)-1) | [
"def",
"create_pointing",
"(",
"self",
",",
"event",
")",
":",
"import",
"math",
"(",
"ra",
",",
"dec",
")",
"=",
"self",
".",
"c2p",
"(",
"(",
"self",
".",
"canvasx",
"(",
"event",
".",
"x",
")",
",",
"self",
".",
"canvasy",
"(",
"event",
".",
... | Plot the sky coverage of pointing at event.x,event.y on the canavas | [
"Plot",
"the",
"sky",
"coverage",
"of",
"pointing",
"at",
"event",
".",
"x",
"event",
".",
"y",
"on",
"the",
"canavas"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L712-L733 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.plot_pointings | def plot_pointings(self,pointings=None):
"""Plot pointings on canavs"""
if pointings is None:
pointings=self.pointings
i=0
for pointing in pointings:
items=[]
i=i+1
label={}
label['text']=pointing['label']['text']
for ccd in pointing["camera"].getGeometry():
(x1,y1)=self.p2c((ccd[0],ccd[1]))
(x2,y2)=self.p2c((ccd[2],ccd[3]))
item=self.create_rectangle(x1,y1,x2,y2,stipple='gray25',fill=pointing.get('color',''))
items.append(item)
if w.show_labels.get()==1:
label['id']=self.label(pointing["camera"].ra,pointing["camera"].dec,label['text'])
pointing["items"]=items
pointing["label"]=label | python | def plot_pointings(self,pointings=None):
"""Plot pointings on canavs"""
if pointings is None:
pointings=self.pointings
i=0
for pointing in pointings:
items=[]
i=i+1
label={}
label['text']=pointing['label']['text']
for ccd in pointing["camera"].getGeometry():
(x1,y1)=self.p2c((ccd[0],ccd[1]))
(x2,y2)=self.p2c((ccd[2],ccd[3]))
item=self.create_rectangle(x1,y1,x2,y2,stipple='gray25',fill=pointing.get('color',''))
items.append(item)
if w.show_labels.get()==1:
label['id']=self.label(pointing["camera"].ra,pointing["camera"].dec,label['text'])
pointing["items"]=items
pointing["label"]=label | [
"def",
"plot_pointings",
"(",
"self",
",",
"pointings",
"=",
"None",
")",
":",
"if",
"pointings",
"is",
"None",
":",
"pointings",
"=",
"self",
".",
"pointings",
"i",
"=",
"0",
"for",
"pointing",
"in",
"pointings",
":",
"items",
"=",
"[",
"]",
"i",
"=... | Plot pointings on canavs | [
"Plot",
"pointings",
"on",
"canavs"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L735-L755 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.set_pointing_label | def set_pointing_label(self):
"""Let the label of the current pointing to the value in the plabel box"""
self.pointings[self.current]['label']['text']=w.plabel.get()
self.reset() | python | def set_pointing_label(self):
"""Let the label of the current pointing to the value in the plabel box"""
self.pointings[self.current]['label']['text']=w.plabel.get()
self.reset() | [
"def",
"set_pointing_label",
"(",
"self",
")",
":",
"self",
".",
"pointings",
"[",
"self",
".",
"current",
"]",
"[",
"'label'",
"]",
"[",
"'text'",
"]",
"=",
"w",
".",
"plabel",
".",
"get",
"(",
")",
"self",
".",
"reset",
"(",
")"
] | Let the label of the current pointing to the value in the plabel box | [
"Let",
"the",
"label",
"of",
"the",
"current",
"pointing",
"to",
"the",
"value",
"in",
"the",
"plabel",
"box"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L758-L762 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.save_pointings | def save_pointings(self):
"""Print the currently defined FOVs"""
import tkFileDialog
f=tkFileDialog.asksaveasfile()
i=0
if self.pointing_format.get()=='CFHT PH':
f.write("""<?xml version = "1.0"?>
<!DOCTYPE ASTRO SYSTEM "http://vizier.u-strasbg.fr/xml/astrores.dtd">
<ASTRO ID="v0.8" xmlns:ASTRO="http://vizier.u-strasbg.fr/doc/astrores.htx">
<TABLE ID="Table">
<NAME>Fixed Targets</NAME>
<TITLE>Fixed Targets for CFHT QSO</TITLE>
<!-- Definition of each field -->
<FIELD name="NAME" datatype="A" width="20">
<DESCRIPTION>Name of target</DESCRIPTION>
</FIELD>
<FIELD name="RA" ref="" datatype="A" width="11" unit=""h:m:s"">
<DESCRIPTION>Right ascension of target</DESCRIPTION>
</FIELD>
<FIELD name="DEC" ref="" datatype="A" width="11" unit=""d:m:s"">
<DESCRIPTION>Declination of target</DESCRIPTION>
</FIELD>
<FIELD name="EPOCH" datatype="F" width="6">
<DESCRIPTION>Epoch of coordinates</DESCRIPTION>
</FIELD>
<FIELD name="POINT" datatype="A" width="5">
<DESCRIPTION>Pointing name</DESCRIPTION>
</FIELD>
<!-- Data table -->
<DATA><CSV headlines="4" colsep="|"><![CDATA[
NAME |RA |DEC |EPOCH |POINT|
|hh:mm:ss.ss|+dd:mm:ss.s| | |
12345678901234567890|12345678901|12345678901|123456|12345|
--------------------|-----------|-----------|------|-----|\n""")
if self.pointing_format.get()=='Palomar':
f.write("index\n")
for pointing in self.pointings:
i=i+1
name=pointing["label"]["text"]
(sra,sdec)=str(pointing["camera"]).split()
ra=sra.split(":")
dec=sdec.split(":")
dec[0]=str(int(dec[0]))
if int(dec[0])>=0:
dec[0]='+'+dec[0]
if self.pointing_format.get()=='Palomar':
f.write( "%5d %16s %2s %2s %4s %3s %2s %4s 2000\n" % (i, name,
ra[0].zfill(2),
ra[1].zfill(2),
ra[2].zfill(2),
dec[0].zfill(3),
dec[1].zfill(2),
dec[2].zfill(2)))
elif self.pointing_format.get()=='CFHT PH':
#f.write("%f %f\n" % (pointing["camera"].ra,pointing["camera"].dec))
f.write("%-20s|%11s|%11s|%6.1f|%-5d|\n" % (name,sra,sdec,2000.0,1))
elif self.pointing_format.get()=='KPNO/CTIO':
str1 = sra.replace(":"," ")
str2 = sdec.replace(":"," ")
f.write("%16s %16s %16s 2000\n" % ( name, str1, str2) )
elif self.pointing_format.get()=='SSim':
ra = []
dec= []
for ccd in pointing["camera"].getGeometry():
ra.append(ccd[0])
ra.append(ccd[2])
dec.append(ccd[1])
dec.append(ccd[3])
import math
dra=math.degrees(math.fabs(max(ra)-min(ra)))
ddec=math.degrees(math.fabs(max(dec)-min(dec)))
f.write("%f %f %16s %16s DATE 1.00 1.00 500 FILE\n" % (dra, ddec, sra, sdec ) )
if self.pointing_format.get()=='CFHT PH':
f.write("""]]</CSV></DATA>
</TABLE>
</ASTRO>
""")
f.close() | python | def save_pointings(self):
"""Print the currently defined FOVs"""
import tkFileDialog
f=tkFileDialog.asksaveasfile()
i=0
if self.pointing_format.get()=='CFHT PH':
f.write("""<?xml version = "1.0"?>
<!DOCTYPE ASTRO SYSTEM "http://vizier.u-strasbg.fr/xml/astrores.dtd">
<ASTRO ID="v0.8" xmlns:ASTRO="http://vizier.u-strasbg.fr/doc/astrores.htx">
<TABLE ID="Table">
<NAME>Fixed Targets</NAME>
<TITLE>Fixed Targets for CFHT QSO</TITLE>
<!-- Definition of each field -->
<FIELD name="NAME" datatype="A" width="20">
<DESCRIPTION>Name of target</DESCRIPTION>
</FIELD>
<FIELD name="RA" ref="" datatype="A" width="11" unit=""h:m:s"">
<DESCRIPTION>Right ascension of target</DESCRIPTION>
</FIELD>
<FIELD name="DEC" ref="" datatype="A" width="11" unit=""d:m:s"">
<DESCRIPTION>Declination of target</DESCRIPTION>
</FIELD>
<FIELD name="EPOCH" datatype="F" width="6">
<DESCRIPTION>Epoch of coordinates</DESCRIPTION>
</FIELD>
<FIELD name="POINT" datatype="A" width="5">
<DESCRIPTION>Pointing name</DESCRIPTION>
</FIELD>
<!-- Data table -->
<DATA><CSV headlines="4" colsep="|"><![CDATA[
NAME |RA |DEC |EPOCH |POINT|
|hh:mm:ss.ss|+dd:mm:ss.s| | |
12345678901234567890|12345678901|12345678901|123456|12345|
--------------------|-----------|-----------|------|-----|\n""")
if self.pointing_format.get()=='Palomar':
f.write("index\n")
for pointing in self.pointings:
i=i+1
name=pointing["label"]["text"]
(sra,sdec)=str(pointing["camera"]).split()
ra=sra.split(":")
dec=sdec.split(":")
dec[0]=str(int(dec[0]))
if int(dec[0])>=0:
dec[0]='+'+dec[0]
if self.pointing_format.get()=='Palomar':
f.write( "%5d %16s %2s %2s %4s %3s %2s %4s 2000\n" % (i, name,
ra[0].zfill(2),
ra[1].zfill(2),
ra[2].zfill(2),
dec[0].zfill(3),
dec[1].zfill(2),
dec[2].zfill(2)))
elif self.pointing_format.get()=='CFHT PH':
#f.write("%f %f\n" % (pointing["camera"].ra,pointing["camera"].dec))
f.write("%-20s|%11s|%11s|%6.1f|%-5d|\n" % (name,sra,sdec,2000.0,1))
elif self.pointing_format.get()=='KPNO/CTIO':
str1 = sra.replace(":"," ")
str2 = sdec.replace(":"," ")
f.write("%16s %16s %16s 2000\n" % ( name, str1, str2) )
elif self.pointing_format.get()=='SSim':
ra = []
dec= []
for ccd in pointing["camera"].getGeometry():
ra.append(ccd[0])
ra.append(ccd[2])
dec.append(ccd[1])
dec.append(ccd[3])
import math
dra=math.degrees(math.fabs(max(ra)-min(ra)))
ddec=math.degrees(math.fabs(max(dec)-min(dec)))
f.write("%f %f %16s %16s DATE 1.00 1.00 500 FILE\n" % (dra, ddec, sra, sdec ) )
if self.pointing_format.get()=='CFHT PH':
f.write("""]]</CSV></DATA>
</TABLE>
</ASTRO>
""")
f.close() | [
"def",
"save_pointings",
"(",
"self",
")",
":",
"import",
"tkFileDialog",
"f",
"=",
"tkFileDialog",
".",
"asksaveasfile",
"(",
")",
"i",
"=",
"0",
"if",
"self",
".",
"pointing_format",
".",
"get",
"(",
")",
"==",
"'CFHT PH'",
":",
"f",
".",
"write",
"(... | Print the currently defined FOVs | [
"Print",
"the",
"currently",
"defined",
"FOVs"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L803-L881 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | camera.getGeometry | def getGeometry(self,ra=None,dec=None):
"""Return an array of rectangles that represent the 'ra,dec' corners of the FOV"""
import math,ephem
ccds=[]
if ra is None:
ra=self.ra
if dec is None:
dec=self.dec
self.ra=ephem.hours(ra)
self.dec=ephem.degrees(dec)
for geo in self.geometry[self.camera]:
ycen=math.radians(geo["dec"])+dec
xcen=math.radians(geo["ra"])/math.cos(ycen)+ra
dy=math.radians(geo["ddec"])
dx=math.radians(geo["dra"]/math.cos(ycen))
ccds.append([xcen-dx/2.0,ycen-dy/2.0,xcen+dx/2.0,ycen+dy/2.0])
return ccds | python | def getGeometry(self,ra=None,dec=None):
"""Return an array of rectangles that represent the 'ra,dec' corners of the FOV"""
import math,ephem
ccds=[]
if ra is None:
ra=self.ra
if dec is None:
dec=self.dec
self.ra=ephem.hours(ra)
self.dec=ephem.degrees(dec)
for geo in self.geometry[self.camera]:
ycen=math.radians(geo["dec"])+dec
xcen=math.radians(geo["ra"])/math.cos(ycen)+ra
dy=math.radians(geo["ddec"])
dx=math.radians(geo["dra"]/math.cos(ycen))
ccds.append([xcen-dx/2.0,ycen-dy/2.0,xcen+dx/2.0,ycen+dy/2.0])
return ccds | [
"def",
"getGeometry",
"(",
"self",
",",
"ra",
"=",
"None",
",",
"dec",
"=",
"None",
")",
":",
"import",
"math",
",",
"ephem",
"ccds",
"=",
"[",
"]",
"if",
"ra",
"is",
"None",
":",
"ra",
"=",
"self",
".",
"ra",
"if",
"dec",
"is",
"None",
":",
... | Return an array of rectangles that represent the 'ra,dec' corners of the FOV | [
"Return",
"an",
"array",
"of",
"rectangles",
"that",
"represent",
"the",
"ra",
"dec",
"corners",
"of",
"the",
"FOV"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L1017-L1036 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | camera.separation | def separation(self,ra,dec):
"""Compute the separation between self and (ra,dec)"""
import ephem
return ephem.separation((self.ra,self.dec),(ra,dec)) | python | def separation(self,ra,dec):
"""Compute the separation between self and (ra,dec)"""
import ephem
return ephem.separation((self.ra,self.dec),(ra,dec)) | [
"def",
"separation",
"(",
"self",
",",
"ra",
",",
"dec",
")",
":",
"import",
"ephem",
"return",
"ephem",
".",
"separation",
"(",
"(",
"self",
".",
"ra",
",",
"self",
".",
"dec",
")",
",",
"(",
"ra",
",",
"dec",
")",
")"
] | Compute the separation between self and (ra,dec) | [
"Compute",
"the",
"separation",
"between",
"self",
"and",
"(",
"ra",
"dec",
")"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L1039-L1043 |
JohnVinyard/zounds | examples/hamming_index.py | produce_fake_hash | def produce_fake_hash(x):
"""
Produce random, binary features, totally irrespective of the content of
x, but in the same shape as x.
"""
h = np.random.binomial(1, 0.5, (x.shape[0], 1024))
packed = np.packbits(h, axis=-1).view(np.uint64)
return zounds.ArrayWithUnits(
packed, [x.dimensions[0], zounds.IdentityDimension()]) | python | def produce_fake_hash(x):
"""
Produce random, binary features, totally irrespective of the content of
x, but in the same shape as x.
"""
h = np.random.binomial(1, 0.5, (x.shape[0], 1024))
packed = np.packbits(h, axis=-1).view(np.uint64)
return zounds.ArrayWithUnits(
packed, [x.dimensions[0], zounds.IdentityDimension()]) | [
"def",
"produce_fake_hash",
"(",
"x",
")",
":",
"h",
"=",
"np",
".",
"random",
".",
"binomial",
"(",
"1",
",",
"0.5",
",",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"1024",
")",
")",
"packed",
"=",
"np",
".",
"packbits",
"(",
"h",
",",
"axi... | Produce random, binary features, totally irrespective of the content of
x, but in the same shape as x. | [
"Produce",
"random",
"binary",
"features",
"totally",
"irrespective",
"of",
"the",
"content",
"of",
"x",
"but",
"in",
"the",
"same",
"shape",
"as",
"x",
"."
] | train | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/examples/hamming_index.py#L16-L24 |
openstack/python-scciclient | scciclient/irmc/ipmi.py | _parse_raw_bytes | def _parse_raw_bytes(raw_bytes):
"""Convert a string of hexadecimal values to decimal values parameters
Example: '0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00' is converted to:
46, 241, [128, 40, 0, 26, 1, 0]
:param raw_bytes: string of hexadecimal values
:returns: 3 decimal values
"""
bytes_list = [int(x, base=16) for x in raw_bytes.split()]
return bytes_list[0], bytes_list[1], bytes_list[2:] | python | def _parse_raw_bytes(raw_bytes):
"""Convert a string of hexadecimal values to decimal values parameters
Example: '0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00' is converted to:
46, 241, [128, 40, 0, 26, 1, 0]
:param raw_bytes: string of hexadecimal values
:returns: 3 decimal values
"""
bytes_list = [int(x, base=16) for x in raw_bytes.split()]
return bytes_list[0], bytes_list[1], bytes_list[2:] | [
"def",
"_parse_raw_bytes",
"(",
"raw_bytes",
")",
":",
"bytes_list",
"=",
"[",
"int",
"(",
"x",
",",
"base",
"=",
"16",
")",
"for",
"x",
"in",
"raw_bytes",
".",
"split",
"(",
")",
"]",
"return",
"bytes_list",
"[",
"0",
"]",
",",
"bytes_list",
"[",
... | Convert a string of hexadecimal values to decimal values parameters
Example: '0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00' is converted to:
46, 241, [128, 40, 0, 26, 1, 0]
:param raw_bytes: string of hexadecimal values
:returns: 3 decimal values | [
"Convert",
"a",
"string",
"of",
"hexadecimal",
"values",
"to",
"decimal",
"values",
"parameters"
] | train | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L47-L57 |
openstack/python-scciclient | scciclient/irmc/ipmi.py | _send_raw_command | def _send_raw_command(ipmicmd, raw_bytes):
"""Use IPMI command object to send raw ipmi command to BMC
:param ipmicmd: IPMI command object
:param raw_bytes: string of hexadecimal values. This is commonly used
for certain vendor specific commands.
:returns: dict -- The response from IPMI device
"""
netfn, command, data = _parse_raw_bytes(raw_bytes)
response = ipmicmd.raw_command(netfn, command, data=data)
return response | python | def _send_raw_command(ipmicmd, raw_bytes):
"""Use IPMI command object to send raw ipmi command to BMC
:param ipmicmd: IPMI command object
:param raw_bytes: string of hexadecimal values. This is commonly used
for certain vendor specific commands.
:returns: dict -- The response from IPMI device
"""
netfn, command, data = _parse_raw_bytes(raw_bytes)
response = ipmicmd.raw_command(netfn, command, data=data)
return response | [
"def",
"_send_raw_command",
"(",
"ipmicmd",
",",
"raw_bytes",
")",
":",
"netfn",
",",
"command",
",",
"data",
"=",
"_parse_raw_bytes",
"(",
"raw_bytes",
")",
"response",
"=",
"ipmicmd",
".",
"raw_command",
"(",
"netfn",
",",
"command",
",",
"data",
"=",
"d... | Use IPMI command object to send raw ipmi command to BMC
:param ipmicmd: IPMI command object
:param raw_bytes: string of hexadecimal values. This is commonly used
for certain vendor specific commands.
:returns: dict -- The response from IPMI device | [
"Use",
"IPMI",
"command",
"object",
"to",
"send",
"raw",
"ipmi",
"command",
"to",
"BMC"
] | train | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L60-L72 |
openstack/python-scciclient | scciclient/irmc/ipmi.py | get_tpm_status | def get_tpm_status(d_info):
"""Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status
"""
# note:
# Get TPM support status : ipmi cmd '0xF5', valid flags '0xC0'
#
# $ ipmitool raw 0x2E 0xF5 0x80 0x28 0x00 0x81 0xC0
#
# Raw response:
# 80 28 00 C0 C0: True
# 80 28 00 -- --: False (other values than 'C0 C0')
ipmicmd = ipmi_command.Command(bmc=d_info['irmc_address'],
userid=d_info['irmc_username'],
password=d_info['irmc_password'])
try:
response = _send_raw_command(ipmicmd, GET_TPM_STATUS)
if response['code'] != 0:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET TMP status",
'error': response.get('error')})
out = ' '.join('{:02X}'.format(x) for x in response['data'])
return out is not None and out[-5:] == 'C0 C0'
except ipmi_exception.IpmiException as e:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET TMP status", 'error': e}) | python | def get_tpm_status(d_info):
"""Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status
"""
# note:
# Get TPM support status : ipmi cmd '0xF5', valid flags '0xC0'
#
# $ ipmitool raw 0x2E 0xF5 0x80 0x28 0x00 0x81 0xC0
#
# Raw response:
# 80 28 00 C0 C0: True
# 80 28 00 -- --: False (other values than 'C0 C0')
ipmicmd = ipmi_command.Command(bmc=d_info['irmc_address'],
userid=d_info['irmc_username'],
password=d_info['irmc_password'])
try:
response = _send_raw_command(ipmicmd, GET_TPM_STATUS)
if response['code'] != 0:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET TMP status",
'error': response.get('error')})
out = ' '.join('{:02X}'.format(x) for x in response['data'])
return out is not None and out[-5:] == 'C0 C0'
except ipmi_exception.IpmiException as e:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET TMP status", 'error': e}) | [
"def",
"get_tpm_status",
"(",
"d_info",
")",
":",
"# note:",
"# Get TPM support status : ipmi cmd '0xF5', valid flags '0xC0'",
"#",
"# $ ipmitool raw 0x2E 0xF5 0x80 0x28 0x00 0x81 0xC0",
"#",
"# Raw response:",
"# 80 28 00 C0 C0: True",
"# 80 28 00 -- --: False (other values than 'C0 C0')"... | Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status | [
"Get",
"the",
"TPM",
"support",
"status",
"."
] | train | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L75-L109 |
openstack/python-scciclient | scciclient/irmc/ipmi.py | _pci_seq | def _pci_seq(ipmicmd):
"""Get output of ipmiraw command and the ordinal numbers.
:param ipmicmd: IPMI command object.
:returns: List of tuple contain ordinal number and output of ipmiraw
command.
"""
for i in range(1, 0xff + 1):
try:
res = _send_raw_command(ipmicmd, GET_PCI % hex(i))
yield i, res
except ipmi_exception.IpmiException as e:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET PCI device quantity", 'error': e}) | python | def _pci_seq(ipmicmd):
"""Get output of ipmiraw command and the ordinal numbers.
:param ipmicmd: IPMI command object.
:returns: List of tuple contain ordinal number and output of ipmiraw
command.
"""
for i in range(1, 0xff + 1):
try:
res = _send_raw_command(ipmicmd, GET_PCI % hex(i))
yield i, res
except ipmi_exception.IpmiException as e:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET PCI device quantity", 'error': e}) | [
"def",
"_pci_seq",
"(",
"ipmicmd",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"0xff",
"+",
"1",
")",
":",
"try",
":",
"res",
"=",
"_send_raw_command",
"(",
"ipmicmd",
",",
"GET_PCI",
"%",
"hex",
"(",
"i",
")",
")",
"yield",
"i",
",",
"... | Get output of ipmiraw command and the ordinal numbers.
:param ipmicmd: IPMI command object.
:returns: List of tuple contain ordinal number and output of ipmiraw
command. | [
"Get",
"output",
"of",
"ipmiraw",
"command",
"and",
"the",
"ordinal",
"numbers",
"."
] | train | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L112-L126 |
openstack/python-scciclient | scciclient/irmc/ipmi.py | get_pci_device | def get_pci_device(d_info, pci_device_ids):
"""Get quantity of PCI devices.
Get quantity of PCI devices of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:param pci_device_ids: the list contains pairs of <vendorID>/<deviceID> for
PCI devices.
:returns: the number of PCI devices.
"""
# note:
# Get quantity of PCI devices:
# ipmi cmd '0xF1'
#
# $ ipmitool raw 0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00
#
# Raw response:
# 80 28 00 00 00 05 data1 data2 34 17 76 11 00 04
# 01
# data1: 2 octet of VendorID
# data2: 2 octet of DeviceID
ipmicmd = ipmi_command.Command(bmc=d_info['irmc_address'],
userid=d_info['irmc_username'],
password=d_info['irmc_password'])
response = itertools.takewhile(
lambda y: (y[1]['code'] != 0xC9 and y[1].get('error') is None),
_pci_seq(ipmicmd))
def _pci_count(accm, v):
out = v[1]['data']
# if system returns value, record id will be increased.
pci_id = "0x{:02x}{:02x}/0x{:02x}{:02x}".format(
out[7], out[6], out[9], out[8])
return accm + 1 if pci_id in pci_device_ids else accm
device_count = functools.reduce(_pci_count, response, 0)
return device_count | python | def get_pci_device(d_info, pci_device_ids):
"""Get quantity of PCI devices.
Get quantity of PCI devices of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:param pci_device_ids: the list contains pairs of <vendorID>/<deviceID> for
PCI devices.
:returns: the number of PCI devices.
"""
# note:
# Get quantity of PCI devices:
# ipmi cmd '0xF1'
#
# $ ipmitool raw 0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00
#
# Raw response:
# 80 28 00 00 00 05 data1 data2 34 17 76 11 00 04
# 01
# data1: 2 octet of VendorID
# data2: 2 octet of DeviceID
ipmicmd = ipmi_command.Command(bmc=d_info['irmc_address'],
userid=d_info['irmc_username'],
password=d_info['irmc_password'])
response = itertools.takewhile(
lambda y: (y[1]['code'] != 0xC9 and y[1].get('error') is None),
_pci_seq(ipmicmd))
def _pci_count(accm, v):
out = v[1]['data']
# if system returns value, record id will be increased.
pci_id = "0x{:02x}{:02x}/0x{:02x}{:02x}".format(
out[7], out[6], out[9], out[8])
return accm + 1 if pci_id in pci_device_ids else accm
device_count = functools.reduce(_pci_count, response, 0)
return device_count | [
"def",
"get_pci_device",
"(",
"d_info",
",",
"pci_device_ids",
")",
":",
"# note:",
"# Get quantity of PCI devices:",
"# ipmi cmd '0xF1'",
"#",
"# $ ipmitool raw 0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00",
"#",
"# Raw response:",
"# 80 28 00 00 00 05 data1 data2 34 17 76 11 00 04",
"# ... | Get quantity of PCI devices.
Get quantity of PCI devices of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:param pci_device_ids: the list contains pairs of <vendorID>/<deviceID> for
PCI devices.
:returns: the number of PCI devices. | [
"Get",
"quantity",
"of",
"PCI",
"devices",
"."
] | train | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L129-L170 |
playpauseandstop/rororo | rororo/schemas/utils.py | defaults | def defaults(current: dict, *args: AnyMapping) -> dict:
r"""Override current dict with defaults values.
:param current: Current dict.
:param \*args: Sequence with default data dicts.
"""
for data in args:
for key, value in data.items():
current.setdefault(key, value)
return current | python | def defaults(current: dict, *args: AnyMapping) -> dict:
r"""Override current dict with defaults values.
:param current: Current dict.
:param \*args: Sequence with default data dicts.
"""
for data in args:
for key, value in data.items():
current.setdefault(key, value)
return current | [
"def",
"defaults",
"(",
"current",
":",
"dict",
",",
"*",
"args",
":",
"AnyMapping",
")",
"->",
"dict",
":",
"for",
"data",
"in",
"args",
":",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"current",
".",
"setdefault",
"(",... | r"""Override current dict with defaults values.
:param current: Current dict.
:param \*args: Sequence with default data dicts. | [
"r",
"Override",
"current",
"dict",
"with",
"defaults",
"values",
"."
] | train | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/utils.py#L17-L26 |
playpauseandstop/rororo | rororo/schemas/utils.py | validate_func_factory | def validate_func_factory(validator_class: Any) -> ValidateFunc:
"""Provide default function for Schema validation.
:param validator_class: JSONSchema suitable validator class.
"""
def validate_func(schema: AnyMapping, pure_data: AnyMapping) -> AnyMapping:
"""Validate schema with given data.
:param schema: Schema representation to use.
:param pure_data: Pure data to validate.
"""
return validator_class(schema).validate(pure_data)
return validate_func | python | def validate_func_factory(validator_class: Any) -> ValidateFunc:
"""Provide default function for Schema validation.
:param validator_class: JSONSchema suitable validator class.
"""
def validate_func(schema: AnyMapping, pure_data: AnyMapping) -> AnyMapping:
"""Validate schema with given data.
:param schema: Schema representation to use.
:param pure_data: Pure data to validate.
"""
return validator_class(schema).validate(pure_data)
return validate_func | [
"def",
"validate_func_factory",
"(",
"validator_class",
":",
"Any",
")",
"->",
"ValidateFunc",
":",
"def",
"validate_func",
"(",
"schema",
":",
"AnyMapping",
",",
"pure_data",
":",
"AnyMapping",
")",
"->",
"AnyMapping",
":",
"\"\"\"Validate schema with given data.\n\n... | Provide default function for Schema validation.
:param validator_class: JSONSchema suitable validator class. | [
"Provide",
"default",
"function",
"for",
"Schema",
"validation",
"."
] | train | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/utils.py#L29-L41 |
OSSOS/MOP | src/jjk/preproc/MOPdisplay.py | moreData | def moreData(ra,dec,box):
"""Search the CFHT archive for more images of this location"""
import cfhtCutout
cdata={'ra_deg': ra, 'dec_deg': dec, 'radius_deg': 0.2}
inter=cfhtCutout.find_images(cdata,0.2) | python | def moreData(ra,dec,box):
"""Search the CFHT archive for more images of this location"""
import cfhtCutout
cdata={'ra_deg': ra, 'dec_deg': dec, 'radius_deg': 0.2}
inter=cfhtCutout.find_images(cdata,0.2) | [
"def",
"moreData",
"(",
"ra",
",",
"dec",
",",
"box",
")",
":",
"import",
"cfhtCutout",
"cdata",
"=",
"{",
"'ra_deg'",
":",
"ra",
",",
"'dec_deg'",
":",
"dec",
",",
"'radius_deg'",
":",
"0.2",
"}",
"inter",
"=",
"cfhtCutout",
".",
"find_images",
"(",
... | Search the CFHT archive for more images of this location | [
"Search",
"the",
"CFHT",
"archive",
"for",
"more",
"images",
"of",
"this",
"location"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPdisplay.py#L33-L38 |
OSSOS/MOP | src/jjk/preproc/MOPdisplay.py | xpacheck | def xpacheck():
"""Check if xpa is running"""
import os
f=os.popen('xpaaccess ds9')
l=f.readline()
f.close()
if l.strip()!='yes':
logger.debug("\t Can't get ds9 access, xpaccess said: %s" % ( l.strip()))
return (False)
return(True) | python | def xpacheck():
"""Check if xpa is running"""
import os
f=os.popen('xpaaccess ds9')
l=f.readline()
f.close()
if l.strip()!='yes':
logger.debug("\t Can't get ds9 access, xpaccess said: %s" % ( l.strip()))
return (False)
return(True) | [
"def",
"xpacheck",
"(",
")",
":",
"import",
"os",
"f",
"=",
"os",
".",
"popen",
"(",
"'xpaaccess ds9'",
")",
"l",
"=",
"f",
".",
"readline",
"(",
")",
"f",
".",
"close",
"(",
")",
"if",
"l",
".",
"strip",
"(",
")",
"!=",
"'yes'",
":",
"logger",... | Check if xpa is running | [
"Check",
"if",
"xpa",
"is",
"running"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPdisplay.py#L40-L49 |
OSSOS/MOP | src/jjk/preproc/MOPdisplay.py | mark | def mark(x,y,label=None):
"""Mark a circle on the current image"""
if label is not None:
os.system("xpaset -p ds9 regions color red ")
cmd="echo 'image; text %d %d # text={%s}' | xpaset ds9 regions " % ( x,y,label)
else:
os.system("xpaset -p ds9 regions color blue")
cmd="echo 'image; circle %d %d 10 ' | xpaset ds9 regions " % (x,y)
os.system(cmd)
return | python | def mark(x,y,label=None):
"""Mark a circle on the current image"""
if label is not None:
os.system("xpaset -p ds9 regions color red ")
cmd="echo 'image; text %d %d # text={%s}' | xpaset ds9 regions " % ( x,y,label)
else:
os.system("xpaset -p ds9 regions color blue")
cmd="echo 'image; circle %d %d 10 ' | xpaset ds9 regions " % (x,y)
os.system(cmd)
return | [
"def",
"mark",
"(",
"x",
",",
"y",
",",
"label",
"=",
"None",
")",
":",
"if",
"label",
"is",
"not",
"None",
":",
"os",
".",
"system",
"(",
"\"xpaset -p ds9 regions color red \"",
")",
"cmd",
"=",
"\"echo 'image; text %d %d # text={%s}' | xpaset ds9 regions \"",
... | Mark a circle on the current image | [
"Mark",
"a",
"circle",
"on",
"the",
"current",
"image"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPdisplay.py#L72-L81 |
OSSOS/MOP | src/jjk/preproc/MOPdisplay.py | display | def display(url):
"""Display a file in ds9"""
import os
oscmd="curl --silent -g --fail --max-time 1800 --user jkavelaars '%s'" % (url)
logger.debug(oscmd)
os.system(oscmd+' | xpaset ds9 fits')
return | python | def display(url):
"""Display a file in ds9"""
import os
oscmd="curl --silent -g --fail --max-time 1800 --user jkavelaars '%s'" % (url)
logger.debug(oscmd)
os.system(oscmd+' | xpaset ds9 fits')
return | [
"def",
"display",
"(",
"url",
")",
":",
"import",
"os",
"oscmd",
"=",
"\"curl --silent -g --fail --max-time 1800 --user jkavelaars '%s'\"",
"%",
"(",
"url",
")",
"logger",
".",
"debug",
"(",
"oscmd",
")",
"os",
".",
"system",
"(",
"oscmd",
"+",
"' | xpaset ds9 f... | Display a file in ds9 | [
"Display",
"a",
"file",
"in",
"ds9"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPdisplay.py#L84-L90 |
eelregit/mcfit | mcfit/mcfit.py | mcfit.inv | def inv(self):
"""Invert the transform.
After calling this method, calling the instance will do the inverse
transform. Calling this twice return the instance to the original
transform.
"""
self.x, self.y = self.y, self.x
self._x_, self._y_ = self._y_, self._x_
self.xfac, self.yfac = 1 / self.yfac, 1 / self.xfac
self._xfac_, self._yfac_ = 1 / self._yfac_, 1 / self._xfac_
self._u = 1 / self._u.conj() | python | def inv(self):
"""Invert the transform.
After calling this method, calling the instance will do the inverse
transform. Calling this twice return the instance to the original
transform.
"""
self.x, self.y = self.y, self.x
self._x_, self._y_ = self._y_, self._x_
self.xfac, self.yfac = 1 / self.yfac, 1 / self.xfac
self._xfac_, self._yfac_ = 1 / self._yfac_, 1 / self._xfac_
self._u = 1 / self._u.conj() | [
"def",
"inv",
"(",
"self",
")",
":",
"self",
".",
"x",
",",
"self",
".",
"y",
"=",
"self",
".",
"y",
",",
"self",
".",
"x",
"self",
".",
"_x_",
",",
"self",
".",
"_y_",
"=",
"self",
".",
"_y_",
",",
"self",
".",
"_x_",
"self",
".",
"xfac",
... | Invert the transform.
After calling this method, calling the instance will do the inverse
transform. Calling this twice return the instance to the original
transform. | [
"Invert",
"the",
"transform",
"."
] | train | https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L248-L260 |
eelregit/mcfit | mcfit/mcfit.py | mcfit.matrix | def matrix(self, full=False, keeppads=True):
"""Return matrix form of the integral transform.
Parameters
----------
full : bool, optional
when False return two vector factors and convolution matrix
separately, otherwise return full transformation matrix
keeppads : bool, optional
whether to keep the padding in the output
Returns
-------
If full is False, output separately
a : (1, N) or (1, Nin) ndarray
"After" factor, `_yfac_` or `yfac`
b : (N,) or (Nin,) ndarray
"Before" factor, `_xfac_` or `xfac`
C : (N, N) or (Nin, Nin) ndarray
Convolution matrix, circulant
Otherwise, output the full matrix, combining `a`, `b`, and `C`
M : (N, N) or (Nin, Nin) ndarray
Full transformation matrix, `M = a * C * b`
Notes
-----
`M`, `a`, `b`, and `C` are padded by default. Pads can be discarded if
`keeppads` is set to False.
This is not meant for evaluation with matrix multiplication but in case
one is interested in the tranformation itself.
When `N` is even and `lowring` is False, :math:`C C^{-1}` and :math:`M
M^{-1}` can deviate from the identity matrix because the imaginary part
of the Nyquist modes are dropped.
The convolution matrix is a circulant matrix, with its first row and
first column being the Fourier transform of :math:`u_m`.
Indeed :math:`u_m` are the eigenvalues of the convolution matrix, that
are diagonalized by the DFT matrix.
Thus :math:`1/u_m` are the eigenvalues of the inverse convolution
matrix.
"""
v = np.fft.hfft(self._u, n=self.N) / self.N
idx = sum(np.ogrid[0:self.N, -self.N:0])
C = v[idx] # follow scipy.linalg.{circulant,toeplitz,hankel}
if keeppads:
a = self._yfac_.copy()
b = self._xfac_.copy()
else:
a = self.yfac.copy()
b = self.xfac.copy()
C = self._unpad(C, 0, True)
C = self._unpad(C, 1, False)
a = a.reshape(-1, 1)
if not full:
return a, b, C
else:
return a * C * b | python | def matrix(self, full=False, keeppads=True):
"""Return matrix form of the integral transform.
Parameters
----------
full : bool, optional
when False return two vector factors and convolution matrix
separately, otherwise return full transformation matrix
keeppads : bool, optional
whether to keep the padding in the output
Returns
-------
If full is False, output separately
a : (1, N) or (1, Nin) ndarray
"After" factor, `_yfac_` or `yfac`
b : (N,) or (Nin,) ndarray
"Before" factor, `_xfac_` or `xfac`
C : (N, N) or (Nin, Nin) ndarray
Convolution matrix, circulant
Otherwise, output the full matrix, combining `a`, `b`, and `C`
M : (N, N) or (Nin, Nin) ndarray
Full transformation matrix, `M = a * C * b`
Notes
-----
`M`, `a`, `b`, and `C` are padded by default. Pads can be discarded if
`keeppads` is set to False.
This is not meant for evaluation with matrix multiplication but in case
one is interested in the tranformation itself.
When `N` is even and `lowring` is False, :math:`C C^{-1}` and :math:`M
M^{-1}` can deviate from the identity matrix because the imaginary part
of the Nyquist modes are dropped.
The convolution matrix is a circulant matrix, with its first row and
first column being the Fourier transform of :math:`u_m`.
Indeed :math:`u_m` are the eigenvalues of the convolution matrix, that
are diagonalized by the DFT matrix.
Thus :math:`1/u_m` are the eigenvalues of the inverse convolution
matrix.
"""
v = np.fft.hfft(self._u, n=self.N) / self.N
idx = sum(np.ogrid[0:self.N, -self.N:0])
C = v[idx] # follow scipy.linalg.{circulant,toeplitz,hankel}
if keeppads:
a = self._yfac_.copy()
b = self._xfac_.copy()
else:
a = self.yfac.copy()
b = self.xfac.copy()
C = self._unpad(C, 0, True)
C = self._unpad(C, 1, False)
a = a.reshape(-1, 1)
if not full:
return a, b, C
else:
return a * C * b | [
"def",
"matrix",
"(",
"self",
",",
"full",
"=",
"False",
",",
"keeppads",
"=",
"True",
")",
":",
"v",
"=",
"np",
".",
"fft",
".",
"hfft",
"(",
"self",
".",
"_u",
",",
"n",
"=",
"self",
".",
"N",
")",
"/",
"self",
".",
"N",
"idx",
"=",
"sum"... | Return matrix form of the integral transform.
Parameters
----------
full : bool, optional
when False return two vector factors and convolution matrix
separately, otherwise return full transformation matrix
keeppads : bool, optional
whether to keep the padding in the output
Returns
-------
If full is False, output separately
a : (1, N) or (1, Nin) ndarray
"After" factor, `_yfac_` or `yfac`
b : (N,) or (Nin,) ndarray
"Before" factor, `_xfac_` or `xfac`
C : (N, N) or (Nin, Nin) ndarray
Convolution matrix, circulant
Otherwise, output the full matrix, combining `a`, `b`, and `C`
M : (N, N) or (Nin, Nin) ndarray
Full transformation matrix, `M = a * C * b`
Notes
-----
`M`, `a`, `b`, and `C` are padded by default. Pads can be discarded if
`keeppads` is set to False.
This is not meant for evaluation with matrix multiplication but in case
one is interested in the tranformation itself.
When `N` is even and `lowring` is False, :math:`C C^{-1}` and :math:`M
M^{-1}` can deviate from the identity matrix because the imaginary part
of the Nyquist modes are dropped.
The convolution matrix is a circulant matrix, with its first row and
first column being the Fourier transform of :math:`u_m`.
Indeed :math:`u_m` are the eigenvalues of the convolution matrix, that
are diagonalized by the DFT matrix.
Thus :math:`1/u_m` are the eigenvalues of the inverse convolution
matrix. | [
"Return",
"matrix",
"form",
"of",
"the",
"integral",
"transform",
"."
] | train | https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L263-L325 |
eelregit/mcfit | mcfit/mcfit.py | mcfit._pad | def _pad(self, a, axis, extrap, out):
"""Add padding to an array.
Parameters
----------
a : (..., Nin, ...) ndarray
array to be padded to size `N`
axis : int
axis along which to pad
extrap : {bool, 'const'} or 2-tuple
Method to extrapolate `a`.
For a 2-tuple, the two elements are for the left and right pads,
whereas a single value applies to both ends.
Options are:
* True: power-law extrapolation using the end segment
* False: zero padding
* 'const': constant padding with the end point value
out : bool
pad the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed
"""
assert a.shape[axis] == self.Nin
axis %= a.ndim # to fix the indexing below with axis+1
to_axis = [1] * a.ndim
to_axis[axis] = -1
Npad = self.N - self.Nin
if out:
_Npad, Npad_ = Npad - Npad//2, Npad//2
else:
_Npad, Npad_ = Npad//2, Npad - Npad//2
try:
_extrap, extrap_ = extrap
except (TypeError, ValueError):
_extrap = extrap_ = extrap
if isinstance(_extrap, bool):
if _extrap:
end = np.take(a, [0], axis=axis)
ratio = np.take(a, [1], axis=axis) / end
exp = np.arange(-_Npad, 0).reshape(to_axis)
_a = end * ratio ** exp
else:
_a = np.zeros(a.shape[:axis] + (_Npad,) + a.shape[axis+1:])
elif _extrap == 'const':
end = np.take(a, [0], axis=axis)
_a = np.repeat(end, _Npad, axis=axis)
else:
raise ValueError("left extrap not supported")
if isinstance(extrap_, bool):
if extrap_:
end = np.take(a, [-1], axis=axis)
ratio = end / np.take(a, [-2], axis=axis)
exp = np.arange(1, Npad_ + 1).reshape(to_axis)
a_ = end * ratio ** exp
else:
a_ = np.zeros(a.shape[:axis] + (Npad_,) + a.shape[axis+1:])
elif extrap_ == 'const':
end = np.take(a, [-1], axis=axis)
a_ = np.repeat(end, Npad_, axis=axis)
else:
raise ValueError("right extrap not supported")
return np.concatenate((_a, a, a_), axis=axis) | python | def _pad(self, a, axis, extrap, out):
"""Add padding to an array.
Parameters
----------
a : (..., Nin, ...) ndarray
array to be padded to size `N`
axis : int
axis along which to pad
extrap : {bool, 'const'} or 2-tuple
Method to extrapolate `a`.
For a 2-tuple, the two elements are for the left and right pads,
whereas a single value applies to both ends.
Options are:
* True: power-law extrapolation using the end segment
* False: zero padding
* 'const': constant padding with the end point value
out : bool
pad the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed
"""
assert a.shape[axis] == self.Nin
axis %= a.ndim # to fix the indexing below with axis+1
to_axis = [1] * a.ndim
to_axis[axis] = -1
Npad = self.N - self.Nin
if out:
_Npad, Npad_ = Npad - Npad//2, Npad//2
else:
_Npad, Npad_ = Npad//2, Npad - Npad//2
try:
_extrap, extrap_ = extrap
except (TypeError, ValueError):
_extrap = extrap_ = extrap
if isinstance(_extrap, bool):
if _extrap:
end = np.take(a, [0], axis=axis)
ratio = np.take(a, [1], axis=axis) / end
exp = np.arange(-_Npad, 0).reshape(to_axis)
_a = end * ratio ** exp
else:
_a = np.zeros(a.shape[:axis] + (_Npad,) + a.shape[axis+1:])
elif _extrap == 'const':
end = np.take(a, [0], axis=axis)
_a = np.repeat(end, _Npad, axis=axis)
else:
raise ValueError("left extrap not supported")
if isinstance(extrap_, bool):
if extrap_:
end = np.take(a, [-1], axis=axis)
ratio = end / np.take(a, [-2], axis=axis)
exp = np.arange(1, Npad_ + 1).reshape(to_axis)
a_ = end * ratio ** exp
else:
a_ = np.zeros(a.shape[:axis] + (Npad_,) + a.shape[axis+1:])
elif extrap_ == 'const':
end = np.take(a, [-1], axis=axis)
a_ = np.repeat(end, Npad_, axis=axis)
else:
raise ValueError("right extrap not supported")
return np.concatenate((_a, a, a_), axis=axis) | [
"def",
"_pad",
"(",
"self",
",",
"a",
",",
"axis",
",",
"extrap",
",",
"out",
")",
":",
"assert",
"a",
".",
"shape",
"[",
"axis",
"]",
"==",
"self",
".",
"Nin",
"axis",
"%=",
"a",
".",
"ndim",
"# to fix the indexing below with axis+1",
"to_axis",
"=",
... | Add padding to an array.
Parameters
----------
a : (..., Nin, ...) ndarray
array to be padded to size `N`
axis : int
axis along which to pad
extrap : {bool, 'const'} or 2-tuple
Method to extrapolate `a`.
For a 2-tuple, the two elements are for the left and right pads,
whereas a single value applies to both ends.
Options are:
* True: power-law extrapolation using the end segment
* False: zero padding
* 'const': constant padding with the end point value
out : bool
pad the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed | [
"Add",
"padding",
"to",
"an",
"array",
"."
] | train | https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L328-L395 |
eelregit/mcfit | mcfit/mcfit.py | mcfit._unpad | def _unpad(self, a, axis, out):
"""Undo padding in an array.
Parameters
----------
a : (..., N, ...) ndarray
array to be trimmed to size `Nin`
axis : int
axis along which to unpad
out : bool
trim the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed
"""
assert a.shape[axis] == self.N
Npad = self.N - self.Nin
if out:
_Npad, Npad_ = Npad - Npad//2, Npad//2
else:
_Npad, Npad_ = Npad//2, Npad - Npad//2
return np.take(a, range(_Npad, self.N - Npad_), axis=axis) | python | def _unpad(self, a, axis, out):
"""Undo padding in an array.
Parameters
----------
a : (..., N, ...) ndarray
array to be trimmed to size `Nin`
axis : int
axis along which to unpad
out : bool
trim the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed
"""
assert a.shape[axis] == self.N
Npad = self.N - self.Nin
if out:
_Npad, Npad_ = Npad - Npad//2, Npad//2
else:
_Npad, Npad_ = Npad//2, Npad - Npad//2
return np.take(a, range(_Npad, self.N - Npad_), axis=axis) | [
"def",
"_unpad",
"(",
"self",
",",
"a",
",",
"axis",
",",
"out",
")",
":",
"assert",
"a",
".",
"shape",
"[",
"axis",
"]",
"==",
"self",
".",
"N",
"Npad",
"=",
"self",
".",
"N",
"-",
"self",
".",
"Nin",
"if",
"out",
":",
"_Npad",
",",
"Npad_",... | Undo padding in an array.
Parameters
----------
a : (..., N, ...) ndarray
array to be trimmed to size `Nin`
axis : int
axis along which to unpad
out : bool
trim the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed | [
"Undo",
"padding",
"in",
"an",
"array",
"."
] | train | https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L398-L420 |
eelregit/mcfit | mcfit/mcfit.py | mcfit.check | def check(self, F):
"""Rough sanity checks on the input function.
"""
assert F.ndim == 1, "checker only supports 1D"
f = self.xfac * F
fabs = np.abs(f)
iQ1, iQ3 = np.searchsorted(fabs.cumsum(), np.array([0.25, 0.75]) * fabs.sum())
assert 0 != iQ1 != iQ3 != self.Nin, "checker giving up"
fabs_l = fabs[:iQ1].mean()
fabs_m = fabs[iQ1:iQ3].mean()
fabs_r = fabs[iQ3:].mean()
if fabs_l > fabs_m:
warnings.warn("left wing seems heavy: {:.2g} vs {:.2g}, "
"change tilt and mind convergence".format(fabs_l, fabs_m), RuntimeWarning)
if fabs_m < fabs_r:
warnings.warn("right wing seems heavy: {:.2g} vs {:.2g}, "
"change tilt and mind convergence".format(fabs_m, fabs_r), RuntimeWarning)
if fabs[0] > fabs[1]:
warnings.warn("left tail may blow up: {:.2g} vs {:.2g}, "
"change tilt or avoid extrapolation".format(f[0], f[1]), RuntimeWarning)
if fabs[-2] < fabs[-1]:
warnings.warn("right tail may blow up: {:.2g} vs {:.2g}, "
"change tilt or avoid extrapolation".format(f[-2], f[-1]), RuntimeWarning)
if f[0]*f[1] <= 0:
warnings.warn("left tail looks wiggly: {:.2g} vs {:.2g}, "
"avoid extrapolation".format(f[0], f[1]), RuntimeWarning)
if f[-2]*f[-1] <= 0:
warnings.warn("right tail looks wiggly: {:.2g} vs {:.2g}, "
"avoid extrapolation".format(f[-2], f[-1]), RuntimeWarning) | python | def check(self, F):
"""Rough sanity checks on the input function.
"""
assert F.ndim == 1, "checker only supports 1D"
f = self.xfac * F
fabs = np.abs(f)
iQ1, iQ3 = np.searchsorted(fabs.cumsum(), np.array([0.25, 0.75]) * fabs.sum())
assert 0 != iQ1 != iQ3 != self.Nin, "checker giving up"
fabs_l = fabs[:iQ1].mean()
fabs_m = fabs[iQ1:iQ3].mean()
fabs_r = fabs[iQ3:].mean()
if fabs_l > fabs_m:
warnings.warn("left wing seems heavy: {:.2g} vs {:.2g}, "
"change tilt and mind convergence".format(fabs_l, fabs_m), RuntimeWarning)
if fabs_m < fabs_r:
warnings.warn("right wing seems heavy: {:.2g} vs {:.2g}, "
"change tilt and mind convergence".format(fabs_m, fabs_r), RuntimeWarning)
if fabs[0] > fabs[1]:
warnings.warn("left tail may blow up: {:.2g} vs {:.2g}, "
"change tilt or avoid extrapolation".format(f[0], f[1]), RuntimeWarning)
if fabs[-2] < fabs[-1]:
warnings.warn("right tail may blow up: {:.2g} vs {:.2g}, "
"change tilt or avoid extrapolation".format(f[-2], f[-1]), RuntimeWarning)
if f[0]*f[1] <= 0:
warnings.warn("left tail looks wiggly: {:.2g} vs {:.2g}, "
"avoid extrapolation".format(f[0], f[1]), RuntimeWarning)
if f[-2]*f[-1] <= 0:
warnings.warn("right tail looks wiggly: {:.2g} vs {:.2g}, "
"avoid extrapolation".format(f[-2], f[-1]), RuntimeWarning) | [
"def",
"check",
"(",
"self",
",",
"F",
")",
":",
"assert",
"F",
".",
"ndim",
"==",
"1",
",",
"\"checker only supports 1D\"",
"f",
"=",
"self",
".",
"xfac",
"*",
"F",
"fabs",
"=",
"np",
".",
"abs",
"(",
"f",
")",
"iQ1",
",",
"iQ3",
"=",
"np",
".... | Rough sanity checks on the input function. | [
"Rough",
"sanity",
"checks",
"on",
"the",
"input",
"function",
"."
] | train | https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L423-L457 |
JohnVinyard/zounds | zounds/spectral/functional.py | fft | def fft(x, axis=-1, padding_samples=0):
"""
Apply an FFT along the given dimension, and with the specified amount of
zero-padding
Args:
x (ArrayWithUnits): an :class:`~zounds.core.ArrayWithUnits` instance
which has one or more :class:`~zounds.timeseries.TimeDimension`
axes
axis (int): The axis along which the fft should be applied
padding_samples (int): The number of padding zeros to apply along
axis before performing the FFT
"""
if padding_samples > 0:
padded = np.concatenate(
[x, np.zeros((len(x), padding_samples), dtype=x.dtype)],
axis=axis)
else:
padded = x
transformed = np.fft.rfft(padded, axis=axis, norm='ortho')
sr = audio_sample_rate(int(Seconds(1) / x.dimensions[axis].frequency))
scale = LinearScale.from_sample_rate(sr, transformed.shape[-1])
new_dimensions = list(x.dimensions)
new_dimensions[axis] = FrequencyDimension(scale)
return ArrayWithUnits(transformed, new_dimensions) | python | def fft(x, axis=-1, padding_samples=0):
"""
Apply an FFT along the given dimension, and with the specified amount of
zero-padding
Args:
x (ArrayWithUnits): an :class:`~zounds.core.ArrayWithUnits` instance
which has one or more :class:`~zounds.timeseries.TimeDimension`
axes
axis (int): The axis along which the fft should be applied
padding_samples (int): The number of padding zeros to apply along
axis before performing the FFT
"""
if padding_samples > 0:
padded = np.concatenate(
[x, np.zeros((len(x), padding_samples), dtype=x.dtype)],
axis=axis)
else:
padded = x
transformed = np.fft.rfft(padded, axis=axis, norm='ortho')
sr = audio_sample_rate(int(Seconds(1) / x.dimensions[axis].frequency))
scale = LinearScale.from_sample_rate(sr, transformed.shape[-1])
new_dimensions = list(x.dimensions)
new_dimensions[axis] = FrequencyDimension(scale)
return ArrayWithUnits(transformed, new_dimensions) | [
"def",
"fft",
"(",
"x",
",",
"axis",
"=",
"-",
"1",
",",
"padding_samples",
"=",
"0",
")",
":",
"if",
"padding_samples",
">",
"0",
":",
"padded",
"=",
"np",
".",
"concatenate",
"(",
"[",
"x",
",",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"x",
... | Apply an FFT along the given dimension, and with the specified amount of
zero-padding
Args:
x (ArrayWithUnits): an :class:`~zounds.core.ArrayWithUnits` instance
which has one or more :class:`~zounds.timeseries.TimeDimension`
axes
axis (int): The axis along which the fft should be applied
padding_samples (int): The number of padding zeros to apply along
axis before performing the FFT | [
"Apply",
"an",
"FFT",
"along",
"the",
"given",
"dimension",
"and",
"with",
"the",
"specified",
"amount",
"of",
"zero",
"-",
"padding"
] | train | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/functional.py#L20-L46 |
JohnVinyard/zounds | zounds/spectral/functional.py | morlet_filter_bank | def morlet_filter_bank(
samplerate,
kernel_size,
scale,
scaling_factor,
normalize=True):
"""
Create a :class:`~zounds.core.ArrayWithUnits` instance with a
:class:`~zounds.timeseries.TimeDimension` and a
:class:`~zounds.spectral.FrequencyDimension` representing a bank of morlet
wavelets centered on the sub-bands of the scale.
Args:
samplerate (SampleRate): the samplerate of the input signal
kernel_size (int): the length in samples of each filter
scale (FrequencyScale): a scale whose center frequencies determine the
fundamental frequency of each filer
scaling_factor (int or list of int): Scaling factors for each band,
which determine the time-frequency resolution tradeoff.
The number(s) should fall between 0 and 1, with smaller numbers
achieving better frequency resolution, and larget numbers better
time resolution
normalize (bool): When true, ensure that each filter in the bank
has unit norm
See Also:
:class:`~zounds.spectral.FrequencyScale`
:class:`~zounds.timeseries.SampleRate`
"""
basis_size = len(scale)
basis = np.zeros((basis_size, kernel_size), dtype=np.complex128)
try:
if len(scaling_factor) != len(scale):
raise ValueError('scaling factor must have same length as scale')
except TypeError:
scaling_factor = np.repeat(float(scaling_factor), len(scale))
sr = int(samplerate)
for i, band in enumerate(scale):
scaling = scaling_factor[i]
w = band.center_frequency / (scaling * 2 * sr / kernel_size)
basis[i] = morlet(
M=kernel_size,
w=w,
s=scaling)
basis = basis.real
if normalize:
basis /= np.linalg.norm(basis, axis=-1, keepdims=True) + 1e-8
basis = ArrayWithUnits(
basis, [FrequencyDimension(scale), TimeDimension(*samplerate)])
return basis | python | def morlet_filter_bank(
samplerate,
kernel_size,
scale,
scaling_factor,
normalize=True):
"""
Create a :class:`~zounds.core.ArrayWithUnits` instance with a
:class:`~zounds.timeseries.TimeDimension` and a
:class:`~zounds.spectral.FrequencyDimension` representing a bank of morlet
wavelets centered on the sub-bands of the scale.
Args:
samplerate (SampleRate): the samplerate of the input signal
kernel_size (int): the length in samples of each filter
scale (FrequencyScale): a scale whose center frequencies determine the
fundamental frequency of each filer
scaling_factor (int or list of int): Scaling factors for each band,
which determine the time-frequency resolution tradeoff.
The number(s) should fall between 0 and 1, with smaller numbers
achieving better frequency resolution, and larget numbers better
time resolution
normalize (bool): When true, ensure that each filter in the bank
has unit norm
See Also:
:class:`~zounds.spectral.FrequencyScale`
:class:`~zounds.timeseries.SampleRate`
"""
basis_size = len(scale)
basis = np.zeros((basis_size, kernel_size), dtype=np.complex128)
try:
if len(scaling_factor) != len(scale):
raise ValueError('scaling factor must have same length as scale')
except TypeError:
scaling_factor = np.repeat(float(scaling_factor), len(scale))
sr = int(samplerate)
for i, band in enumerate(scale):
scaling = scaling_factor[i]
w = band.center_frequency / (scaling * 2 * sr / kernel_size)
basis[i] = morlet(
M=kernel_size,
w=w,
s=scaling)
basis = basis.real
if normalize:
basis /= np.linalg.norm(basis, axis=-1, keepdims=True) + 1e-8
basis = ArrayWithUnits(
basis, [FrequencyDimension(scale), TimeDimension(*samplerate)])
return basis | [
"def",
"morlet_filter_bank",
"(",
"samplerate",
",",
"kernel_size",
",",
"scale",
",",
"scaling_factor",
",",
"normalize",
"=",
"True",
")",
":",
"basis_size",
"=",
"len",
"(",
"scale",
")",
"basis",
"=",
"np",
".",
"zeros",
"(",
"(",
"basis_size",
",",
... | Create a :class:`~zounds.core.ArrayWithUnits` instance with a
:class:`~zounds.timeseries.TimeDimension` and a
:class:`~zounds.spectral.FrequencyDimension` representing a bank of morlet
wavelets centered on the sub-bands of the scale.
Args:
samplerate (SampleRate): the samplerate of the input signal
kernel_size (int): the length in samples of each filter
scale (FrequencyScale): a scale whose center frequencies determine the
fundamental frequency of each filer
scaling_factor (int or list of int): Scaling factors for each band,
which determine the time-frequency resolution tradeoff.
The number(s) should fall between 0 and 1, with smaller numbers
achieving better frequency resolution, and larget numbers better
time resolution
normalize (bool): When true, ensure that each filter in the bank
has unit norm
See Also:
:class:`~zounds.spectral.FrequencyScale`
:class:`~zounds.timeseries.SampleRate` | [
"Create",
"a",
":",
"class",
":",
"~zounds",
".",
"core",
".",
"ArrayWithUnits",
"instance",
"with",
"a",
":",
"class",
":",
"~zounds",
".",
"timeseries",
".",
"TimeDimension",
"and",
"a",
":",
"class",
":",
"~zounds",
".",
"spectral",
".",
"FrequencyDimen... | train | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/functional.py#L271-L326 |
OSSOS/MOP | src/ossos/core/ossos/fitsviewer/colormap.py | GrayscaleColorMap.set_bias | def set_bias(self, bias):
"""
Adjusts the image bias.
Bias determines where the color changes start. At low bias, low
intensities (i.e., low pixel values) will have non-zero color
differences, while at high bias only high pixel values will have
non-zero differences
Args:
bias: float
A number between 0 and 1. Note that upon initialization the
colormap has a default bias of 0.5.
Returns: void
"""
self.x_offset += (bias - self._bias)
self._bias = bias
self._build_cdict() | python | def set_bias(self, bias):
"""
Adjusts the image bias.
Bias determines where the color changes start. At low bias, low
intensities (i.e., low pixel values) will have non-zero color
differences, while at high bias only high pixel values will have
non-zero differences
Args:
bias: float
A number between 0 and 1. Note that upon initialization the
colormap has a default bias of 0.5.
Returns: void
"""
self.x_offset += (bias - self._bias)
self._bias = bias
self._build_cdict() | [
"def",
"set_bias",
"(",
"self",
",",
"bias",
")",
":",
"self",
".",
"x_offset",
"+=",
"(",
"bias",
"-",
"self",
".",
"_bias",
")",
"self",
".",
"_bias",
"=",
"bias",
"self",
".",
"_build_cdict",
"(",
")"
] | Adjusts the image bias.
Bias determines where the color changes start. At low bias, low
intensities (i.e., low pixel values) will have non-zero color
differences, while at high bias only high pixel values will have
non-zero differences
Args:
bias: float
A number between 0 and 1. Note that upon initialization the
colormap has a default bias of 0.5.
Returns: void | [
"Adjusts",
"the",
"image",
"bias",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/fitsviewer/colormap.py#L59-L78 |
OSSOS/MOP | src/ossos/core/ossos/fitsviewer/colormap.py | GrayscaleColorMap.set_contrast | def set_contrast(self, contrast):
"""
Adjusts the image contrast.
Contrast refers to the rate of change of color with color level.
At low contrast, color changes gradually over many intensity
levels, while at high contrast it can change rapidly within a
few levels
Args:
contrast: float
A number between 0 and 1. Note that upon initialization the
colormap has a default contrast value of 0.5.
Returns: void
"""
self._contrast = contrast
self.x_spread = 2 * (1.0 - contrast)
self.y_spread = 2.0 - 2 * (1.0 - contrast)
self._build_cdict() | python | def set_contrast(self, contrast):
"""
Adjusts the image contrast.
Contrast refers to the rate of change of color with color level.
At low contrast, color changes gradually over many intensity
levels, while at high contrast it can change rapidly within a
few levels
Args:
contrast: float
A number between 0 and 1. Note that upon initialization the
colormap has a default contrast value of 0.5.
Returns: void
"""
self._contrast = contrast
self.x_spread = 2 * (1.0 - contrast)
self.y_spread = 2.0 - 2 * (1.0 - contrast)
self._build_cdict() | [
"def",
"set_contrast",
"(",
"self",
",",
"contrast",
")",
":",
"self",
".",
"_contrast",
"=",
"contrast",
"self",
".",
"x_spread",
"=",
"2",
"*",
"(",
"1.0",
"-",
"contrast",
")",
"self",
".",
"y_spread",
"=",
"2.0",
"-",
"2",
"*",
"(",
"1.0",
"-",... | Adjusts the image contrast.
Contrast refers to the rate of change of color with color level.
At low contrast, color changes gradually over many intensity
levels, while at high contrast it can change rapidly within a
few levels
Args:
contrast: float
A number between 0 and 1. Note that upon initialization the
colormap has a default contrast value of 0.5.
Returns: void | [
"Adjusts",
"the",
"image",
"contrast",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/fitsviewer/colormap.py#L83-L104 |
Accelize/pycosio | pycosio/_core/functions_shutil.py | _copy | def _copy(src, dst, src_is_storage, dst_is_storage):
"""
Copies file from source to destination
Args:
src (str or file-like object): Source file.
dst (str or file-like object): Destination file.
src_is_storage (bool): Source is storage.
dst_is_storage (bool): Destination is storage.
"""
# If both storage: Tries to perform same storage direct copy
if src_is_storage and dst_is_storage:
system_src = get_instance(src)
system_dst = get_instance(dst)
# Same storage copy
if system_src is system_dst:
# Checks if same file
if system_src.relpath(src) == system_dst.relpath(dst):
raise same_file_error(
"'%s' and '%s' are the same file" % (src, dst))
# Tries to copy
try:
return system_dst.copy(src, dst)
except (UnsupportedOperation, ObjectException):
pass
# Copy from compatible storage using "copy_from_<src_storage>" or
# "copy_to_<src_storage>" method if any
for caller, called, method in (
(system_dst, system_src, 'copy_from_%s'),
(system_src, system_dst, 'copy_to_%s')):
if hasattr(caller, method % called.storage):
try:
return getattr(caller, method % called.storage)(
src, dst, called)
except (UnsupportedOperation, ObjectException):
continue
# At least one storage object: copies streams
with cos_open(src, 'rb') as fsrc:
with cos_open(dst, 'wb') as fdst:
# Get stream buffer size
for stream in (fsrc, fdst):
try:
buffer_size = getattr(stream, '_buffer_size')
break
except AttributeError:
continue
else:
buffer_size = COPY_BUFSIZE
# Read and write
copyfileobj(fsrc, fdst, buffer_size) | python | def _copy(src, dst, src_is_storage, dst_is_storage):
"""
Copies file from source to destination
Args:
src (str or file-like object): Source file.
dst (str or file-like object): Destination file.
src_is_storage (bool): Source is storage.
dst_is_storage (bool): Destination is storage.
"""
# If both storage: Tries to perform same storage direct copy
if src_is_storage and dst_is_storage:
system_src = get_instance(src)
system_dst = get_instance(dst)
# Same storage copy
if system_src is system_dst:
# Checks if same file
if system_src.relpath(src) == system_dst.relpath(dst):
raise same_file_error(
"'%s' and '%s' are the same file" % (src, dst))
# Tries to copy
try:
return system_dst.copy(src, dst)
except (UnsupportedOperation, ObjectException):
pass
# Copy from compatible storage using "copy_from_<src_storage>" or
# "copy_to_<src_storage>" method if any
for caller, called, method in (
(system_dst, system_src, 'copy_from_%s'),
(system_src, system_dst, 'copy_to_%s')):
if hasattr(caller, method % called.storage):
try:
return getattr(caller, method % called.storage)(
src, dst, called)
except (UnsupportedOperation, ObjectException):
continue
# At least one storage object: copies streams
with cos_open(src, 'rb') as fsrc:
with cos_open(dst, 'wb') as fdst:
# Get stream buffer size
for stream in (fsrc, fdst):
try:
buffer_size = getattr(stream, '_buffer_size')
break
except AttributeError:
continue
else:
buffer_size = COPY_BUFSIZE
# Read and write
copyfileobj(fsrc, fdst, buffer_size) | [
"def",
"_copy",
"(",
"src",
",",
"dst",
",",
"src_is_storage",
",",
"dst_is_storage",
")",
":",
"# If both storage: Tries to perform same storage direct copy",
"if",
"src_is_storage",
"and",
"dst_is_storage",
":",
"system_src",
"=",
"get_instance",
"(",
"src",
")",
"s... | Copies file from source to destination
Args:
src (str or file-like object): Source file.
dst (str or file-like object): Destination file.
src_is_storage (bool): Source is storage.
dst_is_storage (bool): Destination is storage. | [
"Copies",
"file",
"from",
"source",
"to",
"destination"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_shutil.py#L17-L73 |
Accelize/pycosio | pycosio/_core/functions_shutil.py | copy | def copy(src, dst):
"""
Copies a source file to a destination file or directory.
Equivalent to "shutil.copy".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object):
Destination file or directory.
Raises:
IOError: Destination directory not found.
"""
# Handles path-like objects and checks if storage
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
# Local files: Redirects to "shutil.copy"
if not src_is_storage and not dst_is_storage:
return shutil_copy(src, dst)
with handle_os_exceptions():
# Checks destination
if not hasattr(dst, 'read'):
try:
# If destination is directory: defines an output file inside it
if isdir(dst):
dst = join(dst, basename(src))
# Checks if destination dir exists
elif not isdir(dirname(dst)):
raise IOError("No such file or directory: '%s'" % dst)
except ObjectPermissionError:
# Unable to check target directory due to missing read access,
# but do not raise to allow to write if possible
pass
# Performs copy
_copy(src, dst, src_is_storage, dst_is_storage) | python | def copy(src, dst):
"""
Copies a source file to a destination file or directory.
Equivalent to "shutil.copy".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object):
Destination file or directory.
Raises:
IOError: Destination directory not found.
"""
# Handles path-like objects and checks if storage
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
# Local files: Redirects to "shutil.copy"
if not src_is_storage and not dst_is_storage:
return shutil_copy(src, dst)
with handle_os_exceptions():
# Checks destination
if not hasattr(dst, 'read'):
try:
# If destination is directory: defines an output file inside it
if isdir(dst):
dst = join(dst, basename(src))
# Checks if destination dir exists
elif not isdir(dirname(dst)):
raise IOError("No such file or directory: '%s'" % dst)
except ObjectPermissionError:
# Unable to check target directory due to missing read access,
# but do not raise to allow to write if possible
pass
# Performs copy
_copy(src, dst, src_is_storage, dst_is_storage) | [
"def",
"copy",
"(",
"src",
",",
"dst",
")",
":",
"# Handles path-like objects and checks if storage",
"src",
",",
"src_is_storage",
"=",
"format_and_is_storage",
"(",
"src",
")",
"dst",
",",
"dst_is_storage",
"=",
"format_and_is_storage",
"(",
"dst",
")",
"# Local f... | Copies a source file to a destination file or directory.
Equivalent to "shutil.copy".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object):
Destination file or directory.
Raises:
IOError: Destination directory not found. | [
"Copies",
"a",
"source",
"file",
"to",
"a",
"destination",
"file",
"or",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_shutil.py#L76-L118 |
Accelize/pycosio | pycosio/_core/functions_shutil.py | copyfile | def copyfile(src, dst, follow_symlinks=True):
"""
Copies a source file to a destination file.
Equivalent to "shutil.copyfile".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object): Destination file.
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Raises:
IOError: Destination directory not found.
"""
# Handles path-like objects and checks if storage
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
# Local files: Redirects to "shutil.copyfile"
if not src_is_storage and not dst_is_storage:
return shutil_copyfile(src, dst, follow_symlinks=follow_symlinks)
with handle_os_exceptions():
# Checks destination
try:
if not hasattr(dst, 'read') and not isdir(dirname(dst)):
raise IOError("No such file or directory: '%s'" % dst)
except ObjectPermissionError:
# Unable to check target directory due to missing read access, but
# do not raise to allow to write if possible
pass
# Performs copy
_copy(src, dst, src_is_storage, dst_is_storage) | python | def copyfile(src, dst, follow_symlinks=True):
"""
Copies a source file to a destination file.
Equivalent to "shutil.copyfile".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object): Destination file.
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Raises:
IOError: Destination directory not found.
"""
# Handles path-like objects and checks if storage
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
# Local files: Redirects to "shutil.copyfile"
if not src_is_storage and not dst_is_storage:
return shutil_copyfile(src, dst, follow_symlinks=follow_symlinks)
with handle_os_exceptions():
# Checks destination
try:
if not hasattr(dst, 'read') and not isdir(dirname(dst)):
raise IOError("No such file or directory: '%s'" % dst)
except ObjectPermissionError:
# Unable to check target directory due to missing read access, but
# do not raise to allow to write if possible
pass
# Performs copy
_copy(src, dst, src_is_storage, dst_is_storage) | [
"def",
"copyfile",
"(",
"src",
",",
"dst",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"# Handles path-like objects and checks if storage",
"src",
",",
"src_is_storage",
"=",
"format_and_is_storage",
"(",
"src",
")",
"dst",
",",
"dst_is_storage",
"=",
"format_and... | Copies a source file to a destination file.
Equivalent to "shutil.copyfile".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object): Destination file.
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Raises:
IOError: Destination directory not found. | [
"Copies",
"a",
"source",
"file",
"to",
"a",
"destination",
"file",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_shutil.py#L121-L158 |
Accelize/pycosio | pycosio/storage/s3.py | _handle_client_error | def _handle_client_error():
"""
Handle boto exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _ClientError as exception:
error = exception.response['Error']
if error['Code'] in _ERROR_CODES:
raise _ERROR_CODES[error['Code']](error['Message'])
raise | python | def _handle_client_error():
"""
Handle boto exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _ClientError as exception:
error = exception.response['Error']
if error['Code'] in _ERROR_CODES:
raise _ERROR_CODES[error['Code']](error['Message'])
raise | [
"def",
"_handle_client_error",
"(",
")",
":",
"try",
":",
"yield",
"except",
"_ClientError",
"as",
"exception",
":",
"error",
"=",
"exception",
".",
"response",
"[",
"'Error'",
"]",
"if",
"error",
"[",
"'Code'",
"]",
"in",
"_ERROR_CODES",
":",
"raise",
"_E... | Handle boto exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error. | [
"Handle",
"boto",
"exception",
"and",
"convert",
"to",
"class",
"IO",
"exceptions"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L29-L44 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System.copy | def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
"""
copy_source = self.get_client_kwargs(src)
copy_destination = self.get_client_kwargs(dst)
with _handle_client_error():
self.client.copy_object(CopySource=copy_source, **copy_destination) | python | def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
"""
copy_source = self.get_client_kwargs(src)
copy_destination = self.get_client_kwargs(dst)
with _handle_client_error():
self.client.copy_object(CopySource=copy_source, **copy_destination) | [
"def",
"copy",
"(",
"self",
",",
"src",
",",
"dst",
",",
"other_system",
"=",
"None",
")",
":",
"copy_source",
"=",
"self",
".",
"get_client_kwargs",
"(",
"src",
")",
"copy_destination",
"=",
"self",
".",
"get_client_kwargs",
"(",
"dst",
")",
"with",
"_h... | Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused. | [
"Copy",
"object",
"of",
"the",
"same",
"storage",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L70-L82 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System.get_client_kwargs | def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
"""
bucket_name, key = self.split_locator(path)
kwargs = dict(Bucket=bucket_name)
if key:
kwargs['Key'] = key
return kwargs | python | def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
"""
bucket_name, key = self.split_locator(path)
kwargs = dict(Bucket=bucket_name)
if key:
kwargs['Key'] = key
return kwargs | [
"def",
"get_client_kwargs",
"(",
"self",
",",
"path",
")",
":",
"bucket_name",
",",
"key",
"=",
"self",
".",
"split_locator",
"(",
"path",
")",
"kwargs",
"=",
"dict",
"(",
"Bucket",
"=",
"bucket_name",
")",
"if",
"key",
":",
"kwargs",
"[",
"'Key'",
"]"... | Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args | [
"Get",
"base",
"keyword",
"arguments",
"for",
"client",
"for",
"a",
"specific",
"path",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L84-L99 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._get_session | def _get_session(self):
"""
S3 Boto3 Session.
Returns:
boto3.session.Session: session
"""
if self._session is None:
self._session = _boto3.session.Session(
**self._storage_parameters.get('session', dict()))
return self._session | python | def _get_session(self):
"""
S3 Boto3 Session.
Returns:
boto3.session.Session: session
"""
if self._session is None:
self._session = _boto3.session.Session(
**self._storage_parameters.get('session', dict()))
return self._session | [
"def",
"_get_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"None",
":",
"self",
".",
"_session",
"=",
"_boto3",
".",
"session",
".",
"Session",
"(",
"*",
"*",
"self",
".",
"_storage_parameters",
".",
"get",
"(",
"'session'",
","... | S3 Boto3 Session.
Returns:
boto3.session.Session: session | [
"S3",
"Boto3",
"Session",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L101-L111 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._get_client | def _get_client(self):
"""
S3 Boto3 client
Returns:
boto3.session.Session.client: client
"""
client_kwargs = self._storage_parameters.get('client', dict())
# Handles unsecure mode
if self._unsecure:
client_kwargs = client_kwargs.copy()
client_kwargs['use_ssl'] = False
return self._get_session().client("s3", **client_kwargs) | python | def _get_client(self):
"""
S3 Boto3 client
Returns:
boto3.session.Session.client: client
"""
client_kwargs = self._storage_parameters.get('client', dict())
# Handles unsecure mode
if self._unsecure:
client_kwargs = client_kwargs.copy()
client_kwargs['use_ssl'] = False
return self._get_session().client("s3", **client_kwargs) | [
"def",
"_get_client",
"(",
"self",
")",
":",
"client_kwargs",
"=",
"self",
".",
"_storage_parameters",
".",
"get",
"(",
"'client'",
",",
"dict",
"(",
")",
")",
"# Handles unsecure mode",
"if",
"self",
".",
"_unsecure",
":",
"client_kwargs",
"=",
"client_kwargs... | S3 Boto3 client
Returns:
boto3.session.Session.client: client | [
"S3",
"Boto3",
"client"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L113-L127 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._get_roots | def _get_roots(self):
"""
Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots
"""
region = self._get_session().region_name or r'[\w-]+'
return (
# S3 scheme
# - s3://<bucket>/<key>
's3://',
# Virtual-hostedβstyle URL
# - http://<bucket>.s3.amazonaws.com/<key>
# - https://<bucket>.s3.amazonaws.com/<key>
# - http://<bucket>.s3-<region>.amazonaws.com/<key>
# - https://<bucket>.s3-<region>.amazonaws.com/<key>
_re.compile(r'https?://[\w.-]+\.s3\.amazonaws\.com'),
_re.compile(
r'https?://[\w.-]+\.s3-%s\.amazonaws\.com' % region),
# Path-hostedβstyle URL
# - http://s3.amazonaws.com/<bucket>/<key>
# - https://s3.amazonaws.com/<bucket>/<key>
# - http://s3-<region>.amazonaws.com/<bucket>/<key>
# - https://s3-<region>.amazonaws.com/<bucket>/<key>
_re.compile(r'https?://s3\.amazonaws\.com'),
_re.compile(r'https?://s3-%s\.amazonaws\.com' % region),
# Transfer acceleration URL
# - http://<bucket>.s3-accelerate.amazonaws.com
# - https://<bucket>.s3-accelerate.amazonaws.com
# - http://<bucket>.s3-accelerate.dualstack.amazonaws.com
# - https://<bucket>.s3-accelerate.dualstack.amazonaws.com
_re.compile(
r'https?://[\w.-]+\.s3-accelerate\.amazonaws\.com'),
_re.compile(
r'https?://[\w.-]+\.s3-accelerate\.dualstack'
r'\.amazonaws\.com')) | python | def _get_roots(self):
"""
Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots
"""
region = self._get_session().region_name or r'[\w-]+'
return (
# S3 scheme
# - s3://<bucket>/<key>
's3://',
# Virtual-hostedβstyle URL
# - http://<bucket>.s3.amazonaws.com/<key>
# - https://<bucket>.s3.amazonaws.com/<key>
# - http://<bucket>.s3-<region>.amazonaws.com/<key>
# - https://<bucket>.s3-<region>.amazonaws.com/<key>
_re.compile(r'https?://[\w.-]+\.s3\.amazonaws\.com'),
_re.compile(
r'https?://[\w.-]+\.s3-%s\.amazonaws\.com' % region),
# Path-hostedβstyle URL
# - http://s3.amazonaws.com/<bucket>/<key>
# - https://s3.amazonaws.com/<bucket>/<key>
# - http://s3-<region>.amazonaws.com/<bucket>/<key>
# - https://s3-<region>.amazonaws.com/<bucket>/<key>
_re.compile(r'https?://s3\.amazonaws\.com'),
_re.compile(r'https?://s3-%s\.amazonaws\.com' % region),
# Transfer acceleration URL
# - http://<bucket>.s3-accelerate.amazonaws.com
# - https://<bucket>.s3-accelerate.amazonaws.com
# - http://<bucket>.s3-accelerate.dualstack.amazonaws.com
# - https://<bucket>.s3-accelerate.dualstack.amazonaws.com
_re.compile(
r'https?://[\w.-]+\.s3-accelerate\.amazonaws\.com'),
_re.compile(
r'https?://[\w.-]+\.s3-accelerate\.dualstack'
r'\.amazonaws\.com')) | [
"def",
"_get_roots",
"(",
"self",
")",
":",
"region",
"=",
"self",
".",
"_get_session",
"(",
")",
".",
"region_name",
"or",
"r'[\\w-]+'",
"return",
"(",
"# S3 scheme",
"# - s3://<bucket>/<key>",
"'s3://'",
",",
"# Virtual-hostedβstyle URL",
"# - http://<bucket>.s3.ama... | Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots | [
"Return",
"URL",
"roots",
"for",
"this",
"storage",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L129-L168 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._get_time | def _get_time(header, keys, name):
"""
Get time from header
Args:
header (dict): Object header.
keys (tuple of str): Header keys.
name (str): Method name.
Returns:
float: The number of seconds since the epoch
"""
for key in keys:
try:
return _to_timestamp(header.pop(key))
except KeyError:
continue
raise _UnsupportedOperation(name) | python | def _get_time(header, keys, name):
"""
Get time from header
Args:
header (dict): Object header.
keys (tuple of str): Header keys.
name (str): Method name.
Returns:
float: The number of seconds since the epoch
"""
for key in keys:
try:
return _to_timestamp(header.pop(key))
except KeyError:
continue
raise _UnsupportedOperation(name) | [
"def",
"_get_time",
"(",
"header",
",",
"keys",
",",
"name",
")",
":",
"for",
"key",
"in",
"keys",
":",
"try",
":",
"return",
"_to_timestamp",
"(",
"header",
".",
"pop",
"(",
"key",
")",
")",
"except",
"KeyError",
":",
"continue",
"raise",
"_Unsupporte... | Get time from header
Args:
header (dict): Object header.
keys (tuple of str): Header keys.
name (str): Method name.
Returns:
float: The number of seconds since the epoch | [
"Get",
"time",
"from",
"header"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L171-L188 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._head | def _head(self, client_kwargs):
"""
Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
header = self.client.head_object(**client_kwargs)
# Bucket
else:
header = self.client.head_bucket(**client_kwargs)
# Clean up HTTP request information
for key in ('AcceptRanges', 'ResponseMetadata'):
header.pop(key, None)
return header | python | def _head(self, client_kwargs):
"""
Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
header = self.client.head_object(**client_kwargs)
# Bucket
else:
header = self.client.head_bucket(**client_kwargs)
# Clean up HTTP request information
for key in ('AcceptRanges', 'ResponseMetadata'):
header.pop(key, None)
return header | [
"def",
"_head",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_client_error",
"(",
")",
":",
"# Object",
"if",
"'Key'",
"in",
"client_kwargs",
":",
"header",
"=",
"self",
".",
"client",
".",
"head_object",
"(",
"*",
"*",
"client_kwargs",
")"... | Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header. | [
"Returns",
"object",
"or",
"bucket",
"HTTP",
"header",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L205-L227 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._make_dir | def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
return self.client.put_object(Body=b'', **client_kwargs)
# Bucket
return self.client.create_bucket(
Bucket=client_kwargs['Bucket'],
CreateBucketConfiguration=dict(
LocationConstraint=self._get_session().region_name)) | python | def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
return self.client.put_object(Body=b'', **client_kwargs)
# Bucket
return self.client.create_bucket(
Bucket=client_kwargs['Bucket'],
CreateBucketConfiguration=dict(
LocationConstraint=self._get_session().region_name)) | [
"def",
"_make_dir",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_client_error",
"(",
")",
":",
"# Object",
"if",
"'Key'",
"in",
"client_kwargs",
":",
"return",
"self",
".",
"client",
".",
"put_object",
"(",
"Body",
"=",
"b''",
",",
"*",
... | Make a directory.
args:
client_kwargs (dict): Client arguments. | [
"Make",
"a",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L229-L245 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._remove | def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
return self.client.delete_object(**client_kwargs)
# Bucket
return self.client.delete_bucket(Bucket=client_kwargs['Bucket']) | python | def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
return self.client.delete_object(**client_kwargs)
# Bucket
return self.client.delete_bucket(Bucket=client_kwargs['Bucket']) | [
"def",
"_remove",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_client_error",
"(",
")",
":",
"# Object",
"if",
"'Key'",
"in",
"client_kwargs",
":",
"return",
"self",
".",
"client",
".",
"delete_object",
"(",
"*",
"*",
"client_kwargs",
")",
... | Remove an object.
args:
client_kwargs (dict): Client arguments. | [
"Remove",
"an",
"object",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L247-L260 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._list_locators | def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_client_error():
response = self.client.list_buckets()
for bucket in response['Buckets']:
yield bucket.pop('Name'), bucket | python | def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_client_error():
response = self.client.list_buckets()
for bucket in response['Buckets']:
yield bucket.pop('Name'), bucket | [
"def",
"_list_locators",
"(",
"self",
")",
":",
"with",
"_handle_client_error",
"(",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"list_buckets",
"(",
")",
"for",
"bucket",
"in",
"response",
"[",
"'Buckets'",
"]",
":",
"yield",
"bucket",
".",
"... | Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | [
"Lists",
"locators",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L262-L273 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._list_objects | def _list_objects(self, client_kwargs, path, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict
"""
client_kwargs = client_kwargs.copy()
if max_request_entries:
client_kwargs['MaxKeys'] = max_request_entries
while True:
with _handle_client_error():
response = self.client.list_objects_v2(
Prefix=path, **client_kwargs)
try:
for obj in response['Contents']:
yield obj.pop('Key'), obj
except KeyError:
raise _ObjectNotFoundError('Not found: %s' % path)
# Handles results on more than one page
try:
client_kwargs['ContinuationToken'] = response[
'NextContinuationToken']
except KeyError:
# End of results
break | python | def _list_objects(self, client_kwargs, path, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict
"""
client_kwargs = client_kwargs.copy()
if max_request_entries:
client_kwargs['MaxKeys'] = max_request_entries
while True:
with _handle_client_error():
response = self.client.list_objects_v2(
Prefix=path, **client_kwargs)
try:
for obj in response['Contents']:
yield obj.pop('Key'), obj
except KeyError:
raise _ObjectNotFoundError('Not found: %s' % path)
# Handles results on more than one page
try:
client_kwargs['ContinuationToken'] = response[
'NextContinuationToken']
except KeyError:
# End of results
break | [
"def",
"_list_objects",
"(",
"self",
",",
"client_kwargs",
",",
"path",
",",
"max_request_entries",
")",
":",
"client_kwargs",
"=",
"client_kwargs",
".",
"copy",
"(",
")",
"if",
"max_request_entries",
":",
"client_kwargs",
"[",
"'MaxKeys'",
"]",
"=",
"max_reques... | Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict | [
"Lists",
"objects",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L275-L309 |
Accelize/pycosio | pycosio/storage/s3.py | S3RawIO._read_range | def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
# Get object part from S3
try:
with _handle_client_error():
response = self._client.get_object(
Range=self._http_range(start, end), **self._client_kwargs)
# Check for end of file
except _ClientError as exception:
if exception.response['Error']['Code'] == 'InvalidRange':
# EOF
return bytes()
raise
# Get object content
return response['Body'].read() | python | def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
# Get object part from S3
try:
with _handle_client_error():
response = self._client.get_object(
Range=self._http_range(start, end), **self._client_kwargs)
# Check for end of file
except _ClientError as exception:
if exception.response['Error']['Code'] == 'InvalidRange':
# EOF
return bytes()
raise
# Get object content
return response['Body'].read() | [
"def",
"_read_range",
"(",
"self",
",",
"start",
",",
"end",
"=",
"0",
")",
":",
"# Get object part from S3",
"try",
":",
"with",
"_handle_client_error",
"(",
")",
":",
"response",
"=",
"self",
".",
"_client",
".",
"get_object",
"(",
"Range",
"=",
"self",
... | Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read | [
"Read",
"a",
"range",
"of",
"bytes",
"in",
"stream",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L331-L357 |
Accelize/pycosio | pycosio/storage/s3.py | S3RawIO._flush | def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
with _handle_client_error():
self._client.put_object(
Body=buffer.tobytes(), **self._client_kwargs) | python | def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
with _handle_client_error():
self._client.put_object(
Body=buffer.tobytes(), **self._client_kwargs) | [
"def",
"_flush",
"(",
"self",
",",
"buffer",
")",
":",
"with",
"_handle_client_error",
"(",
")",
":",
"self",
".",
"_client",
".",
"put_object",
"(",
"Body",
"=",
"buffer",
".",
"tobytes",
"(",
")",
",",
"*",
"*",
"self",
".",
"_client_kwargs",
")"
] | Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"if",
"applicable",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L369-L378 |
Accelize/pycosio | pycosio/storage/s3.py | S3BufferedIO._flush | def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Initialize multi-part upload
if 'UploadId' not in self._upload_args:
with _handle_client_error():
self._upload_args[
'UploadId'] = self._client.create_multipart_upload(
**self._client_kwargs)['UploadId']
# Upload part with workers
response = self._workers.submit(
self._client.upload_part, Body=self._get_buffer().tobytes(),
PartNumber=self._seek, **self._upload_args)
# Save part information
self._write_futures.append(
dict(response=response, PartNumber=self._seek)) | python | def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Initialize multi-part upload
if 'UploadId' not in self._upload_args:
with _handle_client_error():
self._upload_args[
'UploadId'] = self._client.create_multipart_upload(
**self._client_kwargs)['UploadId']
# Upload part with workers
response = self._workers.submit(
self._client.upload_part, Body=self._get_buffer().tobytes(),
PartNumber=self._seek, **self._upload_args)
# Save part information
self._write_futures.append(
dict(response=response, PartNumber=self._seek)) | [
"def",
"_flush",
"(",
"self",
")",
":",
"# Initialize multi-part upload",
"if",
"'UploadId'",
"not",
"in",
"self",
".",
"_upload_args",
":",
"with",
"_handle_client_error",
"(",
")",
":",
"self",
".",
"_upload_args",
"[",
"'UploadId'",
"]",
"=",
"self",
".",
... | Flush the write buffers of the stream. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L416-L434 |
Accelize/pycosio | pycosio/storage/s3.py | S3BufferedIO._close_writable | def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait parts upload completion
for part in self._write_futures:
part['ETag'] = part.pop('response').result()['ETag']
# Complete multipart upload
with _handle_client_error():
try:
self._client.complete_multipart_upload(
MultipartUpload={'Parts': self._write_futures},
UploadId=self._upload_args['UploadId'],
**self._client_kwargs)
except _ClientError:
# Clean up if failure
self._client.abort_multipart_upload(
UploadId=self._upload_args['UploadId'],
**self._client_kwargs)
raise | python | def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait parts upload completion
for part in self._write_futures:
part['ETag'] = part.pop('response').result()['ETag']
# Complete multipart upload
with _handle_client_error():
try:
self._client.complete_multipart_upload(
MultipartUpload={'Parts': self._write_futures},
UploadId=self._upload_args['UploadId'],
**self._client_kwargs)
except _ClientError:
# Clean up if failure
self._client.abort_multipart_upload(
UploadId=self._upload_args['UploadId'],
**self._client_kwargs)
raise | [
"def",
"_close_writable",
"(",
"self",
")",
":",
"# Wait parts upload completion",
"for",
"part",
"in",
"self",
".",
"_write_futures",
":",
"part",
"[",
"'ETag'",
"]",
"=",
"part",
".",
"pop",
"(",
"'response'",
")",
".",
"result",
"(",
")",
"[",
"'ETag'",... | Close the object in write mode. | [
"Close",
"the",
"object",
"in",
"write",
"mode",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L436-L456 |
Accelize/pycosio | pycosio/storage/azure.py | _handle_azure_exception | def _handle_azure_exception():
"""
Handles Azure exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _AzureHttpError as exception:
if exception.status_code in _ERROR_CODES:
raise _ERROR_CODES[exception.status_code](str(exception))
raise | python | def _handle_azure_exception():
"""
Handles Azure exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _AzureHttpError as exception:
if exception.status_code in _ERROR_CODES:
raise _ERROR_CODES[exception.status_code](str(exception))
raise | [
"def",
"_handle_azure_exception",
"(",
")",
":",
"try",
":",
"yield",
"except",
"_AzureHttpError",
"as",
"exception",
":",
"if",
"exception",
".",
"status_code",
"in",
"_ERROR_CODES",
":",
"raise",
"_ERROR_CODES",
"[",
"exception",
".",
"status_code",
"]",
"(",
... | Handles Azure exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error. | [
"Handles",
"Azure",
"exception",
"and",
"convert",
"to",
"class",
"IO",
"exceptions"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L32-L45 |
Accelize/pycosio | pycosio/storage/azure.py | _properties_model_to_dict | def _properties_model_to_dict(properties):
"""
Convert properties model to dict.
Args:
properties: Properties model.
Returns:
dict: Converted model.
"""
result = {}
for attr in properties.__dict__:
value = getattr(properties, attr)
if hasattr(value, '__module__') and 'models' in value.__module__:
value = _properties_model_to_dict(value)
if not (value is None or (isinstance(value, dict) and not value)):
result[attr] = value
return result | python | def _properties_model_to_dict(properties):
"""
Convert properties model to dict.
Args:
properties: Properties model.
Returns:
dict: Converted model.
"""
result = {}
for attr in properties.__dict__:
value = getattr(properties, attr)
if hasattr(value, '__module__') and 'models' in value.__module__:
value = _properties_model_to_dict(value)
if not (value is None or (isinstance(value, dict) and not value)):
result[attr] = value
return result | [
"def",
"_properties_model_to_dict",
"(",
"properties",
")",
":",
"result",
"=",
"{",
"}",
"for",
"attr",
"in",
"properties",
".",
"__dict__",
":",
"value",
"=",
"getattr",
"(",
"properties",
",",
"attr",
")",
"if",
"hasattr",
"(",
"value",
",",
"'__module_... | Convert properties model to dict.
Args:
properties: Properties model.
Returns:
dict: Converted model. | [
"Convert",
"properties",
"model",
"to",
"dict",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L48-L68 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureBaseSystem._get_endpoint | def _get_endpoint(self, sub_domain):
"""
Get endpoint information from storage parameters.
Update system with endpoint information and return information required
to define roots.
Args:
self (pycosio._core.io_system.SystemBase subclass): System.
sub_domain (str): Azure storage sub-domain.
Returns:
tuple of str: account_name, endpoint_suffix
"""
storage_parameters = self._storage_parameters or dict()
account_name = storage_parameters.get('account_name')
if not account_name:
raise ValueError('"account_name" is required for Azure storage')
suffix = storage_parameters.get(
'endpoint_suffix', 'core.windows.net')
self._endpoint = 'http%s://%s.%s.%s' % (
'' if self._unsecure else 's', account_name, sub_domain, suffix)
return account_name, suffix.replace('.', r'\.') | python | def _get_endpoint(self, sub_domain):
"""
Get endpoint information from storage parameters.
Update system with endpoint information and return information required
to define roots.
Args:
self (pycosio._core.io_system.SystemBase subclass): System.
sub_domain (str): Azure storage sub-domain.
Returns:
tuple of str: account_name, endpoint_suffix
"""
storage_parameters = self._storage_parameters or dict()
account_name = storage_parameters.get('account_name')
if not account_name:
raise ValueError('"account_name" is required for Azure storage')
suffix = storage_parameters.get(
'endpoint_suffix', 'core.windows.net')
self._endpoint = 'http%s://%s.%s.%s' % (
'' if self._unsecure else 's', account_name, sub_domain, suffix)
return account_name, suffix.replace('.', r'\.') | [
"def",
"_get_endpoint",
"(",
"self",
",",
"sub_domain",
")",
":",
"storage_parameters",
"=",
"self",
".",
"_storage_parameters",
"or",
"dict",
"(",
")",
"account_name",
"=",
"storage_parameters",
".",
"get",
"(",
"'account_name'",
")",
"if",
"not",
"account_name... | Get endpoint information from storage parameters.
Update system with endpoint information and return information required
to define roots.
Args:
self (pycosio._core.io_system.SystemBase subclass): System.
sub_domain (str): Azure storage sub-domain.
Returns:
tuple of str: account_name, endpoint_suffix | [
"Get",
"endpoint",
"information",
"from",
"storage",
"parameters",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L112-L138 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureBaseSystem._secured_storage_parameters | def _secured_storage_parameters(self):
"""
Updates storage parameters with unsecure mode.
Returns:
dict: Updated storage_parameters.
"""
parameters = self._storage_parameters or dict()
# Handles unsecure mode
if self._unsecure:
parameters = parameters.copy()
parameters['protocol'] = 'http'
return parameters | python | def _secured_storage_parameters(self):
"""
Updates storage parameters with unsecure mode.
Returns:
dict: Updated storage_parameters.
"""
parameters = self._storage_parameters or dict()
# Handles unsecure mode
if self._unsecure:
parameters = parameters.copy()
parameters['protocol'] = 'http'
return parameters | [
"def",
"_secured_storage_parameters",
"(",
"self",
")",
":",
"parameters",
"=",
"self",
".",
"_storage_parameters",
"or",
"dict",
"(",
")",
"# Handles unsecure mode",
"if",
"self",
".",
"_unsecure",
":",
"parameters",
"=",
"parameters",
".",
"copy",
"(",
")",
... | Updates storage parameters with unsecure mode.
Returns:
dict: Updated storage_parameters. | [
"Updates",
"storage",
"parameters",
"with",
"unsecure",
"mode",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L140-L154 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureBaseSystem._format_src_url | def _format_src_url(self, path, caller_system):
"""
Ensure path is absolute and use the correct URL format for use with
cross Azure storage account copy function.
Args:
path (str): Path or URL.
caller_system (pycosio.storage.azure._AzureBaseSystem subclass):
System calling this method (Can be another Azure system).
Returns:
str: URL.
"""
path = '%s/%s' % (self._endpoint, self.relpath(path))
# If SAS token available, use it to give cross account copy access.
if caller_system is not self:
try:
path = '%s?%s' % (path, self._storage_parameters['sas_token'])
except KeyError:
pass
return path | python | def _format_src_url(self, path, caller_system):
"""
Ensure path is absolute and use the correct URL format for use with
cross Azure storage account copy function.
Args:
path (str): Path or URL.
caller_system (pycosio.storage.azure._AzureBaseSystem subclass):
System calling this method (Can be another Azure system).
Returns:
str: URL.
"""
path = '%s/%s' % (self._endpoint, self.relpath(path))
# If SAS token available, use it to give cross account copy access.
if caller_system is not self:
try:
path = '%s?%s' % (path, self._storage_parameters['sas_token'])
except KeyError:
pass
return path | [
"def",
"_format_src_url",
"(",
"self",
",",
"path",
",",
"caller_system",
")",
":",
"path",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"_endpoint",
",",
"self",
".",
"relpath",
"(",
"path",
")",
")",
"# If SAS token available, use it to give cross account copy access.... | Ensure path is absolute and use the correct URL format for use with
cross Azure storage account copy function.
Args:
path (str): Path or URL.
caller_system (pycosio.storage.azure._AzureBaseSystem subclass):
System calling this method (Can be another Azure system).
Returns:
str: URL. | [
"Ensure",
"path",
"is",
"absolute",
"and",
"use",
"the",
"correct",
"URL",
"format",
"for",
"use",
"with",
"cross",
"Azure",
"storage",
"account",
"copy",
"function",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L156-L178 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureBaseSystem._update_listing_client_kwargs | def _update_listing_client_kwargs(client_kwargs, max_request_entries):
"""
Updates client kwargs for listing functions.
Args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
dict: Updated client_kwargs
"""
client_kwargs = client_kwargs.copy()
if max_request_entries:
client_kwargs['num_results'] = max_request_entries
return client_kwargs | python | def _update_listing_client_kwargs(client_kwargs, max_request_entries):
"""
Updates client kwargs for listing functions.
Args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
dict: Updated client_kwargs
"""
client_kwargs = client_kwargs.copy()
if max_request_entries:
client_kwargs['num_results'] = max_request_entries
return client_kwargs | [
"def",
"_update_listing_client_kwargs",
"(",
"client_kwargs",
",",
"max_request_entries",
")",
":",
"client_kwargs",
"=",
"client_kwargs",
".",
"copy",
"(",
")",
"if",
"max_request_entries",
":",
"client_kwargs",
"[",
"'num_results'",
"]",
"=",
"max_request_entries",
... | Updates client kwargs for listing functions.
Args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
dict: Updated client_kwargs | [
"Updates",
"client",
"kwargs",
"for",
"listing",
"functions",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L181-L196 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureBaseSystem._model_to_dict | def _model_to_dict(obj):
"""
Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model.
"""
result = _properties_model_to_dict(obj.properties)
for attribute in ('metadata', 'snapshot'):
try:
value = getattr(obj, attribute)
except AttributeError:
continue
if value:
result[attribute] = value
return result | python | def _model_to_dict(obj):
"""
Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model.
"""
result = _properties_model_to_dict(obj.properties)
for attribute in ('metadata', 'snapshot'):
try:
value = getattr(obj, attribute)
except AttributeError:
continue
if value:
result[attribute] = value
return result | [
"def",
"_model_to_dict",
"(",
"obj",
")",
":",
"result",
"=",
"_properties_model_to_dict",
"(",
"obj",
".",
"properties",
")",
"for",
"attribute",
"in",
"(",
"'metadata'",
",",
"'snapshot'",
")",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
... | Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model. | [
"Convert",
"object",
"model",
"to",
"dict",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L199-L217 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureStorageRawIOBase._read_range | def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
stream = _BytesIO()
try:
with _handle_azure_exception():
self._get_to_stream(
stream=stream, start_range=start,
end_range=(end - 1) if end else None, **self._client_kwargs)
# Check for end of file
except _AzureHttpError as exception:
if exception.status_code == 416:
# EOF
return bytes()
raise
return stream.getvalue() | python | def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
stream = _BytesIO()
try:
with _handle_azure_exception():
self._get_to_stream(
stream=stream, start_range=start,
end_range=(end - 1) if end else None, **self._client_kwargs)
# Check for end of file
except _AzureHttpError as exception:
if exception.status_code == 416:
# EOF
return bytes()
raise
return stream.getvalue() | [
"def",
"_read_range",
"(",
"self",
",",
"start",
",",
"end",
"=",
"0",
")",
":",
"stream",
"=",
"_BytesIO",
"(",
")",
"try",
":",
"with",
"_handle_azure_exception",
"(",
")",
":",
"self",
".",
"_get_to_stream",
"(",
"stream",
"=",
"stream",
",",
"start... | Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read | [
"Read",
"a",
"range",
"of",
"bytes",
"in",
"stream",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L235-L261 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureStorageRawIOBase._readall | def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
stream = _BytesIO()
with _handle_azure_exception():
self._get_to_stream(stream=stream, **self._client_kwargs)
return stream.getvalue() | python | def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
stream = _BytesIO()
with _handle_azure_exception():
self._get_to_stream(stream=stream, **self._client_kwargs)
return stream.getvalue() | [
"def",
"_readall",
"(",
"self",
")",
":",
"stream",
"=",
"_BytesIO",
"(",
")",
"with",
"_handle_azure_exception",
"(",
")",
":",
"self",
".",
"_get_to_stream",
"(",
"stream",
"=",
"stream",
",",
"*",
"*",
"self",
".",
"_client_kwargs",
")",
"return",
"st... | Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content | [
"Read",
"and",
"return",
"all",
"the",
"bytes",
"from",
"the",
"stream",
"until",
"EOF",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L263-L273 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureStorageRawIORangeWriteBase._init_append | def _init_append(self):
"""
Initializes file on 'a' mode.
"""
if self._content_length:
# Adjust size if content length specified
with _handle_azure_exception():
self._resize(
content_length=self._content_length, **self._client_kwargs)
self._reset_head()
# Make initial seek position to current end of file
self._seek = self._size | python | def _init_append(self):
"""
Initializes file on 'a' mode.
"""
if self._content_length:
# Adjust size if content length specified
with _handle_azure_exception():
self._resize(
content_length=self._content_length, **self._client_kwargs)
self._reset_head()
# Make initial seek position to current end of file
self._seek = self._size | [
"def",
"_init_append",
"(",
"self",
")",
":",
"if",
"self",
".",
"_content_length",
":",
"# Adjust size if content length specified",
"with",
"_handle_azure_exception",
"(",
")",
":",
"self",
".",
"_resize",
"(",
"content_length",
"=",
"self",
".",
"_content_length"... | Initializes file on 'a' mode. | [
"Initializes",
"file",
"on",
"a",
"mode",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L317-L329 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureStorageRawIORangeWriteBase._create | def _create(self):
"""
Create the file if not exists.
"""
# Create new file
with _handle_azure_exception():
self._create_from_size(
content_length=self._content_length, **self._client_kwargs) | python | def _create(self):
"""
Create the file if not exists.
"""
# Create new file
with _handle_azure_exception():
self._create_from_size(
content_length=self._content_length, **self._client_kwargs) | [
"def",
"_create",
"(",
"self",
")",
":",
"# Create new file",
"with",
"_handle_azure_exception",
"(",
")",
":",
"self",
".",
"_create_from_size",
"(",
"content_length",
"=",
"self",
".",
"_content_length",
",",
"*",
"*",
"self",
".",
"_client_kwargs",
")"
] | Create the file if not exists. | [
"Create",
"the",
"file",
"if",
"not",
"exists",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L331-L338 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureStorageRawIORangeWriteBase._flush | def _flush(self, buffer, start, end):
"""
Flush the write buffer of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
Supported only with page blobs.
end (int): End of buffer position to flush.
Supported only with page blobs.
"""
buffer_size = len(buffer)
if not buffer_size:
return
# Write range normally
with self._size_lock:
if end > self._size:
# Require to resize the blob if note enough space
with _handle_azure_exception():
self._resize(content_length=end, **self._client_kwargs)
self._reset_head()
if buffer_size > self.MAX_FLUSH_SIZE:
# Too large buffer, needs to split in multiples requests
futures = []
for part_start in range(0, buffer_size, self.MAX_FLUSH_SIZE):
# Split buffer
buffer_part = buffer[
part_start:part_start + self.MAX_FLUSH_SIZE]
if not len(buffer_part):
# No more data
break
# Upload split buffer in parallel
start_range = start + part_start
futures.append(self._workers.submit(
self._update_range, data=buffer_part.tobytes(),
start_range=start_range,
end_range=start_range + len(buffer_part) - 1,
**self._client_kwargs))
with _handle_azure_exception():
# Wait for upload completion
for future in _as_completed(futures):
future.result()
else:
# Buffer lower than limit, do one requests.
with _handle_azure_exception():
self._update_range(
data=buffer.tobytes(), start_range=start,
end_range=end - 1, **self._client_kwargs) | python | def _flush(self, buffer, start, end):
"""
Flush the write buffer of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
Supported only with page blobs.
end (int): End of buffer position to flush.
Supported only with page blobs.
"""
buffer_size = len(buffer)
if not buffer_size:
return
# Write range normally
with self._size_lock:
if end > self._size:
# Require to resize the blob if note enough space
with _handle_azure_exception():
self._resize(content_length=end, **self._client_kwargs)
self._reset_head()
if buffer_size > self.MAX_FLUSH_SIZE:
# Too large buffer, needs to split in multiples requests
futures = []
for part_start in range(0, buffer_size, self.MAX_FLUSH_SIZE):
# Split buffer
buffer_part = buffer[
part_start:part_start + self.MAX_FLUSH_SIZE]
if not len(buffer_part):
# No more data
break
# Upload split buffer in parallel
start_range = start + part_start
futures.append(self._workers.submit(
self._update_range, data=buffer_part.tobytes(),
start_range=start_range,
end_range=start_range + len(buffer_part) - 1,
**self._client_kwargs))
with _handle_azure_exception():
# Wait for upload completion
for future in _as_completed(futures):
future.result()
else:
# Buffer lower than limit, do one requests.
with _handle_azure_exception():
self._update_range(
data=buffer.tobytes(), start_range=start,
end_range=end - 1, **self._client_kwargs) | [
"def",
"_flush",
"(",
"self",
",",
"buffer",
",",
"start",
",",
"end",
")",
":",
"buffer_size",
"=",
"len",
"(",
"buffer",
")",
"if",
"not",
"buffer_size",
":",
"return",
"# Write range normally",
"with",
"self",
".",
"_size_lock",
":",
"if",
"end",
">",... | Flush the write buffer of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
Supported only with page blobs.
end (int): End of buffer position to flush.
Supported only with page blobs. | [
"Flush",
"the",
"write",
"buffer",
"of",
"the",
"stream",
"if",
"applicable",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L349-L402 |
Accelize/pycosio | pycosio/_core/io_base.py | memoizedmethod | def memoizedmethod(method):
"""
Decorator that caches method result.
Args:
method (function): Method
Returns:
function: Memoized method.
Notes:
Target method class needs as "_cache" attribute (dict).
It is the case of "ObjectIOBase" and all its subclasses.
"""
method_name = method.__name__
@wraps(method)
def patched(self, *args, **kwargs):
"""Patched method"""
# Gets value from cache
try:
return self._cache[method_name]
# Evaluates and cache value
except KeyError:
result = self._cache[method_name] = method(
self, *args, **kwargs)
return result
return patched | python | def memoizedmethod(method):
"""
Decorator that caches method result.
Args:
method (function): Method
Returns:
function: Memoized method.
Notes:
Target method class needs as "_cache" attribute (dict).
It is the case of "ObjectIOBase" and all its subclasses.
"""
method_name = method.__name__
@wraps(method)
def patched(self, *args, **kwargs):
"""Patched method"""
# Gets value from cache
try:
return self._cache[method_name]
# Evaluates and cache value
except KeyError:
result = self._cache[method_name] = method(
self, *args, **kwargs)
return result
return patched | [
"def",
"memoizedmethod",
"(",
"method",
")",
":",
"method_name",
"=",
"method",
".",
"__name__",
"@",
"wraps",
"(",
"method",
")",
"def",
"patched",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Patched method\"\"\"",
"# Gets val... | Decorator that caches method result.
Args:
method (function): Method
Returns:
function: Memoized method.
Notes:
Target method class needs as "_cache" attribute (dict).
It is the case of "ObjectIOBase" and all its subclasses. | [
"Decorator",
"that",
"caches",
"method",
"result",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base.py#L120-L150 |
Accelize/pycosio | pycosio/_core/io_base.py | WorkerPoolBase._generate_async | def _generate_async(self, generator):
"""
Return the previous generator object after having run the first element
evaluation as a background task.
Args:
generator (iterable): A generator function.
Returns:
iterable: The generator function with first element evaluated
in background.
"""
first_value_future = self._workers.submit(next, generator)
def get_first_element(future=first_value_future):
"""
Get first element value from future.
Args:
future (concurrent.futures._base.Future): First value future.
Returns:
Evaluated value
"""
try:
yield future.result()
except StopIteration:
return
return chain(get_first_element(), generator) | python | def _generate_async(self, generator):
"""
Return the previous generator object after having run the first element
evaluation as a background task.
Args:
generator (iterable): A generator function.
Returns:
iterable: The generator function with first element evaluated
in background.
"""
first_value_future = self._workers.submit(next, generator)
def get_first_element(future=first_value_future):
"""
Get first element value from future.
Args:
future (concurrent.futures._base.Future): First value future.
Returns:
Evaluated value
"""
try:
yield future.result()
except StopIteration:
return
return chain(get_first_element(), generator) | [
"def",
"_generate_async",
"(",
"self",
",",
"generator",
")",
":",
"first_value_future",
"=",
"self",
".",
"_workers",
".",
"submit",
"(",
"next",
",",
"generator",
")",
"def",
"get_first_element",
"(",
"future",
"=",
"first_value_future",
")",
":",
"\"\"\"\n ... | Return the previous generator object after having run the first element
evaluation as a background task.
Args:
generator (iterable): A generator function.
Returns:
iterable: The generator function with first element evaluated
in background. | [
"Return",
"the",
"previous",
"generator",
"object",
"after",
"having",
"run",
"the",
"first",
"element",
"evaluation",
"as",
"a",
"background",
"task",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base.py#L174-L203 |
Accelize/pycosio | pycosio/storage/swift.py | _handle_client_exception | def _handle_client_exception():
"""
Handle Swift exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _ClientException as exception:
if exception.http_status in _ERROR_CODES:
raise _ERROR_CODES[exception.http_status](
exception.http_reason)
raise | python | def _handle_client_exception():
"""
Handle Swift exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _ClientException as exception:
if exception.http_status in _ERROR_CODES:
raise _ERROR_CODES[exception.http_status](
exception.http_reason)
raise | [
"def",
"_handle_client_exception",
"(",
")",
":",
"try",
":",
"yield",
"except",
"_ClientException",
"as",
"exception",
":",
"if",
"exception",
".",
"http_status",
"in",
"_ERROR_CODES",
":",
"raise",
"_ERROR_CODES",
"[",
"exception",
".",
"http_status",
"]",
"("... | Handle Swift exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error. | [
"Handle",
"Swift",
"exception",
"and",
"convert",
"to",
"class",
"IO",
"exceptions"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L24-L39 |
Accelize/pycosio | pycosio/storage/swift.py | _SwiftSystem.copy | def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
"""
container, obj = self.split_locator(src)
with _handle_client_exception():
self.client.copy_object(
container=container, obj=obj, destination=self.relpath(dst)) | python | def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
"""
container, obj = self.split_locator(src)
with _handle_client_exception():
self.client.copy_object(
container=container, obj=obj, destination=self.relpath(dst)) | [
"def",
"copy",
"(",
"self",
",",
"src",
",",
"dst",
",",
"other_system",
"=",
"None",
")",
":",
"container",
",",
"obj",
"=",
"self",
".",
"split_locator",
"(",
"src",
")",
"with",
"_handle_client_exception",
"(",
")",
":",
"self",
".",
"client",
".",
... | Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused. | [
"Copy",
"object",
"of",
"the",
"same",
"storage",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L56-L68 |
Accelize/pycosio | pycosio/storage/swift.py | _SwiftSystem.get_client_kwargs | def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
"""
container, obj = self.split_locator(path)
kwargs = dict(container=container)
if obj:
kwargs['obj'] = obj
return kwargs | python | def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
"""
container, obj = self.split_locator(path)
kwargs = dict(container=container)
if obj:
kwargs['obj'] = obj
return kwargs | [
"def",
"get_client_kwargs",
"(",
"self",
",",
"path",
")",
":",
"container",
",",
"obj",
"=",
"self",
".",
"split_locator",
"(",
"path",
")",
"kwargs",
"=",
"dict",
"(",
"container",
"=",
"container",
")",
"if",
"obj",
":",
"kwargs",
"[",
"'obj'",
"]",... | Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args | [
"Get",
"base",
"keyword",
"arguments",
"for",
"client",
"for",
"a",
"specific",
"path",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L70-L85 |
Accelize/pycosio | pycosio/storage/swift.py | _SwiftSystem._get_client | def _get_client(self):
"""
Swift client
Returns:
swiftclient.client.Connection: client
"""
kwargs = self._storage_parameters
# Handles unsecure mode
if self._unsecure:
kwargs = kwargs.copy()
kwargs['ssl_compression'] = False
return _swift.client.Connection(**kwargs) | python | def _get_client(self):
"""
Swift client
Returns:
swiftclient.client.Connection: client
"""
kwargs = self._storage_parameters
# Handles unsecure mode
if self._unsecure:
kwargs = kwargs.copy()
kwargs['ssl_compression'] = False
return _swift.client.Connection(**kwargs) | [
"def",
"_get_client",
"(",
"self",
")",
":",
"kwargs",
"=",
"self",
".",
"_storage_parameters",
"# Handles unsecure mode",
"if",
"self",
".",
"_unsecure",
":",
"kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"kwargs",
"[",
"'ssl_compression'",
"]",
"=",
"Fal... | Swift client
Returns:
swiftclient.client.Connection: client | [
"Swift",
"client"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L87-L101 |
Accelize/pycosio | pycosio/storage/swift.py | _SwiftSystem._head | def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.head_object(**client_kwargs)
# Container
return self.client.head_container(**client_kwargs) | python | def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.head_object(**client_kwargs)
# Container
return self.client.head_container(**client_kwargs) | [
"def",
"_head",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_client_exception",
"(",
")",
":",
"# Object",
"if",
"'obj'",
"in",
"client_kwargs",
":",
"return",
"self",
".",
"client",
".",
"head_object",
"(",
"*",
"*",
"client_kwargs",
")",
... | Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header. | [
"Returns",
"object",
"HTTP",
"header",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L115-L131 |
Accelize/pycosio | pycosio/storage/swift.py | _SwiftSystem._make_dir | def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.put_object(
client_kwargs['container'], client_kwargs['obj'], b'')
# Container
return self.client.put_container(client_kwargs['container']) | python | def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.put_object(
client_kwargs['container'], client_kwargs['obj'], b'')
# Container
return self.client.put_container(client_kwargs['container']) | [
"def",
"_make_dir",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_client_exception",
"(",
")",
":",
"# Object",
"if",
"'obj'",
"in",
"client_kwargs",
":",
"return",
"self",
".",
"client",
".",
"put_object",
"(",
"client_kwargs",
"[",
"'containe... | Make a directory.
args:
client_kwargs (dict): Client arguments. | [
"Make",
"a",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L133-L147 |
Accelize/pycosio | pycosio/storage/swift.py | _SwiftSystem._remove | def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.delete_object(
client_kwargs['container'], client_kwargs['obj'])
# Container
return self.client.delete_container(client_kwargs['container']) | python | def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.delete_object(
client_kwargs['container'], client_kwargs['obj'])
# Container
return self.client.delete_container(client_kwargs['container']) | [
"def",
"_remove",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_client_exception",
"(",
")",
":",
"# Object",
"if",
"'obj'",
"in",
"client_kwargs",
":",
"return",
"self",
".",
"client",
".",
"delete_object",
"(",
"client_kwargs",
"[",
"'contain... | Remove an object.
args:
client_kwargs (dict): Client arguments. | [
"Remove",
"an",
"object",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L149-L163 |
Accelize/pycosio | pycosio/storage/swift.py | _SwiftSystem._list_locators | def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_client_exception():
response = self.client.get_account()
for container in response[1]:
yield container.pop('name'), container | python | def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_client_exception():
response = self.client.get_account()
for container in response[1]:
yield container.pop('name'), container | [
"def",
"_list_locators",
"(",
"self",
")",
":",
"with",
"_handle_client_exception",
"(",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get_account",
"(",
")",
"for",
"container",
"in",
"response",
"[",
"1",
"]",
":",
"yield",
"container",
".",
... | Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | [
"Lists",
"locators",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L165-L176 |
Accelize/pycosio | pycosio/storage/swift.py | _SwiftSystem._list_objects | def _list_objects(self, client_kwargs, path, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict
"""
kwargs = dict(prefix=path)
if max_request_entries:
kwargs['limit'] = max_request_entries
else:
kwargs['full_listing'] = True
with _handle_client_exception():
response = self.client.get_container(
client_kwargs['container'], **kwargs)
for obj in response[1]:
yield obj.pop('name'), obj | python | def _list_objects(self, client_kwargs, path, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict
"""
kwargs = dict(prefix=path)
if max_request_entries:
kwargs['limit'] = max_request_entries
else:
kwargs['full_listing'] = True
with _handle_client_exception():
response = self.client.get_container(
client_kwargs['container'], **kwargs)
for obj in response[1]:
yield obj.pop('name'), obj | [
"def",
"_list_objects",
"(",
"self",
",",
"client_kwargs",
",",
"path",
",",
"max_request_entries",
")",
":",
"kwargs",
"=",
"dict",
"(",
"prefix",
"=",
"path",
")",
"if",
"max_request_entries",
":",
"kwargs",
"[",
"'limit'",
"]",
"=",
"max_request_entries",
... | Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict | [
"Lists",
"objects",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L178-L202 |
Accelize/pycosio | pycosio/storage/swift.py | SwiftRawIO._read_range | def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
try:
with _handle_client_exception():
return self._client.get_object(*self._client_args, headers=dict(
Range=self._http_range(start, end)))[1]
except _ClientException as exception:
if exception.http_status == 416:
# EOF
return b''
raise | python | def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
try:
with _handle_client_exception():
return self._client.get_object(*self._client_args, headers=dict(
Range=self._http_range(start, end)))[1]
except _ClientException as exception:
if exception.http_status == 416:
# EOF
return b''
raise | [
"def",
"_read_range",
"(",
"self",
",",
"start",
",",
"end",
"=",
"0",
")",
":",
"try",
":",
"with",
"_handle_client_exception",
"(",
")",
":",
"return",
"self",
".",
"_client",
".",
"get_object",
"(",
"*",
"self",
".",
"_client_args",
",",
"headers",
... | Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read | [
"Read",
"a",
"range",
"of",
"bytes",
"in",
"stream",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L235-L256 |
Accelize/pycosio | pycosio/storage/swift.py | SwiftRawIO._flush | def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
container, obj = self._client_args
with _handle_client_exception():
self._client.put_object(container, obj, buffer) | python | def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
container, obj = self._client_args
with _handle_client_exception():
self._client.put_object(container, obj, buffer) | [
"def",
"_flush",
"(",
"self",
",",
"buffer",
")",
":",
"container",
",",
"obj",
"=",
"self",
".",
"_client_args",
"with",
"_handle_client_exception",
"(",
")",
":",
"self",
".",
"_client",
".",
"put_object",
"(",
"container",
",",
"obj",
",",
"buffer",
"... | Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"if",
"applicable",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L268-L277 |
Accelize/pycosio | pycosio/storage/swift.py | SwiftBufferedIO._flush | def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Upload segment with workers
name = self._segment_name % self._seek
response = self._workers.submit(
self._client.put_object, self._container, name,
self._get_buffer())
# Save segment information in manifest
self._write_futures.append(dict(
etag=response, path='/'.join((self._container, name)))) | python | def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Upload segment with workers
name = self._segment_name % self._seek
response = self._workers.submit(
self._client.put_object, self._container, name,
self._get_buffer())
# Save segment information in manifest
self._write_futures.append(dict(
etag=response, path='/'.join((self._container, name)))) | [
"def",
"_flush",
"(",
"self",
")",
":",
"# Upload segment with workers",
"name",
"=",
"self",
".",
"_segment_name",
"%",
"self",
".",
"_seek",
"response",
"=",
"self",
".",
"_workers",
".",
"submit",
"(",
"self",
".",
"_client",
".",
"put_object",
",",
"se... | Flush the write buffers of the stream. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L306-L318 |
Accelize/pycosio | pycosio/storage/swift.py | SwiftBufferedIO._close_writable | def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait segments upload completion
for segment in self._write_futures:
segment['etag'] = segment['etag'].result()
# Upload manifest file
with _handle_client_exception():
self._client.put_object(self._container, self._object_name, _dumps(
self._write_futures), query_string='multipart-manifest=put') | python | def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait segments upload completion
for segment in self._write_futures:
segment['etag'] = segment['etag'].result()
# Upload manifest file
with _handle_client_exception():
self._client.put_object(self._container, self._object_name, _dumps(
self._write_futures), query_string='multipart-manifest=put') | [
"def",
"_close_writable",
"(",
"self",
")",
":",
"# Wait segments upload completion",
"for",
"segment",
"in",
"self",
".",
"_write_futures",
":",
"segment",
"[",
"'etag'",
"]",
"=",
"segment",
"[",
"'etag'",
"]",
".",
"result",
"(",
")",
"# Upload manifest file"... | Close the object in write mode. | [
"Close",
"the",
"object",
"in",
"write",
"mode",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L320-L331 |
Accelize/pycosio | pycosio/_core/io_base_raw.py | ObjectRawIOBase._init_append | def _init_append(self):
"""
Initializes file on 'a' mode.
"""
# Require to load the full file content in buffer
self._write_buffer[:] = self._readall()
# Make initial seek position to current end of file
self._seek = self._size | python | def _init_append(self):
"""
Initializes file on 'a' mode.
"""
# Require to load the full file content in buffer
self._write_buffer[:] = self._readall()
# Make initial seek position to current end of file
self._seek = self._size | [
"def",
"_init_append",
"(",
"self",
")",
":",
"# Require to load the full file content in buffer",
"self",
".",
"_write_buffer",
"[",
":",
"]",
"=",
"self",
".",
"_readall",
"(",
")",
"# Make initial seek position to current end of file",
"self",
".",
"_seek",
"=",
"s... | Initializes file on 'a' mode. | [
"Initializes",
"file",
"on",
"a",
"mode",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_raw.py#L117-L125 |
Accelize/pycosio | pycosio/_core/io_base_raw.py | ObjectRawIOBase.close | def close(self):
"""
Flush the write buffers of the stream if applicable and
close the object.
"""
if self._writable and not self._is_raw_of_buffered and not self._closed:
self._closed = True
if self._write_buffer:
self.flush() | python | def close(self):
"""
Flush the write buffers of the stream if applicable and
close the object.
"""
if self._writable and not self._is_raw_of_buffered and not self._closed:
self._closed = True
if self._write_buffer:
self.flush() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writable",
"and",
"not",
"self",
".",
"_is_raw_of_buffered",
"and",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"_closed",
"=",
"True",
"if",
"self",
".",
"_write_buffer",
":",
"self",
".... | Flush the write buffers of the stream if applicable and
close the object. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"if",
"applicable",
"and",
"close",
"the",
"object",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_raw.py#L137-L145 |
Accelize/pycosio | pycosio/_core/io_base_raw.py | ObjectRawIOBase._peek | def _peek(self, size=-1):
"""
Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read
"""
with self._seek_lock:
seek = self._seek
with handle_os_exceptions():
return self._read_range(seek, seek + size) | python | def _peek(self, size=-1):
"""
Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read
"""
with self._seek_lock:
seek = self._seek
with handle_os_exceptions():
return self._read_range(seek, seek + size) | [
"def",
"_peek",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"with",
"self",
".",
"_seek_lock",
":",
"seek",
"=",
"self",
".",
"_seek",
"with",
"handle_os_exceptions",
"(",
")",
":",
"return",
"self",
".",
"_read_range",
"(",
"seek",
",",
"seek... | Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read | [
"Return",
"bytes",
"from",
"the",
"stream",
"without",
"advancing",
"the",
"position",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_raw.py#L246-L260 |
Accelize/pycosio | pycosio/_core/io_base_raw.py | ObjectRawIOBase.readall | def readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
if not self._readable:
raise UnsupportedOperation('read')
with self._seek_lock:
# Get data starting from seek
with handle_os_exceptions():
if self._seek and self._seekable:
data = self._read_range(self._seek)
# Get all data
else:
data = self._readall()
# Update seek
self._seek += len(data)
return data | python | def readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
if not self._readable:
raise UnsupportedOperation('read')
with self._seek_lock:
# Get data starting from seek
with handle_os_exceptions():
if self._seek and self._seekable:
data = self._read_range(self._seek)
# Get all data
else:
data = self._readall()
# Update seek
self._seek += len(data)
return data | [
"def",
"readall",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_readable",
":",
"raise",
"UnsupportedOperation",
"(",
"'read'",
")",
"with",
"self",
".",
"_seek_lock",
":",
"# Get data starting from seek",
"with",
"handle_os_exceptions",
"(",
")",
":",
"i... | Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content | [
"Read",
"and",
"return",
"all",
"the",
"bytes",
"from",
"the",
"stream",
"until",
"EOF",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_raw.py#L262-L284 |
Accelize/pycosio | pycosio/_core/io_base_raw.py | ObjectRawIOBase.readinto | def readinto(self, b):
"""
Read bytes into a pre-allocated, writable bytes-like object b,
and return the number of bytes read.
Args:
b (bytes-like object): buffer.
Returns:
int: number of bytes read
"""
if not self._readable:
raise UnsupportedOperation('read')
# Get and update stream positions
size = len(b)
with self._seek_lock:
start = self._seek
end = start + size
self._seek = end
# Read data range
with handle_os_exceptions():
read_data = self._read_range(start, end)
# Copy to bytes-like object
read_size = len(read_data)
if read_size:
memoryview(b)[:read_size] = read_data
# Update stream position if end of file
if read_size != size:
with self._seek_lock:
self._seek = start + read_size
# Return read size
return read_size | python | def readinto(self, b):
"""
Read bytes into a pre-allocated, writable bytes-like object b,
and return the number of bytes read.
Args:
b (bytes-like object): buffer.
Returns:
int: number of bytes read
"""
if not self._readable:
raise UnsupportedOperation('read')
# Get and update stream positions
size = len(b)
with self._seek_lock:
start = self._seek
end = start + size
self._seek = end
# Read data range
with handle_os_exceptions():
read_data = self._read_range(start, end)
# Copy to bytes-like object
read_size = len(read_data)
if read_size:
memoryview(b)[:read_size] = read_data
# Update stream position if end of file
if read_size != size:
with self._seek_lock:
self._seek = start + read_size
# Return read size
return read_size | [
"def",
"readinto",
"(",
"self",
",",
"b",
")",
":",
"if",
"not",
"self",
".",
"_readable",
":",
"raise",
"UnsupportedOperation",
"(",
"'read'",
")",
"# Get and update stream positions",
"size",
"=",
"len",
"(",
"b",
")",
"with",
"self",
".",
"_seek_lock",
... | Read bytes into a pre-allocated, writable bytes-like object b,
and return the number of bytes read.
Args:
b (bytes-like object): buffer.
Returns:
int: number of bytes read | [
"Read",
"bytes",
"into",
"a",
"pre",
"-",
"allocated",
"writable",
"bytes",
"-",
"like",
"object",
"b",
"and",
"return",
"the",
"number",
"of",
"bytes",
"read",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_raw.py#L295-L331 |
Accelize/pycosio | pycosio/_core/io_base_raw.py | ObjectRawIOBase.seek | def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset (int): Offset is interpreted relative to the position
indicated by whence.
whence (int): The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 β start of the stream (the default);
offset should be zero or positive
SEEK_CUR or 1 β current stream position;
offset may be negative
SEEK_END or 2 β end of the stream;
offset is usually negative
Returns:
int: The new absolute position.
"""
if not self._seekable:
raise UnsupportedOperation('seek')
seek = self._update_seek(offset, whence)
# If seek move out of file, add padding until new seek position.
if self._writable:
size = len(self._write_buffer)
if seek > size:
self._write_buffer[seek:size] = b'\0' * (seek - size)
return seek | python | def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset (int): Offset is interpreted relative to the position
indicated by whence.
whence (int): The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 β start of the stream (the default);
offset should be zero or positive
SEEK_CUR or 1 β current stream position;
offset may be negative
SEEK_END or 2 β end of the stream;
offset is usually negative
Returns:
int: The new absolute position.
"""
if not self._seekable:
raise UnsupportedOperation('seek')
seek = self._update_seek(offset, whence)
# If seek move out of file, add padding until new seek position.
if self._writable:
size = len(self._write_buffer)
if seek > size:
self._write_buffer[seek:size] = b'\0' * (seek - size)
return seek | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"SEEK_SET",
")",
":",
"if",
"not",
"self",
".",
"_seekable",
":",
"raise",
"UnsupportedOperation",
"(",
"'seek'",
")",
"seek",
"=",
"self",
".",
"_update_seek",
"(",
"offset",
",",
"whence",
... | Change the stream position to the given byte offset.
Args:
offset (int): Offset is interpreted relative to the position
indicated by whence.
whence (int): The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 β start of the stream (the default);
offset should be zero or positive
SEEK_CUR or 1 β current stream position;
offset may be negative
SEEK_END or 2 β end of the stream;
offset is usually negative
Returns:
int: The new absolute position. | [
"Change",
"the",
"stream",
"position",
"to",
"the",
"given",
"byte",
"offset",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_raw.py#L347-L377 |
Accelize/pycosio | pycosio/_core/io_base_raw.py | ObjectRawIOBase._update_seek | def _update_seek(self, offset, whence):
"""
Update seek value.
Args:
offset (int): Offset.
whence (int): Whence.
Returns:
int: Seek position.
"""
with self._seek_lock:
if whence == SEEK_SET:
self._seek = offset
elif whence == SEEK_CUR:
self._seek += offset
elif whence == SEEK_END:
self._seek = offset + self._size
else:
raise ValueError('whence value %s unsupported' % whence)
return self._seek | python | def _update_seek(self, offset, whence):
"""
Update seek value.
Args:
offset (int): Offset.
whence (int): Whence.
Returns:
int: Seek position.
"""
with self._seek_lock:
if whence == SEEK_SET:
self._seek = offset
elif whence == SEEK_CUR:
self._seek += offset
elif whence == SEEK_END:
self._seek = offset + self._size
else:
raise ValueError('whence value %s unsupported' % whence)
return self._seek | [
"def",
"_update_seek",
"(",
"self",
",",
"offset",
",",
"whence",
")",
":",
"with",
"self",
".",
"_seek_lock",
":",
"if",
"whence",
"==",
"SEEK_SET",
":",
"self",
".",
"_seek",
"=",
"offset",
"elif",
"whence",
"==",
"SEEK_CUR",
":",
"self",
".",
"_seek... | Update seek value.
Args:
offset (int): Offset.
whence (int): Whence.
Returns:
int: Seek position. | [
"Update",
"seek",
"value",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_raw.py#L379-L399 |
Accelize/pycosio | pycosio/_core/io_base_raw.py | ObjectRawIOBase.write | def write(self, b):
"""
Write the given bytes-like object, b, to the underlying raw stream,
and return the number of bytes written.
Args:
b (bytes-like object): Bytes to write.
Returns:
int: The number of bytes written.
"""
if not self._writable:
raise UnsupportedOperation('write')
# This function write data in a buffer
# "flush()" need to be called to really write content on
# Cloud Storage
size = len(b)
with self._seek_lock:
start = self._seek
end = start + size
self._seek = end
buffer = self._write_buffer
if end <= len(buffer):
buffer = memoryview(buffer)
buffer[start:end] = b
return size | python | def write(self, b):
"""
Write the given bytes-like object, b, to the underlying raw stream,
and return the number of bytes written.
Args:
b (bytes-like object): Bytes to write.
Returns:
int: The number of bytes written.
"""
if not self._writable:
raise UnsupportedOperation('write')
# This function write data in a buffer
# "flush()" need to be called to really write content on
# Cloud Storage
size = len(b)
with self._seek_lock:
start = self._seek
end = start + size
self._seek = end
buffer = self._write_buffer
if end <= len(buffer):
buffer = memoryview(buffer)
buffer[start:end] = b
return size | [
"def",
"write",
"(",
"self",
",",
"b",
")",
":",
"if",
"not",
"self",
".",
"_writable",
":",
"raise",
"UnsupportedOperation",
"(",
"'write'",
")",
"# This function write data in a buffer",
"# \"flush()\" need to be called to really write content on",
"# Cloud Storage",
"s... | Write the given bytes-like object, b, to the underlying raw stream,
and return the number of bytes written.
Args:
b (bytes-like object): Bytes to write.
Returns:
int: The number of bytes written. | [
"Write",
"the",
"given",
"bytes",
"-",
"like",
"object",
"b",
"to",
"the",
"underlying",
"raw",
"stream",
"and",
"return",
"the",
"number",
"of",
"bytes",
"written",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_raw.py#L401-L428 |
Accelize/pycosio | pycosio/storage/http.py | _handle_http_errors | def _handle_http_errors(response):
"""
Check for HTTP errors and raise
OSError if relevant.
Args:
response (requests.Response):
Returns:
requests.Response: response
"""
code = response.status_code
if 200 <= code < 400:
return response
elif code in (403, 404):
raise {403: _ObjectPermissionError,
404: _ObjectNotFoundError}[code](response.reason)
response.raise_for_status() | python | def _handle_http_errors(response):
"""
Check for HTTP errors and raise
OSError if relevant.
Args:
response (requests.Response):
Returns:
requests.Response: response
"""
code = response.status_code
if 200 <= code < 400:
return response
elif code in (403, 404):
raise {403: _ObjectPermissionError,
404: _ObjectNotFoundError}[code](response.reason)
response.raise_for_status() | [
"def",
"_handle_http_errors",
"(",
"response",
")",
":",
"code",
"=",
"response",
".",
"status_code",
"if",
"200",
"<=",
"code",
"<",
"400",
":",
"return",
"response",
"elif",
"code",
"in",
"(",
"403",
",",
"404",
")",
":",
"raise",
"{",
"403",
":",
... | Check for HTTP errors and raise
OSError if relevant.
Args:
response (requests.Response):
Returns:
requests.Response: response | [
"Check",
"for",
"HTTP",
"errors",
"and",
"raise",
"OSError",
"if",
"relevant",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/http.py#L16-L33 |
Accelize/pycosio | pycosio/storage/http.py | _HTTPSystem._head | def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
return _handle_http_errors(
self.client.request(
'HEAD', timeout=self._TIMEOUT, **client_kwargs)).headers | python | def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
return _handle_http_errors(
self.client.request(
'HEAD', timeout=self._TIMEOUT, **client_kwargs)).headers | [
"def",
"_head",
"(",
"self",
",",
"client_kwargs",
")",
":",
"return",
"_handle_http_errors",
"(",
"self",
".",
"client",
".",
"request",
"(",
"'HEAD'",
",",
"timeout",
"=",
"self",
".",
"_TIMEOUT",
",",
"*",
"*",
"client_kwargs",
")",
")",
".",
"headers... | Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header. | [
"Returns",
"object",
"HTTP",
"header",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/http.py#L75-L87 |
Accelize/pycosio | pycosio/storage/http.py | HTTPRawIO._read_range | def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
# Get object part
response = self._client.request(
'GET', self.name, headers=dict(Range=self._http_range(start, end)),
timeout=self._TIMEOUT)
if response.status_code == 416:
# EOF
return b''
# Get object content
return _handle_http_errors(response).content | python | def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
# Get object part
response = self._client.request(
'GET', self.name, headers=dict(Range=self._http_range(start, end)),
timeout=self._TIMEOUT)
if response.status_code == 416:
# EOF
return b''
# Get object content
return _handle_http_errors(response).content | [
"def",
"_read_range",
"(",
"self",
",",
"start",
",",
"end",
"=",
"0",
")",
":",
"# Get object part",
"response",
"=",
"self",
".",
"_client",
".",
"request",
"(",
"'GET'",
",",
"self",
".",
"name",
",",
"headers",
"=",
"dict",
"(",
"Range",
"=",
"se... | Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read | [
"Read",
"a",
"range",
"of",
"bytes",
"in",
"stream",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/http.py#L111-L133 |
Accelize/pycosio | pycosio/storage/http.py | HTTPRawIO._readall | def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
return _handle_http_errors(
self._client.request(
'GET', self.name, timeout=self._TIMEOUT)).content | python | def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
return _handle_http_errors(
self._client.request(
'GET', self.name, timeout=self._TIMEOUT)).content | [
"def",
"_readall",
"(",
"self",
")",
":",
"return",
"_handle_http_errors",
"(",
"self",
".",
"_client",
".",
"request",
"(",
"'GET'",
",",
"self",
".",
"name",
",",
"timeout",
"=",
"self",
".",
"_TIMEOUT",
")",
")",
".",
"content"
] | Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content | [
"Read",
"and",
"return",
"all",
"the",
"bytes",
"from",
"the",
"stream",
"until",
"EOF",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/http.py#L135-L144 |
Accelize/pycosio | pycosio/_core/io_random_write.py | ObjectRawIORandomWriteBase.flush | def flush(self):
"""
Flush the write buffers of the stream if applicable and
save the object on the cloud.
"""
if self._writable:
with self._seek_lock:
buffer = self._get_buffer()
# Flush that part of the file
end = self._seek
start = end - len(buffer)
# Clear buffer
self._write_buffer = bytearray()
# Flush content
with handle_os_exceptions():
self._flush(buffer, start, end) | python | def flush(self):
"""
Flush the write buffers of the stream if applicable and
save the object on the cloud.
"""
if self._writable:
with self._seek_lock:
buffer = self._get_buffer()
# Flush that part of the file
end = self._seek
start = end - len(buffer)
# Clear buffer
self._write_buffer = bytearray()
# Flush content
with handle_os_exceptions():
self._flush(buffer, start, end) | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writable",
":",
"with",
"self",
".",
"_seek_lock",
":",
"buffer",
"=",
"self",
".",
"_get_buffer",
"(",
")",
"# Flush that part of the file",
"end",
"=",
"self",
".",
"_seek",
"start",
"=",
"end... | Flush the write buffers of the stream if applicable and
save the object on the cloud. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"if",
"applicable",
"and",
"save",
"the",
"object",
"on",
"the",
"cloud",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_random_write.py#L26-L44 |
Accelize/pycosio | pycosio/_core/io_random_write.py | ObjectRawIORandomWriteBase.seek | def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset (int): Offset is interpreted relative to the position
indicated by whence.
whence (int): The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 β start of the stream (the default);
offset should be zero or positive
SEEK_CUR or 1 β current stream position;
offset may be negative
SEEK_END or 2 β end of the stream;
offset is usually negative
Returns:
int: The new absolute position.
"""
if not self._seekable:
raise UnsupportedOperation('seek')
# Flush before moving position
self.flush()
return self._update_seek(offset, whence) | python | def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset (int): Offset is interpreted relative to the position
indicated by whence.
whence (int): The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 β start of the stream (the default);
offset should be zero or positive
SEEK_CUR or 1 β current stream position;
offset may be negative
SEEK_END or 2 β end of the stream;
offset is usually negative
Returns:
int: The new absolute position.
"""
if not self._seekable:
raise UnsupportedOperation('seek')
# Flush before moving position
self.flush()
return self._update_seek(offset, whence) | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"SEEK_SET",
")",
":",
"if",
"not",
"self",
".",
"_seekable",
":",
"raise",
"UnsupportedOperation",
"(",
"'seek'",
")",
"# Flush before moving position",
"self",
".",
"flush",
"(",
")",
"return",
... | Change the stream position to the given byte offset.
Args:
offset (int): Offset is interpreted relative to the position
indicated by whence.
whence (int): The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 β start of the stream (the default);
offset should be zero or positive
SEEK_CUR or 1 β current stream position;
offset may be negative
SEEK_END or 2 β end of the stream;
offset is usually negative
Returns:
int: The new absolute position. | [
"Change",
"the",
"stream",
"position",
"to",
"the",
"given",
"byte",
"offset",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_random_write.py#L65-L90 |
Accelize/pycosio | pycosio/_core/io_random_write.py | ObjectBufferedIORandomWriteBase._flush | def _flush(self):
"""
Flush the write buffers of the stream if applicable.
In write mode, send the buffer content to the cloud object.
"""
# Flush buffer to specified range
buffer = self._get_buffer()
start = self._buffer_size * (self._seek - 1)
end = start + len(buffer)
future = self._workers.submit(
self._flush_range, buffer=buffer, start=start, end=end)
self._write_futures.append(future)
future.add_done_callback(partial(self._update_size, end)) | python | def _flush(self):
"""
Flush the write buffers of the stream if applicable.
In write mode, send the buffer content to the cloud object.
"""
# Flush buffer to specified range
buffer = self._get_buffer()
start = self._buffer_size * (self._seek - 1)
end = start + len(buffer)
future = self._workers.submit(
self._flush_range, buffer=buffer, start=start, end=end)
self._write_futures.append(future)
future.add_done_callback(partial(self._update_size, end)) | [
"def",
"_flush",
"(",
"self",
")",
":",
"# Flush buffer to specified range",
"buffer",
"=",
"self",
".",
"_get_buffer",
"(",
")",
"start",
"=",
"self",
".",
"_buffer_size",
"*",
"(",
"self",
".",
"_seek",
"-",
"1",
")",
"end",
"=",
"start",
"+",
"len",
... | Flush the write buffers of the stream if applicable.
In write mode, send the buffer content to the cloud object. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"if",
"applicable",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_random_write.py#L101-L115 |
Accelize/pycosio | pycosio/_core/io_random_write.py | ObjectBufferedIORandomWriteBase._update_size | def _update_size(self, size, future):
"""
Keep track of the file size during writing.
If specified size value is greater than the current size, update the
current size using specified value.
Used as callback in default "_flush" implementation for files supporting
random write access.
Args:
size (int): Size value.
future (concurrent.futures._base.Future): future.
"""
with self._size_lock:
# Update value
if size > self._size and future.done:
# Size can be lower if seek down on an 'a' mode open file.
self._size = size | python | def _update_size(self, size, future):
"""
Keep track of the file size during writing.
If specified size value is greater than the current size, update the
current size using specified value.
Used as callback in default "_flush" implementation for files supporting
random write access.
Args:
size (int): Size value.
future (concurrent.futures._base.Future): future.
"""
with self._size_lock:
# Update value
if size > self._size and future.done:
# Size can be lower if seek down on an 'a' mode open file.
self._size = size | [
"def",
"_update_size",
"(",
"self",
",",
"size",
",",
"future",
")",
":",
"with",
"self",
".",
"_size_lock",
":",
"# Update value",
"if",
"size",
">",
"self",
".",
"_size",
"and",
"future",
".",
"done",
":",
"# Size can be lower if seek down on an 'a' mode open ... | Keep track of the file size during writing.
If specified size value is greater than the current size, update the
current size using specified value.
Used as callback in default "_flush" implementation for files supporting
random write access.
Args:
size (int): Size value.
future (concurrent.futures._base.Future): future. | [
"Keep",
"track",
"of",
"the",
"file",
"size",
"during",
"writing",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_random_write.py#L117-L135 |
Accelize/pycosio | pycosio/_core/io_random_write.py | ObjectBufferedIORandomWriteBase._flush_range | def _flush_range(self, buffer, start, end):
"""
Flush a buffer to a range of the file.
Meant to be used asynchronously, used to provides parallel flushing of
file parts when applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
end (int): End of buffer position to flush.
"""
# On first call, Get file size if exists
with self._size_lock:
if not self._size_synched:
self._size_synched = True
try:
self._size = self.raw._size
except (ObjectNotFoundError, UnsupportedOperation):
self._size = 0
# It is not possible to flush a part if start > size:
# If it is the case, wait that previous parts are flushed before
# flushing this one
while start > self._size:
sleep(self._FLUSH_WAIT)
# Flush buffer using RAW IO
self._raw_flush(buffer, start, end) | python | def _flush_range(self, buffer, start, end):
"""
Flush a buffer to a range of the file.
Meant to be used asynchronously, used to provides parallel flushing of
file parts when applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
end (int): End of buffer position to flush.
"""
# On first call, Get file size if exists
with self._size_lock:
if not self._size_synched:
self._size_synched = True
try:
self._size = self.raw._size
except (ObjectNotFoundError, UnsupportedOperation):
self._size = 0
# It is not possible to flush a part if start > size:
# If it is the case, wait that previous parts are flushed before
# flushing this one
while start > self._size:
sleep(self._FLUSH_WAIT)
# Flush buffer using RAW IO
self._raw_flush(buffer, start, end) | [
"def",
"_flush_range",
"(",
"self",
",",
"buffer",
",",
"start",
",",
"end",
")",
":",
"# On first call, Get file size if exists",
"with",
"self",
".",
"_size_lock",
":",
"if",
"not",
"self",
".",
"_size_synched",
":",
"self",
".",
"_size_synched",
"=",
"True"... | Flush a buffer to a range of the file.
Meant to be used asynchronously, used to provides parallel flushing of
file parts when applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
end (int): End of buffer position to flush. | [
"Flush",
"a",
"buffer",
"to",
"a",
"range",
"of",
"the",
"file",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_random_write.py#L137-L165 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.