content stringlengths 5 1.05M |
|---|
from sqlalchemy import (
Boolean, Column, Date, Enum, ForeignKey, Integer, Table, Unicode, sql,
)
from great.models.core import METADATA, table
from great.models._guid import GUID
def music_table(*args, **kwargs):
args += (
Column("mbid", GUID, nullable=True, unique=True),
Column("spotify_uri... |
# Import packages
import numpy as np
import os
import tensorflow as tf
import pathlib
from pathlib import Path
import model, vae_functions
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
############## NORMALIZATION OF IMAGES
# Value used for normalization
beta = 2.5
def norm(x, ba... |
"""Link function abstract base class."""
# author: Benjamin Cross
# email: btcross26@yahoo.com
# created: 2019-08-26
from abc import ABC, abstractmethod
import numpy as np
class BaseLink(ABC):
"""Abstract base class for link functions."""
def __call__(self, y: np.ndarray, inverse: bool = False) -> np.nda... |
#!/usr/bin/env python3
import time
def main(intervals, loopcount):
for i in (range(0, loopcount)):
for interval in intervals:
msg = interval['message']
dur = interval['length']
print(chr(7) + msg)
time.sleep(dur)
print("done!" + chr(7))
if __name__ ==... |
#!/usr/bin/env python
import os.path as op
from unittest import mock
import wx
import numpy as np
import fsl.data.image as fslimage
from fsl.utils.tempdir import tempdir
import fsleyes.plugins.tools.sampleline as sampleline
import fsleyes.plugins.profiles.samplelineprofile as samplelineprofile
import fsleyes.prof... |
from latex_dataset import *
CONTENT_TYPES = ['number', 'number_sized', 'label', 'long_text']
CONTENT_TYPES_P = [0.4, 0.3, 0.3, 0.0]
def gen_content_type():
return numpy.random.choice(CONTENT_TYPES, p=CONTENT_TYPES_P)
HEADER_CHILDREN_N = [2, 3]
HEADER_CHILDREN_N_P = [0.8, 0.2]
def gen_header_children_n():
ret... |
#!/usr/bin python3
"""
<Description of the programme>
Author: Pouria Hadjibagheri <pouria.hadjibagheri@phe.gov.uk>
Created: 13 Jul 2020
License: MIT
Contributors: Pouria Hadjibagheri
"""
# Imports
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Python:... |
import hcl_mlir
from hcl_mlir import GlobalInsertionPoint
from hcl_mlir.dialects import builtin
from hcl_mlir.dialects import hcl as hcl_d
from hcl_mlir.dialects import std
from hcl_mlir.ir import *
from ..devices import Device, DevMemoryPair
from .context import (ImperativeLoopDepth, ImperativeLoopNestCount,
... |
import os
import uuid
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.db import models
from django.dispatch import receiver
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django_celery_beat.models import Perio... |
from es_index.index_aliases import IndexAlias
officers_index_alias = IndexAlias('officers')
|
import fcntl
import os
from contextlib import closing
from contextlib import contextmanager
from errno import EBADF
from errno import EPERM
from threading import Lock
from contexter import Contexter
from ._libaepipe import ffi
from ._libaepipe import lib
if not hasattr(fcntl, "F_SETPIPE_SZ"):
import platform
... |
from collections import namedtuple
from unittest import TestCase
import os
import datetime as dt
from log_analyzer import find_latest_log, check_if_report_exists, make_report_table, render_html_report, parse_log, parse_config, parse_line
import logging
import sys
import json
import re
import gzip
default_config = {"RE... |
from itertools import islice
from typing import Iterable, Optional, Dict, List, Callable, Any
from thinc.api import Model, Config
from thinc.types import Floats2d
from ..language import Language
from ..training import Example, validate_examples, validate_get_examples
from ..errors import Errors
from ..scorer import S... |
import numpy as np
import pickle
from . import msa as msa
from . import mtss as m
from . import chipseq as c
import subprocess as sp
import os
from Bio import SeqIO
from scipy import stats
from scipy.cluster.hierarchy import dendrogram, linkage
from scipy.spatial.distance import pdist
from matplotlib impor... |
# -*- coding: utf-8 -*-
__author__ = 'lycheng'
__email__ = "lycheng997@gmail.com"
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
words = str.split(" ")
if len(pattern) != len(words):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 26 12:10:35 2018
@author: juanma
"""
# %%
import torch
import torch.nn as nn
import numpy as np
# %%
class SimpleRecurrentSurrogate(nn.Module):
"""Defines simple surrogate for MFAS using a single LSTM layer."""
def __init__(self, num_h... |
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import caffe
import numpy as np
import yaml
from fast_r... |
#!/usr/bin/env python3
"""Counting Fibonacci numbers without recursion"""
def fibonacci(n):
#returns a list of n Fibonacci numbers
array = [1, 1]
for i in range(2, n):
array.append(array[i-2] + array[i-1])
return array
def main():
userInput = ""
while not userInput.isdigit():
... |
# Copyright 2019-2020 by Wenfeng Gao, MGLAND animation studio. All rights reserved.
# This file is part of IUTest, and is released under the "MIT License Agreement".
# Please see the LICENSE file that should have been included as part of this package.
import unittest
import logging
import nose2
from iutest.core import... |
import asyncio
import os
from telethon import __version__
from userbot import ALIVE_NAME, TG_CHANNEL, TG_GRUP
from userbot.thunderconfig import Config
from userbot.utils import lightning_cmd
LIGHTNING_ALV_IMG = os.environ.get("LIGHTNING_ALV_IMG", None)
if not LIGHTNING_ALV_IMG:
LIGHTNING_ALV_IMG = "https://teleg... |
import logging
import click
from bentoml.exceptions import CLIException
from ..yatai_rest_api_client.yatai import YataiRESTApiClient
from ..yatai_rest_api_client.config import add_context
from ..yatai_rest_api_client.config import YataiClientContext
from ..yatai_rest_api_client.config import default_context_name
lo... |
import pytest
from charm import Operator
from ops.model import ActiveStatus, BlockedStatus, WaitingStatus
from ops.testing import Harness
@pytest.fixture
def harness():
return Harness(Operator)
def test_not_leader(harness):
harness.begin_with_initial_hooks()
assert harness.charm.model.unit.status == Wai... |
"""
This script calculates the stress for a multidimensional scaling calculation.
"""
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from signals.time_series_class import MixAr, AR
from signals.aux_functions import sidekick
from nexa.multidimensional_scaling import calculate_temporal_d... |
"""
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to
the top?
Examples
--------
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
... |
"""Unit tests for q0502.py."""
import unittest
from src.q0502 import fraction_to_binary_digits
class MyFractionToBinaryDigits(unittest.TestCase):
def test_0_and_1(self):
self.assertEqual(fraction_to_binary_digits(0), 'Error')
self.assertEqual(fraction_to_binary_digits(1), 'Error')
def test... |
import json
import os
from pathlib import Path
from textwrap import dedent
import numpy as np
import pandas as pd
from pdtable import BlockType, ParseFixer
from pdtable.io import json_data_to_table, table_to_json_data
from pdtable.io._json import to_json_serializable
from pdtable.io.parsers import parse_blocks
from p... |
import oauthlib.oauth
import simplejson
from auth import oauthapp
from const import SPORTS_API_URL
guid = oauthapp.token.yahoo_guid
url = SPORTS_API_URL + "/users;use_login=1/games/leagues"
print url
parameters = { 'format': 'json' }
request = oauthlib.oauth.OAuthRequest.from_consumer_and_token(
oauthapp.... |
import unittest
from smartystreets_python_sdk import Response
from smartystreets_python_sdk.exceptions import UnprocessableEntityError
from smartystreets_python_sdk.international_street import Lookup, Client, language_mode, Candidate
from test.mocks import *
class TestClient(unittest.TestCase):
def test_sending_... |
import matplotlib.pyplot as plt
import discord
import os
import psutil
import json
import urllib.request
TOKEN = 'NTUwODU1MTUxODkyNjkyOTky.D1ovfA._13Nmqjkh01I_Q9b8I_wPX9mtBA'
client = discord.Client()
directory = "D:\servers\sapphire\isle"
playersDir = 'D:\servers\sapphire\isle\TheIsle\Saved\Databases\Survival\Players... |
import re
# 'p' is pattern object
# pattern objects have several methods and attributes
# Method/Attribute Purpose
# match() Determine if the RE matches at the beginning of the string.
# search() Scan through a string, looking for any location where this RE matches.
# findall() Find all substrings where the RE ... |
# Copyright 2020 by Aaron Baker.
# All rights reserved.
# This file is part of the Nightcap Project,
# and is released under the "MIT License Agreement". Please see the LICENSE
# file that should have been included as part of this package.
# region Imports
import os
import platform
# endregion
class ScreenHelper(obj... |
default_app_config = 'wagtailcommerce.dashboard.apps.DashboardAppConfig'
|
def BRGC_gen(n: int):
"""Binary Reflected Gray Code
Args:
n (int): [description]
Yields:
[type]: [description]
"""
if n == 1:
yield 0
return
yield from BRGC_gen(n - 1)
yield n - 1
yield from BRGC_gen(n - 1)
def BRGC(n: int):
"""Binary Reflected Gra... |
import json
import sys
import requests
import sconfig
device_id = sconfig.config_section("particle-credentials")["device-id"]
oauth = sconfig.config_section("particle-credentials")["oauth-token"]
def set_temp(web_temp):
uri="https://api.particle.io/v1/devices/" + device_id + "/setTemp"
headers = {'authorizat... |
class Space(object):
"""A location that is designated for parking
attributes: space id, vehicle
methods: get_vehicle, get_spaceid, park, unpark"""
def __init__(self, spaceid):
self._spaceid = spaceid
self._vehicle = None
""" Property to get the parking space's vehicle details """
... |
# Given a string, find the length of the longest substring without repeating
# characters.
#
# Input: "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
#
# Input: "bbbbb"
# Output: 1
# Explanation: The answer is "b", with the length of 1.
#
# Input: "pwwkew" Output: 3 Explanation: The ans... |
import torch
import torch.nn as nn
from torch.nn.functional import softmax
from torch.distributions import Categorical
import logging
import numpy as np
from crowd_nav.policy.cadrl import mlp
from crowd_nav.policy.multi_human_rl import MultiHumanRL
from crowd_sim.envs.utils.action import ActionRot, ActionXY
class Va... |
import cv2
import pandas as pd
import pathlib
import torch
import dill
from sklearn import model_selection
from rabbitccs.data.transforms import estimate_mean_std
def build_meta_from_files(base_path, phase='train'):
"""
Creates a dataframe from the input and target images.
For 2D data, base path should l... |
# using trf MCMC method to generate word sequences
import tensorflow as tf
import os
import json
import time
from copy import deepcopy
from collections import OrderedDict
from base import *
from lm import *
from . import trfnce
from . import pot
from .trfnce import DefaultOps
class Config(trfnce.Config):
def __... |
from td_db_client import Client
import pandas as pd
import datetime
import time
tdc = Client()
symbol = 'AAPL'
query_stocks = "SELECT stock.id, stock.symbol FROM stock WHERE stock.sector IN ('Technology', 'Health Care') AND stock.id NOT IN (SELECT DISTINCT stock_id FROM ohlc_data) AND symbol NOT SIMILAR TO %s"
# Ge... |
from __future__ import annotations
from typing import Any
class Iterator:
"""
The iterator for smart contracts.
"""
@property
def value(self) -> Any:
"""
Gets the element in the collection at the current position of the iterator.
:return: the element in the collection at... |
from setuptools import setup
setup(
name="eshop_catalog_service",
author="shaik khaja ibrahim",
license="Apache License",
version="1.0.0",
description="This project is a catalog service in an ecommerce application",
author_email="qtkhajacloud@gmail.com",
) |
from recommonmark.transform import AutoStructify
from kottos.version import __version__
# Sphinx Base --------------------------------------------------------------------------
# Extensions
extensions = [
# http://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html
"sphinx.ext.autodoc",
# http://ww... |
from .clf_models import Pretrained
from .seg import Res34Unetv3, Res34Unetv4, Res34Unetv5, ResNet34FPN
|
from TensorMol import GeomOptimizer, Mol, PARAMS
def main(manager, molecule, emit_callback=None):
"""main."""
if (hasattr(manager, 'get_energy_force_function')):
energy_force_function = manager.get_energy_force_function(molecule)
else:
def energy_force_function(x_, do_force=True):
... |
import urandom
def randxy(size):
(width, height) = size
return (urandom.randint(0, width), urandom.randint(0, height))
def randcolor():
if urandom.random() < 0.75:
return (urandom.randint(0, 255), urandom.randint(0, 255), urandom.randint(0, 255))
else:
return (0, 0, 0)
def randstate... |
import re
if __name__ == '__main__':
sentences = ""
for _ in range(int(input())):
sentences += input()
for _ in range(int(input())):
s = input()
s = s[:len(s)-2] + '[sz]e'
print(len(re.findall(s, sentences)))
|
"""TTFQuery font registry with a few VRML-specific methods"""
from ttfquery import ttffiles, describe
import re
ITALICS_FINDER = re.compile( '(italic[s]?)$', re.IGNORECASE )
class TTFRegistry( ttffiles.Registry ):
"""Minor specialisation to provide VRML97 fontstyle matching"""
defaultFontNames = {}
# data... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
from .get_events.trigger import GetEvents
|
"""
To avoid circular import issues, do not import modules from this directory
UNLESS they are marked as safe below.
Instead, import `lib` and utilize `lib.{module}`
Safe Modules:
errors
exceptions
utils
"""
|
# -*- coding: utf-8 -*-
import re
from yelp_uri import RFC3986
from .tlds.all import all_tlds
from .tlds.common import common_tlds
def create_url_regex(rfc3986, tlds):
# A regex for finding urls in free-form text.
# This regex is space-indented, so that it looks OK on ReviewBoard
#
# the following re... |
import nose
import os
nose.config.Config.srcDirs = (os.getcwd())
nose.run(argv=["","test/librarian/Book.py"])
|
import hashlib
from abc import abstractmethod
class Backend:
@abstractmethod
def read_contextmanager(self, name, checksum_sha256=None):
"""
Returns a context manager, that when entered, should return a file-like object that can be
read to get the data.
It is possible to enter ... |
import logging
import os
import cmd
import repo_config
import workflow_step_terraform
def run(state, config):
original_config = config
config = original_config.copy()
config['args'] = ['init']
config['output_key'] = 'init'
(failed, state) = workflow_step_terraform.run(state, config)
if faile... |
from collections import OrderedDict
from django.db import models
from .managers import BookManager
from .services import get_book_average_ratting_by_isbn
class Cover(models.Model):
TYPE_CHOICES = (
('File', 'Arquivo'),
(None, 'Selecione um tipo')
)
type = models.CharField(max_length=2... |
# Por defecto
from django.shortcuts import render
# Llamamos a los metodos por HHTPS
from django.http import HttpResponse
from django.contrib.auth import logout as do_logout
from django.shortcuts import render, redirect
# Llamamos las funciones de util
from usuarios.util import *
from board.util import set_error_user
... |
import justpy as jp
from .element import Element
class Link(Element):
def __init__(self,
text: str = '',
href: str = '#',
):
view = jp.A(text=text, href=href, classes='underline text-blue')
super().__init__(view)
|
import numpy as np
from abc import ABC, abstractmethod
from pybn.functions import plogp
from pybn.networks import FuzzyBooleanNetwork
####################################################################################################
####################################################################################... |
# unit test for constituent_gates.py
from src.tree_support import constituent_gates
import pytest
# exception handling
# arrange
type_error_msg = "only integer inputs are accepted."
value_error_msg = "input cannot be less than or equal to zero."
def test_type_error():
'''when number is negative - number is not co... |
import itertools
class Utils:
EMPTY = 0
BLOCKED = True
ROW = 0
COLUMN = 1
@staticmethod
def get_numbers_in_small_blocks(blocks, max_size):
"""Get a set of all numbers contained in blocks smaller than max_size."""
small_blocks = [block for block in blocks if len(block) < max_si... |
from dolfin import *
from xii import *
f = Expression(('x[0]', '2*x[1]', '2*x[2]-x[0]'), degree=1)
mesh = UnitCubeMesh(4, 4, 4)
facet_f = MeshFunction('size_t', mesh, 2, 0)
DomainBoundary().mark(facet_f, 1)
n = FacetNormal(mesh)
true = assemble(inner(n, f)*ds)
surface_mesh = EmbeddedMesh(facet_f, 1)
n = OuterNormal... |
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from scrapy.http import HtmlResponse
from l... |
# coding: utf-8
"""
tweak-api
Tweak API to integrate with all the Tweak services. You can find out more about Tweak at <a href='https://www.tweak.com'>https://www.tweak.com</a>, #tweak.
OpenAPI spec version: 1.0.8-beta.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
... |
""" elt Calculator
ELT calculator functions
"""
import numpy
import math
import pandas as pd
import numpy as np
from scipy.fft import fft, ifft
from scipy.stats import beta
from aggregationtools import ELT, ep_curve
def calculate_oep_curve(elt, grid_size=2**14, max_loss_factor=5):
""" This function calculates the... |
import fast_com
import arrow
class FastLog(object):
results = {
"download": None,
"upload": None,
"ping": None,
"timestamp": None,
"sponsor": None,
}
def execute(self):
""" run the actual speed test """
result = fast_com.fast_com()
self.pars... |
from enum import Enum
RESOLUTION = 16, 9
BAR_WIDTH = SCREEN_WIDTH = 800
SCREEN_HEIGHT = 450
SCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT
BAR_HEIGHT = 100
AVAILABLE_SCREEN_HEIGHT = SCREEN_HEIGHT - BAR_HEIGHT
TICK = 15
BLOCK_SIZE = 50
CHAR_SIZE = 20
CHAR_MARGIN = 15
class Directions(Enum):
UP = 0
LEFT = 90
... |
m=int(raw_input())
l=[{int(i): j+1} for j, i in enumerate(raw_input().split())]
def traverse(traversed, address):
if traversed == len(l) - m:
return l[address].keys()[0]
else:
try:
traversed += 1
address = l[address].values()[0]
return traverse(traversed, address)
except:
return 'NIL'
print tra... |
class Field:
def __init__(self):
self.name = None
def get_type(self):
return self.name.upper()
class IntegerField(Field):
def __init__(self):
super(IntegerField, self).__init__()
self.name = 'Integer'
class RealField(Field):
def __init__(self):
super(RealFiel... |
# -*- encoding: utf-8 -*-
"""
Created by eniocc at 11/10/2020
"""
import ctypes
from py_dss_interface.models import Bridge
from py_dss_interface.models.Base import Base
class ParserV(Base):
"""
This interface can be used to read/write certain properties of the active DSS object.
The structure of the in... |
'''This package contains step implementations that only is allowed in the `Background` section in a `Feature`.
The feature will fail if they are added into any other section.
'''
# flake8: noqa: F401,F403
from .shapes import *
from .setup import *
|
from colorama import Fore, Back, Style
#print(Fore.RED + 'some red text')
#print(Back.GREEN + 'and with a green background')
#print(Style.DIM + 'and in dim text')
#print(Style.RESET_ALL)
#print('back to normal now')
import os
import pyttsx3
import sys
import platform
def say_stuff(stuff_to_say):
engine = pyttsx3.in... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
import logging
import warnings
import unittest
import mock
import copy
import datetime
import xml.etree.cElementTree as ET
import StringIO
import requests
import httplib
import solrcl
class TestSolrlibSOLRDocumentBase(unittest.TestCase):
def setUp(self):
#Se... |
# required libraries
import pandas as pd
from lightgbm import LGBMRegressor
import xgboost as XGB
from countvec import countvec_matrix_train, countvec_matrix_test, train_df
# dependent features
y = train_df['Match Percentage']
# XGBoost model
xgb = XGB.XGBRegressor(learning_rate=0.3,
n_estimat... |
import asyncio
from unittest import TestCase
from piccolo.utils.sync import run_sync
class TestSync(TestCase):
def test_sync_simple(self):
"""
Test calling a simple coroutine.
"""
run_sync(asyncio.sleep(0.1))
def test_sync_nested(self):
"""
Test calling a coro... |
from django.db.models import Avg, Count, Sum, Q, F, Max, Min
from django.http import HttpResponse
# Create your views here.
from student.models import Score, Student, Teacher, Course
def index1(request):
rows = Student.objects.annotate(avg=Avg("score__number")).values('id', 'name', 'avg')
for row in rows:
... |
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
from datetime import datetime, timedelta
from .analysis import polyfit
from .datafetcher import fetch_measure_levels
from .stationdata import build_station_list
def plot_water_levels(station, dates, levels):
"""Plot the water level for a station... |
import cv2
import torch
import numpy as np
def roi_transform(feature, box, size=(32, 180)):
resize_h, resize_w = size
x1, y1, x2, y2, x3, y3, x4, y4 = box
# rotated_rect = cv2.minAreaRect(np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]]))
# box_w, box_h = rotated_rect[1][0], rotated_rect[1][1]
w... |
# Copyright (c) 2014 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.3 on 2018-02-18 02:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0021_remove_element_eid'),
]
operations = [
migrations.AddField(
... |
import io
import requests
from embeddingutils.transforms import Segmentation2AffinitiesWithPadding
from glob import glob
import h5py
from imgaug import augmenters as iaa
import imgaug as ia
from imgaug.augmentables.segmaps import SegmentationMapsOnImage
import numpy as np
import skimage
import torch
from torch.utils.d... |
from pyFHE.trgsw import Decomposition
from pyFHE.trlwe import trlweSymEncrypt, trlweSymDecrypt
from pyFHE.key import SecretKey
from pyFHE.utils import dtot32
import numpy as np
for i in range(1000):
sk = SecretKey(500, 2 ** (-7), 1024, 2, 10, 3.73e-9, 8, 2, 2.43e-5)
p = np.random.randint(0, 2, size=sk.params.N... |
"""Philips Hue sensors platform tests."""
import asyncio
from unittest.mock import Mock
import aiohue
from homeassistant.components.hue.hue_event import CONF_HUE_EVENT
from .conftest import create_mock_bridge, setup_bridge_for_sensors as setup_bridge
from tests.common import async_capture_events
PRESENCE_SENSOR_1_... |
# Generated by Django 2.0.2 on 2018-02-27 09:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base', '0009_box'),
]
operations = [
migrations.RemoveField(
model_name='box',
name='user',
),
migra... |
# Map coordinates of the Brazilian cities in the dataset.
coords = {
"Belem": {"lat": -1.4, "lon": -48.49},
"Curitiba": {"lat": -25.42, "lon": -49.26},
"Fortaleza": {"lat": -3.73, "lon": -38.52},
"Goiania": {"lat": -16.68, "lon": -49.26},
"Macapa": {"lat": -0.04, "lon": -51.07},
"Manaus":... |
#!/usr/bin python3
""" Face and landmarks detection for faceswap.py """
from lib import face_alignment
import numpy as np
# Static variable wrapper
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
def compute... |
def system_selector():
pass
def subsystem_selector():
pass
def project_selector():
pass
|
# -*- coding: ascii -*-
#
# Copyright 2007-2012
# Andr\xe9 Malo or his licensors, as applicable
#
# 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-... |
"""
This code is modified from harveyslash's work (https://github.com/harveyslash/Deep-Image-Analogy-PyTorch)
"""
import mxnet as mx
from mxnet.gluon.model_zoo import vision as models
from mxnet.gluon import nn
from mxnet import nd
from mxnet import autograd
from time import time
from mxnet import optimizer
import sys... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 16:37:39 2020
@author: wjwesselink
"""
# Imports.
import sys
import stepfinder#lcapy.stepfinder
import matplotlib.pyplot as plt
import numpy as np
from file import parse_xml_table, create_xml_table
from stepfinder import find_steps, running_mean
#%%
###################... |
import json
import os
HOME = os.environ['HOME']
# read in connection profiles for both orgs
with open(os.path.join(HOME, 'creds/org1ConnectionProfile.json'), 'r') as f:
org1CP = json.load(f)
with open(os.path.join(HOME, 'creds/org2ConnectionProfile.json'), 'r') as f:
org2CP = json.load(f)
# read in PTE templ... |
#! /usr/bin/env python3
# -*-coding:utf-8-*-
import pika
class RabbitMqMessageHandler:
def __init__(self):
pass
@staticmethod
def sent_message(host, queue_name, routing_key_name, message_content, exchange_name=""):
connection = pika.BlockingConnection(pika.ConnectionParameters(host))
... |
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import unittest
import sys
import os
import asn1crypto
from oscrypto import keys
from .unittest_data import data_decorator, data
from ._unittest_compat import patch
patch()
if sys.version_info < (3,):
byte_cls = ... |
import itertools
import random
from ...layouts import GridRooms, LineRooms
from ...playground import PlaygroundRegister
from ....common.position_utils import CoordinateSampler
from ....elements.collection.activable import Lock, Dispenser, VendingMachine
from ....elements.collection.contact import Candy
from ....elemen... |
import asyncio
import pytest
from aiohttp import web
from site_monitor.checker import check_urls
async def respond_hello(request):
return web.Response(text='hello')
async def check_result(unused_tcp_port, server_respond, check_regexp, test_func):
server = web.Application()
server.add_routes([web.get('/'... |
class Solution:
def isValid(self, s: str) -> bool:
stack = deque()
for c in s:
if c == '(' or c == '{' or c == '[':
stack.append(c)
elif c == ')':
if not stack or stack[-1] != '(':
return False
else:
... |
# Steps required:
# 1. Get current installed version
# 2. Get latest release
# 3. Download latest version
# 4. Stop running server
# 5. Backup old teamspeak folder
# 6. Unpack new teamspeak
# 7. Start server
# 8. Check if server is running (optional)
import bs4
import os
import re
import requests
VERSION_REGEX = re.co... |
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from xgboost_ray.xgb import xgboost as xgb
try:
from xgboost.callback import TrainingCallback
LEGACY_CALLBACK = False
except ImportError:
class TrainingCallback:
def __init__(self):
if hasattr(self, "before_iteration"):
... |
# InitClass.py is used to
import gc
import os
import sys
import time
from arm_ds.debugger_v1 import Debugger
from arm_ds.debugger_v1 import DebugException
import config
import memory
import mmu
from DexParser import header_item, string_id_item, type_id_item, proto_id_item, method_id_item, encoded_catch... |
from refactor.representation.TILDE_query import TILDEQuery
class QueryWrapper:
def __init__(self, tilde_query: TILDEQuery, external_representation):
self.tilde_query = tilde_query
self.external_representation = external_representation |
from simpleai.search import (
SearchProblem,
breadth_first,
depth_first,
uniform_cost,
greedy,
astar
)
from simpleai.search.viewers import WebViewer, BaseViewer, ConsoleViewer
from itertools import combinations
GRID = [(r,c) for r in range(7) for c in range(6)]
ROADS = []
RACKS = [(0,0),(1,0),(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.