content stringlengths 5 1.05M |
|---|
from django.urls import path
from . import views
urlpatterns = [
# path for signing up a new user
# full path is auth/signup, but auth is already in the root urls (yatube)
path('signup/', views.SignUp.as_view(), name='signup')
]
|
# Code from Chapter 10 of Machine Learning: An Algorithmic Perspective (2nd Edition)
# by Stephen Marsland (http://stephenmonika.net)
# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with n... |
# ----------------------------------------
# Normalized Diversification
# NDiv loss implemented in Pytorch
# ----------------------------------------
import numpy as np
import torch
import torch.nn.functional as F
def compute_pairwise_distance(x):
''' computation of pairwise distance matrix
---- Input
-... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Assistant.nationality'
db.add_column('assistant', 'nation... |
#!/usr/bin/env python3
"""
Functions for converting string values containing numbers, or an iterable containing such
values to floating point or integer numbers (or a similar type of array of floating points
or integer numbers).
Programmed in Python 3.5.2-final.
"""
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
##########################################################################################################################
# Import
from queue import Queue
# Modules
from .promise import Promise
from .cycle import Cycle
################################################################################################... |
import os
from PyQt5.QtWidgets import QWidget, QGridLayout, QLabel, QLineEdit, QPushButton, QHBoxLayout, QGroupBox, QSizePolicy, \
QDoubleSpinBox, QCheckBox
from PyQt5.QtWidgets import QFileDialog, QSpinBox, QVBoxLayout
from .model import Model, Variable
from .utils import connect_input_and_button
class Configura... |
import logging
logging.basicConfig(level=logging.DEBUG)
import time, tempfile, os, socket
from unittest import skip
import zmq
from work_managers.zeromq.core import ZMQCore
# Amount of time to wait after executing setUp() to allow sockets to settle
SETUP_WAIT = 0.010
# Amount of time to wait prior to executing tea... |
# coding=utf-8
#import cPickle #python2
import pickle
import os
import cv2
from imutils import contours #pip install web.py==0.40-dev1
from e import ContourCountError, ContourPerimeterSizeError, PolyNodeCountError
import numpy as np
import settings
#from settings import ANS_IMG_THRESHOLD, CNT_PERIMETER_THRESHOLD, CH... |
import threading
import time
class WorkerThread(threading.Thread):
def __init__(self, name, callback):
super(WorkerThread, self).__init__(name=name)
self.callback = callback
self.stop_event = threading.Event()
def run(self):
while not self.stop_event.is_set():
self... |
from operator import attrgetter
from unittest.mock import patch
from django.conf import settings
from django.contrib.auth.models import Group
from django.http.response import HttpResponseForbidden, HttpResponseBadRequest, HttpResponseBase, \
HttpResponseNotAllowed
from django.test import TestCase
from django.urls ... |
#!/bin/python3
import requests
import pkg_resources
import imageio
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import numpy as np
import os
from PIL.PngImagePlugin import PngImageFile, PngInfo
def flowkey_dl(url):
#url=os.path.dirname(url)+'/{}.png'
hashstring=strip_url(url)
try:
... |
# It's not possible to delete a global var at runtime in strict mode.
gvar = 1
del gvar
gvar = 2
def __main__():
print("in __main__")
global gvar
# In the current implementation, TypeError is thrown. This is considered
# an implementation detail and may change later to e.g. RuntimeError.
try:
... |
class Solution:
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
ht = dict() # Hash table
result = list()
for char in p:
if ht.get(char):
ht[char] += 1
else:
ht[... |
import argparse
import os
import re
class ShowUsageException(Exception):
pass
def dir_path(s):
if os.path.isdir(s):
return s
else:
raise ShowUsageException(f'"{s}" is not a directory')
def origin_directory_pair(s):
try:
origin, path = s.split(':')
except ValueError:
... |
# Copyright (c) 2012 Santosh Philip
# =======================================================================
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
# http://opensource.org/licenses/MIT)
# =======================================================================
"""use epbunc... |
from browser import document
def hash(name):
total = 0
for char in name:
total *= 10
total += ord(char)
return 10 - (total % 11)
def update():
result = hash(document['name'].value)
document['result'].value = 'You are a %s/10' % result
document['name'].bind('onKeyDown', ... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Unit tests for sorting.py functions."""
from __future__ import print_function
from __future_... |
# ================================================================================== #
# __init__.py - This file is part of the yfrake package. #
# ================================================================================== #
# ... |
# 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 ... |
#!/usr/bin/env python
# Copyright (C) 2012-2014 Bastian Kleineidam
"""
Script to get a list of gocomics and save the info in a JSON file for further processing.
"""
from __future__ import print_function
import codecs
import re
import sys
import os
import requests
sys.path.append(os.path.join(os.path.dirname(__file__), ... |
# -*- coding: utf-8 -*-
r"""
Grid View Adapter for partitions
**Grid View partition operations:**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~PartitionGridViewAdapter.cell_to_display` | Static method for typecasting cell content to widget display value
:meth:`~Partition... |
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
# Imports from this application
from app import app
from .predictions import inputs, row1... |
from abc import ABCMeta, abstractmethod
import numpy as np
from sklearn.mixture import GaussianMixture
class Clustering(metaclass=ABCMeta):
def __init__(self, DS, levels=1, random_state=None):
self.DS = DS
self.name = DS.name
self.columns = DS.D.columns
self.X = self.DS.D.as_matri... |
from numpy.testing import assert_raises
from configurator.dialogs import DialogBuilder, Dialog
class TestDialogBuilder(object):
def test_rules_constraints_one_required(self, email_client):
assert_raises(ValueError, DialogBuilder,
email_client.var_domains, email_client.sample)
... |
# from database import db
#from geoalchemy2 import Geometry
#from sqlalchemy import Column
from sqlalchemy.dialects.postgresql.json import JSONB
from app import db
class AWSInstance(db.Model):
__tablename__ = 'aws_instances'
instance_id = db.Column(db.String(30), primary_key=True)
instance_m... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/669/A
n = int(input())
print((n//3)*2 if n%3==0 else (n//3)*2+1)
|
HASH_TAGS = "#joke #programming #programmingjoke"
|
import sys
sys.path.append('../main')
import keras
import numpy as np
from util94 import concat,flatten,n_hot_decoder,load_input2idx, load_label2idx,get_input_set,get_label_set
from util94 import load_text,load_text_hierarchical,get_stopwords,remove_stopwords
stopwords_path = '../train_data/law_stopwords.txt'
path_30w ... |
"""Module to facilitate a generic interface to running long tasks in separate
threads.
"""
# Copyright 2018 Matthew A. Clapp
#
# 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:/... |
from typing import Dict, List
from data_reader.binary_input import Instance
class learner(object):
"""Base class for initial learning methods.
Defines the bare-minimum functionality for initial learning
strategies. Specified learning algorithms can create wrappers
around the underlying methods.
... |
'''Module implements methods to embed contour chain codes as text'''
def chaincodes_to_documents(chaincodes):
'''Converts chain codes to documents
Args:
chaincodes (list of list of int)
>>> chaincodes_to_documents([[1,2,2,3], [1,3,4]])
['12_1 23_2 31_1', '13_1 34_1 41_1']
'''
documents = []
... |
from django import forms
from .models import *
class TeilnahmeEintragenFormular(forms.ModelForm):
class Meta:
model = Zeile
fields = ['autor_name', 'text']
|
# -*- coding: utf-8 -*-
from copy import deepcopy
from loop_index.loop_index import LoopIndex
class DecisionMatrix:
"""
This class is a matrix containing actions at given coordinates. Its axes
are tuplists of conditions (callable objects returning boolean values). A
coordinate is true if the condition... |
import numpy as np
import os.path
import transforms3d.quaternions as txq
import argparse
def params():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataroot', type=str, default='../datasets/7Scenes', help='dataset root')
return parser.pars... |
import os
import cv2
import argparse
import torch as t
from utils import detect_frame, load_mask_classifier
from skvideo.io import FFmpegWriter, vreader, ffprobe
from FaceDetector import FaceDetector
from torchvision.transforms import *
from pathlib import Path
from torch.nn import *
from tqdm import tqdm
arg = argpa... |
import json
import logging; log = logging.getLogger()
class Emotes(object):
def __init__(self, bot):
self.bot = bot
with open(f"data/emotes.json", "r", encoding="utf8", errors="ignore") as f:
self.emotes = json.load(f)
if bot.config.dev:
self.emotes.update(... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-03-04 21:37
from django.db import migrations
def forwards(apps, schema_editor):
from manabi.apps.twitter_usages.harvest import tweet_is_spammy
ExpressionTweet = apps.get_model('twitter_usages', 'ExpressionTweet')
for expression_tweet in Expr... |
from . import AstChecker
class CheckOsSystemCalls(AstChecker):
"""Checks for any calls to os.system and suggests to use subprocess.check_call instead."""
def _warn_about_os_system(self, node):
self.warn("Consider replacing os.system with subprocess.check_output,"
" or use sublime's ... |
# See what happens when we make __get__ and __set__ things other than functions...
# TODO add some with __del__
import sys
import traceback
class CallableGet(object):
def __call__(*args):
print "callable get", map(type, args)
class CallableSet(object):
def __get__(*args):
print "__get__", map(... |
import argparse
import json
from pathlib import Path, PurePosixPath
import jinja2
import yaml
def snake_to_pascal_case(input_string: str):
split_string = input_string.lower().split('_')
return ''.join([i.title() for i in split_string])
def render_template(template_file, job_types, env):
output_file = t... |
# Copyright 2014
# The Cloudscaling Group, 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... |
"""`TypedDict`"""
from typing import TypedDict
Movie = TypedDict("Movie", {"name": str, "year": int})
movie: Movie = {"name": "Blade Runner", "year": 1982}
movie_bad: Movie = {"name": "Blade Runner", "year": 1982, "director": "Scott"}
director = movie_bad["director"]
toy_story = Movie(name="Toy Story", year=1995)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Christof Schöch, 2016-2021.
"""
This is the main script that controls the coleto text collation pipeline.
For more information, please see the README.md and HOTWO.md files.
An API reference can be found in the docs folder.
"""
# === Imports ===
... |
from __future__ import unicode_literals
from frappe import _
def get_dashboard_data(data):
return {
'fieldname': 'company'
}
|
# -*- coding: utf-8 -*-
"""
Code for selecting top N models and build stacker on them.
Competition: HomeDepot Search Relevance
Author: Kostia Omelianchuk
Team: Turing test
"""
from config_IgorKostia import *
import os
import pandas as pd
import xgboost as xgb
import csv
import random
import numpy as np
import scipy ... |
import heapq
import inspect
import sys
"""
Data structures useful for implementing Best-First Search
"""
class FrontierPriorityQueueWithFunction(object):
'''
FrontierPriorityQueueWithFunction class implement a search frontier using a
PriorityQueue for ordering the nodes and a set for
constant-time c... |
import atexit
def my_cleanup(name):
print('my_cleanup(%s)' % name)
atexit.register(my_cleanup, 'first')
atexit.register(my_cleanup, 'second')
atexit.register(my_cleanup, 'third')
|
"""
Functional tests for ``flocker.common.script``.
"""
from __future__ import print_function
import os
import sys
from json import loads
from signal import SIGINT
from zope.interface import implementer
from eliot import Logger, Message
from eliot.testing import assertContainsFields
from twisted.trial.unittest imp... |
import torch.nn as nn
import math
from torch.hub import load_state_dict_from_url
__all__ = ['MobileNetV3']
model_url = ''
class MobileNetV3(nn.Module):
def __init__(self, num_classes=1000, init_weight=True, pretrain=True):
super(MobileNetV3, self).__init__()
# setting of inverted residual blocks... |
"""
Hosting Jupyter Notebooks on GitHub Pages
Author: Anshul Kharbanda
Created: 10 - 12 - 2020
"""
import os
import jinja2
import logging
from .config import Configurable, load_config_file
from . import builders
from . import loaders
# Default config file name
config_file = './config.py'
class Site(Configurable):
... |
#!/bin/python3
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
# Check if number is prime or not
def prime_check(number):
if number == 2:
return True
for pointer in range(2, int(number ** 0.5) + 1):
... |
from django.test import TestCase
from django.core.urlresolvers import reverse
from pkg_resources import parse_version
from cartoview.version import get_current_version
import requests
from geonode.urls import api
import json
class CartoviewHomeViewTest(TestCase):
def test_view_url_exists_at_desired_location(self... |
from __future__ import absolute_import
from udsoncan import DataIdentifier, Routine, Units
from test.UdsTest import UdsTest
class TestDefinitions(UdsTest):
def test_data_identifier_name_from_id(self):
for i in xrange(0x10000):
name = DataIdentifier.name_from_id(i)
self.assert... |
def variance(data):
n = len(data)
mean = sum(data) / n
deviations = [(x-mean) **2 for x in data]
var = sum(deviations) / n
return var
|
#!/usr/bin/env python
import threading
import signal
import sys
import time
import subprocess
import os
import os.path
import argparse
def signal_handler(signal, frame):
print 'You pressend CTRL+C, data is flushed into database/file...'
switchThread.running = False
switchThread.join()
formatString =... |
from setuptools import setup, find_packages
NAME = 'rboost'
VERSION = '0.2.0'
AUTHOR = 'SimoneGasperini'
AUTHOR_EMAIL = 'simone.gasperini2@studio.unibo.it'
REPO_URL = 'https://github.com/SimoneGasperini/rboost.git'
PYTHON_VERSION = '>=3.8'
def get_requirements():
with open('./requirements.txt', 'r') as f:
... |
from pytorch_lightning import LightningDataModule
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.dataset import random_split
from torchvision.datasets import ImageFolder
import os
import sys
sys.path.append('.')
from utils.ImageFolderSplit import ImageFolderSplitter, DatasetFromFilename
class... |
#
# Copyright (c) SAS Institute 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 w... |
#!/usr/bin/env python
# encoding: utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2015 CNRS
#
# 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 limitat... |
def factorial(count):
if num == 1:
return 1
elif num == 0:
return 0
else:
return num * factorial(num - 1)
def fibonacci(num):
if num < 1:
print('输入有误')
return -1
elif num == 1 or num == 2:
return 1
else:
return fibonacci(num - 1) + fibonacci(num - 2)
count = 0
def hanoi(n, x, y ,z):
global count... |
"""A module to store some results that are parsed from .txt files."""
import os
from configparser import ConfigParser
from types import SimpleNamespace
import pandas as pd
import numpy as np
from skm_pyutils.py_table import list_to_df
from dictances.bhattacharyya import bhattacharyya
from .main import main as ctrl_... |
#!/usr/bin/env python3
from codekit import eups
def test_git_tag2eups_tag_prefix():
"""Numeric tags should be prefixed with 'v'"""
eups_tag = eups.git_tag2eups_tag('15')
assert eups_tag == 'v15'
# one `v` is enough
eups_tag = eups.git_tag2eups_tag('v15')
assert eups_tag == 'v15'
def test_... |
from azure.mgmt.dns import DnsManagementClient
from azure.identity import ClientSecretCredential, DefaultAzureCredential
from datetime import datetime
import argparse
import json
import os
parser = argparse.ArgumentParser(
description="Update Azure DNS record based on current public IP"
)
parser.add_argument("--co... |
# Copyright (c) 2014-2021, Manfred Moitzi
# License: MIT License
from typing import BinaryIO, cast, TextIO, List, Optional
import zipfile
from contextlib import contextmanager
from ezdxf.lldxf.validator import is_dxf_stream, dxf_info
CRLF = b"\r\n"
LF = b"\n"
class ZipReader:
def __init__(self, zip_archive_name... |
import get_covid19_data
import discord
from discord.ext import commands
import json, hcskr
import datetime
from variable import *
from embed.help_embed import *
import get_covid19_data
import hcskr
result = ''
class selfcheck(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(... |
import json
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - (
(today.month, today.day) < (born.month, born.day)
)
def filters_user(params):
kwargs = {}
if type(params) is str:
params = json.loads(params)
if 'same_sex' ... |
# Copyright 2012-2015 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 ac... |
# © 2021 Nokia
#
# Licensed under the Apache license, version 2.0
# SPDX-License-Identifier: Apache-2.0
"""Datacollector API resources."""
import json
from datetime import datetime
from flask import Flask, Response, jsonify, request
from datacollector.api.api_collector_handler import CollectorHandler
app = Flask(__n... |
import unittest
import parameterized
import numbers
import openproblems
from openproblems.test import utils
utils.ignore_numba_warnings()
@parameterized.parameterized.expand(
[
(task, dataset, method)
for task in openproblems.TASKS
for dataset in task.DATASETS
for method in task.... |
"""Shipping JPEG 2000 files.
These include:
nemo.jp2: converted from the original JPEG photo of the aftermath of NEMO,
the nor'easter that shutdown Boston in February of 2013.
goodstuff.j2k: my favorite bevorage.
"""
import pkg_resources
def nemo():
"""Shortcut for specifying path to nemo.jp2.... |
"""ResNets, implemented in PyTorch."""
# TODO: add Squeeze and Excitation module
from __future__ import division
__all__ = ['get_resnet', 'ResNetV1', 'ResNetV2',
'BasicBlockV1', 'BasicBlockV2',
'BottleneckV1', 'BottleneckV2',
'resnet18_v1', 'resnet34_v1', 'resnet50_v1', 'resnet101_v1',... |
from sqlalchemy.orm import Session
import random
class RoutedSession(Session):
def get_bind(self, mapper=None, clause=None):
if self._flushing:
engine = api().get_engine(True)
return engine
else:
engine = api().get_engine()
return engine
class RoutedSessionMaker(object):
Mode_RoundRobin = 1 << 0
... |
# ---------------------- Packages
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
import pandas as pd
import psycopg2
# --------------------- Function
def eBayscrapper_remove_duplicates(phone_model):
"""Function to drop duplicate and null rows."""
... |
"""Implementation of the function command."""
from pathlib import Path
from typing import Union
from mcipc.rcon.client import Client
__all__ = ['function']
def function(self: Client, name: Union[Path, str]) -> str:
"""Runs the given function."""
return self.run('function', name)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-23 09:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Invoice... |
# -*- coding: utf-8 -*-
# Python script to remove class from cs:style in dependents
# Author: Rintze M. Zelle
# Version: 2013-03-29
# * Requires lxml library (http://lxml.de/)
import os, glob, re, inspect
from lxml import etree
# http://stackoverflow.com/questions/50499
folderPath = os.path.dirname(os.path.abspath(i... |
from .base import BaseRedisClient
class SMSCodeRedis(BaseRedisClient):
"""full key: sms_code:{key}"""
DB = 1
PREFIX_KEY = 'sms_code'
|
# pylint: disable=too-many-function-args
import os
import numpy as np
import pickle
from PIL import Image
import torchvision as V
from .. import configs
def getDataset(kind: str = 'classification'):
if kind == 'classification':
return __get_classification_dataset()
else:
raise NotImplementedE... |
#!/usr/bin/env python
from __future__ import print_function
import subprocess
import json
import os
import dateutil.parser
import requests
from datetime import datetime
from itertools import izip
import pytz
import argparse
parser = argparse.ArgumentParser(description="")
parser.add_argument('--all', action='store_true... |
# -*- coding: utf-8 -*-
from model.group import Group
from sys import maxsize
def test_test_add_group(app):
old_groups = app.group.get_group_list()
group = Group(name="Python Group", header="This is the Logo", footer="Here we have a group footer")
app.group.create_g(group)
assert len(old_groups) + 1 =... |
import networkx as nx
import matplotlib.pyplot as plt
# BA scale-free degree network
# generalize BA network which has 20 nodes, m = 1
BA = nx.random_graphs.barabasi_albert_graph(20, 1)
# spring layout
pos = nx.spring_layout(BA)
nx.draw(BA, pos, with_labels = False, node_size = 30)
# nx.draw(BA,pos)
plt.show() |
salario = float(input("Digite seu salário: "))
aumento = salario * 0.15
salarioAumento = salario + aumento
print(f'O valor do seu aumento é R${aumento} logo o valor do seu novo salário é R${salarioAumento}') |
# Copyright 2020 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... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_llist(self):
if self.head == None:
print("Linked list is empty")
else:
temp = self.head
while... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
# condition to be cousin: (1)... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Plan'
db.create_table('plans_plan', (
('id', self.gf('django.db.models.fields.Au... |
# ------------------------------------------------------------------------
# Class for reading/writing files
# ------------------------------------------------------------------------
import bpy
import csv
from os import listdir, read
from os.path import isfile, join
from . import calc
from . import data
# -----... |
from zipline.api import attach_pipeline, pipeline_output
from zipline.pipeline import Pipeline
from zipline.pipeline.data import USEquityPricing
from zipline.pipeline.factors import SimpleMovingAverage
def initialize(context):
pipe = Pipeline()
attach_pipeline(pipe, 'example')
sma_short = SimpleMovingAv... |
from time import sleep
from PyQt5.QtCore import QThread, pyqtSlot, pyqtSignal
from PyQt5.QtWidgets import QComboBox
class TSpacecraftSelect(QThread):
selection_changed = pyqtSignal(str, int)
def __init__(self):
super().__init__()
self.spacecraftCBs = []
def add_sc(self, combobox: QCom... |
# pyright: reportMissingImports=false
import os
import clr
import sys
import time
import platform
from PIL import Image
from .CypressFX import FX2
from .definitions import RSC_DIR, LIB_DIR, LED_WHITE
# load appropriate dll
(bits, linkage) = platform.architecture()
if bits == "64bit":
sys.path.append(os.path.join(... |
import xmltodict
import logging
import itertools
import sys
import os
import json
import pandas as pd
import numpy as np
import pywaterml.waterML as pwml
from datetime import datetime
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.core import serializers
from... |
import sys
inputfile = sys.argv[1]
outputfile = sys.argv[2]
if __name__ == "__main__":
with open(inputfile, "r") as f:
l, r = f.readlines()
l = float(l)
r = float(r)
b = r - l
with open(outputfile, "w") as f:
f.writelines([str(b)])
|
# coding: utf-8
# flake8: noqa
from __future__ import absolute_import
# import models into model package
from swagger_server.models.result import Result
from swagger_server.models.result_chains import ResultChains
from swagger_server.models.result_in_complex_with import ResultInComplexWith
from swagger_server.models.r... |
from dataclasses import dataclass
from collections import Counter
from typing import ClassVar, TypeAlias
ELEMENT: TypeAlias = str # represents on character string
PAIR: TypeAlias = tuple[ELEMENT, ELEMENT]
RULES: TypeAlias = dict[PAIR, ELEMENT]
POLYMER: TypeAlias = Counter[PAIR]
@dataclass
class Polymer:
templat... |
"""Decorators that simplify interacting with the FriendlyArgs framework"""
from functools import update_wrapper
import sys
import logging
def main():
"""Decorates the primary entry-point function for your command line
application"""
def _main_decorator(func):
log = logging.getLogger(__name__)
... |
import numpy as np
from numpy.random import randn
import unittest
from niwqg import CoupledModel
from niwqg import QGModel
class QGNIWTester(unittest.TestCase):
""" A class for testing the QGNIW kernel (real and complex 2d ffts)
Note: 1d plane wave pass test with machine precision
2d (slanted... |
import socket
import threading
from os import system
from datetime import date
PORT = 65432
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
clients = []
def start():
server.listen()
print(f"[Server] Listening on {SERVER}\n")
while True:
conn, addr = server.accept() # wa... |
from django.urls import path, re_path
from . import views
urlpatterns = [
path('invoice-list-api/', views.invoice_list_api ),
path('invoice-list/', views.InvoiceList.as_view(), name='invoice_list' ),
path('invoice-list-unpaid/', views.UnpaidInvoice.as_view(), name='unpaid_invoice_list' ),
path('invoice... |
import sys
import logging
import requests
from PIL import Image
def load_pil_image(path):
if path.startswith("http"):
path = requests.get(path, stream=True).raw
else:
path = path
image = Image.open(path).convert("RGB")
return image
def setup_logging(log_level: str = "INFO"):
stdo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.