content stringlengths 5 1.05M |
|---|
import time
from flexsm import StateMachine, State, Transition, addTransition
root = State("root")
state2 = State("state 2")
state1 = State("state 1")
@addTransition(state=root)
class WaitForXToBecomeSmall(Transition):
def getNextState(self, x):
if x>15:
return root
else:
r... |
################################################################################
# E-Cookbook - electronic recipe organizer
# Copyright (C) 2006 Shyam "Doggan" Guthikonda.
#
# Email: shyamguth@gmail.com
# URL: http://shy.am
#
# Project Page: http://sourceforge.net/projects/ecookbook
#
# This library is free so... |
#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author:Administrator
@file: errors.py
@time: 2019/05/04
@software: PyCharm
@detail: 错误处理
"""
|
try:
from buidl.cecc import * # noqa: F401,F403
except ModuleNotFoundError:
from buidl.pecc import * # noqa: F401,F403
|
#coding:utf-8
from mock import patch, Mock
from requests import Session
from unittest import TestCase
from facebook_client.request import FacebookSession, FacebookResponse
class MockedRequestsResponse(object):
status_code = 200
def json(self):
return {'key': 'value'}
class TestFacebookSession(Test... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
def for_minus():
for row in range(5):
for col in range(6):
if row==2 and col>0 and col<5 :
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_minus():
row=0
while row<5:
col=0
while col<6:
... |
from .utils import (
Git2TypeConstIndex,
get_git2_param,
get_c_wrapper_param_list,
get_c_param_list,
get_c_wrapper_before_list,
)
import unittest
class TestUtils(unittest.TestCase):
C_PARAMS = "git_oid *out, git_index *index, git_repository *repo"
def test_match(self):
pt = Git2T... |
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from pyspark.sql import SparkSession
from pyspark.sql.functions import desc, col
cluster_seeds = ['127.0.0.1']
spark = SparkSession.builder.appName('Word Cloud').config('spark.cassandra.connection.host', ','.join(... |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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, merge, publish... |
import nltk
def parse(sent, grammar):
gr = nltk.cfg.parse_cfg(grammar)
parser = nltk.ChartParser(gr, nltk.parse.TD_STRATEGY)
trees = parser.nbest_parse(sent.split())
nltk.draw.draw_trees(*trees)
grammar = """
S -> NP VP
VP -> V NP | VP PP
NP -> Det N | NP PP
PP -> P NP
NP -> 'I'
Det ... |
import unittest
import sys
import pytest
import mock
from niworkflows.viz.utils import save_html
class TestUtils(unittest.TestCase):
@mock.patch('jinja2.Environment')
@mock.patch('niworkflows.common.report.open', mock.mock_open(), create=True)
@pytest.mark.skipif(reason='this test always fails, mock not... |
"""
A structural thing.
"""
from ._structure import Structure
from .property import Property
__all__ = [
"Structure",
"Property",
]
|
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class TemplateJobInfo:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is... |
"""Tests for autocsr."""
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 29 17:02:19 2018
@author: Stamatis Lefkimmiatis
@email : s.lefkimmatis@skoltech.ru
"""
import torch as th
from pydl import utils
def dct(tensor):
r"""Initializes the input tensor with weights from the dct basis or dictionary."""
assert(tens... |
from unittest import TestCase
from attendance.Api import Api
from attendance.Objects import AttendanceObject
class TestAttendanceObject(TestCase):
def test_api(self):
api = Api()
attendance = AttendanceObject(api)
self.assertEqual(api, attendance.api)
api2 = Api()
attendan... |
from pathlib import Path
# import shutil
import subprocess
from build_html import get_solution_details
if __name__ == '__main__':
for path in Path('solutions').glob('**/*.asm'):
details = get_solution_details(path)
size = details['size']
speed = details['speed']
dst = path.parent /... |
from itertools import groupby
import requests, bs4
import re
import pandas as pd
import datetime
from datetime import datetime,timedelta
start_date = '2020.01.01' #開始日期
end_date = '2022.02.13' #結束日期
start = datetime.strptime(str(start_date),"%Y.%m.%d")
end = datetime.strptime(str(end_date),"%Y.%m.%d")
new_start_da... |
#!/usr/bin/env python3.7
#
# File: sendpkts.py
#
# Description : flooder script
# Created by : Quinn Burke (qkb5007@psu.edu)
# Date : November 2019
# Last Modified : November 2019
### Imports ###
from random import randint, shuffle
# from scapy.all import *
import time
import threading
import sys
import... |
import re
import sys
import argparse
import os
import json
from pathlib import Path
from datetime import datetime
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
import pandas as pd
cwd = os.getcwd()
sys.path.insert(1, cwd + '/src')
import PcapUtils
import MUDGenUt... |
""" ExportContainer_Dialog module. """
# ISC License
#
# Copyright (c) 2020–2022, Paul Wilhelm, M. Sc. <anfrage@paulwilhelm.de>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permissi... |
import os, sys
from datetime import datetime, timedelta
from time import sleep
from timeit import default_timer as timer
from story import Story
from utils import ERROR, SUCCESS, WARNING, CAPTURE_WAIT
from utils import DateIterator, clear_screen, ffi_channel, fmt, fmt_text, force_input, get_lang
def build_... |
import datetime
class Stat:
""" VFS stat() result
This differs from the builtin os.stat_result in that:
* It doesn"t include less commonly used attributes like inode number
* It guesses fallbacks, like if mtime is null use ctime, etc.
* Timestamps are datetime objects so they can ... |
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import numpy as np
import time
import sys
# This cube was taken from
# http://www.opengl-tutorial.org/beginners-tutorials/tutorial-4-a-colored-cube/
CUBE = [
-1.0,
-1.0,
-1.0, # triangle 1 : begin
-1.0,
-1.0,
1.0,
... |
# Copyright 2005 Divmod, Inc. See LICENSE file for details
from axiom.test.historic import stubloader
from xmantissa.ixmantissa import IFulltextIndexer
from xmantissa.fulltext import PyLuceneIndexer
class PyLuceneIndexerTestCase(stubloader.StubbedTest):
def testUpgrade(self):
"""
The PyLuceneInd... |
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
from rdkit import Chem
get_ipython().run_line_magic('matplotlib', 'inline')
# In[3]:
homedir = os.path.dirname(os.path.realpath('__file__'))
homedir = homedir+"/data/"
# In[4]:
jo... |
"""Set up for the UrFU LTI Customizations package."""
from setuptools import setup
setup(
name='urfu-lti',
version='0.2.0',
description='UrFU LTI Customizations package.',
packages=[
'urfu_lti',
],
)
|
from filemapper.check.checkcommonextension import CheckCommonExtension
check = CheckCommonExtension()
# Multimedia Check Tests
def test0_filemapper_check_multimedia():
assert check.check_multimedia('multimedia_video_sample.mkv') is True
def test1_filemapper_check_multimedia():
assert check.check_multimedia('... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsZonalStatistics.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
""... |
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... |
import smart_imports
smart_imports.all()
class Mixin:
@contextlib.contextmanager
def check_discord_synced(self, accounts_ids):
with mock.patch('the_tale.portal.logic.sync_with_discord') as sync_with_discord:
yield
if not isinstance(accounts_ids, set):
accounts_ids =... |
#!/usr/bin/env python
import sys
import os
from PySide import QtCore, QtGui
from PySide.QtGui import QFileDialog
from juma.core import app, signals
from juma.qt.TopEditorModule import TopEditorModule, QtMainWindow, SubEditorModule
##----------------------------------------------... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 12 13:34:33 2022
@author: oronald
"""
#Import required libraries
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.models import Model
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib... |
"""
[Weekly #20] Paradigms
https://www.reddit.com/r/dailyprogrammer/comments/2sx7nn/weekly_20_paradigms/
So recently there has been a massive surge in the interest of functional programming, but let's not forget the other
paradigms too!
* Object oriented
* Imperative
* Logic (Prolog)
There are more than I have listed... |
############################################################
#
# functions relative to subdomains
#
############################################################
try:
from mpi4py import MPI
#print('- mpi4py : found')
except:
print('- mpi4py : not found, please install it')
exit(0)
from numpy import zero... |
__version__ = '0.1.4.2'
|
from tk_builder.image_readers.image_reader import ImageReader
import numpy
class NumpyImageReader(ImageReader):
fname = None
full_image_nx = int
full_image_ny = int
numpy_image_data = None # type: numpy.ndarray
def __init__(self, numpy_image_data):
"""
Parameters
----... |
from threading import Timer
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
... |
import sys
import jinja2
from devices import DEVICES
from scrapli_cfg import ScrapliCfg
from scrapli import Scrapli
# we can just search at / because the "base_config" is already fully qualified
JINJA_LOADER = jinja2.FileSystemLoader(searchpath="/")
JINJA_ENV = jinja2.Environment(
loader=JINJA_LOADER, trim_block... |
"""
Tests for IRC bot logging.
"""
from datetime import datetime, timedelta
from json import dumps, loads
from pycon_bot import log
from treq import post
from twisted.internet import defer, task
from twisted.trial import unittest
from zope.interface import verify
class PyConSiteLogTargetTests(unittest.TestCase):
... |
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import Delaunay
from scipy.interpolate import NearestNDInterpolator
from scipy import optimize
plt.gca().set_aspect('equal')
plt.style.use('science')
grid = np.loadtxt("basis.dat")
finegrid = np.loadtxt("finegrid.dat")
Nfine = len(finegrid)
residua... |
""" Pipelines expressed as dask graphs
"""
from dask import delayed
from arl.data.parameters import get_parameter
from arl.image.deconvolution import restore_cube
from arl.graphs.graphs import create_deconvolve_graph, create_invert_graph, create_residual_graph, \
create_selfcal_graph_list, create_predict_graph
d... |
"""
Sheepdog example demonstrating what happens when errors occur.
Our simple function raises an error for one of the arguments, and we'll see
that it gives us a None in the results and we can fetch more error details too.
"""
import sheepdog
def f(a, b):
if a == 2:
raise ValueError("a cannot be 2!!!")
... |
#!/usr/bin/env python3
"""tests for gashlycrumb.py"""
import os
import re
import random
import string
from subprocess import getstatusoutput
prg = "./gashlycrumb.py"
# --------------------------------------------------
def file_flag():
"""Either -f or --file"""
return "-f" if random.randint(0, 1) else "--f... |
# Copyright (c) 2019 Graphcore Ltd. 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 l... |
import logging
import argparse
import math
import os
import sys
from time import strftime, localtime
import random
import numpy
from pytorch_pretrained_bert import BertModel
from sklearn import metrics
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, random_split
from data_utils import buil... |
import logging.handlers
import basebot
class LogBot(basebot.Bot):
filename_format = "%s.log"
message_format = "[%(asctime)s] %(message)s"
def __init__(self, *args, **kwargs):
super(LogBot, self).__init__(*args, **kwargs)
self.logs = {}
def join_room(self, room, password=None):
... |
import logging
def get_config(name, src):
config = {}
if name.upper() == 'HMDB-ARID':
config['num_classes'] = 10
elif name.upper() == 'UCF-HMDB':
config['num_classes'] = 14
elif name.upper() == 'MK200-UCF':
config['num_classes'] = 45
else:
logging.error("Configs for dataset '{}' with source dataset {} n... |
import json
mimetype = 'application/json'
headers = {
'Content-Type': mimetype,
'Accept': mimetype
}
def test_create_success(app, client):
data = {
"audioFileType":"song",
"audioFileMetadata":{
"name":"Fast Lane",
"duration":240
}
}
response... |
from infi.pyutils.lazy import cached_method, clear_cache
from ..base import partition
# pylint: disable=W0212
class LinuxPartition(partition.Partition):
def __init__(self, containing_disk, parted_partition):
super(LinuxPartition, self).__init__()
self._parted_partition = parted_partition
s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 10:59:57 2019
@author: kyle
"""
# Internal modules
from bayesian_methods import lambdas_grid, interpolators
import numpy as np
import Tasmanian
from scipy.interpolate import RegularGridInterpolator
from time import time
import matplotlib.pyplot... |
import argparse
import json
import os
import pickle
import sys
from collections import defaultdict
from copy import deepcopy
from itertools import chain
from tqdm import trange, tqdm
import numpy as np
from multiprocessing import get_context
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# inv.inv data plugin
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ------------------------------------------------------------... |
from collections import deque
class Parser:
@staticmethod
def isValid(data):
parsed = Parser.parseRaw(data)
if data.startswith("%xt%") and len(parsed) >= 3:
return True
else:
return False
@staticmethod
def parseRaw(data):
parsed = deque(data.split("%"))
parsed.popleft()
parsed.pop()
return ... |
import tkinter
import PIL
from PIL import ImageTk
class Top_Menu:
def __init__(self,root, gridx, gridy, open_wld, map_update, map_list, save_wld,
zoom_in, zoom_out, add_object, toggle_grid):
frame = tkinter.Frame(root, bd=2, relief=tkinter.SUNKEN)
frame.grid(row=gridx, column=gridy, sticky=tk... |
#!/usr/bin/python
"""
This is a python implementation of the core
MixText functionality. This is originally intended
to be used with BinStore to allow any machine to configure
BinStore enabled implants.
"""
import sys
MIX_TEXT_KEY_BYTE=0x47
def mix(src, rand):
global MIX_TEXT_KEY_BYTE
prev = ""
retval ... |
illness_list=[ "syöpä",
"syövän",
"syöpiä",
"kasvain",
"tuumori",
"kasvaimen",
"kasvaimia",
"tauti"]
treatment_list=["hoito",
"hoidon",
"hoidot",
"hoitoa",
... |
valid_speed_modes =\
{
"normal": 1.0,
"slow": 2.0,
"turbo": 0.1
}
teams_search_key = 'teams'
bs_generator_api = 'https://corporatebs-generator.sameerkumar.website/'
waiting_intervals = 2
|
import logging
import ibmsecurity.utilities.tools
logger = logging.getLogger(__name__)
def get(isamAppliance, resource_id, check_mode=False, force=False):
"""
Retrieving a list of stanzas - Runtime Environment
"""
return isamAppliance.invoke_get("Retrieving a list of stanzas - Runtime Environment",
... |
#!/usr/bin/env python3
# After this script: ./john --format=NETNTLM freeradius.john
#
# 12/19/2011 - Josh Kelley
###############################################################################
import sys
OUTPUT = "freeradius.john"
LOG_FILE = sys.argv[1]
if len(sys.argv) < 2:
print (sys.argv[0]+" <freeradius log ... |
from . import *
import networkx as nx
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
# https://www.infobyip.com/detectmonitordpi.php
DPI = 96
LINE_WIDTH = 2.0
LABEL_FONT_SIZE = 'xx-large'
TICK_FONT_SIZE = 'x-large'
def plot_vec(data, ax, aspect=3, ytickl... |
import numpy as np
from gym import utils
from gym.envs.dart import dart_env
class DartWalker2dEnv(dart_env.DartEnv, utils.EzPickle):
def __init__(self):
self.control_bounds = np.array([[1.0]*6,[-1.0]*6])
self.action_scale = np.array([100, 100, 20, 100, 100, 20])
obs_dim = 17
dart_... |
# -*- coding: utf-8 -*-
"""Conditional_SLE-GAN_template.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1GADBacbjtpsiWWnlS_gs8KPgIzphobf3
# 概要
SLE-GAN (Lightweight GAN)に、生成画像の条件指定機能を追加
# 使用するGPUを指定
"""
import os
# dual GPUなら、"0,1"
os.environ["C... |
# https://github.com/pytorch/vision/blob/master/torchvision/models/__init__.py
import argparse
import os,sys
import shutil
import pdb, time
from collections import OrderedDict
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import tor... |
# -*- coding: utf-8 -*-
"""
Created on 2021-01-05
@author: cheng.li
"""
from typing import Union
import cvxpy as cp
import numpy as np
from pfopt.base import _IOptimizer
class LpOptimizer(_IOptimizer):
def __init__(self,
cost: np.ndarray,
cons_matrix: np.ndarray = None,
... |
n, k = map(int, input().split())
circle = [x for x in range(1, n + 1)]
series = list()
target = 0
for i in range(n):
target = (target + k - 1) % (n - i)
series.append(circle[target])
circle = circle[:target] + circle[target + 1:]
print(f"<{', '.join(map(str, series))}>")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
import sys
from setuptools import find_packages, setup
def get_version(filename):
"""Extract the package version."""
with open(filename, encoding='utf8') as in_fh:
for line in in_fh:
if line.startswith('__version__'):
... |
import torch
from torch import nn
import torch.nn.functional as F
def smooth_loss(pred_map):
def gradient(pred):
D_dy = pred[:, :, 1:] - pred[:, :, :-1]
D_dx = pred[:, :, :, 1:] - pred[:, :, :, :-1]
return D_dx, D_dy
loss = 0
weight = 1.
dx, dy = gradient(pred_map)
dx2, dx... |
#!/usr/bin/env python
import sys
import subprocess
def main():
paths = sys.argv[1:] or sys.stdin.read().splitlines()
cmd = ['packaging/release/changelogs/changelog.py', 'lint'] + paths
subprocess.check_call(cmd)
if __name__ == '__main__':
main()
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='GradespeedScraper',
version='0.1-dev',
description='Scrapes Gradespeed',
author='Davis Robertson',
author_email='davis@daviskr.com',
license='MIT',
url='https://github.com/ep... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import click
import frappe
def execute():
doctype = "Data Import Legacy"
table = frappe.utils.get_table_name(doctype)
# delete the doctype record to avoid broken links
frappe.db.delete("DocType", {"name": doctype})
# leaving table in database for manual cleanup
click.secho(
f"`{doctype}` has been deprecate... |
'''
Quotes App
=========================================
This program generates a random quote everything time the user requests by pressing a button. Uses the Kivy framework.
'''
#Things to Add: Export it to Play Store, add a way to maxmize window automatically, etc.
import random as r
fr... |
from classes.game_object import GameObject
from classes.game_state import GameState
from classes.ghost import Ghost
import pygame
from pygame.sprite import Sprite
class Resp(GameObject):
"""It's just a resp"""
resp_sprite = None
def __init__(self, x: int, y: int, sprite: Sprite = None):
# Load s... |
# AoC 2019 - Day 6 - Part 1
f = open('input.txt', 'r')
orbits = f.read().split('\n')
planets = {'COM': 0}
sum = 0
def get_orbits(planet):
if planet == 'COM':
return 0
return 1 + get_orbits(planets.get(planet))
for orbit in orbits:
planet = orbit.split(')')
planets[planet[1]] = planet[0]
for ... |
# example@gmail.com
import math
class Dot:
def __init__(self, x_input, y_input):
self.x = x_input
self.y = y_input
def dot_get_x(self):
return self.x
def dot_get_y(self):
return self.y
def dot_add(self, other):
# return (x, y) = (x1 + x2, y1 + y2) (Dot)
r... |
import collections
import typing
from enum import Enum
from .enums import GVAL_TEXTABLE, GVAL_NUMERIC, GVAL_LOCATABLE, GVAL_LISTABLE, GVAL_ITEM, ParticleType, SoundType, \
Material
from .classes.abc import Itemable
from .classes.mc_types import DFNumber, DFText, DFLocation, DFPotion, Item, DFCustomSpawnEgg, DFPart... |
from django.contrib import admin
from users.models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
fields = [
'company_name',
'first_name',
'last_name',
'username',
'phone',
'address',
]
list_display = ['company_name', 'username', 'phon... |
import os
os.chdir("updater-lib")
os.execl("updater.exe", "Rebirth Item Tracker") |
class Identity:
def do(self, x):
return x
|
def voto(anoNascimento):
from datetime import date
idade = date.today().year - anoNascimento
if idade < 16:
return(f'Com {idade} anos: NÃO VOTA!')
elif 16 <= idade < 18 or idade > 65:
return(f'Com {idade} anos: VOTO OPCIONAL!')
else:
return(f'Com {idade} anos: VOTO OBRIGATÓRI... |
from collections import OrderedDict
from pytest import fixture
from oarepo_nusl_rules.xoai.rules import xoai_identifier
@fixture
def identifier():
return OrderedDict([('@name', 'none'),
('field',
OrderedDict([('@name', 'value'),
... |
# repl.py
"""
Simple loop function to take user input
"""
from util.output_handler import handle_output
def user_input(input_handler, output_handler, prompt='>>> '):
"""
Takes in input from user then passes input to input_handler for other code
execution. Input handler should return an output of type l... |
import os
from flask import Blueprint, request, jsonify, make_response, current_app
from flask.views import MethodView
import hashlib, binascii, uuid
import jwt
import datetime
from .. import db
bp = Blueprint('api', __name__, url_prefix='/')
class TestAPI(MethodView):
def get(self):
return make_respons... |
import hashlib
import itertools
import json
import os
import io
import glob
import pathlib
import re
import requests
import sys
import time
from bs4 import BeautifulSoup
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from PIL import Image
from hashlib import md5
from math ... |
#!/usr/bin/env python3
# -*- coding:UTF-8 -*-
#########################################################
# filename : generateReadme.py
# author : geekhall
# version : v1.0.0
# function : Gererate root README.md file.
#########################################################
import os
# Constant
ROOT_DIR = './'
# li... |
import cv2 as cv
import numpy as np
path ="/home/senai/tiago-projects/opencv-tutorials/opencv-course/Resources"
img = cv.imread(path +"/Photos/cats.jpg")
cv.imshow('', img)
blank = np.zeros(img.shape, dtype='uint8')
cv.imshow('b', blank)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('gray', gray)
blur = cv.... |
import os
import textwrap
import unittest
from parameterized.parameterized import parameterized
from conans.client import tools
from conans.model.ref import ConanFileReference, PackageReference
from conans.test.utils.tools import TestClient, NO_SETTINGS_PACKAGE_ID
from conans.util.files import load
class CreateTest... |
"""
main
"""
from scr.floatingwindow import *
def main():
fw = FloatingWindow()
fw.mainloop()
if __name__ == '__main__':
main()
|
# written by junying
# 2019-04-28
def delkey(dict_,field):
for key, value in dict_.items():
if key == field: dict_.pop(field)
if isinstance(value, dict): delkey(value,field)
def rmempty(dict_):
for key, value in dict_.items():
if not value: dict_.pop(key)
if isinstance(value, d... |
class GameBoard(object):
"""
The board of the game, default size is 25x25
"""
def __init__(self, width, height):
self.width = width
self.height = height
self.gameboard = []
for i in xrange(width):
self.gameboard.append([])
for j in xrange(heig... |
from datetime import datetime
from torch import load, no_grad
from painting_mode.utils import *
class GNST:
'''
Inference stage for
Generative Neural Style Transfer with CycleGAN
'''
def __init__(self, content_path):
# Start the clock
self.time_started = self._start_clock()
... |
from django.urls import path
from django.views.generic import TemplateView
app_name='menu'
urlpatterns = [
path('', TemplateView.as_view(template_name='menu/main_menu.html'), name='main'),
path('page1', TemplateView.as_view(template_name='menu/main_menu.html'), name='page1'),
path('page2', TemplateView.as_... |
from proxy.system_handler import system_handler
from proxy.data import data_loader
from proxy.Decklist import Decklist
import os
import test
import logging
##Logging configuration
logger = logging.getLogger()
logger.setLevel(level = logging.INFO)
stream = logging.StreamHandler()
streamformat = logging.Formatter("[%(... |
#thomas feiring model
import math
import numpy as np
import matplotlib.pyplot as plt
month=11#int(input("enter the month number: "))-1
year=2017#int(input("enter year"))
X_t= 6401#int(input("inflow data: "))
number_of_months=20*12#int(input("Enter the number of months for which you want predictions"))
#mean
... |
VERSION = "1.38"
|
game_time = input().split(" ")
initial_hour = int(game_time[0])
initial_min = int(game_time[1])
final_hour = int(game_time[2])
final_min = int(game_time[3])
if (initial_hour < final_hour): # First case: HI > HF
total_hour = (final_hour - initial_hour)
if (initial_min <= final_min):
total_min = (final_mi... |
#!/usr/bin/env python3
"""A cross-platform script to build cohorts, run models, build and
start a notebook, open a web browser on the correct port, and handle
shutdowns gracefully
"""
import cohortextractor
import glob
import importlib
import os
import re
import requests
import shutil
import sys
import base64
from i... |
"""
oauthlib.oauth2.rfc6749.endpoint.metadata
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An implementation of the `OAuth 2.0 Authorization Server Metadata`.
.. _`OAuth 2.0 Authorization Server Metadata`: https://tools.ietf.org/html/rfc8414
"""
import copy
import json
import logging
from .. import grant_types
from .... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.