text stringlengths 8 6.05M |
|---|
from functools import reduce
# map() - Applies the specified function to every element in the collection.
def square(number: int) -> int:
return number * number
list1 = [1, 2, 3, 4, 5]
squared_numbers = list(map(square, list1)) # [result for result in map(square, list1)]
print(squared_numbers)
# filter() - ... |
# -*- coding: utf-8 -*-
#######################################################################
# This file is for project customisation ONLY #
# General DigiPal settings go to digipal/settings.py #
# Particular server instance settings go to local_settings.py #
#######... |
from os import path
from zipfile import ZipFile
class ZipReaderError(Exception):
pass
class InvalidFileName(ZipReaderError):
def __init__(self, file_name):
self.file_name = file_name
super().__init__(f"The ZIP archive contains the invalid file name: '{file_name}'!")
class FileTooLargeError... |
#!/usr/bin/python3
# SPDX-License-Identifier: GPL-2.0-only
#
# Copyright (C) 2018-2019 Netronome Systems, Inc.
# In case user attempts to run with Python 2.
from __future__ import print_function
import argparse
import re
import sys, os
class NoHelperFound(BaseException):
pass
class ParsingError(BaseException):
... |
# -*- coding:utf-8 -*-
"""
Created on 2017-2-28
@author: Kyrie Liu
@description: Global variable
"""
import sys
class Const(object):
class ConstError(TypeError):
pass
def __setattr__(self, key, value):
if key in self.__dict__:
raise self.ConstError, "Not changed the val... |
# Generated by Django 3.0.8 on 2020-11-28 10:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('facilitators', '0004_auto_20201128_1200'),
]
operations = [
migrations.AlterField(
model_name='facilitatorqueries',
... |
from jitcache import Cache
import time
cache = Cache()
@cache.memoize
def slow_fn(input_1, input_2, input_3=10):
print("Slow Function Called")
time.sleep(1)
return input_1 * input_2 * input_3
print(slow_fn(10, 2))
|
import sys
import nbformat
# read notebook from stdin
nb = nbformat.reads(sys.stdin.read(), as_version = 4)
# prepend a comment to the source of each cell
for index, cell in enumerate(nb.cells):
if cell.cell_type == 'code':
cell.source = cell.source.replace('#|export\n', '# this cell is exported to a script\n\n'... |
# 头条搜索内容
touTiaoSearchKey = "西农"
# mongouri配置
mongoUri = "mongodb://172.17.162.189:27017"
# 多久执行一次
interval_minutes = 30
# mysql配置
mysqlHost = "xxx"
mysqlUser = "xxx"
mysqlPasswd = "xxx"
mysqlDb = "xxx"
mysqlPort = 3306
|
import eav
from django.shortcuts import render
from django.http import HttpResponse
from eav.models import Attribute,EnumValue,EnumGroup
from shop.models import Product
def add_attribute(request):
yes = EnumValue.objects.create(value='yes')
no = EnumValue.objects.create(value='no')
unkown = EnumValue.obje... |
import os
import pytest
from etl_toolbox.file_functions import get_file_list_from_dir
@pytest.mark.parametrize("dir, recursive, include_regex, expected", [
(
os.path.join('test_data', 'test_dir'),
False,
None,
[os.path.join('test_data', 'test_dir', '1.csv'),
os.path.join(... |
import tkinter as tk
ICON_CHARS = {
"bug": "\U0001F41B",
"ant": "\U0001F41C",
"honeybee": "\U0001F41D",
"ladybeetle": "\U0001F41E",
"hand": "\U0001F590",
"hazard": "\u2623",
"1": "\u0031",
"width": "\u21D4",
"height": "\u21D5"
}
class CustomBoardWindow(tk.Toplevel):
def __init... |
import re
packages_file = 'packages.txt'
name_regex = 'Product Name:(.*)'
vers_regex = 'Version:(.*)'
pkg_name = ''
pkg_vers = ''
pkg_dict = {}
pkg_names_dict = {'PkgInFile':'PkgOnServer'}
with open(packages_file, 'r') as f:
for line in f:
pkg_name_match = re.search(name_regex, line)
if pkg_name_match:
... |
import scrapy
import re
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError, TCPTimedOutError
UsersConfig = {
# 代理
'proxy': '',
'email': 'placeholder', # placeholder
'password': 'placeholder', # place... |
from flask import Flask
app = Flask(__name__)
# TODO:主页路由
@app.route('/')
def home_page():
return u'今天是11月6日'
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=6000)
|
#! /usr/bin/env python
import random
def seqsim (A, B, D, C):
file = open ( 'SeqSimulation.txt', 'w' ) #This is the file that outcomes will be written
Bases = list ( 'ATGC' )
Barcodes = []
DropSeq = []
for i in range (A):
Barcode = [ random.choice ( Bases ) for i in range (B) ] #random.c... |
import textwrap
import libtcodpy as libtcod
class GUIHandler:
def __init__(self, player):
self.gui_panels = []
#Message Panels
gui_message = MessagePanel(player, 40, 41, 40, 10)
gui_message.message("Welcome to Eoraldil!", libtcod.yellow)
gui_message.message("Your journey begins... in a cave. A dark, and lon... |
""" Tests for the resource manager. """
# Standard library imports.
import unittest
import urllib2
import StringIO
# Major package imports.
from pkg_resources import resource_filename
# Enthought library imports.
from envisage.resource.api import ResourceManager
from envisage.resource.api import NoSuchResourceError... |
from django.apps import AppConfig
class TecheiConfig(AppConfig):
name = 'techei'
|
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman server socket plugin
**Product Home Page:** TBD
**Code Home Page:** TBD
**Authors:** Joel Palmius
**Copyright(c):** Joel Palmius 2018
**Licensing:** MIT
Abstract
--------
This plugin opens a TCP socket a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 1 20:08:24 2018
@author: zhaoyu
"""
from GradientDecent import *
def sigmoid(x):
return 1./(1+np.exp(-x))
def full_connect_sigmoid(X, beta, beta0):
return sigmoid(np.matmul(X, beta)+beta0)
def full_connect_softmax(X, beta, beta0):
r... |
# Generated by Django 3.0.5 on 2020-04-17 17:38
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Mail_Records',
fields=[
('id', models.AutoF... |
"""
tests for the merged-results command
"""
import pscheduler
import unittest
class MergedResultsTest(pscheduler.ToolMergedResultsUnitTest):
name = 'owping'
def test_merged_results(self):
#only to check here is that we get back the one item we put in
#NOTE: There is code for two results but ... |
import unittest
import library
NUM_CORPUS = '''
On the 5th of May every year, Mexicans celebrate Cinco de Mayo. This tradition
began in 1845 (the twenty-second anniversary of the Mexican Revolution), and
is the 1st example of a national independence holiday becoming popular in the
Western Hemisphere. (The Fourth of Ju... |
import random
vidas = 5
CLEAN = "\033[H\033[J"
arquivo = open('Lista_de_Palavras.txt', 'r', encoding='utf-8')
if arquivo.mode == 'r':
linhas_do_arquivo = arquivo.readlines()
for linha in linhas_do_arquivo:
palavra = linhas_do_arquivo[random.randrange(len(linhas_do_arquivo))]
palavr... |
from openspending.test.helpers import *
|
import pandas as pd
import numpy as np
# v = pd.read_csv('data/u_vacancies_parts.csv')
# v['ind'] = v['id_vacancy_part']
# vr = pd.DataFrame()
# vr['vacancy_id'] = v.id
# vr['id'] = pd.Series(range(1, vr.vacancy_id.count() + 1), index=vr.index)
# vr['text'] = v.text
# tv = pd.read_csv('data/d_vacancies_parts_types.csv... |
from onegov.election_day.forms.upload.election_compound \
import UploadElectionCompoundForm
from onegov.election_day.forms.upload.election import UploadMajorzElectionForm
from onegov.election_day.forms.upload.election import UploadProporzElectionForm
from onegov.election_day.forms.upload.party_results import \
... |
"""Generate page for context"""
import os, re
from datetime import datetime as dt
from collections import Counter
def create_page_name(dir_curr_crawl):
return "{0}.md".format(os.path.basename(dir_curr_crawl))
def textify_grouped_notes(grouped_notes):
def textify_created(created):
return "**{0}**".for... |
import Config.Config as config
def delete():
cur = config.conn.cursor()
cmd = """
DROP TABLE public."DzdRules",
public."MatchingRules",
public."AggregateTests",
public."CollectionsData",
public."PhenotypeData",
public."MainTable",
public."MainTableAll",
public."MainTableNull... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index_view, name='index'),
path('signup', views.signup_view, name='signup'),
path('places', views.places_view, name='places'),
path('signin', views.signin_view, name='signin'),
path('logout', views.logout_view, name='l... |
"""
Computations on the (n+1)-dimensional Minkowski space.
"""
import numpy as np
from geomstats.manifold import Manifold
from geomstats.riemannian_metric import RiemannianMetric
import geomstats.vectorization as vectorization
class MinkowskiSpace(Manifold):
"""The Minkowski Space."""
def __init__(self, di... |
'''
Tweets DB schema
Json object example:
{
"_id": ObjectId("56c8c1357e48b67d194d80c7"),
"company": "Amazon",
"count": 1000,
"date": ISODate("2016-02-20T19:12:00Z")
}
'''
# These belongs to models. you should create a seperate folder for models.
# schema folder is just for any .sql file
class tcount():
def... |
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import callbacks
from pages.header import navbar
from pages.layout_dashboard import layout_dashboard
from pages.layout_acceuil import layout_acceuil
from app import app,server
#layout rendu par l'applica... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
'''
class User(models.Model):
summoner = models.CharField(max_length=16)#summoner Name
class Logger(User):
user = models.ForeignKey(User)
username = models.CharField(max_length=16)
password = models.Char... |
import sys
import argparse
from math import sin, cos, pi, exp
from .utils.misc import bisection, newton, secant, false_position
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('mode', type=int, choices=[1, 2, 3])
parser.add_argument('--a', type=float)
parser.add_argument('--b',... |
from .layers import GraphConv, GraphMaxPool, GraphAveragePool
__version__ = '0.14.0'
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
from torch.autograd import Variable
class Head(nn.Module):
def __init__(self, args):
super(Head, self).__init__()
# logging
self.logger = args.log... |
# !/usr/bin/python
# coding=utf-8
#
# @Author: LiXiaoYu
# @Time: 2014-06-06
# @Info: 循环队列
import Log
from Config import Config
class CircularQueue():
#配置对象
__config = ""
#假设队列最大长度
__maxsize = 1000000
#队列数据结构
__sq = {"data":[],"front":0,"rear":0}
#i
__i=0
#初始化
def _... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-04-20 06:30
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authentication', '0021_previouspassword'),
]
operations = [
migrations.RemoveField(
... |
from flask import Flask, render_template, session, request, redirect, url_for
import random
app= Flask(__name__)
f = open('Emergency_Response_Incidents.csv','r')
s = f.read()
f.close()
def happenings():
l = s.split("\n")
Incidents = []
for i in l:
q = i.split(",")
Incidents.append(q[0])
... |
# https://www.hackerrank.com/challenges/symmetric-difference/problem
m = int(input())
setM = set(list(map(int, input().split(" "))))
n = int(input())
setN = set(list(map(int, input().split(" "))))
intersec = setM.intersection(setN)
uni = setM.union(setN)
result = sorted(list(uni.difference(intersec)))
[print(i) for... |
from ffl import app, db, models, espn, draft, mcts
from flask import render_template, session, flash, redirect, url_for, request
@app.route('/team/<team_code>')
def showPlayersByTeam(team_code):
teams = models.NflTeam.query.order_by(models.NflTeam.name).all()
positions = models.Position.query.order_by(models.P... |
#! python3.6
import os
import sys
from functools import partial
import logging.handlers
import atexit
from pathlib import Path # for schedule
from textwrap import dedent # schedule
from time import sleep # schedule
import appdirs
import click
import schedule
import arrow
from screenshotto.__init__ import (APPNAME, V... |
"""
Convert an Excel spreadsheet to a tab-delimited text file.
Prints output to standard output.
"""
import sys
import datetime
try:
import xlrd
except ImportError:
print >> sys.stderr, 'Please see http://pypi.python.org/pypi/xlrd'
sys.exit(1)
def create_parser():
from optparse import OptionParser
... |
import unittest
from resources import pda
from resources import json_reader
class TestPDASimulator(unittest.TestCase):
def test_string_acceptance(self):
"""
Tests if a string is accepted or rejected by a DPA
"""
file_dir = './files/'
test1 = pda.PDA(json_reader.read_file(f... |
x = int(input("Digite um número: "))
lista = []
contador = 0
while contador < x:
if contador % 2 != 0:
lista.append(contador)
contador += 1
print("Os números ímpares são: ", lista)
|
# File Module
FILE_MOD_ADDWORD = "module_addword"
FILE_MOD_CHECKFILE = "module_checkfile"
FILE_MOD_FIND = "module_find"
#Folder
FOLDER_WORD = "word/" |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('investigator', '0011_auto_20170706_0053'),
]
operations = [
migrations... |
import sys
import os
import json
import utils
import activity
def main():
if (len(sys.argv) <3):
print("")
print("")
print('usage: python scanReplay.py <game_dir> <command>')
print("")
print('...where command can be :')
print(' show_activity ... |
# coding:utf-8
from selenium import webdriver
from xlutils3.copy import copy # 将xlrd.Book转为xlwt.workbook,在原有的excel基础上进行修改,添加等。
import xlwt # 写入excel(新建)
import xlrd # 读取excel
import os
import time
import cx_Oracle
import unittest
from openpyxl import Workbook
import sys
sys.path.append('F:\\PyTesting\\AutoTest\\pub... |
a = int(input("Enter the value of a: ")) # 5
b = int(input("Enter the value of b: ")) # 6
a = a + b # a = 11, b = 6
b = a - b # b = 5
a = a - b # a = 6
print("After Swaping")
print("Value of a =", a)
print("Value of b =", b)
|
def tostring(c):
c.__str__ = lambda c: "%s(%s)" % (
c.__class__.__name__,
", ".join(str(v) for v in c.__dict__.values())
)
return c |
a=input()
i=0
b=[]
for y in range(len(a)):
if a[i].lower()=='a' or a[i].lower()=='e' or a[i].lower()=='i' or a[i].lower()=='o' or a[i].lower()=='u':
b.append(a[i])
else:
i=i+1
if (len(b))>0:
print("yes")
else:
print("no")
|
from tokenizers import BertWordPieceTokenizer
import urllib
from transformers import AutoTokenizer
import os
def download_vocab_files_for_tokenizer(tokenizer, model_type, output_path):
vocab_files_map = tokenizer.pretrained_vocab_files_map
vocab_files = {}
for resource in vocab_files_map.keys():
do... |
import cv2
import numpy as np
from darkflow.net.build import TFNet
from shapely.geometry import box, Polygon
from data_collection.img_process import grab_screen
from object_detection.direction import Direct
# set YOLO options
options = {
'model': 'cfg/yolo.cfg',
'load': 'bin/yolov2.weights',
'threshold': ... |
from rest_framework import viewsets
from kratos.apps.app import models, serializers
from rest_framework.response import Response
from rest_framework import status
class AppViewSet(viewsets.GenericViewSet):
'''
应用信息
'''
serializer_class = serializers.AppSerializer
queryset = models.App.objects.all(... |
pessoas = list()
dados = list()
totpessoas = totleve = 0
visual = '*-' *30
while True:
dados.append(str(input('Digite o nome de pessoa:')))
totpessoas += 1
dados.append(int(input('Digite o peso da pessoa:')))
resp = (str(input('Deseja continuar? [S/N]')))
pessoas.append(dados[:])
dados.clear()
... |
#!/usr/bin/env python
# Copyright Reliance Jio Infocomm, Ltd.
# Author: Soren Hansen <Soren.Hansen@ril.com>
#
# 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://w... |
"""
2. Инкапсулировать оба параметра (название и цену)
товара родительского класса.
Убедиться, что при сохранении текущей логики работы программы
будет сгенерирована ошибка выполнения.
"""
class ItemDiscount:
def __init__(self, name, price):
self.__name = name
self.__price = price
class ItemDisco... |
# Implementation of directed graphs#
class CS161Vertex:
def __init__(self, v):
self.inNeighbors = []
self.outNeighbors = []
self.value = v
# useful for DFS/BFS
self.inTime = None
self.outTime = None
self.status = "unvisited"
def hasOutNeighbor(se... |
# Generated by Django 2.0.2 on 2018-03-24 13:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tafaha', '0007_answer_picture'),
]
operations = [
migrations.RemoveField(
model_name='answer',
name='text',
... |
# Programa que imprime a quinta parte de um numero
num = float(input('Entre com um numero: '))
quinta_parte = num / 5
print(f'A quinta parte de {num} é: {quinta_parte}')
|
"""
Representation of the agenda summary given to attendees of a meeting
"""
from pathlib import Path
from typing import (
Optional,
Union,
)
import docx # type: ignore
from docx.oxml import OxmlElement # type: ignore
from docx.oxml.ns import qn # type: ignore
import docx.table # type: ignore
from .meeti... |
import pytest
from pytest_dl import dataset
@pytest.fixture(scope="module")
def data():
yield dataset.MyMNIST()
|
#!/usr/bin/python
## -*- coding: utf-8 -*-
#
import json
#import db_conf
import cgi
import sys
import sqlite3
# Open database (will be created if not exists)
conn = sqlite3.connect('sqlite/hemap_core3.db')
conn.text_factory = str
c = conn.cursor()
qform = cgi.FieldStorage()
inparam = qform.getvalue('inparameter')
#inp... |
from collections import Counter
def popular_words(text: str, words: list) -> dict:
c = dict(Counter(text.split()))
c = {k.lower(): v for k, v in c.items()}
o = {}
for i in words:
if i in c.keys():
o[i] = c.get(i)
else:
o[i] = 0
return o
if __name__ == '__main__':
# These "asserts" ... |
import time #
time.time()
# def prime_check_v1(x):
# check = 1
# if x == 2 and x == 3:
# check = 1
# elif x == 1:
# check = 0
# else:
# for i in range(2, x - 1):# think carefully on this line
# # Explain a little bit more here........
# check ... |
import logging
from typing import Dict
from sonosco.serialization import serializable
from ..abstract_callback import AbstractCallback, ModelTrainer
LOGGER = logging.getLogger(__name__)
@serializable
class DisableSoftWindowAttention(AbstractCallback):
"""
Disable soft window pretraining after the stecified ... |
import time
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
binary = FirefoxBinary('/Applications/Firefox.app/Contents/MacOS/firefox-bin')
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.suppo... |
from abc import ABC, abstractmethod
class AbstractBird(ABC):
def __init__(self, name):
self.name = name
super().__init__()
@abstractmethod
def can_fly(self):
pass
class Penguin1 (AbstractBird):
def __init__(self):
super().__init__("Penguin")
class Penguin2 (AbstractB... |
from django.contrib import admin
from .models import *
class BranchInline (admin.StackedInline):
model = Branch
extra = 0
class ContactInline (admin.StackedInline):
model = Contact
extra = 0
class CoursesAdmin (admin.ModelAdmin):
inlines = [BranchInline, ContactInline]
admin.site.register(Ca... |
from django.contrib import admin
from . import models
admin.site.register(models.StudentDay)
admin.site.register(models.TeacherDay)
admin.site.register(models.WorkerDay)
admin.site.register(models.StudentAttendance)
admin.site.register(models.TeacherAttendance)
admin.site.register(models.WorkerAttendance)
|
# Generated by Django 2.2.5 on 2020-05-20 17:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('listings', '0013_auto_20200520_0612'),
]
operations = [
migrations.AlterField(
model_name='comm... |
import os
import unittest
from pathlib import Path
from click.testing import CliRunner
from prettydata import main
class TestMain(unittest.TestCase):
"""Test class for testing the main module
Arguments:
unittest {[type]} -- [description]
"""
@classmethod
def setUpClass(cls):
prin... |
'''
Source: https://codegolf.stackexchange.com/questions/41523/sudoku-compression
'''
import itertools
def print_sudoku(m):
for k in m:
print((" ".join(str(i) for i in k)))
def potential_squares(u1, u2, u3, l1, l2, l3):
"""
returns generator of possible squares given lists of digits above and... |
import urllib2
from urllib2 import urlopen
import re
from bs4 import BeautifulSoup
from urlparse import urljoin
import csv
import httplib
import sys,getopt
class walk:
starturl= 'http://www.globalscape.com/'
visited = []
checked = []
errors = []
redirects = []
errorfile='errors.csv'
vis... |
import os
import numpy as np
from dm_control.suite import common
from dm_control.utils import io as resources
import xmltodict
_SUITE_DIR = os.path.dirname(os.path.dirname(__file__))
_FILENAMES = [
"./common/materials.xml",
"./common/skybox.xml",
"./common/visual.xml",
]
def get_model_and_assets_from_set... |
# coding: utf-8
class SearchError(Exception):
pass
|
import spotipy
import os
import requests
import json
import pandas as pd
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from flask import Flask, request, redirect, g, render_template
from spotipy.oauth2 import SpotifyClientCredentials
from dotenv import load_dotenv
from urllib.parse impor... |
import numpy as np
from math import sin, cos
def rotation_x(a):
R = [[1, 0, 0], [0, cos(a), -1 * sin(a)], [0, sin(a), cos(a)]]
return np.mat(R)
def rotation_y(a):
R = [[cos(a), 0, -1 * sin(a)], [0, 1, 0], [sin(a), 0, cos(a)]]
return np.mat(R)
def rotation_z(a):
R = [[cos(a), sin(a), 0], [-1 * ... |
from ED6ScenarioHelper import *
def main():
# 蔡斯
CreateScenaFile(
FileName = 'T3116 ._SN',
MapName = 'Zeiss',
Location = 'T3116.x',
MapIndex = 1,
MapDefaultBGM = "ed60013",
Flags = 0,
En... |
print 'helloword-test' |
from collective.cart.core.error import InfiniteLoopError
from collective.cart.core.interfaces import IRandomDigits
from collective.cart.core.interfaces import IRegularExpression
from collective.cart.core.interfaces import ISelectRange
from random import choice
from string import digits
from zope.interface import implem... |
import random
def random_item(iterable):
number = random.randint(0,len(iterable)-1)
print(iterable[number])
random_item("treehouse")
|
from conans.model import Generator
"""
PC FILE EXAMPLE:
prefix=/usr
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include
Name: my-project
Description: Some brief but informative description
Version: 1.2.3
Libs: -L${libdir} -lmy-project-1 -linkerflag
Cflags: -I${includedir}/my-project-1
Requi... |
from keras.models import Sequential
from keras.layers import Dense
model= Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer = 'random_uniform'))
|
# coding: utf-8
import math
import random
import copy
import pygame
from constantes import *
class Carte:
altitude_min_nour_abondante = 0.
proba_modif_point_altitude_fixe = 0.
valeur_modif_point_altitude_fixe = 0
proba_modif_vitesse_point_altitude_fixe = 0.
def __init__(self, largeur_carte: int,... |
'''
Regex with Python is easy
Steps required:
- import standard module `re`
- write your regex pattern and compile it
- call the one of methods - findall, match, search, sub etc.
'''
import re
number_input_text = "the numbers are: 12 34 56 and 78, others numbers are: 33 78 and 0."
number_regex_pattern = r"(\d+)"
r ... |
# Generated by Django 2.2.5 on 2020-04-25 16:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('listings', '0007_mobilephone_is_wkp'),
]
operations = [
migrations.CreateModel(
name='Brand',
... |
import maya.cmds as cmds
import os
from functools import partial
import Utils.Utils_File as fileUtils
class Parts_UI:
def __init__(self):
""" Create a dictionary to store UI elements """
self.UIElements = {}
""" Check to see if the UI exists """
self.windowName... |
from game_engine.constants import STATUS_ACTIVE, STATUS_FOLDED
class Player:
def __init__(self, stack):
self._stack = stack
self._bet = 0
self._status = STATUS_ACTIVE
def get_player_obj(self):
return {
"stack": self._stack,
"bet": self._bet,
... |
#!/usr/bin/python
import socket
from struct import pack, unpack
PROTOCOL_VERSION = 0x200
TYPE_BOOL = 0
TYPE_NUMBER = 1
TYPE_STRING = 2
TYPE_BOOL_ARRAY = 16
TYPE_NUMBER_ARRAY = 17
TYPE_STRING_ARRAY = 18
MSG_NOOP = 0
MSG_HELLO = 1
MSG_UNSUPPORTED = 2
MSG_HELLO_COMPLETE = 3
MSG_ASSIGN = 16
MSG_UPDATE = 17
class Network... |
# Scope of variables
coeff = 1.0
def apply(params):
data = []
for elem in params:
data.append(coeff * elem)
return data
def apply2(params):
coeff = 0.8
data = []
for elem in params:
data.append(coeff * elem)
return data
def apply3(params):
global coe... |
from django import forms
from django.contrib.auth.models import User
from .models import *
from .views import *
from django.forms import ModelForm
class clientesForm(ModelForm):
class Meta:
model = Cliente
fields = '__all__'
class empresaForm(ModelForm):
class Meta:
model = Empresa
fields = ['NombreEmpres... |
#!/usr/bin/env python
# coding=utf-8
# 配置数据库信息,mongo只用来存储题目
MONGO_URI = 'mongodb://localhost:27017/'
MONGO_DATABASE = 'makinami'
# 支持OJ列表
OJS = [
'poj',
]
|
"""
Virtual Tic-Tac-Toe Board
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Optional, List, Tuple
__all__ = ['TTTBoard', 'EMPTY', 'PLAYERX', 'PLAYERO', 'DRAW', 'STRMAP',
'switch_player']
# Constants
EMPTY = 0
PLAYERX = 1
PLAYERO = 2
DRAW = 3
# Map play... |
class Solution:
def buildTree(self, preorder, inorder):
if not preorder or not inorder: return None
root = TreeNode(preorder[0])
idx = inorder.index(preorder[0])
preorder.remove(preorder[0])
root.left = self.buildTree(preorder, inorder[:idx])
root.right = self.buildTr... |
import csv
from flask_hello_world_app import db, STDcodes
f = open("Std.csv")
csv_f = csv.reader(f)
db.create_all()
i = 0
for row in csv_f:
STDcode = STDcodes(stdcode=int(row[0]), city= row[1], state=row[2])
db.session.add(STDcode)
db.session.commit()
print(i)
i += 1
f.close()
|
from time import sleep
from datetime import date
#INTRODUÇÃO DE CABEÇALHO
sleep(1)
print('\n')
print('-=' *31 )
data_atual = date.today()
data_em_texto = data_atual.strftime('%d/%m/%Y')
print('PROTÓTIPO SIMPLIFICADO DE CONSULTA JURÍDICA, RIO, {}.'.format(data_em_texto))
print('-=' *31 )
#INTRODUÇÃO DIDÁTI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.