text stringlengths 38 1.54M |
|---|
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from first_app.forms import UserForm, ProfileForm
# Create your views here.
from first_app.models import AccessRecord, UserProfileInfo
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators... |
# coding: utf-8
from .parsers import LogLine
from .processors import RequestByViewProcessor
def parselog(filename, since=None, slow_threshold=None):
fp = file(filename, 'r')
p1 = RequestByViewProcessor(since=since)
for raw in fp:
line = LogLine(raw.strip())
p1.addline(line)
fp.close()
... |
import os
def get_bool_from_env(var_name):
val = os.getenv(var_name, None)
return str(val).lower() not in ("0", "none", "false")
def get_custom_bool_from_env(var_name, default=None):
val = os.getenv(var_name, default)
return str(val).lower() in ('true', 'on', 'ok', 'y', 'yes', '1')
def split_colon... |
from typing import Optional, Tuple, Union
import numpy as np
import gdsfactory as gf
from gdsfactory.components.text import text
from gdsfactory.types import Anchor, LayerSpec
Coordinate = Union[Tuple[float, float], Tuple[int, int]]
@gf.cell_without_validator
def die_bbox_frame(
bbox: Tuple[Coordinate, Coordin... |
import mysql.connector # import liberries of mysql
mydb = mysql.connector.connect(
host="192.168.56.1", #localhost
user="root",
password="root",
database="vaccine"
)
mycursor = mydb.cursor()
#mycursor.execute("create table covaxin(id int(30),name varchar(30),adhar_no varchar(200),vlocation v... |
from pymongo import MongoClient
from flaskr import sqls as sqls
from flaskr import mongo_templates as templates
class MongoDB():
def __init__(self):
self.app = None
self.client = None
self.db = None
def init_app(self, app):
self.app = app
if not self.client:
... |
import tensorflow as tf
import numpy as np
from scipy.special import softmax
import itertools
from model import ASR
from generator import *
import arpa
import os
from prefix_beam_search import prefix_beam_search
from string import ascii_uppercase
"""
Makes a prediction using prefix beam search decoding.
"... |
import pandas_access as mdb
import pandas as pd
db_filename = 'isear_databank.mdb'
# Listing the tables.
for tbl in mdb.list_tables(db_filename):
df = mdb.read_table(db_filename, tbl)
df.to_csv(tbl+'.csv')
# Read a small table.
db = pd.read_spss('ISEAR SPSS Databank.sav')
db.to_csv('isear.csv')
|
from flask import Blueprint, render_template, flash, request, redirect, url_for, jsonify, session
from flask.ext.login import login_user, logout_user, login_required
from sqlalchemy.sql import func
from sqlalchemy.orm import load_only
from hangman.extensions import cache
from hangman.forms import LoginForm, LogonForm
f... |
from django.db import models
class Customer(models.Model):
id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=60)
last_name = models.CharField(max_length=60)
email = models.CharField(max_length=60)
gender = models.CharField(max_length=10)
company = models.CharFiel... |
from typing import List
def swap(nums, a, b):
temp = nums[a]
nums[a] = nums[b]
nums[b] = temp
def move_zeroes(nums: List[int]) -> None:
if len(nums) == 1:
return
# Two pointer approach, one pointer to the first zero found, the last to the first
# non zero element after the first zer... |
temperature = int(input("UserInout temperature : >> "))
if temperature > 30 :
print("Weather is Warm. ")
print("Drink more water.")
elif temperature > 20:
print("It is nice.")
else:
print("It is cold. ")
print("\nDone") |
# from m12_gird_search.py
import pandas as pd
from sklearn.model_selection import train_test_split , KFold, GridSearchCV
from sklearn.metrics import accuracy_score
from sklearn.utils.testing import all_estimators
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
# 1. 데이터
iris = pd.r... |
# find_element_by_partial_link_text通过部分唯一的连续文本信息去定位某一个控件
# 1.从selenium库导入webriver模块
from selenium import webdriver
import time
# 2.初始化webdriver类的一个对象命名为driver,操作chrome浏览器
driver = webdriver.Chrome()
# 3.调用get()方法打开url地址,对象名.方法名
driver.get("http://101.133.169.100/yuns/index.php")
# 4.推迟执行2秒钟
time.sleep(2)
# 5.对象名.find_e... |
def majority_element(a):
candidate, count = a[0], 0
for element in a:
if element == candidate:
count += 1
else:
count += -1
if count == 0:
candidate, count = element, 1
if a.count(candidate) > len(a)/2:
return candidate
else:
... |
#https://www.roytuts.com/upload-and-display-image-using-python-flask/
import os
import uuid
import urllib.request
from fastai2.learner import load_learner
from flask import Flask, flash, request, redirect, url_for, render_template
app = Flask(__name__)
learner_inference = load_learner('../models/coins.pkl')... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Forecasting in Python with Prophet"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import os
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import boxcox
from scipy.special import inv... |
# -*- coding: utf-8 -*-
# GMate - Plugin Based Programmer's Text Editor
# Copyright © 2008-2009 Alexandre da Silva
#
# This file is part of Gmate.
#
# See LICENTE.TXT for licence information
import gtk
import editor
class Gmate(object):
def __init__(self):
self.editor = editor.GmateEditor()
self... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayFundTransCollectSinglemoneytokenCreateResponse(AlipayResponse):
def __init__(self):
super(AlipayFundTransCollectSinglemoneytokenCreateResponse, self).__init__()
... |
import re
shoppingListRegex = re.compile(r'\d+\s\w+')
list: str = input()
mo = shoppingListRegex.search(list)
print(mo.findall())
|
#-*- coding:utf-8 -*-
import smtplib
from Config import MailConf
from email.mime.text import MIMEText
from email.header import Header
if __name__ == '__main__':
mSender = MailConf.sender
senderName = MailConf.username
senderPwd = MailConf.password
# 邮件标题
subject = u'python se... |
import socket
import binascii
import time
import random
from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit,
QTextEdit, QGridLayout, QApplication, QPushButton,
QMainWindow, QFileDialog, QMessageBox)
from PyQt5.QtGui import QFont
from PyQt5.QtCore import QRegExp, QMetaObject
import s... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\MyTest\LoginTest.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
# from PyQt5.QtWidgets import QWidget, QPushButton, QLineEd... |
import cgi
import pickle as pkl
import numpy as np
form = cgi.FieldStorage()
age = int(form.getvalue('age'))
gender = int(form.getvalue('gender'))
temp = int(form.getvalue('temp'))
body_pain = int(form.getvalue('pain'))
runny_nose = int(form.getvalue('runny_nose'))
breath = int(form.getvalue('breath'))
na... |
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
import os
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
CORS(app)
|
import numpy as np
import matplotlib.pyplot as plt
import random
import os
import seaborn as sns
from scipy.stats import gaussian_kde
def show_galaxy(alias):
if alias[0:2] == 'HP':
a = np.load('..//DATA//HP_inputs//' + alias + '.npy')
if alias[0:2] == 'MP':
a = np.load('..//DATA//MP_inputs//'... |
import sys
import re
def fill_to_end(inp, i, end):
buf = ''
while inp[i] != end:
buf += inp[i]
i += 1
return i, buf
def find_tokens(inp):
tokens = []
buf = ''
i = 0
while i < len(inp):
c = inp[i]
if c == 'r':
if inp[i+1] == "'":
... |
def valid_sol(w1,w2):
prefixes = ['re', 'de', 'co', 'pre', 'in', 'pro', 'di', 'ca', 'cu',
'ba', 'des', 'al', 'bi', 'mi', 'ta', 'tri', 'ex', 'ar', 'st', 'anti',
'para', 'im', 'per', 'ci', 'mono', 'ce', 'că', 'la', 'si', 'dis', 'mă',
'poli', 'or', 'mu', 'fi', 'ga', 'cur', 'ha', 'sur', 'col',
'ad',... |
# Using movie reviews dataset
# Dataset contains 1000 positive and 1000 negative processed reviews
import random
from nltk.corpus import movie_reviews
documents = [(list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fil... |
# benchmark with simple baseline model
import os
import json
import pandas as pd
from sklearn.model_selection import train_test_split
import efficientnet.keras as eff
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, ... |
import schnetpack as spk
import torch
import torch.nn as nn
from torch.autograd import grad
from schnetpack import Properties
from schnetpack.atomistic import Atomwise
import schnarc
from schnarc.data import Properties
class StateModel(nn.Module):
def __init__(self, representation, output_modules, mapping=None)... |
def solution(n):
dfs([], n)
def dfs(ret,n):
if len(ret) >= n:
print ret
return
for i in range(1,1+n):
if i in ret:
continue
ret.append(i)
dfs(ret,n)
ret.pop()
solution(5)
|
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Mail(models.Model):
keyLength = 36
sender = models.ForeignKey(User)
timestamp = models.DateTimeField(auto_now_add= True,null=True)
subject = models.Tex... |
import argparse
from lib.mode import get_by_mode
from lib.readme import README
from lib.options import POOL_DEFAULT
def cli(mode):
parser = argparse.ArgumentParser(
description='Get the most likely yet missing English words.'
)
parser.add_argument(
'--pool', '-p',
type=int, defaul... |
# coding:utf-8
from django.db import models
from django.contrib.auth.models import AbstractUser
from datetime import datetime
# Create your models here.
class UserInfo(AbstractUser):
nick_name = models.CharField(max_length=50,verbose_name=u'昵称')
birthday = models.DateField(verbose_name=u'生日',null=True,blank=... |
from domain.Person import Person
p1 = Person("Juani", 41)
print(p1(1, 2))
print(p1.name, ' is ', p1.age, 'years old!!')
|
#%% code imports
from keras.models import Sequential, Model
from keras.layers import Dense, Input
from keras.callbacks import EarlyStopping
from keras.regularizers import l2
#%% functions definition
def build_model(x_train, y_train, x_model_val, y_model_val, configs, problem_type):
'''function to build the feed f... |
# 69 Sqrt(x)
'''
Implement int sqrt(int x).
Compute and return the square root of x.
'''
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
start=1
end=x
while end-start>1:
mid=(start+end)/2... |
a="stressed"
print(a)
b=a[::-1]
#-1で後ろからの取り出しのため逆順となる
print(b) |
"""monblog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
"""
Question 12
Question:
Write a program, which will find all such numbers between 1000 and 3000 (both included)
such that each digit of the number is an even number.The numbers obtained should be printed
in a comma-separated sequence on a single line.
Hints:
In case of input data being supplied to the question, it s... |
#!/bin/env python3
#-*- encoding: utf-8 -*-
def sample_2_sec(samples, fs):
"""Converts sample to time according to the sample frequency argument.
"""
samples = float(samples)
time = samples / fs
time_rnd = round(time, 3)
return time_rnd
|
import json
from typing import Optional, Union
import pytz
from dateutil.parser import isoparse
from django.utils import timezone
from posthog.models.property import Property
def is_json(val):
if isinstance(val, int):
return False
try:
int(val)
return False
except:
pass
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-08-09 15:02
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('case', '0011_auto_20180731_1409'),
]
operations = [
migrati... |
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
#
f1 = plt.figure("figure 1")
plt.plot(ypoints, 'o:b')
plt.xlabel("X1")
plt.ylabel("Y1")
f1.show()
#
f2 = plt.figure("figure 2")
# ms = MarkerShape, mec = MarkerEdgeColor, mfc = MarkerFaceColor, ls = linestyle
# dotted = :
plt.plot(... |
"""Routines for array manipulations
Routines are mostly an interface for numpy or cupy.
"""
from typing import List
from typing import Tuple
import numpy as np
from nucleon_elastic_ff.utilities import set_up_logger
LOGGER = set_up_logger("nucleon_elastic_ff")
# Cupy captured becaus can only be installed if GPU is ... |
# -*- coding: utf-8 -*-
"""
FileIntro:Wallet, control balance
Created on Fri Aug 21 20:42:39 2020
@author: Archer Zhu
"""
import numpy as np
class Wallet:
'''For saving holding positions, count in units
'''
def __init__(self, initial_cash = 100):
self.holding={'cash':initial_cash}
de... |
import numpy as np
from WindFarm import *
from grid import *
from itertools import combinations
from Farm_Evaluator_Vec import *
import random
MUTATION_RATE = 0.20
def mutate(child,grid):
"""
Mutates a child generated from crossover.
We select a random turbine location
and change it to some other rand... |
class CaseData:
"""
A test case.
Attributes
----------
molecule : :class:`.Molecule`
The molecule to test.
canonical_atom_ids : :class:`dict`
The correct mapping of atom ids in :attr:`.molecule` to their
canonical atom ids.
"""
def __init__(self, molecule, can... |
{
'name': 'Amount to Word',
'author': 'OptesisSA',
'version': '1.3.0',
'category': 'Tools',
'description': """
permet de faire une descripotion ...
""",
'summary': 'Module de ...',
'sequence': 9,
'depends': ['base', 'account'],
'data': [
],
'test': [
],
'installa... |
"""
使用input()函数获取键盘输入(字符串)
使用int()函数将输入的字符串转换成整数
使用print()函数输出带占位符的字符串
Version: 0.1
Author: 余超
"""
a = int(input('a = '))
#输入一个数值给a赋值,并打印a=输入数值
b = int(input('b = '))
#输入一个数值给b赋值,并打印b=输入数值
print('%d + %d = %d' % (a, b, a + b))
#打印a+b=a+b的结果
print('%d - %d = %d' % (a, b, a - b))
#打印a-b=a-b的结果
print('%d * %d = %d' % (a... |
fi = open("sequence.nucleotide.fasta", "r")
seq = ""
for line in fi:
if line.startswith(">"):
continue
seq += line.strip()
fi.close()
n = 0
for base in seq:
if n >= len(seq):
break
print(seq[n : n + 3])
n += 3
|
import os.path as osp
import os
import mmcv
import torch
import numpy as np
from PIL import Image
from mmcv.utils import print_log
from .builder import DATASETS
from .custom import CustomDataset
from tqdm import trange
def covert_color(input):
str1 = input[1:3]
str2 = input[3:5]
str3 = input[5:7]
r =... |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
from distutils.core import setup, Extension
mdl = Extension('_test', sources = ['src/c/test.c', 'src/c/struct.c'])
setup(name = '_test',
version = '1.0',
description = 'Python C API Simplest Module',
ext_modules = [mdl]) |
import os
import numpy as np
import json
import argparse
import pickle
import tensorflow as tf
from pixel_cnn_pp import nn
from pixel_cnn_pp.model import model_spec
#import ipdb
# -----------------------------------------------------------------------------
parser = argparse.ArgumentParser()
# data I/O
parser.add_argu... |
from src.entrypoints.converter.beleza_get_treatment_converter \
import BelezaGetTreatmentConverter
class BelezaTreatmentConverterStrategy:
@staticmethod
def convert(response):
return BelezaGetTreatmentConverter().to_entity(response)
|
from collections import defaultdict
import marshal
import os
import sys
import re
def word_count_mapper(key, value):
words = re.findall(r'\w+', value)
word_dict = defaultdict(int)
for word in words:
if word.isdigit():
continue
word_dict[word.lower()] += 1
word_list = [(key,... |
#!C:/python34/python
import cgi
import mysql.connector
print("Content-type: text/html")
print("")
form=cgi.FieldStorage()
cn=form.getvalue("uname");
ct=form.getvalue("sub");
pn=form.getvalue("desc");
pp=form.getvalue("rate");
cnx = mysql.connector.connect(user='root', password='',
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
def fab(n):
a,b = 0,1
while b<n:
print(b)
a, b = b, a+b
fab(1000)
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
matrix2 = list(zip(*matrix))
print(matrix2)
|
# Copyright 2020 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... |
# -*- coding:utf-8 -*-
# @Time : 2020/3/2 16:37
# @Author : litao
# -*- coding:utf-8 -*-
# @Time : 2020/3/2 11:07
# @Author : litao
# -*- coding:utf-8 -*-
# @Time : 2020/2/28 12:09
# @Author : litao
import requests
import json, re, datetime, urllib
from crawler.crawler_sys.utils.output_results import retry_get_url
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Tkinter import *
__author__ = 'zengxianxi'
class ScrolledList(Frame):
def __init__(self, master=None, files=[], parent=None):
Frame.__init__(self, master)
self.pack(expand=YES, fill=BOTH)
self.makeWidgets(files)
def processEvent(self... |
# relative import "from ..data.multi-instrument" will not work because of the
# "-" in "multi-instrument"... this is the easiest trick I found
import sys
import astropy.units as u
import config
import matplotlib.pyplot as plt
import numpy as np
from astropy.constants import c
from gammapy.estimators import FluxPoints... |
from __future__ import unicode_literals
import logging
import os
from subprocess import call
import os.path
from qiller.utils import q_enc, q_dec
from what_transcode.utils import pthify_torrent
BAD_FILES = ['.ds_store', 'thumbs.db']
logger = logging.getLogger(__name__)
def remove_bad_files(temp_dir):
for f i... |
def min(x, y):
out = []
length = len(x)
a = 0
while length != a:
if x[a] < y[a]:
out.append(x[a])
else:
out.append(y[a])
a += 1
print(out)
x= [10,2,30,4]
y= [1,20,3,40]
min(x, y)
|
import random
import time
length=random.randrange(10,100)
def JumblingBlock(number,length):
cset = list(map(chr, range(97, 10000)))
# print('Random length:',length)
rlength=length
for i in range(0,length):
x=random.randrange(0,len(cset))
number=number+cset[x]
# print (... |
import pygame
import random
from pygame_ninjia_settings import *
class GrassPlatformDecoration(pygame.sprite.Sprite):
images_decor = [
pygame.image.load('assets/grass/grass_ground_Deco/Bush (1).png'),
pygame.image.load('assets/grass/grass_ground_Deco/Bush (2).png'),
pygame.image.load('asse... |
from base_handler import BaseHandler
from abc import abstractmethod
from image import Image
class AbstractHandler(BaseHandler):
"""
Zincirin bir sonraki halkasının referansının tutulduğu sınıftır.
İşlemi gerçekleştirecek olan metot tanımı bulunur.
UML diyagramındaki BaseHandler sınıfına denk gelmekted... |
import os
from .events import Logger, KinesisEvents
from .splice import MaccorSplice
def os_format(json_string):
"""
Helper function to format json string into something
that can be parsed on the command line. For nt (windows)
systems, uses enclosing double quotes and escaped quotes,
for POSIX sy... |
"""
Write all the code here
"""
#%% imports (they work fine)
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import seaborn as sns
import sys
import pandas_profiling
sns.set()
from sympy import latex
#%% Create dataframe
nut = pd.read_csv('nutrition.csv', index_col=1) #nu... |
import os
import random
from typing import List
import pandas as pd
import numpy as np
## Modelling
from transformers import AutoTokenizer
import torch
from torch.utils.data import (
TensorDataset,
RandomSampler,
SequentialSampler,
DataLoader
)
## Metrics / Utils
from sklearn.preprocessing import La... |
import sys
def check(cmd, mf):
m = mf.findNode('pkg_resources')
if m is None or m.filename is None:
return None
for pkg in ['packaging', 'pyparsing', 'six', 'appdirs']:
mf.import_hook('pkg_resources._vendor.' + pkg, m, ['*'])
expected_missing_imports = [
'__main__.__requires__... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-01-07 07:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.manager
class Migration(migrations.Migration):
initial = True
dependencies = [
('finance... |
from tthAnalysis.HiggsToTauTau.configs.analyzeConfig import *
from tthAnalysis.HiggsToTauTau.jobTools import create_if_not_exists
from tthAnalysis.HiggsToTauTau.analysisTools import initDict, getKey, create_cfg, generateInputFileList
from tthAnalysis.HiggsToTauTau.common import logging
import jinja2
import copy
jinja... |
from django_elasticsearch_dsl import Document, fields
from django_elasticsearch_dsl.registries import registry
from toxsign.superprojects.models import Superproject
@registry.register_document
class SuperprojectDocument(Document):
tsx_id = fields.KeywordField()
created_by = fields.ObjectField(properties={
... |
from pdb import set_trace
from time import sleep
import random
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
ROOT_URL = 'https://www.work.ua/ru/jobs/'
def random_sleep():
sleep(random.randint(1, 3))
useragent = UserAgent()
page = 0
ids = set()
with open('./workua.txt', 'w')... |
# Copyright 2019 The Feast Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
from nltk import *
from collections import Counter
ngram_counts = Counter()
print("\n")
ngram_count = Counter()
with open('bible english.txt', encoding='utf-8') as bigtxt:
for l in bigtxt:
ngram_count.update(Counter(ngrams(l.split(), 3)))
print(ngram_count.most_common(100)) |
def move(controller):
player = controller.owner
# Check if neither the left or right keys are being pressed.
if (player["xThrust"] == False):
# Set negligable horizontal speeds to zero so that the spaceship eventually stops.
if ((player["xSpeed"] > -0.03) and (player["xSpeed"] < 0.03)):
... |
import files
import logic
import pygame
import random
from pygame import *
from pygame import gfxdraw
from pygame import font
from pygame import image
bgSurface = 0
gfxSurface = 0
toolSurface = 0
hbSurface = 0
invSurface = 0
scrn = [0, 0, 32, 24, 10]
scale = 5
bgcol = (120, 255, 241)
forestbg = pygame.image.load("Im... |
"""Stores the NDArray array class, that contains NDArray metadata.
This can be used to store an NDArray as a JSON object.
"""
import typing as ty
import json
import numpy as np # only used for typing
np_type_to_single_char: ty.Dict[ty.Text, np.dtype] = {
v: c for c, v in np.sctypeDict.items()
if isinstance(c,... |
# coding:gbk
from socket import *
import sys
from time import sleep
if len(sys.argv) < 3:
print('参数输入错误!')
sys.exit(1)
host = sys.argv[1]
port = sys.argv[2]
addr = (host,int(port))
#创建套接字
sockfd = socket(AF_INET,SOCK_STREAM,0)
#连接服务端
while True:
try:
sockfd.connect(addr)
except ConnectionR... |
#coding:utf8
import numpy as np
import torch as t
from torch import nn
from torch.autograd import Variable
from torch.nn import functional as F
from .basicmodule import BasicModule
class Model_M(BasicModule):
def __init__(self,param):
super(Model_M,self).__init__()
self.param = param
self.feature_dim = param.fe... |
# -*- coding: utf-8 -*-
# @Time : 2021/1/18 21:37
# @Author : qtf
# File : request_handler.py
import requests
from common.logger_handler import logger
from middleware.handler import Handler
def send_requests(datas):
method = datas["method"]
url = Handler.env_config["envurl"] + datas["path"]
head... |
import pygame as pg
from settings import *
from random import choice, randrange
vec = pg.math.Vector2
class Player(pg.sprite.Sprite):
def __init__(self, game):
self._layer = PLAYER_LAYER
self.groups = game.all_sprites
pg.sprite.Sprite.__init__(self, self.groups)
self.game = game
... |
from django.http import HttpResponse
from django.template import RequestContext, loader
#for getting user data
from django.contrib.auth.models import User, Group
#for auth and login
from django.contrib.auth import authenticate, login
#for login required decorator
from django.contrib.auth.decorators import login_requ... |
"""swapi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... |
import boto3
client = boto3.client('dynamodb',
endpoint_url='http://localhost:8000/ ')
client.list_tables( )
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 16 22:38:08 2015
@author: jchen
"""
import pandas as pd
import sqlite3
import numpy as np
pd.set_option('display.max_columns', None)
conn = sqlite3.connect('/Users/jchen/Documents/SQLite/lahman2013.sqlite')
# pull in all metrics from hw #5 for players inducted into ... |
L1 = [9, 41, 12, 3, 74, 15, 20, 21, 7]
number = int(input('search for: '))
found = False
for i in L1:
if i == number:
found = True
break
print('i=', i, 'found', found)
print('---------------------')
if found:
print('found')
else:
print('not found')
|
__author__ = 'hibiki'
#Test
import sys
from PyQt4 import QtGui
from Widgets.frequency import FrequencyWidget
from Widgets.amplitude import AmplitudeWidget
from Widgets.mainmenu import MainMenuWidget
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.shar... |
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.staticfiles import finders
from django.utils import timezone
from django.contrib.auth.models import User
from jokeoverflow.forms import *
from jokeoverflow.models import *
class GenericTests(TestCase):
def test_work... |
from PyQt5.QtWidgets import QDialog
from PyQt5.QtGui import QImage, QPixmap
from .procui import Ui_proc
import cv2
class AppFrame(QDialog):
def __init__(self):
super(AppFrame, self).__init__()
self.ui = Ui_proc()
self.ui.setupUi(self)
# 加载图像
self.img = cv2.imread("./imgapp/g... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index_page(request):
return HttpResponse("<h3>测试开发</h3>")
|
# -*- coding: utf-8 -*-
# This script was adapted from the tutorials of the neurokit project https://neurokit.readthedocs.io/
# Processes an AcqKnowledge format file from an EDA record in which there are two channels: EDA100C and
# Digital input. The triggers were recorded on the digital input.
# After the analysis, ... |
import os, sys
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
print(os.getcwd())
today = datetime.today()
print(today)
date = today - relativedelta(days= 20)
str_date = date.strftime("%Y-%m-%d")
print(str_date)
obj_date = datetime.strptime(str_date, "%Y-%m-%d")
print(o... |
from unittest import TestCase
import io
from unittest.mock import patch
from game import boss_battle_print_health_values
from game import make_player
from game import make_appropriate_boss_phase
class Test(TestCase):
@patch("sys.stdout", new_callable=io.StringIO)
def test_boss_phase_one_print_health_values(se... |
import threading
import time
class x(threading.Thread):
def run(self):
lc.acquire()
myfun("django")
lc.release()
class y(threading.Thread):
def run(self):
lc.acquire()
myfun("flask")
lc.release()
def myfun(msg):
print("{ hello [",msg)
time.sleep(5)
print("] world }")
lc=threading.Lock... |
'''Athelets module with sorted and sanitized lists with list index access'''
def sanitize(time_sting):
if '-' in time_sting:
splitter = '-'
elif ':' in time_sting:
splitter = ':'
else:
return time_sting
(mins, secs) = time_sting.split(splitter)
return mins + '.' + secs
j... |
#Questão 2
#Informe a idade: 25
#Tem obrigação de votar.
def obrigacao_votar():
idade = int(input("Informe a Idade "))
while idade <= 0:
print("Idade Inválida")
idade = int(input("Informe a Idade"))
#Informe a idade: 75
#Não tem obrigação de votar.
if idade >= 16 and idade < 18 or idade > 70:
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.