content stringlengths 5 1.05M |
|---|
import os
import sys
import datetime
from unipath import Path
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = Path(__file__).ancestor(3)
sys.path.append(BASE_DIR.child('apps'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2... |
from .note import Note |
from typing import Any, Dict
from ....models.models import Speaker
from ....shared.exceptions import ActionException
from ....shared.filters import And, FilterOperator
from ....shared.patterns import Collection
from ...generics.delete import DeleteAction
from ...generics.update import UpdateAction
from ...mixins.creat... |
class CommonFinders(object):
@classmethod
def get_ignore_words(cls):
return set(['the', 'of', 'to', 'and', 'a', 'in', 'is', 'it'])
|
from sklearn import cluster
from sklearn import mixture
from sklearn.externals import joblib
import numpy as np
import pandas as pd
class Clustering(object):
def __init__(self, X_train, config, verbose):
self.model_names = config['model_names']
self.n_clusters = config['n_clusters']
self.ad... |
"""Tests for transform calculations."""
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import numpy as np
import scenepic as sp
PI = np.array(np.pi, np.float32)
ANGLE = 60 * PI / 180
COS = np.cos(ANGLE)
SIN = np.sin(ANGLE)
VEC = np.array([0.1, 0.2, 0.3], np.float32)
def test_scale_1():
... |
import click, os
@click.command()
@click.argument("seqfiles", required=True, type=click.STRING, nargs=-1)
@click.option("--names", "-n", required=True, type=click.STRING, help="File of names to subset by.")
@click.option("--output", "-o", required=True, type=click.STRING, help="Output seqfile.")
def by_names_cmd(seqfi... |
import configparser
import pandas as pd
import argparse
from pathlib import Path
import logging
import time
from mastodon import Mastodon
logger = logging.getLogger()
temps_debut = time.time()
config = configparser.ConfigParser()
config.read("config.ini")
def mastodonconnect():
if not Path("mastod... |
# coding=utf-8
from flask import Flask
from flask.ext.redis import FlaskRedis
from redis import StrictRedis
from wechat_sdk import WechatConf
app = Flask(__name__)
app.config.from_envvar('MY_WECHAT_APP_SETTINGS')
redis_store = FlaskRedis.from_custom_provider(StrictRedis, app)
wechat_conf = WechatConf(
token=app.c... |
import cv2
import numpy as np
import os
path="./dataset/"
gestures = os.listdir(path)
print(gestures)
x, y = [], []
dict_labels = {
'A': 1,
'B': 2,
'C':3,
'D':4,
'E':5,
'F':6,
'G':7,
'H':8,
'I':9,
'K':10,
'L':1... |
import pytest
from sparkles.mongo_tools import (
replace__id_with_id,
mongo_query_to_list_of_dicts,
clean_json,
)
class MockMongoEngObj:
def to_mongo(self):
return MockInner()
class MockInner:
def to_dict(self):
return {"_id": 123}
@pytest.fixture
def mongoengine_query():
r... |
#!/usr/bin/python
###############################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Apache License Version 2.0 (the "License"). Y... |
#!/usr/bin/env python
#
# Copyright (c) 2013-2016, ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by writing to:
# ETH Zurich D-INFK, Universitaetstr. 6, CH-8092 Zurich. Attn: Systems Group.
import socket... |
"""
Rhino Python Script Tutorial
Exercise 04
More for.
Let's work with this some more.
This is a parabola.
"""
import rhinoscriptsyntax as rs
import math
def Main():
for i in range(0,10):
rs.AddPoint([5 * i, 0.6 * i * i, 0])
"""
i = 0
rs.AddPoint([5 * i, 0.6 * i... |
#!/bin/python
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import random
random.seed(1)
|
# Copyright (c) 2020 Leeman Geophysical LLC.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Contains utilities to work with "look" style data files and associated "r" files."""
from pathlib import Path
import struct
import warnings
import numpy as np
from pint.e... |
from application import db,app
from flask_login import current_user
from application.models import Base
from sqlalchemy.sql import text
class Location(Base):
__tablename__ = "location"
address = db.Column('address', db.String(144), nullable=False)
postal_code = db.Column('postal_code', db.Integer(), nulla... |
# Copyright (c) 2019 Georgia Tech Robot Learning Lab
# Licensed under the MIT License.
from abc import abstractmethod
from rl.core.oracles import Oracle
class rlOracle(Oracle):
""" rlOracle interacts in terms of `ro` which is a Dataset. """
# `fun`, `grad`, `hess` should now take policy.variable as input.
... |
import cv2
import numpy as np
from skimage.transform import rescale
from PIL import Image, ImageDraw
from matplotlib import cm
def generate_thumbnails(g, type):
thumb_dict = {}
for well in g.wells:
if type == '':
path = g.work.joinpath(g.plate, well, 'img', g.plate + '_' + well + '.png')
... |
# Author: Dushyant Singh
# Company: Truth Power Info.
# March-11-2022 IST
import cv2
import mediapipe as mp
# Importations and initializations
class handTracker():
def __init__(self, mode=False, maxHands=2, detectionCon=0.5,modelComplexity=1,trackCon=0.5):
self.mode = mode
self.maxHand... |
from trading_ig import IGService
from trading_ig.config import config
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# if you need to cache to DB your requests
from datetime import timedelta
import requests_cache
from predefined_functions.initialisation import Initialisation
class... |
# Are there multiple solutions to vP and vP for a given vD and vphi?
# Front matter
##############
import os
from os import fdopen, remove
from tempfile import mkstemp
from shutil import move
import glob
import re
import time
import pandas as pd
import numpy as np
from scipy import constants
from scipy.optimize import... |
"""Unit tests for the GitLab hosting service."""
from django.utils.safestring import SafeText
from reviewboard.hostingsvcs.errors import RepositoryError
from reviewboard.hostingsvcs.gitlab import (GitLabAPIVersionError,
GitLabHostingURLWidget)
from reviewboard.hostingsvcs.t... |
#!/usr/bin/python3
# Copyright (c) 2020 Intel Corporation.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modif... |
import argparse
import logging
from dvc.command.base import CmdBaseNoRepo, append_doc_link
from dvc.config import Config, ConfigError
logger = logging.getLogger(__name__)
class CmdConfig(CmdBaseNoRepo):
def __init__(self, args):
super().__init__(args)
self.config = Config(validate=False)
d... |
#!/usr/bin/python3
import cgi, cgitb ,json
from elasticsearch import Elasticsearch
from email.utils import parseaddr
import json
import re
es_client = Elasticsearch(['http://172.30.0.7:9200'])
def api(jsonv):
print("Content-type: application/json\r\n\r\n")
print(json.dumps(jsonv))
exit()
def verify_email(mail):
... |
import os
import subprocess
from config import Config
class Eshtmc:
def __init__(self, config):
self.config = config
def git_operation(self, operation):
pass
def git_clone(self):
if not os.path.exists(self.config.repository_save_path):
cmd = "git clone " + self.config... |
class MirrorModifier:
merge_threshold = None
mirror_object = None
mirror_offset_u = None
mirror_offset_v = None
use_clip = None
use_mirror_merge = None
use_mirror_u = None
use_mirror_v = None
use_mirror_vertex_groups = None
use_x = None
use_y = None
use_z = None
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-10-19 09:35
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations... |
from django.http.response import Http404, JsonResponse
from django.db.models import Q
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import BookSerializer, FavoriteSerializer, ToReadSerializer
from .models import Book, Favorit... |
from django.shortcuts import render
from django.views.generic.detail import DetailView
from datasource.models import Album, Track
class AlbumDetailView(DetailView):
model = Album
template_name = 'album_view.html'
def get_context_data(self, **kwargs):
context = super(AlbumDetailView, self).get_... |
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Joy
from sightedturtlesim.msg import VelocityXYZ, DriveXYZ, TurtleParams
from sightedturtlesim.srv import SetTurtleParams
class Teleop:
def __init__(self):
self.params = TurtleParams()
rospy.init_node('teleop_sighted_turtle_joy')
... |
"""
Tests for grdfilter.
"""
import os
import numpy as np
import pytest
import xarray as xr
from pygmt import grdfilter, load_dataarray
from pygmt.exceptions import GMTInvalidInput
from pygmt.helpers import GMTTempFile
from pygmt.helpers.testing import load_static_earth_relief
@pytest.fixture(scope="module", name="g... |
class Command:
"""
Abstract command class to hold the command logic, the tag properties and the children and parent commands
Available implementations:
Ignore
Strip
Wrap
WrapIn
WrapOut
WrapWithAttribute
Config
Table
"""
_bullet = " * ... |
def create_stalking_data_dict(stalking_data):
stalking_data_dict = {}
for item in stalking_data:
user_id = int(item["user_id"]) #Decimal型をint型に変更
atcoder_id = item["atcoder_id"]
if(user_id in stalking_data_dict):
stalking_data_dict[user_id].append(atcoder_id)
else... |
class Ant(object):
last_position = None
tour = []
"""docstring for Ant"""
def __init__(self, name, initial_position):
super(Ant, self).__init__()
self.name = name
self.__position = initial_position
@property
def position(self):
return self.__position
@pos... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.scatter import Scatter
from kivy.properties import StringProperty
from kivy.graphics import Ellipse,Color
from museolib.widgets.tutorials.tutoitem import TutoItem
from random import... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'findandreplacedlg.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_FindAndReplaceDlg(object):
def setupUi(self, FindAndRepla... |
from datetime import datetime as Datetime
from enum import Enum
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import models
from django.urls import reverse
from django.utils.timezone import now
from djang... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Author: pirogue
Purpose: 获取白名单ip
Site: http://pirogue.org
Created: 2018-08-27 15:35:43
"""
import tornado
from handlers.base import BaseHandler
from util.auth import jwtauth
from service.whiteipservice import whiteips
# from dbs.dal.LogOperate import LogOp
im... |
from django.test import TestCase
from faker import Faker
from api.users.models import User
from ..models import BadThing, BadThingType
class BadThingTypeTest(TestCase):
def setUp(self):
self.faker = Faker()
self.username = self.faker.name()
self.user = User.objects.create(username=self.... |
import re
txtfile = "d6.txt"
example1 = [
"turn on 0,0 through 999,999",
"toggle 0,0 through 999,0",
"turn off 499,499 through 500,500"
]
answer = 998996
example2 = [
"turn on 0,0 through 0,0",
"toggle 0,0 through 999,999"
]
answer = 2000001
def day_a(test=False):
if test:
inputs = example
else:
inputs =... |
from datetime import datetime
import matplotlib.pyplot as plt
import io
import cv2
plt.switch_backend('agg')
def separate_bn_paras(modules):
if not isinstance(modules, list):
modules = [*modules.modules()]
paras_only_bn = []
paras_wo_bn = []
for layer in modules:
if 'model' in str(layer... |
def example_broadcast_encoder_fn(value):
"""Function for building encoded broadcast.
This method decides, based on the tensor size, whether to use lossy
compression or keep it as is (use identity encoder). The motivation for this
pattern is due to the fact that compression of small model weights can provide
... |
"""
Created on Wed Sep 25 13:57:11 2019
By submitting this assignment , I agree to the following :
"Aggies do not lie , cheat , or steal , or tolerate those who do ."
"I have not given or received any unauthorized aid on this assignment ."
Names: Sameer Hussain
ENGR 102 - 214
Professor: Dr.Socolofsky
As... |
r = 0
while r == 0:
s = str(input('Informe seu sexo: [M/F] ')).strip().upper()[0]
if s == 'M' or s == 'F':
r = 1
print('Sexo {} registrado com sucesso!'.format(s))
else:
print('Dado inválido! Tente novamente.')
|
#!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
from django.core import urlresolvers
from notices import HttpResponseRedirectWithNotice
from notices import allowed_notice_types
def redirect(to, *args, **kwargs):
"""
Extension of redirect shortcut included with Django. Takes one additional
keyword agrument: `notice`. Does not support permanent redirects... |
# Generated by Django 2.2 on 2019-06-04 15:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('device_model', '0002_auto_20190604_1516'),
]
operations = [
migrations.AddField(
model_name='modulebuild',
name='ports... |
#
# ----------------------------------------------------------------------------
# Extracted from pygaarst by Frank Warmerdam, original license is:
# The MIT License (MIT)
# Copyright (c) 2013 Chris Waigl
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated do... |
import cppyy
import numpy as np
from .ortho_tools import RPCCoeffs
cpp_source = """
#include <cmath>
template <class T> constexpr float interpolate(float x, float y, T source, int source_height) {
int x_floor = static_cast<int>(std::floor(x));
int x_ceil = static_cast<int>(std::ceil(x));
int y_floor = ... |
#!/usr/bin/python2
# ////////////////////////////////////////////////////////////////////////////////
# // Company: Multitherman Laboratory @ DEIS - University of Bologna //
# // Viale Risorgimento 2 40136 //
# // Bologna - fax 0512093785 - ... |
class Memory:
"""
Class representing main memory as an array
"""
def __init__(self, size, block_size):
self.size = size
self.block_size = block_size
self.data = [0 for i in range(size)]
def get_block(self, address):
"""
Get a block of memory that contains the b... |
from huiAudioCorpus.persistenz.AudiosFromLibrivoxPersistenz import AudiosFromLibrivoxPersistenz
from huiAudioCorpus.utils.DoneMarker import DoneMarker
class Step1_DownloadAudio:
def __init__(self, audiosFromLibrivoxPersistenz: AudiosFromLibrivoxPersistenz, savePath: str):
self.savePath = savePath
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from . import utilities
from .base import Base, Error, loadable
from . import media_list
class AnimeList(media_list.MediaList):
__id_attribute = "username"
def __init__(self, session, user_name):
super(AnimeList, self).__init__(session, user_name)
@prop... |
from django.apps import AppConfig
class CmctConfig(AppConfig):
name = 'pt.snippets'
# verbose_name = "Cmct"
|
import argparse
import os.path as osp
import mmcv
from PIL import Image
def parse_args():
parser = argparse.ArgumentParser(
description='Process a checkpoint to be published')
parser.add_argument('img_dir', help='img config directory')
parser.add_argument('gt_dir', help='gt config directory')
... |
import sublime, sublime_plugin
class bubbleTabs(sublime_plugin.EventListener):
def on_activated(self,view):
view.window().set_view_index(view.window().active_view(),0,0)
|
import pandas as pd
import numpy as np
data = {"Economy": ["BD", "BD", "BD", "BD", "BD", "BD", "INA", "INA", "INA", "INA", "INA", "INA"],
"Tech": ["Hydro", "Hydro", "Hydro", "GT", "GT", "GT", "Hydro", "Hydro", "Hydro", "GT", "GT", "GT"],
"Capacity": [24, 28, 40, 22, 29, 33, 31, 26, 21, 36, 25, 31]}
df = pd.DataFr... |
# utility.py
import numpy as np
import pandas as pd
import scipy.stats as stats
from scipy.stats import chi2
from sklearn.preprocessing import LabelEncoder
from sklearn.base import BaseEstimator, TransformerMixin
class DataFrameImputer(BaseEstimator, TransformerMixin):
def __init__(self):
"""Impute missi... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None or l2 is None:
raise Exception("At least one list is emp... |
from __future__ import print_function
import os
import sys
import subprocess
r_dependencies = ["RSQLite", "plyr", "gplots", "devtools", "ggplot2"]
r_github_dependencies = ["ucd-cws/wq-heatplot"]
def set_up_r_dependencies():
import launchR # imported here because it will be installed before this is called, but won... |
"""
=======================================================
Visualize Networks (Animated version)
=======================================================
The goal of this demo is to show how to visualize a
complex network and use an force directed algorithm to
layout the network. A simpler animation of the network
mad... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session as SessionClass
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
Base = declarative_base()
##
# DB 接続の準備
#
class MasterSlaveSession(SessionClass):
is_updating = False
def get_bi... |
#!/usr/bin/python
from utils import *
import sys
def format(scriptName, scriptList, version):
return '// All symbols in the `' + scriptName + '` script as per Unicode v' + version + ':\n[\n\t\'' + '\',\n\t\''.join(scriptList) + '\'\n];'
def main(sourceFile, version):
dictionary = parseScriptsOrProps(sourceFile, Tr... |
from django.contrib import admin
from ..models import Timezone
@admin.register(Timezone)
class TimezoneAdmin(admin.ModelAdmin):
list_per_page = 25
list_display = (
'name_id',
'country',
'gmt_offset',
'dst_offset',
'raw_offset',
'is_active',
'slug',
... |
import numpy as np
from src.agent import Agent
from src.banana_env import BananaEnv
class RandomAgent(Agent):
def __init__(self, env: BananaEnv):
super().__init__(env)
def compute_action(self, state):
return np.random.randint(self.env.action_size)
|
# -*- coding: utf-8 -*-
from _newton import lib
print(lib.newton(100, 30))
|
z test zaimportuj support
# If we end up przy a significant number of tests that don't require
# threading, this test module should be split. Right now we skip
# them all jeżeli we don't have threading.
threading = support.import_module('threading')
z contextlib zaimportuj contextmanager
zaimportuj imaplib
zaimportuj... |
import time
import csmapi
#import db, ec_config
def query_binding_devices(db):
session = db.get_session()
bindingDevices = (session.query(db.Device.mac_addr, db.Device.d_name, db.DeviceModel.dm_name, db.Device.dm_id, db.Device.d_id)
.select_from(db.Device)
.join(db... |
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
class ThinG(BaseModel):
attribute_s: Optional[Dict[str, Any]] = Field(None, alias='attribute-s')
class ThanG(BaseModel):
attributes: Optional[List[Dict[str, Any]]] = None
class ClonE(Thi... |
"""
# Copyright 2022 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
import asyncio
from blinker.base import Signal
try: # for Python3.7+
create_task = asyncio.create_task
except AttributeError: # for versions prior to Python3.7
create_task = asyncio.ensure_future
async def _wrap_plain_value(value):
"""Pass through a coroutine 'value' or wrap a plain value"""
if a... |
#Copyright 2011 SRI International
#Modifications Copyright 2014 University Corporation for Atmospheric Research (UCAR)
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apach... |
"""
dc_custom_layers.py
Custom layers for convolutional neural networks
@author: David Van Valen
"""
"""
Import python packages
"""
import numpy as np
from numpy import array
import matplotlib
import matplotlib.pyplot as plt
import shelve
from contextlib import closing
import os
import glob
import re
import numpy ... |
# https://oeis.org/A002717
from math import floor
def solve(n):
return floor(n*(n+2)*(2*n+1)//8)
|
# ------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -------------------------------------------------------------------------
import date... |
import logging
import sys
from functools import wraps
from typing import Callable
import backoff
import django.db.backends.utils
from MySQLdb import (
OperationalError as MySQLOperationalError,
DatabaseError as MySQLDatabaseError
)
from backoff import random_jitter
from django.db import (
OperationalError ... |
s=input();print(s[0].capitalize()+s[1::])
|
from multiprocessing import Process
from time import sleep
def target_function(name: str) -> None:
print(f'Hi -> {name}')
sleep(2)
if __name__ == '__main__':
process = Process(target=target_function, kwargs={'name': 'Bruno'})
process.start()
process.join()
print('Process joined')
|
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
# http://www.apache.org/licenses/LICENSE-2.0
# or in the "license" file... |
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--tokens', type=str,
help='file containing the tokens '
'to be removed from the input file')
parser.add_argument('-o', '--output', type=str,
help='name... |
"""
This package a pyqt distutils hook to replace PyQt5 by our own (
qxpatheditor.qt).
"""
def fix_qt_imports(path):
with open(path, 'r') as f_script:
lines = f_script.read().splitlines()
new_lines = []
for l in lines:
if l.startswith("import "):
l = "from . " + l
if "f... |
# Lint as: python3
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... |
"""
Test utility functions
"""
import pytest
from ..utils import format_unit, check_latex_variable_name
def test_check_latex_variable_name():
"""
Test the check for the format of the LaTeX variable name
"""
check_latex_variable_name("MyVariable")
check_latex_variable_name("myVariable")
check_... |
import json
import os
import datetime
import csv
from random import randint
class sandbox_platform():
"""Simulate a trading platform
"""
# Init, load & save status
def __init__(self, filename = 'sandbox_platform.json', activity_log_file = 'platform.log'):
self.status = {}
self... |
# Copyright (C) PyZMQ Developers
# Distributed under the terms of the Modified BSD License.
import zmq
from zmq.tests import BaseZMQTestCase, GreenTest, have_gevent
class TestMultipart(BaseZMQTestCase):
def test_router_dealer(self):
router, dealer = self.create_bound_pair(zmq.ROUTER, zmq.DEALER)
... |
# from datetime import timedelta, datetime
from celery.utils.log import get_task_logger
# from rest_framework.response import Response
# from rest_framework import status
from bm.taskapp.celery import app
from weather2.utils import get_air_pollution_data, GAS_TYPE_CHOICES
logger = get_task_logger(__name__)
@app.t... |
import base64
import json
from binascii import hexlify
from datetime import datetime
from bs4 import Tag
from pymonad.maybe import Maybe
from dataclasses import is_dataclass
from .log import get_logger
from .types_parliament import House
json_d = json.JSONEncoder.default
log = get_logger(__file__)
class AusBillsJs... |
from .dual_voronoi import DualVoronoiGraph
from .voronoi import DelaunayGraph
__all__ = ["DelaunayGraph", "DualVoronoiGraph"]
|
current_list_users = {}
active_requests = {}
active_chats = {}
active_commands = {}
black_list = []
asked_questionnaire = {}
active_polls = {}
def delete_msg(chat_id, context):
global active_commands
if chat_id:
msg_id = active_commands.get(chat_id, None)
if msg_id:
print(msg_id)
... |
import random
from ruby import Controller
from ruby.communication.messages.Incoming import Incoming
from ruby.communication.messages.output.OPBannerLogin import OPBannerLogin
from ruby.communication.messages.output.OPCorrectVersion import OPCorrectVersion
class IMCorrectVersion(Incoming):
tokens = [28, 1]
... |
# 0901.py
import cv2
import numpy as np
src = cv2.imread('./data/chessBoard.jpg')
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
#1
fastF = cv2.FastFeatureDetector.create(threshold = 30)
kp = fastF.detect(gray)
dst = cv2.drawKeypoints(gray, kp, None, color = (0, 0, 255))
print('len(kp)=', len(kp))
cv2.imsho... |
from .rpsroi_align import RPSRoIAlign, rpsroi_align
__all__ = ['rpsroi_align', 'RPSRoIAlign'] |
from BD import *
# Lista De BD
repo_BD = DB()
# Nueva BD
repo_BD.createDatabase("Data_Base1")
repo_BD.createDatabase("Data_Base2")
repo_BD.createDatabase("Data_Base3")
repo_BD.createDatabase("Data_Base5")
repo_BD.alterDatabase("Data_Base5","Data_Base4")
repo_BD.dropDatabase("Data_Base3")
# Ver Lista D... |
from django.apps import AppConfig
class RapidConfig(AppConfig):
name = 'Rapid'
|
DEBUG = True
TESTING = True
PRESERVE_CONTEXT_ON_EXCEPTION = False
Z3950_DATABASES = {'loc': {'host': 'z3950.loc.gov', 'db': 'Voyager',
'port': '7090'},
'copac': {'host': 'z3950.copac.ac.uk', 'db': 'copac',
'port': '210', 'syntax': 'SUTRS'}}
|
from typing import List
def zerofy(mat: List[List[int]]) -> List[List[int]]:
r = []
for y in range(len(mat)):
s = []
for x in range(len(mat[0])):
s.append(mat[y][x])
r.append(s)
for y in range(len(mat)):
for x in range(len(mat[0])):
if mat[y][x] != 0:
continue
for i in ... |
# -*- coding: utf-8 -*-
import copy
import gc
import random
import BaseThreadedModule
import Utils
import Decorators
import sys
@Decorators.ModuleDocstringParser
class EventBuffer(BaseThreadedModule.BaseThreadedModule):
"""
Store received events in a persistent backend until the event was successfully handled... |
#!/usr/bin/python
import pyflx
import time
def onData(symbol, data={}):
print("[onData] symbol:{}, data:{}".format(symbol, data))
sl = pyflx.Symlistener()
sl.onData(onData)
# Enter loop() and exit if connection error.
while True:
try:
if sl.connect('192.168.11.79', 7600):
sl.subscribe('XA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.