sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def unix_timestamp_to_datetime(unix_timestamp):
"""
<Purpose>
Convert 'unix_timestamp' (i.e., POSIX time, in UNIX_TIMESTAMP_SCHEMA format)
to a datetime.datetime() object. 'unix_timestamp' is the number of seconds
since the epoch (January 1, 1970.)
>>> datetime_object = unix_timestamp_to_datetime(... | <Purpose>
Convert 'unix_timestamp' (i.e., POSIX time, in UNIX_TIMESTAMP_SCHEMA format)
to a datetime.datetime() object. 'unix_timestamp' is the number of seconds
since the epoch (January 1, 1970.)
>>> datetime_object = unix_timestamp_to_datetime(1445455680)
>>> datetime_object
datetime.datetim... | entailment |
def format_base64(data):
"""
<Purpose>
Return the base64 encoding of 'data' with whitespace and '=' signs omitted.
<Arguments>
data:
Binary or buffer of data to convert.
<Exceptions>
securesystemslib.exceptions.FormatError, if the base64 encoding fails or the
argument is invalid.
<Sid... | <Purpose>
Return the base64 encoding of 'data' with whitespace and '=' signs omitted.
<Arguments>
data:
Binary or buffer of data to convert.
<Exceptions>
securesystemslib.exceptions.FormatError, if the base64 encoding fails or the
argument is invalid.
<Side Effects>
None.
<Returns>... | entailment |
def parse_base64(base64_string):
"""
<Purpose>
Parse a base64 encoding with whitespace and '=' signs omitted.
<Arguments>
base64_string:
A string holding a base64 value.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'base64_string' cannot be parsed
due to an invalid base64 enc... | <Purpose>
Parse a base64 encoding with whitespace and '=' signs omitted.
<Arguments>
base64_string:
A string holding a base64 value.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'base64_string' cannot be parsed
due to an invalid base64 encoding.
<Side Effects>
None.
<Re... | entailment |
def encode_canonical(object, output_function=None):
"""
<Purpose>
Encode 'object' in canonical JSON form, as specified at
http://wiki.laptop.org/go/Canonical_JSON . It's a restricted
dialect of JSON in which keys are always lexically sorted,
there is no whitespace, floats aren't allowed, and only q... | <Purpose>
Encode 'object' in canonical JSON form, as specified at
http://wiki.laptop.org/go/Canonical_JSON . It's a restricted
dialect of JSON in which keys are always lexically sorted,
there is no whitespace, floats aren't allowed, and only quote
and backslash get escaped. The result is encoded i... | entailment |
def process_error_labels(value):
""" Process the error labels of a dependent variable 'value' to ensure uniqueness. """
observed_error_labels = {}
for error in value.get('errors', []):
label = error.get('label', 'error')
if label not in observed_error_labels:
... | Process the error labels of a dependent variable 'value' to ensure uniqueness. | entailment |
def raw(text):
"""Returns a raw string representation of text"""
new_string = ''
for char in text:
try:
new_string += escape_dict[char]
except KeyError:
new_string += char
return new_string | Returns a raw string representation of text | entailment |
def get_winfunc(libname, funcname, restype=None, argtypes=(), _libcache={}):
"""Retrieve a function from a library/DLL, and set the data types."""
if libname not in _libcache:
_libcache[libname] = windll.LoadLibrary(libname)
func = getattr(_libcache[libname], funcname)
func.argtypes = argtypes
... | Retrieve a function from a library/DLL, and set the data types. | entailment |
def WinMSGLoop():
"""Run the main windows message loop."""
LPMSG = POINTER(MSG)
LRESULT = c_ulong
GetMessage = get_winfunc("user32", "GetMessageW", BOOL, (LPMSG, HWND, UINT, UINT))
TranslateMessage = get_winfunc("user32", "TranslateMessage", BOOL, (LPMSG,))
# restype = LRESULT
DispatchMessag... | Run the main windows message loop. | entailment |
def ConnectTo(self, appName, data=None):
"""Exceptional error is handled in zdde Init() method, so the exception
must be re-raised"""
global number_of_apps_communicating
self.ddeServerName = appName
try:
self.ddec = DDEClient(self.ddeServerName, self.ddeClientName) # ... | Exceptional error is handled in zdde Init() method, so the exception
must be re-raised | entailment |
def Request(self, item, timeout=None):
"""Request DDE client
timeout in seconds
Note ... handle the exception within this function.
"""
if not timeout:
timeout = self.ddetimeout
try:
reply = self.ddec.request(item, int(timeout*1000)) # convert time... | Request DDE client
timeout in seconds
Note ... handle the exception within this function. | entailment |
def advise(self, item, stop=False):
"""Request updates when DDE data changes."""
hszItem = DDE.CreateStringHandle(self._idInst, item, CP_WINUNICODE)
hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_ADVSTOP if stop else XTYP_ADVSTART, TIMEOUT_ASYNC, LPDWORD())
... | Request updates when DDE data changes. | entailment |
def execute(self, command):
"""Execute a DDE command."""
pData = c_char_p(command)
cbData = DWORD(len(command) + 1)
hDdeData = DDE.ClientTransaction(pData, cbData, self._hConv, HSZ(), CF_TEXT, XTYP_EXECUTE, TIMEOUT_ASYNC, LPDWORD())
if not hDdeData:
raise DDEError("Un... | Execute a DDE command. | entailment |
def request(self, item, timeout=5000):
"""Request data from DDE service."""
hszItem = DDE.CreateStringHandle(self._idInst, item, CP_WINUNICODE)
#hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_REQUEST, timeout, LPDWORD())
pdwResult = DWORD(0)
hDd... | Request data from DDE service. | entailment |
def _callback(self, wType, uFmt, hConv, hsz1, hsz2, hDdeData, dwData1, dwData2):
"""DdeCallback callback function for processing Dynamic Data Exchange (DDE)
transactions sent by DDEML in response to DDE events
Parameters
----------
wType : transaction type (UINT)
uFmt... | DdeCallback callback function for processing Dynamic Data Exchange (DDE)
transactions sent by DDEML in response to DDE events
Parameters
----------
wType : transaction type (UINT)
uFmt : clipboard data format (UINT)
hConv : handle to conversation (HCONV)
... | entailment |
def parse(self, data_in, *args, **kwargs):
"""
:param data_in: path to submission.yaml
:param args:
:param kwargs:
:raise ValueError:
"""
if not os.path.exists(data_in):
raise ValueError("File / Directory does not exist: %s" % data_in)
if os.p... | :param data_in: path to submission.yaml
:param args:
:param kwargs:
:raise ValueError: | entailment |
def generate_ai_request(
predict_rows,
req_dict=None,
req_file=ANTINEX_PUBLISH_REQUEST_FILE,
features=ANTINEX_FEATURES_TO_PROCESS,
ignore_features=ANTINEX_IGNORE_FEATURES,
sort_values=ANTINEX_SORT_VALUES,
ml_type=ANTINEX_ML_TYPE,
use_model_name=ANTINEX_USE... | generate_ai_request
:param predict_rows: list of predict rows to build into the request
:param req_dict: request dictionary to update - for long-running clients
:param req_file: file holding a request dict to update - one-off tests
:param features: features to process in the data
:param ignore_feat... | entailment |
def get_ml_job():
"""get_ml_job
Get an ``MLJob`` by database id.
"""
parser = argparse.ArgumentParser(
description=("Python client get AI Job by ID"))
parser.add_argument(
"-u",
help="username",
required=False,
dest="user")
parser.add_argument(
... | get_ml_job
Get an ``MLJob`` by database id. | entailment |
def get_molo_comments(parser, token):
"""
Get a limited set of comments for a given object.
Defaults to a limit of 5. Setting the limit to -1 disables limiting.
Set the amount of comments to
usage:
{% get_molo_comments for object as variable_name %}
{% get_molo_comments for object ... | Get a limited set of comments for a given object.
Defaults to a limit of 5. Setting the limit to -1 disables limiting.
Set the amount of comments to
usage:
{% get_molo_comments for object as variable_name %}
{% get_molo_comments for object as variable_name limit amount %}
{% get_mo... | entailment |
def get_comments_content_object(parser, token):
"""
Get a limited set of comments for a given object.
Defaults to a limit of 5. Setting the limit to -1 disables limiting.
usage:
{% get_comments_content_object for form_object as variable_name %}
"""
keywords = token.contents.split()
... | Get a limited set of comments for a given object.
Defaults to a limit of 5. Setting the limit to -1 disables limiting.
usage:
{% get_comments_content_object for form_object as variable_name %} | entailment |
def report(request, comment_id):
"""
Flags a comment on GET.
Redirects to whatever is provided in request.REQUEST['next'].
"""
comment = get_object_or_404(
django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)
if comment.parent is not None:
messages.info(reques... | Flags a comment on GET.
Redirects to whatever is provided in request.REQUEST['next']. | entailment |
def post_molo_comment(request, next=None, using=None):
"""
Allows for posting of a Molo Comment, this allows comments to
be set with the "user_name" as "Anonymous"
"""
data = request.POST.copy()
if 'submit_anonymously' in data:
data['name'] = 'Anonymous'
# replace with our changed PO... | Allows for posting of a Molo Comment, this allows comments to
be set with the "user_name" as "Anonymous" | entailment |
def build_ai_client_from_env(
verbose=ANTINEX_CLIENT_VERBOSE,
debug=ANTINEX_CLIENT_DEBUG,
ca_dir=None,
cert_file=None,
key_file=None):
"""build_ai_client_from_env
Use environment variables to build a client
:param verbose: verbose logging
:param debug: debug int... | build_ai_client_from_env
Use environment variables to build a client
:param verbose: verbose logging
:param debug: debug internal client calls
:param ca_dir: optional path to CA bundle dir
:param cert_file: optional path to x509 ssl cert file
:param key_file: optional path to x509 ssl key file | entailment |
def train_new_deep_neural_network():
"""train_new_deep_neural_network
Train a new deep neural network and store the results as a new:
``MLJob`` and ``MLJobResult`` database records.
"""
parser = argparse.ArgumentParser(
description=(
"Python client to Train a Deep Neural Netwo... | train_new_deep_neural_network
Train a new deep neural network and store the results as a new:
``MLJob`` and ``MLJobResult`` database records. | entailment |
def prepare_new_dataset():
"""prepare_new_dataset
Prepare a new ``MLPrepare`` record and dataset files on disk.
"""
parser = argparse.ArgumentParser(
description=(
"Python client to Prepare a dataset"))
parser.add_argument(
"-u",
help="username",
requir... | prepare_new_dataset
Prepare a new ``MLPrepare`` record and dataset files on disk. | entailment |
def drape(raster, feature):
"""Convert a 2D feature to a 3D feature by sampling a raster
Parameters:
raster (rasterio): raster to provide the z coordinate
feature (dict): fiona feature record to convert
Returns:
result (Point or Linestring): shapely Point or LineString of xyz coord... | Convert a 2D feature to a 3D feature by sampling a raster
Parameters:
raster (rasterio): raster to provide the z coordinate
feature (dict): fiona feature record to convert
Returns:
result (Point or Linestring): shapely Point or LineString of xyz coordinate triples | entailment |
def sample(raster, coords):
"""Sample a raster at given coordinates
Given a list of coordinates, return a list of x,y,z triples with z coordinates sampled from an input raster
Parameters:
raster (rasterio): raster dataset to sample
coords: array of tuples containing coordinate pairs (x,y) ... | Sample a raster at given coordinates
Given a list of coordinates, return a list of x,y,z triples with z coordinates sampled from an input raster
Parameters:
raster (rasterio): raster dataset to sample
coords: array of tuples containing coordinate pairs (x,y) or triples (x,y,z)
Returns:
... | entailment |
def setup_logging(
default_level=logging.INFO,
default_path="{}/logging.json".format(
os.getenv(
"LOG_DIR",
os.path.dirname(os.path.realpath(__file__)))),
env_key="LOG_CFG",
config_name=None):
"""setup_logging
Setup logging configurati... | setup_logging
Setup logging configuration
:param default_level: level to log
:param default_path: path to config (optional)
:param env_key: path to config in this env var
:param config_name: filename for config | entailment |
def build_logger(
name=os.getenv(
"LOG_NAME",
"client"),
config="logging.json",
log_level=logging.INFO,
log_config_path="{}/logging.json".format(
os.getenv(
"LOG_CFG",
os.path.dirname(os.path.realpath(__file__))))):
"""build_logger
:param name: na... | build_logger
:param name: name that shows in the logger
:param config: name of the config file
:param log_level: level to log
:param log_config_path: path to log config file | entailment |
def build_colorized_logger(
name=os.getenv(
"LOG_NAME",
"client"),
config="colors-logging.json",
log_level=logging.INFO,
log_config_path="{}/logging.json".format(
os.getenv(
"LOG_CFG",
os.path.dirname(os.path.realpath(__file__))))):
"""build_colorized_... | build_colorized_logger
:param name: name that shows in the logger
:param config: name of the config file
:param log_level: level to log
:param log_config_path: path to log config file | entailment |
def authenticate(self, request: HttpRequest, auth_route: str, actual_params: dict) -> bool:
"""
Your AuhtService should override this method for request authentication, otherwise means no authentication.
:param request: HttpRequest Django's HttpRequest object
:param auth_route: str User'... | Your AuhtService should override this method for request authentication, otherwise means no authentication.
:param request: HttpRequest Django's HttpRequest object
:param auth_route: str User's resqueted route
:param actual_params: User's url parameters
:return: bool | entailment |
def cli(source_f, raster_f, output, verbose):
"""
Converts 2D geometries to 3D using GEOS sample through fiona.
\b
Example:
drape point.shp elevation.tif -o point_z.shp
"""
with fiona.open(source_f, 'r') as source:
source_driver = source.driver
source_crs = source.crs
... | Converts 2D geometries to 3D using GEOS sample through fiona.
\b
Example:
drape point.shp elevation.tif -o point_z.shp | entailment |
def for_model(self, model):
"""
QuerySet for all comments for a particular model (either an instance or
a class).
"""
ct = ContentType.objects.get_for_model(model)
qs = self.get_queryset().filter(content_type=ct)
if isinstance(model, models.Model):
qs ... | QuerySet for all comments for a particular model (either an instance or
a class). | entailment |
def eval(self, command):
'Blocking call, returns the value of the execution in JS'
event = threading.Event()
# TODO: Add event to server
#job_id = str(id(command))
import random
job_id = str(random.random())
server.EVALUATIONS[job_id] = event
message = '?... | Blocking call, returns the value of the execution in JS | entailment |
def register(self, callback, name):
'Register a callback on server and on connected clients.'
server.CALLBACKS[name] = callback
self.run('''
window.skink.%s = function(args=[]) {
window.skink.call("%s", args);
}''' % (name, name)) | Register a callback on server and on connected clients. | entailment |
def launch_exception(message):
"""
Launch a Python exception from an error that took place in the browser.
messsage format:
- name: str
- description: str
"""
error_name = message['name']
error_descr = message['description']
mapping = {
'ReferenceError': Name... | Launch a Python exception from an error that took place in the browser.
messsage format:
- name: str
- description: str | entailment |
def start_predictions():
"""start_predictions
Using environment variables, create an AntiNex AI Client.
You can also use command line args if you want.
This can train a new deep neural network if it does not
exist or it can use an existing pre-trained deep neural
network within the AntiNex Cor... | start_predictions
Using environment variables, create an AntiNex AI Client.
You can also use command line args if you want.
This can train a new deep neural network if it does not
exist or it can use an existing pre-trained deep neural
network within the AntiNex Core to make new predictions. | entailment |
def login(
self):
"""login"""
auth_url = self.api_urls["login"]
if self.verbose:
log.info(("log in user={} url={} ca_dir={} cert={}")
.format(
self.user,
auth_url,
self.ca_dir,
... | login | entailment |
def build_response(
self,
status=NOT_SET,
error="",
data=None):
"""build_response
:param status: status code
:param error: error message
:param data: dictionary to send back
"""
res_node = {
"status": status,
... | build_response
:param status: status code
:param error: error message
:param data: dictionary to send back | entailment |
def retry_login(
self):
"""retry_login"""
if not self.user or not self.password:
return self.build_response(
status=ERROR,
error="please set the user and password")
retry = 0
not_done = True
while not_done:
if ... | retry_login | entailment |
def get_prepare_by_id(
self,
prepare_id=None):
"""get_prepare_by_id
:param prepare_id: MLJob.id in the database
"""
if not prepare_id:
log.error("missing prepare_id for get_prepare_by_id")
return self.build_response(
statu... | get_prepare_by_id
:param prepare_id: MLJob.id in the database | entailment |
def wait_for_job_to_finish(
self,
job_id,
sec_to_sleep=5.0,
max_retries=100000):
"""wait_for_job_to_finish
:param job_id: MLJob.id to wait on
:param sec_to_sleep: seconds to sleep during polling
:param max_retries: max retires until stoppi... | wait_for_job_to_finish
:param job_id: MLJob.id to wait on
:param sec_to_sleep: seconds to sleep during polling
:param max_retries: max retires until stopping | entailment |
def wait_for_prepare_to_finish(
self,
prepare_id,
sec_to_sleep=5.0,
max_retries=100000):
"""wait_for_prepare_to_finish
:param prepare_id: MLPrepare.id to wait on
:param sec_to_sleep: seconds to sleep during polling
:param max_retries: max ... | wait_for_prepare_to_finish
:param prepare_id: MLPrepare.id to wait on
:param sec_to_sleep: seconds to sleep during polling
:param max_retries: max retires until stopping | entailment |
def get_comment_object(self):
"""
NB: Overridden to remove dupe comment check for admins (necessary for
canned responses)
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError i... | NB: Overridden to remove dupe comment check for admins (necessary for
canned responses)
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields tha... | entailment |
def boot(app_name) -> Rinzler:
"""
Start Rinzler App
:param app_name: str Application's identifier
:return: dict
"""
app = Rinzler(app_name)
app.log.info("App booted =)")
return app | Start Rinzler App
:param app_name: str Application's identifier
:return: dict | entailment |
def mount(self, route: str, controller: callable) -> url:
"""
Maps a route namespace with the given params and point it's requests to the especified controller.
:param route: str Namespace route to be mapped
:param controller: callback Controller callable to map end-points
:rtype... | Maps a route namespace with the given params and point it's requests to the especified controller.
:param route: str Namespace route to be mapped
:param controller: callback Controller callable to map end-points
:rtype: url | entailment |
def set_auth_service(self, auth_service: BaseAuthService):
"""
Sets the authentication service
:param auth_service: BaseAuthService Authentication service
:raises: TypeError If the auth_service object is not a subclass of rinzler.auth.BaseAuthService
:rtype: Rinzler
"""
... | Sets the authentication service
:param auth_service: BaseAuthService Authentication service
:raises: TypeError If the auth_service object is not a subclass of rinzler.auth.BaseAuthService
:rtype: Rinzler | entailment |
def handle(self, request: HttpRequest) -> HttpResponse:
"""
Prepares for the CallBackResolver and handles the response and exceptions
:param request HttpRequest
:rtype: HttpResponse
"""
self.__request_start = datetime.now()
self.__request = request
self.__... | Prepares for the CallBackResolver and handles the response and exceptions
:param request HttpRequest
:rtype: HttpResponse | entailment |
def exec_route_callback(self) -> Response or object:
"""
Executes the resolved end-point callback, or its fallback
:rtype: Response or object
"""
if self.__method.lower() in self.__end_points:
for bound in self.__end_points[self.__method.lower()]:
rou... | Executes the resolved end-point callback, or its fallback
:rtype: Response or object | entailment |
def request_matches_route(self, actual_route: str, expected_route: str):
"""
Determines whether a route matches the actual requested route or not
:param actual_route str
:param expected_route
:rtype: Boolean
"""
expected_params = self.get_url_params(expected_route... | Determines whether a route matches the actual requested route or not
:param actual_route str
:param expected_route
:rtype: Boolean | entailment |
def authenticate(self, bound_route, actual_params) -> bool:
"""
Runs the pre-defined authenticaton service
:param bound_route str route matched
:param actual_params dict actual url parameters
:rtype: bool
"""
if self.__auth_service is not None:
auth_ro... | Runs the pre-defined authenticaton service
:param bound_route str route matched
:param actual_params dict actual url parameters
:rtype: bool | entailment |
def get_callback_pattern(expected_params, actual_params):
"""
Assembles a dictionary whith the parameters schema defined for this route
:param expected_params dict parameters schema defined for this route
:param actual_params dict actual url parameters
:rtype: dict
"""
... | Assembles a dictionary whith the parameters schema defined for this route
:param expected_params dict parameters schema defined for this route
:param actual_params dict actual url parameters
:rtype: dict | entailment |
def get_url_params(end_point: str) -> list:
"""
Gets route parameters as dictionary
:param end_point str target route
:rtype: list
"""
var_params = end_point.split('/')
if len(var_params) == 1 and var_params[0] == '':
return []
elif len(var_p... | Gets route parameters as dictionary
:param end_point str target route
:rtype: list | entailment |
def set_end_point_uri(self) -> bool:
"""
Extracts the route from the accessed URL and sets it to __end_point_uri
:rtype: bool
"""
expected_parts = self.__route.split("/")
actual_parts = self.__uri.split("/")
i = 0
for part in expected_parts:
i... | Extracts the route from the accessed URL and sets it to __end_point_uri
:rtype: bool | entailment |
def no_route_found(self, request):
"""
Default callback for route not found
:param request HttpRequest
:rtype: Response
"""
response_obj = OrderedDict()
response_obj["status"] = False
response_obj["exceptions"] = {
"message": "No route found fo... | Default callback for route not found
:param request HttpRequest
:rtype: Response | entailment |
def welcome_page(self):
"""
Defaulf welcome page when the route / is note mapped yet
:rtype: HttpResponse
"""
message = "HTTP/1.1 200 OK RINZLER FRAMEWORK"
return HttpResponse(
"<center><h1>{0}({1})</h1></center>".format(message, self.app.app_name),
... | Defaulf welcome page when the route / is note mapped yet
:rtype: HttpResponse | entailment |
def default_route_options():
"""
Default callback for OPTIONS request
:rtype: Response
"""
response_obj = OrderedDict()
response_obj["status"] = True
response_obj["data"] = "Ok"
return Response(response_obj, content_type="application/json", charset="utf-... | Default callback for OPTIONS request
:rtype: Response | entailment |
def set_response_headers(self, response: HttpResponse) -> HttpResponse:
"""
Appends default headers to every response returned by the API
:param response HttpResponse
:rtype: HttpResponse
"""
public_name = os.environ.get('SERVER_PUBLIC_NAME')
response_headers = {
... | Appends default headers to every response returned by the API
:param response HttpResponse
:rtype: HttpResponse | entailment |
def get_json_ident(request_headers: dict) -> int:
"""
Defines whether the JSON response will be indented or not
:param request_headers: dict
:return: self
"""
if 'HTTP_USER_AGENT' in request_headers:
indent = 2 if re.match("[Mozilla]{7}", request_headers['HTTP... | Defines whether the JSON response will be indented or not
:param request_headers: dict
:return: self | entailment |
def prop(key, dct_or_obj):
"""
Implementation of prop (get_item) that also supports object attributes
:param key:
:param dct_or_obj:
:return:
"""
# Note that hasattr is a builtin and getattr is a ramda function, hence the different arg position
if isinstance(dict, dct_or_obj):
... | Implementation of prop (get_item) that also supports object attributes
:param key:
:param dct_or_obj:
:return: | entailment |
def all_pass_dict(f, dct):
"""
Returns true if all dct values pass f
:param f: binary lambda predicate
:param dct:
:return: True or false
"""
return all(map_with_obj_to_values(
lambda key, value: f(key, value),
dct
)) | Returns true if all dct values pass f
:param f: binary lambda predicate
:param dct:
:return: True or false | entailment |
def prop_or(default, key, dct_or_obj):
"""
Ramda propOr implementation. This also resolves object attributes, so key
can be a dict prop or an attribute of dct_or_obj
:param default: Value if dct_or_obj doesn't have key_or_prop or the resolved value is null
:param key:
:param dct_or_obj:
... | Ramda propOr implementation. This also resolves object attributes, so key
can be a dict prop or an attribute of dct_or_obj
:param default: Value if dct_or_obj doesn't have key_or_prop or the resolved value is null
:param key:
:param dct_or_obj:
:return: | entailment |
def prop_eq_or(default, key, value, dct):
"""
Ramda propEq plus propOr implementation
:param default:
:param key:
:param value:
:param dct:
:return:
"""
return dct[key] and dct[key] == value if key in dct else default | Ramda propEq plus propOr implementation
:param default:
:param key:
:param value:
:param dct:
:return: | entailment |
def prop_eq_or_in_or(default, key, value, dct):
"""
Ramda propEq/propIn plus propOr
:param default:
:param key:
:param value:
:param dct:
:return:
"""
return has(key, dct) and \
(dct[key] == value if key in dct else (
dct[key] in value if isinstance((lis... | Ramda propEq/propIn plus propOr
:param default:
:param key:
:param value:
:param dct:
:return: | entailment |
def item_path_or(default, keys, dict_or_obj):
"""
Optional version of item_path with a default value. keys can be dict keys or object attributes, or a combination
:param default:
:param keys: List of keys or dot-separated string
:param dict_or_obj: A dict or obj
:return:
"""
if not keys:... | Optional version of item_path with a default value. keys can be dict keys or object attributes, or a combination
:param default:
:param keys: List of keys or dot-separated string
:param dict_or_obj: A dict or obj
:return: | entailment |
def item_str_path(keys, dct):
"""
Given a string of path segments separated by ., splits them into an array. Int strings are converted
to numbers to serve as an array index
:param keys: e.g. 'foo.bar.1.goo'
:param dct: e.g. dict(foo=dict(bar=[dict(goo='a'), dict(goo='b')])
:return: The r... | Given a string of path segments separated by ., splits them into an array. Int strings are converted
to numbers to serve as an array index
:param keys: e.g. 'foo.bar.1.goo'
:param dct: e.g. dict(foo=dict(bar=[dict(goo='a'), dict(goo='b')])
:return: The resolved value or an error. E.g. for above the ... | entailment |
def item_str_path_or(default, keys, dct):
"""
Given a string of path segments separated by ., splits them into an array. Int strings are converted
to numbers to serve as an array index
:param default: Value if any part yields None or undefined
:param keys: e.g. 'foo.bar.1.goo'
:param dct... | Given a string of path segments separated by ., splits them into an array. Int strings are converted
to numbers to serve as an array index
:param default: Value if any part yields None or undefined
:param keys: e.g. 'foo.bar.1.goo'
:param dct: e.g. dict(foo=dict(bar=[dict(goo='a'), dict(goo='b')])
... | entailment |
def has(prop, object_or_dct):
"""
Implementation of ramda has
:param prop:
:param object_or_dct:
:return:
"""
return prop in object_or_dct if isinstance(dict, object_or_dct) else hasattr(object_or_dct, prop) | Implementation of ramda has
:param prop:
:param object_or_dct:
:return: | entailment |
def omit_deep(omit_props, dct):
"""
Implementation of omit that recurses. This tests the same keys at every level of dict and in lists
:param omit_props:
:param dct:
:return:
"""
omit_partial = omit_deep(omit_props)
if isinstance(dict, dct):
# Filter out keys and then recurse o... | Implementation of omit that recurses. This tests the same keys at every level of dict and in lists
:param omit_props:
:param dct:
:return: | entailment |
def pick_deep(pick_dct, dct):
"""
Implementation of pick that recurses. This tests the same keys at every level of dict and in lists
:param pick_dct: Deep dict matching some portion of dct.
:param dct: Dct to filter. Any key matching pick_dct pass through. It doesn't matter what the pick_dct value
i... | Implementation of pick that recurses. This tests the same keys at every level of dict and in lists
:param pick_dct: Deep dict matching some portion of dct.
:param dct: Dct to filter. Any key matching pick_dct pass through. It doesn't matter what the pick_dct value
is as long as the key exists. Arrays also p... | entailment |
def map_with_obj_deep(f, dct):
"""
Implementation of map that recurses. This tests the same keys at every level of dict and in lists
:param f: 2-ary function expecting a key and value and returns a modified value
:param dct: Dict for deep processing
:return: Modified dct with matching props mapped
... | Implementation of map that recurses. This tests the same keys at every level of dict and in lists
:param f: 2-ary function expecting a key and value and returns a modified value
:param dct: Dict for deep processing
:return: Modified dct with matching props mapped | entailment |
def map_keys_deep(f, dct):
"""
Implementation of map that recurses. This tests the same keys at every level of dict and in lists
:param f: 2-ary function expecting a key and value and returns a modified key
:param dct: Dict for deep processing
:return: Modified dct with matching props mapped
"""... | Implementation of map that recurses. This tests the same keys at every level of dict and in lists
:param f: 2-ary function expecting a key and value and returns a modified key
:param dct: Dict for deep processing
:return: Modified dct with matching props mapped | entailment |
def _map_deep(f, dct):
"""
Used by map_deep and map_keys_deep
:param map_props:
:param f: Expects a key and value and returns a pair
:param dct:
:return:
"""
if isinstance(dict, dct):
return map_key_values(lambda k, v: f(k, _map_deep(f, v)), dct)
elif isinstance((list, tuple... | Used by map_deep and map_keys_deep
:param map_props:
:param f: Expects a key and value and returns a pair
:param dct:
:return: | entailment |
def dict_matches_params_deep(params_dct, dct):
"""
Filters deeply by comparing dct to filter_dct's value at each depth. Whenever a mismatch occurs the whole
thing returns false
:param params_dct: dict matching any portion of dct. E.g. filter_dct = {foo: {bar: 1}} would allow
{foo: {bar: 1, car: 2}} ... | Filters deeply by comparing dct to filter_dct's value at each depth. Whenever a mismatch occurs the whole
thing returns false
:param params_dct: dict matching any portion of dct. E.g. filter_dct = {foo: {bar: 1}} would allow
{foo: {bar: 1, car: 2}} to pass, {foo: {bar: 2}} would fail, {goo: ...} would fail
... | entailment |
def join(strin, items):
"""
Ramda implementation of join
:param strin:
:param items:
:return:
"""
return strin.join(map(lambda item: str(item), items)) | Ramda implementation of join
:param strin:
:param items:
:return: | entailment |
def map_with_obj(f, dct):
"""
Implementation of Ramda's mapObjIndexed without the final argument.
This returns the original key with the mapped value. Use map_key_values to modify the keys too
:param f: Called with a key and value
:param dct:
:return {dict}: Keyed by the original key, va... | Implementation of Ramda's mapObjIndexed without the final argument.
This returns the original key with the mapped value. Use map_key_values to modify the keys too
:param f: Called with a key and value
:param dct:
:return {dict}: Keyed by the original key, valued by the mapped value | entailment |
def map_keys(f, dct):
"""
Calls f with each key of dct, possibly returning a modified key. Values are unchanged
:param f: Called with each key and returns the same key or a modified key
:param dct:
:return: A dct with keys possibly modifed but values unchanged
"""
f_dict = {}
for k, ... | Calls f with each key of dct, possibly returning a modified key. Values are unchanged
:param f: Called with each key and returns the same key or a modified key
:param dct:
:return: A dct with keys possibly modifed but values unchanged | entailment |
def map_keys_with_obj(f, dct):
"""
Calls f with each key and value of dct, possibly returning a modified key. Values are unchanged
:param f: Called with each key and value and returns the same key or a modified key
:param dct:
:return: A dct with keys possibly modifed but values unchanged
""... | Calls f with each key and value of dct, possibly returning a modified key. Values are unchanged
:param f: Called with each key and value and returns the same key or a modified key
:param dct:
:return: A dct with keys possibly modifed but values unchanged | entailment |
def merge_deep(dct1, dct2, merger=None):
"""
Deep merge by this spec below
:param dct1:
:param dct2:
:param merger Optional merger
:return:
"""
my_merger = merger or Merger(
# pass in a list of tuples,with the
# strategies you are looking to apply
# to each ty... | Deep merge by this spec below
:param dct1:
:param dct2:
:param merger Optional merger
:return: | entailment |
def merge_all(dcts):
"""
Shallow merge all the dcts
:param dcts:
:return:
"""
return reduce(
lambda accum, dct: merge(accum, dct),
dict(),
dcts
) | Shallow merge all the dcts
:param dcts:
:return: | entailment |
def from_pairs_to_array_values(pairs):
"""
Like from pairs but combines duplicate key values into arrays
:param pairs:
:return:
"""
result = {}
for pair in pairs:
result[pair[0]] = concat(prop_or([], pair[0], result), [pair[1]])
return result | Like from pairs but combines duplicate key values into arrays
:param pairs:
:return: | entailment |
def map_prop_value_as_index(prp, lst):
"""
Returns the given prop of each item in the list
:param prp:
:param lst:
:return:
"""
return from_pairs(map(lambda item: (prop(prp, item), item), lst)) | Returns the given prop of each item in the list
:param prp:
:param lst:
:return: | entailment |
def key_string_to_lens_path(key_string):
"""
Converts a key string like 'foo.bar.0.wopper' to ['foo', 'bar', 0, 'wopper']
:param {String} keyString The dot-separated key string
:return {[String]} The lens array containing string or integers
"""
return map(
if_else(
isinstance(int)... | Converts a key string like 'foo.bar.0.wopper' to ['foo', 'bar', 0, 'wopper']
:param {String} keyString The dot-separated key string
:return {[String]} The lens array containing string or integers | entailment |
def fake_lens_path_view(lens_path, obj):
"""
Simulates R.view with a lens_path since we don't have lens functions
:param lens_path: Array of string paths
:param obj: Object containing the given path
:return: The value at the path or None
"""
segment = head(lens_path)
return if_else(
... | Simulates R.view with a lens_path since we don't have lens functions
:param lens_path: Array of string paths
:param obj: Object containing the given path
:return: The value at the path or None | entailment |
def fake_lens_path_set(lens_path, value, obj):
"""
Simulates R.set with a lens_path since we don't have lens functions
:param lens_path: Array of string paths
:param value: The value to set at the lens path
:param obj: Object containing the given path
:return: The value at the path or None
"... | Simulates R.set with a lens_path since we don't have lens functions
:param lens_path: Array of string paths
:param value: The value to set at the lens path
:param obj: Object containing the given path
:return: The value at the path or None | entailment |
def unflatten_dct(obj):
"""
Undoes the work of flatten_dict
@param {Object} obj 1-D object in the form returned by flattenObj
@returns {Object} The original
:param obj:
:return:
"""
def reduce_func(accum, key_string_and_value):
key_string = key_string_and_value[0]
val... | Undoes the work of flatten_dict
@param {Object} obj 1-D object in the form returned by flattenObj
@returns {Object} The original
:param obj:
:return: | entailment |
def ppj(json_data):
"""ppj
:param json_data: dictionary to print
"""
return str(json.dumps(
json_data,
sort_keys=True,
indent=4,
separators=(',', ': '))) | ppj
:param json_data: dictionary to print | entailment |
def change_view(self, request, object_id, form_url='', extra_context=None):
"""
Override change view to add extra context enabling moderate tool.
"""
context = {
'has_moderate_tool': True
}
if extra_context:
context.update(extra_context)
re... | Override change view to add extra context enabling moderate tool. | entailment |
def get_urls(self):
"""
Add aditional moderate url.
"""
from django.conf.urls import url
urls = super(AdminModeratorMixin, self).get_urls()
info = self.model._meta.app_label, self.model._meta.model_name
return [
url(r'^(.+)/moderate/$',
... | Add aditional moderate url. | entailment |
def render(self, indent=0):
"""
Renders a HttpResponse for the ongoing request
:param indent int
:rtype: HttpResponse
"""
self.__indent = indent
return HttpResponse(
str(self), content_type=self.__content_type, charset=self.__charset, **self.__kwargs
... | Renders a HttpResponse for the ongoing request
:param indent int
:rtype: HttpResponse | entailment |
def setup_logging(default_path='logging.yaml', env_key='LOG_CFG'):
"""
Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
configs = yaml.safe_load(f.read(... | Setup logging configuration | entailment |
def get(self, route: str(), callback: object()):
"""
Binds a GET route with the given callback
:rtype: object
"""
self.__set_route('get', {route: callback})
return RouteMapping | Binds a GET route with the given callback
:rtype: object | entailment |
def post(self, route: str(), callback: object()):
"""
Binds a POST route with the given callback
:rtype: object
"""
self.__set_route('post', {route: callback})
return RouteMapping | Binds a POST route with the given callback
:rtype: object | entailment |
def put(self, route: str(), callback: object()):
"""
Binds a PUT route with the given callback
:rtype: object
"""
self.__set_route('put', {route: callback})
return RouteMapping | Binds a PUT route with the given callback
:rtype: object | entailment |
def patch(self, route: str(), callback: object()):
"""
Binds a PATCH route with the given callback
:rtype: object
"""
self.__set_route('patch', {route: callback})
return RouteMapping | Binds a PATCH route with the given callback
:rtype: object | entailment |
def delete(self, route: str(), callback: object()):
"""
Binds a PUT route with the given callback
:rtype: object
"""
self.__set_route('delete', {route: callback})
return RouteMapping | Binds a PUT route with the given callback
:rtype: object | entailment |
def head(self, route: str(), callback: object()):
"""
Binds a HEAD route with the given callback
:rtype: object
"""
self.__set_route('head', {route: callback})
return RouteMapping | Binds a HEAD route with the given callback
:rtype: object | entailment |
def options(self, route: str(), callback: object()):
"""
Binds a OPTIONS route with the given callback
:rtype: object
"""
self.__set_route('options', {route: callback})
return RouteMapping | Binds a OPTIONS route with the given callback
:rtype: object | entailment |
def __set_route(self, type_route, route):
"""
Sets the given type_route and route to the route mapping
:rtype: object
"""
if type_route in self.__routes:
if not self.verify_route_already_bound(type_route, route):
self.__routes[type_route].append(route)... | Sets the given type_route and route to the route mapping
:rtype: object | entailment |
def operating_system():
"""Return a string identifying the operating system the application
is running on.
:rtype: str
"""
if platform.system() == 'Darwin':
return 'OS X Version %s' % platform.mac_ver()[0]
distribution = ' '.join(platform.linux_distribution()).strip()
os_platform =... | Return a string identifying the operating system the application
is running on.
:rtype: str | entailment |
def start(self):
"""Daemonize if the process is not already running."""
if self._is_already_running():
LOGGER.error('Is already running')
sys.exit(1)
try:
self._daemonize()
self.controller.start()
except Exception as error:
sys.... | Daemonize if the process is not already running. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.