content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from rest_framework import serializers
from backend.models import Shortener
# Lead Serializer
class ShortenerSerializer(serializers.ModelSerializer):
class Meta:
model = Shortener
fields = '__all__'
read_only_fields = ['id', 'responseURL', 'date']
| python |
"""For entities that have specs."""
from gemd.entity.has_dependencies import HasDependencies
from gemd.entity.object.has_template import HasTemplate
from gemd.entity.template.base_template import BaseTemplate
from gemd.entity.link_by_uid import LinkByUID
from abc import abstractmethod
from typing import Optional, Unio... | python |
from otree.api import Currency as c, currency_range
from . import pages
from ._builtin import Bot
from .models import Constants
import csv
class PlayerBot(Bot):
def play_round(self):
with open('trial_set_FR.csv', newline='', encoding='cp1252') as csvfile:
csv_reader = csv... | python |
###########DO NOT DELETE#########################
#cat /proc/sys/vm/overcommit_memory
#echo 1 | sudo tee /proc/sys/vm/overcommit_memory
#################################################
from tifffile import imsave
import numpy as np
import cv2
import os
import datetime
from PIL import Image
norm = np.zeros((480,848... | python |
from . import executor
from . import phone
from . import snoopphone | python |
"""Added ml_models table
Revision ID: 7e60a33f42bb
Revises: 11aa784195ef
Create Date: 2021-04-16 02:25:10.719706
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "7e60a33f42bb"
down_revision = "11aa784195ef"
branch_labels = None
depends_on = None
def upgrade()... | python |
import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
from django.test.simple import run_tests as django_test_runner
from django.conf import settings
def runtests():
failures = django_test_runner(['localedb'], verbosity=1, interactive=Tr... | python |
# Working with Date And Time.
import datetime
from datetime import date
# Get today's date from the date class.
today = date.today()
print ("Today's date is ", today)
myDate = datetime.date(2018,6,9)
print(myDate)
print(myDate.year)
print(myDate.month)
print(myDate.day)
#Day-name,Month-name,Day-name,Year
pr... | python |
#!/usr/bin/env python
"""
Merges global.yml and config.yml to create various local.yml for each room assistant peer node. It then
sends the configuration file to peer, and restarts the room assistant service.
See README.md file for details.
"""
import math
import os
import time
import yaml
def mergeDicts(dict1, dict... | python |
n,t=map(int,input().split())
x=[]
mp=10**6
for i in range(n):
x.append([*map(int,input().split())])
mp=min(mp,x[i][1])
left,right=-mp,10**7
while abs(left-right)>=0.00000001:
mid=(left+right)/2
hour=0
for i in x:
hour+=i[0]/(i[1]+mid)
if hour>=t: left=mid
else: right=mid
print(left) | python |
from django.apps import AppConfig
class StudentportalConfig(AppConfig):
name = 'studentportal'
| python |
import os
import qrcode
from ckeditor.fields import RichTextField
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
from . import constants
User = get_user_m... | python |
import numpy as np
from tools.metadata import get_hero_dict
import operator
import pandas as pd
import plotly.graph_objs as go
import plotly.plotly as py
def winrate_statistics(dataset_df, mmr_info):
x_data, y_data = dataset_df
wins = np.zeros(114)
games = np.zeros(114)
winrate = np.zeros(114)
... | python |
# First, lets get a list of all files in the data directory
import time
import sys
from tensorflow import keras
import tensorflow as tf
import pathlib
import json
from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint
from tensorflow.keras.layers import Conv3D, MaxPooling3D, BatchNormalization, GlobalAv... | python |
from Gaussiandistribution import Gaussian
gaussian_one = Gaussian(22, 2)
print(gaussian_one.mean) | python |
from math import floor
def find_position(value):
position = floor(value / 100)
if value % 100 == 0:
position = position - 1
return position
def center_of_square(coordinate, dimension):
return coordinate + dimension / 2
| python |
#
# Script to do an Oracle restore given an optional date range of the copy
# An existing restore job is required, copy version of that job will be updated if applicable
# If no date range is provided the latest copy will be used
# Backup job name for the copy to use can also be provided
# Set the cancel parameter = tr... | python |
# Copyright 2019 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... | python |
def create_app():
from flask import Flask
from localtalk.views import init_views
app = Flask(__name__)
# init views
init_views(app)
return app
def create_server():
from localtalk.server import Server
server = Server()
return server
| python |
import asyncio
from datetime import datetime
import logging
import aiohttp
import requests
import certifi
TIMEOUT_FOR_PAR_REQS = 60*5
TIMEOUT_FOR_SEQ_REQS = 60
Logger = logging.getLogger(__name__)
class InvalidClientResponse:
def __init__(self):
self.status = None
async def fetch(uri, session, body=F... | python |
from django.db import models
from covid_data.models.base import ModeloBase
class Sector(ModeloBase):
"""Identifica el tipo de institución del Sistema Nacional de Salud
que brindó la atención.
"""
clave = models.IntegerField(unique=True)
descripcion = models.CharField(max_length=63)
def __repr... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayUserStepcounterQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayUserStepcounterQueryResponse, self).__init__()
self._count = None
... | python |
#!/usr/bin/env python
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import messagebird
# ACCESS_KEY = ''
# PHONE_NUMBER = ''
try:
ACCESS_KEY
except NameError:
print('You need to set an ACCESS_KEY constant in this file')
sys.exit(1)
try:
PHONE_NUMBER
except NameError:
print... | python |
while 0 < 1:
mec = input("Valor da Medardoria: ")
icns = float(mec) * 17/100
irpf = float(mec) * 15/100
csll = float(mec) * 7.6/100
cofins = float(mec) * 3/100
pis = float(mec) * 1.65/100
me = float(mec) - (icns + irpf + cofins + pis + csll)
print("<<<<<<<<<<<RESLTADO>>>>>>>>>>"... | python |
from ._fastfood import Fastfood
__all__ = ['Fastfood']
| python |
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.conf import *
from .models import User
import json
# Create your views here.
def login(request):
return render(request,'account/login.html')
def dologin(request):
username=request.POST['username']
pwd=request.... | python |
#! /usr/bin/env python
#-******************************************************************************
#
# Copyright (c) 2012-2013,
# Sony Pictures Imageworks Inc. and
# Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
#
# All rights reserved.
#
# Redistribution and use in source and bina... | python |
# Copyright 2022 The Balsa 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | python |
# -*- coding: utf-8 -*-
"""Main module."""
import sys
import urllib.request
import re
def main():
'''Checks that an argument has been given, otherwise returns and error. Then checks that the file contains something.
Then it converts the file to a string, takes the first line as the size of the array for our ... | python |
import os
import logging
import sys
import tempfile
from setuptools import setup, find_packages
from setuptools.command.install import install
VERSION='1.1.4'
def readme():
"""Use `pandoc` to convert `README.md` into a `README.rst` file."""
if os.path.isfile('README.md') and any('dist' in x for x in sys.argv[1:]... | python |
import argparse
class Arguments():
def __init__(self):
self.parser = argparse.ArgumentParser(
description='''
Quick & easy to use nutritional supplement tracking software
https://github.com/ncdulo/suppylement
'''
)
# Shoul... | python |
from timeslot import TimeSlot, sort_by_begin_time, sort_by_end_time
from random import shuffle
import arrow, timeslot
#############################################################################
#
# Testing Merge
#
#############################################################################
def test_merge_unable():... | python |
from zoloto.cameras.camera import Camera # noqa
from zoloto.cameras.file import ImageFileCamera, VideoFileCamera # noqa
| python |
from dagster_graphql.client.query import START_PIPELINE_EXECUTION_MUTATION, SUBSCRIPTION_QUERY
from dagster_graphql.implementation.context import DagsterGraphQLContext
from dagster_graphql.implementation.pipeline_execution_manager import SubprocessExecutionManager
from dagster_graphql.schema import create_schema
from d... | python |
from datetime import timedelta
import pendulum
import pytest
import logging
from uuid import uuid4
from unittest.mock import MagicMock
import prefect
from prefect.client.client import FlowRunInfoResult, ProjectInfo
from prefect.engine import signals, state
from prefect.run_configs import UniversalRun
from prefect.bac... | python |
import time
import random
import logging
from datetime import datetime
from osgate.connectors.connector import AbstractConnector, ConnectorBase
log = logging.getLogger(__name__)
class DefaultConnector(AbstractConnector, ConnectorBase):
"""Used for testing of design pattern; allows non-existing connector and dev... | python |
from os import environ, path
from ._settings_default import *
from ..exceptions import ImproperlyConfigured
PROFILE = environ.get("GOLD_DIGGER_PROFILE", "local")
if PROFILE == "master":
from ._settings_master import *
elif PROFILE == "local":
try:
from ._settings_local import *
except ImportError... | python |
from django.urls import path
from . import views
urlpatterns = [
path('', views.data_view, name='data_view'),
] | python |
from random import randint
class Die():
"""表示一个骰子的类"""
def __init__(self,number_size = 6):
self.number_size = number_size
#翻滚骰子
def roll(self):
"""返回一个位于1和骰子面数之间的随机数"""
return randint(1,self.number_size) | python |
"""Voorbeeld met 2 armen."""
from asyncgcodecli import UArm
async def move_script(uarms: UArm):
"""Script that moves the robot arm."""
# set de robot arm mode to 0 (pomp)
for uarm in uarms:
uarm.set_mode(0)
for _ in range(1, 5):
for uarm in uarms:
await uarm.sleep(0)
... | python |
from django.db import models
# Create your models here.
class List(models.Model):
item = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
def __str__(self):
return self.item + ' | ' + str(self.completed)
| python |
import unittest
import logging
from varfilter import filter
class Testfilter(unittest.TestCase):
def setUp(self):
print('Preparando el contexto')
def test_fint_int_ok(self):
print('fint con entero correcto')
t = filter.fint(10)
self.assertEqual(t, 10)
def test_fint_str_o... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('spam', '0001_initial'),
]
operat... | python |
from messagebird.base import Base
from messagebird.formats import Formats
from messagebird.hlr import HLR
class Lookup(Base):
def __init__(self):
self.href = None
self.countryCode = None
self.countryPrefix = None
self.phoneNumber = None
self.type = None
self._format... | python |
# import commands
import commands
# password helper
import json
from getpass import getpass
# define 'submitnonce' command
def parse(cmd, arguments, connection):
if len(arguments) != 2:
print("error: '"+cmd.name+"' requires one argument.")
else:
nonce = arguments[1]
response, result ... | python |
"""
*C♯ - Level 4*
"""
from ..._pitch import Pitch
__all__ = ["Cs4"]
class Cs4(
Pitch,
):
pass
| python |
for i in range(1,5): #More than 2 lines will result in 0 score. Do not leave a blank line also
print(int(pow(10,i)/9) * i) | python |
import datetime
import getpass
import os
import platform
import pwd
import socket
import sys
import time
def collect_python_facts():
return {
'version': {
'major': sys.version_info[0],
'minor': sys.version_info[1],
'micro': sys.version_info[2],
'releaselevel... | python |
"""Token module to indicate that a feed plugin for LOFAR can be generated from
here.
"""
# Since the LOFAR project provides an AntPat compatible file of beam-model data,
# no initialization steps are necessary.
| python |
"""
A collection of modules for collecting, analyzing and plotting
financial data. User contributions welcome!
"""
#from __future__ import division
import os, time, warnings, md5
from urllib import urlopen
try: import datetime
except ImportError:
raise SystemExit('The finance module requires datetime support... | python |
"""This script uses web.py to control and retreive the state of thermostats in a home.
"""
import json
import random
import web
# web.py definition that maps /anything to the Index class defined below
urls = ('/(.*)', 'Index')
# In memory database for existing sensors
sensor_devices_in_home = {}
def setup_devices(... | python |
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
import errno
import functools
import select
import socket
def syscall_retry_on_interrupt(func, *args):
"""Attempt system call again if interrupted by EINTR """
for _ in range(0, 5):
try:
return f... | python |
# -*- coding: utf-8 -*-
#
# Copyright 2015 Ternaris, Munich, Germany
#
# 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, c... | python |
import numpy as np
def calculate_predictions(events, cluster_info):
# This function takes existing events, and backtracks this to predictions.
predictions = np.empty((len(cluster_info), 2), dtype=np.float64)
# The predictions matrices are stored (for historical reasons) in microns. So multiply with pixel... | python |
import os
import unittest
from __main__ import vtk, qt, ctk, slicer
#
# TortuosityLogicTests
#
class TortuosityLogicTests:
def __init__(self, parent):
parent.title = "TortuosityLogicTests" # TODO make this more human readable by adding spaces
parent.categories = ["Testing.TestCases"]
parent.dependencies... | python |
#!/usr/bin/env python3
# author: greyshell
# description: demo how to use heapq library
import heapq
class MaxHeapNode(object):
def __init__(self, key):
self.key = key
def __lt__(self, other):
# compare based on val
# tweak the comparison logic to build max heap: change less_than_si... | python |
import logging
from gehomesdk.erd.converters.abstract import ErdReadOnlyConverter
from gehomesdk.erd.converters.primitives import *
from gehomesdk.erd.values.laundry import ErdTankSelected, TankSelected, TANK_SELECTED_MAP
_LOGGER = logging.getLogger(__name__)
class TankSelectedConverter(ErdReadOnlyConverter[TankSele... | python |
#!/usr/bin/env python
"""This script generates a two-column reStructuredText table in which:
- each row corresponds to a module in a Python package
- the first column links to the module documentation
- the second column links to the module source code generated by
the 'viewcode' extension
"""
__date__ =... | python |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
import uuid
from azure.keyvault.certificates import CertificateClient, CertificatePolicy
from key_vault_base import KeyVaultBase
class KeyVaultCertificates(Ke... | python |
import os
import dropbox
from .cloud_provider import CloudProvider
class DBox(CloudProvider):
def __init__(self, access_token):
"""
Initializes class
Parameters
----------
access_token : str
Dropbox access token
"""
if not isinstance(access_tok... | python |
#####################################
# CELERY
#####################################
from datetime import timedelta
from kombu import Exchange
from kombu import Queue
def celery_queue(key):
return Queue(key, Exchange(key), routing_key=key)
CELERY_CREATE_MISSING_QUEUES = True
CELERY_DEFAULT_QUEUE = 'default'
CE... | python |
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from authentication.models import Account
from authentication.models import AccountManager
class Entity(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
created_by = Account
updated_at = ... | python |
# Lint as: python3
# Copyright 2021 Jose Carlos Provencio
#
# 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 applicabl... | python |
from flask import url_for, request
from flask_restplus import Namespace, Resource
import strongr.restdomain.model.gateways
from strongr.restdomain.model.oauth2 import Client
ns = Namespace('oauth', description='Operations related to oauth2 login')
@ns.route('/revoke', methods=['POST'])
class Revoke(Resource):
de... | python |
from hs_students import HighSchool
highSchoolStudent = HighSchool('Manasvi', 10)
print(highSchoolStudent.get_name_captalize())
print(highSchoolStudent.get_School_name())
| python |
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from photos import views
from .views import BlogCreateView
urlpatterns =[
path('post/new/', BlogCreateView.as_view(), name='post_new'),
url(r'^one/', vi... | python |
from tests.util import BaseTest
class Test_C2025(BaseTest):
def error_code(self) -> str:
return "C2025"
def test_fail_1(self):
code = """
foo = (1 if True
else 0)
"""
result = self.run_flake8(code, True)
self.assert_error_at(result, "C2025", 1, 8... | python |
"""
This following demonstrates a Noise_NNpsk0+psk2_25519_ChaChaPoly_BLAKE2s handshake and initial transport messages.
"""
from dissononce.processing.impl.handshakestate import HandshakeState
from dissononce.processing.impl.symmetricstate import SymmetricState
from dissononce.processing.impl.cipherstate import CipherSt... | python |
from invoke import (
run,
task,
)
from . import common
LANGUAGE = 'js'
@task
def clean():
print 'cleaning %s...' % (LANGUAGE,)
with common.base_directory():
run("rm -rf %(language)s && mkdir %(language)s" % {'language': LANGUAGE})
@task(default=True)
def compile():
print 'compiling %s.... | python |
import math
from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
def _initialize_embeddings(weight: Tensor, d: int) -> None:
d_sqrt_inv = 1 / math.sqrt(d)
# This initialization is taken from torch.nn.Linear and is equivalent to:
# nn.init.kai... | python |
#!/usr/bin/python3
# Extract Ansible tasks from tripleo repos
import os
import yaml
TASK_ATTRS = [
"action",
"any_errors_fatal",
"args",
"async",
"become",
"become_exe",
"become_flags",
"become_method",
"become_user",
"changed_when",
"check_mode",
"collections",
"c... | python |
from searx import settings, autocomplete
from searx.languages import language_codes as languages
from searx.url_utils import urlencode
COOKIE_MAX_AGE = 60 * 60 * 24 * 365 * 5 # 5 years
LANGUAGE_CODES = [l[0] for l in languages]
LANGUAGE_CODES.append('all')
DISABLED = 0
ENABLED = 1
class MissingArgumentException(Ex... | python |
from scapy.all import *
from ccsds_base import CCSDSPacket
class PL_IF_HK_TLM_PKT_TlmPkt(Packet):
"""Pl_if App
app = PL_IF
command = HK_TLM_PKT
msg_id = PL_IF_HK_TLM_MID = 0x09de = 0x0800 + 0x1de
"""
name = "PL_IF_HK_TLM_PKT_TlmPkt"
fields_desc = [
# APPEND_ITEM CMD_VALID_COUNT 16... | python |
from autorop.bof.Corefile import Corefile
| python |
import netaddr
from django.urls import reverse
from sidekick.models import (
LogicalSystem, RoutingType,
NetworkServiceType, NetworkService,
NetworkServiceGroup,
)
from .utils import BaseTest
class NetworkServiceTest(BaseTest):
# Logical System
def test_logicalsystem_basic(self):
v = Lo... | python |
"""
Http related errors
"""
class HTTPError(Exception):
""" Base class for all http related errors """
status_code = 500
class HTTPForbidden(HTTPError):
""" Http forbidden error (status code 403). """
status_code = 403
class HTTPBadRequest(HTTPError):
""" Client sent a bad request. """
sta... | python |
# coding=utf-8
"""
Port of the ganglia gearman collector
Collects stats from gearman job server
#### Dependencies
* gearman
"""
from diamond.collector import str_to_bool
import diamond.collector
import os
import subprocess
import time
try:
import gearman
except ImportError:
gearman = None
class Gearma... | python |
import requests
print requests.delete("http://localhost:7215/player/", json={"uid": "K/1H5bdxo7GwMBUp8qVQz42h7ZE=", }).content
print requests.put("http://localhost:7215/player/", json={"uid": "K/1H5bdxo7GwMBUp8qVQz42h7ZE=", "team": "emc", "rank": "grunt",}).content
#print requests.put("http://localhost:7215/battlemo... | python |
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth.views import login, logout
from chat.views import index,register_page
app_name= "multichat"
urlpatterns = [url(r'^home/$', index),
url(r'^$', index),
url(r'^register/$', register_page),
url(r'^accounts/login/$', l... | python |
from .game_move import GameMove
from .game_node import GameNode
from .game_state import GameState
from .game_tree import GameTree
# from .game import Game
from .game_multithread import GameMultithread
| python |
from coders import NoopCoder
from sources import CsvFileSource
| python |
# built-in
import ctypes;
import os;
# import matey shared library
current_dir = os.path.dirname(__file__);
matey_path = os.path.join(current_dir, "matey.so");
libmatey = ctypes.CDLL(matey_path);
#### SUM #######################################################################
libmatey.sum.restype = ctypes.c_int;
lib... | python |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.md', 'r') as rm:
long_desc = rm.read()
setup(
name='soloman',
version='3.0.2',
description='For the love of Artificial Intelligence, Python and QML',
long_description=long_desc,
long_description_content_type=... | python |
from email.charset import Charset, QP
from email.mime.text import MIMEText
from .base import AnymailBaseBackend, BasePayload
from .._version import __version__
from ..exceptions import AnymailAPIError, AnymailImproperlyInstalled
from ..message import AnymailRecipientStatus
from ..utils import get_anymail_setting, UNSE... | python |
import pandas as pd
import numpy as np
class omdf:
def __init__(self,dff):
self.df = dff
self.arr = self.df.to_numpy()
def df_add_col_instr(self):
self.df['cat'] = self.df.apply(lambda row: TS(row.Summary), axis = 1)
return self.df.to_dict()
def df_add_col_dic(self,colname,... | python |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import, division
""" http://projecteuler.net/index.php?section=problems&id=18 triangle
it has been finished in 10 minutes
using recursive method is prefered, brute force not feasible to solve this problem
"""
from proje... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, ... | python |
# -*- coding: utf-8 -*-
'''
Este módulo tiene todas las funciones pertinentes para obtener y/o calcular los diferentes parámetros del modelo a partir de datos y/o parámetros del artículo de Arenas.
Convención del vector de parámetros siguiendo la Supplementary Table 1 de [1]:
# Parámetros usuales
β = ... | python |
"""Support for TPLink lights."""
from __future__ import annotations
import logging
from typing import Any
from kasa import SmartDevice
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_HS_COLOR,
ATTR_TRANSITION,
COLOR_MODE_BRIGHTNESS,
COLOR_MODE_COLOR_TEMP,
... | python |
# -*- coding: utf-8 -*-
import logging
import allel
import h5py
import os
import os.path
import haplotype_plot.constants as constants
import haplotype_plot.reader as reader
import haplotype_plot.filter as strainer
import haplotype_plot.haplotyper as haplotyper
import numpy as np
logger = logging.getLogger(... | python |
import torch
import transformers
from packaging import version
from torch.utils.data import SequentialSampler
from transformers import BertConfig, BertForSequenceClassification
from .registry import non_distributed_component_funcs
def get_bert_data_loader(
batch_size,
total_samples,
sequence_... | python |
# SPDX-FileCopyrightText: 2021 European Spallation Source <info@ess.eu>
# SPDX-License-Identifier: BSD-3-Clause
__author__ = 'github.com/wardsimon'
__version__ = '0.0.1'
import numpy as np
import pytest
from easyCore.Objects.Base import Descriptor, Parameter, BaseObj
from easyCore.Objects.Groups import BaseCollecti... | python |
#!/usr/bin/env python3
import csv
import itertools as it
import os
import sys
def write_csv(f, cols, machines, variants):
w = csv.writer(f, delimiter=',')
headers = ["{}-{}".format(m, v) for (m, v) in it.product(machines, variants)]
w.writerow(headers)
for e in zip(*cols):
w.writerow(list(e))
... | python |
import torch
from torch.autograd import Variable
from deepqmc.wavefunction.wf_orbital import Orbital
from deepqmc.wavefunction.molecule import Molecule
from pyscf import gto
import matplotlib.pyplot as plt
import numpy as np
import unittest
class TestAOvalues(unittest.TestCase):
def setUp(self):
# def... | python |
from math import ceil
from struct import pack, unpack
import numpy as np
import ftd2xx as ftd
from timeflux.core.node import Node
from timeflux.helpers.clock import now
from timeflux.core.exceptions import WorkerInterrupt, TimefluxException
VID = 0x24f4 # Vendor ID
PID = 0x1000 # Product ID
HEADER = 0xAA... | python |
first = "0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2021, earthobservations developers.
# Distributed under the MIT License. See LICENSE for more info.
"""
=====
About
=====
Example for DWD RADOLAN Composite RW/SF using wetterdienst and wradlib.
Hourly and gliding 24h sum of radar- and station-based measurements (German).
Se... | python |
# -*- encoding: utf-8 -*-
import pandas as pd
import pytest
from deeptables.datasets import dsutils
from deeptables.models import deeptable
from deeptables.utils import consts
class TestModelInput:
def setup_class(cls):
cls.df_bank = dsutils.load_bank().sample(frac=0.01)
cls.df_movielens = dsuti... | python |
# This file is part of Moksha.
# Copyright (C) 2008-2010 Red Hat, 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 b... | python |
from ctypes import *
SHM_SIZE = 4096
SHM_KEY = 67483
try:
rt = CDLL('librt.so')
except:
rt = CDLL('librt.so.1')
shmget = rt.shmget
shmget.argtypes = [c_int, c_size_t, c_int]
shmget.restype = c_int
shmat = rt.shmat
shmat.argtypes = [c_int, POINTER(c_void_p), c_int]
shmat.restype = c_void_p
shmctl = rt.shmct... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.