content stringlengths 5 1.05M |
|---|
from moai.data.datasets.common import load_color_image
from moai.utils.arguments import ensure_string_list
import torch
import glob
import os
import typing
import logging
__all__ = ["StructuredImages"]
log = logging.getLogger(__name__)
class StructuredImages(torch.utils.data.Dataset):
def __init__(self,
... |
class change_constraint:
""" Generates a partial SQL command to change a foreign key in a table """
def __init__(self, constraint):
self.constraint = constraint
def apply_to_table(self, table):
""" Changes the constraint in the table
:param table: The table to change the constrain... |
import matplotlib.pyplot as plt
from hyperparameters import *
import numpy as np
from tqdm import tqdm
from imutils import paths
import tensorflow as tf
from tensorflow import keras
import tensorflow_datasets as tfds
from tensorflow.keras.layers import *
from tensorflow.keras.models import *
from tensorflow.keras impo... |
#This file handles the statistics portion of the game
titles = []
stats_array = []
def save_stats():
f = open("statistics.csv", "w")
write_str = ""
for x in range(len(titles)):
if x == len(titles) - 1:
write_str = write_str + str(titles[x]) + "\n"
break
write_str = write_str + str(titles[x]) + ","
f.writ... |
from django.db import models
# Create your models here.
class Item(models.Model):
name = models.CharField(max_length=50, unique=True, null=False, blank=False)
price = models.IntegerField(null=False, blank=False)
def __str__(self):
return self.name |
import argparse
import base64
import json
from re import A
import numpy as np
from typing import Dict, Any
import requests
import grpc
import tensorflow as tf
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
def read_text(text_file: str = "./text.txt") ->... |
"""
zamień element pierwszy i ostatni w tablicy [1,2,3, 'wiadomo']
"""
t = [1,2,3, 'wiadomo']
buff = t[0]
t[0] = t[-1]
t[-1] = buff
print(t)
|
#!/usr/bin/python3
"""
Test the main module.
"""
import pytest
import ising.__main__
__ARGS = ["--length", "8"]
def test_cback():
"""
Test the C backend.
"""
assert all(
map(
lambda x: x is not None,
ising.__main__.main(pass_args=__ARGS + ["--backend", "c"], test=True),
... |
# ******************************************************************************
# Copyright 2017-2018 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.apa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ## ###############################################
# Author: Santillan Garcia Josue
# Codigo modificado de blink.py
# Future imports (Python 2.7 compatibility)
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
... |
from . import tic_tac_toe
from . import connect_4
game_types = { str(i) : game_type for (i, game_type) in enumerate((
tic_tac_toe,
connect_4,
))}
STATE_PROPOSED = 0
STATE_ACTIVE = 1
STATE_COMPLETE = 2
STATE_FORFEIT = 3
STATE_CANCELLED = 4
STATES = [
STATE_PROPOSED,
STATE_ACTIVE,
STATE_COMPLETE,
... |
import matplotlib
matplotlib.use('Agg')
import os
import sys
import numpy as np
import json
import matplotlib.pyplot as plt
import caffe
from caffe import layers as L
from caffe import params as P
from activity_data_provider_layer import ActivityDataProvider
from build_val_model import act_proto, exp_proto
import con... |
from unittest import TestCase
from unittest.mock import patch
from dd_import.environment import Environment
class TestEnvironment(TestCase):
def test_check_environment_reimport_findings_empty(self):
with self.assertRaises(Exception) as cm:
environment = Environment()
environment... |
"""
An interface to the python-swiftclient api through Django.
"""
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
import json
from difflib import get_close_matches
dataset = json.load(open("data.json"))
word = input("Enter the word: ")
def translate(word):
word = word.lower() # .lower() convert string to lowercase.
if word in dataset:
print("Meaning - ")
meanings = dataset[word]
for m... |
carro = int(input('Quantos anos tem o seu carro?'))
if carro <=5:
print('Seu carro é novo!')
else:
print('Seu carro é velho!')
print('--FIM--')
#TEMOS COMO DIMINUIR O CÓDIGO ASSIM!!!
#carro = int(input('Quantos anos tem o seu carro?'))
#print('Carro novo' if carro<=5 else 'Carro velho')
#print('--FIM--')
|
#!/usr/bin/env python
import os
import sys
import json
import re
from DIRAC import gLogger
from DIRAC import S_OK, S_ERROR, exit
from DIRAC.Core.Base import Script
Script.setUsageMessage( """
Get and merge output files of the task
Usage:
%(script)s [options] TaskID
Examples:
# Download all output files in... |
from pynetest.lib.expectation import Expectation
from pynetest.matchers import between
class ToBeBetweenExpectation(Expectation):
def __init__(self, lower, upper):
self.lower = lower
self.upper = upper
super().__init__("to_be_between", between(lower, upper), self.message_format)
def m... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
class CryptoKeyIAMMember(pulumi.CustomResource):
"""
Allows creation and management of a s... |
from app.data_layer.datastore import Datastore
class SongFacade:
def __init__(self):
self._datastore = Datastore()
def create_song(self, song_name, song_artist, song_genre):
"""
:param str song_name:
:param str song_artist:
:param str song_genre:
:rtype: dict
... |
from datahub.dataset.core.pagination import DatasetCursorPagination
class TeamsDatasetViewCursorPagination(DatasetCursorPagination):
"""
Cursor Pagination for TeamsDatasetView
"""
ordering = ('id',)
|
# Fixed options
_algorithms = ('Adaptive', 'Non-adaptive')
_weighFuncs = ('Gaussian', 'Linear', 'JSD')
_directions = ('Forward', 'Backward')
_boostMethods = ('Sum similarity', 'Counts')
_yesNo = ('Yes', 'No')
def validatestr(value):
'''Validate that given value is a non-empty string. Used to validate
tracker ... |
import time
import math
maps = {
'costs': {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
},
'autocomplete_costs': {
')': 1,
']': 2,
'}': 3,
'>': 4,
},
'opening': {
"(": ")",
"[": "]",
"{": "}",
"<": ">",
},
'closing': {
")": "(",
"]": "[",
"}": "{",
... |
# The MIT License (MIT)
#
# Copyright (c) 2019 Dan Halbert for Adafruit Industries
#
# 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 righ... |
import setuptools
import os
with open("README.md", "r") as f:
long_description = f.read()
setuptools.setup(
name="cs-kit",
version=os.environ.get("VERSION", "0.0.0"),
author="Hank Doupe",
author_email="henrymdoupe@gmail.com",
description=("Developer tools for compute.studio."),
long_descri... |
#!/usr/bin/env python3
import json
import logging
import sys
import click
from habu.lib.host import gather_details
@click.command()
@click.option('-v', 'verbose', is_flag=True, default=False, help='Verbose output.')
def cmd_host(verbose):
"""
Collect information about the host where habu is running.
Ex... |
import glob
def get_patient_paths(data_path):
patient_paths = glob.glob(data_path + "/*")
return patient_paths
def get_input_paths(patient_path):
input_paths = glob.glob(patient_path + "/*CT*", recursive=True)
return input_paths
def get_label_paths(patient_path):
label_paths = glob.glob(patien... |
from Functions.General_Functions import isNaN, getNContext, pad_array, candidateClsf, filterNumbers, filterNumbers_MaintainDistances
from Method_Handler import MethodHandler
import nltk
import math
import sklearn as sk
import numpy as np
import pandas as pd
import statistics as stats
import os
from tempfile import mkdt... |
"""
A Deep Q-learning agent implementation for the NetworkAttackSimulator
Uses Experience Replay and a seperate Target Network along with the main DQN.
"""
from network_attack_simulator.agents.agent import Agent
import random
import numpy as np
import time
import math
from keras.models import Sequential
from keras.lay... |
"""Back-end code to support the Prereg Challenge initiative
Keeping the code together in this file should make it easier to remove the
features added to the GakuNin RDM specifically to support this initiative in the future.
Other resources that are a part of the Prereg Challenge:
* website/static/js/pages/prereg-lan... |
# -*- coding: utf-8 -*-
# Copyright 2015 Pietro Brunetti <pietro.brunetti@itb.cnr.it>
#
# 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
# Unle... |
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
... |
# https://leetcode.com/problems/design-add-and-search-words-data-structure/
# Design a data structure that supports adding new words and finding if a string
# matches any previously added string.
# Implement the WordDictionary class:
################################################################################
f... |
#from OpenAttack.OpenAttack2.attack_assist.filter_words.protein import PROTEIN_FILTER_WORDS
from .chinese import CHINESE_FILTER_WORDS
from .english import ENGLISH_FILTER_WORDS
from .protein import PROTEIN_FILTER_WORDS
def get_default_filter_words(lang):
from ...tags import TAG_Chinese, TAG_English,TAG_Protein
i... |
import socket
import tokens
import connection
import io
import os
from PIL import Image
from message.literalMessage import LiteralMessage
from baseApplication import BaseApplication
class ClientApplication(BaseApplication):
def __init__(self, host, port):
super().__init__(host, port, token... |
'''
run_tests.py
run unit test cases
'''
import os
import sys
import subprocess as sp
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
test_dir = os.p... |
#!/usr/bin/env python3
###########################################################################
# Bobbi June 2020
#
# Alternative server for ADTPro's VEDRIVE.SYSTEM
# Virtual Ethernet Drive for Apple II / ProDOS
#
# See https://www.adtpro.com/protocolv1.html
#
#######################################################... |
class Solution:
def canCross(self, stones: List[int]) -> bool:
fail = set()
stone_set = set(stones)
stack = []
stack.append((0,0))
while stack:
cur_pos, jump = stack.pop()
for j in (jump-1, jump, jump+1):
pos = cur_pos+j
... |
# Imbalanced Classification
from sklearn.datasets import make_blobs
from sklearn.linear_model import LogisticRegression
import numpy as np
import matplotlib.pyplot as plt
import imageio
import os
try:
os.mkdir('./figures')
except:
pass
images = []
for i,s in enumerate(np.linspace(2000,50,80)):
features, l... |
import inspect
import tempfile
import subprocess
import shutil
import os
import sys
import threading
from itertools import chain
def header(func):
signature = inspect.signature(func)
args = [str(k) if v.default is inspect.Parameter.empty else str(k) + "=" + str(v.default)
for k, v in signature.paramete... |
class Solution:
def findMin(self, nums: List[int]) -> int:
i,j = 0,len(nums)-1
while i < j:
m = (i+j)//2
if nums[m] > nums[j]:
i = m+1
else:
j = m
return nums[i] |
from i2 import Sig
from meshed import DAG, FuncNode
from meshed.base import _func_nodes_to_graph_dict
from meshed.dag import _separate_func_nodes_and_var_nodes
from meshed.itools import topological_sort
# separate with comments lines
def pairs(xs):
if len(xs) <= 1:
return xs
else:
pairs = list(... |
import os
import sys
import yaml
from pathlib import Path
def GetFilesList(yaml_path):
cfg_f = open(yaml_path,'r')
cfg = yaml.load(cfg_f.read(),Loader=yaml.FullLoader)
cwd = os.getcwd()
# print(cfg)
# key is output file name , value is the array of the amalgamated files.
ret = dict()
for k... |
import scrapy
class BlogSpider(scrapy.Spider):
name = 'blogspider'
start_urls = ['https://blog.scrapinghub.com']
def parse(self, response):
for title in response.css('h2.entry-title'):
yield {'title': title.css('a ::text').extract_first()}
next_page = response.css('div.prev-po... |
from boa3.builtin import public
@public
def Main() -> bytes:
return (123).to_script_hash()
|
from pytest import mark
from day_8 import (
parse,
count_1_4_7_8,
count_output,
determine_1_4_7_8,
decode_signals,
main,
)
def test_parse_data() -> None:
parsed_data = parse("day_8_test.txt")
assert parsed_data[0] == [
[
"be",
"cfbegad",
"cbd... |
#!/usr/bin/env python
# encoding: utf-8
import json
import os
import os.path
import re
import sys
from collections import OrderedDict
import copy
from lxml import etree
from lxml.etree import CDATA, SubElement, Element, ElementTree, ParseError, parse, strip_elements
from common import utils, logger
from common.except... |
# -*- encoding: utf-8 -*-
# Date: 16/Jan/2022
# Author: Steven Huang, Auckland, NZ
# License: MIT License
"""
Description: Web Configuration class
"""
import os
class Config:
SECRET_KEY = 'e7c794326ea87a59b2cf616809e1efcd' # secrets.token_hex(16)
SQLALCHEMY_DATABASE_URI = 'sqlite:///db/sqlite/website.db'
... |
#
# Example file for working with functions
#
# define a basic function
def func1():
print("I am a function")
# function that takes arguments
def func2(arg1, arg2):
print(arg1, " ", arg2)
# function that returns a value
def cube(x):
return x * 9
# function with default value for an argument
def power(num, x=... |
from firedrake import *
from firedrake.petsc import PETSc
from firedrake import COMM_WORLD
try:
import matplotlib.pyplot as plt
plt.rcParams["contour.corner_mask"] = False
plt.close("all")
except:
warning("Matplotlib not imported")
nx, ny = 20, 20
Lx, Ly = 1.0, 1.0
quadrilateral = True
mesh = Rectang... |
from flask import Response, request
from db.models import Organism, SecondaryOrganism,Assembly
from flask_restful import Resource
from errors import NotFound,SchemaValidationError,RecordAlreadyExistError,TaxonNotFoundError
from utils.utils import parse_sample_metadata
from utils import ena_client
from datetime import ... |
from queue import Queue
from functools import wraps
class Async:
'''Aync wrapper for all data'''
def __init__(self, func, args):
self.func = func
self.args = args
def inlined_async(func):
@wraps(func)
def wrapper(*args):
f = func(*args)
result_queue = Queue()
re... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
#!/usr/bin/env python2
from setuptools import setup
setup(
name="internalblue",
version="0.4",
description="A Bluetooth Experimentation Framework based on the Broadcom Bluetooth Controller Family.",
url="http://github.com/seemoo-lab/internalblue",
author="The InternalBlue Team",
author_email="... |
__author__ = 'Daniyar'
import itertools
from localsys.storage import db
import math
class score_model:
def check_closest_competitor(self, usrid, your_score):
value_risk = 0.0
value_cost = 0.0
value_risk_cost_contender = 2.0
value_cost_risk_contender = 1.0
prev_value_risk = ... |
import arcpy
structures = "N:\ArcMap_Projects\NG911 Analysis\Gecoding4_7\Geocoding4_7.gdb\Address_Points_4_7"
structureFields = [ "ADDRESS", "DIRPRE","ROADNAME","ROADTYPE","DIRSUF"]
msag = "N:\ArcMap_Projects\NG911 Analysis\Gecoding4_7\Geocoding4_7.gdb\MSAG_4_3"
msagFields = ["Low", "High", "O_E", "Dir", "Street","Com... |
from django.middleware.common import MiddlewareMixin
class ForceDefaultLanguageMiddleware(MiddlewareMixin):
"""
Ignore Accept-Language HTTP headers
This will force the I18N machinery to always choose settings.LANGUAGE_CODE
as the default initial language, unless another one is set via sessions or cooki... |
"""
Basic "generic IDL4" target. Not designed to inherit from anything.
"""
from magpie.targets import base
from magpie.generator.v4generator import V4Generator
class Generator(V4Generator):
pass
class Types(object):
# Methods relating to type declaration, conversion, and marshalling
types_cpp_define_int_constants... |
# -*- encoding: utf-8 -*-
from . import FixtureTest
class ResidentialTest(FixtureTest):
def test_z16(self):
self._check(zoom=16, expect_surface='fine_gravel')
def test_z15(self):
self._check(zoom=15, expect_surface='fine_gravel')
def test_z14(self):
self._check(zoom=14, expect_s... |
import os
import numpy as np
from keras.preprocessing.image import img_to_array, load_img
def load_and_scale_images(img_dir_path, extension, img_width, img_height):
images = []
for f in os.listdir(img_dir_path):
filepath = os.path.join(img_dir_path, f)
if os.path.isfile(filepath) and f.endswi... |
import logging
from django.contrib import messages
from django.core.exceptions import BadRequest
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from dojo.models import Product, Objects_Product
from dojo.forms import ObjectSettingsForm,... |
#!/usr/bin/env python3
"""Given a byte string, split it into rows."""
import os
import sys
def showUsage(msg):
if msg is not None: print(msg)
print("""Usage: split-bytes.py [options...] [infile] [outfile]
options:
-cN: split to N columns
-dNN: byte NN (hex) ends a row (can be used multiple... |
import yfinance as yf
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
import streamlit as st
import pandas as pd
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
Symbol = ["AAPL", "MSFT","AMZN", "FB","GOOG", "GOOGL", "TSLA", "NVDA", "PYPL", "ASML","INTC","CMCSA... |
# See LICENSE for licensing information.
#
# Copyright (c) 2021 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
"""
Enum classes to represent cache policies are defi... |
from PIL import Image
import math
def get_world_coord(img_depth, subj_coordinates, obj_coordinates):
width, height = img_depth.size
uo = width/2
vo = height/2
#FOV (90, 59) given by the depth camera settings
a = 90*math.pi/180
b = 59*math.pi/180
fx = uo / math.tan(a/2)
fy = vo / math.tan(b/2)
#Get the pi... |
import logging
import numpy
from data_models.memory_data_models import Image, GainTable, Visibility, SkyModel
from processing_library.image.operations import copy_image
from workflows.serial.imaging.imaging_serial import predict_list_serial_workflow, invert_list_serial_workflow
from wrappers.arlexecute.visibility.bas... |
# This file is part of the Reproducible and Reusable Data Analysis Workflow
# Server (flowServ).
#
# Copyright (C) 2019-2021 NYU.
#
# flowServ is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Helper method for creating database objec... |
__author__ = 'Serhii Sheiko'
# MIT licence
import subprocess
import sys
# vnstat -tr 3 -i eth0
base_command = ['vnstat']
def help_message():
help_msg = '''Interface usage plugin.
Requirements: vnstat
params:
-i - interface
-t - time for checking in seconds
-rx - limitations for input trafic
-tx - l... |
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Common Google Storage interface library."""
from __future__ import print_function
import base64
import errno
import os
import re
from chromite.l... |
import os
from flask import send_from_directory
from metric.app import ROOTPATH
from metric.app.resource import Resource
class Public(Resource):
def get(self, d, f):
"""
____This resource get will only get the public with 1 depth path only____
@param d: directory public you wanted to acc... |
class Scope:
def __init__ (self, parent=None):
self.parent = parent
self.elements = dict()
def get_element (self, name, type, current=False):
r = self.elements.get(type, None)
if r != None:
r = r.get(name, None)
if r == None and self.parent ... |
"""https://www.codewars.com/kata/576b93db1129fcf2200001e6"""
def sum_array(arr):
"""Returns sum of list without highest and lowest vlues"""
return 0 if arr is None or arr == [] else sum(sorted(arr)[1:-1])
def test_cases():
"""Sample test cases"""
assert sum_array(None) == 0
assert sum_array([]) ==... |
import json
from os import path
from pathlib import Path
class CommonPath:
_instance = None
def __init__(self):
self.PROJECT_ABS_PATH = path.abspath(Path(__file__).parent.parent.absolute())
self.CONFIG_ABS_PATH = self.PROJECT_ABS_PATH + "/config.json"
with open(self.CONFIG_ABS_PATH,... |
"""Core feature extensions for the project related to Python packaging."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2015 Fredy Wijaya
#
# 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 wit... |
from .chem_objects import ChemObject
"""
Lazy Classes to create useful organic compounds.
"""
class PrimaryAlcohol(ChemObject):
"""
Returns a straight chain alcohol.
chain_length >= 1
TODO: Isn't working currently for some reason.
Will fix later.
"""
def __init__(self,... |
from OpenGLCffi.GL import params
@params(api='gl', prms=['n', 'states'])
def glCreateStatesNV(n, states):
pass
@params(api='gl', prms=['n', 'states'])
def glDeleteStatesNV(n, states):
pass
@params(api='gl', prms=['state'])
def glIsStateNV(state):
pass
@params(api='gl', prms=['state', 'mode'])
def glStateCaptur... |
"""Module for the Risk-Exploiting Graph Scenario with variable input parameters
- Network of agents are to act as a connecition between origin and destination terminals of
known (observed).
- This is a simplified, surrogate scenario for the more complex communication relay scenario
since would be expected to produc... |
import mysql.connector as conn
import pandas as pd
import datetime
def show_books(roll,password):
try:
cnx=conn.connect(user='root',password='swapn',host='127.0.0.1',database='library')
cur_book=cnx.cursor()
cur_book.execute("select * from book order by course_id")
temp=cur_book.fetc... |
import computer
output = ""
total = 0
x = 0
y = 0
def RecieveOutput(out):
global output
global total
if(out == 0):
output += "."
return
if(out == 1):
output += "#"
total += 1
return
inputIndex = 0
def SendInput():
global inputIndex
inputIndex += 1... |
# -*- coding: utf-8 -*-
import logging
import os
from unittest.mock import Mock, patch
from django.test import TransactionTestCase
from eventkit_cloud.utils.gpkg.sqlite_utils import get_database_connection, Table
logger = logging.getLogger(__name__)
class TestSqliteUtils(TransactionTestCase):
def setUp(self):
... |
import numpy as np
from copy import copy
from .base import Simplifier
from ... import operations
from ...analyzers import SplitAnalysis
class ConvertBatchNorm(Simplifier):
ANALYSES = {"is_split": SplitAnalysis}
def visit_BatchNormalization(self, operation: operations.BatchNormalization):
input_op =... |
from optuna.logging import get_logger
from optuna.study import Study
from optuna.trial import TrialState
from optuna.visualization._plotly_imports import _imports
if _imports.is_successful():
from optuna.visualization._plotly_imports import go
_logger = get_logger(__name__)
def plot_intermediate_values(study: ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import savReaderWriter as rw
from py3k import isPy3k, isCPython
class Test_spss2strDate(unittest.TestCase):
def setUp(self):
self.savFileName = 'test_data/test_dates.sav'
self.reader = rw.SavReader(self.savFileName)
... |
# -*-coding: utf-8 -
'''
@author: MD. Nazmuddoha Ansary
'''
#--------------------
# imports
#--------------------
import argparse
import os
import json
import random
import cv2
import pandas as pd
import numpy as np
import PIL
import PIL.Image , PIL.ImageDraw , PIL.ImageFont
from tqdm import tqdm
from glob imp... |
import datetime
import json
from django.contrib.admin.templatetags.admin_list import ResultList, result_headers
from django.contrib.admin.utils import (
display_for_field,
display_for_value,
lookup_field,
)
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.forms... |
import json
import hug
from operator import itemgetter
def return_json_file_contents(filename):
"""
Simple function for returning the contents of the input JSON file
"""
try:
with open(filename) as json_data:
return json.load(json_data)
except IOError:
print("File not found: "+filename)
return None
@hug... |
import numpy as np
import unittest
import pytest
from desc.grid import LinearGrid, Grid
from desc.coils import CoilSet, FourierRZCoil, FourierXYZCoil, FourierPlanarCoil
from desc.geometry import FourierRZCurve
class TestCoil(unittest.TestCase):
def test_biot_savart(self):
R = 2
y = 1
I = 1... |
# -*- coding: utf-8 -*-
__author__ = """Biagio Chirico"""
__email__ = 'biagio.chirico.86@gmail.com'
__version__ = '0.1.0'
from pyscholar import Query, Crawler, Article, Parser
|
def color_add():
pass
def color_delete():
pass
def new():
pass
|
import os
from time import time, sleep
from queue import Queue
from pathlib import Path
from multiprocessing import Process
from threading import Lock, Thread
from tempfile import mkstemp
from subprocess import run
from datetime import datetime
from json import dumps
from bisect import insort
from monitor_gui import C... |
# Copyright 2021 Sony Corporation.
# Copyright 2021 Sony Group 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 requi... |
''' This is the main module that runs the api resources & models '''
''' Its an improvement of REST_api_with_DB.py '''
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT
from security import authenticate, identity
from resources.users import UserRegistration, UserCheck
from resources.items... |
# *****************************************************************************
#
# 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
#
# ... |
from django.db import models
from django.contrib.auth.models import AbstractUser
from tournament.models import Tournament
class User(AbstractUser):
is_tournament_manager = models.BooleanField(default=False)
managed_tournaments = models.ManyToManyField(Tournament, blank=True)
|
# pacotes essenciais da V1 da API
from rest_framework import generics
from rest_framework.generics import get_object_or_404
from .models import Curso, Avaliacao
from .serializers import CursoSerializer, AvaliacaoSerializer
# pacotes essenciais da V2 da API
from rest_framework import viewsets
from rest_framework.decora... |
import os
import django
from celery import Celery, shared_task
from celery.schedules import crontab
from celery.signals import task_success
from django.conf import settings
from django.utils import timezone
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_celery_demo.settings')
django.setup()
app = Celery('dj... |
# MIT License
# Copyright (c) 2017 Luca Angioloni and Francesco Pegoraro
# 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 us... |
# coding: utf-8
"""
functools モジュールのサンプルです。
functools.lru_cache() について。
"""
import functools
from trypython.common.commoncls import SampleBase
from trypython.common.commonfunc import pr
class Sample(SampleBase):
def exec(self):
# --------------------------------------------------
# lru_cache()
... |
# vim:set tabstop=4 shiftwidth=4 expandtab:
# Copyright (c) 2008, Humanized, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.