content stringlengths 5 1.05M |
|---|
# Matchmaker Dense Retrieval
# -------------------------------
# Conduct 3 phases of dense retrieval: encoding, indexing, search
# Only in batch form, not really meant for production use of a search engine
#
# - Needs a trained model (via train.py)
# - Measures efficiency & effectiveness on 1 collection + multiple que... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File name: matrix_calc.py
"""
Created on Thu May 7 20:56:54 2020
@author: Neo(liuniu@smail.nju.edu.cn)
Some codes for calculating various matrix & array needed in the LSQ preocess.
The normal equation is writtern as
A * x = b
where A is the normal matrix, x the v... |
# Copyright 2018 The Bazel Authors. 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 la... |
from PIL import Image, ImageDraw
s=24
st_list=['4005','4553','6758','7201','7309','8316','8411','9201','9202','9432','9437','9613','9983']
#st_list = ['AAL','AAPL','AMZN','FB','GOOG','ZM']
images = []
for i in st_list:
st_name = i + '_trend_2020-06-11_'
im = Image.open('./stock/stock0/{}.png'.format(st_name))... |
from typing import Optional, Callable
from model_spaces.core.hyperpriors import Hyperpriors
class Covariance:
rnd_code_max_digit = 10
rnd_code_maximum_length = 16
rnd_code_truncation = 1e6
def __init__(self,
name: str,
is_base: bool,
rnd_code,
... |
# -*- coding: utf-8 -*-
from functools import reduce
from itertools import product
from operator import mul
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
import numpy as np
from africanus.util.requirements import requires_optional
from africanus.rime.predict i... |
from JobBrowserBFF.TestBase import TestBase
UPSTREAM_SERVICE = 'ee2'
ENV = 'ci'
USER_CLASS = 'user'
class JobBrowserBFFTest(TestBase):
def test_get_job_types_happy(self):
try:
self.set_config('upstream-service', UPSTREAM_SERVICE)
impl, context = self.impl_for(ENV, USER_CLASS)
... |
import Tkinter
class MyFrame(Tkinter.Frame):
def __init__(self, parent, *args, **kwargs):
Tkinter.Frame(self, parent, args, **kwargs)
def main():
root = Tkinter.Tk()
MyFrame(root)
root.mainloop()
if __name__ == '__main__':
main()
|
import pytest
from django.core.management import call_command
from company.models import Company, CompanyCaseStudy
from supplier.models import Supplier
@pytest.mark.django_db
def test_load_test_fixture():
try:
call_command('loaddata', 'test_fixtures/load_tests.json')
except Exception:
raise ... |
# Thank For CatUserBot
# Ported By @VckyouuBitch
# FROM Geez - Projects <https://github.com/Vckyou/GeezProjects>
from telethon.tl.functions.contacts import BlockRequest, UnblockRequest
from telethon.tl.types import (
MessageEntityMentionName,
)
from userbot import bot, BOTLOG, BOTLOG_CHATID, CMD_HELP
from userbo... |
"""empty message
Revision ID: f683429df188
Revises: 1f6af6d0cad3, 1b767d526d05
Create Date: 2020-11-29 02:09:29.262379
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f683429df188'
down_revision = ('1f6af6d0cad3', '1b767d526d05')
branch_labels = None
depends_o... |
import abc
from appium import webdriver
from core.task import Task
from utils.tools import AppiumTools
class Processor(metaclass=abc.ABCMeta):
def __init__(self, serial, _session: webdriver.Remote):
self._serial = serial
self._session = _session
self._appium_tools = AppiumTools(self._se... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.management import call_command
def main():
settings.configure(
INSTALLED_APPS = (
'django.contrib.contenttypes',
'uturn',
),
DATABASES = {
'default': {
'ENGINE': 'dj... |
import csv
from scipy import ndimage
from matplotlib import pyplot as plt
import yaml
from PIL import Image
import numpy as np
from numba import njit
import os
import ReferenceModification.LibFunctions as lib
from ReferenceModification.Simulator.map_utils import *
from ReferenceModification.Simulator.BaseSimulator... |
import logging
import time
import discord
import discord_components as dc
import music_bot.embeds as embeds
from music_bot.search import SearchHandler
class CommandHandler:
def __init__(self, client, prefix):
self.client = client
self.prefix = prefix
self.commands = [
Comman... |
'''
Created on Aug 20, 2009
@author: Christopher
'''
def get_birthdays(bdays, now):
import datetime
today = datetime.date.fromtimestamp(now)
new = {}
for uid, d_ in bdays.items():
bd = d_.get('birthday_date')
if bd is not None:
mdy = [None]*3
vals = ... |
import os
import logging
import time
import datetime
from easy_thumbnails.models import Source
from django.core.files.storage import default_storage
from django.core.management.base import BaseCommand, CommandError
from django.db.models import F,Max,OuterRef,Subquery
from django.utils.timezone import now
from ik.models... |
import komand
from .schema import BulkIndicatorDownloadInput, BulkIndicatorDownloadOutput
# Custom imports below
import datetime
class BulkIndicatorDownload(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="bulk_indicator_download",
description="Retri... |
from typing import Optional, Any, Union, Sequence, TextIO
import re
import warnings
from netmiko.base_connection import DELAY_FACTOR_DEPR_SIMPLE_MSG
from netmiko.cisco_base_connection import CiscoBaseConnection, CiscoFileTransfer
class CiscoXrBase(CiscoBaseConnection):
def establish_connection(self, width: int = ... |
import mbuild as mb
from os.path import dirname, join
def _get_library_dir():
""" Returns the absolute path to the test compound library. """
compound_library = join(dirname(__file__), "test_cpds")
return compound_library
def load_solvent():
file_path = join(_get_library_dir(), "test_solvent.mol2")
... |
# one way to optimise this could be to use
# some other implementation to reverse other than using array[::-1]
# 26ms
class Solution:
def reverse(self, x: int) -> int:
if(x>=0):
result = int(str(x)[::-1])
else:
b = str(x)[1:]
result = int("-" + str(i... |
class Student:
def __init__(self, id, name, testscore):
self.id = id
self.name = name
self.testscore =testscore
def display(self):
print(self.id, self.name, self.testscore)
# Go to pickledump.py |
"""
@author: krakowiakpawel9@gmail.com
@site: e-smartdata.org
"""
import cv2
print(cv2.__version__)
image = cv2.imread(filename=r'01_basics/images/bear.jpg')
cv2.imshow(winname='image', mat=image)
cv2.waitKey(delay=0) |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-08 07:44
from __future__ import unicode_literals
import assets.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0017_auto_20170105_1958'),
]
operations = [
... |
#!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, 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 ... |
def inOrder(a, n, i):
global v
if i >= n:
return
inOrder(a, n, 2* i + 1)
v.append(a[i])
inOrder(a, n, 2* i +2)
def minSwaps():
global v
t = [[0, 0] for i in range(len(v))]
ans = -2
for i in range(len(v)):
t[i][0], t[i][1] = v[i], i
t, i = s... |
aluno = {}
aluno['nome'] = str(input('Qual é o nome do aluno? ')).capitalize().strip()
aluno['nota'] = float(input('Qual é a media do aluno? '))
print(f'\nO nome do aluno é {aluno["nome"]}')
print(f'A media do aluno é {aluno["nota"]}')
if aluno['nota'] <= 6.9:
print(f'{aluno["nome"]} está em recuperação')
el... |
import logging
from common.document_parser.ref_utils import make_dict
logger = logging.getLogger(__name__)
ref_regex = make_dict()
def check(check_str, ref_type, exp_result):
count = 0
matches = ref_regex[ref_type][1].findall(check_str)
for match in matches:
num_match = ref_regex[ref_type][0].s... |
from setuptools import setup
from pypandoc import convert_file
#: Converts the Markdown README in the RST format that PyPi expects.
long_description = convert_file('README.md', 'rst')
setup(name='obstruction',
description='Declarative parser for remapping object schemas and data',
long_description=long_d... |
class MissingArgumentException(Exception):
def __init__(self, message):
self.message = message
def __repr__(self):
return f'<MissingArgumentException "{self.message}">'
def __str__(self):
return self.message
class MisMatchException(Exception):
def __init__(self, message):
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------... |
from cisconetworkswitch import *
|
# Generated by Django 2.1.7 on 2019-02-21 11:21
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0019_auto_20181227_1534'),
]
operations = [
migrations.AlterField(
model_name='histor... |
a,b=map(str,input().split())
z=[]
x,c="",""
if a[0].islower():
x=x+a[0].upper()
if b[0].islower():
c=c+b[0].upper()
for i in range(1,len(a)):
if a[i].isupper() or a[i].islower():
x=x+a[i].lower()
for i in range(1,len(b)):
if b[i].isupper() or b[i].islower():
c=c+b[i].lower(... |
"""
Given an array of intervals where intervals[i] = [starti, endi],
merge all overlapping intervals,
and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since inter... |
from .txt_style import txtDataset
from .registry import DATASETS
import numpy as np
import cv2
import os
import math
import time
# import torch
def get_dir(src_point, rot_rad):
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
src_result = [0, 0]
src_result[0] = src_point[0] * cs - src_point[1] * sn
src_resul... |
from conceptnet5.formats.msgpack_stream import read_msgpack_stream
from conceptnet5.uri import uri_prefixes
from conceptnet5.relations import SYMMETRIC_RELATIONS
from ordered_set import OrderedSet
import json
def write_row(outfile, items):
print('\t'.join(sanitize(str(x)) for x in items), file=outfile)
def writ... |
#!/usr/bin/env python
#
# Copyright (c) 2013, 2015 by California Institute of Technology
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the abo... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache 2.0 License.
import os
import time
import paramiko
import logging
import getpass
from contextlib import contextmanager
import infra.remote
from glob import glob
from loguru import logger as LOG
DBG = os.getenv("DBG", "cgdb")
cla... |
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2013-2018, OVH SAS.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, t... |
import json
import re
with open("../data/labels_dict.json") as labelFile:
labels_dict = json.load(labelFile)
def getGoldAnswers(goldanswer_string):
goldanswerList = goldanswer_string.split(";")
goldanswers = []
for ga in goldanswerList:
if "/" in ga:
ga = ga.rsplit("/", 1)[1]
... |
import pytest
import rumps
from src.app_functions.exceptions.login_failed import LoginFailed
from src.app_functions.menu.change_credentials import change_credentials
@pytest.fixture(name="basic_app")
def create_app():
"""Creates a basic app object with some variables to pass to functions
Returns:
rum... |
# -*- coding: utf-8 -*-
# pylint: disable=broad-except, bare-except
from .const import LOGGER, SHELLY_TYPES
from .base import Base
class Device(Base):
def __init__(self, block):
super(Device, self).__init__()
self.block = block
self.id = block.id
self.unit_id = block.id
... |
#!/usr/bin/python3
while True :
password = input("Make up a secure password: ")
print("You entered: ", password)
# initialize
has_capital = False
has_digit = False
# check length
gt_6 = len(password) >= 6
if gt_6 is True :
print("Password length check passed")
# check alp... |
# -*- coding: utf-8 -*-
#from django.contrib import admin
from django.contrib.admin import site, ModelAdmin, TabularInline, StackedInline
#from django.contrib.auth.models import User
from workflow.models import *
from workflow.forms import StepAdminForm
class StepInline(StackedInline):
model = Step
form = St... |
import pygame as pg
from random import randint, uniform
import pytweening as tween
vec = pg.math.Vector2
# fade in/out
# grow/shrink
class Particle(pg.sprite.Sprite):
def __init__(self, image, pos, vel, life, gravity, groups):
pg.sprite.Sprite.__init__(self, *groups)
self.image = image.copy()
... |
from operator import mod
from medical_seg.networks.layers.image_transformer import PoolFormer
from medical_seg.networks.layers.multi_attention import MultiAttentionTransformer
from medical_seg.networks.nets.co_unet import BasicUNet
from medical_seg.networks.nets.basic_unet_encoder import BasicUNetEncoder
import torch.... |
import os
import pickle
from typing import Union
from datetime import date as dt
import cv2
import face_recognition
from src.models import StudentModel, AttendanceModel
from src.settings import (
DATASET_PATH,
HAAR_CASCADE_PATH,
DLIB_MODEL, DLIB_TOLERANCE, ENCODINGS_FILE
)
class CliAppUtils:
app_tit... |
from peepshow.pager.pager import Pager
class TooManyInitialIterations(StopIteration): pass
class PagedCache:
def __init__(self, content, str_func=str):
self.iterator = content.__iter__()
self.index = 0
self.offset = 0
self.cache = []
self.str_func = str_func
def itera... |
"""Module of infoset database functions.
Handles queries that span multiple tables.
"""
# Python standard libraries
import copy
from collections import defaultdict
# PIP libraries
from sqlalchemy import and_
# Infoset libraries
from infoset.utils import general
from infoset.db import db
from infoset.db.db_orm impo... |
from motor_control import roboclaw
reading = roboclaw.readmainbattery()
voltage = (1.0 * reading)/10.0
print "Battery Level: %.1f V" %voltage
if voltage < 10.0:
print "WARNING: Battery low, change soon!"
|
from .rickydl import *
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
import unittest
from freeflow.core.tests.dag import DagTest
from freeflow.core.tests.sensor.externaltask import SensorExternalTaskTest
# Optional tests
try:
from freeflow.core.tests.operator.bigquery import OperatorBigqueryTest
except ImportError:
pass
from freeflo... |
import numpy as np
import numpy.random as npr
import pandas as pd
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.preprocessing import StandardScaler
from scipy.special import logsumexp, softmax, log_softmax, logit
from scipy.sparse import diags
import torch
from torch import nn
from torch.nn import... |
from librosa.core import stft
from librosa import filters
from librosa import to_mono
import numpy as np
import scipy
def medium_time_power_calculation(power_stft_signal, M=2):
medium_time_power = np.zeros_like(power_stft_signal)
power_stft_signal = np.pad(power_stft_signal, [(M, M), (0, 0)], 'constant')
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# test_api
'''
:author: madkote
:contact: madkote(at)bluewin.ch
Test
----
Unit tests for Flask app
Usage
-----
>>> python test_api.py
'''
import json
import unittest
import api
import settings
VERSION = (0, 1, 0)
__all__ = []
__author__ = 'ma... |
from lib.button import Button
# places button objects in an array
class BUTTON_CONTROLLER:
def __init__(self, pins, leds, keys):
self.buttons = []
self.function_state = [
False
]
for index, pin in enumerate(pins, start=0):
self.buttons.append(Button(pin, leds, index, self.funct... |
input = """301"""
input = int(input)
# input = 3
buffer = [0]
def spinlock(s, n, q):
n = n + 1
n = n % len(s)
s = [q] + s[n:] + s[:n]
return s
for i in range(1, 2017 + 1):
buffer = spinlock(buffer, input, i)
print(buffer[1])
|
import ipcalc
import codecs
import yaml
#this function writes the beginning of the VagrantFile
def BeginVagrantFile(f):
# print("writing the beginning of the vagrant file")
f.write("# -*- mode: ruby -*- \n# vi: set ft=ruby :\n\n")
f.write("#All Vagrant configuration is done below. The 2 in Vagrant.co... |
from pm4py.evaluation.generalization.versions import token_based as generalization_token_based
from pm4py.evaluation.precision.versions import etconformance_token as precision_token_based
from pm4py.evaluation.simplicity.versions import arc_degree as simplicity_arc_degree
from pm4py.evaluation.replay_fitness.versions i... |
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... |
import tensorflow as tf
from methods.dpf import DPF
from utils.data_utils import load_data, noisyfy_data, make_batch_iterator, remove_state
from utils.exp_utils import get_default_hyperparams
def train_dpf(task='nav01', data_path='../data/100s', model_path='../models/tmp', plot=False):
# load training data and ... |
# The read4 API is already defined for you.
# @param buf, a list of characters
# @return an integer
# def read4(buf):
from collections import deque
class Solution(object):
def __init__(self):
self.queue = deque()
def read(self, buf, n):
"""
:type buf: Destination buffer (List[... |
faq = """
***FREQUENTLY ASKED QUESTIONS***
**Can I ping or dm John ?**
Yes, feel free to ping or dm john, his response time depends on how busy he is, but he is a teddy bear, so you will get a response sooner or later
**Can I ping moderators role/admins ?**
Yes, but when it is really urgent, otherwise just ping a mod... |
from runs_plot import *
normal_run_data = "../../../experiments/runs/normal_run_data.csv"
normal_plot_path = "../plots/normal/"
thm10_run_data = "../../../experiments/runs/thm10_run_data.csv"
thm10_plot_path = "../plots/thm10/"
v_is_g_run_data = "../../../experiments/runs/v_is_g_run_data.csv"
v_is_g_plot_path = "..... |
__author__ = 'amannhold'
|
__author__ = 's7a'
# All imports
from parser import Parser
from breaker import Breaker
import re
# The Syntactic simplification class
class SyntacticSimplifier:
# Constructor for the Syntactic Simplifier
def __init__(self):
self.parser = Parser()
self.breaker = Breaker()
# Simplify cont... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__... |
# import os
# import pythoncom
#
# from django.core.mail import send_mail
# from django.db.models.signals import post_init, post_save
# from django.dispatch import receiver
# from docx.shared import Mm
# from docxtpl import DocxTemplate, InlineImage
#
# from contactApp.models import Resume
# from docx2pdf import conver... |
print(__doc__)
from time import time
import numpy as np
import matplotlib.pyplot as plt
import h5py
from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn import decomposition
from sklearn.preprocessing import scale
from skimage.transform import rescale
i... |
from nq.filters import Filter
from nq.flags import Flags
class recurse_until:
pass
def _common_iterable(obj):
if isinstance(obj, dict):
return obj
else:
return (index for index, value in enumerate(obj))
def _is_iterable(obj):
return isinstance(obj, (list, tuple, set, dict))
def l... |
# Generated by Django 2.0.9 on 2018-10-28 09:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0002_user_department'),
]
operations = [
migrations.AlterField(
model_name='user',
... |
n = int(input('Digite um numero para ver a sua tabuada: '))
for x in range(1,11):
print('{} x {} = {}'.format(n, x, n*x)) |
__all__ = [
'gbufferedimage',
'gcolor',
'gevents',
'gmath',
'gobjects',
'gwindow',
]
|
import argparse
import json
import matplotlib.pyplot as plt
from pathlib import Path
import joblib
import numpy as np
import rlkit.torch.pytorch_util as ptu
from rlkit.core import logger
from rlkit.torch.core import PyTorchModule
from rlkit.torch.mpc.collocation.collocation_mpc_controller import (
SlsqpCMC,
G... |
# TODOs:
# - use TensorArray as training buffers instead of FIFOQueue
# - recombine without blowing up numbers (should fit in 64bit word)
# - gradient computation + SGD
# - compare performance if native type is float64 instead of int64
# - performance on GPU
# - better cache strategy?
# - does it make sense to cache ad... |
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if x < 10:
return True
temp = x
rem = 0
while temp > 0:
rem = rem*10 + temp % 10
temp = temp//10... |
# 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
# d... |
from optimus.engines.base.dataframe.constants import BaseConstants
class DataFrameBaseConstants(BaseConstants):
pass
|
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... |
def Reverse(input):
total = ""
for char in input:
total = char + total
return total
print(Reverse("Reverse")) |
#!/bin/env python
# -*- coding: utf-8 -*-
import collections
import csv
import click
import numpy as np
import psycopg2
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from postgis import register
def connectDB(db, dbuser, dbpass, line, spacing):
# Connect to the PostgreSQL Database
... |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
from setuptools import find_packages, setup
setup(
name="labgraph_viz",
version="1.0.0",
description="Some useful visualizations for labgraph",
packages=find_packages(),
python_requires=">=3.6, <3.7",
install_requi... |
import numpy as np
import cv2
import os
image_extensions = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.pbm', '.pgm', '.ppm']
def splitfn(fn):
path, fn = os.path.split(fn)
name, ext = os.path.splitext(fn)
return path, name, ext
def anorm2(a):
return (a*a).sum(-1)
def anorm(a):
return np.s... |
import logging
import os
from osgeo import gdal
import matplotlib.pyplot as plt
from sentinelloader import Sentinel2Loader
logging.basicConfig(level=logging.DEBUG)
sl = Sentinel2Loader('/notebooks/data/output/sentinelcache',
os.environ['COPERNICUS_USER'], os.environ['COPERNICUS_PASSWORD'],
... |
from secrets.plugins.base_plugin import BasePlugin
import re
from secrets.plugins.blacklist import Blacklist
class PasswordPatternPlugin(BasePlugin):
BLACKLIST = [r"[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}", # Guid
"RFC[0-9]{3}", "ES201[56]", "Office365", "System32", "log4net",
... |
# coding=utf-8
import sys
def fix_environment_stuff(module, base):
# restore builtins
module.__builtins__ = [x for x in base.__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.__builtins__
# patch getfilesystemencoding for NVIDIA Shield
getfilesystemencoding_orig = sy... |
## set up logging
import logging, os
logging.basicConfig(level=os.environ.get("LOGLEVEL","INFO"))
log = logging.getLogger(__name__)
import requests
class Downloader:
"""A class for downloading USDA WASDE data files
***
Attributes
----------
Methods
-------
"""
def __init__(self):
pass
def __repr__(s... |
import awwards
from awwards.models import Profile
from django.shortcuts import render,redirect,get_object_or_404
from awwards.models import Profile, Project
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Project, Rate
from .serializer import ProjectSerializer,... |
import pygame
class Avatar:
"""Just a joke."""
def __init__(self, screen):
self.screen = screen
self.image = pygame.image.load('images/avatar.png')
self.rect = self.image.get_rect()
self.screen_rect = self.screen.get_rect()
self.rect.center = self.screen_rect.center
... |
# 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
# distributed under t... |
#!/usr/bin/env python
"""
processing GoldCLIP illumina datasets
only one of the PE reads
## type1: goldclip_version_1
read1: {NNN} - {bc} - {NN} - <insert>
## type2: goldclip_version_2
read1: {N10} - <insert> - A{barcode}
read2: {barcode}A - <insert> - {N10}
## type3: eCLIP
read1: {barcode} - <insert> - {N10}
read2: ... |
import requests
from planet.api.dispatch import _get_user_agent
ITEM_TYPE_URL = 'https://api.planet.com/data/v1/item-types/'
ASSET_TYPE_URL = 'https://api.planet.com/data/v1/asset-types/'
_item_types = None
_asset_types = None
# Default values here are used as a fallback
# In case the API fails to respond or takes t... |
from typing import Any, Dict
from typing_extensions import TypedDict
import auth
from api.socket.constants import GAME_NS
from app import app, sio
from models import Label, LabelSelection, PlayerRoom, User
from state.game import game_state
from utils import logger
class LabelVisibilityMessage(TypedDict):
uuid: s... |
import os
import entrypoints
import numpy as np
def test_edf_ingestor(tmp_path):
from fabio.edfimage import EdfImage
# test data
data = np.random.random((1000, 1000))
# write data to test edf
edf_path = os.path.join(tmp_path, "test.edf")
print("edf_path:", edf_path)
EdfImage(data).write(ed... |
#!/usr/bin/env python
##############################################################################
# Written by: Cachen Chen <cachen@novell.com>
# Date: 08/11/2008
# Description: Test accessibility of form widget
# Use the formframe.py wrapper script
# Test the samples/winforms/for... |
version_info = (5, 6, 0)
__version__ = '.'.join(str(v) for v in version_info)
|
"""
Joe Tacheron
difficulty: 5%
runtime: 8m22s
answer: 128088830547982
***
719 Number Splitting
We define an S-number to be a natural number, n, that is a perfect square and its square root can be obtained by splitting the decimal representation of n into 2 or more numbers then adding the numbers.
For example, 81... |
def _setMatrix(mat,d,r,lis,fill,cmat,fmat,uniform,seed,null):
# =============================================================================
#Handle arguments
if isinstance(d,int):
mat._setDim(d)
if not isinstance(lis,(str,list)):
lis = []
#Empty list given
if len(lis)==0:
... |
'''
A 71.03711
C 103.00919
D 115.02694
E 129.04259
F 147.06841
G 57.02146
H 137.05891
I 113.08406
K 128.09496
L 113.08406
M 131.04049
N 114.04293
P 97.05276
Q 128.05858
R 156.10111
S 87.03203
T 101.04768
V 99.06841
W 186.07931
Y 163.06333
'''
if __name__ == '__main__':
data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.