content stringlengths 5 1.05M |
|---|
from mlflow_in_container import model_to_docker_container
if __name__ == "__main__":
model_path = 'example/wine_quality'
model_to_docker_container(modelpath='example/wine_quality/', dockerpath='example/wine_quality_docker/')
pass |
import torch
import torch.nn as nn
class ResNetUnit(nn.Module):
r"""Parameters
----------
in_channels : int
Number of channels in the input vectors.
out_channels : int
Number of channels in the output vectors.
strides: tuple
Strides of the two convolutional layers, in the f... |
from dataclasses import dataclass
from typing import Tuple
from mockdown.model.primitives import Attribute
from mockdown.model.types import IAnchor, IEdge, IView
from mockdown.types import NT
@dataclass(frozen=True)
class Edge(IEdge[NT]):
anchor: IAnchor[NT]
interval: Tuple[NT, NT]
@property
def vie... |
from mcpi_e.minecraft import Minecraft
from mcpi_e import block
serverAddress="192.168.1.155" # change to your minecraft server
playerName ="stoneskin2020"
pythonApiPort=4711
mc=Minecraft.create(serverAddress,pythonApiPort,playerName)
def SetTower(p,id):
for h in range(1,20):
x=p.x+1
y=p.y+h
... |
#!/usr/bin/env python
import sys
args = sys.argv
f = open(args[1])
of = open(args[2], "w")
keep = set(["gene", "transcript", "exon"])
for line in f:
if line.startswith("#"):
continue
cols = line.split("\t")
if cols[2] == "mRNA":
cols[2] = "transcript"
if cols[2] not in keep:
... |
import os
from numpy.testing import assert_equal, \
assert_array_max_ulp
from astropy.io import fits
import shutil
def spectrum_answer_testing(spec, filename, answer_store, answer_dir):
testfile = os.path.join(answer_dir, filename)
if answer_store:
spec.write_h5_file(testfile, overwrite=True)
... |
from .models import iam_backend
from ..core.models import base_decorator
iam_backends = {"global": iam_backend}
mock_iam = base_decorator(iam_backends)
|
#! /usr/bin/env python
import nmrglue.fileio.pipe as pipe
import nmrglue.process.pipe_proc as p
import shutil
d,a = pipe.read("1D_time_real.fid")
d,a = p.rft(d,a)
pipe.write("rft1.glue",d,a,overwrite=True)
d,a = pipe.read("1D_time.fid")
d,a = p.rft(d,a)
pipe.write("rft2.glue",d,a,overwrite=True)
d,a = pipe.read("ti... |
import pywikibot, re, os, time, sys, json
import toolforge
from datetime import date, datetime, timedelta, timezone
from pytz import timezone
site = pywikibot.Site("en", "wikipedia")
conn = toolforge.connect('enwiki_p','analytics')
connLabs = toolforge.connect_tools('s53143__mis_lists_p')
#cursor1 = connLabs.c... |
import praw
class Reddit:
def get_subreddit(self, subreddit):
return self.api.subreddit(subreddit)
def get_submission_title(self, submission):
return submission.title
def get_author(self, item):
return item.author
def __init__(self, config):
self.api = praw.Reddit(cli... |
import pytest
import rasterio
import rasterio.features
from shapely.geometry import shape, MultiPolygon
import numpy as np
DRIVERS = ['sqlite', 'mysql']
METADATA_KEYS = ('bounds', 'range', 'mean', 'stdev', 'percentiles', 'metadata')
@pytest.mark.parametrize('provider', DRIVERS)
def test_insertion_and_retrieval(driv... |
"""
Sequencer wrapper for QWERTY keyboard input.
We allow the synth to be played via string information,
with sources being live keyboard input, text files, and more!
We utilise the current default control scheme:
q,a,w,s,e,d,r,f,t,g,y,h,u,j,i,k,o,l,p - All play musical notes, q being the lowest and p being the high... |
from django.apps import AppConfig
import os
from django.conf import settings
class ssp(AppConfig):
name = 'ssp'
path = os.path.join(settings.BASE_DIR, 'ssp')
def ready(self):
import ssp.signals
|
import settings
import citizen
import praw
# Returns a dict of accessed submissions
def get_accessed_submissions():
# Returns an empty dict until the DB works.
return []
# Polls subreddit for new posts, matches against filters and processes
def process_new_posts():
r = praw.Reddit(user_agent=settings.USE... |
from typing import List, Any, Tuple
import random
import string
import time
import statistics
import torch
from pytorch_fast_elmo import batch_to_char_ids, FastElmo
class SentenceGenerator:
def __init__(
self,
word_min: int,
word_max: int,
sent_min: int,
... |
from itertools import islice
from random import random
from superfastcode import fast_map_tanh
from sys import exit
from time import perf_counter
DATA = iter(lambda: (random() - 0.5) * 3.0, None)
COUNT = 1000000
e = 2.7182818284590452353602874713527
def sinh(x):
return (1 - e ** (-2 * x)) / (2 * e ** -x)
def co... |
from pathlib import Path
from fhir.resources.codesystem import CodeSystem
from oops_fhir.utils import CodeSystemConcept
__all__ = ["HandlingConditionSet"]
_resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json"))
class HandlingConditionSet:
"""
HandlingConditionSet
Set of handling instr... |
# Copyright 2019 Regents of the University of Minnesota.
#
# 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 l... |
from .exceptions import mySword
from .session import session as ses
import requests
class api(object):
def __init__(self, session, v='5.95'):
if not isinstance(session, ses):
raise mySword("invalid session")
self.token = session.token
self.ver = v
def call(self, method, pa... |
from cli.cli import CLIObject
import click
@click.group()
@click.option('--test/--dont_test', default=False, help="Uses test information")
@click.option('--template', type=click.STRING, default=None, help="Define the template")
@click.option('--read/--dontread', is_flag=True, default=False, help="Readin pickled data")... |
from StatisticsCalc.mean import mean
from Calculator.square import square
from Calculator.division import division
def variance(data):
try:
mean_of_data = mean(data)
total_values = len(data)
v = 0
for a in data:
v = v + square(a - mean_of_data)
result = division(... |
#!/usr/bin/env python
# flake8: noqa
from . import dynamic_scraper
|
print(abs(-24.75)) |
def app(environ, start_response):
status = '200 OK'
headers = [
('Content-Type', 'text/plain')
]
body = ''
for line in environ["QUERY_STRING"].split("&"):
body += line + '\n'
start_response(status, headers)
return [bytes(body, encoding = 'utf8')]
|
# This method reads the data from the file and returns the two players decks
def getInput(inputPath):
fileP = open(inputPath, 'r')
fileLines = fileP.readlines()
fileP.close()
player1Deck = []
player2Deck = []
secondPlayer = False
firstPlayer = False
for line in fileLines:
line ... |
"""An example demonstrating displaying only a single annotation box cursor for
multiple subplots."""
import matplotlib.pyplot as plt
import numpy as np
from mpldatacursor import datacursor
plt.figure()
plt.subplot(2,1,1)
plt.title('Note that only one cursor will be displayed for display="single"')
plt.plot(range(10),... |
#!/usr/bin/env python
# flake8: noqa
from sourcestats.app import manager
from sourcestats.scripts import indexes
if __name__ == '__main__':
import boot
manager.run()
|
# Copyright 2014 VMWare.
#
# 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 ... |
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass
from typing import Iterable
@dataclass
class DocChunks:
"""
An chunks
Attributes
-----
chunks
An iterable of chunks where each of chunk
has tokens
"""
chunks: Iterable[Iterable[str]]
class Chunkce... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on: 2021/07/23 17:16
@Author: Merc2
'''
from pytorch_lightning.accelerators import accelerator
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
sys.path.append(r'D:\VQ-DDM')
sys.path.append(r'D:\VQ-DDMvqgan')
import afkmc2
import... |
import math
import os
from datetime import datetime
import keras as keras
import matplotlib.pyplot as plt
import tensorflow as tf
from keras.layers import (BatchNormalization, Conv2D, Conv2DTranspose, Dense,
Dropout, Flatten, LeakyReLU, Reshape)
from keras.models import Sequential
from keras.... |
import numpy as np
import random
from numpy.linalg import svd
import scipy
from scipy.optimize import minimize,minimize_scalar
from numpy.linalg import inv
import math
... |
import torch
import numpy as np
from mmdet.core import (bbox2result, bbox2roi, bbox_mapping, build_assigner,
build_sampler, merge_aug_bboxes, merge_aug_masks,
multiclass_nms)
from mmdet.core.bbox import bbox_mapping_back
from .cascade_roi_head import CascadeRoIHead
from ... |
import smtplib
import os
import subprocess
import sys
def check_setup():
try:
host = os.environ['EMAIL_HOST']
port = os.environ['EMAIL_PORT']
user = os.environ['EMAIL_USER']
password = os.environ['EMAIL_PASSWORD']
recipient = [os.environ['EMAIL_RECIPIENT']]
return h... |
from abc import ABCMeta
from future.utils import with_metaclass
class AbstractCommand(with_metaclass(ABCMeta)):
def __init__(self, command_config, api_client):
self.command_config = command_config
self.api_client = api_client
def execute(self):
return self.api_client.send_call(self.c... |
import os
import pickle
from itertools import compress
from sklearn.model_selection import cross_validate
from sklearn.svm import LinearSVC, SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from imblearn.ensemble import BalancedBaggingClassifier
from utils.logger i... |
import logging
from pathlib import Path
from hw_asr.datasets.custom_audio_dataset import CustomAudioDataset
from hw_asr.text_encoder.ctc_char_text_encoder import CTCCharTextEncoder
from hw_asr.utils.parse_config import ConfigParser
logger = logging.getLogger(__name__)
class CustomDirAudioDataset(CustomAudioDataset)... |
import os
import sys
def set_python_version():
python_version = str(sys.version_info.major) + "." + str(sys.version_info.minor)
file_names = [
r".github/workflows/main.yml",
]
for file_name in file_names:
with open(file_name) as f:
contents = f.read()
... |
# Copyright 2020 Skillfactory LLC
#
# 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 in wri... |
# Crie um programa que leia um número inteiro e mostre na tela se ele é par ou ímpar
num = int(input('Digite um número para saber se é par ou impar: '))
if num % 2 == 0: # % é o resto da divisão. Ou seja, divide o número por 2, se a sobra for 0, é par, do contrário ímpar
print(f'{num} é par')
else:
print(f'{n... |
from tests.test_adapter import TestConfig
import unittest
#test
if __name__ == "__main__":
#suite
suite=unittest.TestSuite()
suite.addTest(TestConfig("test_enforcer_basic"))
suite.addTest(TestConfig("test_add_policy"))
suite.addTest(TestConfig("test_save_policy"))
suite.addTest(TestConfig("test... |
import tweepy
#Enter your own keys here
consumer_key = "wXXXXXXXXXXXXXXXXXXXXXXX1"
consumer_secret = "qXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXh"
access_token = "9XXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXi"
access_token_secret = "kXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXT"
# Creating the API object ... |
from copy import deepcopy
from pandas import DataFrame, Series
from numpy import isnan
from ioUtils import getFile, saveFile
def passSelfMatch(primaryDB, primaryKey, dbIDs):
return primaryKey == dbIDs.get(primaryDB)
def passCircularMatch(primaryDB, primaryKey, secdbIDs):
return primaryKey == secdbIDs.ge... |
import json
from pydantic import BaseModel, Json
from threading import Timer
from timeit import default_timer as timer
from typing import List
from app.config.config import redisConnection
from app.models.game import Game
from app.game.gameBoard import GameBoard
""" --------------- Storage ------------------ """
gam... |
import discord
import asyncio
import logging
import os
import json
import traceback
logging.basicConfig(level=logging.INFO)
client = discord.Client()
EMOJI_RESERVIST = "🇷"
@client.event
async def on_message(message):
if message.content == "/update":
pinned = await message.channel.pins()
msg = pin... |
AMAZON_BASE_URL = 'https://www.amazon.com'
PREDEFINED_PRODUCT_ID = 'B00CYX26BC' ## default PID: Microsoft Sculpt Ergo Keyboard |
"""
PyEmail is a fast, powerful, and easy-to-use open-source Email tool.
"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP_SSL, SMTPServerDisconnected
from ssl import create_default_context
from typing import List, Optional
class Email:
"""Email
... |
#!/bin/python3
import math
import os
import random
import re
import sys
from bisect import insort, bisect_left
'''
Direct solution
num=30171, days= 10000
38
real 0m34.166s
user 0m34.013s
sys 0m0.079s
https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem
'''
# Complete the activit... |
from talon import Context, actions, Module, app
ctx = Context()
mod = Module()
mod.apps.mattermost = """
tag: browser
and title: /Mattermost/
"""
ctx.matches = r"""
app: mattermost
"""
@ctx.action_class("edit")
class EditActions:
def line_insert_up():
actions.key("home shift-enter up")
def line_in... |
import tensorflow as tf
from GanTrainer import GANTrainer
from tensorflow.python.ops import control_flow_ops
from utils import get_variables_to_train, montage_tf
slim = tf.contrib.slim
class SRGANTrainer(GANTrainer):
def __init__(self, *args, **kwargs):
GANTrainer.__init__(self, *args, **kwargs)
def... |
from eth_abi.codec import (
ABICodec,
)
from eth_abi.registry import (
registry,
)
default_codec = ABICodec(registry)
encode = default_codec.encode
decode = default_codec.decode
is_encodable = default_codec.is_encodable
is_encodable_type = default_codec.is_encodable_type
|
from database.mysql import MySQLDatabase
from settings import db_config
"""
Retrieve the settings from the
'db_config' dictionary to connect to
our database so we can instantiate our
MySQLDatabase object
"""
db = MySQLDatabase(db_config.get('db_name'),
db_config.get('user'),
db_c... |
#!/usr/bin/env python3
# Build the documentation.
import errno, os, shutil, sys, tempfile
from subprocess import check_call, check_output, CalledProcessError, Popen, PIPE
from distutils.version import LooseVersion
versions = ['0.1.0']
def pip_install(package, commit=None, **kwargs):
"Install package using pip."
... |
import time
import urllib
imgurl = 'http://127.0.0.1:73/'
imgurl = 'https://www.nordfront.se/wp-content/uploads/2018/01/blaljus-460x195.jpg'
def loop():
start = time.time()
response = urllib.urlopen(imgurl).read()
print(response)
urllib.urlretrieve(imgurl,'blaljus.jpg')
print(1... |
import contextlib
import logging
from dataclasses import dataclass
from typing import Dict, List, Tuple, Union
import discord
from fuzzywuzzy import process
from redbot.core import Config
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import humanize_list
from .exceptions import BankAlreadyExi... |
from decorator import decorator
@decorator
def
|
""" All custom services that can be used with the phoniebox """
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.components.media_player import ATTR_MEDIA_SEEK_POSITION
from homeassistant.const import ATTR_TIME
from homeassistant.helpers import entity_platform
from homeas... |
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic import TemplateView
from django.http import JsonResponse
from post.models import Post, reply, Comment
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from djan... |
from py.test.tools import (
BaseTestCase,
)
from py.src.settings.envar import (
_ENVARS,
)
class EnvarTest(BaseTestCase):
def test_is_web_server(self):
sut = _ENVARS({})
self.assertTrue(sut.is_web_server())
sut = _ENVARS({"instance_type": "dev"})
self.assertTrue(sut.is_we... |
#! /usr/bin/env python
"""
Compute dh/dt and mass balance for input DEMs and glacier polygons
"""
"""
Todo:
GDAL_MAX_DATASET_POOL_SIZE - set to large number of open datasets in vrt
Better error estimates - use buffered dz/dt and semivariogram
Filling gaps using 1) dz/dt obs 2) setting to 0 around polygon margins
Curve... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-10-04 11:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('energy', '0001_initial'),
]
operations = [
migrations.AlterField(
... |
import logging
from dataclasses import dataclass
import csv
@dataclass
class Analogy:
q_1_type: str
q_1_id: str
q_2_type: str
q_2_id: str
p_type: str
p_id: str
q_1_source: str
q_1_source_id: str
q_1_source_context: str
q_1_target: str
q_1_target_id: str
q_1_target_conte... |
from django.apps import AppConfig
class AdminColorsConfig(AppConfig):
name = 'admincolors'
|
import discord
from discord.ext import commands
import asyncio
from pymongo import MongoClient
import datetime
app = MongoClient("mongo_link")
db = app['Database']
muteds = db['muteds']
guilds = db['guilds']
#gostaria de esclarecer que o formato que uso para as guildas na database é
#{'_id': IDdaGuilda, 'modlog': True... |
# -*- coding: utf-8 -*-
"""Container for any media type.
"""
from datetime import datetime
from typing import Dict, Any
from ad_hoc_scripts.common import utils_filesystem
from mss.utils.utils_scripts import get_path_ending, drop_filename_from_path
from ad_hoc_scripts import analyze
# FIXME
total = 0
class Unregist... |
def sum_series(n: int) -> int:
return sum([ sum(range(1, i + 1)) for i in range(1, n + 1)])
def main():
n = int(input("Enter a number: "))
print("S =", sum_series(n))
if __name__ == '__main__':
main()
|
import unittest
from stacker.actions.diff import diff_dictionaries
class TestDiffDictionary(unittest.TestCase):
def setUp(self):
self.old_dict = {
"a": "Apple",
"b": "Banana",
"c": "Corn",
}
self.new_dict = {
"a": "Apple",
"b": "... |
#!/usr/bin/python3
import os
import unittest
from gamutrf.samples2raw import make_procs_args
class Samples2RawTestCase(unittest.TestCase):
def test_procs_args_(self):
self.assertEqual(
[['gunzip', '-c', 'gamutrf_recording1644265099_320000000Hz_20000000sps.s16.gz'],
['sox', '-t'... |
import re
import inspect
from .backwardscompat import callable
# metaclass implementation idea from
# http://blog.ianbicking.org/more-on-python-metaprogramming-comment-14.html
_transition_gatherer = []
def transition(event, from_, to, action=None, guard=None):
_transition_gatherer.append([event, from_, t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
python-cfconfigurator is a simple and small library to manage Cloud Foundry
(c) 2016 Jose Riguera Lopez, jose.riguera@springer.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Sof... |
from copy import deepcopy
from pathlib import Path
from typing import Tuple, Optional
import cv2
import numpy as np
from core.mouse import Mouse
from core.gui import AppGui
class GrabCutApp:
IMAGE_SIZE = (512, 512)
MASK_ALPHA = 0.7
READ_WAIT = 100
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BL... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.6.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %matplotlib inline
# +
# Imp... |
from rest_framework import serializers
from . import models
class ScriptSerializer(serializers.ModelSerializer):
class Meta:
model = models.Script
fields = ('id', 'litter_id', 'status', 'download')
|
import matplotlib; matplotlib.use('Agg')
import torch
import numpy as np
from spirl.utils.general_utils import AttrDict, ParamDict
from spirl.components.params import get_args
from spirl.utils.debug import register_pdb_hook
register_pdb_hook()
from spirl.utils.pytorch_utils import ar2ten, ten2ar
from spirl.fewshot_tr... |
"""
Module for bulk-exporting IsisCB data.
The strategy here is to favor extensibility/flexibility in defining output
columns, at the expense of performance. The performance hit is probably OK,
since these jobs will be performed asynchronously.
"""
from __future__ import print_function
from __future__ import unicode_l... |
from treasury_prime.treasury_prime import TreasuryPrimeAPI
from treasury_prime.models.dataclass_types import account_application_type
from treasury_prime.models.dataclass_types import person_application_type
from treasury_prime.models.apply import Deposit, Ach
r = TreasuryPrimeAPI()
"""
https://developers.sandbox.tr... |
from setuptools import setup
setup(
name='dbinterfacer',
version='0.0.1',
url='https://github.com/csb-comren/dbinterfacer',
description='Abstraction layer between the database and django',
install_requires=['pynmea2'],
)
|
#
# Autogenerated by Thrift Compiler (0.10.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
import sys
import airavata.... |
"""Abstract base interface for vehicle data sources."""
import threading
import logging
import string
import sys
import datetime
from openxc.formats.binary import ProtobufStreamer, ProtobufFormatter
from openxc.formats.json import JsonStreamer, JsonFormatter
LOG = logging.getLogger(__name__)
class MissingPayloadFo... |
# ----------------------------------------------------------------------------------------------------
# (C) Copyright IBM Corp. 2020. 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... |
"""H1st IoT Data Management: models."""
import warnings
from django.db.models import (
Model,
CharField, DateField, FloatField, IntegerField,
JSONField,
ForeignKey, ManyToManyField,
PROTECT)
from django.db.models.signals import m2m_changed, pre_delete
from h1st_contrib.iot_mgmt.utils import MAX_... |
#!/usr/bin/env python
import sys, time, os, os.path, sqlite3, json
prefix = os.path.dirname(sys.argv[0]) or '.'
f = open(prefix + '/vis.min.js')
js = f.read()
f.close()
f = open(prefix + '/vis.min.css')
css = f.read()
f.close()
f = open('mprofile.html', 'w')
print >> f, """<!doctype html>
<html>
<head>
<style>
%s
</s... |
r"""
The MIT License (MIT)
Copyright (c) 2020 Varuna Jayasiri
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, modify, me... |
def rule(_):
return True
def title(event):
query_text = event.get('query_text', '').split(' ')
if len(query_text) > 2:
return f"Snowflake user [{query_text[2]}] created by [{event.get('user_name','<UNKNOWN_ADMIN>')}]"
return f"Snowflake user [<UNKNOWN_USER>] created by [{event.get('user_name','... |
from astropy import units as u
"""The module is a high-level interface to astrocut for use with HAP SVM and MVM files."""
from astrocut import fits_cut
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.io import fits
from astropy.table import Table, vstack
from astropy.units.quantity... |
"""
Small scanf implementation.
Python has powerful regular expressions but sometimes they are totally overkill
when you just want to parse a simple-formatted string.
C programmers use the scanf-function for these tasks (see link below).
This implementation of scanf translates the simple scanf-format into
regular exp... |
import torch
from torch import nn
from torch.nn import functional as F
from transformers import (
AdamW,
get_linear_schedule_with_warmup,
BartModel,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.modeling_outputs import Seq2SeqLMOutput
class BartGen(PreTrainedModel):
... |
# -*- coding: utf-8 -*-
# Вывод текущего состояния всех очередей
"""
[many lines of trassir_script_framework source]
"""
zones = Zones()
queues = zones.get_queues()
for queue in queues:
host.message("{} -> {} чел".format(queue.name, queue.obj.state("zone_queue")))
|
import torch.nn as nn
import torch
input = torch.randn([3, 10, 1, 1])
print(input.shape)
m = nn.ConvTranspose2d(10, 6, kernel_size=10, padding=1, stride=2, bias=False)
out = m(input)
print(out.shape) |
# AUTOGENERATED! DO NOT EDIT! File to edit: 02_dataloader.ipynb (unless otherwise specified).
__all__ = ['Coseg']
# Cell
import os
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms as T
import matplotlib.pyplot as plt
from PIL import Image
# Cell
class Coseg(Dataset):
""" Datas... |
from casexml.apps.case.models import CommCareCase
from corehq.apps.userreports.models import DataSourceConfiguration
from corehq.apps.userreports.sql import get_engine, IndicatorSqlAdapter
from pillowtop.couchdb import CachedCouchDB
from pillowtop.listener import PythonPillow
class ConfigurableIndicatorPillow(PythonP... |
from subprocess import CalledProcessError
from .run_command import run_command
def have_program(program_name):
try:
return bool(run_command("which {}".format(program_name)).stdout.strip())
except CalledProcessError:
return False
|
import socket
import sys
import json
import binascii
import hmac
import yaml
with open("devices.yaml") as f:
devices = yaml.safe_load(f)
device = sys.argv[1]
filename = sys.argv[2]
key = binascii.unhexlify(devices[device]["glitter"])
with open(filename, "rb") as f:
file_contents = f.read()
hmac = binascii.... |
def main():
lines = []
filename = 'day2_1_input.txt'
userInput = open(filename, 'r')
print ("Starting from the top")
for line in userInput:
lines.append(line)
for idx, cur in enumerate(lines):
print(idx)
for other in lines[idx:]:
errorCount = 0
las... |
from typing import Tuple
import torch
import torch.nn.functional as F
import math
import escnn.nn as enn
from escnn.nn import init
from escnn import gspaces
from argparse import ArgumentParser
__all__ = [
"wrn16_8_stl_d8d4d1",
"wrn16_8_stl_d8d4d4",
"wrn16_8_stl_d1d1d1",
"wrn28_10_d8d4d1",
"wrn... |
# Copyright (C) 2020 Intel Corporation
#
# 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 wri... |
#!/usr/bin/env python
# (c) 2016 David A. van Leeuwen
## extract .wav channel from .aup file
##
## usage: python -m audacity --channel 1 file.aup file.wav
import argparse
from . import Aup
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("--channel", type=int, default=1)
p.add_argu... |
"""Generated client library for artifactregistry version v1alpha1."""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.py import base_api
from googlecloudsdk.third_party.apis.artifactregistry.v1alpha1 import artifactregistry_v1alpha1_messag... |
'''
Created on 2018/04/30
@author: syuu
'''
import pandas as pd
from matplotlib import pyplot
indata = [('Toms', 174, 75), ('Jam', 144, 45), ('Lily', 114, 25)]
df = pd.DataFrame(data = indata, columns= ['name','weight','length'], index = ['one','two','threes'])
print(df)
print("====================")
print(df['name'... |
class Solution:
def countElements(self, arr: List[int]) -> int:
map = {}
for n in arr:
if map.get(n) is None:
map[n] = 1
else:
map[n] += 1
count = 0
for key in map.keys():
count += map.get(key + 1) is not None and m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.