output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Create an empty array with appropriate shape. | Can you generate the documentation for the following Python 3 function
def _create_empty_array(self, frames, always_2d, dtype):
import numpy as np
if always_2d or self.channels > 1:
shape = frames, self.channels
else:
shape = frames,
return np.empty(shape, dtype, ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _check_dtype(self, dtype):
"""Check if dtype string is valid and return ctype string."""
try:
return _ffi_types[dtype]
except KeyError:
raise ValueError("dtype must be one of {0!r} and not {1!r}".format(
sorted(_ffi_types.keys()), dtype)) | Implement a Python 3 function for
checking if dtype string is valid and return ctype string. | As a Python code composer, you craft elegant and concise scripts. |
Check array and call low - level IO function. | Given the following Python 3 function, write the documentation
def _array_io(self, action, array, frames):
if (array.ndim not in (1, 2) or
array.ndim == 1 and self.channels != 1 or
array.ndim == 2 and array.shape[1] != self.channels):
raise ValueError("Invalid shape: ... | As a Python code composer, you craft elegant and concise scripts. |
Call one of libsndfile s read and write functions. | Can you generate a brief explanation for the following Python 3 code
def _cdata_io(self, action, data, ctype, frames):
assert ctype in _ffi_types.values()
self._check_if_closed()
if self.seekable():
curr = self.tell()
func = getattr(_snd, 'sf_' + action + 'f_' + ctype)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _update_frames(self, written):
"""Update self.frames after writing."""
if self.seekable():
curr = self.tell()
self._info.frames = self.seek(0, SEEK_END)
self.seek(curr, SEEK_SET)
else:
self._info.frames += written | Can you implement a function in Python 3 that
updates self. frames after writing. | As a python code expert, you are capable of creating scripts from specifications. |
Seek to start frame and calculate length. | How would you explain what the following Python 3 function does
def _prepare_read(self, start, stop, frames):
if start != 0 and not self.seekable():
raise ValueError("start is only allowed for seekable files")
if frames >= 0 and stop is not None:
raise TypeError("Only one of {fra... | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates the directory dirname if it does not already exist. | Can you generate a brief explanation for the following Python 3 code
def ensure_dir(dirname):
try:
# Tries to create the directory
os.makedirs(dirname)
except OSError:
# Check that the directory exists
if os.path.isdir(dirname): pass
else: raise | As a Python code composer, you craft elegant and concise scripts. |
Generates boolean matrices indicating which are the probes for each model in the probe_files_full. | Here you have a function in Python 3, explain what it does
def probes_used_generate_vector(probe_files_full, probe_files_model):
import numpy as np
C_probesUsed = np.ndarray((len(probe_files_full),), 'bool')
C_probesUsed.fill(False)
c=0
for k in sorted(probe_files_full.keys()):
if probe_files_model.has_ke... | As a Python code analyst, you investigate and solve complex coding mysteries |
def probes_used_extract_scores(full_scores, same_probes):
"""Extracts a matrix of scores for a model, given a probes_used row vector of boolean"""
if full_scores.shape[1] != same_probes.shape[0]: raise "Size mismatch"
import numpy as np
model_scores = np.ndarray((full_scores.shape[0],np.sum(same_probes)), 'floa... | How would you implement a function in Python 3 that
extracts a matrix of scores for a model given a probes_used row vector of boolean | You are a Python code analyst, evaluating scripts for potential improvements. |
def normalize_std_array(vector):
"""Applies a unit mean and variance normalization to an arrayset"""
# Initializes variables
length = 1
n_samples = len(vector)
mean = numpy.ndarray((length,), 'float64')
std = numpy.ndarray((length,), 'float64')
mean.fill(0)
std.fill(0)
# Computes mean and variance
... | Implement a Python 3 function for
applying a unit mean and variance normalization to an arrayset | You are a Python code generator, capable of creating scripts from specifications. |
Applies a smoothing on VAD | Explain what the following Python 3 code does
def smoothing(labels, smoothing_window):
if numpy.sum(labels)< smoothing_window:
return labels
segments = []
for k in range(1,len(labels)-1):
if labels[k]==0 and labels[k-1]==1 and labels[k+1]==1 :
labels[k]=1
for k in range(1,len(labels)-1):
if l... | As a Python code composer, you craft elegant and concise scripts. |
Convert an external VAD to a Spear label. | Can you generate a brief explanation for the following Python 3 code
def _conversion(self, input_signal, vad_file):
e = bob.ap.Energy(rate_wavsample[0], self.win_length_ms, self.win_shift_ms)
energy_array = e(rate_wavsample[1])
labels = self.use_existing_vad(energy_array, vad_file)
return labe... | As a python code expert, you are capable of creating scripts from specifications. |
def mod_4hz(self, rate_wavsample):
"""Computes and returns the 4Hz modulation energy features for the given input wave file"""
# Set parameters
wl = self.win_length_ms
ws = self.win_shift_ms
nf = self.n_filters
f_min = self.f_min
f_max = self.f_max
pre = self.pre_emphasis_coef
c = ... | Create a Python 3 function to
compute and returns the 4Hz modulation energy features for the given input wave file | You are a Python code generator, capable of creating scripts from specifications. |
Read pre - computed CQCC Matlab features here
| Can you tell what is the following Python 3 function doing
def read_matlab_files(self, biofile, directory, extension):
import bob.io.matlab
# return the numpy array read from the data_file
data_path = biofile.make_path(directory, extension)
return bob.io.base.load(data_path) | As a python code expert, you are capable of creating scripts from specifications. |
Writes the given preprocessed data to a file with the given name. | Here you have a function in Python 3, explain what it does
def write_data(self, data, data_file, compression=0):
f = bob.io.base.HDF5File(data_file, 'w')
f.set("rate", data[0], compression=compression)
f.set("data", data[1], compression=compression)
f.set("labels", data[2], compression=compression) | You are a Python code architect, reviewing and designing scalable and efficient code |
Defines the command line arguments that are accepted by the user. | Explain what the following Python 3 code does
def command_line_arguments(command_line_parameters):
# create parser
parser = argparse.ArgumentParser(description='Execute baseline algorithms with default parameters', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# add parameters
# - the algorithm to e... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _compute_energy(self, rate_wavsample):
"""retreive the speech / non speech labels for the speech sample given by the tuple (rate, wave signal)"""
e = bob.ap.Energy(rate_wavsample[0], self.win_length_ms, self.win_shift_ms)
energy_array = e(rate_wavsample[1])
labels = self._voice_activity_detection(e... | Can you create a Python 3 function that
computes the energy of the audio sample | You are a Python code generator, capable of creating scripts from specifications. |
Calculates the mean of the data. | Here you have a function in Python 3, explain what it does
def calc_mean(c0, c1=[]):
if c1 != []:
return (numpy.mean(c0, 0) + numpy.mean(c1, 0)) / 2.
else:
return numpy.mean(c0, 0) | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculates the variance of the data. | How would you explain what the following Python 3 function does
def calc_std(c0, c1=[]):
if c1 == []:
return numpy.std(c0, 0)
prop = float(len(c0)) / float(len(c1))
if prop < 1:
p0 = int(math.ceil(1 / prop))
p1 = 1
else:
p0 = 1
p1 = int(math.ceil(prop))
return... | As a python code expert, you are capable of creating scripts from specifications. |
Calculates both the mean and standard deviation of the data. | Can you tell what is the following Python 3 function doing
def calc_mean_std(c0, c1=[], nonStdZero=False):
mi = calc_mean(c0, c1)
std = calc_std(c0, c1)
if (nonStdZero):
std[std == 0] = 1
return mi, std | As a python code expert, you are capable of creating scripts from specifications. |
Filter the features of a VAD file. | How would you explain what the following Python 3 function does
def vad_filter_features(vad_labels, features, filter_frames="trim_silence"):
if not features.size:
raise ValueError("vad_filter_features(): data sample is empty, no features extraction is possible")
vad_labels = numpy.asarray(vad_labels, ... | As a python code expert, you are capable of creating scripts from specifications. |
Solve the structures and save the effective indices in the mode types. | Can you tell what is the following Python 3 function doing
def solve_sweep_structure(
self,
structures,
sweep_param_list,
filename="structure_n_effs.dat",
plot=True,
x_label="Structure number",
fraction_mode_list=[],
):
"""
Find the modes of ma... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Solve for the effective indices of a fixed structure at
different wavelengths. | Can you generate the documentation for the following Python 3 function
def solve_sweep_wavelength(
self,
structure,
wavelengths,
filename="wavelength_n_effs.dat",
plot=True,
):
"""
Solve for the effective indices of a fixed structure at
different wavel... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Solve for the group index and the group index of a structure at a particular wavelength. | Here you have a function in Python 3, explain what it does
def solve_ng(self, structure, wavelength_step=0.01, filename="ng.dat"):
wl_nom = structure._wl
self.solve(structure)
n_ctrs = self.n_effs
structure.change_wavelength(wl_nom - wavelength_step)
self.solve(structure)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def write_modes_to_file(self, filename="mode.dat", plot=True, analyse=True):
"""
Writes the mode fields to a file and optionally plots them.
Args:
filename (str): The nominal filename to use for the saved
data. The suffix will be automatically be changed to
... | Create a Python 3 function for
writing the mode fields to a file and optionally plots them. | You are a Python code analyst, evaluating scripts for potential improvements. |
def write_modes_to_file(
self,
filename="mode.dat",
plot=True,
fields_to_write=("Ex", "Ey", "Ez", "Hx", "Hy", "Hz"),
):
"""
Writes the mode fields to a file and optionally plots them.
Args:
filename (str): The nominal filename to use for the saved... | Can you write a function in Python 3 where it
writes the mode fields to a file. | You are a Python code generator, capable of creating scripts from specifications. |
Sets the required key for the given field. | Can you generate a brief explanation for the following Python 3 code
def set_required(field, render_kw=None, force=False):
if render_kw is None:
render_kw = {}
if 'required' in render_kw and not force:
return render_kw
if field.flags.required:
render_kw['required'] = True
return ... | As a Python code composer, you craft elegant and concise scripts. |
def set_invalid(field, render_kw=None):
"""
Returns *render_kw* with `invalid` added to *class* on validation errors.
Set (or appends) 'invalid' to the fields CSS class(es), if the *field* got
any errors. 'invalid' is also set by browsers if they detect errors on a
field.
"""
if render_kw ... | Can you create a Python 3 function that
sets the invalid CSS class for the a ArcGIS field. | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_minmax(field, render_kw=None, force=False):
"""
Returns *render_kw* with *min* and *max* set if validators use them.
Sets *min* and / or *max* keys if a `Length` or `NumberRange` validator is
using them.
..note::
This won't change keys already present unless *force* is used.
... | Write a Python 3 script for
setting min and max keys for a SequenceField. | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_title(field, render_kw=None):
"""
Returns *render_kw* with *min* and *max* set if required.
If the field got a *description* but no *title* key is set, the *title* is
set to *description*.
"""
if render_kw is None:
render_kw = {}
if 'title' not in render_kw and getattr(fiel... | Create a Python 3 function for
setting the title of the page. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_html5_kwargs(field, render_kw=None, force=False):
"""
Returns a copy of *render_kw* with keys added for a bound *field*.
If some *render_kw* are given, the new keys are added to a copy of them,
which is then returned. If none are given, a dictionary containing only
the automatically genera... | Write a Python 3 script for
returning a dictionary containing keyword arguments for the HTML5 language. | As a python code expert, you are capable of creating scripts from specifications. |
def render_field(self, field, render_kw):
"""
Returns the rendered field after adding auto–attributes.
Calls the field`s widget with the following kwargs:
1. the *render_kw* set on the field are used as based
2. and are updated with the *render_kw* arguments from the render cal... | Write a Python 3 script for
returning the rendered field after adding auto–attributes. | You are a Python code generator, capable of creating scripts from specifications. |
np. array : The grid points in x. | Make a summary of the following Python 3 code
def x(self):
'''
np.array: The grid points in x.
'''
if None not in (self.x_min, self.x_max, self.x_step) and \
self.x_min != self.x_max:
x = np.arange(self.x_min, self.x_max+self.x_step-self.y_step*0.1, self.x_ste... | As a Python code translator, you convert algorithms and pseudocode into Python. |
np. array : The grid points in y. | Can you generate a brief explanation for the following Python 3 code
def y(self):
'''
np.array: The grid points in y.
'''
if None not in (self.y_min, self.y_max, self.y_step) and \
self.y_min != self.y_max:
y = np.arange(self.y_min, self.y_max-self.y_step*0.1,... | As a Python code composer, you craft elegant and concise scripts. |
function that returns the permittivity profile of the structure | How would you explain what the following Python 3 function does
def eps_func(self):
'''
function: a function that when passed a `x` and `y` values,
returns the permittivity profile of the structure,
interpolating if necessary.
'''
interp_real = interpolate.interp2... | As a Python code translator, you convert algorithms and pseudocode into Python. |
function that returns the refractive index profile of the structure | Given the following Python 3 function, write the documentation
def n_func(self):
'''
function: a function that when passed a `x` and `y` values,
returns the refractive index profile of the structure,
interpolating if necessary.
'''
return interpolate.interp2d(self... | You are a Python code architect, reviewing and designing scalable and efficient code |
Writes the refractive index profile to file. | Can you generate a brief explanation for the following Python 3 code
def write_to_file(self, filename='material_index.dat', plot=True):
'''
Write the refractive index profile to file.
Args:
filename (str): The nominal filename the refractive
index data should be save... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates and adds a new slab object. | Can you generate a brief explanation for the following Python 3 code
def add_slab(self, height, n_background=1., position='top'):
'''
Creates and adds a :class:`Slab` object.
Args:
height (float): Height of the slab.
n_background (float): The nominal refractive
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def change_wavelength(self, wavelength):
'''
Changes the wavelength of the structure.
This will affect the mode solver and potentially
the refractive indices used (provided functions
were provided as refractive indices).
Args:
wavelength (float): The new wav... | Implement a function in Python 3 to
change the wavelength of the structure. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the refractive index profile matrix of the current slab. | Can you tell what is the following Python 3 function doing
def n(self):
'''
np.array: The refractive index profile matrix
of the current slab.
'''
try:
n_mat = self.slabs['0'].n
for s in range(1, self.slab_count):
n_mat = np.vstack((self.sl... | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_material(self, x_min, x_max, n, angle=0):
'''
Add a refractive index between two x-points.
Args:
x_min (float): The start x-point.
x_max (float): The stop x-point.
n (float, function): Refractive index between
`x_min` and `x_max`. E... | How would you code a function in Python 3 to
add a material to the structure. | As a Python code analyst, you investigate and solve complex coding mysteries |
def write_to_file(self, filename='material_index.dat', plot=True):
'''
Write the refractive index profile to file.
Args:
filename (str): The nominal filename the refractive
index data should be saved to.
plot (bool): `True` if plots should be generates,
... | Write a Python 3 function for
writing the refractive index profile to file. | As a python code expert, you are capable of creating scripts from specifications. |
def change_wavelength(self, wavelength):
'''
Changes the wavelength of the structure.
This will affect the mode solver and potentially
the refractive indices used (provided functions
were provided as refractive indices).
Args:
wavelength (float): The new wav... | Write a Python 3 script for
changing the wavelength of the structure. | As a python code expert, you are capable of creating scripts from specifications. |
convert string to int or float. | Can you generate a brief explanation for the following Python 3 code
def covstr(s):
try:
ret = int(s)
except ValueError:
ret = float(s)
return ret | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the output string for the sequence of n - stocks. | How would you explain what the following Python 3 function does
def output(self):
#re = "{%(time)s} %(name)s %(stock_no)s %(c)s %(range)+.2f(%(pp)+.2f%%) %(value)s" % {
'''
re = """<table>
<tr><td>%(name)s</td><td>%(c)s</td><td>%(range)+.2f(%(pp)+.2f%%)</td></tr>
<tr><td>%(stock_no)s... | As a Python code composer, you craft elegant and concise scripts. |
For real time stock display
即時盤用,顯示目前查詢各股的股的資訊。 | Can you tell what is the following Python 3 function doing
def Rt_display(stock_no):
a = twsk(stock_no).real
if a:
re = "{%(time)s} %(stock_no)s %(c)s %(range)+.2f(%(pp)+.2f%%) %(value)s" % {
'stock_no': stock_no,
'time': a['time'],
'c': a['c'],
'range': covstr(a['range']),
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def ckinv(self,oo):
""" check the value is date or not
檢查是否為日期格式
"""
pattern = re.compile(r"[0-9]{2}/[0-9]{2}/[0-9]{2}")
b = re.search(pattern, oo[0])
try:
b.group()
return True
except:
return False | Can you write a function in Python 3 where it
checks the value is date or not | You are a Python code analyst, evaluating scripts for potential improvements. |
def high_or_low(self,one,two,rev=0):
""" Return ↑↓- for high, low or equal.
回傳漲跌標示
rev = 0
回傳 ↑↓-
rev = 1
回傳 1 -1 0
"""
if rev == 0:
if one > two:
re = '↑'.decode('utf-8')
elif one < two:
re = '↓'.decode('utf-8')
else:
re ... | Implement a Python 3 function for
returning ↑↓ - for high or low or equal. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Go back days
刪除最新天數資料數據
days 代表刪除多少天數(倒退幾天) | Can you generate a brief explanation for the following Python 3 code
def goback(self,days = 1):
for i in xrange(days):
self.raw_data.pop()
self.data_date.pop()
self.stock_range.pop()
self.stock_vol.pop()
self.stock_open.pop()
self.stock_h.pop()
self.stock_l.pop() | You are a Python code architect, reviewing and designing scalable and efficient code |
def fetch_data(self, stock_no, nowdatetime, firsttime = 1):
""" Fetch data from twse.com.tw
return list.
從 twse.com.tw 下載資料,回傳格式為 list
"""
url = 'http://www.twse.com.tw/ch/trading/exchange/STOCK_DAY/STOCK_DAY_print.php?genpage=genpage/Report%(year)d%(mon)02d/%(year)d%(mon)02d_F3_1_8_%(stock)... | Write a Python 3 function that can
fetch data from twse. com. tw | As a Python code composer, you craft elegant and concise scripts. |
def range_per(self):
""" Range percentage
計算最新日之漲跌幅度百分比
"""
rp = float((self.raw_data[-1] - self.raw_data[-2]) / self.raw_data[-2] * 100)
return rp | Write a Python 3 function that can
range percentage of the last two words | As a Python code composer, you craft elegant and concise scripts. |
Standard Deviation.
計算 days 日內之標準差,預設 45 日 | How would you explain what the following Python 3 function does
def SD(self, days=45):
if len(self.raw_data) >= days:
data = self.raw_data[-days:]
data_avg = float(sum(data) / days)
data2 = []
for x in data:
data2.append((x - data_avg ) ** 2)
return math.sqrt(sum(data2) / len(... | You are a Python code generator, capable of creating scripts from specifications. |
the last 45 days average. | Can you tell what is the following Python 3 function doing
def SDAVG(self, days=45):
if len(self.raw_data) >= days:
data = self.raw_data[-days:]
data_avg = float(sum(data) / days)
return data_avg
else:
return 0 | You are a Python code architect, reviewing and designing scalable and efficient code |
Coefficient of Variation.
計算 days 日內之變異數,預設 45 日 | Can you tell what is the following Python 3 function doing
def CV(self, days=45):
if len(self.raw_data) >= days:
data_avg = sum(self.raw_data[-days:]) / days
return self.SD / data_avg
else:
return 0 | You are a Python code generator, capable of creating scripts from specifications. |
In open market time. | Given the following Python 3 function, write the documentation
def TimeinOpen(self):
now = TWTime().now.hour
if now >= 9 and now <= 14:
return True
else:
return False | You are a Python code generator, capable of creating scripts from specifications. |
def MAC(self,days,rev = 0):
""" Comparing yesterday price is high, low or equal.
return ↑,↓ or -
與前一天 days 日收盤價移動平均比較
rev = 0
回傳 ↑,↓ or -
rev = 1
回傳 1,-1 or 0
"""
yesterday = self.raw_data[:]
yesterday.pop()
yes_MA = float(sum(yesterday[-days:]) / ... | How would you implement a function in Python 3 that
calculates the MAC of the given number of days. | You are a Python code generator, capable of creating scripts from specifications. |
make_serial is a wrapper around make_serial | Here you have a function in Python 3, explain what it does
def MA_serial(self,days,rev=0):
return self.make_serial(self.raw_data,days,rev) | As a Python code analyst, you investigate and solve complex coding mysteries |
def MACVOL(self,days,rev=0):
""" Comparing yesterday volume is high, low or equal.
return ↑,↓ or -
與前一天 days 日成交量移動平均比較
rev = 0
回傳 ↑,↓ or -
rev = 1
回傳 1,-1 or 0
"""
yesterday = self.stock_vol[:]
yesterday.pop()
yes_MAVOL = float(sum(yesterday[-days... | Write a Python 3 function that can
calculate the MACVOL of the given days | As a Python code composer, you craft elegant and concise scripts. |
def MAVOL_serial(self,days,rev=0):
""" see make_serial()
成較量移動平均 list 化,資料格式請見 def make_serial()
"""
return self.make_serial(self.stock_vol,days,rev=0) | Write a Python 3 function for
seeing make_serial() 成較量移動平均 list 化,資料格式請見 def make_serial() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check if volume is the max in last 3 days. | Can you generate the documentation for the following Python 3 function
def VOLMAX3(self):
if self.stock_vol[-1] > self.stock_vol[-2] and self.stock_vol[-1] > self.stock_vol[-3]:
return True
else:
return False | You are a Python code generator, capable of creating scripts from specifications. |
def RABC(self):
""" Return ABC
轉折點 ABC
"""
A = self.raw_data[-3]*2 - self.raw_data[-6]
B = self.raw_data[-2]*2 - self.raw_data[-5]
C = self.raw_data[-1]*2 - self.raw_data[-4]
return '(%.2f,%.2f,%.2f)' % (A,B,C) | Implement a function in Python 3 to
return ABC 轉折點 ABC | You are a Python code architect, reviewing and designing scalable and efficient code |
make data in list
Addon | Given the following Python 3 function, write the documentation
def make_serial(self,data,days,rev=0):
raw = data[:]
result = []
try:
while len(raw) >= days:
result.append(float(sum(raw[-days:]) / days))
raw.pop()
self.debug_print(len(result))
result.reverse()
re = ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Cumulate serial data
and return times(int)
計算數據重複(持續)次數 | Can you generate the documentation for the following Python 3 function
def cum_serial(self, raw,rev=0):
org = raw[1:]
diff = raw[:-1]
result = []
for i in xrange(len(org)):
result.append(self.high_or_low(org[i], diff[i],rev))
times = 0
try:
if result[-1] == result[-2]:
signa... | As a Python code composer, you craft elegant and concise scripts. |
def display(self,*arg):
""" For simple Demo
測試用顯示樣式。
"""
print self.stock_name,self.stock_no
print '%s %s %s(%+.2f%%)' % (self.data_date[-1],self.raw_data[-1],self.stock_range[-1],self.range_per)
for i in arg:
print ' - MA%02s %.2f %s(%s)' % (i,self.MA(i),self.MAC(i),self.MA_serial(i)... | Write a Python 3 script to
display the data in a single line. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Display the data in XMPP Demo. | Given the following Python 3 function, write the documentation
def XMPP_display(self,*arg):
MA = ''
for i in arg:
MAs = '- MA%02s: %.2f %s(%s)\n' % (
unicode(i),
self.MA(i),
self.MAC(i),
unicode(self.MA_serial(i)[0])
)
MA = MA + MAs
vol = '- Volume: %s %s(... | As a Python code analyst, you investigate and solve complex coding mysteries |
For Task overall stock display
顯示資訊樣式之一,兩行資訊。 | How would you explain what the following Python 3 function does
def Task_display(self):
re = """%(stock_name)s %(stock_no)s %(stock_date)s
Today: %(stock_price)s %(stock_range)s
=-=-=-=""" % {
'stock_name': unicode(self.stock_name),
'stock_no': unicode(self.stock_no),
'stock_date': unicode(s... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a list of url to the Google Chart API | Explain what the following Python 3 code does
def gchart(self, s = 0, size = [], candle = 20):
if s == 0:
s = len(self.raw_data)
if len(size) == 2:
sw,sh = size
else:
sh = 300
sw = 25 * s
if sw > 1000:
sw = 1000
candle = 950/s
stc = ''
for i in self.raw... | As a Python code translator, you convert algorithms and pseudocode into Python. |
add buy price to store | Can you tell what is the following Python 3 function doing
def buy(self, no, price, value):
''' 買 '''
self.money += -price*value
try:
self.store[no] += value
except:
self.store[no] = value
try:
self.avgprice[no]['buy'] += [price]
except:
try:
self.avgprice[no]['bu... | You are a Python code architect, reviewing and designing scalable and efficient code |
update the amount of the article with the given price | Given the following Python 3 function, write the documentation
def sell(self, no, price, value):
''' 賣 '''
self.money += price*value
try:
self.store[no] += -value
except:
self.store[no] = -value
try:
self.avgprice[no]['sell'] += [price]
except:
try:
self.avgprice[... | You are a Python code analyst, evaluating scripts for potential improvements. |
Prints information about the current state of the object. | Explain what the following Python 3 code does
def showinfo(self):
''' 總覽顯示 '''
print 'money:',self.money
print 'store:',self.store
print 'avgprice:',self.avgprice | As a Python code translator, you convert algorithms and pseudocode into Python. |
def search(self,q):
""" Search. """
import re
pattern = re.compile("%s" % q)
result = {}
for i in self.allstockno:
b = re.search(pattern, self.allstockno[i])
try:
b.group()
result[i] = self.allstockno[i]
except:
pass
return result | Implement a Python 3 function for
searching for the given stock number. | As a Python code analyst, you investigate and solve complex coding mysteries |
This function solves the VFD mode for a specific set of eigenmodes. | Here you have a function in Python 3, explain what it does
def solve(self, neigs=4, tol=0, guess=None, mode_profiles=True, initial_mode_guess=None):
from scipy.sparse.linalg import eigen
self.nmodes = neigs
self.tol = tol
A = self.build_matrix()
if guess is not None:
... | As a python code expert, you are capable of creating scripts from specifications. |
Return real time data | Given the following Python 3 function, write the documentation
def real(self):
try:
unch = sum([covstr(self.stock[3]),covstr(self.stock[4])])/2
re = {'name': unicode(self.stock[36].replace(' ',''), 'cp950'),
'no': self.stock[0],
'range': self.stock[1],
'time': self.st... | As a python code expert, you are capable of creating scripts from specifications. |
def now(self):
''' Display Taiwan Time now
顯示台灣此刻時間
'''
localtime = datetime.datetime.now()
return localtime + datetime.timedelta(hours = time.timezone/60/60 + self.TimeZone) | Implement a Python 3 function for
displaying Taiwan Time now 顯示台灣此刻時間 | As a Python code analyst, you investigate and solve complex coding mysteries |
Display Taiwan date now
顯示台灣此刻日期 | Explain what the following Python 3 code does
def date(self):
''' Display Taiwan date now
顯示台灣此刻日期
'''
localtime = datetime.date.today()
return localtime + datetime.timedelta(hours = time.timezone/60/60 + self.TimeZone) | You are a Python code analyst, evaluating scripts for potential improvements. |
Calculates the coherence length of the directional coupler. | Here you have a function in Python 3, explain what it does
def directional_coupler_lc(wavelength_nm, n_eff_1, n_eff_2):
'''
Calculates the coherence length (100% power transfer) of a
directional coupler.
Args:
wavelength_nm (float): The wavelength in [nm] the
directional coupler sho... | You are a Python code generator, capable of creating scripts from specifications. |
Calculates the period needed for a grating coupler. | Here you have a function in Python 3, explain what it does
def grating_coupler_period(wavelength,
n_eff,
n_clad,
incidence_angle_deg,
diffration_order=1):
'''
Calculate the period needed for a grating cou... | As a Python code analyst, you investigate and solve complex coding mysteries |
def read_file(filename, prepend_paths=[]):
"""
Returns the contents of *filename* (UTF-8).
If *prepend_paths* is set, join those before the *fielname*.
If it is `True`, prepend the path to `setup.py`.
"""
if prepend_paths is True:
prepend_paths = [
os.path.abspath(os.path.dirname(__file__)),
... | Write a Python 3 script for
reading a file into a string. | As a python code expert, you are capable of creating scripts from specifications. |
Load the date from CSV file. | Make a summary of the following Python 3 code
def loaddate(self):
''' 載入檔案
檔案依據 http://www.twse.com.tw/ch/trading/trading_days.php
'''
ld = csv.reader(open('./%s/opendate.csv' % _CSVFILEPATH, 'r'))
re = {}
re['close'] = []
re['open'] = []
for i in ld:
''' 0 = 休市, 1 = 開市 '''
... | As a Python code composer, you craft elegant and concise scripts. |
def ooc(self):
''' Open or close
回傳 True:開市,False:休市。
'''
if self.ptime.date() in self.ocdate['close']: ## 判對是否為法定休市
return False
elif self.ptime.date() in self.ocdate['open']: ## 判對是否為法定開市
return True
else:
''' 判斷是否為每週開休市 '''
if self.ptime.weekday() <= 4:
ret... | Create a Python 3 function for
returning True if the object is open False if it is close True if it is open False if it is close True if it is open False if it is close False if it is not close | You are a Python code generator, capable of creating scripts from specifications. |
A CK portf is 1999 | Can you generate a brief explanation for the following Python 3 code
def ck_portf_001(self):
''' 3-6負乖離且向上,三日內最大量,成交量大於 1000 張,收盤價大於 10 元。(較嚴謹的選股)'''
return self.a.MAO(3,6)[1] == '↑'.decode('utf-8') and (self.a.MAO(3,6)[0][1][-1] < 0 or ( self.a.MAO(3,6)[0][1][-1] < 1 and self.a.MAO(3,6)[0][1][-1] > 0 and self.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def ck_portf_002(self):
''' 3日均價大於6日均價,6日均價大於18日均價。(短中長線呈現多頭的態勢) '''
return self.a.MA(3) > self.a.MA(6) > self.a.MA(18) and self.a.MAC(18) == '↑'.decode('utf-8') and self.a.stock_vol[-1] > 1000*1000 and self.a.raw_data[-1] > 10 | Create a Python 3 function for
testing if portf is 0 | You are a Python code generator, capable of creating scripts from specifications. |
Checks if portf is 0. 0 | Explain what the following Python 3 code does
def ck_portf_004(self):
''' 價走平一個半月。(箱型整理、盤整) '''
return self.a.SD < 0.25 and self.a.stock_vol[-1] > 1000*1000 and self.a.raw_data[-1] > 10 | As a Python code composer, you craft elegant and concise scripts. |
def reflection(n1, n2):
'''
Calculate the power reflection at the interface
of two refractive index materials.
Args:
n1 (float): Refractive index of material 1.
n2 (float): Refractive index of material 2.
Returns:
float: The percentage of reflected power.
'''
r = ab... | Can you create a Python 3 function that
calculates the power reflection at the interface of two refractive index materials. | You are a Python code architect, reviewing and designing scalable and efficient code |
def coupling_efficiency(mode_solver, fibre_mfd,
fibre_offset_x=0, fibre_offset_y=0,
n_eff_fibre=1.441):
'''
Finds the coupling efficiency between a solved
fundamental mode and a fibre of given MFD.
Args:
mode_solver (_ModeSolver): Mode solver that... | Create a Python 3 function to
find the coupling efficiency between a solved fundamental mode and a fibre. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def getIndex(reference):
'''
Find the reference folder using the location of the script file
Create the index, test if successful
'''
if reference:
reffas = reference
else:
parent_directory = path.dirname(path.abspath(path.dirname(__file__)))
reffas = path.join(parent_dir... | Can you write a function in Python 3 where it
creates the index for the given reference folder | As a python code expert, you are capable of creating scripts from specifications. |
Test if reads can get aligned to the lambda genome and write to stdout
| Can you generate a brief explanation for the following Python 3 code
def align(aligner, reads):
'''
Test if reads can get aligned to the lambda genome,
if not: write to stdout
'''
i = 0
for record in SeqIO.parse(reads, "fastq"):
try:
next(aligner.map(str(record.seq)))
... | As a Python code composer, you craft elegant and concise scripts. |
Converts the response to tables class. | Explain what the following Python 3 code does
def _convert_json_response_to_entities(response, property_resolver, require_encryption,
key_encryption_key, key_resolver):
''' Converts the response to tables class.
'''
if response is None or response.body is None:
... | As a Python code composer, you craft elegant and concise scripts. |
def _exec_ipmitool(driver_info, command):
"""Execute the ipmitool command.
This uses the lanplus interface to communicate with the BMC device driver.
:param driver_info: the ipmitool parameters for accessing a node.
:param command: the ipmitool command to be executed.
"""
ipmi_cmd = ("ipmitoo... | Write a Python 3 script to
execute the ipmitool command. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Gets the max capacity supported by the NIC adapter. | How would you explain what the following Python 3 function does
def get_nic_capacity(driver_info, ilo_fw):
i = 0x0
value = None
ilo_fw_rev = get_ilo_version(ilo_fw) or DEFAULT_FW_REV
# Note(vmud213): iLO firmware versions >= 2.3 support reading the FRU
# information in a single call instead of iter... | As a python code expert, you are capable of creating scripts from specifications. |
def _parse_ipmi_nic_capacity(nic_out):
"""Parse the FRU output for NIC capacity
Parses the FRU output. Seraches for the key "Product Name"
in FRU output and greps for maximum speed supported by the
NIC adapter.
:param nic_out: the FRU output for NIC adapter.
:returns: the max capacity supporte... | Write a Python 3 script for
parsing the NIC capacity output for the NIC adapter. | You are a Python code analyst, evaluating scripts for potential improvements. |
Extracts the encryption metadata from the given entity. | Can you generate the documentation for the following Python 3 function
def _extract_encryption_metadata(entity, require_encryption, key_encryption_key, key_resolver):
'''
Extracts the encryption metadata from the given entity, setting them to be utf-8 strings.
If no encryption metadata is present, will retu... | You are a Python code analyst, evaluating scripts for potential improvements. |
def logical_drives(self):
"""Gets the resource HPELogicalDriveCollection of ArrayControllers"""
return logical_drive.HPELogicalDriveCollection(
self._conn, utils.get_subresource_path_by(
self, ['Links', 'LogicalDrives']),
redfish_version=self.redfish_version) | Write a Python 3 function for
getting the resource HPELogicalDriveCollection of ArrayControllers | As a Python code analyst, you investigate and solve complex coding mysteries |
def physical_drives(self):
"""Gets the resource HPEPhysicalDriveCollection of ArrayControllers"""
return physical_drive.HPEPhysicalDriveCollection(
self._conn, utils.get_subresource_path_by(
self, ['Links', 'PhysicalDrives']),
redfish_version=self.redfish_version) | Create a Python 3 function for
getting the resource HPEPhysicalDriveCollection of ArrayControllers | You are a Python code analyst, evaluating scripts for potential improvements. |
def logical_drives_maximum_size_mib(self):
"""Gets the biggest logical drive
:returns the size in MiB.
"""
return utils.max_safe([member.logical_drives.maximum_size_mib
for member in self.get_members()]) | Create a Python 3 function for
getting the biggest logical drive | As a Python code translator, you convert algorithms and pseudocode into Python. |
def physical_drives_maximum_size_mib(self):
"""Gets the biggest disk
:returns the size in MiB.
"""
return utils.max_safe([member.physical_drives.maximum_size_mib
for member in self.get_members()]) | Can you write a function in Python 3 where it
gets the biggest disk clf. | You are a Python code generator, capable of creating scripts from specifications. |
Return true if any of the array controllers is ssd | Make a summary of the following Python 3 code
def has_ssd(self):
for member in self.get_members():
if member.physical_drives.has_ssd:
return True
return False | As a Python code composer, you craft elegant and concise scripts. |
Return true if any of the members of ArrayControllers is ssd | Can you tell what is the following Python 3 function doing
def has_rotational(self):
for member in self.get_members():
if member.physical_drives.has_rotational:
return True
return False | As a python code expert, you are capable of creating scripts from specifications. |
def logical_raid_levels(self):
"""Gets the raid level for each logical volume
:returns the set of list of raid levels configured
"""
lg_raid_lvls = set()
for member in self.get_members():
lg_raid_lvls.update(member.logical_drives.logical_raid_levels)
return l... | Write a Python 3 function for
getting the set of raid levels configured for each logical volume | You are a Python code generator, capable of creating scripts from specifications. |
Returns array controller instance by location | Given the following Python 3 function, write the documentation
def array_controller_by_location(self, location):
for member in self.get_members():
if member.location == location:
return member | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.