content stringlengths 5 1.05M |
|---|
from django import forms
from django.core import validators
def check_for_z(val):
if val[0].lower() != 'z':
raise forms.ValidationError('man this is wrong use Z')
print('not using z')
class my_form(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'inp'}),validators=... |
from django.core.cache import cache
import logging, sys, csv, os, math, re, string, subprocess, time, stat
from plotty import settings
from plotty.results.Utilities import present_value, present_value_csv, scenario_hash, length_cmp, t_quantile
from plotty.results.Exceptions import LogTabulateStarted, PipelineError
from... |
import numpy as np
from numpy import sqrt as sqrt
from numpy import cos as cos
from numpy import sin as sin
import matplotlib.pyplot as plt
from matplotlib import cm as cm
from matplotlib.ticker import LinearLocator as LinearLocator
from matplotlib.ticker import FormatStrFormatter as FormatStrFormatter
from numpy.fft i... |
'''
Variables: Creation, Initialization, Saving, and Loading
When you train a model, you use variables to hold and update parameters. Variables are in-memory buffers containing tensors. They must be
explicitly initialized and can be saved to disk during and after training. You can later restore saved values to exer... |
#!//dls_sw/prod/R3.14.12.3/support/pythonSoftIoc/2-11/pythonIoc
from pkg_resources import require
require('cothread==2.13')
#require('epicsdbbuilder==1.0')
require("numpy")
import argparse
import logging
import PIStepScan
import PIController
from PIConstants import *
def parse_arguments():
parser = argparse.Arg... |
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# 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/LICEN... |
from django.urls import path
from . import views
urlpatterns = [
path('',views.add_show,name="addandshow"),
path('delete/<int:id>/',views.delete_data,name="deletedata"),
path('<int:id>/',views.update_data,name="updatedata"),
]
|
from flask import request
from flask_restplus import Resource, Namespace, fields
ns_user = Namespace("users", description="Users related operations")
user_model = ns_user.model(
"user",
{
"email": fields.String(required=True, description="user email address"),
"username": fields.String(require... |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-15 20:55
import logging
from typing import Union, List
import torch
from torch import nn
from torch.utils.data import DataLoader
from elit.common.dataset import PadSequenceDataLoader, SamplerBuilder, TransformableDataset
from elit.common.structure import History... |
import unittest
from unittest import mock
import dbt.flags as flags
from dbt.adapters.mysql import MySQLAdapter
from .utils import config_from_parts_or_dicts, mock_connection
class TestMySQLAdapter(unittest.TestCase):
def setUp(self):
pass
flags.STRICT_MODE = True
profile_cfg = {
... |
"""Tests for evohomeclient package"""
from datetime import datetime
import requests_mock
from . import EvohomeClient
UNAUTH_RESPONSE = """[{
"code": "Unauthorized",
"message": "Unauthorized"
}]"""
TASK_ACCEPTED_LIST = """[{"id": "123"}]"""
TASK_ACCEPTED = """{"id": "123"}"""
VALID_SESSION_RESPONSE = """{
... |
# -*- coding: utf-8 -*-
#Need to import this library to support array type
from array import array
# Returns the name of the object if it is supported.
# Returns an empty string else
def supported_object(obj):
if type(obj) not in (tuple, list, array):
return ""
if(type(obj) == tuple):
return "... |
# import h5py
# import json
# from abc import ABC, abstractmethod
# from .utils import *
# class BaseClientDataLoader(ABC):
# @abstractmethod
# def __init__(self, data_path, partition_path, client_idx, partition_method, tokenize, data_fields):
# self.data_path = data_path
# self.partition_pat... |
import tensorflow as tf
import numpy as np
from keras.models import Sequential, Model
from keras.layers import Dense, Input, InputLayer, Conv2D, MaxPooling2D, Reshape, Flatten
from keras.models import load_model
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = ... |
# 2017 John Shell
from datetime import datetime, timezone
from random import randint as rand
import discord
import pytz
from .grasslands import Peacock
log = Peacock()
def m2id(mem):
"""
Convert member object to id str
:param mem: discord.Member or id str
:return: str id
"""
if isinstance(m... |
from anvil import *
import anvil.facebook.auth
import anvil.google.auth, anvil.google.drive
from anvil.google.drive import app_files
import anvil.microsoft.auth
import anvil.users
import anvil.server
if not get_url_hash():
while not anvil.users.login_with_form():
pass
# disabling report module
# open_... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load(":shape.bzl", "shape")
# Define shapes for systemd units. This is not intended to be an exhaustive
# list of every systemd unit settin... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: model.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflect... |
from unittest import TestCase
from currencies import server
from currencies import repository
class TestService(TestCase):
def setUp(self):
app = server.start(repository)
self.client = app.test_client()
def test_root_returns_200(self):
response = self.client.get("/")
assert r... |
from django.shortcuts import render, reverse
from django.http import HttpResponse, HttpResponseRedirect
from batchthis.models import Batch, Fermenter, BatchTestType, BatchNoteType
from django.shortcuts import get_object_or_404
from .forms import BatchTestForm, BatchNoteForm, BatchAdditionForm, RefractometerCorrectionFo... |
"""
Decorators for exposing function arguments / returns
"""
from io import StringIO
import sys
import functools as ftl # , pprint
from .. import pprint as pp
from .base import Decorator
def get_inner(func, args=(), kws=None):
""""""
kws = kws or {}
while isinstance(func, ftl.partial):
kws.upda... |
def resolve():
'''
code here
'''
import collections
import itertools
N = int(input())
Ss = [input()[0] for _ in range(N)]
march_letter = [item for item in Ss if item in ['M', 'A', 'R', 'C', 'H']]
march_cnt = collections.Counter(march_letter)
if len(march_cnt) < 3:
res =... |
import ast
import inspect
import textwrap
from .base import TohuBaseGenerator
from .ipython_support import get_ast_node_for_classes_defined_interactively_in_ipython
__all__ = ["Placeholder", "placeholder", "foreach"]
class Placeholder:
def __init__(self, name):
self.name = name
placeholder = Placeholde... |
def generateTraverse(content, numberOfAssertions):
with open("traverse_tests/main_model_" + str(numberOfAssertions) + ".c", 'w+') as f:
for i,line in enumerate(content):
if "int action_run;" in line:
for x in range(0, numberOfAssertions):
f.write('\nint path_... |
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit, disconnect
from streamer import Stream, auth, preprocessor, clf_path
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@socketio.on('connect... |
from typing import Optional
from distil.primitives.ensemble_forest import EnsembleForestPrimitive
from common_primitives.extract_columns_semantic_types import (
ExtractColumnsBySemanticTypesPrimitive,
)
from common_primitives.grouping_field_compose import GroupingFieldComposePrimitive
from common_primitives.column_... |
from __future__ import absolute_import, division, print_function
import iotbx.phil
import iotbx.pdb
import iotbx.mrcfile
from cctbx import crystal
from cctbx import maptbx
from libtbx.utils import Sorry
import sys, os
from cctbx.array_family import flex
from scitbx.math import matrix
from copy import deepcopy
from libt... |
import os
from PIL import Image, ImageDraw
from PIL import ImageFilter, ImageEnhance
from PIL.ImageFilter import (
GaussianBlur, MaxFilter
)
import numpy as np
import PostOnIg
import random
import json
import randomWords
from bing_image_downloader import downloader
import randomWords
import randomObjects
import... |
"""The Weibull distribution."""
from equadratures.distributions.template import Distribution
from equadratures.distributions.recurrence_utils import custom_recurrence_coefficients
import numpy as np
from scipy.stats import weibull_min
RECURRENCE_PDF_SAMPLES = 8000
class Weibull(Distribution):
"""
The class def... |
"""Show config player."""
from mpf.core.placeholder_manager import ConditionalEvent
from mpf.config_players.device_config_player import DeviceConfigPlayer
RESERVED_KEYS = ["show", "priority", "speed", "block_queue", "start_step", "loops", "sync_ms", "manual_advance",
"key", "show_tokens", "events_whe... |
# -*- coding: utf-8 -*-
__author__ = "Konstantin Klementiev"
__date__ = "23 Jul 2021"
# !!! SEE CODERULES.TXT !!!
import numpy as np
import scipy.linalg as spl
import sys; sys.path.append('..') # analysis:ignore
from parseq.core import transforms as ctr
from parseq.utils import math as uma
from parseq.third_party i... |
@app.on_message(filters.command(["bandiera","bandiera@NFTlittlebot"]) & ~filters.user(bannati))
def gloria(client, message):
username = message.from_user.username
if player[username]["team"] != None and player[username]["team"] != "nessuno":
team = player[username]["team"]
if "Bandiera" in cl... |
#!/usr/bin/env python
# coding: utf8
'''
@author: qitan
@contact: qqing_lai@hotmail.com
@file: myfilter.py
@time: 2017/3/30 15:32
@desc:
'''
from django import template
from django.contrib.auth.models import Group
from userauth.models import User, Department
from django.db.models import Q
from django.shortcuts import ... |
"""
Input classes for nimare data.
"""
import json
class Analyzable(object):
def to_array(self):
pass
class Mappable(Analyzable):
def to_vol(self):
pass
class ConnMatrix(Analyzable):
"""Container for connectome data (i.e., connectivity matrices).
"""
def __init__(self, mat):
... |
print('hello world new!')
|
# 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 ... |
mysp = __import__('my-voice-analysis')
p="converted"
c=r"C:\Users\ishan\OneDrive\Documents\EngHack"
import wave
params = ()
rating = mysp.myspgend(p,c)
pauses = mysp.mysppaus(p,c)
speed = mysp.myspsr(p,c)
articulation = mysp.myspatc(p,c)
pronounce = mysp.mysppron(p,c)
pauses_response = []
speed_response = []... |
r"""
Algebras With Basis
"""
#*****************************************************************************
# Copyright (C) 2008 Teresa Gomez-Diaz (CNRS) <Teresa.Gomez-Diaz@univ-mlv.fr>
# 2008-2009 Nicolas M. Thiery <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General Publi... |
#!/usr/bin/env python
import numpy
from numpy import *
import mpi
import sys
from time import sleep
sys.argv = mpi.mpi_init(len(sys.argv),sys.argv)
myid=mpi.mpi_comm_rank(mpi.MPI_COMM_WORLD)
numprocs=mpi.mpi_comm_size(mpi.MPI_COMM_WORLD)
print "hello from python main1 myid= ",myid
port_name=mpi.mpi_open_port(mpi.... |
import aiohttp
import os
from redbot.core import Config, commands, checks
from redbot.core.utils.chat_formatting import box
import xml.etree.ElementTree as ET
class Wolfram(commands.Cog):
"""Ask Wolfram Alpha any question."""
def __init__(self, bot):
self.bot = bot
self.session = aiohttp.Clie... |
AMR_HEADERS = ['ORF_ID', 'Start', 'Stop', 'Orientation', 'Best_Identities', 'Best_Hit_ARO']
ARGS_DICT={'disable_serotype':False,'disable_vf':False,'pi':90, 'options':{'vf': True, 'amr': True, 'serotype': True}}
set_spfyids_o157 = set([u'https://www.github.com/superphy#spfy3418', u'https://www.github.com/superphy#spfy... |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
from Layer import Layer
class ImageDataSource(Layer):
srcDimList = [(0),(0,1),(0,1,2)]
def __init__(self,para):
Layer.__init__(self,para)
self.lastMiniBatch = True
def createAndInitializeStruct(self):
... |
default_app_config = "oscarbluelight.dashboard.offers.apps.OffersDashboardConfig"
|
from cli.application import CliApplication
if __name__ == "__main__" or __name__ == "src.cli.__main__":
cli = CliApplication()
cli.run()
|
from typing import Any, Union
import numpy as np
import biorbd
from bioptim import Solution
def compute_error_single_shooting(
time: Union[np.ndarray, list],
n_shooting: int,
model: biorbd.Model,
q: np.ndarray,
q_integrated: np.ndarray,
duration: float = None,
):
"""
Compute the error... |
'''
Created on Dec 4, 2018
@author: gsnyder
Get a list of user objects
'''
import json
from blackduck.HubRestApi import HubInstance
hub = HubInstance()
user_groups = hub.get_user_groups()
if 'totalCount' in user_groups and user_groups['totalCount'] > 0:
print(json.dumps(user_groups))
else:
print("No user_group... |
# $Id$
#
# Copyright (C) 2008 Greg Landrum
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
from rdkit.sping import pid
import math, re
from rdk... |
import json
import pprint
import sys
from .backuptools import BackupResource, BackupTools
from .googledriveclient import GoogleDriveClient
if __name__ == '__main__':
config_file = sys.argv[1]
args = sys.argv[2:]
config: dict = None
with open(config_file) as f:
config = json.load(f)
tool... |
from django.contrib import messages
from django.contrib.auth import login, logout
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from core.email_backend import EmailBackend
# Create your views here.
def go_index(request):
return rend... |
import fnmatch
import importlib
import os
from setuptools import setup
import jenkins_monitor.version
# Let's add this later
# long_description = open('README.txt').read()
def discover_packages(base):
"""
Discovers all sub-packages for a base package
Note: does not work with namespaced packages (via p... |
# Check that -vv makes the line number of the failing RUN command clear.
# (-v is actually sufficient in the case of the internal shell.)
#
# RUN: env -u FILECHECK_OPTS not %{lit} -j 1 -vv %{inputs}/shtest-run-at-line > %t.out
# RUN: FileCheck --input-file %t.out %s
#
# END.
# CHECK: Testing: 4 tests
# In the case ... |
# -*- coding: utf-8 -*-
# Peter Zatka-Haas - April 2009
import os
import pickle
import random
quotes_file = "commands/quotes.db"
class Quotes:
"""
Users assign quotes, which momo stores.
Momo can output the quote in channel later.
Momo will re... |
#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
from distutils.core import setup
setup(name='screenAlign',
version='1.5',
py_modules=['screenAlign'],
author='Fahrstuhl',
author_email='fahrstuhl@mailbox.tu-berlin.de',
url='https://github.com/fahrstuhl/screenAlign.py',
)
|
#☆𝒐𝒎𝒂𝒋𝒊𝒏𝒂𝒊☆#
import sys
import math
from math import ceil, floor
import itertools
from functools import lru_cache
from collections import deque
sys.setrecursionlimit(10000000)
input=lambda : sys.stdin.readline().rstrip()
'''''✂'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
n,m=map(int,input().split(... |
import math
N=int(input("Enter values up to which you need to find prime numbers"))
primeflag=[0 for i in range(N+1)]
for i in range(2,int(math.sqrt(N))+1):
for j in range(i*i,N+1,i):
primeflag[j]=1
primeflag[0]=1
primeflag[1]=1
for i in range(N):
if primeflag[i]==0:
print(str(i) + "is prime")
|
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# This is very simple example of some code
# which will use files and will try call external REST API
# so - we will try to create mock for these methods
import requests
class MySuperProgram():
def read_string_from_file(self):
""" This function reads first str... |
import pyxb
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
schema_path = '%s/../schemas/xsi-type.xsd' % (os.path.dirname(__file__),)
code = pyxb.binding.generate.GeneratePython(schema_location=schema_path)
rv = compile(code, 'test', 'exec')
eval(rv)
originalOneFloor ... |
import logging
from collections import namedtuple
import numpy as np
from tensorboardX import SummaryWriter
import torch
import torch.nn as nn
import torch.optim as optim
HIDDEN_SIZE = 128
BATCH_SIZE = 16
PERCENTILE = 70
from cartpole import CartPole
class Net(nn.Module):
def __init__(self, obs_size, hidden_si... |
from dateutils import DateUtils
import datetime
import unittest
CURRENT_YEAR = datetime.datetime.now().year
class TestDateUtils(unittest.TestCase):
def test_last_day_of_month(self):
self.assertEqual(DateUtils.last_day_of_month(2019, 3), 31)
self.assertEqual(DateUtils.last_day_of_month(2018, 7), 3... |
import logging
class GlobalRouting:
def __init__(self, floorplan, top_rtl_parser, slot_manager):
self.floorplan = floorplan
self.top_rtl_parser = top_rtl_parser
self.slot_manager = slot_manager
self.v2s = floorplan.getVertexToSlot()
self.s2e = floorplan.getSlotToEdges()
self.e_name2path = {}... |
import datetime
from .. import db
from sqlalchemy.dialects import postgresql
class BookCarts(db.Model):
""" BookCarts model for storing book details selected"""
__tablename__ = "book_carts"
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
book_id = db.Column(db.Integer)
cart_id =... |
'''
Created on Feb 27, 2012
@author: IslamM
'''
import web
from web.wsgiserver.ssl_builtin import BuiltinSSLAdapter
from logging import getLogger
log = getLogger(__name__)
web.config.debug = False
class UIMWEBApp(web.application):
def run(self, certinfo, server_address=('0.0.0.0', 8080), timeout=9... |
import pandas as pd
import requests
import time
import folium
import pathlib
from folium.plugins import MarkerCluster
from matplotlib import pylab
from pylab import *
from opencage.geocoder import OpenCageGeocode
from pprint import pprint
key = 'add your own Open Cage Code key here'
geocoder = OpenCageGeocode(key)
... |
from .. modello_lineare import RegressioneLineare
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
import numpy as np
X, y = make_regression(n_samples=100, n_features=10, bias=5, random_state=42)
rl_fit_intercept_true = RegressioneLineare(fit_intercept=True)
lr_fit_inter... |
cc_library(
name = "zlib",
hdrs = glob(["include/*.h"]),
srcs = ["lib/libz.a"],
includes = ["include"],
visibility = ["//visibility:public"],
)
|
import os
import os.path
import pathlib
import tempfile
import logging
import warnings
from collections import namedtuple
from joblib import Parallel, delayed, dump, load
import pandas as pd
import numpy as np
try:
import dask.dataframe as ddf
except ImportError:
ddf = None
from ..algorithms import Recommend... |
print('======= DESAFIO 14 =======')
c = float(input('Informe a temperatura em ºC: '))
f = ((9 * c) / 5) + 32
# também pode ser escrito sem parêntese nenhum: ordem de precedência!
print('A temperatura de {:.1f}ºC corresponde a {:.1f}ºF!'.format(c, f))
|
from . import xlsx
class XlsxImport(xlsx.XlsxImport):
def handle(self):
return self
|
from cradmin_legacy.crinstance import reverse_cradmin_url
from cradmin_legacy import crapp
from devilry.apps.core.models import Subject
from devilry.devilry_cradmin import devilry_crinstance
from devilry.devilry_admin.cradminextensions import devilry_crmenu_admin
from devilry.devilry_admin.views.subject_for_period_adm... |
import logging
import os
import textwrap
import yaml
from . import constants
from .exceptions import DefinitionError
from .steps import (
AdditionalBuildSteps, BuildContextSteps, GalaxyInstallSteps, GalaxyCopySteps, AnsibleConfigSteps
)
from .utils import run_command, copy_file
logger = logging.getLogger(__name_... |
from invoke import task
import shutil
from pathlib import Path
@task
def lint(c):
c.run("isort --check winsnap", warn=True)
c.run("black --check winsnap", warn=True)
c.run("flake8 winsnap", warn=True)
@task
def format(c):
c.run("isort winsnap", warn=True)
c.run("black winsnap", warn... |
from time import time
import numpy as np
import cv2 as cv
import win32gui, win32ui, win32con
class Vision:
# Attributes
match_template_methods = list()
normalized_match_template_methods = list()
debug_modes = list()
copper_ore_rgb = list()
tin_ore_rgb = list()
# --------------- Constructo... |
#!/usr/bin/env python
"""
Translate DNA reads from a fasta file.
"""
import sys
import click
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC, Gapped
from flea.util import insert_gaps
def _translate(record, gapped=False):
result = record[:]
if gapped:
translated = reco... |
from selenium.webdriver.support.ui import Select
class ContactHelper:
def __init__(self, app):
self.app = app
def add_new_contact(self, contact):
wd = self.app.wd
# Нажимаем кнопку "Добавить контакт"
wd.find_element_by_link_text("add new").click()
# Заполняем поля
... |
# -*- coding: utf-8 -*-
# This example shows a simple calculation of SNOM contrast between two bulk materials: silicon and gold.
from numpy import *
from matplotlib.pyplot import *
from NearFieldOptics import Materials as Mat
from NearFieldOptics import TipModels as T
##############################################... |
def main():
import argparse
import re
import traceback
import requests
from dlinkscraper import DLink
parser = argparse.ArgumentParser(
'DuckDNS Updater',
description=
"""This script updates your DuckDNS IPv4 address to scraped address
from your D-Link router.... |
import json
import re
import numpy as np
from fastapi import FastAPI, HTTPException
from .colours import random_hex
from .identifiers import (catalogue_id_to_miro_id, valid_catalogue_ids,
miro_id_to_identifiers, index_lookup)
from .neighbours import get_neighbour_ids, palette_index
from .pal... |
from pathlib import Path
# Define path constant at import time
PATH = Path(__file__).parent # Parent will fetch this files parent package
|
# Generated by Django 3.2.9 on 2021-12-31 13:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nezbank', '0002_auto_20211228_1743'),
]
operations = [
migrations.AlterField(
model_name='account',
name='rate',
... |
from selenium import webdriver
from sys import platform as _platform
import platform
driver = ""
opts = webdriver.ChromeOptions()
opts.add_argument('headless')
opts.add_argument('remote-debugging-port=9222')
if _platform.startswith("linux"):
driver = webdriver.Chrome(executable_path="webdrivers/chromedriver-li... |
## License: Apache 2.0. See LICENSE file in root directory.
## Copyright(c) 2017 Intel Corporation. All Rights Reserved.
#####################################################
## rs400 advanced mode tutorial ##
#####################################################
# First import the library
import p... |
LINKS = {
"GB_SAC_shape_file": "https://data.jncc.gov.uk/"
+ "data/52b4e00d-798e-4fbe-a6ca-2c5735ddf049/"
+ "GB-SAC-OSGB36-20190403.zip",
# All below from:
# https://environment.data.gov.uk/ecology/explorer/downloads/
# Data documentation (must read!) is here:
# https://environment.data.gov.... |
from .shelves import LSMShelf, Shelf
from .dict import LSMDict
|
# -*- coding:utf-8 -*-
# !/usr/bin/env python3
"""
"""
__all__ = ['issquare']
def issquare(n):
"""
:param n:
:return:
>>> issquare(256)
True
>>> issquare(255)
False
"""
i = 1
while n > 0:
n -= i
i += 2
return n == 0
if __name__... |
import password_strength as pwd
from django.core.validators import BaseValidator
from django.utils.translation import gettext, ungettext_lazy
class PolicyBaseValidator(BaseValidator):
def js_requirement(self):
return {}
class PolicyMinLengthValidator(PolicyBaseValidator):
message = ungettext_lazy(
... |
from nltk.corpus import stopwords
from nltk.tokenize import TweetTokenizer
from nltk.stem.wordnet import WordNetLemmatizer
def remove_stopwords(words):
return [word for word in words if word not in stopwords.words('english')]
def lemmatize(words):
words = [WordNetLemmatizer().lemmatize(word, pos='n') for ... |
#!/usr/bin/env python
# coding: utf-8
import csv
import random
import datetime
# Global data parameters
product_data = 'product_data.txt'
prod_availability = [[0.8, 0.85, 0.7, 0.6], [0.6, 0.75, 0.98], [0.85, 0.6], 1]
street_data = ['Athens_streets.txt', 'Thessaloniki_streets.txt', 'Volos_streets.txt']
cities = ['At... |
#!env python
from functools import wraps
import time
import collections
import threading
import enum
import json
from threading import Event
from threading import Lock
from itertools import count
import numpy as np
import logging
import queue
from threading import RLock as Lock
import argparse
import exceptions... |
# (C) Copyright 1996-2016 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergov... |
import xml.etree.cElementTree as ET
import sqlite3
import vk_api
import utils as ut
import versions
import os
import random
from math import ceil
import events as ev
with open('token.txt', 'r') as f:
token = f.read()
vk_session = vk_api.VkApi(token=token)
vk = vk_session.get_api()
rulesofinternet = {
'1': "Do not t... |
import os
import pathlib
import tempfile
import unittest
from datetime import datetime
from django.apps import apps
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import connection
from django.db.utils import DataError, IntegrityError
fro... |
import sublime, sublime_plugin
import os.path
import sys
import struct
def GetShortPath(path):
target = ''
try:
with open(path, 'rb') as stream:
content = stream.read()
# skip first 20 bytes (HeaderSize and LinkCLSID)
# read the LinkFlags structure (4 ... |
#!/usr/bin/env python3
# CGIのヘッダ
print("Content-Type : text/html; charset=utf-8")
print("")
#表示するメッセージ
print("<h1>Hello!!!</h1>") |
#!/usr/bin/env python3
from PIL import Image
import os
import re
src = "./supplier-data/images/"
dst = "./supplier-data/images/"
def main():
# read all images
fileslist = []
for root, dirs, files in os.walk(src):
for name in files:
if str(name).endswith(".tiff"):
fileslist.append(name)
# p... |
import json
import os
import subprocess
from ..models import XcTarget, XcProject, XcGroup, XcFile
from ..parsers import XcProjectParser, SwiftCodeParser
# Absolute path of this project root folder.
root_path = __file__
for i in range(0, 4):
root_path = os.path.dirname(root_path)
# Models
class XcModelsFixture... |
from defines import *
class Deposit:
def __init__(self, data):
self.amount = data[1]
self.user_name = data[2]
self.old_credit = data[3]
self.new_credit = data[4]
self.consumption = data[5]
self.Type = data[6]
self.date = data[7]
def get_tye_string(sel... |
# Generated by Django 3.1.7 on 2021-03-02 21:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('autodo', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='car',
name='image',
),
... |
from gym_iOTA.envs.iOTA_env import IotaEnv
|
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... |
from django.contrib import admin
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator
from django.core.validators import MinValueValidator
from django.db import models
from django.forms import CheckboxSelectMultiple
from django.utils.text import slugify
from django.utils.tran... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.