content stringlengths 5 1.05M |
|---|
from numba import *
import numpy as np
@jit(object_(object_[:, :]))
def func(A):
for x in xrange(2):
for y in xrange(2):
items = A[x,y]
if items == None:
continue
for item in items:
print(item)
return A |
import os
import matplotlib.pyplot as plt
import numpy as np
from numba import njit
from connect4.Connect4Logic import Board
from tests.test_nn import get_board
plt.style.use('seaborn-colorblind')
def drawOddEvenThreats(data, title, ymax, save_as=None):
keys = sorted(data.keys(), key=lambda x: int(x.split("_")... |
import json
import argparse
try:
from cookielib import Cookie, LWPCookieJar
except ImportError:
from http.cookiejar import Cookie, LWPCookieJar
class EditThisCookieJsonFileException(Exception):
pass
def main(arg):
try:
with open(arg.input, 'rt') as json_file:
json_data = json.loa... |
import importlib
from unittest.mock import MagicMock, patch, PropertyMock
import pytest
from tools.testing import plugin, python_pytest
# this is necessary to fix coverage as these libs are imported before pytest
# is invoked
importlib.reload(python_pytest)
importlib.reload(plugin)
def test_pytest_cov_collect():... |
__author__ = 'Thomas Rueckstiess, ruecksti@in.tum.de'
from pybrain3.rl.learners.learner import ExploringLearner, DataSetLearner, EpisodicLearner
from pybrain3.rl.explorers.discrete.egreedy import EpsilonGreedyExplorer
class ValueBasedLearner(ExploringLearner, DataSetLearner, EpisodicLearner):
""" An RL algorithm... |
from django.shortcuts import render, redirect, get_object_or_404
from products.models import Product
from .models import CartProducts
from .utils import get_or_create_cart
# Create your views here.
def cart(request):
cart = get_or_create_cart(request)
template_name = 'carts/cart.html'
return render(reques... |
import numpy as np
import matplotlib.pyplot as plt
import numpy.linalg as la
file = open('ejercicios/01/numeros_20.txt')
x = []
y = []
for line in file.readlines():
nums = line.split()
x.append(float(nums[0]))
y.append(float(nums[1]))
x = np.array(x)
y = np.array(y)
def regresion(x,y):
S = np.power(... |
import re
from collections import defaultdict
def input():
lines = list(filter(None, open('day_07/input.txt').read().split('\n')))
top_bags = list(map(extract_top_bag, map(lambda x: '1 ' + x, lines)))
sub_bags = list(map(extract_sub_bags, lines))
bags_to_sub_bags = {
k[1]:set(v) for k, v in zip... |
#! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this wo... |
import inspect
import functools
import types
from types import FunctionType
import itertools
from typing import Type, Optional, get_type_hints, Callable
from fastapi.responses import JSONResponse
from pydantic import BaseModel, create_model
from .object_store import ObjectStore, IdModel
JSON_PRIMITIVE_TYPES = ["str"... |
import copy
from pathlib import Path
from catalyst.utils.config import load_config
from catalyst.utils.misc import merge_dicts
def parse_config_args(*, config, args, unknown_args):
"""Parse config and cli args.
Args:
config: dict-based experiment config
args: cli args
unknown_args: c... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.db import models as db
from django.utils.translation import ugettext_lazy as _
from lck.django.common.models import TimeTrackable
fro... |
from .utils import PermaTestCase
class APIViewsTestCase(PermaTestCase):
pass |
"""Fixtures for the CLI add tests"""
import json
from pathlib import Path
from typing import List
import pytest
@pytest.fixture(name="file_data")
def fixture_file_data(second_sample_vcf: Path, case_id: str, sample_tag_names: List[str]) -> dict:
"""Return a dictionary with file information"""
return {"path": ... |
"""module for actions that modify values"""
from typing import AsyncIterable, cast
from pyspark.sql.functions import last
from .step import Step
class ReplaceValues(Step):
name = "Replace Values"
desc = "Replace values in one or more columns with another value"
def do(self, workflow, etl_process):
... |
from string import ascii_lowercase
str = "good"
str = "".join([c for c in str if c.lower() in ascii_lowercase and c != c.upper()])
l = len(str)
perm = []
for i in range(l):
for j in range(l+1):
if str[i:j] != "":
perm.append(str[i:j])
strength1 = 0
for k, v in enumerate(perm):
print(k, l... |
__author__ = "Frédéric BISSON"
__copyright__ = "Copyright 2022, Frédéric BISSON"
__credits__ = ["Frédéric BISSON"]
__license__ = "mit"
__maintainer__ = "Frédéric BISSON"
__email__ = "zigazou@protonmail.com"
from .PDFToken import PDFToken
class TokenStack:
"""A token stack
A token stack which can be read or ... |
# Generated by Django 2.1 on 2018-11-17 06:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Key',
fields=[
... |
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from requests.auth import HTTPBasicAuth
from urllib.parse import urlencode, quote_plus
import random
import string
import requests
import jwt
import json
from moz_test... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
import math
import os
from functools import reduce
from operator import mul
import numpy as np # Lambdify requires numpy
import warnings
class _Lambdify(object):
""" See docstring of symengine.Lambdify """
# Note that... |
n = int(input())
a = []
mod = 998244353
for i in range(n):
a.append(int(input()))
a.sort()
|
##############################################################################
# Copyright (C) 2019, UW REACT
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above co... |
#*****************************************************************************************
# Content: base class that programs like Maya can utilize for creating and applying colors
# to objects.
#
#
# version: 0.5
# date: 10/10/2020
#
# dependencies = QT
#
# To do's:
# > Create 'reload' action for 'file... |
from __future__ import unicode_literals
import frappe
@frappe.whitelist()
def show_inprocess_template():
item=[]
doc=frappe.db.sql("""select quality_inspection_template_name from `tabQuality Inspection Template` where mfg_inspection = 0""",as_dict=1)
for i in doc:
j=i.get("quality_inspection_templa... |
from pyspark.sql import SparkSession
SEXO = {
2: 'Masculino',
4: 'Feminino'
}
ESCOLARIDADE = {
2: 'Lê e Escreve',
3: 'Ensino Fundamental Incompleto',
4: 'Ensino Fundamental Completo',
5: 'Ensino Médio Incompleto',
6: 'Ensino Médio Completo',
7: 'Superior Incompleto',
8: 'Superior ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
version = "4.0.9"
|
""" a peer's state (and transitions across states) """
_states_by_name = {
"LOOKING": 0,
"FOLLOWING": 1,
"LEADING": 2,
}
_states_by_num = {num: name for name, num in _states_by_name.items()}
class State(object):
LOOKING = _states_by_name["LOOKING"]
FOLLOWING = _states_by_name["FOLLOWING"]
LE... |
# Databricks notebook source
# MAGIC
# MAGIC %scala
# MAGIC println()
# MAGIC println()
# MAGIC println("Note: You can ignore the message 'Warning: classes defined within packages cannot be redefined without a cluster restart.'")
# COMMAND ----------
# MAGIC %scala
# MAGIC package com.databricks.training
# MAGIC obj... |
###############################################################################
# Copyright (c) 2017-2020 Koren Lev (Cisco Systems), #
# Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others #
# #
... |
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2014 Jonathan Labéjof <jonathan.labejof@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation fi... |
"""Favicon generator for Python."""
# Project
from favicons._generate import Favicons
from favicons._exceptions import (
FaviconsError,
FaviconNotFound,
FaviconColorError,
FaviconNotSupported,
)
|
# Дано предложение. Определить количество букв н, предшествующих первой запятой предложения.
# Рассмотреть два случая: известно, что запятые в предложении есть; запятых в предложении может не быть.
# -*- coding: utf-8 -*-
if __name__ == '__main__':
sentense = input("Введите предложение: ")
comma = int(... |
"""Implementation of sumtree for finite distribution sampling."""
import numpy as np
from typing import Optional, Tuple
class SumTree:
"""Implement a sum tree data structure.
A sum tree is a complete tree where the value of each node
is the sum of the values of its children.
"""
def __init__(self,... |
#!/usr/bin/python
# MusicPlayer, https://github.com/albertz/music-player
# Copyright (c) 2012, Albert Zeyer, www.az2000.de
# All rights reserved.
# This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
import os, sys
from glob import glob
os.chdir(os.path.dirname(__file__)... |
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure, io
from skimage.color import rgb2gray
image = io.imread("./images/geometry.png")
image_in_greyscale = rgb2gray(image)
# Find contours at a constant value of 0.8
contours = measure.find_contours(image_in_greyscale, 0.55)
# Display the ... |
from flask import abort
import requests
import contextlib
import hashlib
import hmac
import logging
import sqlite3
import uuid
INVALID_LEASE = "Invalid hub.lease_seconds (should be a positive integer)"
A_MINUTE = 60
A_DAY = A_MINUTE * 60 * 24
def parse_lease_seconds(value):
try:
lease_seconds = int(valu... |
from typing import Any
from typing import Dict
class BaseActionHandler:
def __init__(self, bot: 'PapikaAIBot') -> None:
self.bot = bot
def execute(self, slack_context: 'SlackContext', parameters: Dict[str, Any]) -> None:
raise NotImplementedError()
|
from re import X
import torch.nn as nn
class CLSTM(nn.Module):
# sample rate and embedding sizes are required model attributes for the HEAR API
sample_rate = 16000
embedding_size = 1024
scene_embedding_size = embedding_size
timestamp_embedding_size = embedding_size
def __init__(self):
s... |
#!/usr/bin/env python
#
# // SPDX-License-Identifier: BSD-3-CLAUSE
#
# (C) Copyright 2018, Xilinx, Inc.
#
import numpy as np
import xfmlp
import sys
import random
import argparse
import time
from test import GemmTest
def test_multiInstrv1(int_range, m, k, n, add_bias=False):
print ("test_multiInstrv1: %d %d %d %d"... |
'''Escreva um programa que leia um número n inteiro qualquer e mostre na tela
os n primeiros elementos de uma sequência fibonacci'''
print('=='*5)
print('Fibonacci')
print('=='*5)
n = int(input('Digite quantos termos você quer mostrar: '))
t1 = 0
t2 = 1
print('='*25)
print('{} → {}'.format(t1, t2), end='')
cont = 3
wh... |
from django_cradmin.viewhelpers import listbuilder
class AbstractSubjectOrPeriodPermissionGroupItemValue(listbuilder.itemvalue.TitleDescription):
template_name = 'devilry_cradmin/devilry_listbuilder/' \
'permissiongroup/subjectorperiodpermissiongroup-itemvalue.django.html'
def get_title(s... |
from .contents import * # noqa
|
#
# Data Structures and Algorithms COMP1002
#
# Python file to hold all sorting methods
#
def bubbleSort(A):
n = 0
is_sorted = False
while not is_sorted and n < len(A) - 1:
is_sorted = True
for i in range(len(A) - 1 - n):
if A[i] > A[i + 1]:
A[i], A[i + 1] = A[i ... |
import matplotlib
import glob
from re import match
from pylab import *
from scipy.stats import linregress
from random import random, shuffle
from mods.utils import *
from mods.seq import *
def pn(name):
return name[:name.find('_')]
def ps(sequence):
return pn(sequence.name())
def colordict(sequences):
... |
import asyncio
import configparser
import hashlib
import os
import shutil
import string
import time
from json import JSONDecoder
from aiohttp import test_utils
from hypothesis import given, settings
from hypothesis import strategies as st
import staging_service.app as app
import staging_service.globus as globus
impor... |
"""Implement some basic operations of SGD.
"""
####################################################
# Author: <Changyu Liu>shiyipaisizuo@gmail.com
# License: MIT
####################################################
from activation import *
def random_mini_batches(data, label, batch_size):
""" creates a list of r... |
'''
Error fixing in JSON files.
---
This class is mainly used to handle erroneous hgvs codes.
'''
import os
import json
from typing import Union, Tuple
from lib.constants import HGVS_ERRORDICT_VERSION
from lib.singleton import LazyConfigure
# Typing definitions for clearer type hints
ENTRY_ID = Union[str, int]
ERROR_E... |
import pytest
from chembl_webresource_client.new_client import new_client as Chembl
from mandos.model.apis.chembl_support.chembl_target_graphs import ChemblTargetGraphFactory
from mandos.model.apis.chembl_support.chembl_targets import TargetFactory
from mandos.model.apis.chembl_support.target_traversal import TargetTr... |
# Copyright 2020 Nielsen Global Connect.
#
# 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 ... |
# -*- coding: utf-8 -*-
"""This module contains various helper functions."""
import os
import sys
import contextlib
import logging
import pandas as pd
def load_dataframe():
"""Load the dataset into memory."""
df = pd.read_csv(os.path.join('data/sample_data.csv'),
index_col... |
import csv
from datetime import datetime
import os
import re
import sys
from .utils import calculate_md5
from .utils import human_readable
class Asset():
"""
Class representing a single asset under preservation.
"""
def __init__(self, filename, sourcefile, sourceline,
bytes=None, ti... |
import os
import time
from lexed.const import COMMANDS, CHAR_DICT
from lexed.line import Lines
from lexed.console import curses
from .clipboard import EditorClipboard
from .select import EditorSelect
from .mark import EditorMark
from .files import EditorFiles
from .lines import EditorLines
from .moves import EditorMo... |
from aws_cdk import (
App,
Stack,
RemovalPolicy,
Duration,
CfnOutput,
aws_lambda as _lambda,
aws_logs as logs,
aws_sns as sns,
aws_sns_subscriptions as subs,
)
from constructs import Construct
class SNSLambdaStack(Stack):
def __init__(self, app: App, id: str) -> None:
su... |
import logging
import log
import helper
import command_runner
REQUIRED_ATTRIBUTES = ['s3_bucket', 's3_endpoint', ]
ACTION = 'website deletion'
def set_command_line_options(subparsers):
"""
Command line options for s3 website deletion
:param subparsers: argparse - The parser object
"""
parser =... |
mod = 20201227
c = 10212254
d = 12577395
initial = 7
# 7 ^ k % mod = c
# 7 ^ x % mod = d
x = 1
for i in range(1,mod):
x = (x*7)%mod
if x == c:
k1 = i
if x == d:
k2 = i
print(pow(c,k2,mod))
print(pow(d,k1,mod))
|
# -*- coding: latin-1 -*-
"""
fragments - define text fragments in the document
"""
from domain.norm_document.model import Chapter, Section, Norm, Verifier
S1501 = Section(
identifier="15.01",
title="Informatiebeveiliging in leveranciersrelaties",
text="Doelstelling: De bescherming waarborgen van bedr... |
#!/bin/env python
# pylint: disable=unused-wildcard-import,wildcard-import,redefined-builtin
# pylint: disable=missing-docstring
from docs_conf.conf import * # noqa
|
"""Element family definitions."""
from siriuspy.namesys import join_name as _join_name
import pyaccel as _pyaccel
_family_segmentation = {
'B1': 30, 'B2': 36, 'BC': 34,
'QFA': 1, 'QDA': 1,
'QFB': 1, 'QDB1': 1, 'QDB2': 1,
'QFP': 1, 'QDP1': 1, 'QDP2': 1,
'Q1': 1, 'Q2': 1, 'Q3': 1, 'Q4': 1,
'SDA... |
#!/usr/bin/env python
from os.path import join, dirname
try:
from robot.libdoc import libdoc
except:
def main():
print("Robot Framework 2.7 or later required for generating documentation")
else:
def main():
libdoc(join(dirname(__file__), '..', 'CSVLibrary'), join(dirname(__file__), 'CSVLibra... |
from bs4 import BeautifulSoup
import icalendar
from datetime import datetime, timedelta
import json
import random
from pytz import timezone
def open_file_get_soup():
files = open("KFUPM _ Course Offering.html", "r")
soup = BeautifulSoup(files, "html.parser")
schedule(soup)
def days(i):
days_lis... |
{
'targets': [
{
'target_name': 'mysys',
'type': 'static_library',
'standalone_static_library': 1,
'includes': [ '../config/config.gypi' ],
'cflags!': [ '-O3' ],
'cflags_cc!': [ '-O3' ],
'cflags_c!': [ '-O3' ],
'cflags+': [ '-O2', '-g' ],
'cflags_c+': [ '-O2',... |
"""Reproduces the bug described in https://github.com/f-dangel/cockpit/issues/5."""
from backpack import extend
from torch import manual_seed, rand
from torch.nn import Flatten, Linear, MSELoss, Sequential
from torch.optim import Adam
from cockpit import Cockpit
from cockpit.quantities import Alpha, GradHist1d
from c... |
from dataclasses import dataclass, field
from typing import Optional, List
from dataclass_wizard import JSONWizard, json_field
from .restriction import Restriction
from .progress import Progress, Medals, CompetitiveRank
@dataclass
class Br:
level: int
division: int
streak: Optional[int]
@dataclass
class... |
"""
用Python3运行此程序,即可与Smart的机器助理聊天!
more on www.chenhongyi.cc/lab/
"""
import requests
user = input("Enter user name:")
print("Smart的机器助理:你好,"+user+"!我是Smart的机器助理")
while True:
s = input(user+":")
resp = requests.post("http://www.tuling123.com/openapi/api", data={
"key": "dfa21a126ed2468ca2b9f49d27d735... |
# Copyright 2016 Google Inc. 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... |
# -*- coding: utf-8 -*-
import socket
from threading import Thread
from src.GameRemoteClient import GameRemoteClient
from src.PacketParser import PacketParser
from src.DatabaseManager import DatabaseManager
from src.Logger import Logger
class GameLocalClient(Thread):
def __init__(self, serverIp, serverPort... |
import unittest
import json
from datetime import datetime, timedelta
from pytz import timezone
from togglcmder.toggl.builders.time_entry_builder import TimeEntryBuilder
from togglcmder.toggl.builders.project_builder import ProjectBuilder
from togglcmder.toggl.builders.tag_builder import TagBuilder
from togglcmder.tog... |
"""The radiotherm component."""
|
#!/usr/bin/env python3
import pygatt
from time import sleep
import ev3dev.ev3 as ev3
adapter = pygatt.GATTToolBackend()
m = ev3.MediumMotor('outA')
DELAY = 0.1
try:
adapter.start()
device = adapter.connect('F5:91:E3:32:23:39',address_type=pygatt.BLEAddressType.random)
device.char_write_handle(0x27, byt... |
import unittest
from DepthFunctions import F0, F1, F2, F3, function_from_id
# TODO Comment
class TestDepthFunctions(unittest.TestCase):
def test_function_from_id(self):
self.assertIsInstance(function_from_id(0), F0)
self.assertIsInstance(function_from_id(1), F1)
self.assertIsInstance(function_from_id(2), F2)
... |
# -*- encoding:utf-8 -*-
import torch.nn as nn
from uer.layers.synthesizer import DenseSynthesizer, RandomSynthesizer
from uer.layers.synthesizer import SYNT_TYPE_MAP
class SyntEncoder(nn.Module):
"""
Synthesizer encoder exploits 12 or 24 synthesizer layers to extract features.
"""
def __init__(self... |
#
# Copyright 2020 Antoine Sanner
# 2016, 2020 Lars Pastewka
#
# ### MIT license
#
# 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 ... |
from django import forms
from django.forms import ModelForm
from PartyPlay.models import Video
class UploadVideoForm(forms.Form):
video_name = forms.CharField(label="Name")
video_url = forms.CharField(label="URL")
from django.contrib.auth.models import User
|
# See: https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-no-implicit-reexport
from ._image import Preprocessing as Preprocessing
from ._image import preprocess_image as preprocess_image
from ._inference import predict_image as predict_image
from ._inference import predict_images as predict_images
f... |
from ..utils import DataikuException
from ..utils import DataikuUTF8CSVReader
from ..utils import DataikuStreamedHttpUTF8CSVReader
import json
import time
from .metrics import ComputedMetrics
from .ml import DSSMLTask
from .utils import DSSDatasetSelectionBuilder
class DSSAnalysisStepBuilder(object):
def __init__(... |
"""
Create Lumerical Process File (.lbr)
"""
# Set up path to modules. PDK-Generator/python needs to be in sys.path
import sys, os
proj_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if proj_path not in sys.path:
sys.path.append(proj_path)
from common.lumerical_lumapi import lumapi
from commo... |
from __future__ import absolute_import, division, print_function, unicode_literals
from amaasutils.random_utils import random_string
import datetime
from decimal import Decimal
import random
from amaascore.corporate_actions.corporate_action import CorporateAction
from amaascore.corporate_actions.dividend import Divid... |
from llvmlite import ir
import ctypes as ct
import struct
# indices into a box
TYPE = 0
SIZE = 1
DATA = 2
ENV = 3
# sizes of things
HASH_SIZE = 32
# all sorts of type aliases
i8 = ir.IntType(8)
i32 = ir.IntType(32)
i64 = ir.IntType(64)
f32 = ir.FloatType()
f64 = ir.DoubleType()
void = ir.VoidType()
func = ir.Functio... |
# from machine import Pin, UART
import machine
import numpy as np
# controlString is a 9-element np array:
# forward, backward, left, right, power, ..., ..., ..., ...
# Returns two element array (s,t) that is sent to motor to tell it how many degrees to turn and how much throttle to use
def readRemote(controlString):
... |
import sublime
import json
from ..lib import link_opener
def from_local_requests_error(body):
""" from_local_requests_error parses the body of a non-200 response
returned by our local requests library for a notification. If
one exists, it will create a sublime dialog.
"""
try:
data... |
dicts = {}
while True:
a = input().split(' ')
name = a[0]
if name == 'stop':
# dicts formatting
print("\n".join("{} -> {}".format(k, v) for k, v in dicts.items()))
break
number = int(a[1])
if name in dicts:
# add to dict's values or increase
dicts[name] += n... |
# decompyle3 version 3.3.2
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.8.1 (default, Jan 3 2020, 22:44:00)
# [GCC 8.3.0]
# Embedded file name: ulang\runtime\repl.py
# Size of source mod 2**32: 82682 bytes
import sys, cmd
from ulang.parser.core import Parser
from ulang.parser.lexer import lexer
from ulang... |
#!/usr/bin/env python3
from .helpers import stylize
class Label:
""" A class holding various methods for formatting GH Label information. """
def __init__(self, master, data):
self.master = master
for key in data.keys():
setattr(self, key, data[key])
def print_line(self):
... |
import sys
import os
def clean(file):
""" clean(file)
Abre e limpa um arquivo de texto
Entradas:
file: caminho para o arquivo a partir do arquivo que chamou a função
"""
tfile = os.path.join(sys.path[0], file)
fileToClean = open(tfile, "w")
fileToClean.write("")
fileToClean.cl... |
"""
Django settings for e_commerce project.
Generated by 'django-admin startproject' using Django 3.2.10.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os... |
import requests
from datetime import datetime
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
"""
PURPOSE: Get photo metadata, convert coords to real location, //push to google storage
"""
# how to call places API on an address
# https://maps.googleapis.com/maps/api/place/findplacefromtext/js... |
import unittest
class PythonSet(unittest.TestCase):
"""
A set is an unordered collection of UNIQUE elements.
You can think of them like dicts but keys only
"""
def setUp(self):
self.set1 = {3, 6, 3, 4}
self.set2 = {3, 6}
self.set3 = {3, 6, 4}
self.set4 = {5, 6}
self.set5 = {(1, 3), (2, 4)}
def test_... |
"""
Problem Statement
----------------
Given an arrays of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited num... |
"""
"""
# Created on 2014.10.21
#
# Author: Giovanni Cannata
#
# Copyright 2014, 2015, 2016, 2017 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Soft... |
import logging
from urllib.parse import urlparse, urlunparse
import numpy as np
import h5py
import zarr
import json
from zarr.meta import encode_fill_value
from zarr.storage import _path_to_prefix
from numcodecs import Zlib
import fsspec
lggr = logging.getLogger('h5-to-zarr')
chunks_meta_key = ".zchunkstore"
class ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# You would only use/need this script if using script_info {"type" = "method", "method" = "unload", "script_file" = "unload.py"}
# This gets called when the extension is uninstalled, or is reinstalled and before the nex extension runs. You should clean up here.
# If you ar... |
"""
Name: giExtractor util
Author: Chinedu A. Anene, Phd
"""
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
from tensorflow.keras.applications import inception_resnet_v2, inception_v3
from tensorflow.keras.applications import VGG16, ResNet50
from tensorflo... |
from Warehouse.Bin import Bin
from Warehouse.Inventory import Inventory
class Rack:
'''
Instantiation:
Rack(rack_no = int > 0, bin_count = int > 0)
Method Notes:
bins_a and bins_b are dicts of bins and accessed by bin_no as key
'''
_inventory = Inventory()
def __init__(self, rack_no, bin_count):
asser... |
#!/usr/bin python3
# Copyright 2021 Seonghun Noh
import argparse
import logging
import os
import io
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
import numpy as np
import h5py
import argparse
from tensorboardX import SummaryWriter
import matplotlib.pyplot as plt
import torch.nn... |
from CA import CA
if __name__ == "__main__":
# Create CA objects
img_path = "black.jpeg"
ca = CA(img_path)
res = ca.compute_ca()
print(f"Number of features: {len(res)}\nFeatures: {res}")
# Update the image
img_path = "coarse.png"
ca.update(img_path)
new_res = ca.compute_ca()
pr... |
import torch
from pytorch_lightning.callbacks import Callback
from src.utils import plot_spectrogram
class GanModelsGraphVisualizationCallback(Callback):
def __init__(self):
self.logged_graphs = False
def on_validation_batch_start(
self, trainer, pl_module, batch, batch_idx, datal... |
basis_Zs = {}
basis_Zs['ALA'] = [
["H", "N", "CA", "C"],
["O", "C", "CA", "N"],
["HA", "CA", "N", "C"],
["CB", "CA", "N", "C"], # ... improper
["HB1", "CB", "CA", "N"],
["HB2", "CB", "CA", "HB1"],
["HB3", "CB", "CA", "HB2"]
]#
basis_Zs['LEU'] = [
["H", "N", "CA", "C"], # improper .... |
#!/usr/bin/env python
import os
import numpy as np
import tensorflow as tf
import time
# config
GPU0 = '/gpu:0'
model_path = './shape_complete/train_mod/'
RESOLUTION = 64
class Shape_complete():
def __init__(self, verbose = False):
'''
Constructor of the Shape_complete class. Load the model from 'm... |
# Many Kansas City records are located at same coordinates because of anonymization which makes assessing scale difficult on a map. This file aggregates counts of ShotSpotter activations at a coordinate
import csv
# Get counts
counts = {}
with open('../data/raw/kansas-city-shotspotter-activations.csv', newline='') as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.