repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
wind-python/windpowerlib | windpowerlib/wind_turbine_cluster.py | WindTurbineCluster.mean_hub_height | def mean_hub_height(self):
r"""
Calculates the mean hub height of the wind turbine cluster.
The mean hub height of a wind turbine cluster is necessary for power
output calculations with an aggregated wind turbine cluster power
curve. Hub heights of wind farms with higher nominal power weigh more
than others. Assigns the hub height to the turbine cluster object.
Returns
-------
self
Notes
-----
The following equation is used [1]_:
.. math:: h_{WTC} = e^{\sum\limits_{k}{ln(h_{WF,k})}
\frac{P_{N,k}}{\sum\limits_{k}{P_{N,k}}}}
with:
:math:`h_{WTC}`: mean hub height of wind turbine cluster,
:math:`h_{WF,k}`: hub height of the k-th wind farm of the cluster,
:math:`P_{N,k}`: installed power of the k-th wind farm
References
----------
.. [1] Knorr, K.: "Modellierung von raum-zeitlichen Eigenschaften der
Windenergieeinspeisung für wetterdatenbasierte
Windleistungssimulationen". Universität Kassel, Diss., 2016,
p. 35
"""
self.hub_height = np.exp(sum(
np.log(wind_farm.hub_height) * wind_farm.get_installed_power() for
wind_farm in self.wind_farms) / self.get_installed_power())
return self | python | def mean_hub_height(self):
r"""
Calculates the mean hub height of the wind turbine cluster.
The mean hub height of a wind turbine cluster is necessary for power
output calculations with an aggregated wind turbine cluster power
curve. Hub heights of wind farms with higher nominal power weigh more
than others. Assigns the hub height to the turbine cluster object.
Returns
-------
self
Notes
-----
The following equation is used [1]_:
.. math:: h_{WTC} = e^{\sum\limits_{k}{ln(h_{WF,k})}
\frac{P_{N,k}}{\sum\limits_{k}{P_{N,k}}}}
with:
:math:`h_{WTC}`: mean hub height of wind turbine cluster,
:math:`h_{WF,k}`: hub height of the k-th wind farm of the cluster,
:math:`P_{N,k}`: installed power of the k-th wind farm
References
----------
.. [1] Knorr, K.: "Modellierung von raum-zeitlichen Eigenschaften der
Windenergieeinspeisung für wetterdatenbasierte
Windleistungssimulationen". Universität Kassel, Diss., 2016,
p. 35
"""
self.hub_height = np.exp(sum(
np.log(wind_farm.hub_height) * wind_farm.get_installed_power() for
wind_farm in self.wind_farms) / self.get_installed_power())
return self | [
"def",
"mean_hub_height",
"(",
"self",
")",
":",
"self",
".",
"hub_height",
"=",
"np",
".",
"exp",
"(",
"sum",
"(",
"np",
".",
"log",
"(",
"wind_farm",
".",
"hub_height",
")",
"*",
"wind_farm",
".",
"get_installed_power",
"(",
")",
"for",
"wind_farm",
... | r"""
Calculates the mean hub height of the wind turbine cluster.
The mean hub height of a wind turbine cluster is necessary for power
output calculations with an aggregated wind turbine cluster power
curve. Hub heights of wind farms with higher nominal power weigh more
than others. Assigns the hub height to the turbine cluster object.
Returns
-------
self
Notes
-----
The following equation is used [1]_:
.. math:: h_{WTC} = e^{\sum\limits_{k}{ln(h_{WF,k})}
\frac{P_{N,k}}{\sum\limits_{k}{P_{N,k}}}}
with:
:math:`h_{WTC}`: mean hub height of wind turbine cluster,
:math:`h_{WF,k}`: hub height of the k-th wind farm of the cluster,
:math:`P_{N,k}`: installed power of the k-th wind farm
References
----------
.. [1] Knorr, K.: "Modellierung von raum-zeitlichen Eigenschaften der
Windenergieeinspeisung für wetterdatenbasierte
Windleistungssimulationen". Universität Kassel, Diss., 2016,
p. 35 | [
"r",
"Calculates",
"the",
"mean",
"hub",
"height",
"of",
"the",
"wind",
"turbine",
"cluster",
"."
] | 421b316139743311b7cb68a69f6b53d2665f7e23 | https://github.com/wind-python/windpowerlib/blob/421b316139743311b7cb68a69f6b53d2665f7e23/windpowerlib/wind_turbine_cluster.py#L62-L98 | train | 202,100 |
wind-python/windpowerlib | windpowerlib/wind_turbine_cluster.py | WindTurbineCluster.get_installed_power | def get_installed_power(self):
r"""
Calculates the installed power of a wind turbine cluster.
Returns
-------
float
Installed power of the wind turbine cluster.
"""
for wind_farm in self.wind_farms:
wind_farm.installed_power = wind_farm.get_installed_power()
return sum(wind_farm.installed_power for wind_farm in self.wind_farms) | python | def get_installed_power(self):
r"""
Calculates the installed power of a wind turbine cluster.
Returns
-------
float
Installed power of the wind turbine cluster.
"""
for wind_farm in self.wind_farms:
wind_farm.installed_power = wind_farm.get_installed_power()
return sum(wind_farm.installed_power for wind_farm in self.wind_farms) | [
"def",
"get_installed_power",
"(",
"self",
")",
":",
"for",
"wind_farm",
"in",
"self",
".",
"wind_farms",
":",
"wind_farm",
".",
"installed_power",
"=",
"wind_farm",
".",
"get_installed_power",
"(",
")",
"return",
"sum",
"(",
"wind_farm",
".",
"installed_power",... | r"""
Calculates the installed power of a wind turbine cluster.
Returns
-------
float
Installed power of the wind turbine cluster. | [
"r",
"Calculates",
"the",
"installed",
"power",
"of",
"a",
"wind",
"turbine",
"cluster",
"."
] | 421b316139743311b7cb68a69f6b53d2665f7e23 | https://github.com/wind-python/windpowerlib/blob/421b316139743311b7cb68a69f6b53d2665f7e23/windpowerlib/wind_turbine_cluster.py#L100-L112 | train | 202,101 |
wind-python/windpowerlib | windpowerlib/wind_turbine_cluster.py | WindTurbineCluster.assign_power_curve | def assign_power_curve(self, wake_losses_model='power_efficiency_curve',
smoothing=False, block_width=0.5,
standard_deviation_method='turbulence_intensity',
smoothing_order='wind_farm_power_curves',
turbulence_intensity=None, **kwargs):
r"""
Calculates the power curve of a wind turbine cluster.
The turbine cluster power curve is calculated by aggregating the wind
farm power curves of wind farms within the turbine cluster. Depending
on the parameters the power curves are smoothed (before or after the
aggregation) and/or a wind farm efficiency is applied before the
aggregation.
After the calculations the power curve is assigned to the attribute
`power_curve`.
Parameters
----------
wake_losses_model : string
Defines the method for taking wake losses within the farm into
consideration. Options: 'power_efficiency_curve',
'constant_efficiency' or None. Default: 'power_efficiency_curve'.
smoothing : boolean
If True the power curves will be smoothed before or after the
aggregation of power curves depending on `smoothing_order`.
Default: False.
block_width : float
Width between the wind speeds in the sum of the equation in
:py:func:`~.power_curves.smooth_power_curve`. Default: 0.5.
standard_deviation_method : string
Method for calculating the standard deviation for the Gauss
distribution. Options: 'turbulence_intensity',
'Staffell_Pfenninger'. Default: 'turbulence_intensity'.
smoothing_order : string
Defines when the smoothing takes place if `smoothing` is True.
Options: 'turbine_power_curves' (to the single turbine power
curves), 'wind_farm_power_curves'.
Default: 'wind_farm_power_curves'.
turbulence_intensity : float
Turbulence intensity at hub height of the wind farm or
wind turbine cluster for power curve smoothing with
'turbulence_intensity' method. Can be calculated from
`roughness_length` instead. Default: None.
Other Parameters
----------------
roughness_length : float, optional.
Roughness length. If `standard_deviation_method` is
'turbulence_intensity' and `turbulence_intensity` is not given
the turbulence intensity is calculated via the roughness length.
Returns
-------
self
"""
# Assign wind farm power curves to wind farms of wind turbine cluster
for farm in self.wind_farms:
# Assign hub heights (needed for power curve and later for
# hub height of turbine cluster)
farm.mean_hub_height()
# Assign wind farm power curve
farm.assign_power_curve(
wake_losses_model=wake_losses_model,
smoothing=smoothing, block_width=block_width,
standard_deviation_method=standard_deviation_method,
smoothing_order=smoothing_order,
turbulence_intensity=turbulence_intensity, **kwargs)
# Create data frame from power curves of all wind farms
df = pd.concat([farm.power_curve.set_index(['wind_speed']).rename(
columns={'value': farm.name}) for
farm in self.wind_farms], axis=1)
# Sum up power curves
cluster_power_curve = pd.DataFrame(
df.interpolate(method='index').sum(axis=1))
cluster_power_curve.columns = ['value']
# Return wind speed (index) to a column of the data frame
cluster_power_curve.reset_index('wind_speed', inplace=True)
self.power_curve = cluster_power_curve
return self | python | def assign_power_curve(self, wake_losses_model='power_efficiency_curve',
smoothing=False, block_width=0.5,
standard_deviation_method='turbulence_intensity',
smoothing_order='wind_farm_power_curves',
turbulence_intensity=None, **kwargs):
r"""
Calculates the power curve of a wind turbine cluster.
The turbine cluster power curve is calculated by aggregating the wind
farm power curves of wind farms within the turbine cluster. Depending
on the parameters the power curves are smoothed (before or after the
aggregation) and/or a wind farm efficiency is applied before the
aggregation.
After the calculations the power curve is assigned to the attribute
`power_curve`.
Parameters
----------
wake_losses_model : string
Defines the method for taking wake losses within the farm into
consideration. Options: 'power_efficiency_curve',
'constant_efficiency' or None. Default: 'power_efficiency_curve'.
smoothing : boolean
If True the power curves will be smoothed before or after the
aggregation of power curves depending on `smoothing_order`.
Default: False.
block_width : float
Width between the wind speeds in the sum of the equation in
:py:func:`~.power_curves.smooth_power_curve`. Default: 0.5.
standard_deviation_method : string
Method for calculating the standard deviation for the Gauss
distribution. Options: 'turbulence_intensity',
'Staffell_Pfenninger'. Default: 'turbulence_intensity'.
smoothing_order : string
Defines when the smoothing takes place if `smoothing` is True.
Options: 'turbine_power_curves' (to the single turbine power
curves), 'wind_farm_power_curves'.
Default: 'wind_farm_power_curves'.
turbulence_intensity : float
Turbulence intensity at hub height of the wind farm or
wind turbine cluster for power curve smoothing with
'turbulence_intensity' method. Can be calculated from
`roughness_length` instead. Default: None.
Other Parameters
----------------
roughness_length : float, optional.
Roughness length. If `standard_deviation_method` is
'turbulence_intensity' and `turbulence_intensity` is not given
the turbulence intensity is calculated via the roughness length.
Returns
-------
self
"""
# Assign wind farm power curves to wind farms of wind turbine cluster
for farm in self.wind_farms:
# Assign hub heights (needed for power curve and later for
# hub height of turbine cluster)
farm.mean_hub_height()
# Assign wind farm power curve
farm.assign_power_curve(
wake_losses_model=wake_losses_model,
smoothing=smoothing, block_width=block_width,
standard_deviation_method=standard_deviation_method,
smoothing_order=smoothing_order,
turbulence_intensity=turbulence_intensity, **kwargs)
# Create data frame from power curves of all wind farms
df = pd.concat([farm.power_curve.set_index(['wind_speed']).rename(
columns={'value': farm.name}) for
farm in self.wind_farms], axis=1)
# Sum up power curves
cluster_power_curve = pd.DataFrame(
df.interpolate(method='index').sum(axis=1))
cluster_power_curve.columns = ['value']
# Return wind speed (index) to a column of the data frame
cluster_power_curve.reset_index('wind_speed', inplace=True)
self.power_curve = cluster_power_curve
return self | [
"def",
"assign_power_curve",
"(",
"self",
",",
"wake_losses_model",
"=",
"'power_efficiency_curve'",
",",
"smoothing",
"=",
"False",
",",
"block_width",
"=",
"0.5",
",",
"standard_deviation_method",
"=",
"'turbulence_intensity'",
",",
"smoothing_order",
"=",
"'wind_farm... | r"""
Calculates the power curve of a wind turbine cluster.
The turbine cluster power curve is calculated by aggregating the wind
farm power curves of wind farms within the turbine cluster. Depending
on the parameters the power curves are smoothed (before or after the
aggregation) and/or a wind farm efficiency is applied before the
aggregation.
After the calculations the power curve is assigned to the attribute
`power_curve`.
Parameters
----------
wake_losses_model : string
Defines the method for taking wake losses within the farm into
consideration. Options: 'power_efficiency_curve',
'constant_efficiency' or None. Default: 'power_efficiency_curve'.
smoothing : boolean
If True the power curves will be smoothed before or after the
aggregation of power curves depending on `smoothing_order`.
Default: False.
block_width : float
Width between the wind speeds in the sum of the equation in
:py:func:`~.power_curves.smooth_power_curve`. Default: 0.5.
standard_deviation_method : string
Method for calculating the standard deviation for the Gauss
distribution. Options: 'turbulence_intensity',
'Staffell_Pfenninger'. Default: 'turbulence_intensity'.
smoothing_order : string
Defines when the smoothing takes place if `smoothing` is True.
Options: 'turbine_power_curves' (to the single turbine power
curves), 'wind_farm_power_curves'.
Default: 'wind_farm_power_curves'.
turbulence_intensity : float
Turbulence intensity at hub height of the wind farm or
wind turbine cluster for power curve smoothing with
'turbulence_intensity' method. Can be calculated from
`roughness_length` instead. Default: None.
Other Parameters
----------------
roughness_length : float, optional.
Roughness length. If `standard_deviation_method` is
'turbulence_intensity' and `turbulence_intensity` is not given
the turbulence intensity is calculated via the roughness length.
Returns
-------
self | [
"r",
"Calculates",
"the",
"power",
"curve",
"of",
"a",
"wind",
"turbine",
"cluster",
"."
] | 421b316139743311b7cb68a69f6b53d2665f7e23 | https://github.com/wind-python/windpowerlib/blob/421b316139743311b7cb68a69f6b53d2665f7e23/windpowerlib/wind_turbine_cluster.py#L114-L193 | train | 202,102 |
wind-python/windpowerlib | example/turbine_cluster_modelchain_example.py | run_example | def run_example():
r"""
Runs the example.
"""
weather = mc_e.get_weather_data('weather.csv')
my_turbine, e126, dummy_turbine = mc_e.initialize_wind_turbines()
example_farm, example_farm_2 = initialize_wind_farms(my_turbine, e126)
example_cluster = initialize_wind_turbine_cluster(example_farm,
example_farm_2)
calculate_power_output(weather, example_farm, example_cluster)
plot_or_print(example_farm, example_cluster) | python | def run_example():
r"""
Runs the example.
"""
weather = mc_e.get_weather_data('weather.csv')
my_turbine, e126, dummy_turbine = mc_e.initialize_wind_turbines()
example_farm, example_farm_2 = initialize_wind_farms(my_turbine, e126)
example_cluster = initialize_wind_turbine_cluster(example_farm,
example_farm_2)
calculate_power_output(weather, example_farm, example_cluster)
plot_or_print(example_farm, example_cluster) | [
"def",
"run_example",
"(",
")",
":",
"weather",
"=",
"mc_e",
".",
"get_weather_data",
"(",
"'weather.csv'",
")",
"my_turbine",
",",
"e126",
",",
"dummy_turbine",
"=",
"mc_e",
".",
"initialize_wind_turbines",
"(",
")",
"example_farm",
",",
"example_farm_2",
"=",
... | r"""
Runs the example. | [
"r",
"Runs",
"the",
"example",
"."
] | 421b316139743311b7cb68a69f6b53d2665f7e23 | https://github.com/wind-python/windpowerlib/blob/421b316139743311b7cb68a69f6b53d2665f7e23/example/turbine_cluster_modelchain_example.py#L209-L220 | train | 202,103 |
wind-python/windpowerlib | windpowerlib/wind_turbine.py | WindTurbine.fetch_turbine_data | def fetch_turbine_data(self, fetch_curve, data_source):
r"""
Fetches data of the requested wind turbine.
Method fetches nominal power as well as power coefficient curve or
power curve from a data set provided in the OpenEnergy Database
(oedb). You can also import your own power (coefficient) curves from a
file. For that the wind speeds in m/s have to be in the first row and
the corresponding power coefficient curve values or power curve values
in W in a row where the first column contains the turbine name.
See `example_power_curves.csv' and
`example_power_coefficient_curves.csv` in example/data for the required
form of a csv file (more columns can be added). See
:py:func:`~.get_turbine_data_from_file` for an example reading data
from a csv file.
Parameters
----------
fetch_curve : string
Parameter to specify whether a power or power coefficient curve
should be retrieved from the provided turbine data. Valid options
are 'power_curve' and 'power_coefficient_curve'. Default: None.
data_source : string
Specifies whether turbine data (f.e. nominal power, power curve,
power coefficient curve) is loaded from the OpenEnergy Database
('oedb') or from a csv file ('<path including file name>').
Default: 'oedb'.
Returns
-------
self
Examples
--------
>>> from windpowerlib import wind_turbine
>>> enerconE126 = {
... 'hub_height': 135,
... 'rotor_diameter': 127,
... 'name': 'E-126/4200',
... 'fetch_curve': 'power_coefficient_curve',
... 'data_source': 'oedb'}
>>> e126 = wind_turbine.WindTurbine(**enerconE126)
>>> print(e126.power_coefficient_curve['value'][5])
0.44
>>> print(e126.nominal_power)
4200000.0
"""
if data_source == 'oedb':
curve_df, nominal_power = get_turbine_data_from_oedb(
turbine_type=self.name, fetch_curve=fetch_curve)
else:
curve_df, nominal_power = get_turbine_data_from_file(
turbine_type=self.name, file_=data_source)
if fetch_curve == 'power_curve':
self.power_curve = curve_df
elif fetch_curve == 'power_coefficient_curve':
self.power_coefficient_curve = curve_df
else:
raise ValueError("'{0}' is an invalid value. ".format(
fetch_curve) + "`fetch_curve` must be " +
"'power_curve' or 'power_coefficient_curve'.")
if self.nominal_power is None:
self.nominal_power = nominal_power
return self | python | def fetch_turbine_data(self, fetch_curve, data_source):
r"""
Fetches data of the requested wind turbine.
Method fetches nominal power as well as power coefficient curve or
power curve from a data set provided in the OpenEnergy Database
(oedb). You can also import your own power (coefficient) curves from a
file. For that the wind speeds in m/s have to be in the first row and
the corresponding power coefficient curve values or power curve values
in W in a row where the first column contains the turbine name.
See `example_power_curves.csv' and
`example_power_coefficient_curves.csv` in example/data for the required
form of a csv file (more columns can be added). See
:py:func:`~.get_turbine_data_from_file` for an example reading data
from a csv file.
Parameters
----------
fetch_curve : string
Parameter to specify whether a power or power coefficient curve
should be retrieved from the provided turbine data. Valid options
are 'power_curve' and 'power_coefficient_curve'. Default: None.
data_source : string
Specifies whether turbine data (f.e. nominal power, power curve,
power coefficient curve) is loaded from the OpenEnergy Database
('oedb') or from a csv file ('<path including file name>').
Default: 'oedb'.
Returns
-------
self
Examples
--------
>>> from windpowerlib import wind_turbine
>>> enerconE126 = {
... 'hub_height': 135,
... 'rotor_diameter': 127,
... 'name': 'E-126/4200',
... 'fetch_curve': 'power_coefficient_curve',
... 'data_source': 'oedb'}
>>> e126 = wind_turbine.WindTurbine(**enerconE126)
>>> print(e126.power_coefficient_curve['value'][5])
0.44
>>> print(e126.nominal_power)
4200000.0
"""
if data_source == 'oedb':
curve_df, nominal_power = get_turbine_data_from_oedb(
turbine_type=self.name, fetch_curve=fetch_curve)
else:
curve_df, nominal_power = get_turbine_data_from_file(
turbine_type=self.name, file_=data_source)
if fetch_curve == 'power_curve':
self.power_curve = curve_df
elif fetch_curve == 'power_coefficient_curve':
self.power_coefficient_curve = curve_df
else:
raise ValueError("'{0}' is an invalid value. ".format(
fetch_curve) + "`fetch_curve` must be " +
"'power_curve' or 'power_coefficient_curve'.")
if self.nominal_power is None:
self.nominal_power = nominal_power
return self | [
"def",
"fetch_turbine_data",
"(",
"self",
",",
"fetch_curve",
",",
"data_source",
")",
":",
"if",
"data_source",
"==",
"'oedb'",
":",
"curve_df",
",",
"nominal_power",
"=",
"get_turbine_data_from_oedb",
"(",
"turbine_type",
"=",
"self",
".",
"name",
",",
"fetch_... | r"""
Fetches data of the requested wind turbine.
Method fetches nominal power as well as power coefficient curve or
power curve from a data set provided in the OpenEnergy Database
(oedb). You can also import your own power (coefficient) curves from a
file. For that the wind speeds in m/s have to be in the first row and
the corresponding power coefficient curve values or power curve values
in W in a row where the first column contains the turbine name.
See `example_power_curves.csv' and
`example_power_coefficient_curves.csv` in example/data for the required
form of a csv file (more columns can be added). See
:py:func:`~.get_turbine_data_from_file` for an example reading data
from a csv file.
Parameters
----------
fetch_curve : string
Parameter to specify whether a power or power coefficient curve
should be retrieved from the provided turbine data. Valid options
are 'power_curve' and 'power_coefficient_curve'. Default: None.
data_source : string
Specifies whether turbine data (f.e. nominal power, power curve,
power coefficient curve) is loaded from the OpenEnergy Database
('oedb') or from a csv file ('<path including file name>').
Default: 'oedb'.
Returns
-------
self
Examples
--------
>>> from windpowerlib import wind_turbine
>>> enerconE126 = {
... 'hub_height': 135,
... 'rotor_diameter': 127,
... 'name': 'E-126/4200',
... 'fetch_curve': 'power_coefficient_curve',
... 'data_source': 'oedb'}
>>> e126 = wind_turbine.WindTurbine(**enerconE126)
>>> print(e126.power_coefficient_curve['value'][5])
0.44
>>> print(e126.nominal_power)
4200000.0 | [
"r",
"Fetches",
"data",
"of",
"the",
"requested",
"wind",
"turbine",
"."
] | 421b316139743311b7cb68a69f6b53d2665f7e23 | https://github.com/wind-python/windpowerlib/blob/421b316139743311b7cb68a69f6b53d2665f7e23/windpowerlib/wind_turbine.py#L126-L190 | train | 202,104 |
tkrajina/srtm.py | srtm/utils.py | distance | def distance(latitude_1, longitude_1, latitude_2, longitude_2):
"""
Distance between two points.
"""
coef = mod_math.cos(latitude_1 / 180. * mod_math.pi)
x = latitude_1 - latitude_2
y = (longitude_1 - longitude_2) * coef
return mod_math.sqrt(x * x + y * y) * ONE_DEGREE | python | def distance(latitude_1, longitude_1, latitude_2, longitude_2):
"""
Distance between two points.
"""
coef = mod_math.cos(latitude_1 / 180. * mod_math.pi)
x = latitude_1 - latitude_2
y = (longitude_1 - longitude_2) * coef
return mod_math.sqrt(x * x + y * y) * ONE_DEGREE | [
"def",
"distance",
"(",
"latitude_1",
",",
"longitude_1",
",",
"latitude_2",
",",
"longitude_2",
")",
":",
"coef",
"=",
"mod_math",
".",
"cos",
"(",
"latitude_1",
"/",
"180.",
"*",
"mod_math",
".",
"pi",
")",
"x",
"=",
"latitude_1",
"-",
"latitude_2",
"y... | Distance between two points. | [
"Distance",
"between",
"two",
"points",
"."
] | 37fb8a6f52c8ca25565772e59e867ac26181f829 | https://github.com/tkrajina/srtm.py/blob/37fb8a6f52c8ca25565772e59e867ac26181f829/srtm/utils.py#L28-L37 | train | 202,105 |
tkrajina/srtm.py | srtm/utils.py | get_color_between | def get_color_between(color1, color2, i):
""" i is a number between 0 and 1, if 0 then color1, if 1 color2, ... """
if i <= 0:
return color1
if i >= 1:
return color2
return (int(color1[0] + (color2[0] - color1[0]) * i),
int(color1[1] + (color2[1] - color1[1]) * i),
int(color1[2] + (color2[2] - color1[2]) * i)) | python | def get_color_between(color1, color2, i):
""" i is a number between 0 and 1, if 0 then color1, if 1 color2, ... """
if i <= 0:
return color1
if i >= 1:
return color2
return (int(color1[0] + (color2[0] - color1[0]) * i),
int(color1[1] + (color2[1] - color1[1]) * i),
int(color1[2] + (color2[2] - color1[2]) * i)) | [
"def",
"get_color_between",
"(",
"color1",
",",
"color2",
",",
"i",
")",
":",
"if",
"i",
"<=",
"0",
":",
"return",
"color1",
"if",
"i",
">=",
"1",
":",
"return",
"color2",
"return",
"(",
"int",
"(",
"color1",
"[",
"0",
"]",
"+",
"(",
"color2",
"[... | i is a number between 0 and 1, if 0 then color1, if 1 color2, ... | [
"i",
"is",
"a",
"number",
"between",
"0",
"and",
"1",
"if",
"0",
"then",
"color1",
"if",
"1",
"color2",
"..."
] | 37fb8a6f52c8ca25565772e59e867ac26181f829 | https://github.com/tkrajina/srtm.py/blob/37fb8a6f52c8ca25565772e59e867ac26181f829/srtm/utils.py#L39-L47 | train | 202,106 |
tkrajina/srtm.py | srtm/data.py | GeoElevationData._IDW | def _IDW(self, latitude, longitude, radius=1):
"""
Return the interpolated elevation at a point.
Load the correct tile for latitude and longitude given.
If the tile doesn't exist, return None. Otherwise,
call the tile's Inverse Distance Weighted function and
return the elevation.
Args:
latitude: float with the latitude in decimal degrees
longitude: float with the longitude in decimal degrees
radius: int of 1 or 2 indicating the approximate radius
of adjacent cells to include
Returns:
a float of the interpolated elevation with the same unit
as the .hgt file (meters)
"""
tile = self.get_file(latitude, longitude)
if tile is None:
return None
return tile._InverseDistanceWeighted(latitude, longitude, radius) | python | def _IDW(self, latitude, longitude, radius=1):
"""
Return the interpolated elevation at a point.
Load the correct tile for latitude and longitude given.
If the tile doesn't exist, return None. Otherwise,
call the tile's Inverse Distance Weighted function and
return the elevation.
Args:
latitude: float with the latitude in decimal degrees
longitude: float with the longitude in decimal degrees
radius: int of 1 or 2 indicating the approximate radius
of adjacent cells to include
Returns:
a float of the interpolated elevation with the same unit
as the .hgt file (meters)
"""
tile = self.get_file(latitude, longitude)
if tile is None:
return None
return tile._InverseDistanceWeighted(latitude, longitude, radius) | [
"def",
"_IDW",
"(",
"self",
",",
"latitude",
",",
"longitude",
",",
"radius",
"=",
"1",
")",
":",
"tile",
"=",
"self",
".",
"get_file",
"(",
"latitude",
",",
"longitude",
")",
"if",
"tile",
"is",
"None",
":",
"return",
"None",
"return",
"tile",
".",
... | Return the interpolated elevation at a point.
Load the correct tile for latitude and longitude given.
If the tile doesn't exist, return None. Otherwise,
call the tile's Inverse Distance Weighted function and
return the elevation.
Args:
latitude: float with the latitude in decimal degrees
longitude: float with the longitude in decimal degrees
radius: int of 1 or 2 indicating the approximate radius
of adjacent cells to include
Returns:
a float of the interpolated elevation with the same unit
as the .hgt file (meters) | [
"Return",
"the",
"interpolated",
"elevation",
"at",
"a",
"point",
"."
] | 37fb8a6f52c8ca25565772e59e867ac26181f829 | https://github.com/tkrajina/srtm.py/blob/37fb8a6f52c8ca25565772e59e867ac26181f829/srtm/data.py#L70-L93 | train | 202,107 |
tkrajina/srtm.py | srtm/data.py | GeoElevationData.get_image | def get_image(self, size, latitude_interval, longitude_interval, max_elevation, min_elevation=0,
unknown_color = (255, 255, 255, 255), zero_color = (0, 0, 255, 255),
min_color = (0, 0, 0, 255), max_color = (0, 255, 0, 255),
mode='image'):
"""
Returns a numpy array or PIL image.
"""
if not size or len(size) != 2:
raise Exception('Invalid size %s' % size)
if not latitude_interval or len(latitude_interval) != 2:
raise Exception('Invalid latitude interval %s' % latitude_interval)
if not longitude_interval or len(longitude_interval) != 2:
raise Exception('Invalid longitude interval %s' % longitude_interval)
width, height = size
width, height = int(width), int(height)
latitude_from, latitude_to = latitude_interval
longitude_from, longitude_to = longitude_interval
if mode == 'array':
import numpy as np
array = np.empty((height,width))
for row in range(height):
for column in range(width):
latitude = latitude_from + float(row) / height * (latitude_to - latitude_from)
longitude = longitude_from + float(column) / width * (longitude_to - longitude_from)
elevation = self.get_elevation(latitude, longitude)
array[row,column] = elevation
return array
elif mode == 'image':
try: import Image as mod_image
except: from PIL import Image as mod_image
try: import ImageDraw as mod_imagedraw
except: from PIL import ImageDraw as mod_imagedraw
image = mod_image.new('RGBA', (width, height),
(255, 255, 255, 255))
draw = mod_imagedraw.Draw(image)
max_elevation -= min_elevation
for row in range(height):
for column in range(width):
latitude = latitude_from + float(row) / height * (latitude_to - latitude_from)
longitude = longitude_from + float(column) / width * (longitude_to - longitude_from)
elevation = self.get_elevation(latitude, longitude)
if elevation == None:
color = unknown_color
else:
elevation_coef = (elevation - min_elevation) / float(max_elevation)
if elevation_coef < 0: elevation_coef = 0
if elevation_coef > 1: elevation_coef = 1
color = mod_utils.get_color_between(min_color, max_color, elevation_coef)
if elevation <= 0:
color = zero_color
draw.point((column, height - row), color)
return image
else:
raise Exception('Invalid mode ' + mode) | python | def get_image(self, size, latitude_interval, longitude_interval, max_elevation, min_elevation=0,
unknown_color = (255, 255, 255, 255), zero_color = (0, 0, 255, 255),
min_color = (0, 0, 0, 255), max_color = (0, 255, 0, 255),
mode='image'):
"""
Returns a numpy array or PIL image.
"""
if not size or len(size) != 2:
raise Exception('Invalid size %s' % size)
if not latitude_interval or len(latitude_interval) != 2:
raise Exception('Invalid latitude interval %s' % latitude_interval)
if not longitude_interval or len(longitude_interval) != 2:
raise Exception('Invalid longitude interval %s' % longitude_interval)
width, height = size
width, height = int(width), int(height)
latitude_from, latitude_to = latitude_interval
longitude_from, longitude_to = longitude_interval
if mode == 'array':
import numpy as np
array = np.empty((height,width))
for row in range(height):
for column in range(width):
latitude = latitude_from + float(row) / height * (latitude_to - latitude_from)
longitude = longitude_from + float(column) / width * (longitude_to - longitude_from)
elevation = self.get_elevation(latitude, longitude)
array[row,column] = elevation
return array
elif mode == 'image':
try: import Image as mod_image
except: from PIL import Image as mod_image
try: import ImageDraw as mod_imagedraw
except: from PIL import ImageDraw as mod_imagedraw
image = mod_image.new('RGBA', (width, height),
(255, 255, 255, 255))
draw = mod_imagedraw.Draw(image)
max_elevation -= min_elevation
for row in range(height):
for column in range(width):
latitude = latitude_from + float(row) / height * (latitude_to - latitude_from)
longitude = longitude_from + float(column) / width * (longitude_to - longitude_from)
elevation = self.get_elevation(latitude, longitude)
if elevation == None:
color = unknown_color
else:
elevation_coef = (elevation - min_elevation) / float(max_elevation)
if elevation_coef < 0: elevation_coef = 0
if elevation_coef > 1: elevation_coef = 1
color = mod_utils.get_color_between(min_color, max_color, elevation_coef)
if elevation <= 0:
color = zero_color
draw.point((column, height - row), color)
return image
else:
raise Exception('Invalid mode ' + mode) | [
"def",
"get_image",
"(",
"self",
",",
"size",
",",
"latitude_interval",
",",
"longitude_interval",
",",
"max_elevation",
",",
"min_elevation",
"=",
"0",
",",
"unknown_color",
"=",
"(",
"255",
",",
"255",
",",
"255",
",",
"255",
")",
",",
"zero_color",
"=",... | Returns a numpy array or PIL image. | [
"Returns",
"a",
"numpy",
"array",
"or",
"PIL",
"image",
"."
] | 37fb8a6f52c8ca25565772e59e867ac26181f829 | https://github.com/tkrajina/srtm.py/blob/37fb8a6f52c8ca25565772e59e867ac26181f829/srtm/data.py#L187-L251 | train | 202,108 |
tkrajina/srtm.py | srtm/data.py | GeoElevationData._add_interval_elevations | def _add_interval_elevations(self, gpx, min_interval_length=100):
"""
Adds elevation on points every min_interval_length and add missing
elevation between
"""
for track in gpx.tracks:
for segment in track.segments:
last_interval_changed = 0
previous_point = None
length = 0
for no, point in enumerate(segment.points):
if previous_point:
length += point.distance_2d(previous_point)
if no == 0 or no == len(segment.points) - 1 or length > last_interval_changed:
last_interval_changed += min_interval_length
point.elevation = self.get_elevation(point.latitude, point.longitude)
else:
point.elevation = None
previous_point = point
gpx.add_missing_elevations() | python | def _add_interval_elevations(self, gpx, min_interval_length=100):
"""
Adds elevation on points every min_interval_length and add missing
elevation between
"""
for track in gpx.tracks:
for segment in track.segments:
last_interval_changed = 0
previous_point = None
length = 0
for no, point in enumerate(segment.points):
if previous_point:
length += point.distance_2d(previous_point)
if no == 0 or no == len(segment.points) - 1 or length > last_interval_changed:
last_interval_changed += min_interval_length
point.elevation = self.get_elevation(point.latitude, point.longitude)
else:
point.elevation = None
previous_point = point
gpx.add_missing_elevations() | [
"def",
"_add_interval_elevations",
"(",
"self",
",",
"gpx",
",",
"min_interval_length",
"=",
"100",
")",
":",
"for",
"track",
"in",
"gpx",
".",
"tracks",
":",
"for",
"segment",
"in",
"track",
".",
"segments",
":",
"last_interval_changed",
"=",
"0",
"previous... | Adds elevation on points every min_interval_length and add missing
elevation between | [
"Adds",
"elevation",
"on",
"points",
"every",
"min_interval_length",
"and",
"add",
"missing",
"elevation",
"between"
] | 37fb8a6f52c8ca25565772e59e867ac26181f829 | https://github.com/tkrajina/srtm.py/blob/37fb8a6f52c8ca25565772e59e867ac26181f829/srtm/data.py#L280-L300 | train | 202,109 |
tkrajina/srtm.py | srtm/data.py | GeoElevationFile.get_elevation | def get_elevation(self, latitude, longitude, approximate=None):
"""
If approximate is True then only the points from SRTM grid will be
used, otherwise a basic aproximation of nearby points will be calculated.
"""
if not (self.latitude - self.resolution <= latitude < self.latitude + 1):
raise Exception('Invalid latitude %s for file %s' % (latitude, self.file_name))
if not (self.longitude <= longitude < self.longitude + 1 + self.resolution):
raise Exception('Invalid longitude %s for file %s' % (longitude, self.file_name))
row, column = self.get_row_and_column(latitude, longitude)
if approximate:
return self.approximation(latitude, longitude)
else:
return self.get_elevation_from_row_and_column(int(row), int(column)) | python | def get_elevation(self, latitude, longitude, approximate=None):
"""
If approximate is True then only the points from SRTM grid will be
used, otherwise a basic aproximation of nearby points will be calculated.
"""
if not (self.latitude - self.resolution <= latitude < self.latitude + 1):
raise Exception('Invalid latitude %s for file %s' % (latitude, self.file_name))
if not (self.longitude <= longitude < self.longitude + 1 + self.resolution):
raise Exception('Invalid longitude %s for file %s' % (longitude, self.file_name))
row, column = self.get_row_and_column(latitude, longitude)
if approximate:
return self.approximation(latitude, longitude)
else:
return self.get_elevation_from_row_and_column(int(row), int(column)) | [
"def",
"get_elevation",
"(",
"self",
",",
"latitude",
",",
"longitude",
",",
"approximate",
"=",
"None",
")",
":",
"if",
"not",
"(",
"self",
".",
"latitude",
"-",
"self",
".",
"resolution",
"<=",
"latitude",
"<",
"self",
".",
"latitude",
"+",
"1",
")",... | If approximate is True then only the points from SRTM grid will be
used, otherwise a basic aproximation of nearby points will be calculated. | [
"If",
"approximate",
"is",
"True",
"then",
"only",
"the",
"points",
"from",
"SRTM",
"grid",
"will",
"be",
"used",
"otherwise",
"a",
"basic",
"aproximation",
"of",
"nearby",
"points",
"will",
"be",
"calculated",
"."
] | 37fb8a6f52c8ca25565772e59e867ac26181f829 | https://github.com/tkrajina/srtm.py/blob/37fb8a6f52c8ca25565772e59e867ac26181f829/srtm/data.py#L360-L375 | train | 202,110 |
tkrajina/srtm.py | srtm/data.py | GeoElevationFile.approximation | def approximation(self, latitude, longitude):
"""
Dummy approximation with nearest points. The nearest the neighbour the
more important will be its elevation.
"""
d = 1. / self.square_side
d_meters = d * mod_utils.ONE_DEGREE
# Since the less the distance => the more important should be the
# distance of the point, we'll use d-distance as importance coef
# here:
importance_1 = d_meters - mod_utils.distance(latitude + d, longitude, latitude, longitude)
elevation_1 = self.geo_elevation_data.get_elevation(latitude + d, longitude, approximate=False)
importance_2 = d_meters - mod_utils.distance(latitude - d, longitude, latitude, longitude)
elevation_2 = self.geo_elevation_data.get_elevation(latitude - d, longitude, approximate=False)
importance_3 = d_meters - mod_utils.distance(latitude, longitude + d, latitude, longitude)
elevation_3 = self.geo_elevation_data.get_elevation(latitude, longitude + d, approximate=False)
importance_4 = d_meters - mod_utils.distance(latitude, longitude - d, latitude, longitude)
elevation_4 = self.geo_elevation_data.get_elevation(latitude, longitude - d, approximate=False)
# TODO(TK) Check if coordinates inside the same file, and only then decide if to call
# self.geo_elevation_data.get_elevation or just self.get_elevation
if elevation_1 == None or elevation_2 == None or elevation_3 == None or elevation_4 == None:
elevation = self.get_elevation(latitude, longitude, approximate=False)
if not elevation:
return None
elevation_1 = elevation_1 or elevation
elevation_2 = elevation_2 or elevation
elevation_3 = elevation_3 or elevation
elevation_4 = elevation_4 or elevation
# Normalize importance:
sum_importances = float(importance_1 + importance_2 + importance_3 + importance_4)
# Check normalization:
assert abs(importance_1 / sum_importances + \
importance_2 / sum_importances + \
importance_3 / sum_importances + \
importance_4 / sum_importances - 1 ) < 0.000001
result = importance_1 / sum_importances * elevation_1 + \
importance_2 / sum_importances * elevation_2 + \
importance_3 / sum_importances * elevation_3 + \
importance_4 / sum_importances * elevation_4
return result | python | def approximation(self, latitude, longitude):
"""
Dummy approximation with nearest points. The nearest the neighbour the
more important will be its elevation.
"""
d = 1. / self.square_side
d_meters = d * mod_utils.ONE_DEGREE
# Since the less the distance => the more important should be the
# distance of the point, we'll use d-distance as importance coef
# here:
importance_1 = d_meters - mod_utils.distance(latitude + d, longitude, latitude, longitude)
elevation_1 = self.geo_elevation_data.get_elevation(latitude + d, longitude, approximate=False)
importance_2 = d_meters - mod_utils.distance(latitude - d, longitude, latitude, longitude)
elevation_2 = self.geo_elevation_data.get_elevation(latitude - d, longitude, approximate=False)
importance_3 = d_meters - mod_utils.distance(latitude, longitude + d, latitude, longitude)
elevation_3 = self.geo_elevation_data.get_elevation(latitude, longitude + d, approximate=False)
importance_4 = d_meters - mod_utils.distance(latitude, longitude - d, latitude, longitude)
elevation_4 = self.geo_elevation_data.get_elevation(latitude, longitude - d, approximate=False)
# TODO(TK) Check if coordinates inside the same file, and only then decide if to call
# self.geo_elevation_data.get_elevation or just self.get_elevation
if elevation_1 == None or elevation_2 == None or elevation_3 == None or elevation_4 == None:
elevation = self.get_elevation(latitude, longitude, approximate=False)
if not elevation:
return None
elevation_1 = elevation_1 or elevation
elevation_2 = elevation_2 or elevation
elevation_3 = elevation_3 or elevation
elevation_4 = elevation_4 or elevation
# Normalize importance:
sum_importances = float(importance_1 + importance_2 + importance_3 + importance_4)
# Check normalization:
assert abs(importance_1 / sum_importances + \
importance_2 / sum_importances + \
importance_3 / sum_importances + \
importance_4 / sum_importances - 1 ) < 0.000001
result = importance_1 / sum_importances * elevation_1 + \
importance_2 / sum_importances * elevation_2 + \
importance_3 / sum_importances * elevation_3 + \
importance_4 / sum_importances * elevation_4
return result | [
"def",
"approximation",
"(",
"self",
",",
"latitude",
",",
"longitude",
")",
":",
"d",
"=",
"1.",
"/",
"self",
".",
"square_side",
"d_meters",
"=",
"d",
"*",
"mod_utils",
".",
"ONE_DEGREE",
"# Since the less the distance => the more important should be the",
"# dist... | Dummy approximation with nearest points. The nearest the neighbour the
more important will be its elevation. | [
"Dummy",
"approximation",
"with",
"nearest",
"points",
".",
"The",
"nearest",
"the",
"neighbour",
"the",
"more",
"important",
"will",
"be",
"its",
"elevation",
"."
] | 37fb8a6f52c8ca25565772e59e867ac26181f829 | https://github.com/tkrajina/srtm.py/blob/37fb8a6f52c8ca25565772e59e867ac26181f829/srtm/data.py#L377-L425 | train | 202,111 |
tkrajina/srtm.py | srtm/data.py | GeoElevationFile._InverseDistanceWeighted | def _InverseDistanceWeighted(self, latitude, longitude, radius=1):
"""
Return the Inverse Distance Weighted Elevation.
Interpolate the elevation of the given point using the inverse
distance weigthing algorithm (exp of 1) in the form:
sum((1/distance) * elevation)/sum(1/distance)
for each point in the matrix.
The matrix size is determined by the radius. A radius of 1 uses
5 points and a radius of 2 uses 13 points. The matrices are set
up to use cells adjacent to and including the one that contains
the given point. Any cells referenced by the matrix that are on
neighboring tiles are ignored.
Args:
latitude: float of the latitude in decimal degrees
longitude: float of the longitude in decimal degrees
radius: int of 1 or 2 indicating the size of the matrix
Returns:
a float of the interpolated elevation in the same units as
the underlying .hgt file (meters)
Exceptions:
raises a ValueError if an invalid radius is supplied
"""
if radius == 1:
offsetmatrix = (None, (0, 1), None,
(-1, 0), (0, 0), (1, 0),
None, (0, -1), None)
elif radius == 2:
offsetmatrix = (None, None, (0, 2), None, None,
None, (-1, 1), (0, 1), (1, 1), None,
(-2, 0), (-1, 0), (0, 0), (1, 0), (2, 0),
None, (-1, -1), (0, -1), (1, -1), None,
None, None, (0, -2), None, None)
else:
raise ValueError("Radius {} invalid, "
"expected 1 or 2".format(radius))
row, column = self.get_row_and_column(latitude, longitude)
center_lat, center_long = self.get_lat_and_long(row, column)
if latitude == center_lat and longitude == center_long:
# return direct elev at point (infinite weight)
return self.get_elevation_from_row_and_column(int(row), int(column))
weights = 0
elevation = 0
for offset in offsetmatrix:
if (offset is not None and
0 <= row + offset[0] < self.square_side and
0 <= column + offset[1] < self.square_side):
cell = self.get_elevation_from_row_and_column(int(row + offset[0]),
int(column + offset[1]))
if cell is not None:
# does not need to be meters, anything proportional
distance = mod_utils.distance(latitude, longitude,
center_lat + float(offset[0])/(self.square_side-1),
center_long + float(offset[1])/(self.square_side-1))
weights += 1/distance
elevation += cell/distance
return elevation/weights | python | def _InverseDistanceWeighted(self, latitude, longitude, radius=1):
"""
Return the Inverse Distance Weighted Elevation.
Interpolate the elevation of the given point using the inverse
distance weigthing algorithm (exp of 1) in the form:
sum((1/distance) * elevation)/sum(1/distance)
for each point in the matrix.
The matrix size is determined by the radius. A radius of 1 uses
5 points and a radius of 2 uses 13 points. The matrices are set
up to use cells adjacent to and including the one that contains
the given point. Any cells referenced by the matrix that are on
neighboring tiles are ignored.
Args:
latitude: float of the latitude in decimal degrees
longitude: float of the longitude in decimal degrees
radius: int of 1 or 2 indicating the size of the matrix
Returns:
a float of the interpolated elevation in the same units as
the underlying .hgt file (meters)
Exceptions:
raises a ValueError if an invalid radius is supplied
"""
if radius == 1:
offsetmatrix = (None, (0, 1), None,
(-1, 0), (0, 0), (1, 0),
None, (0, -1), None)
elif radius == 2:
offsetmatrix = (None, None, (0, 2), None, None,
None, (-1, 1), (0, 1), (1, 1), None,
(-2, 0), (-1, 0), (0, 0), (1, 0), (2, 0),
None, (-1, -1), (0, -1), (1, -1), None,
None, None, (0, -2), None, None)
else:
raise ValueError("Radius {} invalid, "
"expected 1 or 2".format(radius))
row, column = self.get_row_and_column(latitude, longitude)
center_lat, center_long = self.get_lat_and_long(row, column)
if latitude == center_lat and longitude == center_long:
# return direct elev at point (infinite weight)
return self.get_elevation_from_row_and_column(int(row), int(column))
weights = 0
elevation = 0
for offset in offsetmatrix:
if (offset is not None and
0 <= row + offset[0] < self.square_side and
0 <= column + offset[1] < self.square_side):
cell = self.get_elevation_from_row_and_column(int(row + offset[0]),
int(column + offset[1]))
if cell is not None:
# does not need to be meters, anything proportional
distance = mod_utils.distance(latitude, longitude,
center_lat + float(offset[0])/(self.square_side-1),
center_long + float(offset[1])/(self.square_side-1))
weights += 1/distance
elevation += cell/distance
return elevation/weights | [
"def",
"_InverseDistanceWeighted",
"(",
"self",
",",
"latitude",
",",
"longitude",
",",
"radius",
"=",
"1",
")",
":",
"if",
"radius",
"==",
"1",
":",
"offsetmatrix",
"=",
"(",
"None",
",",
"(",
"0",
",",
"1",
")",
",",
"None",
",",
"(",
"-",
"1",
... | Return the Inverse Distance Weighted Elevation.
Interpolate the elevation of the given point using the inverse
distance weigthing algorithm (exp of 1) in the form:
sum((1/distance) * elevation)/sum(1/distance)
for each point in the matrix.
The matrix size is determined by the radius. A radius of 1 uses
5 points and a radius of 2 uses 13 points. The matrices are set
up to use cells adjacent to and including the one that contains
the given point. Any cells referenced by the matrix that are on
neighboring tiles are ignored.
Args:
latitude: float of the latitude in decimal degrees
longitude: float of the longitude in decimal degrees
radius: int of 1 or 2 indicating the size of the matrix
Returns:
a float of the interpolated elevation in the same units as
the underlying .hgt file (meters)
Exceptions:
raises a ValueError if an invalid radius is supplied | [
"Return",
"the",
"Inverse",
"Distance",
"Weighted",
"Elevation",
"."
] | 37fb8a6f52c8ca25565772e59e867ac26181f829 | https://github.com/tkrajina/srtm.py/blob/37fb8a6f52c8ca25565772e59e867ac26181f829/srtm/data.py#L427-L490 | train | 202,112 |
tkrajina/srtm.py | srtm/main.py | get_data | def get_data(srtm1=True, srtm3=True, leave_zipped=False, file_handler=None,
use_included_urls=True, batch_mode=False):
"""
Get the utility object for querying elevation data.
All data files will be stored in localy (note that it may be
gigabytes of data so clean it from time to time).
On first run -- all files needed url will be stored and for every next
elevation query if the SRTM file is not found it will be retrieved and
saved.
If you need to change the way the files are saved locally (for example if
you need to save them locally) -- change the file_handler. See
srtm.main.FileHandler.
If leave_zipped is True then files will be stored locally as compressed
zip files. That means less disk space but more computing space for every
file loaded.
If use_included_urls is True urls to SRTM files included in the library
will be used. Set to false if you need to reload them on first run.
If batch_mode is True, only the most recent file will be stored. This is
ideal for situations where you want to use this function to enrich a very
large dataset. If your data are spread over a wide geographic area, this
setting will make this function slower but will greatly reduce the risk
of out-of-memory errors. Default is False.
With srtm1 or srtm3 params you can decide which SRTM format to use. Srtm3
has a resolution of three arc-seconds (cca 90 meters between points).
Srtm1 has a resolution of one arc-second (cca 30 meters). Srtm1 is
available only for the United states. If both srtm1 ans srtm3 are True and
both files are present for a location -- the srtm1 will be used.
"""
if not file_handler:
file_handler = FileHandler()
if not srtm1 and not srtm3:
raise Exception('At least one of srtm1 and srtm3 must be True')
srtm1_files, srtm3_files = _get_urls(use_included_urls, file_handler)
assert srtm1_files
assert srtm3_files
if not srtm1:
srtm1_files = {}
if not srtm3:
srtm3_files = {}
assert srtm1_files or srtm3_files
return mod_data.GeoElevationData(srtm1_files, srtm3_files, file_handler=file_handler,
leave_zipped=leave_zipped, batch_mode=batch_mode) | python | def get_data(srtm1=True, srtm3=True, leave_zipped=False, file_handler=None,
use_included_urls=True, batch_mode=False):
"""
Get the utility object for querying elevation data.
All data files will be stored in localy (note that it may be
gigabytes of data so clean it from time to time).
On first run -- all files needed url will be stored and for every next
elevation query if the SRTM file is not found it will be retrieved and
saved.
If you need to change the way the files are saved locally (for example if
you need to save them locally) -- change the file_handler. See
srtm.main.FileHandler.
If leave_zipped is True then files will be stored locally as compressed
zip files. That means less disk space but more computing space for every
file loaded.
If use_included_urls is True urls to SRTM files included in the library
will be used. Set to false if you need to reload them on first run.
If batch_mode is True, only the most recent file will be stored. This is
ideal for situations where you want to use this function to enrich a very
large dataset. If your data are spread over a wide geographic area, this
setting will make this function slower but will greatly reduce the risk
of out-of-memory errors. Default is False.
With srtm1 or srtm3 params you can decide which SRTM format to use. Srtm3
has a resolution of three arc-seconds (cca 90 meters between points).
Srtm1 has a resolution of one arc-second (cca 30 meters). Srtm1 is
available only for the United states. If both srtm1 ans srtm3 are True and
both files are present for a location -- the srtm1 will be used.
"""
if not file_handler:
file_handler = FileHandler()
if not srtm1 and not srtm3:
raise Exception('At least one of srtm1 and srtm3 must be True')
srtm1_files, srtm3_files = _get_urls(use_included_urls, file_handler)
assert srtm1_files
assert srtm3_files
if not srtm1:
srtm1_files = {}
if not srtm3:
srtm3_files = {}
assert srtm1_files or srtm3_files
return mod_data.GeoElevationData(srtm1_files, srtm3_files, file_handler=file_handler,
leave_zipped=leave_zipped, batch_mode=batch_mode) | [
"def",
"get_data",
"(",
"srtm1",
"=",
"True",
",",
"srtm3",
"=",
"True",
",",
"leave_zipped",
"=",
"False",
",",
"file_handler",
"=",
"None",
",",
"use_included_urls",
"=",
"True",
",",
"batch_mode",
"=",
"False",
")",
":",
"if",
"not",
"file_handler",
"... | Get the utility object for querying elevation data.
All data files will be stored in localy (note that it may be
gigabytes of data so clean it from time to time).
On first run -- all files needed url will be stored and for every next
elevation query if the SRTM file is not found it will be retrieved and
saved.
If you need to change the way the files are saved locally (for example if
you need to save them locally) -- change the file_handler. See
srtm.main.FileHandler.
If leave_zipped is True then files will be stored locally as compressed
zip files. That means less disk space but more computing space for every
file loaded.
If use_included_urls is True urls to SRTM files included in the library
will be used. Set to false if you need to reload them on first run.
If batch_mode is True, only the most recent file will be stored. This is
ideal for situations where you want to use this function to enrich a very
large dataset. If your data are spread over a wide geographic area, this
setting will make this function slower but will greatly reduce the risk
of out-of-memory errors. Default is False.
With srtm1 or srtm3 params you can decide which SRTM format to use. Srtm3
has a resolution of three arc-seconds (cca 90 meters between points).
Srtm1 has a resolution of one arc-second (cca 30 meters). Srtm1 is
available only for the United states. If both srtm1 ans srtm3 are True and
both files are present for a location -- the srtm1 will be used. | [
"Get",
"the",
"utility",
"object",
"for",
"querying",
"elevation",
"data",
"."
] | 37fb8a6f52c8ca25565772e59e867ac26181f829 | https://github.com/tkrajina/srtm.py/blob/37fb8a6f52c8ca25565772e59e867ac26181f829/srtm/main.py#L30-L84 | train | 202,113 |
tkrajina/srtm.py | srtm/main.py | FileHandler.get_srtm_dir | def get_srtm_dir(self):
""" The default path to store files. """
# Local cache path:
result = ""
if 'HOME' in mod_os.environ:
result = mod_os.sep.join([mod_os.environ['HOME'], '.cache', 'srtm'])
elif 'HOMEPATH' in mod_os.environ:
result = mod_os.sep.join([mod_os.environ['HOMEPATH'], '.cache', 'srtm'])
else:
raise Exception('No default HOME directory found, please specify a path where to store files')
if not mod_path.exists(result):
mod_os.makedirs(result)
return result | python | def get_srtm_dir(self):
""" The default path to store files. """
# Local cache path:
result = ""
if 'HOME' in mod_os.environ:
result = mod_os.sep.join([mod_os.environ['HOME'], '.cache', 'srtm'])
elif 'HOMEPATH' in mod_os.environ:
result = mod_os.sep.join([mod_os.environ['HOMEPATH'], '.cache', 'srtm'])
else:
raise Exception('No default HOME directory found, please specify a path where to store files')
if not mod_path.exists(result):
mod_os.makedirs(result)
return result | [
"def",
"get_srtm_dir",
"(",
"self",
")",
":",
"# Local cache path:",
"result",
"=",
"\"\"",
"if",
"'HOME'",
"in",
"mod_os",
".",
"environ",
":",
"result",
"=",
"mod_os",
".",
"sep",
".",
"join",
"(",
"[",
"mod_os",
".",
"environ",
"[",
"'HOME'",
"]",
"... | The default path to store files. | [
"The",
"default",
"path",
"to",
"store",
"files",
"."
] | 37fb8a6f52c8ca25565772e59e867ac26181f829 | https://github.com/tkrajina/srtm.py/blob/37fb8a6f52c8ca25565772e59e867ac26181f829/srtm/main.py#L115-L129 | train | 202,114 |
sammchardy/python-kucoin | kucoin/asyncio/websockets.py | KucoinSocketManager.unsubscribe | async def unsubscribe(self, topic: str):
"""Unsubscribe from a topic
:param topic: required
:returns: None
Sample ws response
.. code-block:: python
{
"id": "1545910840805",
"type": "ack"
}
"""
req_msg = {
'type': 'unsubscribe',
'topic': topic,
'response': True
}
await self._conn.send_message(req_msg) | python | async def unsubscribe(self, topic: str):
"""Unsubscribe from a topic
:param topic: required
:returns: None
Sample ws response
.. code-block:: python
{
"id": "1545910840805",
"type": "ack"
}
"""
req_msg = {
'type': 'unsubscribe',
'topic': topic,
'response': True
}
await self._conn.send_message(req_msg) | [
"async",
"def",
"unsubscribe",
"(",
"self",
",",
"topic",
":",
"str",
")",
":",
"req_msg",
"=",
"{",
"'type'",
":",
"'unsubscribe'",
",",
"'topic'",
":",
"topic",
",",
"'response'",
":",
"True",
"}",
"await",
"self",
".",
"_conn",
".",
"send_message",
... | Unsubscribe from a topic
:param topic: required
:returns: None
Sample ws response
.. code-block:: python
{
"id": "1545910840805",
"type": "ack"
} | [
"Unsubscribe",
"from",
"a",
"topic"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/asyncio/websockets.py#L221-L245 | train | 202,115 |
sammchardy/python-kucoin | kucoin/client.py | Client._generate_signature | def _generate_signature(self, nonce, method, path, data):
"""Generate the call signature
:param path:
:param data:
:param nonce:
:return: signature string
"""
data_json = ""
endpoint = path
if method == "get":
if data:
query_string = self._get_params_for_sig(data)
endpoint = "{}?{}".format(path, query_string)
elif data:
data_json = compact_json_dict(data)
sig_str = ("{}{}{}{}".format(nonce, method.upper(), endpoint, data_json)).encode('utf-8')
m = hmac.new(self.API_SECRET.encode('utf-8'), sig_str, hashlib.sha256)
return base64.b64encode(m.digest()) | python | def _generate_signature(self, nonce, method, path, data):
"""Generate the call signature
:param path:
:param data:
:param nonce:
:return: signature string
"""
data_json = ""
endpoint = path
if method == "get":
if data:
query_string = self._get_params_for_sig(data)
endpoint = "{}?{}".format(path, query_string)
elif data:
data_json = compact_json_dict(data)
sig_str = ("{}{}{}{}".format(nonce, method.upper(), endpoint, data_json)).encode('utf-8')
m = hmac.new(self.API_SECRET.encode('utf-8'), sig_str, hashlib.sha256)
return base64.b64encode(m.digest()) | [
"def",
"_generate_signature",
"(",
"self",
",",
"nonce",
",",
"method",
",",
"path",
",",
"data",
")",
":",
"data_json",
"=",
"\"\"",
"endpoint",
"=",
"path",
"if",
"method",
"==",
"\"get\"",
":",
"if",
"data",
":",
"query_string",
"=",
"self",
".",
"_... | Generate the call signature
:param path:
:param data:
:param nonce:
:return: signature string | [
"Generate",
"the",
"call",
"signature"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L100-L121 | train | 202,116 |
sammchardy/python-kucoin | kucoin/client.py | Client._handle_response | def _handle_response(response):
"""Internal helper for handling API responses from the Quoine server.
Raises the appropriate exceptions when necessary; otherwise, returns the
response.
"""
if not str(response.status_code).startswith('2'):
raise KucoinAPIException(response)
try:
res = response.json()
if 'code' in res and res['code'] != "200000":
raise KucoinAPIException(response)
if 'success' in res and not res['success']:
raise KucoinAPIException(response)
# by default return full response
# if it's a normal response we have a data attribute, return that
if 'data' in res:
res = res['data']
return res
except ValueError:
raise KucoinRequestException('Invalid Response: %s' % response.text) | python | def _handle_response(response):
"""Internal helper for handling API responses from the Quoine server.
Raises the appropriate exceptions when necessary; otherwise, returns the
response.
"""
if not str(response.status_code).startswith('2'):
raise KucoinAPIException(response)
try:
res = response.json()
if 'code' in res and res['code'] != "200000":
raise KucoinAPIException(response)
if 'success' in res and not res['success']:
raise KucoinAPIException(response)
# by default return full response
# if it's a normal response we have a data attribute, return that
if 'data' in res:
res = res['data']
return res
except ValueError:
raise KucoinRequestException('Invalid Response: %s' % response.text) | [
"def",
"_handle_response",
"(",
"response",
")",
":",
"if",
"not",
"str",
"(",
"response",
".",
"status_code",
")",
".",
"startswith",
"(",
"'2'",
")",
":",
"raise",
"KucoinAPIException",
"(",
"response",
")",
"try",
":",
"res",
"=",
"response",
".",
"js... | Internal helper for handling API responses from the Quoine server.
Raises the appropriate exceptions when necessary; otherwise, returns the
response. | [
"Internal",
"helper",
"for",
"handling",
"API",
"responses",
"from",
"the",
"Quoine",
"server",
".",
"Raises",
"the",
"appropriate",
"exceptions",
"when",
"necessary",
";",
"otherwise",
"returns",
"the",
"response",
"."
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L161-L184 | train | 202,117 |
sammchardy/python-kucoin | kucoin/client.py | Client.create_account | def create_account(self, account_type, currency):
"""Create an account
https://docs.kucoin.com/#create-an-account
:param account_type: Account type - main or trade
:type account_type: string
:param currency: Currency code
:type currency: string
.. code:: python
account = client.create_account('trade', 'BTC')
:returns: API Response
.. code-block:: python
{
"id": "5bd6e9286d99522a52e458de"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'type': account_type,
'currency': currency
}
return self._post('accounts', True, data=data) | python | def create_account(self, account_type, currency):
"""Create an account
https://docs.kucoin.com/#create-an-account
:param account_type: Account type - main or trade
:type account_type: string
:param currency: Currency code
:type currency: string
.. code:: python
account = client.create_account('trade', 'BTC')
:returns: API Response
.. code-block:: python
{
"id": "5bd6e9286d99522a52e458de"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'type': account_type,
'currency': currency
}
return self._post('accounts', True, data=data) | [
"def",
"create_account",
"(",
"self",
",",
"account_type",
",",
"currency",
")",
":",
"data",
"=",
"{",
"'type'",
":",
"account_type",
",",
"'currency'",
":",
"currency",
"}",
"return",
"self",
".",
"_post",
"(",
"'accounts'",
",",
"True",
",",
"data",
"... | Create an account
https://docs.kucoin.com/#create-an-account
:param account_type: Account type - main or trade
:type account_type: string
:param currency: Currency code
:type currency: string
.. code:: python
account = client.create_account('trade', 'BTC')
:returns: API Response
.. code-block:: python
{
"id": "5bd6e9286d99522a52e458de"
}
:raises: KucoinResponseException, KucoinAPIException | [
"Create",
"an",
"account"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L344-L375 | train | 202,118 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_account_activity | def get_account_activity(self, account_id, start=None, end=None, page=None, limit=None):
"""Get list of account activity
https://docs.kucoin.com/#get-account-history
:param account_id: ID for account - from list_accounts()
:type account_id: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Current page - default 1
:type page: int
:param limit: (optional) Number of results to return - default 50
:type limit: int
.. code:: python
history = client.get_account_activity('5bd6e9216d99522a52e458d6')
history = client.get_account_activity('5bd6e9216d99522a52e458d6', start='1540296039000')
history = client.get_account_activity('5bd6e9216d99522a52e458d6', page=2, page_size=10)
:returns: API Response
.. code-block:: python
{
"currentPage": 1,
"pageSize": 10,
"totalNum": 2,
"totalPage": 1,
"items": [
{
"currency": "KCS",
"amount": "0.0998",
"fee": "0",
"balance": "1994.040596",
"bizType": "withdraw",
"direction": "in",
"createdAt": 1540296039000,
"context": {
"orderId": "5bc7f080b39c5c03286eef8a",
"currency": "BTC"
}
},
{
"currency": "KCS",
"amount": "0.0998",
"fee": "0",
"balance": "1994.140396",
"bizType": "trade exchange",
"direction": "in",
"createdAt": 1540296039000,
"context": {
"orderId": "5bc7f080b39c5c03286eef8e",
"tradeId": "5bc7f080b3949c03286eef8a",
"symbol": "BTC-USD"
}
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['currentPage'] = page
if limit:
data['pageSize'] = limit
return self._get('accounts/{}/ledgers'.format(account_id), True, data=data) | python | def get_account_activity(self, account_id, start=None, end=None, page=None, limit=None):
"""Get list of account activity
https://docs.kucoin.com/#get-account-history
:param account_id: ID for account - from list_accounts()
:type account_id: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Current page - default 1
:type page: int
:param limit: (optional) Number of results to return - default 50
:type limit: int
.. code:: python
history = client.get_account_activity('5bd6e9216d99522a52e458d6')
history = client.get_account_activity('5bd6e9216d99522a52e458d6', start='1540296039000')
history = client.get_account_activity('5bd6e9216d99522a52e458d6', page=2, page_size=10)
:returns: API Response
.. code-block:: python
{
"currentPage": 1,
"pageSize": 10,
"totalNum": 2,
"totalPage": 1,
"items": [
{
"currency": "KCS",
"amount": "0.0998",
"fee": "0",
"balance": "1994.040596",
"bizType": "withdraw",
"direction": "in",
"createdAt": 1540296039000,
"context": {
"orderId": "5bc7f080b39c5c03286eef8a",
"currency": "BTC"
}
},
{
"currency": "KCS",
"amount": "0.0998",
"fee": "0",
"balance": "1994.140396",
"bizType": "trade exchange",
"direction": "in",
"createdAt": 1540296039000,
"context": {
"orderId": "5bc7f080b39c5c03286eef8e",
"tradeId": "5bc7f080b3949c03286eef8a",
"symbol": "BTC-USD"
}
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['currentPage'] = page
if limit:
data['pageSize'] = limit
return self._get('accounts/{}/ledgers'.format(account_id), True, data=data) | [
"def",
"get_account_activity",
"(",
"self",
",",
"account_id",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"page",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"start",
":",
"data",
"[",
"'startAt'",
"... | Get list of account activity
https://docs.kucoin.com/#get-account-history
:param account_id: ID for account - from list_accounts()
:type account_id: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Current page - default 1
:type page: int
:param limit: (optional) Number of results to return - default 50
:type limit: int
.. code:: python
history = client.get_account_activity('5bd6e9216d99522a52e458d6')
history = client.get_account_activity('5bd6e9216d99522a52e458d6', start='1540296039000')
history = client.get_account_activity('5bd6e9216d99522a52e458d6', page=2, page_size=10)
:returns: API Response
.. code-block:: python
{
"currentPage": 1,
"pageSize": 10,
"totalNum": 2,
"totalPage": 1,
"items": [
{
"currency": "KCS",
"amount": "0.0998",
"fee": "0",
"balance": "1994.040596",
"bizType": "withdraw",
"direction": "in",
"createdAt": 1540296039000,
"context": {
"orderId": "5bc7f080b39c5c03286eef8a",
"currency": "BTC"
}
},
{
"currency": "KCS",
"amount": "0.0998",
"fee": "0",
"balance": "1994.140396",
"bizType": "trade exchange",
"direction": "in",
"createdAt": 1540296039000,
"context": {
"orderId": "5bc7f080b39c5c03286eef8e",
"tradeId": "5bc7f080b3949c03286eef8a",
"symbol": "BTC-USD"
}
}
]
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"list",
"of",
"account",
"activity"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L377-L455 | train | 202,119 |
sammchardy/python-kucoin | kucoin/client.py | Client.create_deposit_address | def create_deposit_address(self, currency):
"""Create deposit address of currency for deposit. You can just create one deposit address.
https://docs.kucoin.com/#create-deposit-address
:param currency: Name of currency
:type currency: string
.. code:: python
address = client.create_deposit_address('NEO')
:returns: ApiResponse
.. code:: python
{
"address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
"memo": "5c247c8a03aa677cea2a251d"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency
}
return self._post('deposit-addresses', True, data=data) | python | def create_deposit_address(self, currency):
"""Create deposit address of currency for deposit. You can just create one deposit address.
https://docs.kucoin.com/#create-deposit-address
:param currency: Name of currency
:type currency: string
.. code:: python
address = client.create_deposit_address('NEO')
:returns: ApiResponse
.. code:: python
{
"address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
"memo": "5c247c8a03aa677cea2a251d"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency
}
return self._post('deposit-addresses', True, data=data) | [
"def",
"create_deposit_address",
"(",
"self",
",",
"currency",
")",
":",
"data",
"=",
"{",
"'currency'",
":",
"currency",
"}",
"return",
"self",
".",
"_post",
"(",
"'deposit-addresses'",
",",
"True",
",",
"data",
"=",
"data",
")"
] | Create deposit address of currency for deposit. You can just create one deposit address.
https://docs.kucoin.com/#create-deposit-address
:param currency: Name of currency
:type currency: string
.. code:: python
address = client.create_deposit_address('NEO')
:returns: ApiResponse
.. code:: python
{
"address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
"memo": "5c247c8a03aa677cea2a251d"
}
:raises: KucoinResponseException, KucoinAPIException | [
"Create",
"deposit",
"address",
"of",
"currency",
"for",
"deposit",
".",
"You",
"can",
"just",
"create",
"one",
"deposit",
"address",
"."
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L561-L590 | train | 202,120 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_deposit_address | def get_deposit_address(self, currency):
"""Get deposit address for a currency
https://docs.kucoin.com/#get-deposit-address
:param currency: Name of currency
:type currency: string
.. code:: python
address = client.get_deposit_address('NEO')
:returns: ApiResponse
.. code:: python
{
"address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
"memo": "5c247c8a03aa677cea2a251d"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency
}
return self._get('deposit-addresses', True, data=data) | python | def get_deposit_address(self, currency):
"""Get deposit address for a currency
https://docs.kucoin.com/#get-deposit-address
:param currency: Name of currency
:type currency: string
.. code:: python
address = client.get_deposit_address('NEO')
:returns: ApiResponse
.. code:: python
{
"address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
"memo": "5c247c8a03aa677cea2a251d"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency
}
return self._get('deposit-addresses', True, data=data) | [
"def",
"get_deposit_address",
"(",
"self",
",",
"currency",
")",
":",
"data",
"=",
"{",
"'currency'",
":",
"currency",
"}",
"return",
"self",
".",
"_get",
"(",
"'deposit-addresses'",
",",
"True",
",",
"data",
"=",
"data",
")"
] | Get deposit address for a currency
https://docs.kucoin.com/#get-deposit-address
:param currency: Name of currency
:type currency: string
.. code:: python
address = client.get_deposit_address('NEO')
:returns: ApiResponse
.. code:: python
{
"address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",
"memo": "5c247c8a03aa677cea2a251d"
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"deposit",
"address",
"for",
"a",
"currency"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L592-L621 | train | 202,121 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_withdrawals | def get_withdrawals(self, currency=None, status=None, start=None, end=None, page=None, limit=None):
"""Get deposit records for a currency
https://docs.kucoin.com/#get-withdrawals-list
:param currency: Name of currency (optional)
:type currency: string
:param status: optional - Status of deposit (PROCESSING, SUCCESS, FAILURE)
:type status: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of transactions
:type limit: int
.. code:: python
withdrawals = client.get_withdrawals('NEO')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 10,
"totalNum": 1,
"totalPage": 1,
"items": [
{
"id": "5c2dc64e03aa675aa263f1ac",
"address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9",
"memo": "",
"currency": "ETH",
"amount": 1.0000000,
"fee": 0.0100000,
"walletTxId": "3e2414d82acce78d38be7fe9",
"isInner": false,
"status": "FAILURE",
"createdAt": 1546503758000,
"updatedAt": 1546504603000
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if currency:
data['currency'] = currency
if status:
data['status'] = status
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if limit:
data['pageSize'] = limit
if page:
data['page'] = page
return self._get('withdrawals', True, data=data) | python | def get_withdrawals(self, currency=None, status=None, start=None, end=None, page=None, limit=None):
"""Get deposit records for a currency
https://docs.kucoin.com/#get-withdrawals-list
:param currency: Name of currency (optional)
:type currency: string
:param status: optional - Status of deposit (PROCESSING, SUCCESS, FAILURE)
:type status: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of transactions
:type limit: int
.. code:: python
withdrawals = client.get_withdrawals('NEO')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 10,
"totalNum": 1,
"totalPage": 1,
"items": [
{
"id": "5c2dc64e03aa675aa263f1ac",
"address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9",
"memo": "",
"currency": "ETH",
"amount": 1.0000000,
"fee": 0.0100000,
"walletTxId": "3e2414d82acce78d38be7fe9",
"isInner": false,
"status": "FAILURE",
"createdAt": 1546503758000,
"updatedAt": 1546504603000
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if currency:
data['currency'] = currency
if status:
data['status'] = status
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if limit:
data['pageSize'] = limit
if page:
data['page'] = page
return self._get('withdrawals', True, data=data) | [
"def",
"get_withdrawals",
"(",
"self",
",",
"currency",
"=",
"None",
",",
"status",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"page",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"curr... | Get deposit records for a currency
https://docs.kucoin.com/#get-withdrawals-list
:param currency: Name of currency (optional)
:type currency: string
:param status: optional - Status of deposit (PROCESSING, SUCCESS, FAILURE)
:type status: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of transactions
:type limit: int
.. code:: python
withdrawals = client.get_withdrawals('NEO')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 10,
"totalNum": 1,
"totalPage": 1,
"items": [
{
"id": "5c2dc64e03aa675aa263f1ac",
"address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9",
"memo": "",
"currency": "ETH",
"amount": 1.0000000,
"fee": 0.0100000,
"walletTxId": "3e2414d82acce78d38be7fe9",
"isInner": false,
"status": "FAILURE",
"createdAt": 1546503758000,
"updatedAt": 1546504603000
}
]
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"deposit",
"records",
"for",
"a",
"currency"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L703-L769 | train | 202,122 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_withdrawal_quotas | def get_withdrawal_quotas(self, currency):
"""Get withdrawal quotas for a currency
https://docs.kucoin.com/#get-withdrawal-quotas
:param currency: Name of currency
:type currency: string
.. code:: python
quotas = client.get_withdrawal_quotas('ETH')
:returns: ApiResponse
.. code:: python
{
"currency": "ETH",
"availableAmount": 2.9719999,
"remainAmount": 2.9719999,
"withdrawMinSize": 0.1000000,
"limitBTCAmount": 2.0,
"innerWithdrawMinFee": 0.00001,
"isWithdrawEnabled": true,
"withdrawMinFee": 0.0100000,
"precision": 7
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency
}
return self._get('withdrawals/quotas', True, data=data) | python | def get_withdrawal_quotas(self, currency):
"""Get withdrawal quotas for a currency
https://docs.kucoin.com/#get-withdrawal-quotas
:param currency: Name of currency
:type currency: string
.. code:: python
quotas = client.get_withdrawal_quotas('ETH')
:returns: ApiResponse
.. code:: python
{
"currency": "ETH",
"availableAmount": 2.9719999,
"remainAmount": 2.9719999,
"withdrawMinSize": 0.1000000,
"limitBTCAmount": 2.0,
"innerWithdrawMinFee": 0.00001,
"isWithdrawEnabled": true,
"withdrawMinFee": 0.0100000,
"precision": 7
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency
}
return self._get('withdrawals/quotas', True, data=data) | [
"def",
"get_withdrawal_quotas",
"(",
"self",
",",
"currency",
")",
":",
"data",
"=",
"{",
"'currency'",
":",
"currency",
"}",
"return",
"self",
".",
"_get",
"(",
"'withdrawals/quotas'",
",",
"True",
",",
"data",
"=",
"data",
")"
] | Get withdrawal quotas for a currency
https://docs.kucoin.com/#get-withdrawal-quotas
:param currency: Name of currency
:type currency: string
.. code:: python
quotas = client.get_withdrawal_quotas('ETH')
:returns: ApiResponse
.. code:: python
{
"currency": "ETH",
"availableAmount": 2.9719999,
"remainAmount": 2.9719999,
"withdrawMinSize": 0.1000000,
"limitBTCAmount": 2.0,
"innerWithdrawMinFee": 0.00001,
"isWithdrawEnabled": true,
"withdrawMinFee": 0.0100000,
"precision": 7
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"withdrawal",
"quotas",
"for",
"a",
"currency"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L771-L807 | train | 202,123 |
sammchardy/python-kucoin | kucoin/client.py | Client.create_withdrawal | def create_withdrawal(self, currency, amount, address, memo=None, is_inner=False, remark=None):
"""Process a withdrawal
https://docs.kucoin.com/#apply-withdraw
:param currency: Name of currency
:type currency: string
:param amount: Amount to withdraw
:type amount: number
:param address: Address to withdraw to
:type address: string
:param memo: (optional) Remark to the withdrawal address
:type memo: string
:param is_inner: (optional) Remark to the withdrawal address
:type is_inner: bool
:param remark: (optional) Remark
:type remark: string
.. code:: python
withdrawal = client.create_withdrawal('NEO', 20, '598aeb627da3355fa3e851')
:returns: ApiResponse
.. code:: python
{
"withdrawalId": "5bffb63303aa675e8bbe18f9"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency,
'amount': amount,
'address': address
}
if memo:
data['memo'] = memo
if is_inner:
data['isInner'] = is_inner
if remark:
data['remark'] = remark
return self._post('withdrawals', True, data=data) | python | def create_withdrawal(self, currency, amount, address, memo=None, is_inner=False, remark=None):
"""Process a withdrawal
https://docs.kucoin.com/#apply-withdraw
:param currency: Name of currency
:type currency: string
:param amount: Amount to withdraw
:type amount: number
:param address: Address to withdraw to
:type address: string
:param memo: (optional) Remark to the withdrawal address
:type memo: string
:param is_inner: (optional) Remark to the withdrawal address
:type is_inner: bool
:param remark: (optional) Remark
:type remark: string
.. code:: python
withdrawal = client.create_withdrawal('NEO', 20, '598aeb627da3355fa3e851')
:returns: ApiResponse
.. code:: python
{
"withdrawalId": "5bffb63303aa675e8bbe18f9"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'currency': currency,
'amount': amount,
'address': address
}
if memo:
data['memo'] = memo
if is_inner:
data['isInner'] = is_inner
if remark:
data['remark'] = remark
return self._post('withdrawals', True, data=data) | [
"def",
"create_withdrawal",
"(",
"self",
",",
"currency",
",",
"amount",
",",
"address",
",",
"memo",
"=",
"None",
",",
"is_inner",
"=",
"False",
",",
"remark",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'currency'",
":",
"currency",
",",
"'amount'",
":... | Process a withdrawal
https://docs.kucoin.com/#apply-withdraw
:param currency: Name of currency
:type currency: string
:param amount: Amount to withdraw
:type amount: number
:param address: Address to withdraw to
:type address: string
:param memo: (optional) Remark to the withdrawal address
:type memo: string
:param is_inner: (optional) Remark to the withdrawal address
:type is_inner: bool
:param remark: (optional) Remark
:type remark: string
.. code:: python
withdrawal = client.create_withdrawal('NEO', 20, '598aeb627da3355fa3e851')
:returns: ApiResponse
.. code:: python
{
"withdrawalId": "5bffb63303aa675e8bbe18f9"
}
:raises: KucoinResponseException, KucoinAPIException | [
"Process",
"a",
"withdrawal"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L809-L856 | train | 202,124 |
sammchardy/python-kucoin | kucoin/client.py | Client.create_market_order | def create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, remark=None, stp=None):
"""Create a market order
One of size or funds must be set
https://docs.kucoin.com/#place-a-new-order
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: buy or sell
:type side: string
:param size: (optional) Desired amount in base currency
:type size: string
:param funds: (optional) Desired amount of quote currency to use
:type funds: string
:param client_oid: (optional) Unique order id (default flat_uuid())
:type client_oid: string
:param remark: (optional) remark for the order, max 100 utf8 characters
:type remark: string
:param stp: (optional) self trade protection CN, CO, CB or DC (default is None)
:type stp: string
.. code:: python
order = client.create_market_order('NEO', Client.SIDE_BUY, size=20)
:returns: ApiResponse
.. code:: python
{
"orderOid": "596186ad07015679730ffa02"
}
:raises: KucoinResponseException, KucoinAPIException, MarketOrderException
"""
if not size and not funds:
raise MarketOrderException('Need size or fund parameter')
if size and funds:
raise MarketOrderException('Need size or fund parameter not both')
data = {
'side': side,
'symbol': symbol,
'type': self.ORDER_MARKET
}
if size:
data['size'] = size
if funds:
data['funds'] = funds
if client_oid:
data['clientOid'] = client_oid
else:
data['clientOid'] = flat_uuid()
if remark:
data['remark'] = remark
if stp:
data['stp'] = stp
return self._post('orders', True, data=data) | python | def create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, remark=None, stp=None):
"""Create a market order
One of size or funds must be set
https://docs.kucoin.com/#place-a-new-order
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: buy or sell
:type side: string
:param size: (optional) Desired amount in base currency
:type size: string
:param funds: (optional) Desired amount of quote currency to use
:type funds: string
:param client_oid: (optional) Unique order id (default flat_uuid())
:type client_oid: string
:param remark: (optional) remark for the order, max 100 utf8 characters
:type remark: string
:param stp: (optional) self trade protection CN, CO, CB or DC (default is None)
:type stp: string
.. code:: python
order = client.create_market_order('NEO', Client.SIDE_BUY, size=20)
:returns: ApiResponse
.. code:: python
{
"orderOid": "596186ad07015679730ffa02"
}
:raises: KucoinResponseException, KucoinAPIException, MarketOrderException
"""
if not size and not funds:
raise MarketOrderException('Need size or fund parameter')
if size and funds:
raise MarketOrderException('Need size or fund parameter not both')
data = {
'side': side,
'symbol': symbol,
'type': self.ORDER_MARKET
}
if size:
data['size'] = size
if funds:
data['funds'] = funds
if client_oid:
data['clientOid'] = client_oid
else:
data['clientOid'] = flat_uuid()
if remark:
data['remark'] = remark
if stp:
data['stp'] = stp
return self._post('orders', True, data=data) | [
"def",
"create_market_order",
"(",
"self",
",",
"symbol",
",",
"side",
",",
"size",
"=",
"None",
",",
"funds",
"=",
"None",
",",
"client_oid",
"=",
"None",
",",
"remark",
"=",
"None",
",",
"stp",
"=",
"None",
")",
":",
"if",
"not",
"size",
"and",
"... | Create a market order
One of size or funds must be set
https://docs.kucoin.com/#place-a-new-order
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: buy or sell
:type side: string
:param size: (optional) Desired amount in base currency
:type size: string
:param funds: (optional) Desired amount of quote currency to use
:type funds: string
:param client_oid: (optional) Unique order id (default flat_uuid())
:type client_oid: string
:param remark: (optional) remark for the order, max 100 utf8 characters
:type remark: string
:param stp: (optional) self trade protection CN, CO, CB or DC (default is None)
:type stp: string
.. code:: python
order = client.create_market_order('NEO', Client.SIDE_BUY, size=20)
:returns: ApiResponse
.. code:: python
{
"orderOid": "596186ad07015679730ffa02"
}
:raises: KucoinResponseException, KucoinAPIException, MarketOrderException | [
"Create",
"a",
"market",
"order"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L880-L943 | train | 202,125 |
sammchardy/python-kucoin | kucoin/client.py | Client.cancel_all_orders | def cancel_all_orders(self, symbol=None):
"""Cancel all orders
https://docs.kucoin.com/#cancel-all-orders
.. code:: python
res = client.cancel_all_orders()
:returns: ApiResponse
.. code:: python
{
"cancelledOrderIds": [
"5bd6e9286d99522a52e458de"
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if symbol is not None:
data['symbol'] = symbol
return self._delete('orders', True, data=data) | python | def cancel_all_orders(self, symbol=None):
"""Cancel all orders
https://docs.kucoin.com/#cancel-all-orders
.. code:: python
res = client.cancel_all_orders()
:returns: ApiResponse
.. code:: python
{
"cancelledOrderIds": [
"5bd6e9286d99522a52e458de"
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if symbol is not None:
data['symbol'] = symbol
return self._delete('orders', True, data=data) | [
"def",
"cancel_all_orders",
"(",
"self",
",",
"symbol",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"symbol",
"is",
"not",
"None",
":",
"data",
"[",
"'symbol'",
"]",
"=",
"symbol",
"return",
"self",
".",
"_delete",
"(",
"'orders'",
",",
"True... | Cancel all orders
https://docs.kucoin.com/#cancel-all-orders
.. code:: python
res = client.cancel_all_orders()
:returns: ApiResponse
.. code:: python
{
"cancelledOrderIds": [
"5bd6e9286d99522a52e458de"
]
}
:raises: KucoinResponseException, KucoinAPIException | [
"Cancel",
"all",
"orders"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1079-L1104 | train | 202,126 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_orders | def get_orders(self, symbol=None, status=None, side=None, order_type=None,
start=None, end=None, page=None, limit=None):
"""Get list of orders
https://docs.kucoin.com/#list-orders
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
:param status: (optional) Specify status active or done (default done)
:type status: string
:param side: (optional) buy or sell
:type side: string
:param order_type: (optional) limit, market, limit_stop or market_stop
:type order_type: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of orders
:type limit: int
.. code:: python
orders = client.get_orders(symbol='KCS-BTC', status='active')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 1,
"totalNum": 153408,
"totalPage": 153408,
"items": [
{
"id": "5c35c02703aa673ceec2a168",
"symbol": "BTC-USDT",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "10",
"size": "2",
"funds": "0",
"dealFunds": "0.166",
"dealSize": "2",
"fee": "0",
"feeCurrency": "USDT",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberge": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "IOS",
"clientOid": null,
"remark": null,
"tags": null,
"isActive": false,
"cancelExist": false,
"createdAt": 1547026471000
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if symbol:
data['symbol'] = symbol
if status:
data['status'] = status
if side:
data['side'] = side
if order_type:
data['type'] = order_type
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['page'] = page
if limit:
data['pageSize'] = limit
return self._get('orders', True, data=data) | python | def get_orders(self, symbol=None, status=None, side=None, order_type=None,
start=None, end=None, page=None, limit=None):
"""Get list of orders
https://docs.kucoin.com/#list-orders
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
:param status: (optional) Specify status active or done (default done)
:type status: string
:param side: (optional) buy or sell
:type side: string
:param order_type: (optional) limit, market, limit_stop or market_stop
:type order_type: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of orders
:type limit: int
.. code:: python
orders = client.get_orders(symbol='KCS-BTC', status='active')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 1,
"totalNum": 153408,
"totalPage": 153408,
"items": [
{
"id": "5c35c02703aa673ceec2a168",
"symbol": "BTC-USDT",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "10",
"size": "2",
"funds": "0",
"dealFunds": "0.166",
"dealSize": "2",
"fee": "0",
"feeCurrency": "USDT",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberge": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "IOS",
"clientOid": null,
"remark": null,
"tags": null,
"isActive": false,
"cancelExist": false,
"createdAt": 1547026471000
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if symbol:
data['symbol'] = symbol
if status:
data['status'] = status
if side:
data['side'] = side
if order_type:
data['type'] = order_type
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['page'] = page
if limit:
data['pageSize'] = limit
return self._get('orders', True, data=data) | [
"def",
"get_orders",
"(",
"self",
",",
"symbol",
"=",
"None",
",",
"status",
"=",
"None",
",",
"side",
"=",
"None",
",",
"order_type",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"page",
"=",
"None",
",",
"limit",
"=",
"... | Get list of orders
https://docs.kucoin.com/#list-orders
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
:param status: (optional) Specify status active or done (default done)
:type status: string
:param side: (optional) buy or sell
:type side: string
:param order_type: (optional) limit, market, limit_stop or market_stop
:type order_type: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of orders
:type limit: int
.. code:: python
orders = client.get_orders(symbol='KCS-BTC', status='active')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 1,
"totalNum": 153408,
"totalPage": 153408,
"items": [
{
"id": "5c35c02703aa673ceec2a168",
"symbol": "BTC-USDT",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "10",
"size": "2",
"funds": "0",
"dealFunds": "0.166",
"dealSize": "2",
"fee": "0",
"feeCurrency": "USDT",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberge": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "IOS",
"clientOid": null,
"remark": null,
"tags": null,
"isActive": false,
"cancelExist": false,
"createdAt": 1547026471000
}
]
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"list",
"of",
"orders"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1106-L1200 | train | 202,127 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_historical_orders | def get_historical_orders(self, symbol=None, side=None,
start=None, end=None, page=None, limit=None):
"""List of KuCoin V1 historical orders.
https://docs.kucoin.com/#get-v1-historical-orders-list
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: (optional) buy or sell
:type side: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of orders
:type limit: int
.. code:: python
orders = client.get_historical_orders(symbol='KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 50,
"totalNum": 1,
"totalPage": 1,
"items": [
{
"symbol": "SNOV-ETH",
"dealPrice": "0.0000246",
"dealValue": "0.018942",
"amount": "770",
"fee": "0.00001137",
"side": "sell",
"createdAt": 1540080199
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if symbol:
data['symbol'] = symbol
if side:
data['side'] = side
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['page'] = page
if limit:
data['pageSize'] = limit
return self._get('hist-orders', True, data=data) | python | def get_historical_orders(self, symbol=None, side=None,
start=None, end=None, page=None, limit=None):
"""List of KuCoin V1 historical orders.
https://docs.kucoin.com/#get-v1-historical-orders-list
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: (optional) buy or sell
:type side: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of orders
:type limit: int
.. code:: python
orders = client.get_historical_orders(symbol='KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 50,
"totalNum": 1,
"totalPage": 1,
"items": [
{
"symbol": "SNOV-ETH",
"dealPrice": "0.0000246",
"dealValue": "0.018942",
"amount": "770",
"fee": "0.00001137",
"side": "sell",
"createdAt": 1540080199
}
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if symbol:
data['symbol'] = symbol
if side:
data['side'] = side
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['page'] = page
if limit:
data['pageSize'] = limit
return self._get('hist-orders', True, data=data) | [
"def",
"get_historical_orders",
"(",
"self",
",",
"symbol",
"=",
"None",
",",
"side",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"page",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"sy... | List of KuCoin V1 historical orders.
https://docs.kucoin.com/#get-v1-historical-orders-list
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: (optional) buy or sell
:type side: string
:param start: (optional) Start time as unix timestamp
:type start: string
:param end: (optional) End time as unix timestamp
:type end: string
:param page: (optional) Page to fetch
:type page: int
:param limit: (optional) Number of orders
:type limit: int
.. code:: python
orders = client.get_historical_orders(symbol='KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"currentPage": 1,
"pageSize": 50,
"totalNum": 1,
"totalPage": 1,
"items": [
{
"symbol": "SNOV-ETH",
"dealPrice": "0.0000246",
"dealValue": "0.018942",
"amount": "770",
"fee": "0.00001137",
"side": "sell",
"createdAt": 1540080199
}
]
}
:raises: KucoinResponseException, KucoinAPIException | [
"List",
"of",
"KuCoin",
"V1",
"historical",
"orders",
"."
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1202-L1266 | train | 202,128 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_ticker | def get_ticker(self, symbol=None):
"""Get symbol tick
https://docs.kucoin.com/#get-ticker
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
all_ticks = client.get_ticker()
ticker = client.get_ticker('ETH-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "1545825031840", # now sequence
"price": "3494.367783", # last trade price
"size": "0.05027185", # last trade size
"bestBid": "3494.367783", # best bid price
"bestBidSize": "2.60323254", # size at best bid price
"bestAsk": "3499.12", # best ask price
"bestAskSize": "0.01474011" # size at best ask price
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
tick_path = 'market/allTickers'
if symbol is not None:
tick_path = 'market/orderbook/level1'
data = {
'symbol': symbol
}
return self._get(tick_path, False, data=data) | python | def get_ticker(self, symbol=None):
"""Get symbol tick
https://docs.kucoin.com/#get-ticker
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
all_ticks = client.get_ticker()
ticker = client.get_ticker('ETH-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "1545825031840", # now sequence
"price": "3494.367783", # last trade price
"size": "0.05027185", # last trade size
"bestBid": "3494.367783", # best bid price
"bestBidSize": "2.60323254", # size at best bid price
"bestAsk": "3499.12", # best ask price
"bestAskSize": "0.01474011" # size at best ask price
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
tick_path = 'market/allTickers'
if symbol is not None:
tick_path = 'market/orderbook/level1'
data = {
'symbol': symbol
}
return self._get(tick_path, False, data=data) | [
"def",
"get_ticker",
"(",
"self",
",",
"symbol",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"tick_path",
"=",
"'market/allTickers'",
"if",
"symbol",
"is",
"not",
"None",
":",
"tick_path",
"=",
"'market/orderbook/level1'",
"data",
"=",
"{",
"'symbol'",
"... | Get symbol tick
https://docs.kucoin.com/#get-ticker
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
all_ticks = client.get_ticker()
ticker = client.get_ticker('ETH-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "1545825031840", # now sequence
"price": "3494.367783", # last trade price
"size": "0.05027185", # last trade size
"bestBid": "3494.367783", # best bid price
"bestBidSize": "2.60323254", # size at best bid price
"bestAsk": "3499.12", # best ask price
"bestAskSize": "0.01474011" # size at best ask price
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"symbol",
"tick"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1444-L1482 | train | 202,129 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_fiat_prices | def get_fiat_prices(self, base=None, symbol=None):
"""Get fiat price for currency
https://docs.kucoin.com/#get-fiat-price
:param base: (optional) Fiat,eg.USD,EUR, default is USD.
:type base: string
:param symbol: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with
comma one by one. default is all
:type symbol: string
.. code:: python
prices = client.get_fiat_prices()
:returns: ApiResponse
.. code:: python
{
"BTC": "3911.28000000",
"ETH": "144.55492453",
"LTC": "48.45888179",
"KCS": "0.45546856"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if base is not None:
data['base'] = base
if symbol is not None:
data['currencies'] = symbol
return self._get('prices', False, data=data) | python | def get_fiat_prices(self, base=None, symbol=None):
"""Get fiat price for currency
https://docs.kucoin.com/#get-fiat-price
:param base: (optional) Fiat,eg.USD,EUR, default is USD.
:type base: string
:param symbol: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with
comma one by one. default is all
:type symbol: string
.. code:: python
prices = client.get_fiat_prices()
:returns: ApiResponse
.. code:: python
{
"BTC": "3911.28000000",
"ETH": "144.55492453",
"LTC": "48.45888179",
"KCS": "0.45546856"
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {}
if base is not None:
data['base'] = base
if symbol is not None:
data['currencies'] = symbol
return self._get('prices', False, data=data) | [
"def",
"get_fiat_prices",
"(",
"self",
",",
"base",
"=",
"None",
",",
"symbol",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"base",
"is",
"not",
"None",
":",
"data",
"[",
"'base'",
"]",
"=",
"base",
"if",
"symbol",
"is",
"not",
"None",
":... | Get fiat price for currency
https://docs.kucoin.com/#get-fiat-price
:param base: (optional) Fiat,eg.USD,EUR, default is USD.
:type base: string
:param symbol: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with
comma one by one. default is all
:type symbol: string
.. code:: python
prices = client.get_fiat_prices()
:returns: ApiResponse
.. code:: python
{
"BTC": "3911.28000000",
"ETH": "144.55492453",
"LTC": "48.45888179",
"KCS": "0.45546856"
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"fiat",
"price",
"for",
"currency"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1484-L1521 | train | 202,130 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_24hr_stats | def get_24hr_stats(self, symbol):
"""Get 24hr stats for a symbol. Volume is in base currency units. open, high, low are in quote currency units.
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
stats = client.get_24hr_stats('ETH-BTC')
:returns: ApiResponse
Without a symbol param
.. code:: python
{
"symbol": "BTC-USDT",
"changeRate": "0.0128", # 24h change rate
"changePrice": "0.8", # 24h rises and falls in price (if the change rate is a negative number,
# the price rises; if the change rate is a positive number, the price falls.)
"open": 61, # Opening price
"close": 63.6, # Closing price
"high": "63.6", # Highest price filled
"low": "61", # Lowest price filled
"vol": "244.78", # Transaction quantity
"volValue": "15252.0127" # Transaction amount
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/stats', False, data=data) | python | def get_24hr_stats(self, symbol):
"""Get 24hr stats for a symbol. Volume is in base currency units. open, high, low are in quote currency units.
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
stats = client.get_24hr_stats('ETH-BTC')
:returns: ApiResponse
Without a symbol param
.. code:: python
{
"symbol": "BTC-USDT",
"changeRate": "0.0128", # 24h change rate
"changePrice": "0.8", # 24h rises and falls in price (if the change rate is a negative number,
# the price rises; if the change rate is a positive number, the price falls.)
"open": 61, # Opening price
"close": 63.6, # Closing price
"high": "63.6", # Highest price filled
"low": "61", # Lowest price filled
"vol": "244.78", # Transaction quantity
"volValue": "15252.0127" # Transaction amount
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/stats', False, data=data) | [
"def",
"get_24hr_stats",
"(",
"self",
",",
"symbol",
")",
":",
"data",
"=",
"{",
"'symbol'",
":",
"symbol",
"}",
"return",
"self",
".",
"_get",
"(",
"'market/stats'",
",",
"False",
",",
"data",
"=",
"data",
")"
] | Get 24hr stats for a symbol. Volume is in base currency units. open, high, low are in quote currency units.
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
stats = client.get_24hr_stats('ETH-BTC')
:returns: ApiResponse
Without a symbol param
.. code:: python
{
"symbol": "BTC-USDT",
"changeRate": "0.0128", # 24h change rate
"changePrice": "0.8", # 24h rises and falls in price (if the change rate is a negative number,
# the price rises; if the change rate is a positive number, the price falls.)
"open": 61, # Opening price
"close": 63.6, # Closing price
"high": "63.6", # Highest price filled
"low": "61", # Lowest price filled
"vol": "244.78", # Transaction quantity
"volValue": "15252.0127" # Transaction amount
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"24hr",
"stats",
"for",
"a",
"symbol",
".",
"Volume",
"is",
"in",
"base",
"currency",
"units",
".",
"open",
"high",
"low",
"are",
"in",
"quote",
"currency",
"units",
"."
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1523-L1560 | train | 202,131 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_order_book | def get_order_book(self, symbol):
"""Get a list of bids and asks aggregated by price for a symbol.
Returns up to 100 depth each side. Fastest Order book API
https://docs.kucoin.com/#get-part-order-book-aggregated
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "3262786978",
"bids": [
["6500.12", "0.45054140"], # [price, size]
["6500.11", "0.45054140"]
],
"asks": [
["6500.16", "0.57753524"],
["6500.15", "0.57753524"]
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/orderbook/level2_100', False, data=data) | python | def get_order_book(self, symbol):
"""Get a list of bids and asks aggregated by price for a symbol.
Returns up to 100 depth each side. Fastest Order book API
https://docs.kucoin.com/#get-part-order-book-aggregated
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "3262786978",
"bids": [
["6500.12", "0.45054140"], # [price, size]
["6500.11", "0.45054140"]
],
"asks": [
["6500.16", "0.57753524"],
["6500.15", "0.57753524"]
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/orderbook/level2_100', False, data=data) | [
"def",
"get_order_book",
"(",
"self",
",",
"symbol",
")",
":",
"data",
"=",
"{",
"'symbol'",
":",
"symbol",
"}",
"return",
"self",
".",
"_get",
"(",
"'market/orderbook/level2_100'",
",",
"False",
",",
"data",
"=",
"data",
")"
] | Get a list of bids and asks aggregated by price for a symbol.
Returns up to 100 depth each side. Fastest Order book API
https://docs.kucoin.com/#get-part-order-book-aggregated
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "3262786978",
"bids": [
["6500.12", "0.45054140"], # [price, size]
["6500.11", "0.45054140"]
],
"asks": [
["6500.16", "0.57753524"],
["6500.15", "0.57753524"]
]
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"a",
"list",
"of",
"bids",
"and",
"asks",
"aggregated",
"by",
"price",
"for",
"a",
"symbol",
"."
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1588-L1626 | train | 202,132 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_full_order_book | def get_full_order_book(self, symbol):
"""Get a list of all bids and asks aggregated by price for a symbol.
This call is generally used by professional traders because it uses more server resources and traffic,
and Kucoin has strict access frequency control.
https://docs.kucoin.com/#get-full-order-book-aggregated
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "3262786978",
"bids": [
["6500.12", "0.45054140"], # [price size]
["6500.11", "0.45054140"]
],
"asks": [
["6500.16", "0.57753524"],
["6500.15", "0.57753524"]
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/orderbook/level2', False, data=data) | python | def get_full_order_book(self, symbol):
"""Get a list of all bids and asks aggregated by price for a symbol.
This call is generally used by professional traders because it uses more server resources and traffic,
and Kucoin has strict access frequency control.
https://docs.kucoin.com/#get-full-order-book-aggregated
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "3262786978",
"bids": [
["6500.12", "0.45054140"], # [price size]
["6500.11", "0.45054140"]
],
"asks": [
["6500.16", "0.57753524"],
["6500.15", "0.57753524"]
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/orderbook/level2', False, data=data) | [
"def",
"get_full_order_book",
"(",
"self",
",",
"symbol",
")",
":",
"data",
"=",
"{",
"'symbol'",
":",
"symbol",
"}",
"return",
"self",
".",
"_get",
"(",
"'market/orderbook/level2'",
",",
"False",
",",
"data",
"=",
"data",
")"
] | Get a list of all bids and asks aggregated by price for a symbol.
This call is generally used by professional traders because it uses more server resources and traffic,
and Kucoin has strict access frequency control.
https://docs.kucoin.com/#get-full-order-book-aggregated
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "3262786978",
"bids": [
["6500.12", "0.45054140"], # [price size]
["6500.11", "0.45054140"]
],
"asks": [
["6500.16", "0.57753524"],
["6500.15", "0.57753524"]
]
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"a",
"list",
"of",
"all",
"bids",
"and",
"asks",
"aggregated",
"by",
"price",
"for",
"a",
"symbol",
"."
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1628-L1667 | train | 202,133 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_full_order_book_level3 | def get_full_order_book_level3(self, symbol):
"""Get a list of all bids and asks non-aggregated for a symbol.
This call is generally used by professional traders because it uses more server resources and traffic,
and Kucoin has strict access frequency control.
https://docs.kucoin.com/#get-full-order-book-atomic
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "1545896707028",
"bids": [
[
"5c2477e503aa671a745c4057", # orderId
"6", # price
"0.999" # size
],
[
"5c2477e103aa671a745c4054",
"5",
"0.999"
]
],
"asks": [
[
"5c24736703aa671a745c401e",
"200",
"1"
],
[
"5c2475c903aa671a745c4033",
"201",
"1"
]
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/orderbook/level3', False, data=data) | python | def get_full_order_book_level3(self, symbol):
"""Get a list of all bids and asks non-aggregated for a symbol.
This call is generally used by professional traders because it uses more server resources and traffic,
and Kucoin has strict access frequency control.
https://docs.kucoin.com/#get-full-order-book-atomic
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "1545896707028",
"bids": [
[
"5c2477e503aa671a745c4057", # orderId
"6", # price
"0.999" # size
],
[
"5c2477e103aa671a745c4054",
"5",
"0.999"
]
],
"asks": [
[
"5c24736703aa671a745c401e",
"200",
"1"
],
[
"5c2475c903aa671a745c4033",
"201",
"1"
]
]
}
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/orderbook/level3', False, data=data) | [
"def",
"get_full_order_book_level3",
"(",
"self",
",",
"symbol",
")",
":",
"data",
"=",
"{",
"'symbol'",
":",
"symbol",
"}",
"return",
"self",
".",
"_get",
"(",
"'market/orderbook/level3'",
",",
"False",
",",
"data",
"=",
"data",
")"
] | Get a list of all bids and asks non-aggregated for a symbol.
This call is generally used by professional traders because it uses more server resources and traffic,
and Kucoin has strict access frequency control.
https://docs.kucoin.com/#get-full-order-book-atomic
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_order_book('KCS-BTC')
:returns: ApiResponse
.. code:: python
{
"sequence": "1545896707028",
"bids": [
[
"5c2477e503aa671a745c4057", # orderId
"6", # price
"0.999" # size
],
[
"5c2477e103aa671a745c4054",
"5",
"0.999"
]
],
"asks": [
[
"5c24736703aa671a745c401e",
"200",
"1"
],
[
"5c2475c903aa671a745c4033",
"201",
"1"
]
]
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"a",
"list",
"of",
"all",
"bids",
"and",
"asks",
"non",
"-",
"aggregated",
"for",
"a",
"symbol",
"."
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1669-L1724 | train | 202,134 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_trade_histories | def get_trade_histories(self, symbol):
"""List the latest trades for a symbol
https://docs.kucoin.com/#get-trade-histories
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_trade_histories('KCS-BTC')
:returns: ApiResponse
.. code:: python
[
{
"sequence": "1545896668571",
"price": "0.07", # Filled price
"size": "0.004", # Filled amount
"side": "buy", # Filled side. The filled side is set to the taker by default.
"time": 1545904567062140823 # Transaction time
},
{
"sequence": "1545896668578",
"price": "0.054",
"size": "0.066",
"side": "buy",
"time": 1545904581619888405
}
]
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/histories', False, data=data) | python | def get_trade_histories(self, symbol):
"""List the latest trades for a symbol
https://docs.kucoin.com/#get-trade-histories
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_trade_histories('KCS-BTC')
:returns: ApiResponse
.. code:: python
[
{
"sequence": "1545896668571",
"price": "0.07", # Filled price
"size": "0.004", # Filled amount
"side": "buy", # Filled side. The filled side is set to the taker by default.
"time": 1545904567062140823 # Transaction time
},
{
"sequence": "1545896668578",
"price": "0.054",
"size": "0.066",
"side": "buy",
"time": 1545904581619888405
}
]
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
return self._get('market/histories', False, data=data) | [
"def",
"get_trade_histories",
"(",
"self",
",",
"symbol",
")",
":",
"data",
"=",
"{",
"'symbol'",
":",
"symbol",
"}",
"return",
"self",
".",
"_get",
"(",
"'market/histories'",
",",
"False",
",",
"data",
"=",
"data",
")"
] | List the latest trades for a symbol
https://docs.kucoin.com/#get-trade-histories
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
.. code:: python
orders = client.get_trade_histories('KCS-BTC')
:returns: ApiResponse
.. code:: python
[
{
"sequence": "1545896668571",
"price": "0.07", # Filled price
"size": "0.004", # Filled amount
"side": "buy", # Filled side. The filled side is set to the taker by default.
"time": 1545904567062140823 # Transaction time
},
{
"sequence": "1545896668578",
"price": "0.054",
"size": "0.066",
"side": "buy",
"time": 1545904581619888405
}
]
:raises: KucoinResponseException, KucoinAPIException | [
"List",
"the",
"latest",
"trades",
"for",
"a",
"symbol"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1726-L1767 | train | 202,135 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_kline_data | def get_kline_data(self, symbol, kline_type='5min', start=None, end=None):
"""Get kline data
For each query, the system would return at most 1500 pieces of data.
To obtain more data, please page the data by time.
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param kline_type: type of symbol, type of candlestick patterns: 1min, 3min, 5min, 15min, 30min, 1hour, 2hour,
4hour, 6hour, 8hour, 12hour, 1day, 1week
:type kline_type: string
:param start: Start time as unix timestamp (optional) default start of day in UTC
:type start: int
:param end: End time as unix timestamp (optional) default now in UTC
:type end: int
https://docs.kucoin.com/#get-historic-rates
.. code:: python
klines = client.get_kline_data('KCS-BTC', '5min', 1507479171, 1510278278)
:returns: ApiResponse
.. code:: python
[
[
"1545904980", //Start time of the candle cycle
"0.058", //opening price
"0.049", //closing price
"0.058", //highest price
"0.049", //lowest price
"0.018", //Transaction amount
"0.000945" //Transaction volume
],
[
"1545904920",
"0.058",
"0.072",
"0.072",
"0.058",
"0.103",
"0.006986"
]
]
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
if kline_type is not None:
data['type'] = kline_type
if start is not None:
data['startAt'] = start
else:
data['startAt'] = calendar.timegm(datetime.utcnow().date().timetuple())
if end is not None:
data['endAt'] = end
else:
data['endAt'] = int(time.time())
return self._get('market/candles', False, data=data) | python | def get_kline_data(self, symbol, kline_type='5min', start=None, end=None):
"""Get kline data
For each query, the system would return at most 1500 pieces of data.
To obtain more data, please page the data by time.
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param kline_type: type of symbol, type of candlestick patterns: 1min, 3min, 5min, 15min, 30min, 1hour, 2hour,
4hour, 6hour, 8hour, 12hour, 1day, 1week
:type kline_type: string
:param start: Start time as unix timestamp (optional) default start of day in UTC
:type start: int
:param end: End time as unix timestamp (optional) default now in UTC
:type end: int
https://docs.kucoin.com/#get-historic-rates
.. code:: python
klines = client.get_kline_data('KCS-BTC', '5min', 1507479171, 1510278278)
:returns: ApiResponse
.. code:: python
[
[
"1545904980", //Start time of the candle cycle
"0.058", //opening price
"0.049", //closing price
"0.058", //highest price
"0.049", //lowest price
"0.018", //Transaction amount
"0.000945" //Transaction volume
],
[
"1545904920",
"0.058",
"0.072",
"0.072",
"0.058",
"0.103",
"0.006986"
]
]
:raises: KucoinResponseException, KucoinAPIException
"""
data = {
'symbol': symbol
}
if kline_type is not None:
data['type'] = kline_type
if start is not None:
data['startAt'] = start
else:
data['startAt'] = calendar.timegm(datetime.utcnow().date().timetuple())
if end is not None:
data['endAt'] = end
else:
data['endAt'] = int(time.time())
return self._get('market/candles', False, data=data) | [
"def",
"get_kline_data",
"(",
"self",
",",
"symbol",
",",
"kline_type",
"=",
"'5min'",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'symbol'",
":",
"symbol",
"}",
"if",
"kline_type",
"is",
"not",
"None",
":",
"data... | Get kline data
For each query, the system would return at most 1500 pieces of data.
To obtain more data, please page the data by time.
:param symbol: Name of symbol e.g. KCS-BTC
:type symbol: string
:param kline_type: type of symbol, type of candlestick patterns: 1min, 3min, 5min, 15min, 30min, 1hour, 2hour,
4hour, 6hour, 8hour, 12hour, 1day, 1week
:type kline_type: string
:param start: Start time as unix timestamp (optional) default start of day in UTC
:type start: int
:param end: End time as unix timestamp (optional) default now in UTC
:type end: int
https://docs.kucoin.com/#get-historic-rates
.. code:: python
klines = client.get_kline_data('KCS-BTC', '5min', 1507479171, 1510278278)
:returns: ApiResponse
.. code:: python
[
[
"1545904980", //Start time of the candle cycle
"0.058", //opening price
"0.049", //closing price
"0.058", //highest price
"0.049", //lowest price
"0.018", //Transaction amount
"0.000945" //Transaction volume
],
[
"1545904920",
"0.058",
"0.072",
"0.072",
"0.058",
"0.103",
"0.006986"
]
]
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"kline",
"data"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1769-L1835 | train | 202,136 |
sammchardy/python-kucoin | kucoin/client.py | Client.get_ws_endpoint | def get_ws_endpoint(self, private=False):
"""Get websocket channel details
:param private: Name of symbol e.g. KCS-BTC
:type private: bool
https://docs.kucoin.com/#websocket-feed
.. code:: python
ws_details = client.get_ws_endpoint(private=True)
:returns: ApiResponse
.. code:: python
{
"code": "200000",
"data": {
"instanceServers": [
{
"pingInterval": 50000,
"endpoint": "wss://push1-v2.kucoin.net/endpoint",
"protocol": "websocket",
"encrypt": true,
"pingTimeout": 10000
}
],
"token": "vYNlCtbz4XNJ1QncwWilJnBtmmfe4geLQDUA62kKJsDChc6I4bRDQc73JfIrlFaVYIAE0Gv2--MROnLAgjVsWkcDq_MuG7qV7EktfCEIphiqnlfpQn4Ybg==.IoORVxR2LmKV7_maOR9xOg=="
}
}
:raises: KucoinResponseException, KucoinAPIException
"""
path = 'bullet-public'
signed = private
if private:
path = 'bullet-private'
return self._post(path, signed) | python | def get_ws_endpoint(self, private=False):
"""Get websocket channel details
:param private: Name of symbol e.g. KCS-BTC
:type private: bool
https://docs.kucoin.com/#websocket-feed
.. code:: python
ws_details = client.get_ws_endpoint(private=True)
:returns: ApiResponse
.. code:: python
{
"code": "200000",
"data": {
"instanceServers": [
{
"pingInterval": 50000,
"endpoint": "wss://push1-v2.kucoin.net/endpoint",
"protocol": "websocket",
"encrypt": true,
"pingTimeout": 10000
}
],
"token": "vYNlCtbz4XNJ1QncwWilJnBtmmfe4geLQDUA62kKJsDChc6I4bRDQc73JfIrlFaVYIAE0Gv2--MROnLAgjVsWkcDq_MuG7qV7EktfCEIphiqnlfpQn4Ybg==.IoORVxR2LmKV7_maOR9xOg=="
}
}
:raises: KucoinResponseException, KucoinAPIException
"""
path = 'bullet-public'
signed = private
if private:
path = 'bullet-private'
return self._post(path, signed) | [
"def",
"get_ws_endpoint",
"(",
"self",
",",
"private",
"=",
"False",
")",
":",
"path",
"=",
"'bullet-public'",
"signed",
"=",
"private",
"if",
"private",
":",
"path",
"=",
"'bullet-private'",
"return",
"self",
".",
"_post",
"(",
"path",
",",
"signed",
")"
... | Get websocket channel details
:param private: Name of symbol e.g. KCS-BTC
:type private: bool
https://docs.kucoin.com/#websocket-feed
.. code:: python
ws_details = client.get_ws_endpoint(private=True)
:returns: ApiResponse
.. code:: python
{
"code": "200000",
"data": {
"instanceServers": [
{
"pingInterval": 50000,
"endpoint": "wss://push1-v2.kucoin.net/endpoint",
"protocol": "websocket",
"encrypt": true,
"pingTimeout": 10000
}
],
"token": "vYNlCtbz4XNJ1QncwWilJnBtmmfe4geLQDUA62kKJsDChc6I4bRDQc73JfIrlFaVYIAE0Gv2--MROnLAgjVsWkcDq_MuG7qV7EktfCEIphiqnlfpQn4Ybg==.IoORVxR2LmKV7_maOR9xOg=="
}
}
:raises: KucoinResponseException, KucoinAPIException | [
"Get",
"websocket",
"channel",
"details"
] | a4cacde413804784bd313f27a0ad37234888be29 | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1839-L1880 | train | 202,137 |
martinrusev/django-redis-sessions | redis_sessions/session.py | SessionStore.get_real_stored_key | def get_real_stored_key(self, session_key):
"""Return the real key name in redis storage
@return string
"""
prefix = settings.SESSION_REDIS_PREFIX
if not prefix:
return session_key
return ':'.join([prefix, session_key]) | python | def get_real_stored_key(self, session_key):
"""Return the real key name in redis storage
@return string
"""
prefix = settings.SESSION_REDIS_PREFIX
if not prefix:
return session_key
return ':'.join([prefix, session_key]) | [
"def",
"get_real_stored_key",
"(",
"self",
",",
"session_key",
")",
":",
"prefix",
"=",
"settings",
".",
"SESSION_REDIS_PREFIX",
"if",
"not",
"prefix",
":",
"return",
"session_key",
"return",
"':'",
".",
"join",
"(",
"[",
"prefix",
",",
"session_key",
"]",
"... | Return the real key name in redis storage
@return string | [
"Return",
"the",
"real",
"key",
"name",
"in",
"redis",
"storage"
] | 260b9f3b61a17de9fa26f3e697b94bceee21e715 | https://github.com/martinrusev/django-redis-sessions/blob/260b9f3b61a17de9fa26f3e697b94bceee21e715/redis_sessions/session.py#L169-L176 | train | 202,138 |
mapbox/supermercado | supermercado/scripts/cli.py | burn | def burn(features, sequence, zoom):
"""
Burn a stream of GeoJSONs into a output stream of the tiles they intersect for a given zoom.
"""
features = [f for f in super_utils.filter_polygons(features)]
tiles = burntiles.burn(features, zoom)
for t in tiles:
click.echo(t.tolist()) | python | def burn(features, sequence, zoom):
"""
Burn a stream of GeoJSONs into a output stream of the tiles they intersect for a given zoom.
"""
features = [f for f in super_utils.filter_polygons(features)]
tiles = burntiles.burn(features, zoom)
for t in tiles:
click.echo(t.tolist()) | [
"def",
"burn",
"(",
"features",
",",
"sequence",
",",
"zoom",
")",
":",
"features",
"=",
"[",
"f",
"for",
"f",
"in",
"super_utils",
".",
"filter_polygons",
"(",
"features",
")",
"]",
"tiles",
"=",
"burntiles",
".",
"burn",
"(",
"features",
",",
"zoom",... | Burn a stream of GeoJSONs into a output stream of the tiles they intersect for a given zoom. | [
"Burn",
"a",
"stream",
"of",
"GeoJSONs",
"into",
"a",
"output",
"stream",
"of",
"the",
"tiles",
"they",
"intersect",
"for",
"a",
"given",
"zoom",
"."
] | a3f3e4b0a5b4694aabc6245f90bd8a93db8c90a4 | https://github.com/mapbox/supermercado/blob/a3f3e4b0a5b4694aabc6245f90bd8a93db8c90a4/supermercado/scripts/cli.py#L52-L60 | train | 202,139 |
SectorLabs/django-localized-fields | localized_fields/mixins.py | AtomicSlugRetryMixin.save | def save(self, *args, **kwargs):
"""Saves this model instance to the database."""
max_retries = getattr(
settings,
'LOCALIZED_FIELDS_MAX_RETRIES',
100
)
if not hasattr(self, 'retries'):
self.retries = 0
with transaction.atomic():
try:
return super().save(*args, **kwargs)
except IntegrityError as ex:
# this is as retarded as it looks, there's no
# way we can put the retry logic inside the slug
# field class... we can also not only catch exceptions
# that apply to slug fields... so yea.. this is as
# retarded as it gets... i am sorry :(
if 'slug' not in str(ex):
raise ex
if self.retries >= max_retries:
raise ex
self.retries += 1
return self.save() | python | def save(self, *args, **kwargs):
"""Saves this model instance to the database."""
max_retries = getattr(
settings,
'LOCALIZED_FIELDS_MAX_RETRIES',
100
)
if not hasattr(self, 'retries'):
self.retries = 0
with transaction.atomic():
try:
return super().save(*args, **kwargs)
except IntegrityError as ex:
# this is as retarded as it looks, there's no
# way we can put the retry logic inside the slug
# field class... we can also not only catch exceptions
# that apply to slug fields... so yea.. this is as
# retarded as it gets... i am sorry :(
if 'slug' not in str(ex):
raise ex
if self.retries >= max_retries:
raise ex
self.retries += 1
return self.save() | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"max_retries",
"=",
"getattr",
"(",
"settings",
",",
"'LOCALIZED_FIELDS_MAX_RETRIES'",
",",
"100",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'retries'",
")",
":",
"s... | Saves this model instance to the database. | [
"Saves",
"this",
"model",
"instance",
"to",
"the",
"database",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/mixins.py#L10-L38 | train | 202,140 |
SectorLabs/django-localized-fields | localized_fields/fields/integer_field.py | LocalizedIntegerField.to_python | def to_python(self, value: Union[Dict[str, int], int, None]) -> LocalizedIntegerValue:
"""Converts the value from a database value into a Python value."""
db_value = super().to_python(value)
return self._convert_localized_value(db_value) | python | def to_python(self, value: Union[Dict[str, int], int, None]) -> LocalizedIntegerValue:
"""Converts the value from a database value into a Python value."""
db_value = super().to_python(value)
return self._convert_localized_value(db_value) | [
"def",
"to_python",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"Dict",
"[",
"str",
",",
"int",
"]",
",",
"int",
",",
"None",
"]",
")",
"->",
"LocalizedIntegerValue",
":",
"db_value",
"=",
"super",
"(",
")",
".",
"to_python",
"(",
"value",
")",
"... | Converts the value from a database value into a Python value. | [
"Converts",
"the",
"value",
"from",
"a",
"database",
"value",
"into",
"a",
"Python",
"value",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/fields/integer_field.py#L30-L34 | train | 202,141 |
SectorLabs/django-localized-fields | localized_fields/fields/integer_field.py | LocalizedIntegerField.get_prep_value | def get_prep_value(self, value: LocalizedIntegerValue) -> dict:
"""Gets the value in a format to store into the database."""
# apply default values
default_values = LocalizedIntegerValue(self.default)
if isinstance(value, LocalizedIntegerValue):
for lang_code, _ in settings.LANGUAGES:
local_value = value.get(lang_code)
if local_value is None:
value.set(lang_code, default_values.get(lang_code, None))
prepped_value = super().get_prep_value(value)
if prepped_value is None:
return None
# make sure all values are proper integers
for lang_code, _ in settings.LANGUAGES:
local_value = prepped_value[lang_code]
try:
if local_value is not None:
int(local_value)
except (TypeError, ValueError):
raise IntegrityError('non-integer value in column "%s.%s" violates '
'integer constraint' % (self.name, lang_code))
# convert to a string before saving because the underlying
# type is hstore, which only accept strings
prepped_value[lang_code] = str(local_value) if local_value is not None else None
return prepped_value | python | def get_prep_value(self, value: LocalizedIntegerValue) -> dict:
"""Gets the value in a format to store into the database."""
# apply default values
default_values = LocalizedIntegerValue(self.default)
if isinstance(value, LocalizedIntegerValue):
for lang_code, _ in settings.LANGUAGES:
local_value = value.get(lang_code)
if local_value is None:
value.set(lang_code, default_values.get(lang_code, None))
prepped_value = super().get_prep_value(value)
if prepped_value is None:
return None
# make sure all values are proper integers
for lang_code, _ in settings.LANGUAGES:
local_value = prepped_value[lang_code]
try:
if local_value is not None:
int(local_value)
except (TypeError, ValueError):
raise IntegrityError('non-integer value in column "%s.%s" violates '
'integer constraint' % (self.name, lang_code))
# convert to a string before saving because the underlying
# type is hstore, which only accept strings
prepped_value[lang_code] = str(local_value) if local_value is not None else None
return prepped_value | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
":",
"LocalizedIntegerValue",
")",
"->",
"dict",
":",
"# apply default values",
"default_values",
"=",
"LocalizedIntegerValue",
"(",
"self",
".",
"default",
")",
"if",
"isinstance",
"(",
"value",
",",
"LocalizedI... | Gets the value in a format to store into the database. | [
"Gets",
"the",
"value",
"in",
"a",
"format",
"to",
"store",
"into",
"the",
"database",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/fields/integer_field.py#L36-L65 | train | 202,142 |
SectorLabs/django-localized-fields | localized_fields/fields/autoslug_field.py | LocalizedAutoSlugField._make_unique_slug | def _make_unique_slug(slug: str, language: str, is_unique: Callable[[str], bool]) -> str:
"""Guarentees that the specified slug is unique by appending
a number until it is unique.
Arguments:
slug:
The slug to make unique.
is_unique:
Function that can be called to verify
whether the generate slug is unique.
Returns:
A guarenteed unique slug.
"""
index = 1
unique_slug = slug
while not is_unique(unique_slug, language):
unique_slug = '%s-%d' % (slug, index)
index += 1
return unique_slug | python | def _make_unique_slug(slug: str, language: str, is_unique: Callable[[str], bool]) -> str:
"""Guarentees that the specified slug is unique by appending
a number until it is unique.
Arguments:
slug:
The slug to make unique.
is_unique:
Function that can be called to verify
whether the generate slug is unique.
Returns:
A guarenteed unique slug.
"""
index = 1
unique_slug = slug
while not is_unique(unique_slug, language):
unique_slug = '%s-%d' % (slug, index)
index += 1
return unique_slug | [
"def",
"_make_unique_slug",
"(",
"slug",
":",
"str",
",",
"language",
":",
"str",
",",
"is_unique",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"bool",
"]",
")",
"->",
"str",
":",
"index",
"=",
"1",
"unique_slug",
"=",
"slug",
"while",
"not",
"is_uni... | Guarentees that the specified slug is unique by appending
a number until it is unique.
Arguments:
slug:
The slug to make unique.
is_unique:
Function that can be called to verify
whether the generate slug is unique.
Returns:
A guarenteed unique slug. | [
"Guarentees",
"that",
"the",
"specified",
"slug",
"is",
"unique",
"by",
"appending",
"a",
"number",
"until",
"it",
"is",
"unique",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/fields/autoslug_field.py#L109-L132 | train | 202,143 |
SectorLabs/django-localized-fields | localized_fields/fields/autoslug_field.py | LocalizedAutoSlugField._get_populate_from_value | def _get_populate_from_value(instance, field_name: Union[str, Tuple[str]], language: str):
"""Gets the value to create a slug from in the specified language.
Arguments:
instance:
The model that the field resides on.
field_name:
The name of the field to generate a slug for.
language:
The language to generate the slug for.
Returns:
The text to generate a slug for.
"""
if callable(field_name):
return field_name(instance)
def get_field_value(name):
value = resolve_object_property(instance, name)
with translation.override(language):
return str(value)
if isinstance(field_name, tuple) or isinstance(field_name, list):
value = '-'.join([
value
for value in [get_field_value(name) for name in field_name]
if value
])
return value
return get_field_value(field_name) | python | def _get_populate_from_value(instance, field_name: Union[str, Tuple[str]], language: str):
"""Gets the value to create a slug from in the specified language.
Arguments:
instance:
The model that the field resides on.
field_name:
The name of the field to generate a slug for.
language:
The language to generate the slug for.
Returns:
The text to generate a slug for.
"""
if callable(field_name):
return field_name(instance)
def get_field_value(name):
value = resolve_object_property(instance, name)
with translation.override(language):
return str(value)
if isinstance(field_name, tuple) or isinstance(field_name, list):
value = '-'.join([
value
for value in [get_field_value(name) for name in field_name]
if value
])
return value
return get_field_value(field_name) | [
"def",
"_get_populate_from_value",
"(",
"instance",
",",
"field_name",
":",
"Union",
"[",
"str",
",",
"Tuple",
"[",
"str",
"]",
"]",
",",
"language",
":",
"str",
")",
":",
"if",
"callable",
"(",
"field_name",
")",
":",
"return",
"field_name",
"(",
"insta... | Gets the value to create a slug from in the specified language.
Arguments:
instance:
The model that the field resides on.
field_name:
The name of the field to generate a slug for.
language:
The language to generate the slug for.
Returns:
The text to generate a slug for. | [
"Gets",
"the",
"value",
"to",
"create",
"a",
"slug",
"from",
"in",
"the",
"specified",
"language",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/fields/autoslug_field.py#L159-L192 | train | 202,144 |
SectorLabs/django-localized-fields | localized_fields/fields/uniqueslug_field.py | LocalizedUniqueSlugField.deconstruct | def deconstruct(self):
"""Deconstructs the field into something the database
can store."""
name, path, args, kwargs = super(
LocalizedUniqueSlugField, self).deconstruct()
kwargs['populate_from'] = self.populate_from
kwargs['include_time'] = self.include_time
return name, path, args, kwargs | python | def deconstruct(self):
"""Deconstructs the field into something the database
can store."""
name, path, args, kwargs = super(
LocalizedUniqueSlugField, self).deconstruct()
kwargs['populate_from'] = self.populate_from
kwargs['include_time'] = self.include_time
return name, path, args, kwargs | [
"def",
"deconstruct",
"(",
"self",
")",
":",
"name",
",",
"path",
",",
"args",
",",
"kwargs",
"=",
"super",
"(",
"LocalizedUniqueSlugField",
",",
"self",
")",
".",
"deconstruct",
"(",
")",
"kwargs",
"[",
"'populate_from'",
"]",
"=",
"self",
".",
"populat... | Deconstructs the field into something the database
can store. | [
"Deconstructs",
"the",
"field",
"into",
"something",
"the",
"database",
"can",
"store",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/fields/uniqueslug_field.py#L40-L49 | train | 202,145 |
SectorLabs/django-localized-fields | localized_fields/fields/field.py | LocalizedField.contribute_to_class | def contribute_to_class(self, model, name, **kwargs):
"""Adds this field to the specifed model.
Arguments:
cls:
The model to add the field to.
name:
The name of the field to add.
"""
super(LocalizedField, self).contribute_to_class(model, name, **kwargs)
setattr(model, self.name, self.descriptor_class(self)) | python | def contribute_to_class(self, model, name, **kwargs):
"""Adds this field to the specifed model.
Arguments:
cls:
The model to add the field to.
name:
The name of the field to add.
"""
super(LocalizedField, self).contribute_to_class(model, name, **kwargs)
setattr(model, self.name, self.descriptor_class(self)) | [
"def",
"contribute_to_class",
"(",
"self",
",",
"model",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"LocalizedField",
",",
"self",
")",
".",
"contribute_to_class",
"(",
"model",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
"setattr",
"... | Adds this field to the specifed model.
Arguments:
cls:
The model to add the field to.
name:
The name of the field to add. | [
"Adds",
"this",
"field",
"to",
"the",
"specifed",
"model",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/fields/field.py#L42-L53 | train | 202,146 |
SectorLabs/django-localized-fields | localized_fields/fields/field.py | LocalizedField.get_prep_value | def get_prep_value(self, value: LocalizedValue) -> dict:
"""Turns the specified value into something the database
can store.
If an illegal value (non-LocalizedValue instance) is
specified, we'll treat it as an empty :see:LocalizedValue
instance, on which the validation will fail.
Dictonaries are converted into :see:LocalizedValue instances.
Arguments:
value:
The :see:LocalizedValue instance to serialize
into a data type that the database can understand.
Returns:
A dictionary containing a key for every language,
extracted from the specified value.
"""
if isinstance(value, dict):
value = LocalizedValue(value)
# default to None if this is an unknown type
if not isinstance(value, LocalizedValue) and value:
value = None
if value:
cleaned_value = self.clean(value)
self.validate(cleaned_value)
else:
cleaned_value = value
return super(LocalizedField, self).get_prep_value(
cleaned_value.__dict__ if cleaned_value else None
) | python | def get_prep_value(self, value: LocalizedValue) -> dict:
"""Turns the specified value into something the database
can store.
If an illegal value (non-LocalizedValue instance) is
specified, we'll treat it as an empty :see:LocalizedValue
instance, on which the validation will fail.
Dictonaries are converted into :see:LocalizedValue instances.
Arguments:
value:
The :see:LocalizedValue instance to serialize
into a data type that the database can understand.
Returns:
A dictionary containing a key for every language,
extracted from the specified value.
"""
if isinstance(value, dict):
value = LocalizedValue(value)
# default to None if this is an unknown type
if not isinstance(value, LocalizedValue) and value:
value = None
if value:
cleaned_value = self.clean(value)
self.validate(cleaned_value)
else:
cleaned_value = value
return super(LocalizedField, self).get_prep_value(
cleaned_value.__dict__ if cleaned_value else None
) | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
":",
"LocalizedValue",
")",
"->",
"dict",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"value",
"=",
"LocalizedValue",
"(",
"value",
")",
"# default to None if this is an unknown type",
"if",
... | Turns the specified value into something the database
can store.
If an illegal value (non-LocalizedValue instance) is
specified, we'll treat it as an empty :see:LocalizedValue
instance, on which the validation will fail.
Dictonaries are converted into :see:LocalizedValue instances.
Arguments:
value:
The :see:LocalizedValue instance to serialize
into a data type that the database can understand.
Returns:
A dictionary containing a key for every language,
extracted from the specified value. | [
"Turns",
"the",
"specified",
"value",
"into",
"something",
"the",
"database",
"can",
"store",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/fields/field.py#L126-L161 | train | 202,147 |
SectorLabs/django-localized-fields | localized_fields/fields/field.py | LocalizedField.clean | def clean(self, value, *_):
"""Cleans the specified value into something we
can store in the database.
For example, when all the language fields are
left empty, and the field is allowed to be null,
we will store None instead of empty keys.
Arguments:
value:
The value to clean.
Returns:
The cleaned value, ready for database storage.
"""
if not value or not isinstance(value, LocalizedValue):
return None
# are any of the language fiels None/empty?
is_all_null = True
for lang_code, _ in settings.LANGUAGES:
if value.get(lang_code) is not None:
is_all_null = False
break
# all fields have been left empty and we support
# null values, let's return null to represent that
if is_all_null and self.null:
return None
return value | python | def clean(self, value, *_):
"""Cleans the specified value into something we
can store in the database.
For example, when all the language fields are
left empty, and the field is allowed to be null,
we will store None instead of empty keys.
Arguments:
value:
The value to clean.
Returns:
The cleaned value, ready for database storage.
"""
if not value or not isinstance(value, LocalizedValue):
return None
# are any of the language fiels None/empty?
is_all_null = True
for lang_code, _ in settings.LANGUAGES:
if value.get(lang_code) is not None:
is_all_null = False
break
# all fields have been left empty and we support
# null values, let's return null to represent that
if is_all_null and self.null:
return None
return value | [
"def",
"clean",
"(",
"self",
",",
"value",
",",
"*",
"_",
")",
":",
"if",
"not",
"value",
"or",
"not",
"isinstance",
"(",
"value",
",",
"LocalizedValue",
")",
":",
"return",
"None",
"# are any of the language fiels None/empty?",
"is_all_null",
"=",
"True",
"... | Cleans the specified value into something we
can store in the database.
For example, when all the language fields are
left empty, and the field is allowed to be null,
we will store None instead of empty keys.
Arguments:
value:
The value to clean.
Returns:
The cleaned value, ready for database storage. | [
"Cleans",
"the",
"specified",
"value",
"into",
"something",
"we",
"can",
"store",
"in",
"the",
"database",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/fields/field.py#L163-L194 | train | 202,148 |
SectorLabs/django-localized-fields | localized_fields/fields/field.py | LocalizedField.validate | def validate(self, value: LocalizedValue, *_):
"""Validates that the values has been filled in for all required
languages
Exceptions are raises in order to notify the user
of invalid values.
Arguments:
value:
The value to validate.
"""
if self.null:
return
for lang in self.required:
lang_val = getattr(value, settings.LANGUAGE_CODE)
if lang_val is None:
raise IntegrityError('null value in column "%s.%s" violates '
'not-null constraint' % (self.name, lang)) | python | def validate(self, value: LocalizedValue, *_):
"""Validates that the values has been filled in for all required
languages
Exceptions are raises in order to notify the user
of invalid values.
Arguments:
value:
The value to validate.
"""
if self.null:
return
for lang in self.required:
lang_val = getattr(value, settings.LANGUAGE_CODE)
if lang_val is None:
raise IntegrityError('null value in column "%s.%s" violates '
'not-null constraint' % (self.name, lang)) | [
"def",
"validate",
"(",
"self",
",",
"value",
":",
"LocalizedValue",
",",
"*",
"_",
")",
":",
"if",
"self",
".",
"null",
":",
"return",
"for",
"lang",
"in",
"self",
".",
"required",
":",
"lang_val",
"=",
"getattr",
"(",
"value",
",",
"settings",
".",... | Validates that the values has been filled in for all required
languages
Exceptions are raises in order to notify the user
of invalid values.
Arguments:
value:
The value to validate. | [
"Validates",
"that",
"the",
"values",
"has",
"been",
"filled",
"in",
"for",
"all",
"required",
"languages"
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/fields/field.py#L196-L216 | train | 202,149 |
SectorLabs/django-localized-fields | localized_fields/value.py | LocalizedValue.get | def get(self, language: str=None, default: str=None) -> str:
"""Gets the underlying value in the specified or
primary language.
Arguments:
language:
The language to get the value in.
Returns:
The value in the current language, or
the primary language in case no language
was specified.
"""
language = language or settings.LANGUAGE_CODE
value = super().get(language, default)
return value if value is not None else default | python | def get(self, language: str=None, default: str=None) -> str:
"""Gets the underlying value in the specified or
primary language.
Arguments:
language:
The language to get the value in.
Returns:
The value in the current language, or
the primary language in case no language
was specified.
"""
language = language or settings.LANGUAGE_CODE
value = super().get(language, default)
return value if value is not None else default | [
"def",
"get",
"(",
"self",
",",
"language",
":",
"str",
"=",
"None",
",",
"default",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"language",
"=",
"language",
"or",
"settings",
".",
"LANGUAGE_CODE",
"value",
"=",
"super",
"(",
")",
".",
"get",
"... | Gets the underlying value in the specified or
primary language.
Arguments:
language:
The language to get the value in.
Returns:
The value in the current language, or
the primary language in case no language
was specified. | [
"Gets",
"the",
"underlying",
"value",
"in",
"the",
"specified",
"or",
"primary",
"language",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/value.py#L26-L42 | train | 202,150 |
SectorLabs/django-localized-fields | localized_fields/value.py | LocalizedValue.set | def set(self, language: str, value: str):
"""Sets the value in the specified language.
Arguments:
language:
The language to set the value in.
value:
The value to set.
"""
self[language] = value
self.__dict__.update(self)
return self | python | def set(self, language: str, value: str):
"""Sets the value in the specified language.
Arguments:
language:
The language to set the value in.
value:
The value to set.
"""
self[language] = value
self.__dict__.update(self)
return self | [
"def",
"set",
"(",
"self",
",",
"language",
":",
"str",
",",
"value",
":",
"str",
")",
":",
"self",
"[",
"language",
"]",
"=",
"value",
"self",
".",
"__dict__",
".",
"update",
"(",
"self",
")",
"return",
"self"
] | Sets the value in the specified language.
Arguments:
language:
The language to set the value in.
value:
The value to set. | [
"Sets",
"the",
"value",
"in",
"the",
"specified",
"language",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/value.py#L44-L57 | train | 202,151 |
SectorLabs/django-localized-fields | localized_fields/value.py | LocalizedValue.deconstruct | def deconstruct(self) -> dict:
"""Deconstructs this value into a primitive type.
Returns:
A dictionary with all the localized values
contained in this instance.
"""
path = 'localized_fields.value.%s' % self.__class__.__name__
return path, [self.__dict__], {} | python | def deconstruct(self) -> dict:
"""Deconstructs this value into a primitive type.
Returns:
A dictionary with all the localized values
contained in this instance.
"""
path = 'localized_fields.value.%s' % self.__class__.__name__
return path, [self.__dict__], {} | [
"def",
"deconstruct",
"(",
"self",
")",
"->",
"dict",
":",
"path",
"=",
"'localized_fields.value.%s'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"return",
"path",
",",
"[",
"self",
".",
"__dict__",
"]",
",",
"{",
"}"
] | Deconstructs this value into a primitive type.
Returns:
A dictionary with all the localized values
contained in this instance. | [
"Deconstructs",
"this",
"value",
"into",
"a",
"primitive",
"type",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/value.py#L59-L68 | train | 202,152 |
SectorLabs/django-localized-fields | localized_fields/value.py | LocalizedValue.translate | def translate(self) -> Optional[str]:
"""Gets the value in the current language or falls
back to the next language if there's no value in the
current language."""
fallbacks = getattr(settings, 'LOCALIZED_FIELDS_FALLBACKS', {})
language = translation.get_language() or settings.LANGUAGE_CODE
languages = fallbacks.get(language, [settings.LANGUAGE_CODE])[:]
languages.insert(0, language)
for lang_code in languages:
value = self.get(lang_code)
if value:
return value or None
return None | python | def translate(self) -> Optional[str]:
"""Gets the value in the current language or falls
back to the next language if there's no value in the
current language."""
fallbacks = getattr(settings, 'LOCALIZED_FIELDS_FALLBACKS', {})
language = translation.get_language() or settings.LANGUAGE_CODE
languages = fallbacks.get(language, [settings.LANGUAGE_CODE])[:]
languages.insert(0, language)
for lang_code in languages:
value = self.get(lang_code)
if value:
return value or None
return None | [
"def",
"translate",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"fallbacks",
"=",
"getattr",
"(",
"settings",
",",
"'LOCALIZED_FIELDS_FALLBACKS'",
",",
"{",
"}",
")",
"language",
"=",
"translation",
".",
"get_language",
"(",
")",
"or",
"setti... | Gets the value in the current language or falls
back to the next language if there's no value in the
current language. | [
"Gets",
"the",
"value",
"in",
"the",
"current",
"language",
"or",
"falls",
"back",
"to",
"the",
"next",
"language",
"if",
"there",
"s",
"no",
"value",
"in",
"the",
"current",
"language",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/value.py#L104-L120 | train | 202,153 |
SectorLabs/django-localized-fields | localized_fields/value.py | LocalizedIntegerValue.translate | def translate(self):
"""Gets the value in the current language, or
in the configured fallbck language."""
value = super().translate()
if value is None or (isinstance(value, str) and value.strip() == ''):
return None
return int(value) | python | def translate(self):
"""Gets the value in the current language, or
in the configured fallbck language."""
value = super().translate()
if value is None or (isinstance(value, str) and value.strip() == ''):
return None
return int(value) | [
"def",
"translate",
"(",
"self",
")",
":",
"value",
"=",
"super",
"(",
")",
".",
"translate",
"(",
")",
"if",
"value",
"is",
"None",
"or",
"(",
"isinstance",
"(",
"value",
",",
"str",
")",
"and",
"value",
".",
"strip",
"(",
")",
"==",
"''",
")",
... | Gets the value in the current language, or
in the configured fallbck language. | [
"Gets",
"the",
"value",
"in",
"the",
"current",
"language",
"or",
"in",
"the",
"configured",
"fallbck",
"language",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/value.py#L213-L221 | train | 202,154 |
SectorLabs/django-localized-fields | localized_fields/util.py | resolve_object_property | def resolve_object_property(obj, path: str):
"""Resolves the value of a property on an object.
Is able to resolve nested properties. For example,
a path can be specified:
'other.beer.name'
Raises:
AttributeError:
In case the property could not be resolved.
Returns:
The value of the specified property.
"""
value = obj
for path_part in path.split('.'):
value = getattr(value, path_part)
return value | python | def resolve_object_property(obj, path: str):
"""Resolves the value of a property on an object.
Is able to resolve nested properties. For example,
a path can be specified:
'other.beer.name'
Raises:
AttributeError:
In case the property could not be resolved.
Returns:
The value of the specified property.
"""
value = obj
for path_part in path.split('.'):
value = getattr(value, path_part)
return value | [
"def",
"resolve_object_property",
"(",
"obj",
",",
"path",
":",
"str",
")",
":",
"value",
"=",
"obj",
"for",
"path_part",
"in",
"path",
".",
"split",
"(",
"'.'",
")",
":",
"value",
"=",
"getattr",
"(",
"value",
",",
"path_part",
")",
"return",
"value"
... | Resolves the value of a property on an object.
Is able to resolve nested properties. For example,
a path can be specified:
'other.beer.name'
Raises:
AttributeError:
In case the property could not be resolved.
Returns:
The value of the specified property. | [
"Resolves",
"the",
"value",
"of",
"a",
"property",
"on",
"an",
"object",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/util.py#L24-L44 | train | 202,155 |
SectorLabs/django-localized-fields | localized_fields/widgets.py | LocalizedFieldWidget.decompress | def decompress(self, value: LocalizedValue) -> List[str]:
"""Decompresses the specified value so
it can be spread over the internal widgets.
Arguments:
value:
The :see:LocalizedValue to display in this
widget.
Returns:
All values to display in the inner widgets.
"""
result = []
for lang_code, _ in settings.LANGUAGES:
if value:
result.append(value.get(lang_code))
else:
result.append(None)
return result | python | def decompress(self, value: LocalizedValue) -> List[str]:
"""Decompresses the specified value so
it can be spread over the internal widgets.
Arguments:
value:
The :see:LocalizedValue to display in this
widget.
Returns:
All values to display in the inner widgets.
"""
result = []
for lang_code, _ in settings.LANGUAGES:
if value:
result.append(value.get(lang_code))
else:
result.append(None)
return result | [
"def",
"decompress",
"(",
"self",
",",
"value",
":",
"LocalizedValue",
")",
"->",
"List",
"[",
"str",
"]",
":",
"result",
"=",
"[",
"]",
"for",
"lang_code",
",",
"_",
"in",
"settings",
".",
"LANGUAGES",
":",
"if",
"value",
":",
"result",
".",
"append... | Decompresses the specified value so
it can be spread over the internal widgets.
Arguments:
value:
The :see:LocalizedValue to display in this
widget.
Returns:
All values to display in the inner widgets. | [
"Decompresses",
"the",
"specified",
"value",
"so",
"it",
"can",
"be",
"spread",
"over",
"the",
"internal",
"widgets",
"."
] | f0ac0f7f2503317fde5d75ba8481e34db83512bd | https://github.com/SectorLabs/django-localized-fields/blob/f0ac0f7f2503317fde5d75ba8481e34db83512bd/localized_fields/widgets.py#L32-L52 | train | 202,156 |
guyzmo/git-repo | git_repo/services/service.py | register_target | def register_target(repo_cmd, repo_service):
"""Decorator to register a class with an repo_service"""
def decorate(klass):
log.debug('Loading service module class: {}'.format(klass.__name__) )
klass.command = repo_cmd
klass.name = repo_service
RepositoryService.service_map[repo_service] = klass
RepositoryService.command_map[repo_cmd] = repo_service
return klass
return decorate | python | def register_target(repo_cmd, repo_service):
"""Decorator to register a class with an repo_service"""
def decorate(klass):
log.debug('Loading service module class: {}'.format(klass.__name__) )
klass.command = repo_cmd
klass.name = repo_service
RepositoryService.service_map[repo_service] = klass
RepositoryService.command_map[repo_cmd] = repo_service
return klass
return decorate | [
"def",
"register_target",
"(",
"repo_cmd",
",",
"repo_service",
")",
":",
"def",
"decorate",
"(",
"klass",
")",
":",
"log",
".",
"debug",
"(",
"'Loading service module class: {}'",
".",
"format",
"(",
"klass",
".",
"__name__",
")",
")",
"klass",
".",
"comman... | Decorator to register a class with an repo_service | [
"Decorator",
"to",
"register",
"a",
"class",
"with",
"an",
"repo_service"
] | 2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b | https://github.com/guyzmo/git-repo/blob/2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b/git_repo/services/service.py#L57-L66 | train | 202,157 |
guyzmo/git-repo | git_repo/services/service.py | RepositoryService.get_service | def get_service(cls, repository, command):
'''Accessor for a repository given a command
:param repository: git-python repository instance
:param command: aliased name of the service
:return: instance for using the service
'''
if not repository:
config = git_config.GitConfigParser(cls.get_config_path())
else:
config = repository.config_reader()
target = cls.command_map.get(command, command)
conf_section = list(filter(lambda n: 'gitrepo' in n and target in n, config.sections()))
http_section = [config._sections[scheme] for scheme in ('http', 'https') if scheme in config.sections()]
# check configuration constraints
if len(conf_section) == 0:
if not target:
raise ValueError('Service {} unknown'.format(target))
else:
config = dict()
elif len(conf_section) > 1:
raise ValueError('Too many configurations for service {}'.format(target))
# get configuration section as a dict
else:
config = config._sections[conf_section[0]]
if target in cls.service_map:
service = cls.service_map.get(target, cls)
service.name = target
else:
if 'type' not in config:
raise ValueError('Missing service type for custom service.')
if config['type'] not in cls.service_map:
raise ValueError('Service type {} does not exists.'.format(config['type']))
service = cls.service_map.get(config['type'], cls)
cls._current = service(repository, config, http_section)
return cls._current | python | def get_service(cls, repository, command):
'''Accessor for a repository given a command
:param repository: git-python repository instance
:param command: aliased name of the service
:return: instance for using the service
'''
if not repository:
config = git_config.GitConfigParser(cls.get_config_path())
else:
config = repository.config_reader()
target = cls.command_map.get(command, command)
conf_section = list(filter(lambda n: 'gitrepo' in n and target in n, config.sections()))
http_section = [config._sections[scheme] for scheme in ('http', 'https') if scheme in config.sections()]
# check configuration constraints
if len(conf_section) == 0:
if not target:
raise ValueError('Service {} unknown'.format(target))
else:
config = dict()
elif len(conf_section) > 1:
raise ValueError('Too many configurations for service {}'.format(target))
# get configuration section as a dict
else:
config = config._sections[conf_section[0]]
if target in cls.service_map:
service = cls.service_map.get(target, cls)
service.name = target
else:
if 'type' not in config:
raise ValueError('Missing service type for custom service.')
if config['type'] not in cls.service_map:
raise ValueError('Service type {} does not exists.'.format(config['type']))
service = cls.service_map.get(config['type'], cls)
cls._current = service(repository, config, http_section)
return cls._current | [
"def",
"get_service",
"(",
"cls",
",",
"repository",
",",
"command",
")",
":",
"if",
"not",
"repository",
":",
"config",
"=",
"git_config",
".",
"GitConfigParser",
"(",
"cls",
".",
"get_config_path",
"(",
")",
")",
"else",
":",
"config",
"=",
"repository",... | Accessor for a repository given a command
:param repository: git-python repository instance
:param command: aliased name of the service
:return: instance for using the service | [
"Accessor",
"for",
"a",
"repository",
"given",
"a",
"command"
] | 2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b | https://github.com/guyzmo/git-repo/blob/2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b/git_repo/services/service.py#L151-L190 | train | 202,158 |
guyzmo/git-repo | git_repo/services/service.py | RepositoryService.format_path | def format_path(self, repository, namespace=None, rw=False):
'''format the repository's URL
:param repository: name of the repository
:param namespace: namespace of the repository
:param rw: return a git+ssh URL if true, an https URL otherwise
:return: the full URI of the repository ready to use as remote
if namespace is not given, repository is expected to be of format
`<namespace>/<repository>`.
'''
repo = repository
if namespace:
repo = '{}/{}'.format(namespace, repository)
if not rw and repo.count('/') >= self._min_nested_namespaces:
return '{}/{}'.format(self.url_ro, repo)
elif rw and repo.count('/') >= self._min_nested_namespaces:
if self.url_rw.startswith('ssh://'):
return '{}/{}'.format(self.url_rw, repo)
else:
return '{}:{}'.format(self.url_rw, repo)
else:
raise ArgumentError("Cannot tell how to handle this url: `{}/{}`!".format(namespace, repo)) | python | def format_path(self, repository, namespace=None, rw=False):
'''format the repository's URL
:param repository: name of the repository
:param namespace: namespace of the repository
:param rw: return a git+ssh URL if true, an https URL otherwise
:return: the full URI of the repository ready to use as remote
if namespace is not given, repository is expected to be of format
`<namespace>/<repository>`.
'''
repo = repository
if namespace:
repo = '{}/{}'.format(namespace, repository)
if not rw and repo.count('/') >= self._min_nested_namespaces:
return '{}/{}'.format(self.url_ro, repo)
elif rw and repo.count('/') >= self._min_nested_namespaces:
if self.url_rw.startswith('ssh://'):
return '{}/{}'.format(self.url_rw, repo)
else:
return '{}:{}'.format(self.url_rw, repo)
else:
raise ArgumentError("Cannot tell how to handle this url: `{}/{}`!".format(namespace, repo)) | [
"def",
"format_path",
"(",
"self",
",",
"repository",
",",
"namespace",
"=",
"None",
",",
"rw",
"=",
"False",
")",
":",
"repo",
"=",
"repository",
"if",
"namespace",
":",
"repo",
"=",
"'{}/{}'",
".",
"format",
"(",
"namespace",
",",
"repository",
")",
... | format the repository's URL
:param repository: name of the repository
:param namespace: namespace of the repository
:param rw: return a git+ssh URL if true, an https URL otherwise
:return: the full URI of the repository ready to use as remote
if namespace is not given, repository is expected to be of format
`<namespace>/<repository>`. | [
"format",
"the",
"repository",
"s",
"URL"
] | 2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b | https://github.com/guyzmo/git-repo/blob/2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b/git_repo/services/service.py#L287-L310 | train | 202,159 |
guyzmo/git-repo | git_repo/services/service.py | RepositoryService.open | def open(self, user=None, repo=None):
'''Open the URL of a repository in the user's browser'''
webbrowser.open(self.format_path(repo, namespace=user, rw=False)) | python | def open(self, user=None, repo=None):
'''Open the URL of a repository in the user's browser'''
webbrowser.open(self.format_path(repo, namespace=user, rw=False)) | [
"def",
"open",
"(",
"self",
",",
"user",
"=",
"None",
",",
"repo",
"=",
"None",
")",
":",
"webbrowser",
".",
"open",
"(",
"self",
".",
"format_path",
"(",
"repo",
",",
"namespace",
"=",
"user",
",",
"rw",
"=",
"False",
")",
")"
] | Open the URL of a repository in the user's browser | [
"Open",
"the",
"URL",
"of",
"a",
"repository",
"in",
"the",
"user",
"s",
"browser"
] | 2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b | https://github.com/guyzmo/git-repo/blob/2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b/git_repo/services/service.py#L512-L514 | train | 202,160 |
guyzmo/git-repo | git_repo/services/service.py | RepositoryService.request_fetch | def request_fetch(self, user, repo, request, pull=False, force=False): #pragma: no cover
'''Fetches given request as a branch, and switch if pull is true
:param repo: name of the repository to create
Meant to be implemented by subclasses
'''
raise NotImplementedError | python | def request_fetch(self, user, repo, request, pull=False, force=False): #pragma: no cover
'''Fetches given request as a branch, and switch if pull is true
:param repo: name of the repository to create
Meant to be implemented by subclasses
'''
raise NotImplementedError | [
"def",
"request_fetch",
"(",
"self",
",",
"user",
",",
"repo",
",",
"request",
",",
"pull",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"#pragma: no cover",
"raise",
"NotImplementedError"
] | Fetches given request as a branch, and switch if pull is true
:param repo: name of the repository to create
Meant to be implemented by subclasses | [
"Fetches",
"given",
"request",
"as",
"a",
"branch",
"and",
"switch",
"if",
"pull",
"is",
"true"
] | 2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b | https://github.com/guyzmo/git-repo/blob/2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b/git_repo/services/service.py#L606-L613 | train | 202,161 |
guyzmo/git-repo | git_repo/kwargparse.py | register_action | def register_action(*args, **kwarg):
'''
Decorator for an action, the arguments order is not relevant, but it's best
to use the same order as in the docopt for clarity.
'''
def decorator(fun):
KeywordArgumentParser._action_dict[frozenset(args)] = fun
return fun
return decorator | python | def register_action(*args, **kwarg):
'''
Decorator for an action, the arguments order is not relevant, but it's best
to use the same order as in the docopt for clarity.
'''
def decorator(fun):
KeywordArgumentParser._action_dict[frozenset(args)] = fun
return fun
return decorator | [
"def",
"register_action",
"(",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
":",
"def",
"decorator",
"(",
"fun",
")",
":",
"KeywordArgumentParser",
".",
"_action_dict",
"[",
"frozenset",
"(",
"args",
")",
"]",
"=",
"fun",
"return",
"fun",
"return",
"decorat... | Decorator for an action, the arguments order is not relevant, but it's best
to use the same order as in the docopt for clarity. | [
"Decorator",
"for",
"an",
"action",
"the",
"arguments",
"order",
"is",
"not",
"relevant",
"but",
"it",
"s",
"best",
"to",
"use",
"the",
"same",
"order",
"as",
"in",
"the",
"docopt",
"for",
"clarity",
"."
] | 2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b | https://github.com/guyzmo/git-repo/blob/2974c3f52bc64fa8a467ac2b0e9a485ba7ed333b/git_repo/kwargparse.py#L89-L97 | train | 202,162 |
LEW21/pydbus | pydbus/proxy.py | ProxyMixin.get | def get(self, bus_name, object_path=None, **kwargs):
"""Get a remote object.
Parameters
----------
bus_name : string
Name of the service that exposes this object.
You may start with "." - then org.freedesktop will be automatically prepended.
object_path : string, optional
Path of the object. If not provided, bus_name translated to path format is used.
Returns
-------
ProxyObject implementing all the Interfaces exposed by the remote object.
Note that it inherits from multiple Interfaces, so the method you want to use
may be shadowed by another one, eg. from a newer version of the interface.
Therefore, to interact with only a single interface, use:
>>> bus.get("org.freedesktop.systemd1")["org.freedesktop.systemd1.Manager"]
or simply
>>> bus.get(".systemd1")[".Manager"]
which will give you access to the one specific interface.
"""
# Python 2 sux
for kwarg in kwargs:
if kwarg not in ("timeout",):
raise TypeError(self.__qualname__ + " got an unexpected keyword argument '{}'".format(kwarg))
timeout = kwargs.get("timeout", None)
bus_name = auto_bus_name(bus_name)
object_path = auto_object_path(bus_name, object_path)
ret = self.con.call_sync(
bus_name, object_path,
'org.freedesktop.DBus.Introspectable', "Introspect", None, GLib.VariantType.new("(s)"),
0, timeout_to_glib(timeout), None)
if not ret:
raise KeyError("no such object; you might need to pass object path as the 2nd argument for get()")
xml, = ret.unpack()
try:
introspection = ET.fromstring(xml)
except:
raise KeyError("object provides invalid introspection XML")
return CompositeInterface(introspection)(self, bus_name, object_path) | python | def get(self, bus_name, object_path=None, **kwargs):
"""Get a remote object.
Parameters
----------
bus_name : string
Name of the service that exposes this object.
You may start with "." - then org.freedesktop will be automatically prepended.
object_path : string, optional
Path of the object. If not provided, bus_name translated to path format is used.
Returns
-------
ProxyObject implementing all the Interfaces exposed by the remote object.
Note that it inherits from multiple Interfaces, so the method you want to use
may be shadowed by another one, eg. from a newer version of the interface.
Therefore, to interact with only a single interface, use:
>>> bus.get("org.freedesktop.systemd1")["org.freedesktop.systemd1.Manager"]
or simply
>>> bus.get(".systemd1")[".Manager"]
which will give you access to the one specific interface.
"""
# Python 2 sux
for kwarg in kwargs:
if kwarg not in ("timeout",):
raise TypeError(self.__qualname__ + " got an unexpected keyword argument '{}'".format(kwarg))
timeout = kwargs.get("timeout", None)
bus_name = auto_bus_name(bus_name)
object_path = auto_object_path(bus_name, object_path)
ret = self.con.call_sync(
bus_name, object_path,
'org.freedesktop.DBus.Introspectable', "Introspect", None, GLib.VariantType.new("(s)"),
0, timeout_to_glib(timeout), None)
if not ret:
raise KeyError("no such object; you might need to pass object path as the 2nd argument for get()")
xml, = ret.unpack()
try:
introspection = ET.fromstring(xml)
except:
raise KeyError("object provides invalid introspection XML")
return CompositeInterface(introspection)(self, bus_name, object_path) | [
"def",
"get",
"(",
"self",
",",
"bus_name",
",",
"object_path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Python 2 sux",
"for",
"kwarg",
"in",
"kwargs",
":",
"if",
"kwarg",
"not",
"in",
"(",
"\"timeout\"",
",",
")",
":",
"raise",
"TypeError",
... | Get a remote object.
Parameters
----------
bus_name : string
Name of the service that exposes this object.
You may start with "." - then org.freedesktop will be automatically prepended.
object_path : string, optional
Path of the object. If not provided, bus_name translated to path format is used.
Returns
-------
ProxyObject implementing all the Interfaces exposed by the remote object.
Note that it inherits from multiple Interfaces, so the method you want to use
may be shadowed by another one, eg. from a newer version of the interface.
Therefore, to interact with only a single interface, use:
>>> bus.get("org.freedesktop.systemd1")["org.freedesktop.systemd1.Manager"]
or simply
>>> bus.get(".systemd1")[".Manager"]
which will give you access to the one specific interface. | [
"Get",
"a",
"remote",
"object",
"."
] | cc407c8b1d25b7e28a6d661a29f9e661b1c9b964 | https://github.com/LEW21/pydbus/blob/cc407c8b1d25b7e28a6d661a29f9e661b1c9b964/pydbus/proxy.py#L13-L59 | train | 202,163 |
LEW21/pydbus | pydbus/request_name.py | RequestNameMixin.request_name | def request_name(self, name, allow_replacement=True, replace=False):
"""Aquires a bus name.
Returns
-------
NameOwner
An object you can use as a context manager to unown the name later.
"""
return NameOwner(self, name, allow_replacement, replace) | python | def request_name(self, name, allow_replacement=True, replace=False):
"""Aquires a bus name.
Returns
-------
NameOwner
An object you can use as a context manager to unown the name later.
"""
return NameOwner(self, name, allow_replacement, replace) | [
"def",
"request_name",
"(",
"self",
",",
"name",
",",
"allow_replacement",
"=",
"True",
",",
"replace",
"=",
"False",
")",
":",
"return",
"NameOwner",
"(",
"self",
",",
"name",
",",
"allow_replacement",
",",
"replace",
")"
] | Aquires a bus name.
Returns
-------
NameOwner
An object you can use as a context manager to unown the name later. | [
"Aquires",
"a",
"bus",
"name",
"."
] | cc407c8b1d25b7e28a6d661a29f9e661b1c9b964 | https://github.com/LEW21/pydbus/blob/cc407c8b1d25b7e28a6d661a29f9e661b1c9b964/pydbus/request_name.py#L21-L29 | train | 202,164 |
LEW21/pydbus | pydbus/subscription.py | SubscriptionMixin.subscribe | def subscribe(self, sender=None, iface=None, signal=None, object=None, arg0=None, flags=0, signal_fired=None):
"""Subscribes to matching signals.
Subscribes to signals on connection and invokes signal_fired callback
whenever the signal is received.
To receive signal_fired callback, you need an event loop.
https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop
Parameters
----------
sender : string, optional
Sender name to match on (unique or well-known name) or None to listen from all senders.
iface : string, optional
Interface name to match on or None to match on all interfaces.
signal : string, optional
Signal name to match on or None to match on all signals.
object : string, optional
Object path to match on or None to match on all object paths.
arg0 : string, optional
Contents of first string argument to match on or None to match on all kinds of arguments.
flags : SubscriptionFlags, optional
signal_fired : callable, optional
Invoked when there is a signal matching the requested data.
Parameters: sender, object, iface, signal, params
Returns
-------
Subscription
An object you can use as a context manager to unsubscribe from the signal later.
See Also
--------
See https://developer.gnome.org/gio/2.44/GDBusConnection.html#g-dbus-connection-signal-subscribe
for more information.
"""
callback = (lambda con, sender, object, iface, signal, params: signal_fired(sender, object, iface, signal, params.unpack())) if signal_fired is not None else lambda *args: None
return Subscription(self.con, sender, iface, signal, object, arg0, flags, callback) | python | def subscribe(self, sender=None, iface=None, signal=None, object=None, arg0=None, flags=0, signal_fired=None):
"""Subscribes to matching signals.
Subscribes to signals on connection and invokes signal_fired callback
whenever the signal is received.
To receive signal_fired callback, you need an event loop.
https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop
Parameters
----------
sender : string, optional
Sender name to match on (unique or well-known name) or None to listen from all senders.
iface : string, optional
Interface name to match on or None to match on all interfaces.
signal : string, optional
Signal name to match on or None to match on all signals.
object : string, optional
Object path to match on or None to match on all object paths.
arg0 : string, optional
Contents of first string argument to match on or None to match on all kinds of arguments.
flags : SubscriptionFlags, optional
signal_fired : callable, optional
Invoked when there is a signal matching the requested data.
Parameters: sender, object, iface, signal, params
Returns
-------
Subscription
An object you can use as a context manager to unsubscribe from the signal later.
See Also
--------
See https://developer.gnome.org/gio/2.44/GDBusConnection.html#g-dbus-connection-signal-subscribe
for more information.
"""
callback = (lambda con, sender, object, iface, signal, params: signal_fired(sender, object, iface, signal, params.unpack())) if signal_fired is not None else lambda *args: None
return Subscription(self.con, sender, iface, signal, object, arg0, flags, callback) | [
"def",
"subscribe",
"(",
"self",
",",
"sender",
"=",
"None",
",",
"iface",
"=",
"None",
",",
"signal",
"=",
"None",
",",
"object",
"=",
"None",
",",
"arg0",
"=",
"None",
",",
"flags",
"=",
"0",
",",
"signal_fired",
"=",
"None",
")",
":",
"callback"... | Subscribes to matching signals.
Subscribes to signals on connection and invokes signal_fired callback
whenever the signal is received.
To receive signal_fired callback, you need an event loop.
https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop
Parameters
----------
sender : string, optional
Sender name to match on (unique or well-known name) or None to listen from all senders.
iface : string, optional
Interface name to match on or None to match on all interfaces.
signal : string, optional
Signal name to match on or None to match on all signals.
object : string, optional
Object path to match on or None to match on all object paths.
arg0 : string, optional
Contents of first string argument to match on or None to match on all kinds of arguments.
flags : SubscriptionFlags, optional
signal_fired : callable, optional
Invoked when there is a signal matching the requested data.
Parameters: sender, object, iface, signal, params
Returns
-------
Subscription
An object you can use as a context manager to unsubscribe from the signal later.
See Also
--------
See https://developer.gnome.org/gio/2.44/GDBusConnection.html#g-dbus-connection-signal-subscribe
for more information. | [
"Subscribes",
"to",
"matching",
"signals",
"."
] | cc407c8b1d25b7e28a6d661a29f9e661b1c9b964 | https://github.com/LEW21/pydbus/blob/cc407c8b1d25b7e28a6d661a29f9e661b1c9b964/pydbus/subscription.py#L16-L53 | train | 202,165 |
LEW21/pydbus | pydbus/bus_names.py | WatchMixin.watch_name | def watch_name(self, name, flags=0, name_appeared=None, name_vanished=None):
"""Asynchronously watches a bus name.
Starts watching name on the bus specified by bus_type and calls
name_appeared and name_vanished when the name is known to have a owner
respectively known to lose its owner.
To receive name_appeared and name_vanished callbacks, you need an event loop.
https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop
Parameters
----------
name : string
Bus name to watch
flags : NameWatcherFlags, optional
name_appeared : callable, optional
Invoked when name is known to exist
Called as name_appeared(name_owner).
name_vanished : callable, optional
Invoked when name is known to not exist
Returns
-------
NameWatcher
An object you can use as a context manager to unwatch the name later.
See Also
--------
See https://developer.gnome.org/gio/2.44/gio-Watching-Bus-Names.html#g-bus-watch-name
for more information.
"""
name_appeared_handler = (lambda con, name, name_owner: name_appeared(name_owner)) if name_appeared is not None else None
name_vanished_handler = (lambda con, name: name_vanished()) if name_vanished is not None else None
return NameWatcher(self.con, name, flags, name_appeared_handler, name_vanished_handler) | python | def watch_name(self, name, flags=0, name_appeared=None, name_vanished=None):
"""Asynchronously watches a bus name.
Starts watching name on the bus specified by bus_type and calls
name_appeared and name_vanished when the name is known to have a owner
respectively known to lose its owner.
To receive name_appeared and name_vanished callbacks, you need an event loop.
https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop
Parameters
----------
name : string
Bus name to watch
flags : NameWatcherFlags, optional
name_appeared : callable, optional
Invoked when name is known to exist
Called as name_appeared(name_owner).
name_vanished : callable, optional
Invoked when name is known to not exist
Returns
-------
NameWatcher
An object you can use as a context manager to unwatch the name later.
See Also
--------
See https://developer.gnome.org/gio/2.44/gio-Watching-Bus-Names.html#g-bus-watch-name
for more information.
"""
name_appeared_handler = (lambda con, name, name_owner: name_appeared(name_owner)) if name_appeared is not None else None
name_vanished_handler = (lambda con, name: name_vanished()) if name_vanished is not None else None
return NameWatcher(self.con, name, flags, name_appeared_handler, name_vanished_handler) | [
"def",
"watch_name",
"(",
"self",
",",
"name",
",",
"flags",
"=",
"0",
",",
"name_appeared",
"=",
"None",
",",
"name_vanished",
"=",
"None",
")",
":",
"name_appeared_handler",
"=",
"(",
"lambda",
"con",
",",
"name",
",",
"name_owner",
":",
"name_appeared",... | Asynchronously watches a bus name.
Starts watching name on the bus specified by bus_type and calls
name_appeared and name_vanished when the name is known to have a owner
respectively known to lose its owner.
To receive name_appeared and name_vanished callbacks, you need an event loop.
https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop
Parameters
----------
name : string
Bus name to watch
flags : NameWatcherFlags, optional
name_appeared : callable, optional
Invoked when name is known to exist
Called as name_appeared(name_owner).
name_vanished : callable, optional
Invoked when name is known to not exist
Returns
-------
NameWatcher
An object you can use as a context manager to unwatch the name later.
See Also
--------
See https://developer.gnome.org/gio/2.44/gio-Watching-Bus-Names.html#g-bus-watch-name
for more information. | [
"Asynchronously",
"watches",
"a",
"bus",
"name",
"."
] | cc407c8b1d25b7e28a6d661a29f9e661b1c9b964 | https://github.com/LEW21/pydbus/blob/cc407c8b1d25b7e28a6d661a29f9e661b1c9b964/pydbus/bus_names.py#L64-L97 | train | 202,166 |
ranaroussi/fix-yahoo-finance | fix_yahoo_finance/__init__.py | Ticker.info | def info(self):
""" retreive metadata and currenct price data """
url = "{}/v7/finance/quote?symbols={}".format(
self._base_url, self.ticker)
r = _requests.get(url=url).json()["quoteResponse"]["result"]
if len(r) > 0:
return r[0]
return {} | python | def info(self):
""" retreive metadata and currenct price data """
url = "{}/v7/finance/quote?symbols={}".format(
self._base_url, self.ticker)
r = _requests.get(url=url).json()["quoteResponse"]["result"]
if len(r) > 0:
return r[0]
return {} | [
"def",
"info",
"(",
"self",
")",
":",
"url",
"=",
"\"{}/v7/finance/quote?symbols={}\"",
".",
"format",
"(",
"self",
".",
"_base_url",
",",
"self",
".",
"ticker",
")",
"r",
"=",
"_requests",
".",
"get",
"(",
"url",
"=",
"url",
")",
".",
"json",
"(",
"... | retreive metadata and currenct price data | [
"retreive",
"metadata",
"and",
"currenct",
"price",
"data"
] | b34950075009588b5bba6cdd26275b7795108b01 | https://github.com/ranaroussi/fix-yahoo-finance/blob/b34950075009588b5bba6cdd26275b7795108b01/fix_yahoo_finance/__init__.py#L71-L78 | train | 202,167 |
jupyterhub/jupyter-server-proxy | jupyter_server_proxy/websocket.py | pingable_ws_connect | def pingable_ws_connect(request=None, on_message_callback=None,
on_ping_callback=None):
"""
A variation on websocket_connect that returns a PingableWSClientConnection
with on_ping_callback.
"""
# Copy and convert the headers dict/object (see comments in
# AsyncHTTPClient.fetch)
request.headers = httputil.HTTPHeaders(request.headers)
request = httpclient._RequestProxy(
request, httpclient.HTTPRequest._DEFAULTS)
# for tornado 4.5.x compatibility
if version_info[0] == 4:
conn = PingableWSClientConnection(io_loop=ioloop.IOLoop.current(),
request=request,
on_message_callback=on_message_callback,
on_ping_callback=on_ping_callback)
else:
conn = PingableWSClientConnection(request=request,
on_message_callback=on_message_callback,
on_ping_callback=on_ping_callback,
max_message_size=getattr(websocket, '_default_max_message_size', 10 * 1024 * 1024))
return conn.connect_future | python | def pingable_ws_connect(request=None, on_message_callback=None,
on_ping_callback=None):
"""
A variation on websocket_connect that returns a PingableWSClientConnection
with on_ping_callback.
"""
# Copy and convert the headers dict/object (see comments in
# AsyncHTTPClient.fetch)
request.headers = httputil.HTTPHeaders(request.headers)
request = httpclient._RequestProxy(
request, httpclient.HTTPRequest._DEFAULTS)
# for tornado 4.5.x compatibility
if version_info[0] == 4:
conn = PingableWSClientConnection(io_loop=ioloop.IOLoop.current(),
request=request,
on_message_callback=on_message_callback,
on_ping_callback=on_ping_callback)
else:
conn = PingableWSClientConnection(request=request,
on_message_callback=on_message_callback,
on_ping_callback=on_ping_callback,
max_message_size=getattr(websocket, '_default_max_message_size', 10 * 1024 * 1024))
return conn.connect_future | [
"def",
"pingable_ws_connect",
"(",
"request",
"=",
"None",
",",
"on_message_callback",
"=",
"None",
",",
"on_ping_callback",
"=",
"None",
")",
":",
"# Copy and convert the headers dict/object (see comments in",
"# AsyncHTTPClient.fetch)",
"request",
".",
"headers",
"=",
"... | A variation on websocket_connect that returns a PingableWSClientConnection
with on_ping_callback. | [
"A",
"variation",
"on",
"websocket_connect",
"that",
"returns",
"a",
"PingableWSClientConnection",
"with",
"on_ping_callback",
"."
] | f12a090babe3c6e37a777b7e54c7b415de5c7e18 | https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/jupyter_server_proxy/websocket.py#L39-L63 | train | 202,168 |
jupyterhub/jupyter-server-proxy | jupyter_server_proxy/utils.py | call_with_asked_args | def call_with_asked_args(callback, args):
"""
Call callback with only the args it wants from args
Example
>>> def cb(a):
... return a * 5
>>> print(call_with_asked_args(cb, {'a': 4, 'b': 8}))
20
"""
# FIXME: support default args
# FIXME: support kwargs
# co_varnames contains both args and local variables, in order.
# We only pick the local variables
asked_arg_names = callback.__code__.co_varnames[:callback.__code__.co_argcount]
asked_arg_values = []
missing_args = []
for asked_arg_name in asked_arg_names:
if asked_arg_name in args:
asked_arg_values.append(args[asked_arg_name])
else:
missing_args.append(asked_arg_name)
if missing_args:
raise TypeError(
'{}() missing required positional argument: {}'.format(
callback.__code__.co_name,
', '.join(missing_args)
)
)
return callback(*asked_arg_values) | python | def call_with_asked_args(callback, args):
"""
Call callback with only the args it wants from args
Example
>>> def cb(a):
... return a * 5
>>> print(call_with_asked_args(cb, {'a': 4, 'b': 8}))
20
"""
# FIXME: support default args
# FIXME: support kwargs
# co_varnames contains both args and local variables, in order.
# We only pick the local variables
asked_arg_names = callback.__code__.co_varnames[:callback.__code__.co_argcount]
asked_arg_values = []
missing_args = []
for asked_arg_name in asked_arg_names:
if asked_arg_name in args:
asked_arg_values.append(args[asked_arg_name])
else:
missing_args.append(asked_arg_name)
if missing_args:
raise TypeError(
'{}() missing required positional argument: {}'.format(
callback.__code__.co_name,
', '.join(missing_args)
)
)
return callback(*asked_arg_values) | [
"def",
"call_with_asked_args",
"(",
"callback",
",",
"args",
")",
":",
"# FIXME: support default args",
"# FIXME: support kwargs",
"# co_varnames contains both args and local variables, in order. ",
"# We only pick the local variables",
"asked_arg_names",
"=",
"callback",
".",
"__cod... | Call callback with only the args it wants from args
Example
>>> def cb(a):
... return a * 5
>>> print(call_with_asked_args(cb, {'a': 4, 'b': 8}))
20 | [
"Call",
"callback",
"with",
"only",
"the",
"args",
"it",
"wants",
"from",
"args"
] | f12a090babe3c6e37a777b7e54c7b415de5c7e18 | https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/jupyter_server_proxy/utils.py#L1-L31 | train | 202,169 |
jupyterhub/jupyter-server-proxy | jupyter_server_proxy/config.py | _make_serverproxy_handler | def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port):
"""
Create a SuperviseAndProxyHandler subclass with given parameters
"""
# FIXME: Set 'name' properly
class _Proxy(SuperviseAndProxyHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = name
self.proxy_base = name
self.absolute_url = absolute_url
self.requested_port = port
@property
def process_args(self):
return {
'port': self.port,
'base_url': self.base_url,
}
def _render_template(self, value):
args = self.process_args
if type(value) is str:
return value.format(**args)
elif type(value) is list:
return [self._render_template(v) for v in value]
elif type(value) is dict:
return {
self._render_template(k): self._render_template(v)
for k, v in value.items()
}
else:
raise ValueError('Value of unrecognized type {}'.format(type(value)))
def get_cmd(self):
if callable(command):
return self._render_template(call_with_asked_args(command, self.process_args))
else:
return self._render_template(command)
def get_env(self):
if callable(environment):
return self._render_template(call_with_asked_args(environment, self.process_args))
else:
return self._render_template(environment)
def get_timeout(self):
return timeout
return _Proxy | python | def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port):
"""
Create a SuperviseAndProxyHandler subclass with given parameters
"""
# FIXME: Set 'name' properly
class _Proxy(SuperviseAndProxyHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = name
self.proxy_base = name
self.absolute_url = absolute_url
self.requested_port = port
@property
def process_args(self):
return {
'port': self.port,
'base_url': self.base_url,
}
def _render_template(self, value):
args = self.process_args
if type(value) is str:
return value.format(**args)
elif type(value) is list:
return [self._render_template(v) for v in value]
elif type(value) is dict:
return {
self._render_template(k): self._render_template(v)
for k, v in value.items()
}
else:
raise ValueError('Value of unrecognized type {}'.format(type(value)))
def get_cmd(self):
if callable(command):
return self._render_template(call_with_asked_args(command, self.process_args))
else:
return self._render_template(command)
def get_env(self):
if callable(environment):
return self._render_template(call_with_asked_args(environment, self.process_args))
else:
return self._render_template(environment)
def get_timeout(self):
return timeout
return _Proxy | [
"def",
"_make_serverproxy_handler",
"(",
"name",
",",
"command",
",",
"environment",
",",
"timeout",
",",
"absolute_url",
",",
"port",
")",
":",
"# FIXME: Set 'name' properly",
"class",
"_Proxy",
"(",
"SuperviseAndProxyHandler",
")",
":",
"def",
"__init__",
"(",
"... | Create a SuperviseAndProxyHandler subclass with given parameters | [
"Create",
"a",
"SuperviseAndProxyHandler",
"subclass",
"with",
"given",
"parameters"
] | f12a090babe3c6e37a777b7e54c7b415de5c7e18 | https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/jupyter_server_proxy/config.py#L12-L61 | train | 202,170 |
jupyterhub/jupyter-server-proxy | jupyter_server_proxy/config.py | make_handlers | def make_handlers(base_url, server_processes):
"""
Get tornado handlers for registered server_processes
"""
handlers = []
for sp in server_processes:
handler = _make_serverproxy_handler(
sp.name,
sp.command,
sp.environment,
sp.timeout,
sp.absolute_url,
sp.port,
)
handlers.append((
ujoin(base_url, sp.name, r'(.*)'), handler, dict(state={}),
))
handlers.append((
ujoin(base_url, sp.name), AddSlashHandler
))
return handlers | python | def make_handlers(base_url, server_processes):
"""
Get tornado handlers for registered server_processes
"""
handlers = []
for sp in server_processes:
handler = _make_serverproxy_handler(
sp.name,
sp.command,
sp.environment,
sp.timeout,
sp.absolute_url,
sp.port,
)
handlers.append((
ujoin(base_url, sp.name, r'(.*)'), handler, dict(state={}),
))
handlers.append((
ujoin(base_url, sp.name), AddSlashHandler
))
return handlers | [
"def",
"make_handlers",
"(",
"base_url",
",",
"server_processes",
")",
":",
"handlers",
"=",
"[",
"]",
"for",
"sp",
"in",
"server_processes",
":",
"handler",
"=",
"_make_serverproxy_handler",
"(",
"sp",
".",
"name",
",",
"sp",
".",
"command",
",",
"sp",
".... | Get tornado handlers for registered server_processes | [
"Get",
"tornado",
"handlers",
"for",
"registered",
"server_processes"
] | f12a090babe3c6e37a777b7e54c7b415de5c7e18 | https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/jupyter_server_proxy/config.py#L72-L92 | train | 202,171 |
jupyterhub/jupyter-server-proxy | jupyter_server_proxy/handlers.py | LocalProxyHandler.open | async def open(self, port, proxied_path=''):
"""
Called when a client opens a websocket connection.
We establish a websocket connection to the proxied backend &
set up a callback to relay messages through.
"""
if not proxied_path.startswith('/'):
proxied_path = '/' + proxied_path
client_uri = self.get_client_uri('ws', port, proxied_path)
headers = self.request.headers
def message_cb(message):
"""
Callback when the backend sends messages to us
We just pass it back to the frontend
"""
# Websockets support both string (utf-8) and binary data, so let's
# make sure we signal that appropriately when proxying
self._record_activity()
if message is None:
self.close()
else:
self.write_message(message, binary=isinstance(message, bytes))
def ping_cb(data):
"""
Callback when the backend sends pings to us.
We just pass it back to the frontend.
"""
self._record_activity()
self.ping(data)
async def start_websocket_connection():
self.log.info('Trying to establish websocket connection to {}'.format(client_uri))
self._record_activity()
request = httpclient.HTTPRequest(url=client_uri, headers=headers)
self.ws = await pingable_ws_connect(request=request,
on_message_callback=message_cb, on_ping_callback=ping_cb)
self._record_activity()
self.log.info('Websocket connection established to {}'.format(client_uri))
ioloop.IOLoop.current().add_callback(start_websocket_connection) | python | async def open(self, port, proxied_path=''):
"""
Called when a client opens a websocket connection.
We establish a websocket connection to the proxied backend &
set up a callback to relay messages through.
"""
if not proxied_path.startswith('/'):
proxied_path = '/' + proxied_path
client_uri = self.get_client_uri('ws', port, proxied_path)
headers = self.request.headers
def message_cb(message):
"""
Callback when the backend sends messages to us
We just pass it back to the frontend
"""
# Websockets support both string (utf-8) and binary data, so let's
# make sure we signal that appropriately when proxying
self._record_activity()
if message is None:
self.close()
else:
self.write_message(message, binary=isinstance(message, bytes))
def ping_cb(data):
"""
Callback when the backend sends pings to us.
We just pass it back to the frontend.
"""
self._record_activity()
self.ping(data)
async def start_websocket_connection():
self.log.info('Trying to establish websocket connection to {}'.format(client_uri))
self._record_activity()
request = httpclient.HTTPRequest(url=client_uri, headers=headers)
self.ws = await pingable_ws_connect(request=request,
on_message_callback=message_cb, on_ping_callback=ping_cb)
self._record_activity()
self.log.info('Websocket connection established to {}'.format(client_uri))
ioloop.IOLoop.current().add_callback(start_websocket_connection) | [
"async",
"def",
"open",
"(",
"self",
",",
"port",
",",
"proxied_path",
"=",
"''",
")",
":",
"if",
"not",
"proxied_path",
".",
"startswith",
"(",
"'/'",
")",
":",
"proxied_path",
"=",
"'/'",
"+",
"proxied_path",
"client_uri",
"=",
"self",
".",
"get_client... | Called when a client opens a websocket connection.
We establish a websocket connection to the proxied backend &
set up a callback to relay messages through. | [
"Called",
"when",
"a",
"client",
"opens",
"a",
"websocket",
"connection",
"."
] | f12a090babe3c6e37a777b7e54c7b415de5c7e18 | https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/jupyter_server_proxy/handlers.py#L38-L83 | train | 202,172 |
jupyterhub/jupyter-server-proxy | jupyter_server_proxy/handlers.py | LocalProxyHandler.on_message | def on_message(self, message):
"""
Called when we receive a message from our client.
We proxy it to the backend.
"""
self._record_activity()
if hasattr(self, 'ws'):
self.ws.write_message(message, binary=isinstance(message, bytes)) | python | def on_message(self, message):
"""
Called when we receive a message from our client.
We proxy it to the backend.
"""
self._record_activity()
if hasattr(self, 'ws'):
self.ws.write_message(message, binary=isinstance(message, bytes)) | [
"def",
"on_message",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"_record_activity",
"(",
")",
"if",
"hasattr",
"(",
"self",
",",
"'ws'",
")",
":",
"self",
".",
"ws",
".",
"write_message",
"(",
"message",
",",
"binary",
"=",
"isinstance",
"(",
... | Called when we receive a message from our client.
We proxy it to the backend. | [
"Called",
"when",
"we",
"receive",
"a",
"message",
"from",
"our",
"client",
"."
] | f12a090babe3c6e37a777b7e54c7b415de5c7e18 | https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/jupyter_server_proxy/handlers.py#L85-L93 | train | 202,173 |
jupyterhub/jupyter-server-proxy | jupyter_server_proxy/handlers.py | LocalProxyHandler.on_ping | def on_ping(self, data):
"""
Called when the client pings our websocket connection.
We proxy it to the backend.
"""
self.log.debug('jupyter_server_proxy: on_ping: {}'.format(data))
self._record_activity()
if hasattr(self, 'ws'):
self.ws.protocol.write_ping(data) | python | def on_ping(self, data):
"""
Called when the client pings our websocket connection.
We proxy it to the backend.
"""
self.log.debug('jupyter_server_proxy: on_ping: {}'.format(data))
self._record_activity()
if hasattr(self, 'ws'):
self.ws.protocol.write_ping(data) | [
"def",
"on_ping",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'jupyter_server_proxy: on_ping: {}'",
".",
"format",
"(",
"data",
")",
")",
"self",
".",
"_record_activity",
"(",
")",
"if",
"hasattr",
"(",
"self",
",",
"'ws'"... | Called when the client pings our websocket connection.
We proxy it to the backend. | [
"Called",
"when",
"the",
"client",
"pings",
"our",
"websocket",
"connection",
"."
] | f12a090babe3c6e37a777b7e54c7b415de5c7e18 | https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/jupyter_server_proxy/handlers.py#L95-L104 | train | 202,174 |
jupyterhub/jupyter-server-proxy | jupyter_server_proxy/handlers.py | LocalProxyHandler.select_subprotocol | def select_subprotocol(self, subprotocols):
'''Select a single Sec-WebSocket-Protocol during handshake.'''
if isinstance(subprotocols, list) and subprotocols:
self.log.info('Client sent subprotocols: {}'.format(subprotocols))
return subprotocols[0]
return super().select_subprotocol(subprotocols) | python | def select_subprotocol(self, subprotocols):
'''Select a single Sec-WebSocket-Protocol during handshake.'''
if isinstance(subprotocols, list) and subprotocols:
self.log.info('Client sent subprotocols: {}'.format(subprotocols))
return subprotocols[0]
return super().select_subprotocol(subprotocols) | [
"def",
"select_subprotocol",
"(",
"self",
",",
"subprotocols",
")",
":",
"if",
"isinstance",
"(",
"subprotocols",
",",
"list",
")",
"and",
"subprotocols",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Client sent subprotocols: {}'",
".",
"format",
"(",
"subprot... | Select a single Sec-WebSocket-Protocol during handshake. | [
"Select",
"a",
"single",
"Sec",
"-",
"WebSocket",
"-",
"Protocol",
"during",
"handshake",
"."
] | f12a090babe3c6e37a777b7e54c7b415de5c7e18 | https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/jupyter_server_proxy/handlers.py#L275-L280 | train | 202,175 |
jupyterhub/jupyter-server-proxy | jupyter_server_proxy/handlers.py | SuperviseAndProxyHandler.port | def port(self):
"""
Allocate either the requested port or a random empty port for use by
application
"""
if 'port' not in self.state:
sock = socket.socket()
sock.bind(('', self.requested_port))
self.state['port'] = sock.getsockname()[1]
sock.close()
return self.state['port'] | python | def port(self):
"""
Allocate either the requested port or a random empty port for use by
application
"""
if 'port' not in self.state:
sock = socket.socket()
sock.bind(('', self.requested_port))
self.state['port'] = sock.getsockname()[1]
sock.close()
return self.state['port'] | [
"def",
"port",
"(",
"self",
")",
":",
"if",
"'port'",
"not",
"in",
"self",
".",
"state",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
")",
"sock",
".",
"bind",
"(",
"(",
"''",
",",
"self",
".",
"requested_port",
")",
")",
"self",
".",
"state",... | Allocate either the requested port or a random empty port for use by
application | [
"Allocate",
"either",
"the",
"requested",
"port",
"or",
"a",
"random",
"empty",
"port",
"for",
"use",
"by",
"application"
] | f12a090babe3c6e37a777b7e54c7b415de5c7e18 | https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/jupyter_server_proxy/handlers.py#L299-L309 | train | 202,176 |
jupyterhub/jupyter-server-proxy | contrib/rstudio/jupyter_rsession_proxy/__init__.py | setup_shiny | def setup_shiny():
'''Manage a Shiny instance.'''
name = 'shiny'
def _get_shiny_cmd(port):
conf = dedent("""
run_as {user};
server {{
listen {port};
location / {{
site_dir {site_dir};
log_dir {site_dir}/logs;
directory_index on;
}}
}}
""").format(
user=getpass.getuser(),
port=str(port),
site_dir=os.getcwd()
)
f = tempfile.NamedTemporaryFile(mode='w', delete=False)
f.write(conf)
f.close()
return ['shiny-server', f.name]
return {
'command': _get_shiny_cmd,
'launcher_entry': {
'title': 'Shiny',
'icon_path': os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icons', 'shiny.svg')
}
} | python | def setup_shiny():
'''Manage a Shiny instance.'''
name = 'shiny'
def _get_shiny_cmd(port):
conf = dedent("""
run_as {user};
server {{
listen {port};
location / {{
site_dir {site_dir};
log_dir {site_dir}/logs;
directory_index on;
}}
}}
""").format(
user=getpass.getuser(),
port=str(port),
site_dir=os.getcwd()
)
f = tempfile.NamedTemporaryFile(mode='w', delete=False)
f.write(conf)
f.close()
return ['shiny-server', f.name]
return {
'command': _get_shiny_cmd,
'launcher_entry': {
'title': 'Shiny',
'icon_path': os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icons', 'shiny.svg')
}
} | [
"def",
"setup_shiny",
"(",
")",
":",
"name",
"=",
"'shiny'",
"def",
"_get_shiny_cmd",
"(",
"port",
")",
":",
"conf",
"=",
"dedent",
"(",
"\"\"\"\n run_as {user};\n server {{\n listen {port};\n location / {{\n ... | Manage a Shiny instance. | [
"Manage",
"a",
"Shiny",
"instance",
"."
] | f12a090babe3c6e37a777b7e54c7b415de5c7e18 | https://github.com/jupyterhub/jupyter-server-proxy/blob/f12a090babe3c6e37a777b7e54c7b415de5c7e18/contrib/rstudio/jupyter_rsession_proxy/__init__.py#L8-L40 | train | 202,177 |
cackharot/suds-py3 | suds/xsd/query.py | Query.filter | def filter(self, result):
"""
Filter the specified result based on query criteria.
@param result: A potential result.
@type result: L{sxbase.SchemaObject}
@return: True if result should be excluded.
@rtype: boolean
"""
if result is None:
return True
reject = result in self.history
if reject:
log.debug('result %s, rejected by\n%s', Repr(result), self)
return reject | python | def filter(self, result):
"""
Filter the specified result based on query criteria.
@param result: A potential result.
@type result: L{sxbase.SchemaObject}
@return: True if result should be excluded.
@rtype: boolean
"""
if result is None:
return True
reject = result in self.history
if reject:
log.debug('result %s, rejected by\n%s', Repr(result), self)
return reject | [
"def",
"filter",
"(",
"self",
",",
"result",
")",
":",
"if",
"result",
"is",
"None",
":",
"return",
"True",
"reject",
"=",
"result",
"in",
"self",
".",
"history",
"if",
"reject",
":",
"log",
".",
"debug",
"(",
"'result %s, rejected by\\n%s'",
",",
"Repr"... | Filter the specified result based on query criteria.
@param result: A potential result.
@type result: L{sxbase.SchemaObject}
@return: True if result should be excluded.
@rtype: boolean | [
"Filter",
"the",
"specified",
"result",
"based",
"on",
"query",
"criteria",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/query.py#L58-L71 | train | 202,178 |
cackharot/suds-py3 | suds/xsd/query.py | Query.result | def result(self, result):
"""
Query result post processing.
@param result: A query result.
@type result: L{sxbase.SchemaObject}
"""
if result is None:
log.debug('%s, not-found', self.ref)
return
if self.resolved:
result = result.resolve()
log.debug('%s, found as: %s', self.ref, Repr(result))
self.history.append(result)
return result | python | def result(self, result):
"""
Query result post processing.
@param result: A query result.
@type result: L{sxbase.SchemaObject}
"""
if result is None:
log.debug('%s, not-found', self.ref)
return
if self.resolved:
result = result.resolve()
log.debug('%s, found as: %s', self.ref, Repr(result))
self.history.append(result)
return result | [
"def",
"result",
"(",
"self",
",",
"result",
")",
":",
"if",
"result",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"'%s, not-found'",
",",
"self",
".",
"ref",
")",
"return",
"if",
"self",
".",
"resolved",
":",
"result",
"=",
"result",
".",
"resolve"... | Query result post processing.
@param result: A query result.
@type result: L{sxbase.SchemaObject} | [
"Query",
"result",
"post",
"processing",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/query.py#L73-L86 | train | 202,179 |
cackharot/suds-py3 | suds/xsd/deplist.py | DepList.add | def add(self, *items):
"""
Add items to be sorted.
@param items: One or more items to be added.
@type items: I{item}
@return: self
@rtype: L{DepList}
"""
for item in items:
self.unsorted.append(item)
key = item[0]
self.index[key] = item
return self | python | def add(self, *items):
"""
Add items to be sorted.
@param items: One or more items to be added.
@type items: I{item}
@return: self
@rtype: L{DepList}
"""
for item in items:
self.unsorted.append(item)
key = item[0]
self.index[key] = item
return self | [
"def",
"add",
"(",
"self",
",",
"*",
"items",
")",
":",
"for",
"item",
"in",
"items",
":",
"self",
".",
"unsorted",
".",
"append",
"(",
"item",
")",
"key",
"=",
"item",
"[",
"0",
"]",
"self",
".",
"index",
"[",
"key",
"]",
"=",
"item",
"return"... | Add items to be sorted.
@param items: One or more items to be added.
@type items: I{item}
@return: self
@rtype: L{DepList} | [
"Add",
"items",
"to",
"be",
"sorted",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/deplist.py#L53-L65 | train | 202,180 |
cackharot/suds-py3 | suds/xsd/deplist.py | DepList.sort | def sort(self):
"""
Sort the list based on dependancies.
@return: The sorted items.
@rtype: list
"""
self.sorted = list()
self.pushed = set()
for item in self.unsorted:
popped = []
self.push(item)
while len(self.stack):
try:
top = self.top()
ref = next(top[1])
refd = self.index.get(ref)
if refd is None:
log.debug('"%s" not found, skipped', Repr(ref))
continue
self.push(refd)
except StopIteration:
popped.append(self.pop())
continue
for p in popped:
self.sorted.append(p)
self.unsorted = self.sorted
return self.sorted | python | def sort(self):
"""
Sort the list based on dependancies.
@return: The sorted items.
@rtype: list
"""
self.sorted = list()
self.pushed = set()
for item in self.unsorted:
popped = []
self.push(item)
while len(self.stack):
try:
top = self.top()
ref = next(top[1])
refd = self.index.get(ref)
if refd is None:
log.debug('"%s" not found, skipped', Repr(ref))
continue
self.push(refd)
except StopIteration:
popped.append(self.pop())
continue
for p in popped:
self.sorted.append(p)
self.unsorted = self.sorted
return self.sorted | [
"def",
"sort",
"(",
"self",
")",
":",
"self",
".",
"sorted",
"=",
"list",
"(",
")",
"self",
".",
"pushed",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"self",
".",
"unsorted",
":",
"popped",
"=",
"[",
"]",
"self",
".",
"push",
"(",
"item",
")",
... | Sort the list based on dependancies.
@return: The sorted items.
@rtype: list | [
"Sort",
"the",
"list",
"based",
"on",
"dependancies",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/deplist.py#L67-L93 | train | 202,181 |
cackharot/suds-py3 | suds/xsd/deplist.py | DepList.push | def push(self, item):
"""
Push and item onto the sorting stack.
@param item: An item to push.
@type item: I{item}
@return: The number of items pushed.
@rtype: int
"""
if item in self.pushed:
return
frame = (item, iter(item[1]))
self.stack.append(frame)
self.pushed.add(item) | python | def push(self, item):
"""
Push and item onto the sorting stack.
@param item: An item to push.
@type item: I{item}
@return: The number of items pushed.
@rtype: int
"""
if item in self.pushed:
return
frame = (item, iter(item[1]))
self.stack.append(frame)
self.pushed.add(item) | [
"def",
"push",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
"in",
"self",
".",
"pushed",
":",
"return",
"frame",
"=",
"(",
"item",
",",
"iter",
"(",
"item",
"[",
"1",
"]",
")",
")",
"self",
".",
"stack",
".",
"append",
"(",
"frame",
")",
... | Push and item onto the sorting stack.
@param item: An item to push.
@type item: I{item}
@return: The number of items pushed.
@rtype: int | [
"Push",
"and",
"item",
"onto",
"the",
"sorting",
"stack",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/deplist.py#L103-L115 | train | 202,182 |
cackharot/suds-py3 | suds/reader.py | DocumentReader.download | def download(self, url):
"""
Download the docuemnt.
@param url: A document url.
@type url: str.
@return: A file pointer to the docuemnt.
@rtype: file-like
"""
store = DocumentStore()
fp = store.open(url)
if fp is None:
fp = self.options.transport.open(Request(url))
content = fp.read()
fp.close()
ctx = self.plugins.document.loaded(url=url, document=content)
content = ctx.document
sax = Parser()
return sax.parse(string=content) | python | def download(self, url):
"""
Download the docuemnt.
@param url: A document url.
@type url: str.
@return: A file pointer to the docuemnt.
@rtype: file-like
"""
store = DocumentStore()
fp = store.open(url)
if fp is None:
fp = self.options.transport.open(Request(url))
content = fp.read()
fp.close()
ctx = self.plugins.document.loaded(url=url, document=content)
content = ctx.document
sax = Parser()
return sax.parse(string=content) | [
"def",
"download",
"(",
"self",
",",
"url",
")",
":",
"store",
"=",
"DocumentStore",
"(",
")",
"fp",
"=",
"store",
".",
"open",
"(",
"url",
")",
"if",
"fp",
"is",
"None",
":",
"fp",
"=",
"self",
".",
"options",
".",
"transport",
".",
"open",
"(",... | Download the docuemnt.
@param url: A document url.
@type url: str.
@return: A file pointer to the docuemnt.
@rtype: file-like | [
"Download",
"the",
"docuemnt",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/reader.py#L83-L100 | train | 202,183 |
cackharot/suds-py3 | suds/store.py | DocumentStore.open | def open(self, url):
"""
Open a document at the specified url.
@param url: A document URL.
@type url: str
@return: A file pointer to the document.
@rtype: StringIO
"""
protocol, location = self.split(url)
if protocol == self.protocol:
return self.find(location)
else:
return None | python | def open(self, url):
"""
Open a document at the specified url.
@param url: A document URL.
@type url: str
@return: A file pointer to the document.
@rtype: StringIO
"""
protocol, location = self.split(url)
if protocol == self.protocol:
return self.find(location)
else:
return None | [
"def",
"open",
"(",
"self",
",",
"url",
")",
":",
"protocol",
",",
"location",
"=",
"self",
".",
"split",
"(",
"url",
")",
"if",
"protocol",
"==",
"self",
".",
"protocol",
":",
"return",
"self",
".",
"find",
"(",
"location",
")",
"else",
":",
"retu... | Open a document at the specified url.
@param url: A document URL.
@type url: str
@return: A file pointer to the document.
@rtype: StringIO | [
"Open",
"a",
"document",
"at",
"the",
"specified",
"url",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/store.py#L554-L566 | train | 202,184 |
cackharot/suds-py3 | suds/wsdl.py | Definitions.add_children | def add_children(self, root):
""" Add child objects using the factory """
for c in root.getChildren(ns=wsdlns):
child = Factory.create(c, self)
if child is None:
continue
self.children.append(child)
if isinstance(child, Import):
self.imports.append(child)
continue
if isinstance(child, Types):
self.types.append(child)
continue
if isinstance(child, Message):
self.messages[child.qname] = child
continue
if isinstance(child, PortType):
self.port_types[child.qname] = child
continue
if isinstance(child, Binding):
self.bindings[child.qname] = child
continue
if isinstance(child, Service):
self.services.append(child)
continue | python | def add_children(self, root):
""" Add child objects using the factory """
for c in root.getChildren(ns=wsdlns):
child = Factory.create(c, self)
if child is None:
continue
self.children.append(child)
if isinstance(child, Import):
self.imports.append(child)
continue
if isinstance(child, Types):
self.types.append(child)
continue
if isinstance(child, Message):
self.messages[child.qname] = child
continue
if isinstance(child, PortType):
self.port_types[child.qname] = child
continue
if isinstance(child, Binding):
self.bindings[child.qname] = child
continue
if isinstance(child, Service):
self.services.append(child)
continue | [
"def",
"add_children",
"(",
"self",
",",
"root",
")",
":",
"for",
"c",
"in",
"root",
".",
"getChildren",
"(",
"ns",
"=",
"wsdlns",
")",
":",
"child",
"=",
"Factory",
".",
"create",
"(",
"c",
",",
"self",
")",
"if",
"child",
"is",
"None",
":",
"co... | Add child objects using the factory | [
"Add",
"child",
"objects",
"using",
"the",
"factory"
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/wsdl.py#L173-L197 | train | 202,185 |
cackharot/suds-py3 | suds/wsdl.py | Import.load | def load(self, definitions):
""" Load the object by opening the URL """
url = self.location
log.debug('importing (%s)', url)
if '://' not in url:
url = urljoin(definitions.url, url)
options = definitions.options
d = Definitions(url, options)
if d.root.match(Definitions.Tag, wsdlns):
self.import_definitions(definitions, d)
return
if d.root.match(Schema.Tag, Namespace.xsdns):
self.import_schema(definitions, d)
return
raise Exception('document at "%s" is unknown' % url) | python | def load(self, definitions):
""" Load the object by opening the URL """
url = self.location
log.debug('importing (%s)', url)
if '://' not in url:
url = urljoin(definitions.url, url)
options = definitions.options
d = Definitions(url, options)
if d.root.match(Definitions.Tag, wsdlns):
self.import_definitions(definitions, d)
return
if d.root.match(Schema.Tag, Namespace.xsdns):
self.import_schema(definitions, d)
return
raise Exception('document at "%s" is unknown' % url) | [
"def",
"load",
"(",
"self",
",",
"definitions",
")",
":",
"url",
"=",
"self",
".",
"location",
"log",
".",
"debug",
"(",
"'importing (%s)'",
",",
"url",
")",
"if",
"'://'",
"not",
"in",
"url",
":",
"url",
"=",
"urljoin",
"(",
"definitions",
".",
"url... | Load the object by opening the URL | [
"Load",
"the",
"object",
"by",
"opening",
"the",
"URL"
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/wsdl.py#L307-L321 | train | 202,186 |
cackharot/suds-py3 | suds/wsdl.py | Part.__getref | def __getref(self, a, tns):
""" Get the qualified value of attribute named 'a'."""
s = self.root.get(a)
if s is None:
return s
else:
return qualify(s, self.root, tns) | python | def __getref(self, a, tns):
""" Get the qualified value of attribute named 'a'."""
s = self.root.get(a)
if s is None:
return s
else:
return qualify(s, self.root, tns) | [
"def",
"__getref",
"(",
"self",
",",
"a",
",",
"tns",
")",
":",
"s",
"=",
"self",
".",
"root",
".",
"get",
"(",
"a",
")",
"if",
"s",
"is",
"None",
":",
"return",
"s",
"else",
":",
"return",
"qualify",
"(",
"s",
",",
"self",
".",
"root",
",",
... | Get the qualified value of attribute named 'a'. | [
"Get",
"the",
"qualified",
"value",
"of",
"attribute",
"named",
"a",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/wsdl.py#L409-L415 | train | 202,187 |
cackharot/suds-py3 | suds/umx/typed.py | Typed.translated | def translated(self, value, type):
""" translate using the schema type """
if value is not None:
resolved = type.resolve()
return resolved.translate(value)
else:
return value | python | def translated(self, value, type):
""" translate using the schema type """
if value is not None:
resolved = type.resolve()
return resolved.translate(value)
else:
return value | [
"def",
"translated",
"(",
"self",
",",
"value",
",",
"type",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"resolved",
"=",
"type",
".",
"resolve",
"(",
")",
"return",
"resolved",
".",
"translate",
"(",
"value",
")",
"else",
":",
"return",
"valu... | translate using the schema type | [
"translate",
"using",
"the",
"schema",
"type"
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/umx/typed.py#L137-L143 | train | 202,188 |
cackharot/suds-py3 | suds/xsd/sxbasic.py | Import.open | def open(self, options):
"""
Open and import the refrenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@return: The referenced schema.
@rtype: L{Schema}
"""
if self.opened:
return
self.opened = True
log.debug('%s, importing ns="%s", location="%s"',
self.id,
self.ns[1],
self.location
)
result = self.locate()
if result is None:
if self.location is None:
log.debug('imported schema (%s) not-found', self.ns[1])
else:
result = self.download(options)
log.debug('imported:\n%s', result)
return result | python | def open(self, options):
"""
Open and import the refrenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@return: The referenced schema.
@rtype: L{Schema}
"""
if self.opened:
return
self.opened = True
log.debug('%s, importing ns="%s", location="%s"',
self.id,
self.ns[1],
self.location
)
result = self.locate()
if result is None:
if self.location is None:
log.debug('imported schema (%s) not-found', self.ns[1])
else:
result = self.download(options)
log.debug('imported:\n%s', result)
return result | [
"def",
"open",
"(",
"self",
",",
"options",
")",
":",
"if",
"self",
".",
"opened",
":",
"return",
"self",
".",
"opened",
"=",
"True",
"log",
".",
"debug",
"(",
"'%s, importing ns=\"%s\", location=\"%s\"'",
",",
"self",
".",
"id",
",",
"self",
".",
"ns",
... | Open and import the refrenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@return: The referenced schema.
@rtype: L{Schema} | [
"Open",
"and",
"import",
"the",
"refrenced",
"schema",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/sxbasic.py#L523-L546 | train | 202,189 |
cackharot/suds-py3 | suds/xsd/sxbasic.py | Include.open | def open(self, options):
"""
Open and include the refrenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@return: The referenced schema.
@rtype: L{Schema}
"""
if self.opened:
return
self.opened = True
log.debug('%s, including location="%s"', self.id, self.location)
result = self.download(options)
log.debug('included:\n%s', result)
return result | python | def open(self, options):
"""
Open and include the refrenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@return: The referenced schema.
@rtype: L{Schema}
"""
if self.opened:
return
self.opened = True
log.debug('%s, including location="%s"', self.id, self.location)
result = self.download(options)
log.debug('included:\n%s', result)
return result | [
"def",
"open",
"(",
"self",
",",
"options",
")",
":",
"if",
"self",
".",
"opened",
":",
"return",
"self",
".",
"opened",
"=",
"True",
"log",
".",
"debug",
"(",
"'%s, including location=\"%s\"'",
",",
"self",
".",
"id",
",",
"self",
".",
"location",
")"... | Open and include the refrenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@return: The referenced schema.
@rtype: L{Schema} | [
"Open",
"and",
"include",
"the",
"refrenced",
"schema",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/sxbasic.py#L593-L607 | train | 202,190 |
cackharot/suds-py3 | suds/xsd/sxbasic.py | Include.download | def download(self, options):
""" download the schema """
url = self.location
try:
if '://' not in url:
url = urljoin(self.schema.baseurl, url)
reader = DocumentReader(options)
d = reader.open(url)
root = d.root()
root.set('url', url)
self.__applytns(root)
return self.schema.instance(root, url, options)
except TransportError:
msg = 'include schema at (%s), failed' % url
log.error('%s, %s', self.id, msg, exc_info=True)
raise Exception(msg) | python | def download(self, options):
""" download the schema """
url = self.location
try:
if '://' not in url:
url = urljoin(self.schema.baseurl, url)
reader = DocumentReader(options)
d = reader.open(url)
root = d.root()
root.set('url', url)
self.__applytns(root)
return self.schema.instance(root, url, options)
except TransportError:
msg = 'include schema at (%s), failed' % url
log.error('%s, %s', self.id, msg, exc_info=True)
raise Exception(msg) | [
"def",
"download",
"(",
"self",
",",
"options",
")",
":",
"url",
"=",
"self",
".",
"location",
"try",
":",
"if",
"'://'",
"not",
"in",
"url",
":",
"url",
"=",
"urljoin",
"(",
"self",
".",
"schema",
".",
"baseurl",
",",
"url",
")",
"reader",
"=",
... | download the schema | [
"download",
"the",
"schema"
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/sxbasic.py#L609-L624 | train | 202,191 |
cackharot/suds-py3 | suds/xsd/sxbasic.py | Factory.build | def build(cls, root, schema, filter=('*',)):
"""
Build an xsobject representation.
@param root: An schema XML root.
@type root: L{sax.element.Element}
@param filter: A tag filter.
@type filter: [str,...]
@return: A schema object graph.
@rtype: L{sxbase.SchemaObject}
"""
children = []
for node in root.getChildren(ns=Namespace.xsdns):
if '*' in filter or node.name in filter:
child = cls.create(node, schema)
if child is None:
continue
children.append(child)
c = cls.build(node, schema, child.childtags())
child.rawchildren = c
return children | python | def build(cls, root, schema, filter=('*',)):
"""
Build an xsobject representation.
@param root: An schema XML root.
@type root: L{sax.element.Element}
@param filter: A tag filter.
@type filter: [str,...]
@return: A schema object graph.
@rtype: L{sxbase.SchemaObject}
"""
children = []
for node in root.getChildren(ns=Namespace.xsdns):
if '*' in filter or node.name in filter:
child = cls.create(node, schema)
if child is None:
continue
children.append(child)
c = cls.build(node, schema, child.childtags())
child.rawchildren = c
return children | [
"def",
"build",
"(",
"cls",
",",
"root",
",",
"schema",
",",
"filter",
"=",
"(",
"'*'",
",",
")",
")",
":",
"children",
"=",
"[",
"]",
"for",
"node",
"in",
"root",
".",
"getChildren",
"(",
"ns",
"=",
"Namespace",
".",
"xsdns",
")",
":",
"if",
"... | Build an xsobject representation.
@param root: An schema XML root.
@type root: L{sax.element.Element}
@param filter: A tag filter.
@type filter: [str,...]
@return: A schema object graph.
@rtype: L{sxbase.SchemaObject} | [
"Build",
"an",
"xsobject",
"representation",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/sxbasic.py#L761-L780 | train | 202,192 |
cackharot/suds-py3 | suds/sax/attribute.py | Attribute.clone | def clone(self, parent=None):
"""
Clone this object.
@param parent: The parent for the clone.
@type parent: L{element.Element}
@return: A copy of this object assigned to the new parent.
@rtype: L{Attribute}
"""
a = Attribute(self.qname(), self.value)
a.parent = parent
return a | python | def clone(self, parent=None):
"""
Clone this object.
@param parent: The parent for the clone.
@type parent: L{element.Element}
@return: A copy of this object assigned to the new parent.
@rtype: L{Attribute}
"""
a = Attribute(self.qname(), self.value)
a.parent = parent
return a | [
"def",
"clone",
"(",
"self",
",",
"parent",
"=",
"None",
")",
":",
"a",
"=",
"Attribute",
"(",
"self",
".",
"qname",
"(",
")",
",",
"self",
".",
"value",
")",
"a",
".",
"parent",
"=",
"parent",
"return",
"a"
] | Clone this object.
@param parent: The parent for the clone.
@type parent: L{element.Element}
@return: A copy of this object assigned to the new parent.
@rtype: L{Attribute} | [
"Clone",
"this",
"object",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/sax/attribute.py#L52-L62 | train | 202,193 |
cackharot/suds-py3 | suds/sax/attribute.py | Attribute.setValue | def setValue(self, value):
"""
Set the attributes value
@param value: The new value (may be None)
@type value: basestring
@return: self
@rtype: L{Attribute}
"""
if isinstance(value, Text):
self.value = value
else:
self.value = Text(value)
return self | python | def setValue(self, value):
"""
Set the attributes value
@param value: The new value (may be None)
@type value: basestring
@return: self
@rtype: L{Attribute}
"""
if isinstance(value, Text):
self.value = value
else:
self.value = Text(value)
return self | [
"def",
"setValue",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Text",
")",
":",
"self",
".",
"value",
"=",
"value",
"else",
":",
"self",
".",
"value",
"=",
"Text",
"(",
"value",
")",
"return",
"self"
] | Set the attributes value
@param value: The new value (may be None)
@type value: basestring
@return: self
@rtype: L{Attribute} | [
"Set",
"the",
"attributes",
"value"
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/sax/attribute.py#L75-L87 | train | 202,194 |
cackharot/suds-py3 | suds/sax/attribute.py | Attribute.namespace | def namespace(self):
"""
Get the attributes namespace. This may either be the namespace
defined by an optional prefix, or its parent's namespace.
@return: The attribute's namespace
@rtype: (I{prefix}, I{name})
"""
if self.prefix is None:
return Namespace.default
else:
return self.resolvePrefix(self.prefix) | python | def namespace(self):
"""
Get the attributes namespace. This may either be the namespace
defined by an optional prefix, or its parent's namespace.
@return: The attribute's namespace
@rtype: (I{prefix}, I{name})
"""
if self.prefix is None:
return Namespace.default
else:
return self.resolvePrefix(self.prefix) | [
"def",
"namespace",
"(",
"self",
")",
":",
"if",
"self",
".",
"prefix",
"is",
"None",
":",
"return",
"Namespace",
".",
"default",
"else",
":",
"return",
"self",
".",
"resolvePrefix",
"(",
"self",
".",
"prefix",
")"
] | Get the attributes namespace. This may either be the namespace
defined by an optional prefix, or its parent's namespace.
@return: The attribute's namespace
@rtype: (I{prefix}, I{name}) | [
"Get",
"the",
"attributes",
"namespace",
".",
"This",
"may",
"either",
"be",
"the",
"namespace",
"defined",
"by",
"an",
"optional",
"prefix",
"or",
"its",
"parent",
"s",
"namespace",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/sax/attribute.py#L112-L122 | train | 202,195 |
cackharot/suds-py3 | suds/sax/attribute.py | Attribute.resolvePrefix | def resolvePrefix(self, prefix):
"""
Resolve the specified prefix to a known namespace.
@param prefix: A declared prefix
@type prefix: basestring
@return: The namespace that has been mapped to I{prefix}
@rtype: (I{prefix}, I{name})
"""
ns = Namespace.default
if self.parent is not None:
ns = self.parent.resolvePrefix(prefix)
return ns | python | def resolvePrefix(self, prefix):
"""
Resolve the specified prefix to a known namespace.
@param prefix: A declared prefix
@type prefix: basestring
@return: The namespace that has been mapped to I{prefix}
@rtype: (I{prefix}, I{name})
"""
ns = Namespace.default
if self.parent is not None:
ns = self.parent.resolvePrefix(prefix)
return ns | [
"def",
"resolvePrefix",
"(",
"self",
",",
"prefix",
")",
":",
"ns",
"=",
"Namespace",
".",
"default",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"ns",
"=",
"self",
".",
"parent",
".",
"resolvePrefix",
"(",
"prefix",
")",
"return",
"ns"
] | Resolve the specified prefix to a known namespace.
@param prefix: A declared prefix
@type prefix: basestring
@return: The namespace that has been mapped to I{prefix}
@rtype: (I{prefix}, I{name}) | [
"Resolve",
"the",
"specified",
"prefix",
"to",
"a",
"known",
"namespace",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/sax/attribute.py#L124-L135 | train | 202,196 |
cackharot/suds-py3 | suds/bindings/rpc.py | Encoded.unmarshaller | def unmarshaller(self, typed=True):
"""
Get the appropriate XML decoder.
@return: Either the (basic|typed) unmarshaller.
@rtype: L{UmxTyped}
"""
if typed:
return UmxEncoded(self.schema())
else:
return RPC.unmarshaller(self, typed) | python | def unmarshaller(self, typed=True):
"""
Get the appropriate XML decoder.
@return: Either the (basic|typed) unmarshaller.
@rtype: L{UmxTyped}
"""
if typed:
return UmxEncoded(self.schema())
else:
return RPC.unmarshaller(self, typed) | [
"def",
"unmarshaller",
"(",
"self",
",",
"typed",
"=",
"True",
")",
":",
"if",
"typed",
":",
"return",
"UmxEncoded",
"(",
"self",
".",
"schema",
"(",
")",
")",
"else",
":",
"return",
"RPC",
".",
"unmarshaller",
"(",
"self",
",",
"typed",
")"
] | Get the appropriate XML decoder.
@return: Either the (basic|typed) unmarshaller.
@rtype: L{UmxTyped} | [
"Get",
"the",
"appropriate",
"XML",
"decoder",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/bindings/rpc.py#L89-L98 | train | 202,197 |
cackharot/suds-py3 | suds/client.py | Client.set_options | def set_options(self, **kwargs):
"""
Set options.
@param kwargs: keyword arguments.
@see: L{Options}
"""
p = Unskin(self.options)
p.update(kwargs) | python | def set_options(self, **kwargs):
"""
Set options.
@param kwargs: keyword arguments.
@see: L{Options}
"""
p = Unskin(self.options)
p.update(kwargs) | [
"def",
"set_options",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"p",
"=",
"Unskin",
"(",
"self",
".",
"options",
")",
"p",
".",
"update",
"(",
"kwargs",
")"
] | Set options.
@param kwargs: keyword arguments.
@see: L{Options} | [
"Set",
"options",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/client.py#L122-L129 | train | 202,198 |
cackharot/suds-py3 | suds/client.py | Client.clone | def clone(self):
"""
Get a shallow clone of this object.
The clone only shares the WSDL. All other attributes are
unique to the cloned object including options.
@return: A shallow clone.
@rtype: L{Client}
"""
class Uninitialized(Client):
def __init__(self):
pass
clone = Uninitialized()
clone.options = Options()
cp = Unskin(clone.options)
mp = Unskin(self.options)
cp.update(deepcopy(mp))
clone.wsdl = self.wsdl
clone.factory = self.factory
clone.service = ServiceSelector(clone, self.wsdl.services)
clone.sd = self.sd
clone.messages = dict(tx=None, rx=None)
return clone | python | def clone(self):
"""
Get a shallow clone of this object.
The clone only shares the WSDL. All other attributes are
unique to the cloned object including options.
@return: A shallow clone.
@rtype: L{Client}
"""
class Uninitialized(Client):
def __init__(self):
pass
clone = Uninitialized()
clone.options = Options()
cp = Unskin(clone.options)
mp = Unskin(self.options)
cp.update(deepcopy(mp))
clone.wsdl = self.wsdl
clone.factory = self.factory
clone.service = ServiceSelector(clone, self.wsdl.services)
clone.sd = self.sd
clone.messages = dict(tx=None, rx=None)
return clone | [
"def",
"clone",
"(",
"self",
")",
":",
"class",
"Uninitialized",
"(",
"Client",
")",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"pass",
"clone",
"=",
"Uninitialized",
"(",
")",
"clone",
".",
"options",
"=",
"Options",
"(",
")",
"cp",
"=",
"Unskin... | Get a shallow clone of this object.
The clone only shares the WSDL. All other attributes are
unique to the cloned object including options.
@return: A shallow clone.
@rtype: L{Client} | [
"Get",
"a",
"shallow",
"clone",
"of",
"this",
"object",
".",
"The",
"clone",
"only",
"shares",
"the",
"WSDL",
".",
"All",
"other",
"attributes",
"are",
"unique",
"to",
"the",
"cloned",
"object",
"including",
"options",
"."
] | 7387ec7806e9be29aad0a711bea5cb3c9396469c | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/client.py#L166-L187 | train | 202,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.