content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import os
import pathlib
import shlex
import shutil
import subprocess
import sys
import unittest
from vtam.utils import pip_install_vtam_for_tests
from vtam.utils.PathManager import PathManager
class TestCommandExample(unittest.TestCase):
"""Will test main commands based on a complete test dataset"""
def s... | python |
from kivymd.app import MDApp
from kivymd.uix.screen import Screen
from kivymd.uix.button import MDRectangleFlatButton, MDFlatButton
from kivy.lang import Builder
from kivymd.uix.dialog import MDDialog
import helpers
class DemoAPP(MDApp):
def build(self):
self.theme_cls.primary_palette = "Green"... | python |
import csv
import logging
import os
from dataclasses import asdict
from typing import List, TypeVar
from analysis.src.python.data_collection.api.platform_objects import Object
class CsvWriter:
def __init__(self, result_dir: str, csv_file: str, field_names: List[str]):
os.makedirs(result_dir, exist_ok=Tr... | python |
from src.base.test_cases import TestCases
class PartEqualSubSumTestCases(TestCases):
def __init__(self):
super(PartEqualSubSumTestCases, self).__init__()
self.__add_test_case__("Example 1", ([1, 5, 11, 5]), (True))
self.__add_test_case__("Example 2", ([1, 2, 3, 5]), (False))
self._... | python |
PALAVRA = "EXEMPLO"
print(PALAVRA[0])
print(PALAVRA[2:5])
print(len(PALAVRA))
nova = PALAVRA + "s!!"
print(nova)
outra = "Novos" + nova
print(outra)
for i in range(len(PALAVRA)):
print(PALAVRA[i])
lista = [2,4,7]
lista [1] = 9
print(lista)
print("O" in PALAVRA)
print("o" in PALAVRA)
#Eu tbm posso colocar:
p... | python |
from discordbot.minigamesbot import MiniGamesBot
from discordbot.utils.private import DISCORD
bot = MiniGamesBot("?")
bot.run(DISCORD["TOKEN"])
| python |
import numpy as np
import mistree as mist
def test_PlotHistMST_rotate():
pmst = mist.PlotHistMST()
pmst._get_rotate_colors()
assert pmst.rotate_colors == 1
pmst._get_rotate_linestyles()
assert pmst.rotate_linestyle == 1
def test_PlotHistMST_plot():
x = np.random.random_sample(100)
y = np... | python |
#!/usr/bin/python3
from tools import *
from sys import argv
from os.path import join
import h5py
import matplotlib.pylab as plt
import numpy as np
###################################################### see old version at the end (easier to understand, but less generalized and not using pca) ########################... | python |
# -*- coding: utf-8 -*-
"""
Contains a base class for a calltips mode.
"""
import logging
from pyqode.core.api import Mode, TextHelper
from pyqode.core.api.panel import Panel
from pyqode.qt import QtCore, QtWidgets
MAX_CALLTIP_WIDTH = 80
def _logger():
return logging.getLogger(__name__)
class CalltipsMode(Mode... | python |
from .queryset import *
| python |
import typing as t
def client_id() -> str:
"""Application (client) ID of app registration"""
return None
def client_secret() -> str:
"""Application secret"""
return None
def authority() -> str:
"""The authority URL"""
return 'https://login.microsoftonline.com/common'
def scope() -> t.Uni... | python |
from PIL import Image
from pytesseract import pytesseract
import argparse
import xmltodict
import json
import cv2
import os
import requests
from puttext import puttext
from nltk.tokenize import sent_tokenize
import math
filename = '../upload/table1.png'
o_filename = '../upload/table2.png'
conf_data = pytesseract.run_t... | python |
#
# Loop transformation submodule.that implements a combination of various loop transformations.
#
import sys
import orio.module.loop.submodule.submodule, transformation
import orio.module.loop.submodule.tile.tile
import orio.module.loop.submodule.permut.permut
import orio.module.loop.submodule.regtile.regtile
import ... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-04-23 11:07
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('shop', '0002_product_im... | python |
from collections import Iterator, Iterable
import string
from . import reader
class Record:
"""
Simple namespace object that makes the fields of a GTF record available. Subclassed
to create records specific to exons, transcripts, and genes
"""
__slots__ = ['_fields', '_attribute']
_del_lette... | python |
import pdb
def add_default_args(parser, root_dir, rand_seed=None, possible_model_names=None):
# tng, test, val check intervals
parser.add_argument('--eval_test_set', dest='eval_test_set', action='store_true', help='true = run test set also')
parser.add_argument('--check_val_every_n_epoch', default=1, type... | python |
#!/usr/bin/python
########################################################################################################################
#
# Copyright (c) 2014, Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permi... | python |
from .models import db
from .utils import update_menus
from diff_match_patch import diff_match_patch
from flask import Markup, abort, g, redirect, render_template, request, send_file, url_for
from flask_security.core import current_user
import os
def render(page, path, version):
file, mimetype, fragment = page.sub... | python |
import numpy as np
import pandas
import pickle
import json
import shutil
import warnings
from typing import Union, List
import os
from sfaira.consts import OCS
from sfaira.data import load_store
from sfaira.data.dataloaders import Universe
from sfaira.estimators import EstimatorKerasEmbedding
from sfaira.ui import Mod... | python |
"""
Defines the possible rewards for rollout.
Can be augmented for more complex policies using simialr scheme as Rollout or UCT policies.
Is defined through CLI in the Tree script.
"""
class RolloutRewards(object):
"""
Defines penalty and rewards for the rollout if it's in the chasis.
"""
def __init__(... | python |
"""
sentry.models.release
~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
from django.db import models
from django.utils import timezone
from jsonfield import JSONF... | python |
import os
from setuptools import setup
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(
name="restful-gpio",
version="0.1.0",
license="MIT",
author="ykaragol",
python_requires='>3.4.0',
packages=["gpio"],
install_requires=required
)
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.TargetInfo import TargetInfo
class AlipayMerchantServiceconsultBatchqueryModel(object):
def __init__(self):
self._begin_time = None
self._end_time = None
... | python |
import math
from typing import List, Optional
from PyQt5 import QtGui
from PyQt5.QtCore import QCoreApplication, Qt
from PyQt5.QtWidgets import (QApplication, QDesktopWidget, QMainWindow,
QShortcut)
from sqlalchemy.orm.exc import NoResultFound
from src.error.invalid_reference import Invali... | python |
from gi.repository import Gtk
from gi.repository import Gio
from gi.repository import Pango
from internationalize import _
import os
def create_function_str(name, *args):
new_func = name + "("
for i, arg in enumerate(args):
if i != 0:
new_func += ", "
new_func += repr(arg)
new_... | python |
# -*- coding: utf-8 -*-
#
# Copyright 2011-2018 Matt Austin
#
# 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 applicabl... | python |
def uncentime(jours):
total = [0.01]
for i in range(jours - 1):
total.append(total[-1] * 2)
return sum(total)
print(uncentime(30))
| python |
a=1
for i in range(int(input())):
print(f"{a} {a+1} {a+2} PUM")
a+=4
| python |
import pandas as pd
class Security():
'''
Generic Class that initializes an object to hold price and volume
data on a particular financial security.
'''
def __init__(self, dataframe, security_name, ticker):
'''
Arguments
---------
dataframe Pandas Dataframe. Co... | python |
from pprint import pprint
from intentBox import IntentAssistant
i = IntentAssistant()
i.load_folder("test/intents")
print("\nADAPT:")
pprint(i.adapt_intents)
print("\nPADATIOUS:")
pprint(i.padatious_intents)
print("\nFUZZY MATCH:")
pprint(i.fuzzy_intents)
| python |
"""
1013 : Contact
URL : https://www.acmicpc.net/problem/1013
Input :
3
10010111
011000100110001
0110001011001
Output :
NO
NO
YES
"""
def test(s):
if len(s) == 0:
return True
if s.startswith('10'):
i = 2
if i >= ... | python |
"""
Simple API implementation within a single GET request.
Generally wrap these in a docker container and could deploy to cluster.
I use cherryPy because it was so simple to run, but heard Flask was pretty
good. So I decided to give it a try.
Wanted to try out connecting pymongo to flask, but was spending too much tim... | python |
# Copyright 2021 DeepMind Technologies Limited. 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 ... | python |
import enum
from EoraReader import EoraReader
from PrimaryInputs import PrimaryInputs
from DomesticTransactions import DomesticTransactions
from os import listdir
from os.path import isfile, join
import pandas as pd
class CountryTableSegment(enum.Enum):
DomesticTransations = 1
PrimaryInputs = 2
class CountryTab... | python |
from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import E... | python |
"""
@author: Jim
@project: DataBrain
@file: exceptions.py
@time: 2020/10/4 17:03
@desc:
"""
class StopException(BaseException):
""" 停止爬
"""
pass | python |
import matplotlib
matplotlib.use('Agg')
import numpy as np, scipy as sci, os, pylab as pyl, sys, smtplib
from trippy import pill
from glob import glob
from astropy.io import fits
from astropy.wcs import WCS
from datetime import datetime, timedelta
# Send email.
def sendemail(from_addr, to_addr_list, cc_addr_... | python |
import collections
import dataclasses
import gc
import multiprocessing
import os
import traceback
from multiprocessing import Lock, Pipe, Pool, Process, Value
from typing import Any, Callable, Dict, Iterable, List, Tuple
from .exceptions import (UnidentifiedMessageReceivedError,
WorkerHasNoUse... | python |
from collections import defaultdict
import numpy as np
import torch
class Filter(object):
def __init__(self):
pass
def __call__(self, cube_acts, **kwargs):
'''
Perform filter on an `activity_spec.CubeActivities` object,
returns a filtered `activity_spec.CubeActivities` object... | python |
import argparse
import numpy as np
import time
import torch
import json
import torch.nn as nn
import torch.nn.functional as FN
import cv2
import random
from tqdm import tqdm
from solver import Solver
from removalmodels.models import Generator, Discriminator
from removalmodels.models import GeneratorDiff, GeneratorDiff... | python |
from django.contrib import admin
from django.contrib.admin import register
from .models import Organization, Employee, Position, Phone, PhoneType
from .forms import EmployeeAdminForm
@register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
pass
@register(Employee)
class EmployeeAdmin(admin.ModelAdmin)... | python |
import os
import subprocess
from typing import Tuple
import pandas as pd
LABEL_MAPPING = {
"Negative": 0,
"Positive": 1,
"I can't tell": 2,
"Neutral / author is just sharing information": 2,
"Tweet not related to weather condition": 2,
}
def load_data() -> Tuple[pd.DataFrame, pd.DataFrame, pd.D... | python |
import itertools
import random
import re
from dataclasses import dataclass
from enum import Enum
from typing import Dict, Iterable, Iterator, List, Tuple, cast
FIELD_SIZE = 10
class GameError(Exception):
"""Game error."""
class CellState(Enum):
UNKNOWN = "unknown"
EMPTY = "empty"
WOUNDED = "wounded... | python |
"""
Sams Teach Yourself Python in 24 Hours
by Katie Cunningham
Hour 4: Storing Text in Strings
Exercise:
1.
a) You're given a string that contains the body of an email.
If the email contains the word "emergency", print out
"Do you wnat to make this email urgent?"
If it contains the word "joke", prin... | python |
import sys
sys.path.append('../')
import codecs
from docopt import docopt
from dsm_creation.common import *
def main():
"""
Weeds Precision - as described in:
J. Weeds and D. Weir. 2003. A general framework for distributional similarity. In EMNLP.
"""
# Get the arguments
args = docopt("""Co... | python |
class renderizar(object):
def savarLegenda(self,legenda,local_legenda):
with open(local_legenda, 'wt') as f:
f.write(legenda)
f.close()
return True
def criarArquivoHTML(self,titulo,local_video,local_legenda,token):
with open('model/template.html','rt') as f:
... | python |
from utils import *
full_exps = []
for k, v in experiments.items():
full_exps.extend(f"{k}={vv}" for vv in v)
print(full_exps) | python |
from mock import patch
print(patch.object)
import mock
print(mock.patch.object) | python |
"""Generate a random key."""
import argparse
import os
from intervention_system.deploy import settings_key_path as default_keyfile_path
from intervention_system.util import crypto
def main(key_path):
box = crypto.generate_box()
crypto.save_box(box, key_path)
if __name__ == '__main__':
parser = argparse... | python |
############################ USED LIBRARIES ############################
from tkinter import *
from tkinter import messagebox
import os, sys, time
import mysql.connector
import queries as q
import datetime as d
import functions as f
from constants import DEBUG, HOST, USER, PASSWORD, DATABASE
###################... | python |
#!/usr/bin/env python3
# Write a program that prints the reverse-complement of a DNA sequence
# You must use a loop and conditional
dna = 'ACTGAAAAAAAAAAA'
rcdna = ''
for i in range(len(dna) -1, -1, -1):
nt = dna[i]
if nt == 'A': nt = 'T'
elif nt == 'T': nt = 'A'
elif nt == 'C': nt = 'G'
elif nt == 'G': nt =... | python |
from math import sqrt
from numpy import matrix
from intpm import intpm
A = matrix([[1, 0, 1, 0], [0, 1, 0, 1]])
b = matrix([1, 1]).T
c = matrix([-1, -2, 0, 0]).T
mu = 100
x1 = 0.5 * (-2 * mu + 1 + sqrt(1 + 4*mu*mu))
x2 = 0.5 * (-mu + 1 + sqrt(1 + mu * mu))
x0 = matrix([x1, x2, 1 - x1, 1 - x2]).T
intpm(A, b, c, x0, ... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 10:57:29 2020
@author: cheritie
"""
# modules for the KL basis computation:
import numpy as np
from astropy.io import fits as pfits
from AO_modules.tools.tools import createFolder
import AO_modules... | python |
from collections import deque
from re import sub
from sys import stderr
p1 = deque([], maxlen = 52)
p2 = deque([], maxlen = 52)
n = int(input()) # the number of cards for player 1
for i in range(n):
p1.append(input()) # the n cards of player 1
m = int(input()) # the number of cards for player 2
for i in range(... | python |
import operator
from pandas import notnull, isnull
from zeex.core.utility.collection import Eval
STRING_TO_OP = {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv,
'%' : operator.mod,
'^' : ... | python |
# tensorflow core
import tensorflow as tf
# a=3,b=5,(a+b)+(a*b)=?
node1 = tf.constant(3.0)
node2 = tf.constant(4.0)
print("node1:", node1, "\nnode2:", node2)
sess = tf.Session()
print("sess.run([node1,node2]):", sess.run([node1, node2]))
node3 = tf.add(node1, node2)
print("node3:", node3)
print("sess.run(node3):", sess... | python |
#!/usr/bin/env python
# encoding: utf-8
"""
display.py is the portion of Death God that manages the screen.
by William Makley
"""
import pygame
from pygame.locals import Rect
from . import colors
from . import settings
from . import fonts
from .map_view import MapView
from . import message
from .status_view import St... | python |
#!/usr/bin/env python
# coding: utf-8
import re
import logging
from collections import defaultdict
from abc import ABC, abstractmethod
from . import strutil
REPLACER = "**"
REPLACER_HEAD = "*"
REPLACER_TAIL = "*"
REPLACER_REGEX = re.compile(r"\*[A-Z]*?\*") # shortest match
ANONYMIZED_DESC = "##"
_logger = logging.... | python |
import pandas as pd
import numpy as np
from sklearn.externals import joblib
from sklearn.preprocessing import LabelEncoder
from functools import partial
import re
num_months = 4
chunk_size = 1000000
indicators = ['ind_ahor_fin_ult1', 'ind_aval_fin_ult1', 'ind_cco_fin_ult1', 'ind_cder_fin_ult1', 'ind_cno_fin_ult1',
... | python |
""" navigate env with velocity target """
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import rospy
from blimp_env.envs.common.abstract import ROSAbstractEnv
from blimp_env.envs.common.ac... | python |
import os.path
import unittest
import unittest.mock as mock
import psutil
import pytest
import fpgaedu.vivado
def find_vivado_pids():
'''
return a set containing the pids for the vivado processes currently
activated.
'''
vivado_procs = filter(lambda p: 'vivado' in p.name(), psutil.process_iter())... | python |
# Copyright 2021 The TensorFlow Authors. 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... | python |
#imports
from random import randint
stDevMonthly = 0.07
stDevWeekly = 0.0095
def getDosageStats(popSize):
exposureStats = []
for i in range(0, popSize):
temp = []
temp.append(randint(3,7))
temp.append(stDevMonthly)
temp.append(stDevWeekly)
exposureStats.append(temp)
... | python |
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
name = 'Jhasmany'
return render_template('index.html', name=name)
@app.route('/client')
def client():
list_name = ['Test1', 'Test2', 'Test3']
return render_template('client.html', list=list_na... | python |
#------------------------------------------------------------------------------
# Get the trending colors.
# GET /v1/color_trends/{report_name}/trending_colors
#------------------------------------------------------------------------------
import os
import json
import requests
from urlparse import urljoin
from pprint ... | python |
#coding=utf-8
from __future__ import print_function
import os
import sys
# Do not use end=None, it will put '\n' in the line end auto.
print('test\r\ntest',end=u'')
# 74 65 73 74 0D 0D 0A 74 65 73 74
# Debug in python Windows source code, it run into
# builtin_print() -> PyFile_WriteObject()->file_Pyobject_Print()->
... | python |
from . import serializers
from rest_framework import generics,authentication,permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
class CreateUserView(generics.CreateAPIView):
serializer_class=serializers.UserApiSerializer
class CreateTokenView(O... | python |
#!/usr/bin/env python
# Load required modules
import matplotlib
matplotlib.use('agg')
import sys, os, argparse, json, matplotlib.pyplot as plt, seaborn as sns, pandas as pd, numpy as np
import matplotlib.patches as mpatches
from models import EN, RF, IMPORTANCE_NAMES, FEATURE_CLASS_NAMES
sns.set_style('whitegrid')
# ... | python |
def other_side_of_seven(num):
dist = 7 - num
num = 7 + (2 * dist)
return num
print(other_side_of_seven(4))
print(other_side_of_seven(12)) | python |
import argparse
def parse():
parser = argparse.ArgumentParser()
parser.add_argument("URL", nargs='?')
parser.add_argument("-s", action="store_true")
parser.add_argument("-l", type=str)
parser.add_argument("-t", type=str)
args = parser.parse_args()
return args
| python |
import torch
from torchtext import data
import numpy as np
import pandas as pd
import torch.nn as nn
import torch.nn.functional as F
import spacy
nlp = spacy.load('en')
SEED = 1
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
TEXT = data.Field(tokenize='spacy')
LABEL = data.LabelField(tensor_type=torch.FloatTen... | python |
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Rating, Site, Picture, Like, Category
class CategorySerialier(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'description', 'icon')
class RatingSerializer(serializer... | python |
#!/usr/bin/env python
import os
import time
import re
import sys
import hashlib
import shutil
import pathlib
import traceback
import subprocess
import pandas
import argparse
from ...shared import shared_tools as st
import lxml.etree as et
from pathlib import Path
from datetime import datetime
from job... | python |
# Generated by Django 1.10.5 on 2017-02-15 08:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('admin', '0008_domain_enable_dns_checks'),
]
operations = [
migrations.RenameField(
model_name='domain',
old_name='quota',
... | python |
#assigning the int 100 to "cars"
cars = 100
#assiging the int 4.0 to "space_in_a_car
space_in_a_car = 4.0
#assigning drivers to the int 30
drivers = 30
#assigning passangers to the int 90
passengers = 90
#assigning cars_not_driver to (cars-drivers)
cars_not_driven = cars - drivers
#assigning cars_driven to drivers
cars... | python |
"""
Copyright 2020 The OneFlow Authors. 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 applicable law or agr... | python |
import codecs
import logging
import time
from concurrent.futures.thread import ThreadPoolExecutor
from pathlib import Path
import frontmatter
from bs4 import BeautifulSoup
from jinja2 import Environment, FileSystemLoader
from aqui_brain_dump import base_url, content_path, get_creation_date, get_last_modification_date... | python |
#! /usr/bin/env python
"""
This script produces the stacks for emission line luminosity limited samples.
"""
import sys
import os
from os.path import join
import glob
import numpy as n
import astropy.io.fits as fits
import SpectraStackingEBOSS as sse
from scipy.interpolate import interp1d
import matplotlib
matplotlib... | python |
import socket
import sys
name = sys.argv[1]
print 'Resolving Server Service Name for ' + name
ipAddress = socket.gethostbyname(name)
print('IP address of host name ' + name + ' is: ' + ipAddress)
| python |
import cStringIO as StringIO
import numpy as np
from sensor_msgs.msg import PointCloud2
#from rospy.numpy_msg import numpy_msg
#PointCloud2Np = numpy_msg(PointCloud2)
import pypcd
import pyrosmsg
pc = pypcd.PointCloud.from_path('./tmp.pcd')
msg = pc.to_msg()
#msg2 = PointCloud2()
#msg2.deserialize(smsg)
def wit... | python |
#!/usr/bin/env python3
# train MNIST with latent equilibrium model
# and track experiment using sacred
import torch
from sacred import Experiment
from sacred.observers import FileStorageObserver
ex = Experiment('layeredMNIST')
ex.observers.append(FileStorageObserver('runs'))
# configuration
@ex.config
def config():... | python |
from django.contrib import admin
from demo_api import models
admin.site.register(models.CustomUser)
# Register your models here.
| python |
# Generated by Django 2.0.7 on 2018-08-06 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0004_auto_20180804_2152'),
]
operations = [
migrations.AlterModelOptions(
name='dac',
options={'ordering': [... | python |
import os
from flask import Flask, redirect
from flask import request
from flask import jsonify
import hashlib
app = Flask(__name__)
c = 0
clients = []
chat = []
#[from, to, status[0sent, 1accepted, 2rejected]]
requests = {}
requests_sent = {}
version = 5
additive = 0
def getUID(ip):
return hashlib.sha256(str(... | python |
from django.apps import AppConfig
from django.db.models.signals import post_migrate
from django.utils.translation import gettext_lazy as _
class SitesConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "webquills.sites"
label = "sites"
verbose_name = _("Webquills sites")
... | python |
import socket
import select
import threading
import json
import sys
import traceback
import os
import random
from clientInterface import ClientInterface
from constants import LOGIN, LOGOUT, CREATE_ACCOUNT, DELETE_ACCOUNT, EXIT, ACTIVE_USERS, ACTIVE_STATUS, INACTIVE_STATUS, OPEN_CHAT, CLOSE_CHAT, DELETE_MESSAGES, SEND_M... | python |
#!/usr/bin/env python
# The MIT License (MIT)
# Copyright (c) 2017 Lancaster University.
# 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
#... | python |
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
from sklearn import neighbors
import numpy as np
from ela.textproc import *
from ela.classification import KNN_WEIGHTING
# These functions were an attempt to have interactive maps with ipywidgets but proved to be a pain... | python |
import os
import six
from six.moves import cPickle
import time
import numpy as np
import modelarts.aibox.ops as ops
from modelarts.aibox.pipeline import Pipeline
import modelarts.aibox.types as types
_R_MEAN = 125.31
_G_MEAN = 122.95
_B_MEAN = 113.87
_CHANNEL_MEANS = [_R_MEAN, _G_MEAN, _B_MEAN]
_R_STD = 62.99
_G_ST... | python |
#!/usr/bin/env python
import flask
from flask import Flask, render_template, request, json, redirect, session, flash
from flaskext.mysql import MySQL
from processor import Processor
from werkzeug import generate_password_hash, check_password_hash
def init_db():
print "Init DB"
print "mysql = ", mysql
pr... | python |
from . import BaseAgent
from pommerman.constants import Action
from pommerman.agents import filter_action
import random
class RulesRandomAgentNoBomb(BaseAgent):
""" random with filtered actions but no bomb"""
def __init__(self, *args, **kwargs):
super(RulesRandomAgentNoBomb, self).__init__(*args, **k... | python |
class Database(object):
placeholder = '?'
def connect(self, dbtype, *args, **kwargs):
if dbtype == 'sqlite3':
import sqlite3
self.connection = sqlite3.connect(*args)
elif dbtype == 'mysql':
import MySQLdb
self.connection = MySQLdb.con... | python |
import re
import requests
import csv
lines = []
with open('01.csv', 'r') as csvFile:
texts = csv.reader(csvFile)
for text in texts:
lines.append(text[0])
datas = []
datass = []
count = 0
# 提取阅读数,评论数,转发数,收藏数
for num in range(0,220):
datas = []
x = lines[num]
w = x[-21:-13]
... | python |
from connaisseur.image import Image
class ValidatorInterface:
def __init__(self, name: str, **kwargs): # pylint: disable=unused-argument
"""
Initializes a validator based on the data from the configuration file.
"""
self.name = name
def validate(self, image: Image, **kwargs) ... | python |
"""
defines:
- CalculixConverter
"""
from collections import defaultdict
from numpy import array, zeros, cross
from numpy.linalg import norm # type: ignore
from pyNastran.bdf.bdf import BDF, LOAD # PBAR, PBARL, PBEAM, PBEAML,
from pyNastran.bdf.cards.loads.static_loads import Force, Moment
class CalculixConvert... | python |
import serial
import serial.tools.list_ports
import time
import threading as thread
class Laser:
def __init__(self):
self.__ser = serial.Serial()
self.pulseMode = None
self.repRate = None
self.burstCount = None
self.diodeCurrent = None
self.energyMode = None
... | python |
# Generated by Django 3.1.5 on 2021-04-15 14:49
from django.db import migrations, models
import django.db.models.deletion
import mptt.fields
class Migration(migrations.Migration):
dependencies = [
('comments', '0001_initial'),
]
operations = [
migrations.AlterField(
model_na... | python |
from datetime import datetime
from flask import (Flask, abort, flash, jsonify, redirect, render_template,
url_for, request)
from flask_bootstrap import Bootstrap
from flask_login import (LoginManager, current_user, UserMixin,
login_required, login_user, logout_user)
from fl... | python |
from hstest import StageTest, TestedProgram, CheckResult, dynamic_test
class Test(StageTest):
answers = [
'#### Hello World!\n',
'plain text**bold text**',
'*italic text*`code.work()`',
'[google](https://www.google.com)\n',
'1. first\n2. second\n3. third\n4. fourth\n',
... | python |
import pytest
from pasee.__main__ import load_conf
from pasee import MissingSettings
import mocks
def test_load_conf():
"""Test the configuration logging"""
with pytest.raises(MissingSettings):
load_conf("nonexistant.toml")
config = load_conf("tests/test-settings.toml")
assert config["host"] ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.