예제 #1
0
class TestShortId(unittest.TestCase):
    def setUp(self):
        self.shortid = ShortId()

    def test_should_be_unambiquous_on_a_bunch_of_iterations(self):
        ids = []
        for i in range(0, 100000):
            ids.append(self.shortid.generate())

        self.assertEqual(len(set(ids)), len(ids))

    def test_should_be_unambiquous_on_a_bunch_of_iterations_new_instance(self):
        ids = []
        for i in range(0, 100000):
            ids.append(ShortId().generate())

        self.assertEqual(len(set(ids)), len(ids))

    def test_generate_max_length(self):
        lengths = []
        for i in range(0, 50000):
            lengths.append(len(self.shortid.generate()))
        self.assertEqual(max(lengths) < 12, True)


    def test_generate_max_length_new_instance(self):
        lengths = []
        for i in range(0, 50000):
            lengths.append(len(ShortId().generate()))
        self.assertEqual(max(lengths) < 12, True)
예제 #2
0
class TestShortId(unittest.TestCase):
    def setUp(self):
        self.shortid = ShortId()

    def test_should_be_unambiquous_on_a_bunch_of_iterations(self):
        ids = []
        for i in range(0, 100000):
            ids.append(self.shortid.generate())

        self.assertEqual(len(set(ids)), len(ids))

    def test_should_be_unambiquous_on_a_bunch_of_iterations_new_instance(self):
        ids = []
        for i in range(0, 100000):
            ids.append(ShortId().generate())

        self.assertEqual(len(set(ids)), len(ids))

    def test_generate_max_length(self):
        lengths = []
        for i in range(0, 50000):
            lengths.append(len(self.shortid.generate()))
        self.assertEqual(max(lengths) < 12, True)

    def test_generate_max_length_new_instance(self):
        lengths = []
        for i in range(0, 50000):
            lengths.append(len(ShortId().generate()))
        self.assertEqual(max(lengths) < 12, True)
예제 #3
0
파일: user.py 프로젝트: DESECTORCON/noteit
    def __init__(self,
                 email,
                 password,
                 _id=None,
                 nick_name=None,
                 last_logined=datetime.datetime.now(),
                 friends=[],
                 group_id=None,
                 picture=None):
        """

        :param email:
        :param password:
        :param _id:
        :param nick_name:
        :param last_logined:
        :param friends:
        :param group_id:
        """
        self.email = email
        self.password = password
        self._id = uuid.uuid4().hex if _id is None else _id
        sid = ShortId()
        self.nick_name = "User " + sid.generate(
        ) if nick_name is None else nick_name
        self.last_logined = last_logined
        self.friends = friends
        self.group_id = group_id
        if picture is None:
            self.picture = 'img/index.jpg'
        else:
            self.picture = picture
예제 #4
0
    def copy_to_clipboard(self):
        clipboard = QApplication.clipboard()

        if self.canvas.mode == 'selectrect' and self.canvas.locked:
            clipboard.setPixmap(self.canvas.selectrect_copy())
            sid = ShortId()
            id = sid.generate()
            path =r'.//stamps//' + id + '.png'
            STAMPS.insert(0, path)
            self.canvas.selectrect_copy().save(path, "PNG")
            self.current_stamp_n = -1
            self.next_stamp()
            self.canvas.set_mode('selectrect')

        elif self.canvas.mode == 'selectpoly' and self.canvas.locked:
            clipboard.setPixmap(self.canvas.selectpoly_copy())
            path, _ = QFileDialog.getSaveFileName(self, "Save file", "", "PNG Image file (*.png)")
            self.canvas.selectrect_copy().save(path, "PNG")
            # sid = ShortId()
            # id = sid.generate()
            # path = r'.//stamps//' + id + '.png'
            # STAMPS.insert(0, path)
            # self.canvas.selectrect_copy().save(path, "PNG")
            # self.current_stamp_n = -1
            # self.next_stamp()
            # self.canvas.set_mode('selectpoly')
        else:
            clipboard.setPixmap(self.canvas.pixmap())
예제 #5
0
 def __init__(self,
              email,
              password,
              _id=None,
              nick_name=None,
              last_logined=datetime.datetime.now()):
     self.email = email
     self.password = password
     self._id = uuid.uuid4().hex if _id is None else _id
     sid = ShortId()
     self.nick_name = "User " + sid.generate(
     ) if nick_name is None else nick_name
     self.last_logined = last_logined
예제 #6
0
파일: models.py 프로젝트: jdcantrell/spice
    def __init__(
        self, name, filename, path, handler, filetype, access, user_id
    ):
        self.name = name
        self.filename = filename
        self.path = path
        self.handler = handler
        self.filetype = filetype
        self.user_id = user_id
        self.access = access
        sid = ShortId()
        self.key = sid.generate()

        self.views = 0
예제 #7
0
class TestShortId(unittest.TestCase):
    def setUp(self):
        self.shortid = ShortId()

    def test_should_be_unambiquous_on_a_bunch_of_iterations(self):
        ids = []
        for i in range(0, 50000):
            ids.append(self.shortid.generate())

        self.assertEqual(len(set(ids)), len(ids))
예제 #8
0
class TestShortId(unittest.TestCase):
    def setUp(self):
        self.shortid = ShortId()

    def test_should_be_unambiquous_on_a_bunch_of_iterations(self):
        ids = []
        for i in range(0, 50000):
            ids.append(self.shortid.generate())

        self.assertEqual(len(set(ids)), len(ids))

    def test_shortid_should_generate_the_right_string_length(self):
        self.assertEqual(len(shortid(7)), 7)

    def test_shortid_should_use_the_right_alphabet(self):
        self.assertTrue(re.match(r'^[a-zA-Z0-9_-]+$', shortid()))

    def test_generate_should_use_the_right_alphabet(self):
        self.assertTrue(re.match(r'^[a-zA-Z0-9_-]+$', self.shortid.generate()))

    def test_generate_should_generate_the_right_string_length(self):
        self.assertTrue(7 <= len(shortid(7)) <= 14)
예제 #9
0
파일: pool_executor.py 프로젝트: asrvsn/lkf
def pool_execute(args: list,
                 gen_system: Callable,
                 seed=None,
                 reduce_result=lambda x: x):
    global _implicit_gen
    _implicit_gen = gen_system

    idgen = ShortId()
    results = dict()

    with tqdm(total=len(args)) as pbar:

        def add_result(result):
            results[result['id']] = reduce_result(result)
            pbar.update(1)

        with multiprocessing.Pool() as pool:
            for arg in args:
                arg['id'] = idgen.generate()
                pool.apply_async(worker, args=(arg, seed), callback=add_result)
            pool.close()
            pool.join()

    return [results[arg['id']] for arg in args]
예제 #10
0
    async def send_message(self, category: SubscribeCategory, msg):
        wait_count = 0
        if not self._socket or not self._sid:
            self._log.debug("waiting for socket to init and handshake")
            wait_count += 1
            if wait_count < 5:
                await asyncio.sleep(1)

        # build the message
        rid = ShortId()
        socket_msg = json.dumps({
            "rid": f"rid:{rid.generate()}",
            "sid": self._sid,
            "request": category,
            "payload": json.dumps(msg)
        })
        await self._socket.send(socket_msg)
예제 #11
0
    def __init__(
            self,
            api_key: str = '17paIsICur8sA0OBqG6dH5G1rmrHNMwt4oNk4iX9',
            version: str = '1.0.0',
            ws_endpoint: str = 'wss://datastream.idex.market',
            handshake_timeout: float = 1.0,
            return_sub_responses=False,
            loop: AbstractEventLoop = None
    ):
        self._API_KEY = api_key
        self._WS_ENDPOINT = ws_endpoint
        self._WS_VERSION = version
        self._HANDSHAKE_TIMEOUT = handshake_timeout

        self._loop = loop or asyncio.get_event_loop()
        self._logger = logging.getLogger(__name__)

        self._rid = ShortId()

        self.sub_manager = SubscriptionManager(self, return_sub_responses)
예제 #12
0
from collections import defaultdict
from copy import deepcopy
from numbers import Number

import six
from shortid import ShortId

from swimlane.core.fields.base import FieldCursor
from swimlane.exceptions import ValidationError
from .base import CursorField

SID = ShortId()


class _ListFieldCursor(FieldCursor):
    """Base class for Text and Numeric FieldCursors emulating a basic list"""
    def _validate_list(self, target):
        """Validate a list against field validation rules"""
        # Check list length restrictions
        min_items = self._field.field_definition.get('minItems')
        max_items = self._field.field_definition.get('maxItems')

        if min_items is not None:
            if len(target) < min_items:
                raise ValidationError(
                    self._record,
                    "Field '{}' must have a minimum of {} item(s)".format(
                        self._field.name, min_items))

        if max_items is not None:
            if len(target) > max_items:
예제 #13
0
 def setUp(self):
     self.shortid = ShortId()
예제 #14
0
 def setUp(self):
     self.shortid = ShortId()
예제 #15
0
import json
from shortid import ShortId

sid = ShortId()

stations = {}
lines = {}


def read_file(filename='./data/subway_link_data.json'):
    with open(filename, 'r') as f:
        return json.loads(f.read())


def write_file(data, filename='./data/subway_link.json'):
    with open(filename, 'w') as f:
        f.write(
            json.dumps(data,
                       ensure_ascii=False,
                       indent=2,
                       separators=(',', ': ')))


def get_subway_node(filename):
    subway_nodes = {}
    return subway_nodes


def convert(data):
    buf = {}
    for d in data:
]
nombre_dia = [
    'Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo'
]
covid_df['month_name'] = covid_df['month'].transform(
    lambda value: nombre_mes[int(value) - 1])
covid_df['day_name'] = covid_df['date'].transform(
    lambda value: nombre_dia[date(int(value.split('/')[
        2]), int(value.split('/')[1]), int(value.split('/')[0])).weekday()])
# Show dataframe
covid_df.head()

# %%
# Update Case ID
covid_df['id_case'] = covid_df['id_case'].transform(
    lambda value: ShortId().generate())
covid_df['id_case'] = covid_df['sex'] + covid_df['id_case'] + covid_df['age']
covid_df.head()

# %%
# Sort columns
covid_df = covid_df[[
    'id_case', 'date', 'day', 'month', 'year', 'month_name', 'day_name',
    'city', 'dept_dist', 'age', 'sex', 'kind', 'country_origin', 'care'
]]
covid_df.head()

# %% [markdown]
# ## Covid 19 Dataset
# > ***Output file***: covid19_co.csv
예제 #17
0
from eight_mile.utils import read_yaml
from odin.http.models import *
from odin.http.orm import *
from odin.http.utils import (
    _convert_to_path,
    set_repo_creds,
    _request_status,
    _submit_job,
    _request_cleanup,
    _request_data,
    _request_events,
    _validate_filename,
)
import jose.jwt as jwt
# This indicates what branch we should be looking at in git for its pipelines
SHORT_ID = ShortId()
PIPELINES_MAIN = os.environ.get('ODIN_PIPELINES_MAIN', 'master')
RENDERED_TEMPLATES = os.environ.get('ODIN_RENDER_PATH', 'rendered')
JWT_ISSUER = os.environ.get('ODIN_AUTH_ISSUER', 'com.interactions')
JWT_SECRET = os.environ.get('ODIN_SECRET')
JWT_LIFETIME_SECONDS = os.environ.get('ODIN_TOKEN_DURATION', 60 * 60 * 12)
JWT_ALGORITHM = os.environ.get('ODIN_AUTH_ALG', 'HS256')
MIDGARD_PORT = os.environ.get('MIDGARD_PORT', 29999)
MIDGARD_API_VERSION = os.environ.get('MIDGARD_API_VERSION', 'v1')
LOGGER = logging.getLogger('odin-http')
WS_SCHEME = os.environ.get('ODIN_WS_SCHEME', 'ws')
WS_HOST = os.environ.get('ODIN_WS_HOST', 'localhost')
WS_PORT = os.environ.get('ODIN_WS_PORT', 30000)
ODIN_DB = os.getenv('ODIN_DB', 'odin_db')
ODIN_FS_ROOT = os.getenv('ODIN_FS_ROOT', '/data/pipelines')
LOGGER = logging.getLogger('odin-http')
예제 #18
0
파일: models.py 프로젝트: jdcantrell/kodiak
 def __init__(self, data, access='limited'):
     self.data = data
     self.access = access
     sid = ShortId()
     self.key = sid.generate()
예제 #19
0
from __future__ import print_function

import os
import cv2
import requests
import json
import numpy as np

from FaceRecognition import *
from local_settings import *
from face import *
from upload import upload
from shortid import ShortId

sid = ShortId()

BACKEND_URL = 'http://127.0.0.1:8000'

def save_face(img, filename):
    # 获取人头位置
    try:
        position = img.cut_face('default.png')
        rect = tuple(position[0])
    except Exception, e:
        return ''
    
    img.face_roi('cut.png', rect)
    fina = img.resize(img.read('cut.png'), (100, 100))
    img.save('./images/%s.png' % filename, fina)
    return './images/%s.png' % filename
예제 #20
0
    def generate_uid() -> str:
        """ Static helper method to generate an identifier.

        :return:
        """
        return ShortId().generate()
예제 #21
0
"""
This tracks anonymized usage statistics of gluestick using Mixpanel.
If you'd like to disable this, please refer to the gluestick docs https://docs.gluestick.xyz
"""
import os

from mixpanel import Mixpanel
from shortid import ShortId

mp = Mixpanel('c1183ed0e00132d88ad169ddd3f3673b')
sid = ShortId()
anon_id = sid.generate()

def track(event_name, event_data = {}):
    """
    Sends event to Mixpanel using anon_id 
    """
    # Check if usage stat collection is enabled
    is_enabled = os.environ.get("GLUESTICK_USAGE_STATS", "ENABLE") == "ENABLE"
    if not is_enabled:
        return

    # Send event to Mixpanel
    mp.track(anon_id, event_name, event_data)

예제 #22
0
 def test_generate_max_length_new_instance(self):
     lengths = []
     for i in range(0, 50000):
         lengths.append(len(ShortId().generate()))
     self.assertEqual(max(lengths) < 12, True)
예제 #23
0
    def test_should_be_unambiquous_on_a_bunch_of_iterations_new_instance(self):
        ids = []
        for i in range(0, 100000):
            ids.append(ShortId().generate())

        self.assertEqual(len(set(ids)), len(ids))
예제 #24
0
import datetime as dt

from shortid import ShortId
import boto3
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all

from src.models import ShortenedLink
from src.exceptions import ExternalError, InternalError

client = boto3.client('events')

# apply the XRay handler to all clients.
patch_all()

shortid = ShortId()
logger = logging.getLogger(__name__)
if os.environ['STAGE'] == 'dev':
    logger.setLevel(logging.DEBUG)
else:
    logger.setLevel(logging.INFO)


def handler(event, context):
    """
    Creates a shortened link for a given URL and returns said URL
    :param event:
    :param context:
    :return:
    """
    logger.debug(f'Received event: {event}')