content stringlengths 5 1.05M |
|---|
c=j=k=0
for _ in input():
if _.isupper():c+=k%4;k+=k%4+1
k+=1
print(c)
|
#! /usr/bin/python
'''Script that extracts the fish classification for the entire possible grid of bounding boxes. Stores the results in a bag file.'''
usage='ExtractGridClassification.py [options]'
import roslib; roslib.load_manifest('species_id')
import rospy
import rosbag
import numpy as np
from optparse import Opt... |
# -*- coding: utf-8 -*-
import logging
import traceback
import easyjoblite.exception
from easyjoblite import constants
from easyjoblite.consumers.base_rmq_consumer import BaseRMQConsumer
from easyjoblite.job import EasyJob
from easyjoblite.job_response import JobResponse
from easyjoblite.response import EasyResponse
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from storm.locals import *
from mdcorpus.orm import *
database = create_database("sqlite:")
store = Store(database)
store.execute(MovieConversation.CREATE_SQL)
store.execute(MovieLine.CREATE_SQL)
conversation = store.add(MovieConversation(0, 2, 0))
line194 = store.add(... |
from __future__ import division
import numpy as np
# import cv2
import time, io
# from matplotlib import pyplot as plt
from google.cloud import vision
from google.cloud.vision.feature import Feature,FeatureTypes
MIN_MATCH_COUNT = 200
# only using match count right now
MIN_MATCH_RATIO = .2
NUM_LABELS = 20
NUM_LANDMARK... |
import glob
import os
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from lxml import etree
from ead.constants import NS_MAP
from ead.models import EAD, Relation, RelationEntry
class Command(BaseCommand):
help = "Re-imports sh_connection items from specified... |
import pytest
import numpy as np
from numpy import testing
from gammy import utils
from gammy.arraymapper import ArrayMapper, lift
np.random.seed(42)
data = np.random.randn(42, 8)
@pytest.mark.parametrize("op", [
(lambda _, y: y),
(lambda x, _: x[:, 2]),
(lambda x, y: x + y),
(lambda x, y: x - y),... |
import sys
sys.path.append("../../utils") # Use predefined utility functions
import cv2
import numpy as np
from scipy.ndimage import convolve, gaussian_filter
from scipy.interpolate import splprep, splev, RectBivariateSpline
from contour import getContour
## Sobel kernels
# H... |
#!/usr/bin/env python3
# Dump Android Verified Boot Signature (c) B.Kerler 2017-2018
import hashlib
import struct
import binascii
import rsa
import sys
import argparse
from rsa import common, transform, core
from Crypto.Util.asn1 import DerSequence
from Crypto.PublicKey import RSA
version="v1.3"
def extra... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import compas_rhino
from compas_rhino.geometry import RhinoMesh
from compas_rv2.datastructures import Pattern
from compas_rv2.rhino import get_scene
from compas_rv2.rhino import rv2_undo
from compas_rv2.rhino i... |
#!/usr/bin/env python
from bob.bio.face.database import ReplayBioDatabase
from bob.bio.base.pipelines.vanilla_biometrics import DatabaseConnector
from bob.extension import rc
replay_attack_directory = rc["bob.db.replay.directory"]
database = DatabaseConnector(
ReplayBioDatabase(
original_directory=repla... |
import unittest
from ptools.lipytools.little_methods import stamp, print_nested_dict
class TestStamp(unittest.TestCase):
def test_stamp(self):
print(stamp())
print(stamp(letters=None))
print(stamp(year=True))
def test_print_nested_dict(self):
dc = {
'a0': {
... |
from .constant import Service as Service_keys
from .services.base import Services
from .services import (
resource,
config,
logger,
)
class Application(object):
def __init__(self):
self.services = Services()
self.services.init()
def init(self):
services_tuple = (
... |
# Sum of multiples of 3 and 5
# OPTIMAL (<0.1s)
#
# APPROACH:
# Simple brute force is enough.
DUMMY_LIMIT = 10
DUMMY_RESULT = 23
LIMIT = 1000
def sum_multiples(limit):
return sum(i for i in range(1, limit) if not i % 3 or not i % 5)
assert sum_multiples(DUMMY_LIMIT) == DUMMY_RESULT
result = sum_multiples(LIMI... |
from DAL.DAL_Prescription import DAL_Prescription
class BUS_Prescription():
def __init__(self):
self.dalPrescription = DAL_Prescription()
def loadPrescription(self, IDPatient):
return self.dalPrescription.selectAllPrescription(IDPatient=IDPatient)
def addPrescription(self, dtoPrescription... |
import csv
class Helper:
def __init__(self,symbol,volume,min,max):
self.symbol = symbol
self.volume = volume
self.min = min
self.max = max
with open("example.csv", "r") as f:
reader = csv.reader(f)
line = next(reader)
d=dict()
for x in reader:
if len(x)<1:
... |
import numpy as np
import sys
sys.path.insert(0, "../")
from nn_models import model2 as md
from data import formatImage
import matplotlib.image as image
"""
This initalizes a neural net with a given file and test the file on a given image.
"""
inputSize = 28 * 28 # the pixels space
outputSize = 10 # the number of c... |
# $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#
#modification, are permitted provided that the following conditions are
#met:
#
... |
# standard library
from datetime import date
# Django
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required, user_passes_test
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect, get_obje... |
#!/usr/bin/env python3
##############################################################################
# Copyright 2020 spcnvdr <spcnvdrr@protonmail.com> #
# #
# Redistribution and use in source and binary forms, with or... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-09 11:18
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('houses', '0087_auto_20170109_1214'),
]
operations = [
migrations.RenameField(
... |
from typing import List, Optional
from pypika import Table
from pypika.enums import Dialects
from pypika.functions import Lower
from pypika.queries import QueryBuilder
from app.models.division_model import Division, DivisionStatus
from app.repositories.base_repository import BaseRepository
from app.utils.postgres imp... |
import pytest
import numpy as np
import pybnesian as pbn
from pybnesian import BayesianNetwork, GaussianNetwork
import util_test
df = util_test.generate_normal_data(10000)
def test_create_bn():
gbn = GaussianNetwork(['a', 'b', 'c', 'd'])
assert gbn.num_nodes() == 4
assert gbn.num_arcs() == 0
assert g... |
from urllib.parse import urlparse
def check_if_legit(domain_name):
true_points = 0
if domain_name in illegit_sites:
return "Fake / Malicious"
if domain_name in legit_sites:
return ("Authentic")
return "Not found as a news aggregator"
def checker(complete_link):
global legit_sites
global illegit_sites
... |
#!/usr/bin/env python3
# coding: utf8
print('Hello Python!!')
|
#!/usr/bin/env python3
#
# Note that we do not deploy pip as part of the installation, since it does take
# quite a bit of space (> 8 MB), and using pip together with an "embedded Python"
# isn't officially supported. If we do want to ship pip in a future version,
# please see the following as a starting point on how t... |
# Copyright 2021 DeepMind Technologies Limited
#
# 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 pytest
from helpers.utils import (
NAMESPACE,
VALUES_DISABLE_EVERYTHING,
cleanup_helm,
cleanup_k8s,
exec_subprocess,
install_chart,
install_custom_resources,
merge_yaml,
wait_for_pods_to_be_ready,
)
VALUES_ACCESS_CLICKHOUSE = merge_yaml(
VALUES_DISABLE_EVERYTHING,
""... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
# fmt: off
class Tests:
camera_creation = ("Camera Entity successfully created", ... |
from django.conf import settings
from django.db import models
from django.utils import timezone
class Post(models.Model):
title = models.CharField(max_length=200)
post_url = models.TextField()
img_url = models.TextField()
published_date = models.DateField()
created_date = models.DateTimeField(defa... |
# Generated by Django 2.2.13 on 2020-07-29 10:06
import django.contrib.postgres.fields
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('commodities', '0002_auto_20200723_1020'),... |
import win32api
import win32gui
import win32con
import win32ui
from .base_handler import Base
class FrontEnd(Base):
name = "frontend"
@classmethod
def get_point(cls, hwnd):
return win32gui.GetCursorPos()
@classmethod
def move_to(x, y):
win32api.mouse_event(win32con.MOUSEEVENT... |
# Copyright 2020 The TensorFlow Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2019-11-01 07:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Cre... |
# -*- coding: utf-8 -*-
import datetime
import json
import os
import random
import uuid
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
DB_HOST = os.getenv("MYSQL_DB_HOST", "mysql.platiagro")
DB_NAME = os.getenv("MYSQ... |
__all__ = ["LarkParser", "ParserError", "Lark2Django"]
#from .lark_parser import LarkParser, ParserError
from QueryLarkDjangoParser import LarkParser, ParserError, Lark2Django |
class Pessoa:
def __init__(self,nome=None,idade=0,*filhos):
self.nome = nome
self.idade = idade
self.filhos = list(filhos)
def cumprimentar(self):
return 'Olá'
if __name__ == '__main__':
matheus = Pessoa('Matheus',25)
edmilson = Pessoa("Edmilson",60,matheus)
for fil... |
import datetime
from datetime import date
from io import BytesIO
import pandas as pd
import numpy as np
import re
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.operators.bash import BashOperator
from airflow.models import Variable
from minio import Minio
DEFAULT_ARGS... |
from PyQt5.QtWidgets import QWidget, QGridLayout, QPushButton
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QPixmap, QIcon
from app.editor.lib.state_editor.state_enums import MainEditorScreenStates
from app.resources.resources import RESOURCES
from app.data.database import DB
from app.data.overworld impo... |
import requests
res = requests.get("http://api.aoikujira.com/time/get.php")
text = res.text
print(text)
bin = res.content
print(bin)
|
from typing import List
import os
from sqlalchemy.orm.exc import NoResultFound
import sqlalchemy.sql
from ping_dashboard.data import db_session
from ping_dashboard.data.location import Location
def init_db():
top_folder = os.path.dirname(__file__)
rel_file = os.path.join('..', 'db', 'ping_dashboard.sqlite')
... |
import heapq
from collections import defaultdict
# Custom object to store the required values
class Element:
def __init__(self, frequency, sequence, number):
self.frequency = frequency
self.sequence = sequence
self.number = number
def __lt__(self, other):
# higher frequency w... |
lambda x: x + 1
|
from lockfish.nc import nc
from testing import *
from lockfish.clangparser import *
rdr()
res = parse_folder('csourcelim', '.c')
rdrstop()
rdrv=rdrval()
r2=[r.cursor for r in res]
restus=res
res=r2
#Testing node collection
class TestNC(tc):
#1
def testPreps(self):
global res
global rdrv
self.assertTr... |
expected_output = {
"interface": {
"Loopback0": {
"interface_status": "Up",
"ip_address": "200.0.7.1",
"protocol_status": "Up"
},
"MgmtEth0/RSP0/CPU0/0": {
"interface_status": "Up",
"ip_address": "5.25.27.1",
"protocol_s... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Fetches line spectra from the NIST Atomic Spectra Database.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nist`.
"""
server = _config.ConfigItem(
['... |
"""
This parent playbook collects data and launches appropriate child playbooks to gather threat intelligence information about indicators. After the child playbooks have run, this playbook posts the notes to the container and prompts the analyst to add tags to each enriched indicator based on the intelligence provided... |
# import Node as nd
# import time
# node1 = nd.Node(10,12,1,1,1,1)
# print(node1.get_sensed_data())
# time.sleep(3)
# print(node1.get_sensed_data())
# time.sleep(3)
# print(node1.get_sensed_data())
# import time, threading
# def foo():
# print(time.ctime())
# threading.Timer(10, foo).start()
# f... |
import data_mine as dm
import json
import jsonlines
import os
import pandas as pd
import sys
import unittest
from data_mine import Collection
from data_mine.nlp.CSQA import CSQAType
from data_mine.nlp.CSQA.utils import type_to_data_file
from data_mine.utils import datamine_cache_dir
from pyfakefs.fake_filesystem_unitt... |
# -*- coding: utf-8 -*-
def sol():
"""
Solution module
"""
return "/SOLU"
def load_step_solve(n1,n2,inc=1):
"""
Solve from load step n1 to n2
"""
_lss = "LSSOLVE,%g,%g,%g"%(n1,n2,inc)
return _lss
def solve():
"""
Solve
"""
return "SOLVE"
if __name__ == '__main... |
# Generated by Django 3.0 on 2020-02-22 13:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('profiles_api', '0002_profilefeediten'),
]
operations = [
migrations.RenameModel(
old_name='ProfileFeedIten',
new_name='Profile... |
import numpy as np
from borderDetector import borderDetector
if __name__ == '__main__':
bd = borderDetector(imgPath="car.bmp", sigmas=np.array([0.73, 0.84]))
bd.detect()
|
import unittest
from troposphere import Join
from troposphere.sqs import Queue
class TestQueue(unittest.TestCase):
def test_QueueName(self):
Queue(
"q",
FifoQueue=False,
).validate()
Queue(
"q",
FifoQueue=True,
QueueName="foobar... |
# coding: utf-8
'''
Created on 11.05.2013
@author: кей
'''
from dals.local_host.local_host_io_wrapper import file2list
from dals.local_host.local_host_io_wrapper import get_utf8_template
if __name__=="__main__":
sets = get_utf8_template()
sets['name'] = '../info/preposition_ru.txt'
readed = ... |
"""Helpful utilities for the AiiDA lab tools."""
import sys
from os import path
from importlib import import_module
from markdown import markdown
import requests
import ipywidgets as ipw
from IPython.lib import backgroundjobs as bg
from .config import AIIDALAB_APPS, AIIDALAB_REGISTRY
def update_cache():
"""Run... |
"""Module for plotting summarised data with matplotlib."""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from typing import List, Optional
from ..checks import check_type, check_condition
def plot_summarised_variable(
summary_df: pd.DataFrame,
axis_right: int,
axis_left: Option... |
import cv2
import numpy as np
from optical_flow import OpticalFlow, OpticalFlowFeatures
class VideoFeatures:
def __init__(self, filepath):
self.filepath = filepath
def get_feature_vector(self):
hists, magnitudes = self.__get_feature()
avg_hists = np.nanmean(hists, 0)
avg_magnitu... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... |
"""Test Cloud preferences."""
from unittest.mock import patch
from homeassistant.auth.const import GROUP_ID_ADMIN
from homeassistant.components.cloud.prefs import CloudPreferences, STORAGE_KEY
async def test_set_username(hass):
"""Test we clear config if we set different username."""
prefs = CloudPreferences... |
from django.urls import path
from . import views
app_name = 'sell'
urlpatterns = [
# path('', views.index, name='index'),
path('', views.ProtectView.as_view(), name='index'),
path('create_sell/', views.InvoiceCreateView.as_view(), name='create'),
path('sell_list/', views.InvoiceListView.as_view(), nam... |
import os
import pytest
import subprocess
import tempfile
import time
import warnings
import docker
import girder_client
def getTestFilePath(name):
"""
Return the path to a file in the tests/test_files directory.
:param name: The name of the file.
:returns: the path to the file.
"""
return os.... |
import frappe
# def get_or_create_doc(params):
# print(params)
#
# dn = params[params['key']]
# doc = frappe.db.exists(params['doctype'], dn)
# if doc:
# created = False
# else:
# created = True
# doc = frappe.get_doc(params).insert()
#
# return created, doc
def get_o... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from . import user_pb2 as user_dot_user__pb2
class UserServiceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel... |
# DHANUSH H V https://www.github.com/DHANUSH-web
# Both decimal to binary and binary to decimal in a single program
# Programmed in: Python
# binary to decimal without using built-in method int()
def decimal(binary):
sz = len(binary)
dec, index = 0, sz-1
for bit in binary:
if bit == '1':
... |
import six
import types
class Field(object):
""":class:`Field` is used to define what attributes will be serialized.
A :class:`Field` maps a property or function on an object to a value in the
serialized result. Subclass this to make custom fields. For most simple
cases, overriding :meth:`Field.to_va... |
#!/usr/bin/env python3
# Author: Volodymyr Shymanskyy
import os
import re, fnmatch
import pathlib
class ansi:
ENDC = '\033[0m'
HEADER = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class dotdict(dict):
def __init__(self... |
from ebl.transliteration.domain.atf import Atf
from ebl.fragmentarium.domain.museum_number import MuseumNumber
from ebl.transliteration.domain.sign import (
Sign,
SignListRecord,
SignName,
Value,
Logogram,
Fossey,
)
def test_logogram():
logogram = Logogram(
"AŠ-IKU", Atf("AŠ-IKU"),... |
import urllib.request
from typing import List
import re, os, json
from courseDB import CourseDB
from bs4 import BeautifulSoup
from pprint import pprint
from utils import get_page, change_keys, parse_day
from utils import bcolors
from halo import Halo
from shared_course_web_ananlyzer import download_course_description_s... |
def ReadInt(msg):
while True:
try:
number = int(input(msg))
except (ValueError, TypeError):
print('\033[1;31mERRO: Digite um número inteiro válido!\033[m')
continue
except (KeyboardInterrupt):
print('\n\033[1;31O usuário preferiu não informar e... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-+
from stopover import Stopover
endpoint = 'http://localhost:5704'
receiver_group = 'group0'
stream = 'stream0'
# all the messages with the same key will fall under the same partition
key = None
stopover = Stopover(endpoint)
stopover.put('hi 0', stream, key=key)
index =... |
str=input()
n=int(input())
res =str[n:]
print(res+str[:n])
|
from __future__ import print_function, absolute_import, unicode_literals
from zope.interface import implementer
import contextlib
from ._interfaces import IJournal
@implementer(IJournal)
class Journal(object):
def __init__(self, save_checkpoint):
self._save_checkpoint = save_checkpoint
self._outbou... |
import requests
import json
import time
import hmac
import base64
import hashlib
import urllib.parse
def create_sign_for_dingtalk(secret: str):
"""
docstring
"""
timestamp = str(round(time.time() * 1000))
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
... |
from frogsay.client import open_client
from .util import temp_dir_name
def test_empty_cache_fetches_more_tips():
with temp_dir_name() as db_dir:
with open_client(db_dir) as client:
# Exhaust all tips
tries = 0
max_tips = 49
client.frog_tip()
wh... |
import json
import pathlib
from pathlib import Path
from dask.array.routines import shape
import distributed
from ..parse import utilities
import h5py
from dask import array as da
from dask import bag as db
from distributed import progress
from dask import delayed
from dask.diagnostics import ProgressBar
import dask
... |
import logging
import time
import requests
def get_tweets(query, token, batch_size=100, **options):
"""
Yield all tweets matching query
:param query: query (string)
:param token: bearer token for academic api
:param batch_size: number of tweets per batch (max=100)
:return:
"""
data = ... |
from PIL import Image, ImageEnhance
img = Image.open("Sample3.jpeg")
img_con = ImageEnhance.Bri(img)
img_con.enhance(1.0).show("100% more contrast")
|
'''
Python reducer UDO definition
'''
def usqlml_main(df):
pass |
from login import Locker
class Credential:
"""
Class that generates new instances of credential
"""
list_cred = []
list_credentials= []
def __init__(self,username,password,new_account,email):
'''
__init__ method that helps us define properties for our objects.
... |
class Employee:
def __init__(self, eid, did, name, money):
self.did = did
self.eid = eid
self.name = name
self.money = money
list_employees = [Employee(1001, 9002, "师父", 60000),
Employee(1002, 9001, "孙悟空", 50000),
Employee(1003, 9002, "猪八戒", 2000... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.collections import LineCollection
import seaborn as sns
# Download data shapes from:
# http://www.gadm.org/download
# More details on how to read the .shp files
# https://gis.stackexchange.com/questions/113799/... |
import unittest
from katas.kyu_7.pythons_dynamic_classes_1 import class_name_changer
class ClassNameChangerTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(str(MyClass),
'<class \'tests.kyu_7_tests.test_pythons_dynamic_c'
'lasses_1.MyC... |
#!/usr/bin/env python
import rospy
import math
import tf
from std_msgs.msg import Bool
from geometry_msgs.msg import Point
from geometry_msgs.msg import Pose
from robomuse_gazebo.srv import *
def callback2(msg):
global pos
pos = msg
def callback1(msg):
global state
state = msg.data
def move_arm_clien... |
"""Tests that the LEDs are working, by writing to the appropriate GPIO pins"""
from periphery import GPIO # pylint: disable=W0403
IN = "in"
OUT = "out"
HIGH = "high"
LOW = "low"
CCP_OK = GPIO(pin=13, direction=OUT)
IED_OK = GPIO(pin=12, direction=OUT)
FAULT = GPIO(pin=11, direction=OUT)
CCP_DATA_TX = GPIO(pin=25, d... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 3 20:12:48 2021
@author: ShiningStone
"""
import numpy as np
class CCoreCuda:
def __init__(self):
self.cp = self.getCupy()
self.DEBUG = False
self.memPool = self.cp.get_default_memory_pool()#self.cp.cuda.MemoryPool(self.cp.cuda.malloc_ma... |
# Copyright 2015 Google Inc. 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.0
#
# Unless required by applicable law or a... |
# code for streaming twitter to a mysql db
# for Python 3 and will support emoji characters (utf8mb4)
# based on the Python 2 code
# supplied by http://pythonprogramming.net/twitter-api-streaming-tweets-python-tutorial/
# for further information on how to use python 3, twitter's api, and
# mysql together visit: http:... |
from typing import Any, Dict
from labfunctions import types
from labfunctions.executors.docker_exec import docker_exec
from labfunctions.runtimes.builder import builder_exec
def notebook_dispatcher(data: Dict[str, Any]):
ctx = types.ExecutionNBTask(**data)
result = docker_exec(ctx)
return result.dict()
... |
"""
(C) Copyright 2021 IBM Corp.
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 agreed to in writing, software
dist... |
from flask import current_app, url_for, g
from app import db, geolocator
from sqlalchemy import event
class Address(db.Model):
__tablename__ = 'address'
id = db.Column(db.Integer, primary_key=True)
line_1 = db.Column(db.String(255))
line_2 = db.Column(db.String(255))
line_3 = db.Column(db.String(25... |
from sense_hat import SenseHat
from random import randint
import math
import sys
import json
def main():
sense = SenseHat()
sense.set_imu_config(True, True, True)
gyro = sense.get_gyroscope_raw()
acc = sense.get_accelerometer_raw()
comp = sense.get_compass_raw()
temp = sense.temp
humidit... |
#!/usr/bin/env python3
# Loads metadata about a release into the database.
import sqlite3
import sys
import re
if len(sys.argv) < 4:
print("usage: load-release.py <DB_FILE> <TAG> <GIT_COMMIT_HASH>")
sys.exit(1)
dbfile, tag, githash = sys.argv[1:4]
# Extract major.minor.patch from tag.
m = re.match(r'v(\d+)\... |
import numpy as np
import time
from kid_readout.utils import data_block,roach_interface,data_file
from sim900 import sim900Client
ri = roach_interface.RoachBaseband()
df = data_file.DataFile()
sc = sim900Client.sim900Client()
ri.set_adc_attenuator(31)
ri.set_dac_attenuator(26)
ri.set_tone_freqs(np.array([67.001,150... |
import asyncio
import json
import multiprocessing
import aioredis
import deserialize
from common.logger.logger import get_logger
from common.queue.push.fcm import blocking_get_fcm_job
from common.queue.result.push import publish_push_result_job
from common.structure.job.fcm import FCMJob
from worker.push.fcm.config i... |
import graphene
import hero.schema
# Our Project Level Schema 🚒 🔥
# If we had multiple apps, we'd import them here ✈
# Then, inherit from their Queries and Mutations 👦
# And, finally return them as one object 💧
class Query(hero.schema.Query, graphene.ObjectType):
# This class will inherit from multiple Queri... |
"""
Utilities related to reading DSM2 data
"""
import numpy as np
from .. import utils
from ..grid import unstructured_grid
from ..spatial import wkb2shp
def line_parser(fn):
"""
Generator to read lines, removing comments along the way
"""
with open(fn,'rt') as fp:
for line in fp:
... |
import logging
import random
from django.conf import settings
from django.db import transaction
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import CreateAPIView, ListAPIView, GenericAPIView
from rest_framework.permissions import IsAuthenticated
from rest... |
from datetime import datetime
from app.main.model.user import User
from app.main.model.users_chat import UsersChat
from app.main import db
from app.main.util.extract_resource import extract_resource
from app.main.model.message import Message
def __make_users_chat(user1, user2):
c1 = UsersChat(of_user=user1)
... |
"""
Colour Correction
=================
Defines various objects for colour correction, like colour matching two images:
- :func:`colour.characterisation.matrix_augmented_Cheung2004` : Polynomial
expansion using *Cheung, Westland, Connah and Ripamonti (2004)* method.
- :func:`colour.characterisation.polynomial... |
# Generated by Django 3.1.4 on 2021-03-31 22:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('nlpviewer_backend', '0015_remove_job_document'),
]
operations = [
migrations.AlterModelOptions(
name='project',
options={'pe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.