repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/message_request.py | GetReadGroupChatUserIdsRequest.get_read_user_ids | python | def get_read_user_ids(self):
"""Method to get chatid of group created."""
read_user_ids = self.json_response.get("readUserIdList", None)
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return read_user_ids | Method to get chatid of group created. | train | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/message_request.py#L192-L196 | null | class GetReadGroupChatUserIdsRequest(BaseRequest):
"""
Description: The GetReadGroupChatUserIdsRequest aims to get the user id
list of whom has read message by messageId
parameter_R: <access_token>, <messageId>, <cursor>, <size>
parameter_O: None
post_data_R: <chatid>, <msg>
post_data_O: N... |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/user_request.py | DeptUserRequest.get_userinfo | python | def get_userinfo(self):
"""Method to get current user's name, mobile, email and position."""
wanted_fields = ["name", "mobile", "orgEmail", "position", "avatar"]
userinfo = {k: self.json_response.get(k, None) for k in wanted_fields}
return userinfo | Method to get current user's name, mobile, email and position. | train | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/user_request.py#L30-L34 | null | class DeptUserRequest(BaseRequest):
"""
Description: The response of DeptUserRequest contains a department member's
detail information specified by userid
parameter_R: <access_token>, <userid>
parameter_O: None
post_data_R: None
post_data_O: None
Return: a department member's detail i... |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/user_request.py | AdminUsersRequest.get_admin_ids | python | def get_admin_ids(self):
"""Method to get the administrator id list."""
admins = self.json_response.get("admin_list", None)
admin_ids = [admin_id for admin_id in admins["userid"]]
return admin_ids | Method to get the administrator id list. | train | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/user_request.py#L54-L58 | null | class AdminUsersRequest(BaseRequest):
"""
Description: The response of AdminUsersRequest contains all admin user's id
list
parameter_R: <access_token>
parameter_O: None
post_data_R: None
post_data_O: None
Return: admin user's id list
doc_links: https://open-doc.dingtalk.com/micro... |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/department_request.py | DeptRequest.get_dept_name | python | def get_dept_name(self):
"""Method to get the department name"""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("name", None) | Method to get the department name | train | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L22-L25 | null | class DeptRequest(BaseRequest):
"""
Description: The response of DeptRequest contains detail of specified
department by parameter <id>
parameter_R: <access_token>, <id> (department_id)
parameter_O: None
post_data_R: None
post_data_O: None
Return: all information fields for specified d... |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/department_request.py | DeptRequest.get_dept_manager_ids | python | def get_dept_manager_ids(self):
"""Method to get the id list of department manager."""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("deptManagerUseridList", None) | Method to get the id list of department manager. | train | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L27-L30 | null | class DeptRequest(BaseRequest):
"""
Description: The response of DeptRequest contains detail of specified
department by parameter <id>
parameter_R: <access_token>, <id> (department_id)
parameter_O: None
post_data_R: None
post_data_O: None
Return: all information fields for specified d... |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/department_request.py | DeptsRequest.get_depts | python | def get_depts(self, dept_name=None):
"""Method to get department by name."""
depts = self.json_response.get("department", None)
params = self.kwargs.get("params", None)
fetch_child = params.get("fetch_child", True) if params else True
if dept_name is not None:
d... | Method to get department by name. | train | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L52-L61 | null | class DeptsRequest(BaseRequest):
"""
Description: The response of DeptsRequest contains a department list, but
each element just contain the main fields of id, name, parentid,
createDeptGroup and autoAddUser. fetch_child (Bool, default is True,
it decides whether recursively response the sub-departm... |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/department_request.py | SubDeptIdsRequest.get_sub_dept_ids | python | def get_sub_dept_ids(self):
"""Method to get the department list"""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("sub_dept_id_list", None) | Method to get the department list | train | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L81-L84 | null | class SubDeptIdsRequest(BaseRequest):
"""
Description: The response of SubDeptIdsRequest contains the id list of sub
department for specified department by id
parameter_R: <access_token>, <id> (department_id)
parameter_O: None
post_data_R: None
post_data_O: None
Return: the id list of... |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/department_request.py | ParentDeptPathRequest.get_parent_dept_path | python | def get_parent_dept_path(self):
"""Method to get the department list"""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("parentIds", None) | Method to get the department list | train | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L105-L108 | null | class ParentDeptPathRequest(BaseRequest):
"""
Description: The response of ParentDeptPathRequest aimed at showing the
department tree reversely, the path, i.e, find the path from the initial
leaf node to the root node.
parameter_R: <access_token>, <id> (department_id)
parameter_O: None
pos... |
praekeltfoundation/seed-message-sender | message_sender/factory.py | GenericHttpApiSender._get_filename | python | def _get_filename(self, path):
match = re.search("[a-z]{2,3}_[A-Z]{2}", path)
if match:
start = match.start(0)
filename = path[start:]
else:
filename = os.path.basename(path)
return filename | This function gets the base filename from the path, if a language code
is present the filename will start from there. | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/factory.py#L72-L85 | null | class GenericHttpApiSender(VumiHttpApiSender):
def __init__(
self,
url,
auth=None,
from_addr=None,
session=None,
override_payload=None,
strip_filepath=False,
):
"""
:param url str: The URL for the HTTP API channel
:param auth tuple:... |
praekeltfoundation/seed-message-sender | message_sender/factory.py | GenericHttpApiSender._override_payload | python | def _override_payload(self, payload):
if self.override_payload:
old_payload = payload
def get_value(data, key):
try:
parent_key, nested_key = key.split(".", 1)
return get_value(data.get(parent_key, {}), nested_key)
... | This function transforms the payload into a new format using the
self.override_payload property. | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/factory.py#L123-L148 | null | class GenericHttpApiSender(VumiHttpApiSender):
def __init__(
self,
url,
auth=None,
from_addr=None,
session=None,
override_payload=None,
strip_filepath=False,
):
"""
:param url str: The URL for the HTTP API channel
:param auth tuple:... |
praekeltfoundation/seed-message-sender | message_sender/factory.py | WhatsAppApiSender.fire_failed_contact_lookup | python | def fire_failed_contact_lookup(self, msisdn):
payload = {"address": msisdn}
# We cannot user the raw_hook_event here, because we don't have a user, so we
# manually filter and send the hooks for all users
hooks = Hook.objects.filter(event="whatsapp.failed_contact_check")
for hook... | Fires a webhook in the event of a failed WhatsApp contact lookup. | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/factory.py#L321-L332 | null | class WhatsAppApiSender(object):
def __init__(
self, api_url, token, hsm_namespace, hsm_element_name, ttl, session=None
):
self.api_url = api_url
self.token = token
self.hsm_namespace = hsm_namespace
self.hsm_element_name = hsm_element_name
self.ttl = ttl
... |
praekeltfoundation/seed-message-sender | message_sender/factory.py | WhatsAppApiSender.get_contact | python | def get_contact(self, msisdn):
response = self.session.post(
urllib_parse.urljoin(self.api_url, "/v1/contacts"),
json={"blocking": "wait", "contacts": [msisdn]},
)
response.raise_for_status()
whatsapp_id = response.json()["contacts"][0].get("wa_id")
if not... | Returns the WhatsApp ID for the given MSISDN | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/factory.py#L334-L346 | [
"def fire_failed_contact_lookup(self, msisdn):\n \"\"\"\n Fires a webhook in the event of a failed WhatsApp contact lookup.\n \"\"\"\n payload = {\"address\": msisdn}\n # We cannot user the raw_hook_event here, because we don't have a user, so we\n # manually filter and send the hooks for all user... | class WhatsAppApiSender(object):
def __init__(
self, api_url, token, hsm_namespace, hsm_element_name, ttl, session=None
):
self.api_url = api_url
self.token = token
self.hsm_namespace = hsm_namespace
self.hsm_element_name = hsm_element_name
self.ttl = ttl
... |
praekeltfoundation/seed-message-sender | message_sender/factory.py | WhatsAppApiSender.send_custom_hsm | python | def send_custom_hsm(self, whatsapp_id, template_name, language, variables):
data = {
"to": whatsapp_id,
"type": "hsm",
"hsm": {
"namespace": self.hsm_namespace,
"element_name": template_name,
"language": {"policy": "deterministi... | Sends an HSM with more customizable fields than the send_hsm function | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/factory.py#L366-L386 | [
"def return_response(self, response):\n try:\n response.raise_for_status()\n except requests_exceptions.HTTPError as exc:\n resp = exc.response.text\n\n if not (\"1006\" in resp and \"unknown contact\" in resp):\n raise exc\n\n return response.json()\n"
] | class WhatsAppApiSender(object):
def __init__(
self, api_url, token, hsm_namespace, hsm_element_name, ttl, session=None
):
self.api_url = api_url
self.token = token
self.hsm_namespace = hsm_namespace
self.hsm_element_name = hsm_element_name
self.ttl = ttl
... |
praekeltfoundation/seed-message-sender | message_sender/views.py | process_event | python | def process_event(message_id, event_type, event_detail, timestamp):
# Load message
try:
message = Outbound.objects.select_related("channel").get(
vumi_message_id=message_id
)
except ObjectDoesNotExist:
return (False, "Cannot find message for ID {}".format(message_id))
... | Processes an event of the given details, returning a (success, message) tuple | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/views.py#L324-L373 | [
"def decr_message_count(message):\n if message.channel:\n channel = message.channel\n else:\n channel = Channel.objects.get(default=True)\n ConcurrencyLimiter.decr_message_count(channel, message.last_sent_time)\n",
"def fire_delivery_hook(outbound):\n outbound.refresh_from_db()\n # On... | import base64
import hmac
from datetime import datetime, timedelta
from hashlib import sha256
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.shortcuts import get_object_or_4... |
praekeltfoundation/seed-message-sender | message_sender/views.py | EventListener.post | python | def post(self, request, *args, **kwargs):
serializer = EventSerializer(data=request.data)
if not serializer.is_valid():
return Response(
{"accepted": False, "reason": serializer.errors}, status=400
)
data = serializer.validated_data
event_type =... | Checks for expect event types before continuing | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/views.py#L384-L409 | null | class EventListener(APIView):
"""
Triggers updates to outbound messages based on event data from Vumi
"""
permission_classes = (AllowAny,)
|
praekeltfoundation/seed-message-sender | message_sender/signals.py | psh_fire_msg_action_if_new | python | def psh_fire_msg_action_if_new(sender, instance, created, **kwargs):
if created:
from message_sender.tasks import send_message
send_message.apply_async(kwargs={"message_id": str(instance.id)}) | Post save hook to fire message send task | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/signals.py#L4-L10 | null | from .models import Channel
def update_default_channels(sender, instance, created, **kwargs):
""" Post save hook to ensure that there is only one default
"""
if instance.default:
Channel.objects.filter(default=True).exclude(
channel_id=instance.channel_id
).update(default=Fals... |
praekeltfoundation/seed-message-sender | message_sender/signals.py | update_default_channels | python | def update_default_channels(sender, instance, created, **kwargs):
if instance.default:
Channel.objects.filter(default=True).exclude(
channel_id=instance.channel_id
).update(default=False) | Post save hook to ensure that there is only one default | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/signals.py#L13-L19 | null | from .models import Channel
def psh_fire_msg_action_if_new(sender, instance, created, **kwargs):
""" Post save hook to fire message send task
"""
if created:
from message_sender.tasks import send_message
send_message.apply_async(kwargs={"message_id": str(instance.id)})
|
praekeltfoundation/seed-message-sender | message_sender/migrations/0020_outboundsendfailure_db_backed_fk_constraint.py | modify_fk_constraint | python | def modify_fk_constraint(apps, schema_editor):
model = apps.get_model("message_sender", "OutboundSendFailure")
table = model._meta.db_table
with schema_editor.connection.cursor() as cursor:
constraints = schema_editor.connection.introspection.get_constraints(
cursor, table
)
... | Delete's the current foreign key contraint on the outbound field, and adds
it again, but this time with an ON DELETE clause | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/migrations/0020_outboundsendfailure_db_backed_fk_constraint.py#L10-L47 | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-03-22 07:48
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.backends.postgresql.schema import DatabaseSchemaEditor
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies =... |
praekeltfoundation/seed-message-sender | message_sender/serializers.py | InboundSerializer.to_internal_value | python | def to_internal_value(self, data):
if "session_event" in data:
data["helper_metadata"]["session_event"] = data["session_event"]
return super(InboundSerializer, self).to_internal_value(data) | Adds extra data to the helper_metadata field. | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/serializers.py#L97-L104 | null | class InboundSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Inbound
fields = (
"url",
"id",
"message_id",
"in_reply_to",
"to_addr",
"from_addr",
"content",
"transport_name",
... |
praekeltfoundation/seed-message-sender | message_sender/tasks.py | deliver_hook | python | def deliver_hook(target, payload, instance_id=None, hook_id=None, **kwargs):
r = requests.post(
url=target,
data=json.dumps(payload),
headers={
"Content-Type": "application/json",
"Authorization": "Token %s" % settings.HOOK_AUTH_TOKEN,
},
)
r.raise_for... | target: the url to receive the payload.
payload: a python primitive data structure
instance_id: a possibly None "trigger" instance ID
hook_id: the ID of defining Hook object | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/tasks.py#L76-L92 | null | import gzip
import json
import os
import pytz
import random
import requests
import time
from celery.exceptions import MaxRetriesExceededError, SoftTimeLimitExceeded
from celery.task import Task
from celery.utils.log import get_task_logger
from rest_hooks.models import Hook
from datetime import datetime, timedelta
fro... |
praekeltfoundation/seed-message-sender | message_sender/tasks.py | fire_metric | python | def fire_metric(metric_name, metric_value):
metric_value = float(metric_value)
metric = {metric_name: metric_value}
metric_client.fire_metrics(**metric)
return "Fired metric <{}> with value <{}>".format(metric_name, metric_value) | Fires a metric using the MetricsApiClient | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/tasks.py#L118-L124 | null | import gzip
import json
import os
import pytz
import random
import requests
import time
from celery.exceptions import MaxRetriesExceededError, SoftTimeLimitExceeded
from celery.task import Task
from celery.utils.log import get_task_logger
from rest_hooks.models import Hook
from datetime import datetime, timedelta
fro... |
praekeltfoundation/seed-message-sender | message_sender/tasks.py | SendMessage.fire_failed_msisdn_lookup | python | def fire_failed_msisdn_lookup(self, to_identity):
payload = {"to_identity": to_identity}
hooks = Hook.objects.filter(event="identity.no_address")
for hook in hooks:
hook.deliver_hook(
None, payload_override={"hook": hook.dict(), "data": payload}
) | Fires a webhook in the event of a None to_addr. | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/tasks.py#L214-L223 | null | class SendMessage(Task):
"""
Task to load and contruct message and send them off
"""
name = "message_sender.tasks.send_message"
default_retry_delay = 5
max_retries = None
max_error_retries = 5
class FailedEventRequest(Exception):
"""
The attempted task failed because ... |
praekeltfoundation/seed-message-sender | message_sender/tasks.py | SendMessage.run | python | def run(self, message_id, **kwargs):
log = self.get_logger(**kwargs)
error_retry_count = kwargs.get("error_retry_count", 0)
if error_retry_count >= self.max_error_retries:
raise MaxRetriesExceededError(
"Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
... | Load and contruct message and send them off | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/tasks.py#L225-L383 | [
"def calculate_retry_delay(attempt, max_delay=300):\n \"\"\"Calculates an exponential backoff for retry attempts with a small\n amount of jitter.\"\"\"\n delay = int(random.uniform(2, 4) ** attempt)\n if delay > max_delay:\n # After reaching the max delay, stop using expontential growth\n ... | class SendMessage(Task):
"""
Task to load and contruct message and send them off
"""
name = "message_sender.tasks.send_message"
default_retry_delay = 5
max_retries = None
max_error_retries = 5
class FailedEventRequest(Exception):
"""
The attempted task failed because ... |
praekeltfoundation/seed-message-sender | message_sender/tasks.py | ArchiveOutboundMessages.dump_data | python | def dump_data(self, filename, queryset):
with gzip.open(filename, "wb") as f:
for outbound in queryset.iterator():
data = OutboundArchiveSerializer(outbound).data
data = JSONRenderer().render(data)
f.write(data)
f.write("\n".encode("utf... | Serializes the queryset into a newline separated JSON format, and
places it into a gzipped file | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/tasks.py#L486-L496 | null | class ArchiveOutboundMessages(Task):
"""
Task to archive the outbound messages and store the messages in the
storage backend
"""
name = "message_sender.tasks.archive_outbounds"
def filename(self, date):
"""
Returns the filename for the provided date
"""
return "... |
praekeltfoundation/seed-message-sender | message_sender/tasks.py | ArchiveOutboundMessages.create_archived_outbound | python | def create_archived_outbound(self, date, filename):
with open(filename, "rb") as f:
f = File(f)
ArchivedOutbounds.objects.create(date=date, archive=f) | Creates the required ArchivedOutbound entry with the file specified
at `filename` | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/tasks.py#L498-L505 | null | class ArchiveOutboundMessages(Task):
"""
Task to archive the outbound messages and store the messages in the
storage backend
"""
name = "message_sender.tasks.archive_outbounds"
def filename(self, date):
"""
Returns the filename for the provided date
"""
return "... |
praekeltfoundation/seed-message-sender | message_sender/formatters.py | e_164 | python | def e_164(msisdn: str) -> str:
# Phonenumbers library requires the + to identify the country, so we add it if it
# does not already exist
number = phonenumbers.parse("+{}".format(msisdn.lstrip("+")), None)
return phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164) | Returns the msisdn in E.164 international format. | train | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/formatters.py#L31-L38 | null | import re
import phonenumbers
def noop(msisdn):
return msisdn
def vas2nets_voice(msisdn):
"""
FIXME: this should not need be in this repo
Vas2Nets is an aggregator in Nigeria, for some reason they need
MSISDNs prefixed with a 9 instead of the country code to initiate an OBD.
"""
return... |
smnorris/bcdata | bcdata/cli.py | parse_db_url | python | def parse_db_url(db_url):
u = urlparse(db_url)
db = {}
db["database"] = u.path[1:]
db["user"] = u.username
db["password"] = u.password
db["host"] = u.hostname
db["port"] = u.port
return db | provided a db url, return a dict with connection properties | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L27-L37 | null | import json
import logging
import math
import os
import re
import subprocess
from urllib.parse import urlencode
from urllib.parse import urlparse
from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call
import click
from cligj import indent_opt
from cligj import compact_opt
from... |
smnorris/bcdata | bcdata/cli.py | from_like_context | python | def from_like_context(ctx, param, value):
if ctx.obj and ctx.obj.get("like") and (value == "like" or ctx.obj.get("all_like")):
return ctx.obj["like"][param.name]
else:
return None | Return the value for an option from the context if the option
or `--all` is given, else return None. | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L49-L55 | null | import json
import logging
import math
import os
import re
import subprocess
from urllib.parse import urlencode
from urllib.parse import urlparse
from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call
import click
from cligj import indent_opt
from cligj import compact_opt
from... |
smnorris/bcdata | bcdata/cli.py | bounds_handler | python | def bounds_handler(ctx, param, value):
retval = from_like_context(ctx, param, value)
if retval is None and value is not None:
try:
value = value.strip(", []")
retval = tuple(float(x) for x in re.split(r"[,\s]+", value))
assert len(retval) == 4
return retva... | Handle different forms of bounds. | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L58-L72 | [
"def from_like_context(ctx, param, value):\n \"\"\"Return the value for an option from the context if the option\n or `--all` is given, else return None.\"\"\"\n if ctx.obj and ctx.obj.get(\"like\") and (value == \"like\" or ctx.obj.get(\"all_like\")):\n return ctx.obj[\"like\"][param.name]\n els... | import json
import logging
import math
import os
import re
import subprocess
from urllib.parse import urlencode
from urllib.parse import urlparse
from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call
import click
from cligj import indent_opt
from cligj import compact_opt
from... |
smnorris/bcdata | bcdata/cli.py | info | python | def info(dataset, indent, meta_member):
table = bcdata.validate_name(dataset)
wfs = WebFeatureService(url=bcdata.OWS_URL, version="2.0.0")
info = {}
info["name"] = table
info["count"] = bcdata.get_count(table)
info["schema"] = wfs.get_schema("pub:" + table)
if meta_member:
click.echo... | Print basic metadata about a DataBC WFS layer as JSON.
Optionally print a single metadata item as a string. | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L120-L134 | [
"def get_count(dataset, query=None):\n \"\"\"Ask DataBC WFS how many features there are in a table/query\n \"\"\"\n # https://gis.stackexchange.com/questions/45101/only-return-the-numberoffeatures-in-a-wfs-query\n table = validate_name(dataset)\n payload = {\n \"service\": \"WFS\",\n \"... | import json
import logging
import math
import os
import re
import subprocess
from urllib.parse import urlencode
from urllib.parse import urlparse
from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call
import click
from cligj import indent_opt
from cligj import compact_opt
from... |
smnorris/bcdata | bcdata/cli.py | dem | python | def dem(bounds, src_crs, dst_crs, out_file, resolution):
if not dst_crs:
dst_crs = "EPSG:3005"
bcdata.get_dem(bounds, out_file=out_file, src_crs=src_crs, dst_crs=dst_crs, resolution=resolution) | Dump BC DEM to TIFF | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L143-L148 | [
"def get_dem(bounds, out_file=\"dem.tif\", src_crs=\"EPSG:3005\", dst_crs=\"EPSG:3005\", resolution=25):\n \"\"\"Get 25m DEM for provided bounds, write to GeoTIFF\n \"\"\"\n bbox = \",\".join([str(b) for b in bounds])\n # todo: validate resolution units are equivalent to src_crs units\n # build reque... | import json
import logging
import math
import os
import re
import subprocess
from urllib.parse import urlencode
from urllib.parse import urlparse
from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call
import click
from cligj import indent_opt
from cligj import compact_opt
from... |
smnorris/bcdata | bcdata/cli.py | dump | python | def dump(dataset, query, out_file, bounds):
table = bcdata.validate_name(dataset)
data = bcdata.get_data(table, query=query, bounds=bounds)
if out_file:
with open(out_file, "w") as f:
json.dump(data.json(), f)
else:
sink = click.get_text_stream("stdout")
sink.write(js... | Write DataBC features to stdout as GeoJSON feature collection.
\b
$ bcdata dump bc-airports
$ bcdata dump bc-airports --query "AIRPORT_NAME='Victoria Harbour (Shoal Point) Heliport'"
$ bcdata dump bc-airports --bounds xmin ymin xmax ymax
The values of --bounds must be in BC Albers.
It ... | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L159-L181 | [
"def get_data(\n dataset,\n query=None,\n crs=\"epsg:4326\",\n bounds=None,\n sortby=None,\n pagesize=10000,\n max_workers=5,\n):\n \"\"\"Get GeoJSON featurecollection from DataBC WFS\n \"\"\"\n param_dicts = define_request(dataset, query, crs, bounds, sortby, pagesize)\n\n with Thr... | import json
import logging
import math
import os
import re
import subprocess
from urllib.parse import urlencode
from urllib.parse import urlparse
from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call
import click
from cligj import indent_opt
from cligj import compact_opt
from... |
smnorris/bcdata | bcdata/cli.py | cat | python | def cat(dataset, query, bounds, indent, compact, dst_crs, pagesize, sortby):
# Note that cat does not concatenate!
dump_kwds = {"sort_keys": True}
if indent:
dump_kwds["indent"] = indent
if compact:
dump_kwds["separators"] = (",", ":")
table = bcdata.validate_name(dataset)
for fe... | Write DataBC features to stdout as GeoJSON feature objects. | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L198-L211 | [
"def get_features(\n dataset,\n query=None,\n crs=\"epsg:4326\",\n bounds=None,\n sortby=None,\n pagesize=10000,\n max_workers=5,\n):\n \"\"\"Yield features from DataBC WFS\n \"\"\"\n param_dicts = define_request(dataset, query, crs, bounds, sortby, pagesize)\n\n with ThreadPoolExec... | import json
import logging
import math
import os
import re
import subprocess
from urllib.parse import urlencode
from urllib.parse import urlparse
from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call
import click
from cligj import indent_opt
from cligj import compact_opt
from... |
smnorris/bcdata | bcdata/cli.py | bc2pg | python | def bc2pg(dataset, db_url, table, schema, query, append, pagesize, sortby, max_workers):
src = bcdata.validate_name(dataset)
src_schema, src_table = [i.lower() for i in src.split(".")]
if not schema:
schema = src_schema
if not table:
table = src_table
# create schema if it does not ... | Download a DataBC WFS layer to postgres - an ogr2ogr wrapper.
\b
$ bcdata bc2pg bc-airports --db_url postgresql://postgres:postgres@localhost:5432/postgis
The default target database can be specified by setting the $DATABASE_URL
environment variable.
https://docs.sqlalchemy.org/en/latest/core/e... | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/cli.py#L235-L333 | [
"def validate_name(dataset):\n \"\"\"Check wfs/cache and the bcdc api to see if dataset name is valid\n \"\"\"\n if dataset in list_tables():\n return dataset\n else:\n return bcdc_package_show(dataset)[\"object_name\"]\n",
"def define_request(\n dataset, query=None, crs=\"epsg:4326\"... | import json
import logging
import math
import os
import re
import subprocess
from urllib.parse import urlencode
from urllib.parse import urlparse
from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call
import click
from cligj import indent_opt
from cligj import compact_opt
from... |
smnorris/bcdata | bcdata/wcs.py | get_dem | python | def get_dem(bounds, out_file="dem.tif", src_crs="EPSG:3005", dst_crs="EPSG:3005", resolution=25):
bbox = ",".join([str(b) for b in bounds])
# todo: validate resolution units are equivalent to src_crs units
# build request
payload = {
"service": "WCS",
"version": "1.0.0",
"request... | Get 25m DEM for provided bounds, write to GeoTIFF | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wcs.py#L10-L38 | null | import logging
import requests
import bcdata
log = logging.getLogger(__name__)
|
smnorris/bcdata | bcdata/wfs.py | get_sortkey | python | def get_sortkey(table):
# Just pick the first column in the table in alphabetical order.
# Ideally we would get the primary key from bcdc api, but it doesn't
# seem to be available
wfs = WebFeatureService(url=bcdata.OWS_URL, version="2.0.0")
return sorted(wfs.get_schema("pub:" + table)["properties"]... | Get a field to sort by | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L26-L33 | null | from datetime import datetime
from datetime import timedelta
import json
import logging
import math
import os
from pathlib import Path
import sys
import warnings
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from owslib.wfs import WebFeatureService
import requests
import bcdata... |
smnorris/bcdata | bcdata/wfs.py | check_cache | python | def check_cache(path):
if not os.path.exists(path):
return True
else:
# check the age
mod_date = datetime.fromtimestamp(os.path.getmtime(path))
if mod_date < (datetime.now() - timedelta(days=30)):
return True
else:
return False | Return true if the cache file holding list of all datasets
does not exist or is older than 30 days | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L36-L48 | null | from datetime import datetime
from datetime import timedelta
import json
import logging
import math
import os
from pathlib import Path
import sys
import warnings
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from owslib.wfs import WebFeatureService
import requests
import bcdata... |
smnorris/bcdata | bcdata/wfs.py | bcdc_package_show | python | def bcdc_package_show(package):
params = {"id": package}
r = requests.get(bcdata.BCDC_API_URL + "package_show", params=params)
if r.status_code != 200:
raise ValueError("{d} is not present in DataBC API list".format(d=package))
return r.json()["result"] | Query DataBC Catalogue API about given package | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L51-L58 | null | from datetime import datetime
from datetime import timedelta
import json
import logging
import math
import os
from pathlib import Path
import sys
import warnings
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from owslib.wfs import WebFeatureService
import requests
import bcdata... |
smnorris/bcdata | bcdata/wfs.py | list_tables | python | def list_tables(refresh=False, cache_file=None):
# default cache listing all objects available is
# ~/.bcdata
if not cache_file:
cache_file = os.path.join(str(Path.home()), ".bcdata")
# regenerate the cache if:
# - the cache file doesn't exist
# - we force a refresh
# - the cache is... | Return a list of all datasets available via WFS | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L70-L91 | [
"def check_cache(path):\n \"\"\"Return true if the cache file holding list of all datasets\n does not exist or is older than 30 days\n \"\"\"\n if not os.path.exists(path):\n return True\n else:\n # check the age\n mod_date = datetime.fromtimestamp(os.path.getmtime(path))\n ... | from datetime import datetime
from datetime import timedelta
import json
import logging
import math
import os
from pathlib import Path
import sys
import warnings
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from owslib.wfs import WebFeatureService
import requests
import bcdata... |
smnorris/bcdata | bcdata/wfs.py | get_count | python | def get_count(dataset, query=None):
# https://gis.stackexchange.com/questions/45101/only-return-the-numberoffeatures-in-a-wfs-query
table = validate_name(dataset)
payload = {
"service": "WFS",
"version": "2.0.0",
"request": "GetFeature",
"typeName": table,
"resultType... | Ask DataBC WFS how many features there are in a table/query | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L94-L110 | [
"def validate_name(dataset):\n \"\"\"Check wfs/cache and the bcdc api to see if dataset name is valid\n \"\"\"\n if dataset in list_tables():\n return dataset\n else:\n return bcdc_package_show(dataset)[\"object_name\"]\n"
] | from datetime import datetime
from datetime import timedelta
import json
import logging
import math
import os
from pathlib import Path
import sys
import warnings
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from owslib.wfs import WebFeatureService
import requests
import bcdata... |
smnorris/bcdata | bcdata/wfs.py | make_request | python | def make_request(parameters):
r = requests.get(bcdata.WFS_URL, params=parameters)
return r.json()["features"] | Submit a getfeature request to DataBC WFS and return features | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L113-L117 | null | from datetime import datetime
from datetime import timedelta
import json
import logging
import math
import os
from pathlib import Path
import sys
import warnings
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from owslib.wfs import WebFeatureService
import requests
import bcdata... |
smnorris/bcdata | bcdata/wfs.py | define_request | python | def define_request(
dataset, query=None, crs="epsg:4326", bounds=None, sortby=None, pagesize=10000
):
# validate the table name and find out how many features it holds
table = validate_name(dataset)
n = bcdata.get_count(table, query=query)
# DataBC WFS getcapabilities says that it supports paging,
... | Define the getfeature request parameters required to download a dataset
References:
- http://www.opengeospatial.org/standards/wfs
- http://docs.geoserver.org/stable/en/user/services/wfs/vendor.html
- http://docs.geoserver.org/latest/en/user/tutorials/cql/cql_tutorial.html | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L120-L167 | [
"def get_count(dataset, query=None):\n \"\"\"Ask DataBC WFS how many features there are in a table/query\n \"\"\"\n # https://gis.stackexchange.com/questions/45101/only-return-the-numberoffeatures-in-a-wfs-query\n table = validate_name(dataset)\n payload = {\n \"service\": \"WFS\",\n \"... | from datetime import datetime
from datetime import timedelta
import json
import logging
import math
import os
from pathlib import Path
import sys
import warnings
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from owslib.wfs import WebFeatureService
import requests
import bcdata... |
smnorris/bcdata | bcdata/wfs.py | get_data | python | def get_data(
dataset,
query=None,
crs="epsg:4326",
bounds=None,
sortby=None,
pagesize=10000,
max_workers=5,
):
param_dicts = define_request(dataset, query, crs, bounds, sortby, pagesize)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
results = executor.map(ma... | Get GeoJSON featurecollection from DataBC WFS | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L170-L189 | [
"def define_request(\n dataset, query=None, crs=\"epsg:4326\", bounds=None, sortby=None, pagesize=10000\n):\n \"\"\"Define the getfeature request parameters required to download a dataset\n\n References:\n - http://www.opengeospatial.org/standards/wfs\n - http://docs.geoserver.org/stable/en/user/serv... | from datetime import datetime
from datetime import timedelta
import json
import logging
import math
import os
from pathlib import Path
import sys
import warnings
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from owslib.wfs import WebFeatureService
import requests
import bcdata... |
smnorris/bcdata | bcdata/wfs.py | get_features | python | def get_features(
dataset,
query=None,
crs="epsg:4326",
bounds=None,
sortby=None,
pagesize=10000,
max_workers=5,
):
param_dicts = define_request(dataset, query, crs, bounds, sortby, pagesize)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
for result in executo... | Yield features from DataBC WFS | train | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L192-L208 | [
"def define_request(\n dataset, query=None, crs=\"epsg:4326\", bounds=None, sortby=None, pagesize=10000\n):\n \"\"\"Define the getfeature request parameters required to download a dataset\n\n References:\n - http://www.opengeospatial.org/standards/wfs\n - http://docs.geoserver.org/stable/en/user/serv... | from datetime import datetime
from datetime import timedelta
import json
import logging
import math
import os
from pathlib import Path
import sys
import warnings
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from owslib.wfs import WebFeatureService
import requests
import bcdata... |
aquatix/ns-api | ns_api.py | simple_time | python | def simple_time(value):
if isinstance(value, timedelta):
return ':'.join(str(value).split(':')[:2])
return datetime_to_string(value, '%H:%M') | Format a datetime or timedelta object to a string of format HH:MM | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L32-L38 | null | """
Library to query the official Dutch railways API
"""
from __future__ import print_function
import collections
import json
import time
from datetime import datetime, timedelta
import pytz
import requests
import xmltodict
from future.utils import python_2_unicode_compatible
from pytz.tzinfo import StaticTzInfo
from... |
aquatix/ns-api | ns_api.py | is_dst | python | def is_dst(zonename):
tz = pytz.timezone(zonename)
now = pytz.utc.localize(datetime.utcnow())
return now.astimezone(tz).dst() != timedelta(0) | Find out whether it's Daylight Saving Time in this timezone | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L43-L49 | null | """
Library to query the official Dutch railways API
"""
from __future__ import print_function
import collections
import json
import time
from datetime import datetime, timedelta
import pytz
import requests
import xmltodict
from future.utils import python_2_unicode_compatible
from pytz.tzinfo import StaticTzInfo
from... |
aquatix/ns-api | ns_api.py | load_datetime | python | def load_datetime(value, dt_format):
if dt_format.endswith('%z'):
dt_format = dt_format[:-2]
offset = value[-5:]
value = value[:-5]
if offset != offset.replace(':', ''):
# strip : from HHMM if needed (isoformat() adds it between HH and MM)
offset = '+' + offse... | Create timezone-aware datetime object | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L62-L76 | null | """
Library to query the official Dutch railways API
"""
from __future__ import print_function
import collections
import json
import time
from datetime import datetime, timedelta
import pytz
import requests
import xmltodict
from future.utils import python_2_unicode_compatible
from pytz.tzinfo import StaticTzInfo
from... |
aquatix/ns-api | ns_api.py | list_to_json | python | def list_to_json(source_list):
result = []
for item in source_list:
result.append(item.to_json())
return result | Serialise all the items in source_list to json | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L81-L88 | null | """
Library to query the official Dutch railways API
"""
from __future__ import print_function
import collections
import json
import time
from datetime import datetime, timedelta
import pytz
import requests
import xmltodict
from future.utils import python_2_unicode_compatible
from pytz.tzinfo import StaticTzInfo
from... |
aquatix/ns-api | ns_api.py | list_from_json | python | def list_from_json(source_list_json):
result = []
if source_list_json == [] or source_list_json == None:
return result
for list_item in source_list_json:
item = json.loads(list_item)
try:
if item['class_name'] == 'Departure':
temp = Departure()
... | Deserialise all the items in source_list from json | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L91-L123 | null | """
Library to query the official Dutch railways API
"""
from __future__ import print_function
import collections
import json
import time
from datetime import datetime, timedelta
import pytz
import requests
import xmltodict
from future.utils import python_2_unicode_compatible
from pytz.tzinfo import StaticTzInfo
from... |
aquatix/ns-api | ns_api.py | list_diff | python | def list_diff(list_a, list_b):
result = []
for item in list_b:
if not item in list_a:
result.append(item)
return result | Return the items from list_b that differ from list_a | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L126-L134 | null | """
Library to query the official Dutch railways API
"""
from __future__ import print_function
import collections
import json
import time
from datetime import datetime, timedelta
import pytz
import requests
import xmltodict
from future.utils import python_2_unicode_compatible
from pytz.tzinfo import StaticTzInfo
from... |
aquatix/ns-api | ns_api.py | list_same | python | def list_same(list_a, list_b):
result = []
for item in list_b:
if item in list_a:
result.append(item)
return result | Return the items from list_b that are also on list_a | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L137-L145 | null | """
Library to query the official Dutch railways API
"""
from __future__ import print_function
import collections
import json
import time
from datetime import datetime, timedelta
import pytz
import requests
import xmltodict
from future.utils import python_2_unicode_compatible
from pytz.tzinfo import StaticTzInfo
from... |
aquatix/ns-api | ns_api.py | list_merge | python | def list_merge(list_a, list_b):
#return list(collections.OrderedDict.fromkeys(list_a + list_b))
#result = list(list_b)
result = []
for item in list_a:
if not item in result:
result.append(item)
for item in list_b:
if not item in result:
result.append(item)
... | Merge two lists without duplicating items
Args:
list_a: list
list_b: list
Returns:
New list with deduplicated items from list_a and list_b | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L148-L167 | null | """
Library to query the official Dutch railways API
"""
from __future__ import print_function
import collections
import json
import time
from datetime import datetime, timedelta
import pytz
import requests
import xmltodict
from future.utils import python_2_unicode_compatible
from pytz.tzinfo import StaticTzInfo
from... |
aquatix/ns-api | ns_api.py | Trip.delay | python | def delay(self):
delay = {'departure_time': None, 'departure_delay': None, 'requested_differs': None,
'remarks': self.trip_remarks, 'parts': []}
if self.departure_time_actual > self.departure_time_planned:
delay['departure_delay'] = self.departure_time_actual - self.departure... | Return the delay of the train for this instance | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L580-L594 | null | class Trip(BaseObject):
"""
Suggested route for the provided departure/destination combination
"""
def __init__(self, trip_dict=None, datetime=None):
if trip_dict is None:
return
# self.key = ??
try:
# VOLGENS-PLAN, GEWIJZIGD, VERTRAAGD, NIEUW, NIET-OPTI... |
aquatix/ns-api | ns_api.py | Trip.has_departure_delay | python | def has_departure_delay(self, subpartcheck=True):
if self.status != 'VOLGENS-PLAN':
return True
if subpartcheck and self.trip_parts[0].has_delay:
return True
if self.requested_time != self.departure_time_actual:
return True
return False | Deprecated | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L609-L619 | null | class Trip(BaseObject):
"""
Suggested route for the provided departure/destination combination
"""
def __init__(self, trip_dict=None, datetime=None):
if trip_dict is None:
return
# self.key = ??
try:
# VOLGENS-PLAN, GEWIJZIGD, VERTRAAGD, NIEUW, NIET-OPTI... |
aquatix/ns-api | ns_api.py | Trip.get_actual | python | def get_actual(cls, trip_list, time):
for trip in trip_list:
if simple_time(trip.departure_time_planned) == time:
return trip
return None | Look for the train actually leaving at time | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L674-L681 | [
"def simple_time(value):\n \"\"\"\n Format a datetime or timedelta object to a string of format HH:MM\n \"\"\"\n if isinstance(value, timedelta):\n return ':'.join(str(value).split(':')[:2])\n return datetime_to_string(value, '%H:%M')\n"
] | class Trip(BaseObject):
"""
Suggested route for the provided departure/destination combination
"""
def __init__(self, trip_dict=None, datetime=None):
if trip_dict is None:
return
# self.key = ??
try:
# VOLGENS-PLAN, GEWIJZIGD, VERTRAAGD, NIEUW, NIET-OPTI... |
aquatix/ns-api | ns_api.py | NSAPI.parse_disruptions | python | def parse_disruptions(self, xml):
obj = xmltodict.parse(xml)
disruptions = {}
disruptions['unplanned'] = []
disruptions['planned'] = []
if obj['Storingen']['Ongepland']:
raw_disruptions = obj['Storingen']['Ongepland']['Storing']
if isinstance(raw_disrupti... | Parse the NS API xml result into Disruption objects
@param xml: raw XML result from the NS API | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L729-L756 | null | class NSAPI(object):
"""
NS API object
Library to query the official Dutch railways API
"""
def __init__(self, username, apikey):
self.username = username
self.apikey = apikey
def _request(self, method, url, postdata=None, params=None):
headers = {"Accept": "application... |
aquatix/ns-api | ns_api.py | NSAPI.get_disruptions | python | def get_disruptions(self, station=None, actual=True, unplanned=True):
url = "http://webservices.ns.nl/ns-api-storingen?station=${Stationsnaam}&actual=${true or false}&unplanned=${true or false}"
url = "http://webservices.ns.nl/ns-api-storingen?actual=true&unplanned=true"
raw_disruptions = self.... | Fetch the current disruptions, or even the planned ones
@param station: station to lookup
@param actual: only actual disruptions, or a
actuele storingen (=ongeplande storingen + actuele werkzaamheden)
geplande werkzaamheden (=geplande werkzaamheden)
actuele storingen voor een g... | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L759-L773 | [
"def _request(self, method, url, postdata=None, params=None):\n headers = {\"Accept\": \"application/xml\",\n \"Content-Type\": \"application/xml\",\n \"User-Agent\": \"ns_api\"}\n\n if postdata:\n postdata = json.dumps(postdata)\n\n r = requests.request(method,\n ... | class NSAPI(object):
"""
NS API object
Library to query the official Dutch railways API
"""
def __init__(self, username, apikey):
self.username = username
self.apikey = apikey
def _request(self, method, url, postdata=None, params=None):
headers = {"Accept": "application... |
aquatix/ns-api | ns_api.py | NSAPI.parse_departures | python | def parse_departures(self, xml):
obj = xmltodict.parse(xml)
departures = []
for departure in obj['ActueleVertrekTijden']['VertrekkendeTrein']:
newdep = Departure(departure)
departures.append(newdep)
#print('-- dep --')
#print(newdep.__dict__)
... | Parse the NS API xml result into Departure objects
@param xml: raw XML result from the NS API | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L776-L792 | null | class NSAPI(object):
"""
NS API object
Library to query the official Dutch railways API
"""
def __init__(self, username, apikey):
self.username = username
self.apikey = apikey
def _request(self, method, url, postdata=None, params=None):
headers = {"Accept": "application... |
aquatix/ns-api | ns_api.py | NSAPI.get_departures | python | def get_departures(self, station):
url = 'http://webservices.ns.nl/ns-api-avt?station=' + station
raw_departures = self._request('GET', url)
return self.parse_departures(raw_departures) | Fetch the current departure times from this station
http://webservices.ns.nl/ns-api-avt?station=${Naam of afkorting Station}
@param station: station to lookup | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L795-L804 | [
"def _request(self, method, url, postdata=None, params=None):\n headers = {\"Accept\": \"application/xml\",\n \"Content-Type\": \"application/xml\",\n \"User-Agent\": \"ns_api\"}\n\n if postdata:\n postdata = json.dumps(postdata)\n\n r = requests.request(method,\n ... | class NSAPI(object):
"""
NS API object
Library to query the official Dutch railways API
"""
def __init__(self, username, apikey):
self.username = username
self.apikey = apikey
def _request(self, method, url, postdata=None, params=None):
headers = {"Accept": "application... |
aquatix/ns-api | ns_api.py | NSAPI.parse_trips | python | def parse_trips(self, xml, requested_time):
obj = xmltodict.parse(xml)
trips = []
if 'error' in obj:
print('Error in trips: ' + obj['error']['message'])
return None
try:
for trip in obj['ReisMogelijkheden']['ReisMogelijkheid']:
newtri... | Parse the NS API xml result into Trip objects | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L807-L826 | null | class NSAPI(object):
"""
NS API object
Library to query the official Dutch railways API
"""
def __init__(self, username, apikey):
self.username = username
self.apikey = apikey
def _request(self, method, url, postdata=None, params=None):
headers = {"Accept": "application... |
aquatix/ns-api | ns_api.py | NSAPI.get_trips | python | def get_trips(self, timestamp, start, via, destination, departure=True, prev_advices=1, next_advices=1):
timezonestring = '+0100'
if is_dst('Europe/Amsterdam'):
timezonestring = '+0200'
url = 'http://webservices.ns.nl/ns-api-treinplanner?'
url = url + 'fromStation=' + start
... | Fetch trip possibilities for these parameters
http://webservices.ns.nl/ns-api-treinplanner?<parameters>
fromStation
toStation
dateTime: 2012-02-21T15:50
departure: true for starting at timestamp, false for arriving at timestamp
previousAdvices
nextAdvices | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L829-L862 | [
"def is_dst(zonename):\n \"\"\"\n Find out whether it's Daylight Saving Time in this timezone\n \"\"\"\n tz = pytz.timezone(zonename)\n now = pytz.utc.localize(datetime.utcnow())\n return now.astimezone(tz).dst() != timedelta(0)\n",
"def load_datetime(value, dt_format):\n \"\"\"\n Create t... | class NSAPI(object):
"""
NS API object
Library to query the official Dutch railways API
"""
def __init__(self, username, apikey):
self.username = username
self.apikey = apikey
def _request(self, method, url, postdata=None, params=None):
headers = {"Accept": "application... |
aquatix/ns-api | ns_api.py | NSAPI.get_stations | python | def get_stations(self):
url = 'http://webservices.ns.nl/ns-api-stations-v2'
raw_stations = self._request('GET', url)
return self.parse_stations(raw_stations) | Fetch the list of stations | train | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L877-L883 | [
"def _request(self, method, url, postdata=None, params=None):\n headers = {\"Accept\": \"application/xml\",\n \"Content-Type\": \"application/xml\",\n \"User-Agent\": \"ns_api\"}\n\n if postdata:\n postdata = json.dumps(postdata)\n\n r = requests.request(method,\n ... | class NSAPI(object):
"""
NS API object
Library to query the official Dutch railways API
"""
def __init__(self, username, apikey):
self.username = username
self.apikey = apikey
def _request(self, method, url, postdata=None, params=None):
headers = {"Accept": "application... |
thespacedoctor/astrocalc | astrocalc/__init__.py | luminosity_to_flux | python | def luminosity_to_flux(lumErg_S, dist_Mpc):
################ > IMPORTS ################
## STANDARD LIB ##
## THIRD PARTY ##
import numpy as np
import math
## LOCAL APPLICATION ##
################ > VARIABLE SETTINGS ######
################ >ACTION(S) ################
# Convert the... | *Convert luminosity to a flux*
**Key Arguments:**
- ``lumErg_S`` -- luminosity in ergs/sec
- ``dist_Mpc`` -- distance in Mpc
**Return:**
- ``fluxErg_cm2_S`` -- flux in ergs/cm2/s | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/__init__.py#L3-L28 | null |
##########################################################################
# PRIVATE (HELPER) FUNCTIONS #
##########################################################################
if __name__ == '__main__':
main()
|
thespacedoctor/astrocalc | astrocalc/times/now.py | now.get_mjd | python | def get_mjd(self):
self.log.info('starting the ``get_mjd`` method')
jd = time.time() / 86400.0 + 2440587.5
mjd = jd - 2400000.5
self.log.info('completed the ``get_mjd`` method')
return mjd | *Get the current time as an MJD*
**Return:**
- ``mjd`` -- the current MJD as a float
**Usage:**
.. todo::
- add clutil
- remove `getCurrentMJD` from all other code
.. code-block:: python
from astrocalc.times import now
mjd... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/times/now.py#L47-L74 | null | class now():
"""
*Report the current time into various formats*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
"""
# Initialisation
def __init__(
self,
log,
settings=False,
):
self.log = log
... |
thespacedoctor/astrocalc | astrocalc/coords/unit_conversion.py | unit_conversion.get | python | def get(self):
self.log.info('starting the ``get`` method')
unit_conversion = None
self.log.info('completed the ``get`` method')
return unit_conversion | *get the unit_conversion object*
**Return:**
- ``unit_conversion``
.. todo::
- @review: when complete, clean get method
- @review: when complete add logging | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/unit_conversion.py#L71-L88 | null | class unit_conversion():
"""
*The worker class for the unit_conversion module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary (prob not required)
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usag... |
thespacedoctor/astrocalc | astrocalc/coords/unit_conversion.py | unit_conversion.dec_sexegesimal_to_decimal | python | def dec_sexegesimal_to_decimal(
self,
dec):
self.log.info(
'starting the ``dec_sexegesimal_to_decimal`` method')
import re
# TEST TO SEE IF DECIMAL DEGREES PASSED
try:
dec = float(dec)
if dec > -90. and dec < 90.:
... | *Convert a declination from sexegesimal format to decimal degrees.*
Precision should be respected. If a float is passed to this method, the same float will be returned (useful if unclear which format coordinates are in).
The code will attempt to read the sexegesimal value in whatever form it is passed... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/unit_conversion.py#L90-L188 | null | class unit_conversion():
"""
*The worker class for the unit_conversion module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary (prob not required)
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usag... |
thespacedoctor/astrocalc | astrocalc/coords/unit_conversion.py | unit_conversion.ra_sexegesimal_to_decimal | python | def ra_sexegesimal_to_decimal(
self,
ra
):
import re
# TEST TO SEE IF DECIMAL DEGREES PASSED
try:
ra = float(ra)
if ra >= 0. and ra <= 360.:
self.log.info(
'RA seems to already be in decimal degrees, returning origi... | *Convert a right-ascension from sexegesimal format to decimal degrees.*
Precision should be respected. If a float is passed to this method, the same float will be returned (useful if unclear which format coordinates are in).
The code will attempt to read the sexegesimal value in whatever form it is pa... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/unit_conversion.py#L190-L278 | null | class unit_conversion():
"""
*The worker class for the unit_conversion module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary (prob not required)
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usag... |
thespacedoctor/astrocalc | astrocalc/coords/unit_conversion.py | unit_conversion.ra_decimal_to_sexegesimal | python | def ra_decimal_to_sexegesimal(
self,
ra,
delimiter=":"):
self.log.info('starting the ``ra_decimal_to_sexegesimal`` method')
# CONVERT RA TO FLOAT
try:
self.log.debug("attempting to convert RA to float")
ra = float(ra)
except Ex... | *Convert a right-ascension between decimal degrees and sexegesimal.*
Precision should be respected.
**Key Arguments:**
- ``ra`` -- RA in decimal degrees. Will try and convert to float before performing calculation.
- ``delimiter`` -- how to delimit the RA units. Default *:*
... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/unit_conversion.py#L280-L361 | null | class unit_conversion():
"""
*The worker class for the unit_conversion module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary (prob not required)
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usag... |
thespacedoctor/astrocalc | astrocalc/coords/unit_conversion.py | unit_conversion.dec_decimal_to_sexegesimal | python | def dec_decimal_to_sexegesimal(
self,
dec,
delimiter=":"):
self.log.info('starting the ``dec_decimal_to_sexegesimal`` method')
import math
# CONVERT DEC TO FLOAT
try:
self.log.debug("attempting to convert RA to float")
dec = f... | *Convert a declination between decimal degrees and sexegesimal.*
Precision should be respected.
**Key Arguments:**
- ``dec`` -- DEC in decimal degrees. Will try and convert to float before performing calculation.
- ``delimiter`` -- how to delimit the RA units. Default *:*
... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/unit_conversion.py#L363-L448 | null | class unit_conversion():
"""
*The worker class for the unit_conversion module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary (prob not required)
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usag... |
thespacedoctor/astrocalc | astrocalc/coords/unit_conversion.py | unit_conversion.ra_dec_to_cartesian | python | def ra_dec_to_cartesian(
self,
ra,
dec):
self.log.info('starting the ``ra_dec_to_cartesian`` method')
ra = self.ra_sexegesimal_to_decimal(
ra=ra
)
dec = self.dec_sexegesimal_to_decimal(
dec=dec
)
ra = math.radi... | *Convert an RA, DEC coordinate set to x, y, z cartesian coordinates*
**Key Arguments:**
- ``ra`` -- right ascension in sexegesimal or decimal degress.
- ``dec`` -- declination in sexegesimal or decimal degress.
**Return:**
- ``cartesians`` -- tuple of (x, y, z) coor... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/unit_conversion.py#L451-L503 | [
"def dec_sexegesimal_to_decimal(\n self,\n dec):\n \"\"\"\n *Convert a declination from sexegesimal format to decimal degrees.*\n\n Precision should be respected. If a float is passed to this method, the same float will be returned (useful if unclear which format coordinates are in).\n\n T... | class unit_conversion():
"""
*The worker class for the unit_conversion module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary (prob not required)
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usag... |
thespacedoctor/astrocalc | astrocalc/distances/converter.py | converter.distance_to_redshift | python | def distance_to_redshift(
self,
mpc):
self.log.info('starting the ``distance_to_redshift`` method')
lowerLimit = 0.
upperLimit = 30.
redshift = upperLimit - lowerLimit
distGuess = float(self.redshift_to_distance(redshift)['dl_mpc'])
distDiff = mp... | *Convert a distance from MPC to redshift*
The code works by iteratively converting a redshift to a distance, correcting itself and honing in on the true answer (within a certain precision)
**Key Arguments:**
- ``mpc`` -- distance in MPC (assumes a luminousity distance).
**Return:*... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/distances/converter.py#L55-L111 | [
"def redshift_to_distance(\n self,\n z,\n WM=0.3,\n WV=0.7,\n H0=70.0):\n \"\"\"*convert redshift to various distance measurements*\n\n **Key Arguments:**\n - ``z`` -- redshift measurement.\n - ``WM`` -- Omega_matter. Default *0.3*\n - ``WV`` -- Omega_va... | class converter():
"""
*A converter to switch distance between various units of measurement*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
**Usage:**
To instantiate a ``converter`` object:
.. code-block:: python
from ast... |
thespacedoctor/astrocalc | astrocalc/distances/converter.py | converter.redshift_to_distance | python | def redshift_to_distance(
self,
z,
WM=0.3,
WV=0.7,
H0=70.0):
self.log.info('starting the ``redshift_to_distance`` method')
# VARIABLE
h = H0 / 100.0
WR = 4.165E-5 / (h * h) # Omega_radiation
WK = 1.0 - WM - WV - WR ... | *convert redshift to various distance measurements*
**Key Arguments:**
- ``z`` -- redshift measurement.
- ``WM`` -- Omega_matter. Default *0.3*
- ``WV`` -- Omega_vacuum. Default *0.7*
- ``H0`` -- Hubble constant. (km s-1 Mpc-1) Default *70.0*
**Return:**... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/distances/converter.py#L113-L265 | null | class converter():
"""
*A converter to switch distance between various units of measurement*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
**Usage:**
To instantiate a ``converter`` object:
.. code-block:: python
from ast... |
thespacedoctor/astrocalc | astrocalc/coords/separations.py | separations.get | python | def get(
self):
self.log.info('starting the ``get_angular_separation`` method')
from astrocalc.coords import unit_conversion
# CONSTANTS
pi = (4 * math.atan(1.0))
DEG_TO_RAD_FACTOR = pi / 180.0
RAD_TO_DEG_FACTOR = 180.0 / pi
converter = unit_convers... | *Calulate the angular separation between two locations on the sky*
Input precision should be respected.
**Key Arguments:**
**Return:**
- ``angularSeparation`` -- total angular separation between coordinates (arcsec)
- ``north`` -- north-south separation between coordin... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/separations.py#L110-L191 | [
"def dec_sexegesimal_to_decimal(\n self,\n dec):\n \"\"\"\n *Convert a declination from sexegesimal format to decimal degrees.*\n\n Precision should be respected. If a float is passed to this method, the same float will be returned (useful if unclear which format coordinates are in).\n\n T... | class separations():
"""
*The worker class for the separations module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
- ``ra1`` -- the right-ascension of the first location. Decimal degrees or sexegesimal.
- ``dec1`` -- the declination of th... |
thespacedoctor/astrocalc | astrocalc/cl_utils.py | main | python | def main(arguments=None):
from astrocalc.coords import unit_conversion
# setup the command-line util settings
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="CRITICAL",
options_first=True,
projectName="astrocalc"
)
arguments, settings, log, dbCon... | *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/cl_utils.py#L58-L291 | [
"def ut_datetime_to_mjd(\n self,\n utDatetime):\n \"\"\"*ut datetime to mjd*\n\n If the date given has no time associated with it (e.g. ``20160426``), then the datetime assumed is ``20160426 00:00:00.0``.\n\n Precision should be respected. \n\n **Key Arguments:**\n - ``utDatetime`` ... | #!/usr/local/bin/python
# encoding: utf-8
"""
Documentation for astrocalc can be found here: http://astrocalc.readthedocs.org/en/stable
Usage:
astrocalc [-c] coordflip <ra> <dec>
astrocalc sep <ra1> <dec1> <ra2> <dec2>
astrocalc timeflip <datetime>
astrocalc trans <ra> <dec> <north> <east>
astrocal... |
thespacedoctor/astrocalc | astrocalc/coords/coordinates_to_array.py | coordinates_to_array | python | def coordinates_to_array(
log,
ra,
dec):
log.info('starting the ``coordinates_to_array`` function')
if isinstance(ra, np.ndarray) and isinstance(dec, np.ndarray):
return ra, dec
# ASTROCALC UNIT CONVERTER OBJECT
converter = unit_conversion(
log=log
)
# C... | *Convert a single value RA, DEC or list of RA and DEC to numpy arrays*
**Key Arguments:**
- ``ra`` -- list, numpy array or single ra value
- ``dec`` --list, numpy array or single dec value
- ``log`` -- logger
**Return:**
- ``raArray`` -- input RAs as a numpy array of decimal de... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/coordinates_to_array.py#L21-L95 | null | #!/usr/local/bin/python
# encoding: utf-8
"""
*Convert single values of RA, DEC or list of RA and DEC to numpy arrays*
:Author:
David Young
:Date Created:
October 6, 2016
"""
################# GLOBAL IMPORTS ####################
import sys
import os
os.environ['TERM'] = 'vt100'
from fundamentals import tools... |
thespacedoctor/astrocalc | astrocalc/coords/translate.py | translate.get | python | def get(self):
self.log.info('starting the ``get`` method')
# PRECISION TEST
decprecision = len(repr(self.dec).split(".")[-1])
raprecision = len(repr(self.ra).split(".")[-1])
dec2 = self.dec + self.north
ra2 = self.ra + \
((self.east) /
(math.c... | *translate the coordinates*
**Return:**
- ``ra`` -- the right-ascension of the translated coordinate
- ``dec`` -- the declination of the translated coordinate | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/translate.py#L93-L129 | null | class translate():
"""
*Translate a set of coordinates north and east by distances given in arcsecs*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary. Default *False*
- ``ra`` -- ra (decimal or sexegesimal)
- ``dec`` -- dec (decimal or sexeges... |
thespacedoctor/astrocalc | astrocalc/times/conversions.py | conversions.get | python | def get(self):
self.log.info('starting the ``get`` method')
conversions = None
self.log.info('completed the ``get`` method')
return conversions | *get the conversions object*
**Return:**
- ``conversions``
.. todo::
- @review: when complete, clean get method
- @review: when complete add logging | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/times/conversions.py#L55-L72 | null | class conversions():
"""
*The worker class for the conversions module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usage
- add mjd_to_d... |
thespacedoctor/astrocalc | astrocalc/times/conversions.py | conversions.ut_datetime_to_mjd | python | def ut_datetime_to_mjd(
self,
utDatetime):
self.log.info('starting the ``ut_datetime_to_mjd`` method')
import time
import re
mjd = None
# TRIM WHITESPACE FROM AROUND STRING
utDatetime = utDatetime.strip()
# DATETIME REGEX
matchOb... | *ut datetime to mjd*
If the date given has no time associated with it (e.g. ``20160426``), then the datetime assumed is ``20160426 00:00:00.0``.
Precision should be respected.
**Key Arguments:**
- ``utDatetime`` -- UT datetime. Can accept various formats e.g. ``201604261444``, ``... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/times/conversions.py#L74-L185 | null | class conversions():
"""
*The worker class for the conversions module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usage
- add mjd_to_d... |
thespacedoctor/astrocalc | astrocalc/times/conversions.py | conversions.mjd_to_ut_datetime | python | def mjd_to_ut_datetime(
self,
mjd,
sqlDate=False,
datetimeObject=False):
self.log.info('starting the ``mjd_to_ut_datetime`` method')
from datetime import datetime
# CONVERT TO UNIXTIME
unixtime = (float(mjd) + 2400000.5 - 2440587.5) * 864... | *mjd to ut datetime*
Precision should be respected.
**Key Arguments:**
- ``mjd`` -- time in MJD.
- ``sqlDate`` -- add a 'T' between date and time instead of space
- ``datetimeObject`` -- return a datetime object instead of a string. Default *False*
.. todo... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/times/conversions.py#L187-L276 | null | class conversions():
"""
*The worker class for the conversions module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usage
- add mjd_to_d... |
thespacedoctor/astrocalc | astrocalc/times/conversions.py | conversions.decimal_day_to_day_hour_min_sec | python | def decimal_day_to_day_hour_min_sec(
self,
daysFloat):
self.log.info(
'starting the ``decimal_day_to_day_hour_min_sec`` method')
daysInt = int(daysFloat)
hoursFloat = (daysFloat - daysInt) * 24.
hoursInt = int(hoursFloat)
minsFloat = (hoursFlo... | *Convert a day from decimal format to hours mins and sec*
Precision should be respected.
**Key Arguments:**
- ``daysFloat`` -- the day as a decimal.
**Return:**
- ``daysInt`` -- day as an integer
- ``hoursInt`` -- hour as an integer (None if input precsion... | train | https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/times/conversions.py#L278-L363 | null | class conversions():
"""
*The worker class for the conversions module*
**Key Arguments:**
- ``log`` -- logger
- ``settings`` -- the settings dictionary
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usage
- add mjd_to_d... |
openp2pdesign/makerlabs | makerlabs/makeinitaly_foundation.py | get_lab_text | python | def get_lab_text(lab_slug, language):
if language == "English" or language == "english" or language == "EN" or language == "En":
language = "en"
elif language == "Italian" or language == "italian" or language == "IT" or language == "It" or language == "it":
language = "it"
else:
lang... | Gets text description in English or Italian from a single lab from makeinitaly.foundation. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/makeinitaly_foundation.py#L34-L61 | null | # -*- encoding: utf-8 -*-
#
# Access data from makeinitaly.foundation
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
from simplemediawiki import MediaWiki
import pandas as pd
makeinitaly__foundation_api_url = "http://makeinitaly... |
openp2pdesign/makerlabs | makerlabs/makeinitaly_foundation.py | get_single_lab | python | def get_single_lab(lab_slug):
wiki = MediaWiki(makeinitaly__foundation_api_url)
wiki_response = wiki.call(
{'action': 'query',
'titles': lab_slug,
'prop': 'revisions',
'rvprop': 'content'})
# If we don't know the pageid...
for i in wiki_response["query"]["pages"]:
... | Gets data from a single lab from makeinitaly.foundation. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/makeinitaly_foundation.py#L64-L137 | [
"def get_lab_text(lab_slug, language):\n \"\"\"Gets text description in English or Italian from a single lab from makeinitaly.foundation.\"\"\"\n if language == \"English\" or language == \"english\" or language == \"EN\" or language == \"En\":\n language = \"en\"\n elif language == \"Italian\" or l... | # -*- encoding: utf-8 -*-
#
# Access data from makeinitaly.foundation
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
from simplemediawiki import MediaWiki
import pandas as pd
makeinitaly__foundation_api_url = "http://makeinitaly... |
openp2pdesign/makerlabs | makerlabs/makeinitaly_foundation.py | get_labs | python | def get_labs(format):
labs = []
# Get the first page of data
wiki = MediaWiki(makeinitaly__foundation_api_url)
wiki_response = wiki.call(
{'action': 'query',
'list': 'categorymembers',
'cmtitle': 'Category:Italian_FabLabs',
'cmlimit': '500'})
if "query-continue" ... | Gets data from all labs from makeinitaly.foundation. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/makeinitaly_foundation.py#L140-L225 | [
"def get_single_lab(lab_slug):\n \"\"\"Gets data from a single lab from makeinitaly.foundation.\"\"\"\n wiki = MediaWiki(makeinitaly__foundation_api_url)\n wiki_response = wiki.call(\n {'action': 'query',\n 'titles': lab_slug,\n 'prop': 'revisions',\n 'rvprop': 'content'})\n\... | # -*- encoding: utf-8 -*-
#
# Access data from makeinitaly.foundation
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
from simplemediawiki import MediaWiki
import pandas as pd
makeinitaly__foundation_api_url = "http://makeinitaly... |
openp2pdesign/makerlabs | makerlabs/utils.py | get_location | python | def get_location(query, format, api_key):
# Play nice with the API...
sleep(1)
geolocator = OpenCage(api_key=api_key, timeout=10)
# Variables for storing the data
data = {"city": None,
"address_1": None,
"postal_code": None,
"country": None,
"county"... | Get geographic data of a lab in a coherent way for all labs. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/utils.py#L18-L110 | null | # -*- encoding: utf-8 -*-
#
# Fuctions for the other modules
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
# Import necessary modules
from geopy.geocoders import OpenCage
from time import sleep
from incf.countryutils import transformations
if __name__ == "__main_... |
openp2pdesign/makerlabs | makerlabs/repaircafe_org.py | data_from_repaircafe_org | python | def data_from_repaircafe_org():
# Use Chrome as a browser
browser = webdriver.Chrome()
# Use PhantomJS as a browser
# browser = webdriver.PhantomJS('phantomjs')
browser.get("https://repaircafe.org/en/?s=Contact+the+local+organisers")
browser.maximize_window()
# Iterate over results (the #v... | Gets data from repaircafe_org. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/repaircafe_org.py#L44-L79 | null | # -*- encoding: utf-8 -*-
#
# Access data from repaircafe.org
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
from geojson import dumps, Feature, Point, FeatureCollection
from geopy.geocoders import Nominatim
import pycountry
from ... |
openp2pdesign/makerlabs | makerlabs/repaircafe_org.py | get_labs | python | def get_labs(format):
data = data_from_repaircafe_org()
repaircafes = {}
# Load all the Repair Cafes
for i in data:
# Create a lab
current_lab = RepairCafe()
# Add existing data from first scraping
current_lab.name = i["name"]
slug = i["url"].replace("https://r... | Gets Repair Cafe data from repairecafe.org. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/repaircafe_org.py#L82-L214 | [
"def data_from_repaircafe_org():\n \"\"\"Gets data from repaircafe_org.\"\"\"\n\n # Use Chrome as a browser\n browser = webdriver.Chrome()\n # Use PhantomJS as a browser\n # browser = webdriver.PhantomJS('phantomjs')\n browser.get(\"https://repaircafe.org/en/?s=Contact+the+local+organisers\")\n ... | # -*- encoding: utf-8 -*-
#
# Access data from repaircafe.org
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
from geojson import dumps, Feature, Point, FeatureCollection
from geopy.geocoders import Nominatim
import pycountry
from ... |
openp2pdesign/makerlabs | makerlabs/timeline.py | get_multiple_data | python | def get_multiple_data():
# Get data from all the mapped platforms
all_labs = {}
all_labs["diybio_org"] = diybio_org.get_labs(format="dict")
all_labs["fablabs_io"] = fablabs_io.get_labs(format="dict")
all_labs["makeinitaly_foundation"] = makeinitaly_foundation.get_labs(
format="dict")
al... | Get data from all the platforms listed in makerlabs. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/timeline.py#L24-L39 | [
"def get_labs(format):\n \"\"\"Gets current UK Makerspaces data as listed by NESTA.\"\"\"\n\n ukmakerspaces_data = data_from_nesta()\n ukmakerspaces = {}\n\n # Iterate over csv rows\n for index, row in ukmakerspaces_data.iterrows():\n current_lab = UKMakerspace()\n current_lab.address_1... | # -*- encoding: utf-8 -*-
#
# Rebuild a timeline of makerlabs
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
# Import all the mapped platforms
import diybio_org
import fablabs_io
import makeinitaly_foundation
import hackaday_io
import hackerspaces_org
import makery_in... |
openp2pdesign/makerlabs | makerlabs/timeline.py | get_timeline | python | def get_timeline(source):
# Set up the pandas timeseries dataframe
timeline_format = ["name", "type", "source", "country", "city", "latitude",
"longitude", "website_url", "twitter_url",
"facebook_page_url", "facebook_group_url",
"whois_start"... | Rebuild a timeline of the history of makerlabs. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/timeline.py#L42-L105 | [
"def get_labs(format, open_cage_api_key):\n \"\"\"Gets DIYBio Lab data from diybio.org.\"\"\"\n\n diybiolabs_soup = data_from_diybio_org()\n diybiolabs = {}\n\n rows_list = []\n continents_dict = {}\n continents_order = 0\n ranges_starting_points = []\n\n # Load all the DIYBio Labs\n # By... | # -*- encoding: utf-8 -*-
#
# Rebuild a timeline of makerlabs
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
# Import all the mapped platforms
import diybio_org
import fablabs_io
import makeinitaly_foundation
import hackaday_io
import hackerspaces_org
import makery_in... |
openp2pdesign/makerlabs | makerlabs/nesta.py | get_labs | python | def get_labs(format):
ukmakerspaces_data = data_from_nesta()
ukmakerspaces = {}
# Iterate over csv rows
for index, row in ukmakerspaces_data.iterrows():
current_lab = UKMakerspace()
current_lab.address_1 = row["Address"].replace("\r", " ")
current_lab.address_2 = row["Region"].... | Gets current UK Makerspaces data as listed by NESTA. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/nesta.py#L47-L105 | [
"def data_from_nesta():\n \"\"\"Read data from the GitHub repo.\"\"\"\n\n data = pd.read_csv(nesta_uk_url)\n\n return data\n"
] | # -*- encoding: utf-8 -*-
#
# Access data from NESTA at https://github.com/nesta-uk/UK-makerspaces
# Data license: CC Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
import pa... |
openp2pdesign/makerlabs | makerlabs/makery_info.py | get_labs | python | def get_labs(format):
labs_json = data_from_makery_info(makery_info_labs_api_url)
labs = {}
# Load all the FabLabs
for i in labs_json["labs"]:
current_lab = MakeryLab()
current_lab.address_1 = i["address_1"]
current_lab.address_2 = i["address_2"]
current_lab.address_not... | Gets Lab data from makery.info. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/makery_info.py#L44-L129 | [
"def data_from_makery_info(endpoint):\n \"\"\"Gets data from makery.info.\"\"\"\n\n data = requests.get(endpoint).json()\n\n return data\n"
] | # -*- encoding: utf-8 -*-
#
# Access data from makery.info
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
import requests
from geojson import dumps, Feature, Point, FeatureCollection
from geopy.geocoders import Nominatim
import pa... |
openp2pdesign/makerlabs | makerlabs/hackaday_io.py | get_labs | python | def get_labs(format):
hackerspaces_json = data_from_hackaday_io(hackaday_io_labs_map_url)
hackerspaces = {}
# Load all the Hackerspaces
for i in hackerspaces_json:
current_lab = Hackerspace()
current_lab.id = i["id"]
current_lab.url = "https://hackaday.io/hackerspace/" + curren... | Gets Hackerspaces data from hackaday.io. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/hackaday_io.py#L57-L137 | [
"def data_from_hackaday_io(endpoint):\n \"\"\"Gets data from hackaday.io.\"\"\"\n\n data = requests.get(endpoint).json()\n\n return data\n"
] | # -*- encoding: utf-8 -*-
#
# Access data from hackaday.io
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
import requests
from geojson import dumps, Feature, Point, FeatureCollection
from geopy.geocoders import Nominatim
import pa... |
openp2pdesign/makerlabs | makerlabs/diybio_org.py | data_from_diybio_org | python | def data_from_diybio_org():
r = requests.get(diy_bio_labs_url)
if r.status_code == 200:
# Fix a problem in the html source while loading it
data = BeautifulSoup(r.text.replace(u'\xa0', u''), "lxml")
else:
data = "There was an error while accessing data on diybio.org."
return d... | Scrapes data from diybio.org. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/diybio_org.py#L34-L45 | null | # -*- encoding: utf-8 -*-
#
# Access data from diybio.org
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
from utils import get_location
import json
from bs4 import BeautifulSoup
import requests
from geojson import dumps, Feature, Point, Featu... |
openp2pdesign/makerlabs | makerlabs/diybio_org.py | get_labs | python | def get_labs(format, open_cage_api_key):
diybiolabs_soup = data_from_diybio_org()
diybiolabs = {}
rows_list = []
continents_dict = {}
continents_order = 0
ranges_starting_points = []
# Load all the DIYBio Labs
# By first parsing the html
# Parse table rows
for row in diybiola... | Gets DIYBio Lab data from diybio.org. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/diybio_org.py#L48-L176 | [
"def get_location(query, format, api_key):\n \"\"\"Get geographic data of a lab in a coherent way for all labs.\"\"\"\n\n # Play nice with the API...\n sleep(1)\n geolocator = OpenCage(api_key=api_key, timeout=10)\n\n # Variables for storing the data\n data = {\"city\": None,\n \"addres... | # -*- encoding: utf-8 -*-
#
# Access data from diybio.org
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
from utils import get_location
import json
from bs4 import BeautifulSoup
import requests
from geojson import dumps, Feature, Point, Featu... |
openp2pdesign/makerlabs | makerlabs/techshop_ws.py | data_from_techshop_ws | python | def data_from_techshop_ws(tws_url):
r = requests.get(tws_url)
if r.status_code == 200:
data = BeautifulSoup(r.text, "lxml")
else:
data = "There was an error while accessing data on techshop.ws."
return data | Scrapes data from techshop.ws. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/techshop_ws.py#L38-L47 | null | # -*- encoding: utf-8 -*-
#
# Access data from techshop.ws
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
from bs4 import BeautifulSoup
import requests
from geojson import dumps, Feature, Point, FeatureCollection
from geopy.geocod... |
openp2pdesign/makerlabs | makerlabs/techshop_ws.py | get_labs | python | def get_labs(format):
techshops_soup = data_from_techshop_ws(techshop_us_url)
techshops = {}
# Load all the TechShops
# By first parsing the html
data = techshops_soup.findAll('div', attrs={'id': 'main-content'})
for element in data:
links = element.findAll('a')
hrefs = {}
... | Gets Techshop data from techshop.ws. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/techshop_ws.py#L50-L191 | [
"def data_from_techshop_ws(tws_url):\n \"\"\"Scrapes data from techshop.ws.\"\"\"\n\n r = requests.get(tws_url)\n if r.status_code == 200:\n data = BeautifulSoup(r.text, \"lxml\")\n else:\n data = \"There was an error while accessing data on techshop.ws.\"\n\n return data\n"
] | # -*- encoding: utf-8 -*-
#
# Access data from techshop.ws
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
from bs4 import BeautifulSoup
import requests
from geojson import dumps, Feature, Point, FeatureCollection
from geopy.geocod... |
openp2pdesign/makerlabs | makerlabs/fablabs_io.py | get_labs | python | def get_labs(format):
fablabs_json = data_from_fablabs_io(fablabs_io_labs_api_url_v0)
fablabs = {}
# Load all the FabLabs
for i in fablabs_json["labs"]:
current_lab = FabLab()
current_lab.name = i["name"]
current_lab.address_1 = i["address_1"]
current_lab.address_2 = i[... | Gets Fab Lab data from fablabs.io. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/fablabs_io.py#L82-L172 | [
"def data_from_fablabs_io(endpoint):\n \"\"\"Gets data from fablabs.io.\"\"\"\n\n data = requests.get(endpoint).json()\n\n return data\n"
] | # -*- encoding: utf-8 -*-
#
# Access data from fablabs.io
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
import requests
from geojson import dumps, Feature, Point, FeatureCollection
from geopy.geocoders import Nominatim
import pyc... |
openp2pdesign/makerlabs | makerlabs/fablabs_io.py | get_projects | python | def get_projects(format):
projects_json = data_from_fablabs_io(fablabs_io_projects_api_url_v0)
projects = {}
project_url = "https://www.fablabs.io/projects/"
fablabs = get_labs(format="object")
# Load all the FabLabs
for i in projects_json["projects"]:
i = i["projects"]
current... | Gets projects data from fablabs.io. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/fablabs_io.py#L183-L269 | [
"def get_labs(format):\n \"\"\"Gets Fab Lab data from fablabs.io.\"\"\"\n\n fablabs_json = data_from_fablabs_io(fablabs_io_labs_api_url_v0)\n fablabs = {}\n\n # Load all the FabLabs\n for i in fablabs_json[\"labs\"]:\n current_lab = FabLab()\n current_lab.name = i[\"name\"]\n cur... | # -*- encoding: utf-8 -*-
#
# Access data from fablabs.io
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
import json
import requests
from geojson import dumps, Feature, Point, FeatureCollection
from geopy.geocoders import Nominatim
import pyc... |
openp2pdesign/makerlabs | makerlabs/hackerspaces_org.py | get_single_lab | python | def get_single_lab(lab_slug, open_cage_api_key):
wiki = MediaWiki(hackerspaces_org_api_url)
wiki_response = wiki.call(
{'action': 'query',
'titles': lab_slug,
'prop': 'revisions',
'rvprop': 'content'})
# If we don't know the pageid...
for i in wiki_response["query"]["... | Gets data from a single lab from hackerspaces.org. | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/hackerspaces_org.py#L32-L142 | null | # -*- encoding: utf-8 -*-
#
# Access data from hackerspaces.org
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: LGPL v.3
#
#
from classes import Lab
from utils import get_location
import json
from simplemediawiki import MediaWiki
import mwparserfromhell
import pandas as pd
hacke... |
wtsi-hgi/gitlab-build-variables | gitlabbuildvariables/executables/gitlab_get_variables.py | _parse_args | python | def _parse_args(args: List[str]) -> ProjectRunConfig:
parser = argparse.ArgumentParser(prog="gitlab-get-variables", description="Tool for getting a GitLab project's "
"build variables")
add_common_arguments(parser, project=True)
a... | Parses the given CLI arguments to get a run configuration.
:param args: CLI arguments
:return: run configuration derived from the given CLI arguments | train | https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/gitlab_get_variables.py#L11-L21 | [
"def add_common_arguments(parser: ArgumentParser, project: bool=False):\n \"\"\"\n Adds common arguments to the given argument parser.\n :param parser: argument parser\n :param url: whether the URL named argument should be added\n :param token: whether the access token named argument should be added\... | import argparse
import json
import sys
from typing import List
from gitlabbuildvariables.common import GitLabConfig
from gitlabbuildvariables.executables._common import add_common_arguments, ProjectRunConfig
from gitlabbuildvariables.manager import ProjectVariablesManager
def main():
"""
Main method.
""... |
wtsi-hgi/gitlab-build-variables | gitlabbuildvariables/executables/gitlab_get_variables.py | main | python | def main():
run_config = _parse_args(sys.argv[1:])
gitlab_config = GitLabConfig(run_config.url, run_config.token)
manager = ProjectVariablesManager(gitlab_config, run_config.project)
output = json.dumps(manager.get(), sort_keys=True, indent=4, separators=(",", ": "))
print(output) | Main method. | train | https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/gitlab_get_variables.py#L24-L32 | [
"def _parse_args(args: List[str]) -> ProjectRunConfig:\n \"\"\"\n Parses the given CLI arguments to get a run configuration.\n :param args: CLI arguments\n :return: run configuration derived from the given CLI arguments\n \"\"\"\n parser = argparse.ArgumentParser(prog=\"gitlab-get-variables\", des... | import argparse
import json
import sys
from typing import List
from gitlabbuildvariables.common import GitLabConfig
from gitlabbuildvariables.executables._common import add_common_arguments, ProjectRunConfig
from gitlabbuildvariables.manager import ProjectVariablesManager
def _parse_args(args: List[str]) -> ProjectR... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.