content stringlengths 5 1.05M |
|---|
# TODO: Show runs with command line option
# TODO: Let user customize root template
# TODO: Add unit tests
import json
from invisibleroads_macros_disk import is_path_in_folder, make_random_folder
from itertools import count
from logging import getLogger
from os.path import basename, exists, join, splitext
from pyramid.... |
'''
Created on May 6, 2017
This file is subject to the terms and conditions defined in the
file 'LICENSE.txt', which is part of this source code package.
@author: David Moss
'''
from devices.device import Device
class SirenDevice(Device):
"""
Siren
"""
def __init__(self, botengine, device_id, devic... |
from .training_runtime_controller import router as TrainingRuntimeEnvironmentController
from .training_runtime_service import TrainingRuntimeService
|
import pytest
from credsweeper.filters import ValueAllowlistCheck
from tests.test_utils.dummy_line_data import get_line_data
class TestValueAllowlistCheck:
def test_value_allowlist_check_p(self, file_path: pytest.fixture, success_line: pytest.fixture) -> None:
line_data = get_line_data(file_path, line=s... |
from dsbox.template.template import DSBoxTemplate
from d3m.metadata.problem import TaskKeyword
from dsbox.template.template_steps import TemplateSteps
from dsbox.schema import SpecializedProblem
import typing
import numpy as np # type: ignore
class MuxinTA1ClassificationTemplate1(DSBoxTemplate):
def __init__... |
class A:
@classmethod
def test(cls, param):
return None
class B(A):
@classmethod
def test(cls, param):
if param == 1:
return 1
raise NotImplementedError
class C(B):
pass |
# Eugene Tin
# TP061195
# ASIA PACIFIC UNIVERSITY OF TECHNOLOGY AND INNOVATION
# GITHUB REPO https://github.com/EuJin03/SCRS_APU
# Chia Wen Xuen
# TP061184
# ASIA PACIFIC UNIVERSITY OF TECHNOLOGY AND INNOVATION
# Copyright (C) 2021 SCRS_APU Open Source Project
# Licensed under the MIT License
# you may not use this... |
# coding: utf_8
import keras
from keras_retinanet import models
from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image
from keras_retinanet.utils.visualization import draw_box, draw_caption
from keras_retinanet.utils.colors import label_color
import matplotlib.pyplot as plt
import cv2
... |
class TFTFarmingCalculator:
def __init__(self, node_id, node_config, threefold_explorer ):
self.threefold_explorer = threefold_explorer
#configuration as used for the node
self.node_config = node_config
#unique node id in the TFGrid
self.node_id = node_id
@property
... |
"""Utility functions."""
import networkx as nx
class Utility(object):
"""Base class for all utility functions."""
def __init__(self):
pass
def utility_of_relation(self, model, r, v):
pass
def utility_of_substitution(self, s):
pass
def best(self):
pass
def ... |
import errno
import os
def create_file_if_needed(file_name):
"""
Create a specified file if it doesn't exist
:param file_name: The file to check and create
"""
if not os.path.exists(os.path.dirname(file_name)):
try:
os.makedirs(os.path.dirname(file_name))
except OSError... |
from unittest import TestCase
from regene.expression.character_class import CharacterClassFactory
class TestCharacterSet(TestCase):
def test_only_characters(self):
assert str(CharacterClassFactory.get("[abcde]")) == "a"
def test_a_single_range(self):
assert str(CharacterClassFactory.get("[0-6... |
# Copyright (c) Nanjing University, Vision Lab.
# Last update: 2019.10.04
import tensorflow as tf
import numpy as np
import h5py
tf.enable_eager_execution()
# def select_voxels(vols, points_nums, offset_ratio=1.0, init_thres=-1.0):
# '''Select the top k voxels and generate the mask.
# input: vols: [batch_siz... |
# 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
# distrib... |
import subprocess # noqa: F401
import pytest
from pandas.io.formats.console import detect_console_encoding
from pandas.io.formats.terminal import _get_terminal_size_tput
class MockEncoding(object): # TODO(py27): replace with mock
"""
Used to add a side effect when accessing the 'encoding' property. If the... |
import os
import yoloCarAccident as yc
# yc.find('test.txt')
f1 = open('result2.txt','r')
i = 0
s = ""
for lines in f1:
if(i<80000):
s += lines
i+=1
else:
f2 = open('test.txt','w')
f2.write(s)
f2.close()
try:
yc.find('test.txt')
except ValueError:
pass
s = ""
i = 0
# break
# f2 = open('t... |
# Copyright (c) 2007, Simon Edwards <simon@simonzone.com>
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
import sys
import distutils.sysconfig
print("exec_prefix:%s" % sys.exec_prefix)
print("short_version:%s" % sys.versio... |
" Implementations of Reaction Network Pathway "
|
"""
SystemctlShow - command ``systemctl show``
==========================================
Parsers included in this module are:
SystemctlShowServiceAll - command ``systemctl show *.service``
--------------------------------------------------------------
Parsers the output of `systemctl show *.service` against all serv... |
from fastapi import APIRouter, Depends
from starlette.responses import JSONResponse
router = APIRouter()
@router.get(
"",
summary="Health Check",
tags=["Health Check"],
)
async def healthCheck():
return JSONResponse(status_code=200, content={
"status_code": 200,
"m... |
from celery.schedules import crontab
CELERY_ACKS_LATE = True
CELERYD_PREFETCH_MULTIPLIER = 1
CELERY_IMPORTS = ('openpds.questions.tasks',"openpds.questions.socialhealth_tasks", "openpds.questions.places_tasks", "openpds.meetup.tasks", "openpds.questions.probedatavisualization_tasks", "openpds.questions.mitfit_tasks",... |
# Copyright 2020 The TensorFlow 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 applica... |
from conans import ConanFile, CMake, tools
import os, subprocess
class HelloTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "virtualrunenv"
requires = "ghc/8.10.1"
def build(self):
currentDirectory = os.path.dirname(os.path.realpath(__file__))
sel... |
import os
import sys
import string
from PyQt5 import QtCore
self = sys.modules[__name__]
self._path = os.path.dirname(__file__)
self._current_task = None
class FormatDict(dict):
def __missing__(self, key):
return "{" + key + "}"
def resource(*path):
path = os.path.join(self._path, "res", *path)
... |
# import the necessary packages
import numpy as np
import base64
import sys
import cv2
def base64_encode_image(a):
# base64 encode the input NumPy array
return base64.b64encode(a)
def base64_decode_image(a,h):
img_ = base64.b64decode(a)
img = np.frombuffer(img_, dtype=np.uint8)
img= np.reshape(img,(-1,h,3))
ret... |
import bcrypt
def encrypt_password(password: str) -> str:
"""
Encryption on a password
:param password: the password to encrypt
:return: the hashed password
"""
return bcrypt.hashpw(password.encode("utf8"),
bcrypt.gensalt()).decode("utf8")
def decrypt_password(passwo... |
# Copyright 2019 Cortex Labs, 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 wri... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import pkg_resources
from cryptography.hazmat.backends.multibackend impo... |
#
# Copyright 2017 , UT-Battelle, LLC
# All rights reserved
# [Home Assistant- VOLTTRON Integration, Version 1.0]
# OPEN SOURCE LICENSE (Permissive)
#
# Subject to the conditions of this License, UT-Battelle, LLC (the “Licensor”)
# hereby grants, free of charge, to any person (the “Licensee”) obtaining a copy
# of th... |
# Global settings for photologue example project.
import os
DEBUG = TEMPLATE_DEBUG = True
# Top level folder - the one created by the startproject command.
TOP_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
ADMINS = ()
MANAGERS = ADMINS
# Default dev database is Sqlite. In production I us... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 13:47:01 2019
@author: abibeka
Read data from travel time files
"""
#0.0 Housekeeping. Clear variable space
from IPython import get_ipython #run magic commands
ipython = get_ipython()
ipython.magic("reset -f")
ipython = get_ipython()
import os
import pandas as pd
... |
#Compound Selection Behavior
#https://kivy.org/docs/api-kivy.uix.behaviors.compoundselection.html
from kivy.uix.behaviors.compoundselection import CompoundSelectionBehavior
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.core.window i... |
# -*- coding: utf-8 -*-
# Simulate standards and thin film specimens of ZnO on Si for
# measuring K-ratios for thin film measurement.
#
# For 500 trajectories at 4 kV:
# This script required 1.248 min
# Elapse: 0:01:14.9
#
# For 50000 trajectories at 4kV:
# This script required 144.035 min
# ...or 2.401 hr
# Elapse: 2... |
"""See https://docs.python.org/3/library/unittest.html#assert-methods
for more information about 'unittest' framework.
"""
import unittest
class TestEmptyCM(unittest.TestCase):
"""Class with all the unit test made on the CM."""
def test_data(self):
"""Function performing a unit test."""
pass
... |
""" Helper functions for the test suite
"""
# Standard library imports
import json
import sys
# Local imports
from spotifython.album import Album
from spotifython.artist import Artist
from spotifython.playlist import Playlist
from spotifython.track import Track
from spotifython.user import User
#pylint: disable=wron... |
## Sid Meier's Civilization 4
from CvPythonExtensions import *
import CvUtil
import ScreenInput
import CvScreenEnums
import math
# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()
class TechTree:
"Creates Tech Tree"
def __init__ (self):
self.dIsRequiredPrereqFor... |
import torch
import torch.onnx
import torchvision.models as models
from torch import nn
from torch.autograd import Variable
from resnet import resnet18
from vgg import vgg16_bn
import onnx as nx
def main():
device = torch.device('cpu')
model = vgg16_bn()
# PATH = 'weights/resnet18_acc_89.078.pt'
PATH ... |
import pandas as pd
import numpy as np
import math
import os, sys
import random
import tensorflow as tf
from sklearn.model_selection import train_test_split
import dataset_utils
tf.logging.set_verbosity(tf.logging.INFO)
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('output_dir',
... |
#!python3
import os, sys
import queue
import shlex
import threading
import time
import zmq
from . import config
from . import logging
log = logging.logger(__package__)
from . import outputs
class RobotError(BaseException): pass
class NoSuchActionError(RobotError): pass
class Robot(object):
def __init__(
... |
#!/usr/bin/env python3
import re
from reporter.connections import RedcapInstance
from reporter.emailing import (
RECIPIENT_CVLPRIT_ADMIN as RECIPIENT_ADMIN,
RECIPIENT_CVLPRIT_MANAGER as RECIPIENT_MANAGER,
)
from reporter.application_abstract_reports.redcap.data_quality import (
RedcapFieldMatchesR... |
"""Unit tests for numbering.py."""
import itertools
import unittest
import pmix.numbering as numbering
class NumberingFormatTest(unittest.TestCase):
"""Test the string format for fixed numberings."""
def match_re(self, prog, expr, match):
found = prog.match(expr)
if match:
msg =... |
from base import InternedCollection
from base import InternedNamedCollection
from chat import ChatServer
from .discordchatchannel import DiscordChatChannel
from .discorduser import DiscordUser
class DiscordPrivateMessagingServer(ChatServer):
def __init__(self, chatService, client):
super(DiscordPrivateMess... |
from .api_resource import ApiResource
from .defaults import * # flake8: noqa
class ReportType(object):
IdentityReport = "identity"
DocumentReport = "document"
EmploymentReport = "employment"
EducationReport = "education"
NegativeMediaReport = "negative_media"
DirectorshipReport = "directorship"... |
"""An unofficial Python wrapper for coinzo exchange Rest API
.. moduleauthor:: tolgamorf
"""
name = "coinzo"
|
from lib.Evaluator_line import *
from lib.utils import *
import matplotlib.pyplot as plt
import os
import numpy as np
import scipy.io as sio
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy import interpolate
import sys
mpl.rcParams.update({"font.size": 12})
plt.rcParams["font.family"] = "Times New... |
import bokeh.io
import bokeh_garden
import bokeh.models.sources
from bokeh.models import Div
import logging
class LoggingBG(bokeh_garden.application.AppWidget, bokeh.models.layouts.Column):
def __init__(self, app, **kw):
self._app = app
self._records = ''
self._queue = []
self._l... |
# -*- coding: utf-8 -*-
from torch import optim
from torch import tensor,save
from torch import cuda
from torch.nn.utils import clip_grad_value_
from dataloader import read_data,DataLoader,load_init
from cdkt import CDKT
use_cuda = True
if use_cuda:
cuda.empty_cache()
""" training mode"""
resul... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-06-17 08:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_cowhite_blog', '0001_initial'),
]
operations = [
migrations.AddFiel... |
"""Plotting utilities."""
import networkx as nx
import matplotlib.pyplot as plt
from .nodes import Node
def _get_node_colors(nodes, path, colors):
"""For each node, assign color based on membership in path."""
node_colors = []
for x in nodes:
if x in path:
node_colors.append(colors['a... |
#!/usr/bin/env python
# Copyright 2008-2014 Nokia Solutions and Networks
#
# 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 r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys, os, platform, argparse
from datetime import datetime
from util import util
# gestion des options en ligne de commande
parser = argparse.ArgumentParser (description=u'Interface Imagine - broker MQTT')
group = parser.add_ar... |
import random
def random_hash(length=64) -> str:
return "".join(random.choice("0123456789abcdef") for i in range(length))
|
"""Holds documentation for the bot in dict form."""
def help_book(p):
return [
# Table of Contents
{
"title": "Table of Contents",
"description": f"Navigate between pages with the reaction buttons",
"1. Vibrant Tutorial": ["Learn how to use the bot and its comma... |
from django.conf.urls.defaults import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'pyclass.views.index'),
url(r... |
from cloudify.manager import get_rest_client
from cloudify.workflows import ctx, parameters
instance = next(ctx.node_instances)
instance.execute_operation('custom_lifecycle.custom_operation',
kwargs={'update_id': parameters.update_id})
rest_client = get_rest_client()
rest_client.deployment... |
"""Posts forms"""
# Django
from django import forms
# Models
from posts.models import Post
class PostForm(forms.ModelForm):
"""Post model form"""
class Meta:
"""Form settings."""
model = Post
fields = ('profile', 'title', 'photo')
|
from ....cost.redshift_common import RedshiftPerformanceIterator
def test_init():
rpi = RedshiftPerformanceIterator()
assert True # no exception
from moto import mock_redshift
@mock_redshift
def test_iterateCore_none(mocker):
# mock the get regions part
mockreturn = lambda service: ['us-east-1']
mockee = ... |
#!/usr/bin/env python
"""
================================================
ABElectronics Expander Pi | RTC memory integer demo
Requires python smbus to be installed
For Python 2 install with: sudo apt-get install python-smbus
For Python 3 install with: sudo apt-get install python3-smbus
run with: python demo_rtcmemo... |
import dash
from dash.dependencies import Input, Output, State, ALL, MATCH
import dash_html_components as html
import dash_core_components as dcc
import plotly.express as px
import yfinance as yf
df = px.data.gapminder()
app = dash.Dash(__name__)
app.layout = html.Div([
html.Div(children=[
dcc.Dropdown(
... |
import m2
import subpkg.m3
print(m2, subpkg.m3.VAR)
|
"""
Code adapted from Dan Krause.
https://gist.github.com/dankrause/6000248
http://github.com/dankrause
"""
import socket
from http.client import HTTPResponse
from io import BytesIO
ST_DIAL = 'urn:dial-multiscreen-org:service:dial:1'
ST_ECP = 'roku:ecp'
class _FakeSocket(BytesIO):
def makefile(self, *args, **kw)... |
import random
from src.base.globalmaptiles import GlobalMercator
class UrlBuilder:
def __init__(self, zoom_level=19):
self._url_first_part = 'https://t'
self._url_second_part = '.ssl.ak.tiles.virtualearth.net/tiles/a'
self._url_last_part = '.jpeg?g=4401&n=z'
self._zoom_level = zoo... |
#!/usr/bin/env python3
"""Train a model to classify herbarium traits."""
import argparse
import textwrap
from pathlib import Path
from pylib import db
from pylib import model_util as mu
from pylib.const import ALL_TRAITS
from pylib.herbarium_model import BACKBONES
from pylib.herbarium_model import HerbariumModel
from ... |
""" This module defines the class QueryHMDBTimestamp.
It is written to get the release date of HMDB Database.
http://www.hmdb.ca/release-notes
"""
__author__ = ""
__copyright__ = ""
__credits__ = ['Deqing Qu', 'Stephen Ramsey']
__license__ = ""
__version__ = ""
__maintainer__ = ""
__email__ = ""
__status__ = "Prototy... |
#!/usr/bin/env python
""" test_aes_cmac.py
Tests for AES CMAC from NIST 800-38B
References:
RFC 4493 - http://www.rfc-editor.org/rfc/rfc4493.txt
NIST - http://csrc.nist.gov/publications/nistpubs/800-38B/Updated_CMAC_Examples.pdf
test_aes_cmac.py(c) 2015 by Paul A. Lam... |
#!/usr/bin/python
#
# Copyright 2020 Google 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
# Authors: Sylvain MARIE <sylvain.marie@se.com>
# + All contributors to <https://github.com/smarie/python-m5p>
#
# License: 3-clause BSD, <https://github.com/smarie/python-m5p/blob/main/LICENSE>
from m5py.main import M5Prime
from m5py.export import export_text_m5
try:
# -- Distribution mode --
# ... |
import pytest
from tokki.abc import Client, Project, Repo
AGENT = "Tests for Tokki +(https://github.com/ChomusukeBot/Tokki)"
@pytest.mark.asyncio
async def test_no_agent():
with pytest.raises(TypeError, match=r": 'useragent'"):
Client()
@pytest.mark.asyncio
async def test_rest():
client = Client(AG... |
from gdsfactory.component import Component, ComponentReference
try:
import dphox as dp
DPHOX_IMPORTED = True
except ImportError:
DPHOX_IMPORTED = False
def from_dphox(device: "dp.Device", foundry: "dp.foundry.Foundry") -> Component:
"""Converts a Dphox Device into a gdsfactory Component.
Note t... |
import argparse
import numpy as np
import matplotlib.pyplot as plt
from auto_utils import (
get_kw_count,
get_word_count,
load_keywords,
get_wset,
get_wlen,
get_wfreq,
CAP,
CUP,
arrange_into_freq_bins,
)
PRE = "/home/santosh/tools/kaldi/egs/indic/"
PATHS = {
"tel": [
"te... |
import scrypt
from typing import Union
class ArgumentError(Exception):
pass
def generate_digest(message: str,
password: str = None,
maxtime: Union[float, int] = 0.5,
salt: str = "",
length: int = 64) -> bytes:
"""Multi-arity fu... |
try:
from importlib_resources import files
except ImportError:
from importlib.resources import files
__version__ = files("pyjet").joinpath("VERSION.txt").read_text().strip()
version = __version__
version_info = __version__.split(".")
FASTJET_VERSION = "3.3.4"
FJCONTRIB_VERSION = "1.045"
|
#!/usr/bin/env python3
import glob, os, sys
from collections import defaultdict
import random
from shutil import copyfile
#List of schema parts to allow us to generate our own with dynamic tables
schemaparts = {
"PART": """
BEGIN;
CREATE TABLE PART (
P_PARTKEY SE... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import Person
from django.shortcuts import render
# Create your views here.
def index(request):
"""
This function takes a request and renders an html in templates for main page.
:param request: A request
:return: a render
... |
import json
import logging
from typing import List, Optional, Tuple
from sqlalchemy.orm import Session
from telegram.bot import Bot
from app import crud
from app.database import get_db
from app.settings import settings
from app.web import post_async
bot = Bot(token=settings.telegram_bot_token)
TELEGRAM_SET_WEBHOOK... |
from django.conf.urls import *
from django.contrib import admin
from django.views.generic import TemplateView
admin.autodiscover()
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
# Examples:
# url(r'^$', 'mendelmd.views.home', name='home'),
... |
def rule(event):
return (event['eventName'] == 'ConsoleLogin' and
event['userIdentity'].get('type') == 'IAMUser' and
event.get('responseElements', {}).get('ConsoleLogin') == 'Failure')
def dedup(event):
return event['userIdentity'].get('arn')
|
from django.db import models
from hashid_field import HashidAutoField, HashidField
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse # Django <= 1.8
class Author(models.Model):
id = HashidAutoField(primary_key=True)
name = models.CharField(max_len... |
import sys
import unittest
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '../src'))
from RtmTokenBuilder import *
from AccessToken import *
appID = "970CA35de60c44645bbae8a215061b33"
appCertificate = "5CFd2fd1755d40ecb72977518be15d3b"
userAccount = "test_user"
expireTimestamp = 1446455471
salt = 1... |
#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
from abc import ABCMeta, abstractmethod
from prettytable import PrettyTable
def print_progress_bar(iteration: int, total: int, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""
Call in a loop to create terminal progress bar
@... |
import numpy
import pandas as pd
import re
import csv
import time
import datetime
from selenium import webdriver
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdrive... |
"""
Author: Arthur Wesley
"""
from unittest import TestCase
import sente
import numpy as np
from assert_does_not_raise import DoesNotRaiseTestCase
class TestBasicMethods(DoesNotRaiseTestCase):
def test_constructor(self):
"""
checks that all possible constructors work
:return:
... |
"""
Dataset augmentation functionality
NOTE: This module is much more free to change than many other modules
in CleverHans. CleverHans is very conservative about changes to any
code that affects the output of benchmark tests (attacks, evaluation
methods, etc.). This module provides *dataset augmentation* code for
buil... |
from django.core.urlresolvers import resolve, reverse
from rest_framework.test import APIRequestFactory, force_authenticate
from scrappyr.users.testing.factories import AdminUserFactory
def json_post_to_view(viewname, **kwargs):
"""Post json request to view given by viewname.
Args:
viewname (str): N... |
from __future__ import unicode_literals
import os
from django.conf import settings
from django.test import override_settings
from django.test import TestCase
from django.urls import clear_url_caches
from django.urls import reverse
from django.utils import translation
from django.utils._os import upath
from mock impor... |
from prob_14 import prob_14
n = int(input("Ingrese un numero: "))
print (prob_14(n)) |
""" Monolithic game server function. This file contains all the backend logic to execute moves and
push the observations to the agents. """
import dill, json
import argparse
from multiprocessing import Event
from typing import Type, Dict, List, NamedTuple
from time import sleep
from spacetime import Node, Dataframe
... |
#!/bin/env python3
from math import cos,pi
def size_inscrit_polygon(size, n):
return size * (2 - 2 * cos(2*pi / n))**0.5 |
from setuptools import setup, find_packages
from codecs import open
from os import path
VERSION = 'v2.1.0'
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='ran... |
# Time: O(nlon + n * t), t is the value of target.
# Space: O(t)
# 377
# Given an integer array with all positive numbers and no duplicates,
# find the number of possible combinations that add up to a positive integer target.
#
# Example:
#
# nums = [1, 2, 3]
# target = 4
#
# The possible combination ways are:
# (1, ... |
#!/usr/bin/env pypy
import sys
def mex(S):
S = set(S)
v = 0
while v in S:
v += 1
return v
n = int(sys.argv[1])
sg = [0] * (n + 1)
cnt = 0
for i in range(2, n + 1):
S = []
for j in range(0, i - 1):
S.append(sg[j] ^ sg[i - j - 2])
sg[i] = mex(S)
if sg[i]:
cnt ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import os
import sys
from setuptools import find_packages, setup
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as f:
long_description = "\n" + f.read()
about = {}
with open(os.pa... |
from logging import critical, debug, error, info, warning
from src.Player import Player
from src.utils import get_stars, query_leaderboard_API, truncate_name
HEADER = """
Day 1111111111222222
1234567890123456789012345\
"""
class Leaderboard:
def __init__(self, db) -> None:
self.p... |
"""
virenamer
"""
import subprocess
import sys
from argparse import ONE_OR_MORE, ArgumentParser
from os import getenv
from pathlib import Path
from shutil import rmtree
from tempfile import NamedTemporaryFile
from typing import List, Optional
from colorama import Fore as F
from . import __version__
DEFAULT_EDITOR = ... |
from elf.types.base.int.elf_int_8_type import ElfInt8Type
from elf.types.base.int.elf_int_16_type import ElfInt16Type
from elf.types.base.int.elf_int_32_type import ElfInt32Type
from elf.types.base.int.elf_int_64_type import ElfInt64Type
from elf.types.base.int.elf_int_n_type import ElfIntNType
|
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
class Con... |
# creating a Class of name Employee
class Employee:
# creating a Class Variable
increament = 1.5
# Creating a Constructor of the Class Employee
def __init__(self, fname, lname, salary):
# setting Values to the variables
self.fname = fname
# setting Values to the variables
... |
from django.shortcuts import render, redirect
from django.contrib import messages
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.forms.models import modelformset_factory
from basic_newsletter.models import Issue, NewsItem, Newsletter
from basic_newsletter.forms impo... |
import logging
import networkx as nx
from iteration_utilities import duplicates
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.model_selection import train_test_split
from stellargraph.data import EdgeSplitter
logger = logging.getLogger(__name__)
def get_edge_list(G, sort=True):
if sort:
... |
import torch
from model.base_semantic_segmentation_model import SemanticSegmentationModel
from metrics.iou import iou_coefficient
class UNET(SemanticSegmentationModel):
def __init__(
self, in_channels=3, out_channels=1, features=[64, 128, 256, 512], normalize_output=False
):
super().__ini... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.