code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
r
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) | 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 othe... | 5.919799 | 4.349205 | 1.361122 |
r
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) | r"""
Calculates the installed power of a wind turbine cluster.
Returns
-------
float
Installed power of the wind turbine cluster. | 3.160172 | 3.25231 | 0.97167 |
r
# 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
... | 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_in... | 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... | 3.193282 | 3.177901 | 1.00484 |
r
# specification of wind farm data
example_farm_data = {
'name': 'example_farm',
'wind_turbine_fleet': [{'wind_turbine': my_turbine,
'number_of_turbines': 6},
{'wind_turbine': e126,
'number_of_tu... | def initialize_wind_farms(my_turbine, e126) | r"""
Initializes two :class:`~.wind_farm.WindFarm` objects.
This function shows how to initialize a WindFarm object. You need to
provide at least a name and a the wind farm's wind turbine fleet as done
below for 'example_farm'. Optionally you can provide a wind farm efficiency
(which can be constan... | 2.408631 | 1.940884 | 1.240997 |
r
# specification of cluster data
example_cluster_data = {
'name': 'example_cluster',
'wind_farms': [example_farm, example_farm_2]}
# initialize WindTurbineCluster object
example_cluster = WindTurbineCluster(**example_cluster_data)
return example_cluster | def initialize_wind_turbine_cluster(example_farm, example_farm_2) | r"""
Initializes a :class:`~.wind_turbine_cluster.WindTurbineCluster` object.
Function shows how to initialize a WindTurbineCluster object. In this case
the cluster only contains two wind farms.
Parameters
----------
example_farm : WindFarm
WindFarm object.
example_farm_2 : WindFar... | 4.230113 | 3.958423 | 1.068636 |
r
# set efficiency of example_farm to apply wake losses
example_farm.efficiency = 0.9
# power output calculation for example_farm
# initialize TurbineClusterModelChain with default parameters and use
# run_model method to calculate power output
mc_example_farm = TurbineClusterModelChain(exa... | def calculate_power_output(weather, example_farm, example_cluster) | r"""
Calculates power output of wind farms and clusters using the
:class:`~.turbine_cluster_modelchain.TurbineClusterModelChain`.
The :class:`~.turbine_cluster_modelchain.TurbineClusterModelChain` is a
class that provides all necessary steps to calculate the power output of a
wind farm or cluster. ... | 4.21272 | 3.73343 | 1.128378 |
r
# plot or print power output
if plt:
example_cluster.power_output.plot(legend=True, label='example cluster')
example_farm.power_output.plot(legend=True, label='example farm')
plt.show()
else:
print(example_cluster.power_output)
print(example_farm.power_output) | def plot_or_print(example_farm, example_cluster) | r"""
Plots or prints power output and power (coefficient) curves.
Parameters
----------
example_farm : WindFarm
WindFarm object.
example_farm_2 : WindFarm
WindFarm object constant wind farm efficiency and coordinates. | 3.066988 | 2.963578 | 1.034894 |
r
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,
... | def run_example() | r"""
Runs the example. | 6.944409 | 6.650965 | 1.04412 |
r
def isfloat(x):
try:
float(x)
return x
except ValueError:
return False
try:
df = pd.read_csv(file_, index_col=0)
except FileNotFoundError:
raise FileNotFoundError("The file '{}' was not found.".format(file_))
wpp_df = df[df.turbi... | def get_turbine_data_from_file(turbine_type, file_) | r"""
Fetches power (coefficient) curve data from a csv file.
See `example_power_curves.csv' and `example_power_coefficient_curves.csv`
in example/data for the required format of a csv file. The self-provided
csv file may contain more columns than the example files. Only columns
containing wind spee... | 3.710161 | 3.678839 | 1.008514 |
r
# hdf5 filename
filename = os.path.join(os.path.dirname(__file__), 'data',
'turbine_data_oedb.h5')
if os.path.isfile(filename) and not overwrite:
logging.debug("Turbine data is fetched from {}".format(filename))
with pd.HDFStore(filename) as hdf_store:
... | def get_turbine_data_from_oedb(turbine_type, fetch_curve, overwrite=False) | r"""
Fetches data for one wind turbine type from the OpenEnergy Database (oedb).
If turbine data exists in local repository it is loaded from this file. The
file is created when turbine data was loaded from oedb in
:py:func:`~.load_turbine_data_from_oedb`. Use this function with
`overwrite=True` to... | 3.289334 | 2.988682 | 1.100597 |
r
# url of OpenEnergy Platform that contains the oedb
oep_url = 'http://oep.iks.cs.ovgu.de/'
# location of data
schema = 'model_draft'
table = 'openfred_windpower_powercurve'
# load data
result = requests.get(
oep_url + '/api/v0/schema/{}/tables/{}/rows/?'.format(
sch... | def load_turbine_data_from_oedb() | r"""
Loads turbine data from the OpenEnergy Database (oedb).
Turbine data is saved to `filename` for offline usage of windpowerlib.
Returns
-------
turbine_data : pd.DataFrame
Contains turbine data of different turbines such as 'manufacturer',
'turbine_type', nominal power ('instal... | 4.525019 | 4.378301 | 1.03351 |
r
df = load_turbine_data_from_oedb()
cp_curves_df = df.iloc[df.loc[df['has_cp_curve']].index][
['manufacturer', 'turbine_type', 'has_cp_curve']]
p_curves_df = df.iloc[df.loc[df['has_power_curve']].index][
['manufacturer', 'turbine_type', 'has_power_curve']]
curves_df = pd.merge(p_cu... | def get_turbine_types(print_out=True) | r"""
Get the names of all possible wind turbine types for which the power
coefficient curve or power curve is provided in the OpenEnergy Data Base
(oedb).
Parameters
----------
print_out : boolean
Directly prints a tabular containing the turbine types in column
'turbine_type', t... | 2.811805 | 2.285057 | 1.230518 |
r
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)
... | 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 spee... | 2.592327 | 2.514681 | 1.030877 |
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) | Distance between two points. | 3.397823 | 3.297648 | 1.030378 |
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) | i is a number between 0 and 1, if 0 then color1, if 1 color2, ... | 1.410339 | 1.37387 | 1.026545 |
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) | 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 latit... | 6.164506 | 4.929775 | 1.250464 |
file_name = self.get_file_name(latitude, longitude)
if not file_name:
return None
if (file_name in self.files):
return self.files[file_name]
else:
data = self.retrieve_or_load_file_data(file_name)
if not data:
ret... | def get_file(self, latitude, longitude) | If the file can't be found -- it will be retrieved from the server. | 3.156027 | 3.046951 | 1.035798 |
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:
... | 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. | 1.758333 | 1.780717 | 0.98743 |
if only_missing:
original_elevations = list(map(lambda point: point.elevation, gpx.walk(only_points=True)))
if smooth:
self._add_sampled_elevations(gpx)
else:
for point in gpx.walk(only_points=True):
ele = self.get_elevation(point.lat... | def add_elevations(self, gpx, only_missing=False, smooth=False, gpx_smooth_no=0) | only_missing -- if True only points without elevation will get a SRTM value
smooth -- if True interpolate between points
if gpx_smooth_no > 0 -- execute gpx.smooth(vertical=True) | 2.585194 | 2.512485 | 1.028939 |
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:
lengt... | def _add_interval_elevations(self, gpx, min_interval_length=100) | Adds elevation on points every min_interval_length and add missing
elevation between | 2.691059 | 2.632395 | 1.022286 |
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 fo... | 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. | 2.628476 | 2.52994 | 1.038948 |
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, lo... | def approximation(self, latitude, longitude) | Dummy approximation with nearest points. The nearest the neighbour the
more important will be its elevation. | 2.665009 | 2.613198 | 1.019827 |
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), (... | 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 b... | 2.765387 | 2.736322 | 1.010622 |
groups = mod_re.findall('([NS])(\d+)([EW])(\d+)\.hgt', self.file_name)
assert groups and len(groups) == 1 and len(groups[0]) == 4, 'Invalid file name {0}'.format(self.file_name)
groups = groups[0]
if groups[0] == 'N':
latitude = float(groups[1])
else:
... | def parse_file_name_starting_position(self) | Returns (latitude, longitude) of lower left point of the file | 2.619765 | 2.281832 | 1.148097 |
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:
... | 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 a... | 2.586279 | 2.801912 | 0.923041 |
# 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:
... | def get_srtm_dir(self) | The default path to store files. | 3.303377 | 3.069241 | 1.076285 |
req_msg = {
'type': 'subscribe',
'topic': topic,
'response': True
}
await self._conn.send_message(req_msg) | async def subscribe(self, topic: str) | Subscribe to a channel
:param topic: required
:returns: None
Sample ws response
.. code-block:: python
{
"type":"message",
"topic":"/market/ticker:BTC-USDT",
"subject":"trade.ticker",
"data":{
... | 6.078462 | 4.629417 | 1.313008 |
req_msg = {
'type': 'unsubscribe',
'topic': topic,
'response': True
}
await self._conn.send_message(req_msg) | 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"
} | 6.234281 | 5.209599 | 1.196691 |
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 = ("{}{... | def _generate_signature(self, nonce, method, path, data) | Generate the call signature
:param path:
:param data:
:param nonce:
:return: signature string | 3.021278 | 3.050527 | 0.990412 |
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['su... | def _handle_response(response) | Internal helper for handling API responses from the Quoine server.
Raises the appropriate exceptions when necessary; otherwise, returns the
response. | 3.136353 | 3.038852 | 1.032085 |
data = {
'type': account_type,
'currency': currency
}
return self._post('accounts', True, data=data) | 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')... | 3.700881 | 5.707135 | 0.648466 |
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=... | 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 ... | 2.541427 | 2.737097 | 0.928512 |
data = {}
if page:
data['currentPage'] = page
if page_size:
data['pageSize'] = page_size
return self._get('accounts/{}/holds'.format(account_id), True, data=data) | def get_account_holds(self, account_id, page=None, page_size=None) | Get account holds placed for any active orders or pending withdraw requests
https://docs.kucoin.com/#get-holds
:param account_id: ID for account - from list_accounts()
:type account_id: string
:param page: (optional) Current page - default 1
:type page: int
:param page_... | 3.009106 | 3.293521 | 0.913644 |
data = {
'payAccountId': from_account_id,
'recAccountId': to_account_id,
'amount': amount
}
if order_id:
data['clientOid'] = order_id
else:
data['clientOid'] = flat_uuid()
return self._post('accounts/inner-tr... | def create_inner_transfer(self, from_account_id, to_account_id, amount, order_id=None) | Get account holds placed for any active orders or pending withdraw requests
https://docs.kucoin.com/#get-holds
:param from_account_id: ID of account to transfer funds from - from list_accounts()
:type from_account_id: str
:param to_account_id: ID of account to transfer funds to - from ... | 3.680705 | 3.980895 | 0.924592 |
data = {
'currency': currency
}
return self._post('deposit-addresses', True, data=data) | 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')
:retu... | 5.447964 | 9.015183 | 0.60431 |
data = {
'currency': currency
}
return self._get('deposit-addresses', True, data=data) | 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
{
... | 5.618069 | 8.15679 | 0.68876 |
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:
... | 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) ... | 1.959693 | 2.195058 | 0.892775 |
data = {
'currency': currency
}
return self._get('withdrawals/quotas', True, data=data) | 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
... | 4.989761 | 8.16438 | 0.611162 |
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._p... | 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: (option... | 1.871509 | 2.455697 | 0.762109 |
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... | 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... | 2.201482 | 2.115021 | 1.04088 |
if stop and not stop_price:
raise LimitOrderException('Stop order needs stop_price')
if stop_price and not stop:
raise LimitOrderException('Stop order type required with stop_price')
if cancel_after and time_in_force != self.TIMEINFORCE_GOOD_TILL_TIME:
... | def create_limit_order(self, symbol, side, price, size, client_oid=None, remark=None,
time_in_force=None, stop=None, stop_price=None, stp=None, cancel_after=None, post_only=None,
hidden=None, iceberg=None, visible_size=None) | Create an order
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 price: Name of coin
:type price: string
:param size: Amount of base currency to ... | 1.925029 | 1.858614 | 1.035734 |
data = {}
if symbol is not None:
data['symbol'] = symbol
return self._delete('orders', True, data=data) | 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"
]
... | 4.402567 | 7.311255 | 0.602163 |
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:
... | 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
:ty... | 1.571115 | 1.79191 | 0.876782 |
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['... | 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 time... | 1.905988 | 2.294173 | 0.830796 |
data = {}
if order_id:
data['orderId'] = order_id
if symbol:
data['symbol'] = symbol
if side:
data['side'] = side
if order_type:
data['type'] = order_type
if start:
data['startAt'] = start
if e... | def get_fills(self, order_id=None, symbol=None, side=None, order_type=None,
start=None, end=None, page=None, limit=None) | Get a list of recent fills.
https://docs.kucoin.com/#list-fills
:param order_id: (optional) generated order id
:type order_id: string
:param symbol: (optional) Name of symbol e.g. KCS-BTC
:type symbol: string
:param side: (optional) buy or sell
:type side: strin... | 1.565922 | 1.771248 | 0.884078 |
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) | 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
.. co... | 4.63037 | 5.375091 | 0.86145 |
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) | 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. d... | 3.563463 | 4.708715 | 0.75678 |
data = {
'symbol': symbol
}
return self._get('market/stats', False, data=data) | 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
... | 6.967729 | 7.346668 | 0.94842 |
data = {
'symbol': symbol
}
return self._get('market/orderbook/level2_100', False, data=data) | 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... | 7.449246 | 7.740986 | 0.962312 |
data = {
'symbol': symbol
}
return self._get('market/orderbook/level2', False, data=data) | 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 symbo... | 6.680698 | 7.12037 | 0.938252 |
data = {
'symbol': symbol
}
return self._get('market/orderbook/level3', False, data=data) | 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 o... | 5.715412 | 7.432422 | 0.768984 |
data = {
'symbol': symbol
}
return self._get('market/histories', False, data=data) | 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
... | 6.900657 | 9.334304 | 0.739279 |
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 i... | 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, 5m... | 2.315414 | 2.447505 | 0.946031 |
path = 'bullet-public'
signed = private
if private:
path = 'bullet-private'
return self._post(path, signed) | 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
{... | 12.101193 | 13.944833 | 0.86779 |
prefix = settings.SESSION_REDIS_PREFIX
if not prefix:
return session_key
return ':'.join([prefix, session_key]) | def get_real_stored_key(self, session_key) | Return the real key name in redis storage
@return string | 4.141675 | 4.410345 | 0.939082 |
try:
inputtiles = click.open_file(inputtiles).readlines()
except IOError:
inputtiles = [inputtiles]
# parse the input stream into an array
tiles = edge_finder.findedges(inputtiles, parsenames)
for t in tiles:
click.echo(t.tolist()) | def edges(inputtiles, parsenames) | For a stream of [<x>, <y>, <z>] tiles, return only those tiles that are on the edge. | 5.638144 | 5.214674 | 1.081208 |
try:
inputtiles = click.open_file(inputtiles).readlines()
except IOError:
inputtiles = [inputtiles]
unioned = uniontiles.union(inputtiles, parsenames)
for u in unioned:
click.echo(json.dumps(u)) | def union(inputtiles, parsenames) | Returns the unioned shape of a steeam of [<x>, <y>, <z>] tiles in GeoJSON. | 4.017384 | 3.915717 | 1.025964 |
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) | Burn a stream of GeoJSONs into a output stream of the tiles they intersect for a given zoom. | 10.329443 | 7.407968 | 1.394369 |
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)
... | def save(self, *args, **kwargs) | Saves this model instance to the database. | 6.376882 | 6.23652 | 1.022507 |
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 | Converts the value from a database value into a Python value. | 5.856948 | 3.989988 | 1.467911 |
# 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:
va... | def get_prep_value(self, value: LocalizedIntegerValue) -> dict | Gets the value in a format to store into the database. | 2.843728 | 2.767096 | 1.027694 |
defaults = {
'form_class': LocalizedIntegerFieldForm
}
defaults.update(kwargs)
return super().formfield(**defaults) | def formfield(self, **kwargs) | Gets the form field associated with this field. | 4.620378 | 4.502327 | 1.02622 |
integer_values = {}
for lang_code, _ in settings.LANGUAGES:
local_value = value.get(lang_code, None)
if local_value is None or local_value.strip() == '':
local_value = None
try:
integer_values[lang_code] = int(local_value)
... | def _convert_localized_value(value: LocalizedValue) -> LocalizedIntegerValue | Converts from :see:LocalizedValue to :see:LocalizedIntegerValue. | 2.443529 | 2.361643 | 1.034673 |
localized_value = self.value_class()
for (lang_code, _), value in zip(settings.LANGUAGES, value):
localized_value.set(lang_code, value)
return localized_value | def compress(self, value: List[str]) -> value_class | Compresses the values from individual fields
into a single :see:LocalizedValue instance.
Arguments:
value:
The values from all the widgets.
Returns:
A :see:LocalizedValue containing all
the value in several languages. | 4.808717 | 4.037349 | 1.191058 |
if initial is None:
initial = [None for x in range(0, len(value))]
else:
if not isinstance(initial, list):
initial = self.widget.decompress(initial)
clean_data = []
errors = []
if not value or isinstance(value, (list, tuple)):
... | def clean(self, value, initial=None) | Most part of this method is a copy of
django.forms.MultiValueField.clean, with the exception of initial
value handling (this need for correct processing FileField's).
All original comments saved. | 2.546878 | 2.377454 | 1.071263 |
defaults = {
'form_class': LocalizedTextFieldForm
}
defaults.update(kwargs)
return super().formfield(**defaults) | def formfield(self, **kwargs) | Gets the form field associated with this field. | 4.637195 | 4.446421 | 1.042905 |
defaults = {
'form_class': forms.CharField,
'required': False
}
defaults.update(kwargs)
form_field = super().formfield(**defaults)
form_field.widget = forms.HiddenInput()
return form_field | def formfield(self, **kwargs) | Gets the form field associated with this field.
Because this is a slug field which is automatically
populated, it should be hidden from the form. | 2.609689 | 2.403071 | 1.085981 |
slugs = LocalizedValue()
for lang_code, value in self._get_populate_values(instance):
if not value:
continue
if self.include_time:
value += '-%s' % datetime.now().microsecond
def is_unique(slug: str, language: str) -> bool:... | def pre_save(self, instance, add: bool) | Ran just before the model is saved, allows us to built
the slug.
Arguments:
instance:
The model that is being saved.
add:
Indicates whether this is a new entry
to the database or an update. | 4.558944 | 4.251289 | 1.072367 |
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 | 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.
Return... | 2.94906 | 2.901889 | 1.016255 |
return [
(
lang_code,
self._get_populate_from_value(
instance,
self.populate_from,
lang_code
),
)
for lang_code, _ in settings.LANGUAGES
] | def _get_populate_values(self, instance) -> Tuple[str, str] | Gets all values (for each language) from the
specified's instance's `populate_from` field.
Arguments:
instance:
The instance to get the values from.
Returns:
A list of (lang_code, value) tuples. | 4.715126 | 3.61191 | 1.305438 |
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(fi... | 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 f... | 2.846758 | 2.767325 | 1.028704 |
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) | Deconstructs the field into something the database
can store. | 5.710166 | 5.079174 | 1.124231 |
if not isinstance(instance, AtomicSlugRetryMixin):
raise ImproperlyConfigured((
'Model \'%s\' does not inherit from AtomicSlugRetryMixin. '
'Without this, the LocalizedUniqueSlugField will not work.'
) % type(instance).__name__)
slugs = ... | def pre_save(self, instance, add: bool) | Ran just before the model is saved, allows us to built
the slug.
Arguments:
instance:
The model that is being saved.
add:
Indicates whether this is a new entry
to the database or an update.
Returns:
The locali... | 4.252834 | 3.915415 | 1.086177 |
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) | Adds this field to the specifed model.
Arguments:
cls:
The model to add the field to.
name:
The name of the field to add. | 2.925305 | 5.047872 | 0.579513 |
if not value:
if getattr(settings, 'LOCALIZED_FIELDS_EXPERIMENTAL', False):
return None
else:
return cls.attr_class()
# we can get a list if an aggregation expression was used..
# if we the expression was flattened when only one ... | def from_db_value(cls, value, *_) -> Optional[LocalizedValue] | Turns the specified database value into its Python
equivalent.
Arguments:
value:
The value that is stored in the database and
needs to be converted to its Python equivalent.
Returns:
A :see:LocalizedValue instance containing the
... | 5.079845 | 5.291459 | 0.960008 |
# first let the base class handle the deserialization, this is in case we
# get specified a json string representing a dict
try:
deserialized_value = super(LocalizedField, self).to_python(value)
except json.JSONDecodeError:
deserialized_value = value
... | def to_python(self, value: Union[dict, str, None]) -> LocalizedValue | Turns the specified database value into its Python
equivalent.
Arguments:
value:
The value that is stored in the database and
needs to be converted to its Python equivalent.
Returns:
A :see:LocalizedValue instance containing the
... | 5.704823 | 6.141047 | 0.928966 |
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(cl... | 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 instan... | 3.32511 | 3.436574 | 0.967565 |
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
... | 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.
... | 5.728679 | 4.693508 | 1.220554 |
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' ... | 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. | 6.334648 | 5.448809 | 1.162575 |
defaults = dict(
form_class=LocalizedFieldForm,
required=False if self.blank else self.required
)
defaults.update(kwargs)
return super().formfield(**defaults) | def formfield(self, **kwargs) | Gets the form field associated with this field. | 4.242875 | 3.982534 | 1.065371 |
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 | 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. | 4.990756 | 6.340382 | 0.787138 |
self[language] = value
self.__dict__.update(self)
return self | 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. | 13.273277 | 10.84051 | 1.224414 |
path = 'localized_fields.value.%s' % self.__class__.__name__
return path, [self.__dict__], {} | def deconstruct(self) -> dict | Deconstructs this value into a primitive type.
Returns:
A dictionary with all the localized values
contained in this instance. | 22.351763 | 15.125979 | 1.477707 |
for lang_code, _ in settings.LANGUAGES:
self.set(lang_code, self.default_value)
if isinstance(value, str):
self.set(settings.LANGUAGE_CODE, value)
elif isinstance(value, dict):
for lang_code, _ in settings.LANGUAGES:
lang_value = va... | def _interpret_value(self, value) | Interprets a value passed in the constructor as
a :see:LocalizedValue.
If string:
Assumes it's the default language.
If dict:
Each key is a language and the value a string
in that language.
If list:
Recurse into to apply rules above.
... | 2.229136 | 2.189857 | 1.017937 |
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... | 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. | 3.896932 | 3.362564 | 1.158917 |
value = super().translate()
if value is None or (isinstance(value, str) and value.strip() == ''):
return None
return int(value) | def translate(self) | Gets the value in the current language, or
in the configured fallbck language. | 4.938655 | 5.222038 | 0.945733 |
if isinstance(value, LocalizedValue):
prep_value = LocalizedValue()
for k, v in value.__dict__.items():
if v is None:
prep_value.set(k, '')
else:
# Need to convert File objects provided via a form to
... | def get_prep_value(self, value) | Returns field's value prepared for saving into a database. | 4.079802 | 3.86952 | 1.054343 |
value = super().pre_save(model_instance, add)
if isinstance(value, LocalizedValue):
for file in value.__dict__.values():
if file and not file._committed:
file.save(file.name, file, save=False)
return value | def pre_save(self, model_instance, add) | Returns field's value just before saving. | 4.455044 | 4.129945 | 1.078718 |
value = obj
for path_part in path.split('.'):
value = getattr(value, path_part)
return value | 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. | 4.281349 | 5.637391 | 0.759456 |
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] | 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. | 3.312818 | 3.824825 | 0.866136 |
defaults = {
'form_class': LocalizedCharFieldForm
}
defaults.update(kwargs)
return super().formfield(**defaults) | def formfield(self, **kwargs) | Gets the form field associated with this field. | 4.259529 | 4.186786 | 1.017374 |
localized_value = getattr(instance, self.attname)
if not localized_value:
return None
for lang_code, _ in settings.LANGUAGES:
value = localized_value.get(lang_code)
if not value:
continue
localized_value.set(
... | def pre_save(self, instance, add: bool) | Ran just before the model is saved, allows us to built
the slug.
Arguments:
instance:
The model that is being saved.
add:
Indicates whether this is a new entry
to the database or an update. | 3.554769 | 3.595021 | 0.988803 |
'''
Method to show a CLI based confirmation message, waiting for a yes/no answer.
"what" and "where" are used to better define the message.
'''
ans = input('Are you sure you want to delete the '
'{} {} from the service?\n[yN]> '.format(what, where))
if 'y' in ans:
ans = l... | def confirm(what, where) | Method to show a CLI based confirmation message, waiting for a yes/no answer.
"what" and "where" are used to better define the message. | 9.890639 | 5.864684 | 1.686474 |
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
... | def register_target(repo_cmd, repo_service) | Decorator to register a class with an repo_service | 4.540159 | 3.985604 | 1.13914 |
'''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()... | 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 | 3.986963 | 3.253645 | 1.225384 |
'''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 give... | 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, reposito... | 4.482845 | 2.491673 | 1.79913 |
'''Pull a repository
:param remote: git-remote instance
:param branch: name of the branch to pull
'''
pb = ProgressBar()
pb.setup(self.name)
if branch:
remote.pull(branch, progress=pb)
else: # pragma: no cover
remote.pull(progress=p... | def pull(self, remote, branch=None) | Pull a repository
:param remote: git-remote instance
:param branch: name of the branch to pull | 4.875442 | 3.790824 | 1.286117 |
'''Push a repository
:param remote: git-remote instance
:param branch: name of the branch to push
:return: PushInfo, git push output lines
'''
pb = ProgressBar()
pb.setup(self.name, ProgressBar.Action.PUSH)
if branch:
result = remote.push(branc... | def push(self, remote, branch=None) | Push a repository
:param remote: git-remote instance
:param branch: name of the branch to push
:return: PushInfo, git push output lines | 6.26497 | 4.09022 | 1.531695 |
'''Pull a repository
:param remote: git-remote instance
:param branch: name of the branch to pull
'''
pb = ProgressBar()
pb.setup(self.name)
if local_branch:
branch = ':'.join([branch, local_branch])
remote.fetch(branch, update_head_ok=True, ... | def fetch(self, remote, branch, local_branch = None, force=False) | Pull a repository
:param remote: git-remote instance
:param branch: name of the branch to pull | 6.123845 | 4.619765 | 1.325575 |
'''Clones a new repository
:param user: namespace of the repository
:param repo: name slug of the repository
:Param branch: branch to pull as tracking
This command is fairly simple, and pretty close to the real `git clone`
command, except it does not take a full path, b... | def clone(self, user, repo, branch=None, rw=True) | Clones a new repository
:param user: namespace of the repository
:param repo: name slug of the repository
:Param branch: branch to pull as tracking
This command is fairly simple, and pretty close to the real `git clone`
command, except it does not take a full path, but just a n... | 5.932664 | 3.034231 | 1.955245 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.