content stringlengths 5 1.05M |
|---|
"""
Models for mail
"""
from django.contrib.auth.models import User
from django.db import models
from financialaid.models import FinancialAid
from micromasters.models import TimestampedModel
from search.models import PercolateQuery
class FinancialAidEmailAudit(TimestampedModel):
"""
Audit table for the Finan... |
import numpy as np
import os
from costants import \
EXTRACTION_DPI, \
TEXT_FOLDER, \
TABLE_FOLDER, \
MAX_NUM_BOXES, \
MIN_SCORE
from personal_errors import InputError, OutputError
import errno
import tensorflow as tf
from PIL import Image
from alyn import deskew
import logging
from logger import Tim... |
# -*- coding: utf-8 -*-
from pokemongo_bot.event_manager import EventHandler
from pokemongo_bot.base_dir import _base_dir
import json
import os
import time
import discord_simple
import thread
import re
from pokemongo_bot.datastore import Datastore
from pokemongo_bot import inventory
from chat_handler import ChatHandler... |
import random
a=int(input("Enter the stating range of the number : "))
b=int(input("Enter the Ending range of the number : "))
x = random.randint(a,b)
print("")
y=int(input("The Correct Number is : "))
t=0
while(t==0):
y=int(input("The Correct Number is : "))
if(x<y):
print("")
print("oops! w... |
#!/usr/bin/env python
"""
.. py:currentmodule:: FileFormat.test_ExportedSpectrum
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
Tests for module `ExportedSpectrum`.
"""
# Script information for the file.
__author__ = "Hendrix Demers (hendrix.demers@mail.mcgill.ca)"
__version__ = ""
__date__ = ""
__c... |
import inspect
import pandas as pd
def get_info(function):
arguments = inspect.getfullargspec(function)[0]
class_name, function_name = function.__qualname__.split(".")[-2:]
if "self" in arguments:
raise ValueError("all transformations should be static functions")
return class_name, function_... |
##############################################################################
# Copyright (c) 2017, Rice University.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions ... |
from src.sentiment import sentiment
"""neutral rew"""
text = """
average facilities need overhaul feel dated, service ok. reason stay good rate need central location
"""
def test_neutral():
print("Test 3 - ", sentiment(text, '../src/algos'))
return sentiment(text, '../src/algos')[0]
|
# coding: utf-8
"""
"""
import secrets
import pytest
from sampledb import logic
from sampledb.logic.authentication import _validate_password_hash
from sampledb.logic.component_authentication import add_own_token_authentication, add_token_authentication, \
get_own_authentication, remove_own_component_authenticatio... |
# -*- coding: cp1252 -*-
#!/usr/bin/tclsh
################################################################################
# #
# Copyright 1997 - 2019 by IXIA Keysight #
# All Rights Reserved. ... |
from flask import Flask, request, abort
from state_manager import StateManager
app = Flask(__name__)
@app.route('/calculate', methods=['POST'])
def calc():
try:
print('Server received ' + str(request.json))
resp = StateManager.process_request(request.json)
print('Server returned ' + str(res... |
from __future__ import division, absolute_imports, print_function
"""
openmoltools wrapper for packmol ? https://github.com/choderalab/openmoltools
"""
def oesolvate(solute, density=1.0, padding_distance=10.0,
distance_between_atoms=2.5,
solvents='[H]O[H]', molar_fractions='1.0',
... |
saisie_chiffre = input("Saisir le chiffre1:")
chiffre1 = int(saisie_chiffre)
saisie_chiffre = input("Saisir le chiffre2:")
chiffre2 = int(saisie_chiffre)
def factoriel(chiffre):
resultat = 1
liste = range(chiffre,0,-1)
liste = list(liste)
#print(liste)
for elem in liste:
resultat = resultat... |
# -*- coding: utf-8 -*-
import sys
sys.path.insert(0, '../preprocessing')
import csv
import json
import os
from tweet import sanitize
with open('sanders/corpus.csv', 'r') as corpus:
reader = csv.reader(corpus, delimiter=',', quotechar='"')
with open('sanders/tweets.txt', 'w') as tweets:
with op... |
from numbers import Real
class ProbDict(dict):
"""A dictionary serving as a probability measure."""
def __init__(self, items = None):
"""Create a dictionary from iters.
If items can't be fed to a dictionary, it will be interpreted as a
collection of keys, and each value will defa... |
from FreeTAKServer.model.ExCheck.Checklists.checklistTask import checklistTask
class checklistTasks:
def __init__(self):
self.checklistTask = []
self.__count = 0
def setchecklistTask(self, checklistTaskobj):
if isinstance(checklistTaskobj, checklistTask):
self.checklistTask.a... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-18 18:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('team', '0001_initial'),
]
operations = [
migrations.AlterField(
m... |
import requests, re
from bs4 import BeautifulSoup
from Model import Project, UsersProject
from tool import log as _l
log = _l("PARSER", "parser.log")
def write_db(f):
def wrapper(*args, **kwargs):
result = f(*args, **kwargs)
mutation = UsersProject.custom_insert(result)
return mutation
... |
import keras
import logging
import numpy as np
import tensorflow as tf
from collections import OrderedDict, deque
from keras.layers import Input, Dense, Lambda, Dropout, Dot, Permute, Reshape, Embedding, Concatenate, Multiply
from keras.models import Model, load_model
import os
import sys
sys.path.append('../utils... |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep t... |
from django.urls import path
from .views import create_post, view_post, edit_post, delete_post
app_name = 'post'
urlpatterns = [
path('create', create_post, name='create'),
path('<uuid:pk>', view_post, name='view_post'),
path('<uuid:pk>/edit', edit_post, name='edit_post'),
path('<uuid:pk>/delete', dele... |
from typing import List, Set, Tuple
import libcst as cst
from libcst import MetadataWrapper
from libcst.metadata import CodePosition, CodeRange, PositionProvider
def is_whitespace_node(node: cst.CSTNode) -> bool:
return isinstance(
node, (cst.BaseParenthesizableWhitespace, cst.EmptyLine, cst.TrailingWhit... |
"""
APNS Notification platform.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.apns/
"""
import logging
import os
import voluptuous as vol
from homeassistant.helpers.event import track_state_change
from homeassistant.config import load_yaml_conf... |
from functools import partial
from pipe import select, where
from pydash import chunk
from pydash import filter_ as filter
from pydash import flatten, get, omit
from .primitives import parallel, pipeline, scatter
__all__ = (
"parallel",
"scatter",
"pipeline",
"partial",
"select",
"where",
... |
"""
Crop box
========
Crop atoms within a box or, alternatively, the inverse.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from . import base
from . import _filtering
class CropBoxFilterSettings(base.BaseSettings):
"""
Settings for the crop box filter
"""
... |
"""
Check that bitstream doesn't change between versions
"""
import cfg
from TestSuite import runTests, SummaryType, TestUtils as TU
import re
import operator as op
def main():
seqs = cfg.sequences
seq_names = cfg.class_sequence_names
base_v = 5
new_v = base_v + 1
outname = f"kvz_conf_check_v{n... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch import Tensor
import numpy as np
from... |
'''
module handles config
'''
import os
import sys
import configparser
from xdg.BaseDirectory import (xdg_data_home, xdg_config_home, xdg_cache_home)
class SaurConfigError (Exception):
'''Exception for when an error occurs within the SaurConfig class.'''
def __init__ (self, message, errorcode=None):
su... |
#/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from collections import OrderedDict
def slack_post(token, channel, blind=False):
'''Post a slack message possibly with a picture. Prepare a function that
will be called later by the main script.'''
slack_api_url = 'https://slack.com/api/{}'
... |
import pytest
from lorenz import generate_L96
import numpy as np
import numpy.random as rd
from tools import *
from pytest import approx
import os
# =========================================================
# Set up code
# =========================================================
N = 1000
t = np.linspace(0, 6 * np.pi,... |
def isPrime(num):
''' isPrime determines if num is prime
argument
-- num : int
return
-- boolean
'''
if num < 2:
return False
elif num in [2,3]:
return True
elif num % 2 == 0:
return False
else:
upper_limit = int(num ** 0.5) + 1
... |
from pyleap import Rectangle, window, Line, Polygon, Circle, Text, repeat, run
bg = Rectangle(0, 0, window.w, window.h, "white")
def draw(dt):
window.clear()
bg.draw()
window.show_axis()
Rectangle(10, 10, 300, 200, "#00ff0080").stroke()
Line(100, 100, 600, 100, 100, 'pink').draw()
Poly... |
from bluebottle.activities.messages import ActivityRejectedNotification, ActivityCancelledNotification, \
ActivitySucceededNotification, ActivityRestoredNotification, ActivityExpiredNotification
from bluebottle.test.utils import NotificationTestCase
from bluebottle.time_based.tests.factories import DateActivityFac... |
# --------------------------------------------------------------------------
# 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 may cause... |
from sqlalchemy import Column, Boolean, Text, Integer, ForeignKey
from sqlalchemy.orm import relationship
from db_conf import Base
class DiagInfo(Base):
__tablename__ = "Diagnostics"
id = Column('id', Integer, primary_key=True, autoincrement=True)
dg_findings = Column('findings', Text)
dg_custcomp =... |
from .generic_wrappers import * # NOQA
from .lambda_wrappers import action_lambda_v1, observation_lambda_v0, reward_lambda_v0 # NOQA
from .multiagent_wrappers import agent_indicator_v0, black_death_v2, \
pad_action_space_v0, pad_observations_v0 # NOQA
from supersuit.generic_wrappers import frame_skip_v0, color_redu... |
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
""" Module with methods for notifications on people mentions."""
import re
from collections import defaultdict
from collections import namedtuple
from logging import getLogger
from email.utils import parsea... |
#KNN_classify()
import numpy as np
from math import sqrt
from collections import Counter
def KNN_classify(k,X_train,y_train,x):
assert 1<=k<=X_train.shape[0],'k must be valid'
assert X_train.shape[0]==y_train.shape[0],\
'the size of X_train must equal to the size of y_train'
assert X_train.shape[1]... |
# 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... |
# Parse config files
configfile: "config.json"
# Parse the required files and parameter
# Parse the required files
GENOME = config["resources"]["reference"]
REF_INDEX = config["resources"]["index_ref"]
BAMDIR = config["resources"]["bam"]
# Parse the tools
GRAPHTYPER = config["tools"]["Graphtyper"]
SAMTOOLS = config... |
import task
import deit
import deit_models
import torch
import fairseq
import os
from fairseq import utils
from fairseq_cli import generate
from PIL import Image
import torchvision.transforms as transforms
from data_aug import build_data_aug
def init(model_path, beam=5):
model, cfg, task = fairseq... |
import numpy as np
import argparse
import os
import glob
from paths import GPU_DATASETS
def np_flat_map(src, func):
return np.concatenate([func(s) for s in src], 0)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--run_name", type=str, required=True)
parser.add_argu... |
#!/usr/bin/python
import psycopg2
import sys
import os
DB = {
'DATABASE_SERVICE_NAME': os.getenv('DATABASE_SERVICE_NAME', None),
'DATABASE_USER': os.getenv('DATABASE_USER', None),
'DATABASE_PASSWORD': os.getenv('DATABASE_PASSWORD', None),
'DATABASE_NAME': os.getenv('DATABASE_NAME', None)
}
try:
... |
# Copyright 1999-2021 Alibaba Group Holding 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 a... |
from recipe_scrapers.whatsgabycooking import WhatsGabyCooking
from tests import ScraperTest
class TestWhatsGabyCookingScraper(ScraperTest):
scraper_class = WhatsGabyCooking
def test_host(self):
self.assertEqual("whatsgabycooking.com", self.harvester_class.host())
def test_canonical_url(self):
... |
import sys
import os
import pandas as pd
import numpy as np
import nltk
import re
from sklearn import linear_model
from nltk.tokenize import word_tokenize
import time
import random
nltk.download('punkt')
# data_path = "C:\\Users\\darwi\\OneDrive - " \
# "The University of Texas at Dallas\\Acads\\Machine Le... |
"""
-------Simple Logistic Regression to Classify the Iris Flowers-----------
Read the database and assign the variables to a dataframe by using pandas.
Plot the variables to visualize the relation between each other.
According to the plots, on the first sight, setosa has very different
... |
# -*- coding: utf-8 -*-
"""
@Author : Invoker Bot
@Email : invoker-bot@outlook.com
@Site :
@Data : 2021/3/25
@Version : 1.0
"""
import random
import collections
from typing import *
from ..basic import *
from .gtp import *
__all__ = ["GTPRandomBot"]
class GTPRandomBot(GTPClient):
name = "random_bot"
... |
# -*- coding: utf-8 -*-
import numpy as np
import pprint
from envs.GridWorld import GridworldEnv
import matplotlib.pyplot as pl
pp = pprint.PrettyPrinter(indent=2)
env = GridworldEnv(shape=[4,4])
def policy_eval(policy, env, discount_factor=1.0, theta=0.00001):
"""
Evaluate a policy given an environment and... |
#!/usr/bin/python
from SciServer import Authentication, LoginPortal, Config, CasJobs, SkyServer, SkyQuery, SciDrive, Files, Jobs
import unittest2 as unittest
import os;
import pandas;
import sys;
import json;
from io import StringIO
from io import BytesIO
import skimage
# Define login Name and password before running ... |
from hypernet.apps import box
from hypernet.apps import fitRates
__all__ = [
"box",
"fitRates"
]
|
r,c,zr,zc=map(int,input().split());a=[];res=""
for i in range(r):
a.append(input())
for i in range(r*zr):
for j in range(c*zc):
res+=a[i//zr][j//zc]
res+='\n'
print(res,end="")
|
import json
import logging
import pickle
import re
import chardet
import faker
from urllib3.exceptions import InvalidHeader
_COOKIE_PARSER = re.compile(r"([\w\-\d]+)\((.*)\)")
_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')
_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')
_HOST_EXTRACT = h = re.c... |
from space_wrappers.classify import *
from gym import Space
from gym.spaces import *
import numpy as np
import pytest
class UnknownSpace(Space):
pass
# is_discrete
def test_is_discrete():
assert is_discrete(Discrete(10))
assert is_discrete(MultiDiscrete([4, 5]))
assert is_discrete(MultiBinary(5))
... |
from itertools import groupby
import psycopg2
import smtplib
import helper_functions
from helper_functions import cleanDirPath
import subprocess
import argparse
import os
import sys
import zipfile
import xml.etree.ElementTree as ET
import xml
import sqlparse
from tableau_xml import TableauDatasource as TDS
from tableau... |
from app import db
print(f"running create_db")
db.create_all()
|
if node.os != 'ubuntu' and node.os != 'raspbian':
raise Exception('{} {} is not supported by this bundle'.format(node.os, node.os_version))
files = {}
pkg_apt = {
'sudo': {},
}
files['/etc/sudoers'] = {
'source': 'sudoers',
'content_type': 'text',
'mode': '0440',
'owner': 'root',
'group':... |
# -------------------------------------------------------------------------------------
# Libraries
import logging
import re
import xarray as xr
import pandas as pd
from src.hyde.algorithm.settings.satellite.gsmap.lib_gsmap_args import logger_name
# Logging
log_stream = logging.getLogger(logger_name)
# Debug
# impo... |
import random
import os
import discord
from discord.ext import commands
from validators.user import is_registered, is_unregistered
from utils.commands import confirm
class Management(commands.Cog):
@is_unregistered()
@commands.command()
async def register(self, ctx):
await ctx.bot.user_reposito... |
def fun():
for x in range(6):
for y in [-1, 4, 2, 1, 7]:
if (x > y):
yield x*2+y
gencomp = (x*2+y for x in range(6) for y in [-1, 4, 2, 1, 7] if x > y)
___assertEqual(list(fun()), list(gencomp))
def filgen(f, it):
if (f == None):
for x in it:
if (x):
yield x
else:
for x in it:
if (f(x)):
... |
from nba_api.stats.endpoints._base import Endpoint
from nba_api.stats.library.http import NBAStatsHTTP
from nba_api.stats.library.parameters import GameDate, LeagueID
class VideoStatus(Endpoint):
endpoint = 'videostatus'
expected_data = {'VideoStatus': ['GAME_ID', 'GAME_DATE', 'VISITOR_TEAM_ID', 'VISITOR_TEAM... |
"""
Manage symbols can be used in BUILD files.
"""
__build_rules = {}
def register_variable(name, value):
"""Register a variable that accessiable in BUILD file """
__build_rules[name] = value
def register_function(f):
"""Register a function as a build function that callable in BUILD file """
regi... |
from setuptools import setup, find_packages
with open("requirements.txt") as f:
requirements = f.read().splitlines()
setup(
name='dsmodule',
packages=find_packages(),
install_requires=requirements,
include_package_data=True,
description='Template Python package for Data Science projects.',
... |
from indicators.rsi import *
def test_rsi():
assert(True is True)
|
# --- Day 5: How About a Nice Game of Chess? ---
import hashlib
def solve1(door_id):
code = []
i = 0
while len(code) < 8:
s = (door_id + str(i)).encode('utf-8')
hash = hashlib.md5(s).hexdigest()
i += 1
if hash[:5] == '00000':
code.append(hash[5])
return ''.j... |
import astrometry.net.appsecrets.auth as authsecrets
# The namespace for social authentication is horrible.
# This uses the Python Social Auth module,
# http://python-social-auth-docs.readthedocs.io/en/latest/configuration/settings.html
# which was derived from the django-social-auth module.
SOCIAL_INSTALLED_APPS ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from nose.tools import eq_
from pyexcel_cli.view import view
from click.testing import CliRunner
from textwrap import dedent
def test_stdin_option():
runner = CliRunner()
result = runner.invoke(view,
["--source-file... |
import flask, os, sys,time
from flask import request,render_template,send_file,Flask
import subprocess
from shutil import copyfile
import textrank
import FSM
app = Flask(__name__, static_folder='pdf')
def html_and_txt(file_name):
path = os.getcwd().replace('\\','/') + '/pdf'
cmd_docker = 'docker run -idt --rm... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import re
from bs4 import BeautifulSoup
import scrape_common as sc
def strip_value(value):
if value:
return re.sub(r'[^0-9]', '', value)
return None
base_url = 'https://www.vs.ch'
url = f'{base_url}/web/coronavirus/statistiques'
content... |
from src import EventManager, ModuleManager, utils
CAP = utils.irc.Capability("echo-message", depends_on=["labeled-response"])
@utils.export("cap", CAP)
class Module(ModuleManager.BaseModule):
@utils.hook("raw.send.privmsg", priority=EventManager.PRIORITY_LOW)
@utils.hook("raw.send.notice", priority=EventMa... |
import sys
MAP_WIDTH = 5
MAP_HEIGHT = 5
ITERATIONS = 3
def neighbours(x, y):
for dx, dy in [(-1,1),(0,1),(1,1),(-1,0),(1,0),(-1,-1),(0,-1),(1,-1)]:
nx = x + dx
ny = y + dy
if nx >= 0 and nx < MAP_WIDTH and ny >= 0 and ny < MAP_HEIGHT:
yield (nx, ny)
else:
... |
def hanoi(n : int, s : str, d : str, i : str):
if n == 0:
return
hanoi(n - 1, s, i, d)
print("Move disc", n, "from", s, "to", d)
hanoi(n - 1, i, d, s)
hanoi(5, "left", "right", "centre")
|
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test import TestCase, override_settings
from uw_sws.util import fdao_sws_override
from uw_pws.util import fdao_pws_override
from sis_provisioner.builders import Builder
from sis_provisioner.csv.data import Collector
from... |
'''
This module provides an "in memory" implementation of the NetworkNode interface.
As the module's name implies, it's intended for use in testing code. This
implementation provides deterministic messaging that always deliveres messages
in the same order across repeated runs of the same test.
'''
from twisted.interne... |
# Copyright (c) 2020-2021 Matematyka dla Ciekawych Świata (http://ciekawi.icm.edu.pl/)
# Copyright (c) 2020-2021 Robert Ryszard Paciorek <rrp@opcode.eu.org>
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Soft... |
import tensorflow as tf
from tensorflow.python.ops import variables
from tensorflow.python.ops import array_ops
from tensorflow.python.framework import ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tf_extended import math as tfe_math
import util
def _create_local... |
import json
import os
from django.contrib.auth import get_user_model
from django.utils import timezone
from iotile_cloud.utils.gid import IOTileProjectSlug, IOTileStreamSlug, IOTileVariableSlug
from apps.configattribute.models import ConfigAttribute, ConfigAttributeName
from apps.configattribute.serializers import C... |
# outlook
outlook_client_id = "your-client-id-here"
outlook_client_secret = "your-client-secret-here"
outlook_scopes = ["basic", "calendar"]
outlook_token_path = "./credentials/"
outlook_token_filename = "outlook_token.txt"
previous_days = 40 # retrieve this many past days of events
future_days = 365 # retrieve this ... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: temporal/api/enums/v1/reset.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Author: <Zurdi>
import sys
import os
import psutil
import argparse
from pyvirtualdisplay import Display
from nbz_core import NBZCore
from parser.nbz_parser import NBZParser
from data.natives import NATIVES
from lib.lib_log_nbz import Logging
logger = Logging()
BASE_... |
from ...Location import Location
from ...Specification.SpecEvaluation import ProblemObjectivesEvaluations
from ..NoSolutionError import NoSolutionError
class ObjectivesMaximizerMixin:
@property
def objectives_before(self):
if self._objectives_before is None:
sequence = self.sequence
... |
#!/usr/bin/env python
# encoding: utf-8
'''
zscores_for_mutants_with_vaf_median.py
Created by Joan Smith
on 2017-9-03.
Calculate zscores for mutants where patients are only counted as mutated if their vaf is >= median vaf for a gene
Copyright (c) 2018. All rights reserved.
'''
import pandas as pd
import numpy as np... |
"""Users model
"""
from django.contrib.auth.models import User
from django.db import models
class Profile(models.Model):
"""Profile model
Args:
models (subclass): a python class that subclasses django.db.models.Model
Returns:
string: account of the user profile
"""
user = models... |
"""
Classes from the 'CoreMotion' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
CMWorkoutManager = _Class("CMWorkoutManager")
CMWorkoutMa... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-05-29 09:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data', '0042_import_officerbadgenumber_data'),
]
operations = [
migrations.... |
#!/usr/opt/bs-python-2.7/bin/python
import os
import sys
import decimal
sys.path.append(os.path.realpath(__file__ + '/../../../lib'))
import udf
class Round(udf.TestCase):
def checkType(self, query, type):
self.query('''create or replace table tmp as ''' + query)
rows = self.query('describe tmp... |
import csv
from tqdm import tqdm
import logging
from sklearn.cluster import k_means
from collections import Counter
# Symbols for flosses legend.
SYMBOLS = ['*', '-', '+', 'T', '>', '<', 'V', 'O', 'X', 'U', 'B', 'A', 'X', '||', '^']
def get_text_color(color):
"""Gets color that would be visible on given backgro... |
"Stress test diskcache.core.Cache."
from __future__ import print_function
import collections as co
from diskcache import Cache, UnknownFileWarning, EmptyDirWarning, Timeout
import multiprocessing as mp
import os
import random
import shutil
import sys
import threading
import time
import warnings
try:
import Queue... |
from Views.UnitsOptionsView import UnitsOptionsView
class UnitsOptionsController:
def __init__(self):
self.unitsOptionsObservers = []
self.units = {
"P": "bar",
"T": "K",
"V": "m3/mol",
"rho": "kg/m3",
"energy_per_mol": "J/mol",
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 1 21:02:22 2019
@author: yoelr
"""
from .palette import Palette
from math import floor, ceil
from .color import Color
from .utils import view
class ColorWheel:
"""
Create a ColorWheel object that cycles through Color objects.
Parameters
----------
... |
# 🤗 Datasets
from datasets import (
concatenate_datasets,
DatasetDict,
)
from thesis.datasets.s2orc.preprocessing import get_dataset
from thesis.datasets.s2orc.read_dataset import s2orc_multichunk_read
# Dataset configuration files
from thesis.config.datasets import S2orcConfig, KeyPHConfig
from thesis.con... |
import os, cv2
# Create resize_imgs function
def resize_imgs():
"""
Used to quickly resize images to 600 width x auto height. Must be run inside the root folder that contains an existing dataset and resized folder. Additionally, resized folder must contain class subfolders already.
Command example:
python r... |
from .pages.locators import BasePageLocators
from .pages.main_page import MainPage
def test_guest_cant_see_success_message_after_adding_product_to_basket(browser):
link = "http://selenium1py.pythonanywhere.com/"
page = MainPage(browser, link)
page.open()
page.add_to_basket(*BasePageLocators.BASKET_BUT... |
import pandas as pd
import numpy as np
from scipy.optimize import minimize
import holoviews as hv
class EfficientFrontier:
def __init__(self, daily_returns, op=1, stocks=[]):
self.daily_returns = daily_returns
if op == 1:
self.get_ret_vol_sr = self.get_ret_vol_sr1
else:
self.get_ret_vol_sr = self.get_ret_... |
from __future__ import absolute_import
from pysoa.client.client import Client
__all__ = (
'Client',
)
|
import boto3, os, json
import smtplib
import email.message
from boto3.dynamodb.conditions import Key, Attr
url_expiration = 172800 # 2days
def sendEmail(to, subject, body):
gmail_sender = os.environ['email_account']
gmail_passwd = os.environ['email_password']
print(gmail_passwd)
msg = email.message.M... |
from . import _morphology
__all__ = ['iterate_structure', 'generate_binary_structure', # noqa: F822
'binary_erosion', 'binary_dilation', 'binary_opening',
'binary_closing', 'binary_hit_or_miss', 'binary_propagation',
'binary_fill_holes', 'grey_erosion', 'grey_dilation',
'g... |
from setuptools import setup
import taxicab as tc
with open("README.md", "r") as f:
long_description = f.read()
with open("requirements.txt", "r") as f:
INSTALL_REQUIRES = [line.strip() for line in f.readlines()]
setup(
name='Taxicab',
version=tc.__version__,
author=tc.__author__,
author_... |
#!/usr/bin/env python
import re
import sys
keys_for_uri = {}
uris_for_key = {}
for line in sys.stdin:
s,p,o = line.split(None, 2)
uri = s[1:-1]
key = o.split('"')[1]
keys_for_uri.setdefault(uri, [])
keys_for_uri[uri].append(key)
uris_for_key.setdefault(key, [])
uris_for_key[key].append(u... |
# --------------------------------------------------------------------------
# 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 may cause... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.