text stringlengths 8 6.05M |
|---|
print("julia safada") |
# Libraries for Path Management and Handling Directories
import os
from os import makedirs
from os import listdir
from shutil import copyfile
from shutil import rmtree
from random import seed
from random import random
# Main Directory, adjust according to your File System Structure
os.chdir("C:/github_simba_... |
import psycopg2
conn = psycopg2.connect(database="news")
cursor = conn.cursor()
cursor.execute('''select articles.slug, count(log.path) as a from
articles join log on SUBSTRING( log.path, 10)=articles.slug
group by articles.slug order by a desc limit 3;''')
results = cursor.fetchall()
print('1. What are the most popu... |
from jBird.utils.Constants import PlayerPos
class Player(object):
"""Class containing methods and attributes referring to current player."""
def __init__(self, nick):
"""Player initialize."""
self.nick = nick
self.hp = 2
self.points = 0
self.width = PlayerPos.START_WID... |
from celery.task import Task
from celery.registry import tasks
from celery.task import PeriodicTask
import datetime
from datetime import timedelta
from django.db.models import F
#from yoolotto.second_chance.models import ResetCoins
import celery
|
import random
import time
from tkinter import *
root = Tk ()
canv = Canvas (root, width = 600, height = 500)
canv.pack ()
A = [0] * 100
for i in range (len (A)):
A[i] = random.randint (1, 100)
for n in range(len (A)):
m = A[n]
for j in range (len(A) - n):
if A[j + n] > m:
m = A[j + n]
... |
import re
def is_pangram(sentence):
letters_seen = ''
alphabet_re = re.compile('[a-z]')
for letter in sentence.lower():
if alphabet_re.search(letter):
if letter in letters_seen:
next
else:
letters_seen += letter
if len(letters_seen) == 26... |
#!/usr/bin/env python
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# print(line)
# split the line into words
words = line.split(",")
year = ''
if len(words) == 3:
if "-" in words[0]:
... |
import web
import config
import firebase_admin
import cloudinary.uploader
db = config.db
cloudinary.config(
cloud_name = "patyluprz",
api_key = "448467956332495",
api_secret = "iovK969N-ZReTDBMukFZp8JKrq0"
)
def insertFoto(image):
try:
result = cloudinary.uploader.upload(image)
return r... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255)
train_generator = train_datagen.flow_from_directory(
'../data',
classes=['dirty_mnist_2nd'],
batch_... |
import math
class Machine:
def __init__(self, id):
self.id = id
self.running_job_id = -1
self.is_free = True
self.job_history = []
def taken_by_job(self, job_id):
if self.is_free:
self.running_job_id = job_id
self.is_free = False
sel... |
# @Title: 根据身高重建队列 (Queue Reconstruction by Height)
# @Author: 2464512446@qq.com
# @Date: 2020-11-16 11:39:35
# @Runtime: 116 ms
# @Memory: 14 MB
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
if len(people) <= 1:
return people
people = sorted... |
# weight value
# item1 5 60
# item2 3 50
# item3 4 70
# item4 2 30
# max_weight=5 find max value we can get!
# ans:80
# we choose item4 and item2
weight=[5,3,4,2]
max_weight=5
value=[60,50,70,30]
dp_matrix=[[None for j in range(max_weight+1)] for i in range(len(value... |
class Room:
tag = 1
def __init__(self,name,owner,width,length,height):
self.name=name
self.owner=owner
self.width=width
self.length = length
self.height=height
@property #
def mianji(self):
return self.width * self.length
@property #静态属性 把函数封装成属性
... |
# Generated by Django 3.0.3 on 2020-02-29 15:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('njrealestate', '0004_auto_20200229_1514'),
]
operations = [
migrations.CreateModel(
name='Propertyclassifications',
... |
print('_'*30)
print('\nSequência de Fibonacci')
print('_'*30)
termo = int(input('Digite quantos termos você quer mostrar: '))
t1 = 0
t2 = 1
print(f'{t1} ➞ {t2}', end=' ')
cont = 3
while cont <= termo:
t3 = t1 + t2
print(f'➞ {t3}', end=' ')
t1 = t2
t2 = t3
t3 = t1 + t2
cont += 1 |
{
'name': 'Advanced Pivot Table',
'version': '8.0.0.1',
'author': 'Geo Technosoft',
'sequence':'10',
'category': 'Hidden',
'website': 'https://www.geotechnosoft.com',
'summary': 'Custom Pivot Table',
'description': """
This module will add new features pivot table like click on td.
... |
'''
Usos comuns:
-Redes
-Requisições
-Abrir ou fechar arquivos
'''
try:
open("Alou")
except Exception as erro:
print("Erro capturado:", erro, "\n")
print("Arruma aê bocó") |
{
"name" : "econube_report",
"version" : "7.0",
"author" : "Econube | pablo cabezas",
"category" : "reportes account",
"description" : "reportes facturas tipo chilean",
"init_xml" : [],
"update_xml" : [
'eco_report.xml',
],
"depends" : ['base','account'],
"active" : False... |
#!/usr/bin/env python
"""
_SetLocation_
MySQL implementation of Files.SetLocation
"""
from WMCore.Database.DBFormatter import DBFormatter
class SetLocation(DBFormatter):
sql = """INSERT INTO wmbs_file_location (fileid, location)
SELECT :fileid, wmbs_location.id FROM wmbs_location
INN... |
... the content of __init__.py file.
... definition in __init__.py file will tell other
... python files how is the code hierarchy.
your_package/
__init__.py
file1.py
file2.py
...
fileN.py
# in __init__.py
from .file1 import *
from .file2 import *
...
from .fileN import *
# in file1.py
def add():
... |
from xmind.core.markerref import MarkerRefsElement
from xmind.core.const import TAG_MARKERREFS
from xmind.tests import logging_configuration as lc
from xmind.tests import base
from unittest.mock import patch
class MarkerRefsElementTest(base.Base):
"""MarkerRefsElementTest"""
def getLogger(self):
if n... |
import pickle
def save_to_pickle(variable, filename):
with open(filename, 'wb') as handle:
pickle.dump(variable, handle)
def open_pickle(path_to_file):
with open(path_to_file, 'rb') as handle:
f = pickle.load(handle)
return f
class Caching:
def __init__(self):
self.access_list... |
# add path to the src and test directory
import os
import sys
PARENT_PATH = os.getenv('PYMCTS_ROOT')
SRC_PATH = PARENT_PATH +"src/"
TEST_PATH = PARENT_PATH +"test/"
sys.path.append(SRC_PATH+"algorithm")
sys.path.append(TEST_PATH)
sys.path.append(PARENT_PATH+"performance/accuracy/testset")
sys.path.append(PARENT_PATH+"p... |
# 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
name1_lower = name1.lower()
name2_lower = name2.lower()
t1=name1_lower.count("... |
from django.apps import AppConfig
class SpinnerConfig(AppConfig):
name = 'spinner'
|
import time
from datetime import datetime
from features.feature import Feature
from field import Field
from numbersforwatch import Number
from painter import RGB_Field_Painter, Led_Matrix_Painter
class Clock(Feature):
def __init__(self, field_leds: Field, field_matrix: Field, rgb_field_painter: RGB_Field_Painter,... |
#import sys
#input = sys.stdin.readline
def prime_factor(N): #素因数
ret = 0
middle = int( N**(1/2))
for i in range(2, middle+1):
if N%i == 0:
return i
return N
def factors(N): #約数を全て求める。ただし、順不同
from collections import deque
ret = deque()
middle = int( N**(1/2))
for i i... |
def paty_planner(people ,cook):
cooks = cook // people
left = people % cook
print("Good! Your Paty will have {} people witch a total of {} cookies each people will eat {}and will left {}".format(people,cook,cooks,left))
paty_start = 'y'
while paty_start == 'y':
while True:
try:
people = int(i... |
from . import *
class IsRestartRequiredCommand(ShellCommand):
name = "needs_restart"
command = "sh -c 'if test -f /var/run/reboot-required.pkgs ; then cat /var/run/reboot-required.pkgs; fi'"
desc = "checks whether a reboot is required (Ubuntu-only)"
supported = "linux"
@staticmethod
def parse(output=None):
if... |
"""empty message
Revision ID: e400dee696f2
Revises: 5d6b56b7dc32
Create Date: 2018-10-30 21:04:00.455078
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e400dee696f2'
down_revision = '5d6b56b7dc32'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from typing import List
import numpy as np
def cal_q_error(predict, label, log=True):
if log:
predict = np.e**predict
label = np.e**label
if predict > label:
q_error = predict / label
else:
q_error = label / predict
return q_error
def print_qerror(q_error: List):
... |
from typing import Any, Dict, List
from .base_api import BaseAPI
class TransactionService(BaseAPI):
URL_BY_NETWORK = {
1: 'https://safe-transaction.mainnet.gnosis.io',
# 3:
4: 'https://safe-transaction.rinkeby.gnosis.io',
# 5:
# 42
}
def get_balances(self, safe_ad... |
print "hello,world"
print "Muxistdio yuyilei"
|
from itertools import product
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
f = lambda x: (x.lower(), x.upper()) if x.isalpha() else (x)
return list(map(''.join, product(*map(f, S)))) |
from bp.Model import Model
import numpy as np
# 卷积神经网络 架构 还不错。。
x = np.ones([8,2,2,1])
x[(1,3,5,7),:,:,:] = np.zeros([4,2,2,1])
y = np.array([[1, 0, 1, 0, 1, 0, 1, 0]])
model = Model(x, y,inputType='image')
model.addConv(shape=(2,2,1,1),ifOutput=False)
model.addReshape(shape=[8,1])
model.addLayer(10,'sigmoid',False)
m... |
# try:
# for i in ['a','b','c']:
# i = int(i)
# print (i**2)
# except TypeError:
# print("Une erreur s'est produite ! ")
# def demande():
# while True:
# try:
# n = int(input("Entrer un entier: "))
# except:
# print("Merci d'entre un entier a nouve... |
import time
# Read in data
def get_data(filename, features_in_use):
global top_file_line
file = open(filename)
top_file_line = file.readline()
data = []
for line in file:
data_points = line.split(",")
# Get the features as an np vector
features = [float(x) for x in data_poin... |
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^$', 'app.views.home', name='home'),
url(r'^paypal/data.json$', 'app.views.data', name='data'),
url(r'^paypal$', 'app.views.paypal', name='paypal'),
url(r'^graphite$', 'app.views.graphite', name='graphite'),
url(r'... |
"""
This is a password generator script that works as follows:
It allows the user to enter a word or phrase and the length they would like for the password.
If it is over 20 characters then it will ask if they are sure as long passwords aren't memorable unless stored.
If they do not provide a word or phrase it will c... |
# -*- coding: UTF-8 -*-
import numpy as np
import pandas as pd
train_data = pd.read_csv("train.csv", header=0, delimiter=',')
test_data = pd.read_csv("test.csv", header=0, delimiter=',')
result = pd.read_csv("gender_submission.csv", header=0, delimiter=',')
result = result['Survived']
class Datasets:
def __init__(s... |
import logging
import os
import shutil
from pathlib import Path
import tempfile
import pandas as pd
from autumn.core import db, plots
from autumn.settings import REMOTE_BASE_DIR
from autumn.infrastructure.tasks.utils import get_project_from_run_id
from autumn.core.utils.s3 import download_from_run_s3, list_s3, upload... |
from django.db import models
class Pizza(models.Model):
name = models.TextField(max_length=50)
def __str__(self):
if len(self.name) > 20:
return self.name[:20] + ...
else:
return self.name
class Topping(models.Model):
name = models.TextField(max_length=50)
pi... |
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://inventwithpython.com')
head = browser.find_element_by_id('headerimage')
linkr = head.get_attribute('alt')
print(linkr)
#browser.close()
|
from django.dispatch import receiver
from bifrost.signals import init_service
from bifrost.src.ioc.ServiceContainer import Container
from bifrost_location.Services import Location
@receiver(init_service)
def declare_services(sender, **kwargs):
Container.set_service('location_service', Location.Service)
|
import pytest
from django.test import TestCase, override_settings
from .utils import MIDDLEWARES_FOR_TESTING
class TestResponseFunctionWithoutUser(TestCase):
def test_middleware_simple_get_request(self):
try:
self.client.get('/restframework/simple/')
except Exception as e:
... |
import crc
from itertools import chain, product
HEX_STRIP = [hex(i)[2:] for i in range(0, 16)]
CRC_TARGET = '4930'
FORMATTED_PARTIAL_INPUT = '1b{}beaf'
BLANK_MIN_LEN = 4
BLANK_MAX_LEN = 4
def bruteforce(strip, min_length, max_length):
"""
returns all options of the strip characters in required length
:pa... |
import pygame
from config import (
PLAYER_IMAGE,
PLAYER_SIZE,
PLAYER_HP,
PLAYER_POSITION,
PLAYER_SPEED,
PLAYER_FIRE_CADENCE,
PLAYER_BULLET_LINES,
PLAYER_BULLET_SPEED,
PLAYER_BULLET_SIZE
)
from Entity import Entity
from Bullet import Bullet
class Player(Entity):
def __init_... |
# Generated by Django 3.1.1 on 2020-11-27 09:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0012_post_etime'),
]
operations = [
migrations.AlterField(
model_name='post',
name='event',
fiel... |
# Binary search
#http://rosalind.info/problems/bins/
n = 5
m = 6
A = [10, 20, 30, 40, 50]
K = [40, 10, 35, 15, 40, 20]
# Parsing from file:
with open('rosalind_bins.txt', 'r') as contents:
n,m,A,K = contents.read().strip().split('\n')
A = [int(a) for a in A.split(' ')]
K = [int(k) for k in K.split(' ')]
def bina... |
#!/usr/bin/env python3
from ObliviousTransfer import One_out_of_Two
alice = One_out_of_Two(client=False)
alice.verbose = True
alice.store_secret("A", "Some description")
alice.store_secret("B", "Another description")
alice.show_secrets()
alice.start() |
# -*- coding: utf-8 -*-
"""
The :mod:`.utility` module has several functions that support celloracle.
"""
from .make_log import makelog
from .utility import (save_as_pickled_object, load_pickled_object,
intersect,
exec_process,
standard, inverse_dicti... |
import waveletsim_53 as dwt
im = dwt.Image.open("../lena_512.png")
pix = im.load()
m = list(im.getdata())
#print m.__sizeof__()
m = [m[i:i+im.size[0]] for i in range(0, len(m), im.size[0])]
#m_orig = copy.deepcopy(m)
#m_orig[0][0]=300
#print m_orig[0][0], m[0][0]
#print len(m_orig[0]), len(m_orig[1])
#print m._... |
#prime factorization using seive()
#find smallest prime factor(spf) for everynumber using seive()
#and recursively divide the number with this SPF and add to prime list
import math
def smallest_prime_factor(limit):
spf=[0]*(limit+1)
spf[1]=1
#smallest prime factor for every even number is 2
for j in ra... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def subtreeWithAllDeepest(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == N... |
from samson_const import *
from pathloc import *
import matplotlib as mpl
mpl.use('Agg')
from readsnap_cr import readsnapcr
import Sasha_functions as SF
import graphics_library as GL
import gas_temperature as GT
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from samson_functio... |
# Generated by Django 3.0 on 2019-12-07 17:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera... |
#7. Write program to convert prefix/net mask to IP
subnet = 16
ones = [1]*subnet
b1 = ones[0:8]
b2 = ones[8:16]
b3 = ones[16:24]
b4 = ones[24:32]
lst = [b1, b2, b3, b4]
for j in range(4):
if(len(lst[j]) < 8):
x = 8 -len(lst[j])
y = 0
for i in range(x):
lst[j].append(y)
lst2 ... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Nombre: recuperarImagen.py
# Autor: Miguel Andres Garcia Niño
# Creado: 07 de Mayo 2018
# Modificado: 07 de Mayo 2018
# Copyright: (c) 2018 by Miguel Andres Garcia Niño, 2018
# License: ... |
from mongoengine import Document, fields
# Create your models here.
class Certification(Document):
_id = fields.ObjectIdField(require=True)
user_id = fields.ObjectIdField(require=True)
org = fields.StringField(required=True)
name = fields.StringField(required=True)
tags = fields.ListField(required... |
import numpy as np
import scipy as sp
import OpenPNM
import pytest
def test_linear_solvers():
pn = OpenPNM.Network.Cubic([1, 40, 30], spacing=0.0001)
geom = OpenPNM.Geometry.Toray090(network=pn,
pores=pn.pores(),
throats=pn.throats())
... |
/home/miaojian/miniconda3/lib/python3.7/_bootlocale.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: cg错过
# time : 2017-12-08
class DataTemplate:
# data数据模板
# 程序运行得到的数据将不再存放到txt文件中,而是存放到此模板中,即内存中
def __init__(self, strDateTime, strServerName):
# 添加标识self.strServerName-add in 2018-04-09
self.dataForHour = ""
... |
# Generated by Django 3.2.4 on 2021-06-09 01:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('itens', '0001_initial'),
migrations.swappable_dependency(settin... |
from pwn import *
import sys
#config
context(os='linux', arch='i386')
context.log_level = 'debug'
FILE_NAME = "./chall"
#"""
HOST = "pwn.kosenctf.com"
PORT = 9003
"""
HOST = "localhost"
PORT = 7777
#"""
if len(sys.argv) > 1 and sys.argv[1] == 'r':
conn = remote(HOST, PORT)
else:
conn = process(FILE_NAME)
elf = ELF... |
import zmq
import os
from time import sleep
# -*-*config*-*-
work_ip = '0.0.0.0' # Принемать конекты с ip
port = '18735'
channel = 'sms' # Канал для отправки сообщений
command = 'poweroff' # Команды которая будет послана системе
mess_in = 'power off' # Какую команду надо получить чтобы выполнить "command"
# -*-... |
# Generated by Django 2.2.1 on 2019-08-22 17:24
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
#!/usr/bin/python3
def isint(x):
try:
int(x)
return True
except ValueError:
return False
def isfloat(x):
try:
float(x)
return True
except ValueError:
return False
def isindex(name, index):
try:
name[index]
return True
except I... |
## Python 3
answer = sum(filter(lambda x: x % 3 == 0 or x % 5 == 0, list(range(1000))))
print("The answer is %d" % answer)
|
import git
from VersionDetermination.MergeDetector.MergeDetector import MergeDetector
from VersionDetermination.LastVersionDetector.LastVersionDetector import LastVersionDetector
# https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-log.html#_pretty_formats
class Main(object):
def __init__(self, ... |
from keras.models import model_from_json
import operator
import cv2
json_file = open("model-bw.json", "r")
model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(model_json)
loaded_model.load_weights("model-bw.h5")
print("Loaded model from disk")
cap = cv2.VideoCapture(0)
categories = {0: 'Z... |
import sentry_sdk
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.django import DjangoIntegration
import os
import logging
from logdna import LogDNAHandler
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.pat... |
#!/usr/bin/env python3
#
# Convert comamnd-line options to a test specification
import optparse
import pscheduler
import sys
if len(sys.argv) > 1:
# Args are on the command line
args = sys.argv[1:]
else:
# Args are in a JSON array on stdin
json_args = pscheduler.json_load(exit_on_error=True)
args = ... |
#-*- coding:utf8 -*-
def update_model_fields(obj,update_fields=[]):
"""
根据给定字段,保存该对象的对应字段信息
"""
field_entry = {}
for k in update_fields:
if hasattr(obj,k) :
field_entry[k] = getattr(obj,k)
rows = obj.__class__.objects.filter(pk=obj.pk).update(**field_entry)
retu... |
from ED6ScenarioHelper import *
def main():
# 洛连特市 钟楼
CreateScenaFile(
FileName = 'T0133 ._SN',
MapName = 'Rolent',
Location = 'T0133.x',
MapIndex = 10,
MapDefaultBGM = "ed60010",
Flags = 0,
... |
#!/usr/bin/python2
from __future__ import print_function
import os
import csv
import re
import subprocess
from string import Template
from osgeo import ogr
from .chartsymbols import ChartSymbols
from utils import dirutils
def generate_includes(includes_dir, theme):
# Get all includefiles with the correct theme... |
from PIL import Image
from jieba import *
from numpy import *
from matplotlib.pyplot import *
from wordcloud import *
from collections import *
figure=figure()
data=open('19.txt').read()
words=cut(data,cut_all=False)
remove_words=[u'\n',u'\t',u'。',u',',u'、',u'的',u'和']#还有更多无意义词汇 这里只是举例
words_list=[]
for word in words :
... |
#-*- coding:utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import datetime
# Create your models here.
class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
def __unicode__(self):
re... |
class Solution(object):
def validWordSquare(self, words):
word_mat = [list(word) for word in words]
for word in word_mat:
word += [None]*(len(words[0])-len(word))
word_tra = [list(i) for i in zip(*word_mat)]
return word_mat == word_tra |
"""
A program that stores book information:
Title, Author, Year, ISBN
User can:
View all records
Search all entry
Add entry
Update entry
Delete entry
Close app
"""
from tkinter import *
import backend
# def get_selected_row(event):
# global selected_tuple
# if list1.size() > 0:
# index = list1.curs... |
"""
Crie um programa que vai gerar cinco números aleatórios e colocar
em uma tupla.
Depois disso, mostre a listagem de números gerados e tambem indique o
menos e o maior valor que estão na tupla
"""
from random import randint
numeros = (randint(1, 100), randint(1, 100), randint(1, 100),
randint(1, 100), randint(... |
# This file is only intended for development purposes
from kubeflow.kubeflow.cd import base_runner
base_runner.main(
component_name="notebook_servers.notebook_server_jupyter_tensorflow",
workflow_name="nb-j-tf-build")
|
import os
import re
import time
import cv2
import numpy as np
from os.path import isfile, join
tree_classifier = cv2.CascadeClassifier('C:\\Users\\titan\\Desktop\\cv_detect\\cascade.xml')
cap = cv2.VideoCapture('C:\\Users\\titan\\Desktop\\cv_detect\\DJI_0017.MP4')
out = cv2.VideoWriter('results.avi',cv2.VideoWriter_fo... |
# coding=utf-8
from django.shortcuts import render_to_response, redirect
from article.models import Article
from comment.forms import CommentParent, CommentParentForm
def article_detail(request, **kwargs):
context = kwargs['base_context']
context['article'] = Article.objects.get(name=kwargs['article_name'])
... |
#imports
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#get list of available languages
list_lang = []
with open("list_lang.txt", "r") as f:
for lang in f:
list_lang.append(lang.replace("\n", ""))
#initialize parameter
def pytest_addoption(parser):
... |
# Generated by Django 2.0.5 on 2018-07-08 07:49
import datetime
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [migrations.swappable_dependency(sett... |
'''
Given a year, return the century it is in.
The first century spans from the year 1 up to and including the year 100,
the second - from the year 101 up to and including the year 200, etc.
Let's see some examples:
centuryFromYear(1705) // returns 18
centuryFromYear(1900) // returns 19
centuryFromYear(1601) // retu... |
#!/usr/bin/env python3
"""
test for the Psjson module.
"""
import io
import os
import tempfile
import unittest
from base_test import PschedTestBase
from pscheduler.psjson import *
class TestPsjson(PschedTestBase):
"""
Psjson tests.
"""
def test_jsondecomment(self):
"""Test decomment"""
... |
import re
def abbreviate(phrase):
regex = '[A-Z]+[a-z]*|[a-z]+'
return ''.join(word[0].upper() for word in re.findall(regex, phrase))
if __name__ == '__main__':
print(abbreviate('HyperText Markup language'))
|
# Generated by Django 3.0.8 on 2020-09-06 09:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('crm_user', '0003_auto_20200905_1900'),
]
operations = [
migrations.AlterField(
model_name='myus... |
# -*- coding: utf-8 -*-
#import re
import wx
class RedisDataGrid(wx.grid.Grid):
KEY_COL = 0
DATA_TYPE_COL = 1
VALUE_COL = 2
def __init__(self, parent, id):
wx.grid.Grid.__init__(self, parent, id, size=(1000, 500))
self._redis = None
self._data = None
self._last_line = 1... |
import cv2
import matplotlib.pyplot as plt
import numpy as np
img= cv2.imread("H:/Github/OpenCv/FaceRecognition/TrainingImages/img2.jpg")
# print(img.size)
# print(img.shape)
r,g,b = cv2.split(img) # get r,g,b
# print(r)
# print(g)
# print(b)
red = r[: , 0]
# print(red)
green = g[: , 0]
# print(len(green))
... |
from django.urls import path
from . import views
urlpatterns = [
path('persons-list/', views.persons_list, name='persons_list'),
path('persons-create/', views.persons_create, name='persons_create'),
path('persons-update/<int:id>', views.persons_update, name='persons_update'),
path('persons-delete/<int:... |
#TODO fix those methods - probably broke after moving stuff to separate files
def printDifference(pTable, gaussianPTable, n):
print("difference <- c(", end="")
first = True
for i in range(0, len(pTable[n])):
if first == False:
print(", ", end="")
print(-(pTable[n][i]-gaussianPTab... |
# Generates an attack graph of state nodes and vulnerability nodes
import networkx as nx
from input_parser import Parser
from state_node import StateNode
class GraphGenerator(object):
def __init__(self, startNodeSet, adjList, vulnDict, portDict):
self.startNodeSet = startNodeSet
self.a... |
from django.db import models
from django.contrib.auth.models import User
class PatientFamily(models.Model):
user = models.ForeignKey(User)
last_name = models.CharField(max_length=30)
def __str__(self):
return self.last_name
class Patient(models.Model):
family = models.ForeignKey(PatientFami... |
#!/usr/bin/python
from sympy import Symbol, cos,sqrt, series
h = Symbol('h')
c = Symbol('c')
r0 = Symbol('r0')
P=r0/sqrt(r0**2-c*h**2)
print(series(P,h))
DP=diff(P,h)
print(series(P,h))
|
import csv
import httplib2
import logging
import pprint
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
from settings.local import *
logging.basicConfig()
def get_csv(client_email, client_key, document_id):
# Create an httplib2.Http object to handl... |
# the relation between height and positioning error
import os
import numpy as np
from sklearn import preprocessing
import csv
import time
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from keras import Input,Model
from keras.models import Sequential,save_mod... |
a = {
"code":1,
"data":
{
"totalPage":139,
"currentPage":1,
"totalItem":13894,
"itemCountPerPage":100,
"currentItems":
[
{
'expriedDate': '2017-05-24',
'startDate': '2016-05-24',
'createdByName': 'Pham Xuan Hung',
'service': None,
'type': 'Ki mi',
'status':... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.