text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
'''
fizz buzz test with normal functions
The fizz buzz tests is aimed to check if you know how to write a function.
For a different example using lambda functions, see fizzBuzz_lambda.py
Check out fizzBuzz_errors.py for an example that provides error messages to the user.
You may find useful do... |
import tensorflow as tf
import module.conv_training as conv_training
# import module.transfer_training as transfer_training
import random
def to_ds_degree(degree):
ds = tf.data.experimental.SqlDataset(
"sqlite", "/data/aoi-wzs-p1-dip-fa-nvidia/training/p1-dip-metadata.db",
f"""select path, degree from met... |
# Generated by Django 2.2.10 on 2020-03-11 17:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("recruitment", "0013_add_job_application_url_query"),
("recruitment", "0015_job_alert_task_started_auto_timestamp"),
]
operations = []
|
import requests
from bs4 import BeautifulSoup
def consulta_asegurado(nro_cic):
def clean_data(data):
return data.get_text().replace('\n', '').replace('\t', '').strip()
url = 'https://servicios.ips.gov.py/consulta_asegurado/comprobacion_de_derecho_externo.php'
form_data = {'nro_cic': str(... |
import re, folium, math
def creategeojson(point, dummy): # geojson erstellen aus dummy
name = str(id(point))
with open(dummy) as file: # öffnen des dummy geojson
data = file.read()
data = re.sub("XXX", str(point), data) # ersetzen der XXX durch die coordinaten in die geojson
with open(... |
from django.contrib import admin
from .models import Movie, Cinema, Show
# Register your models here.
admin.site.register(Movie)
admin.site.register(Cinema)
admin.site.register(Show)
|
import numpy as np
# read in binary file
numbers = np.fromfile("numbers.dat", dtype="longdouble")[1:]
result1 = np.longdouble(0)
for item in np.nditer(numbers[np.isfinite(numbers)], order="K"):
result1 += item
print(result1)
|
#!venv/bin/python
from flask_frozen import Freezer
from flask import Flask, render_template, send_from_directory
from flask_bootstrap import Bootstrap
from flask_script import Manager
from flask_moment import Moment
from glob import glob
app = Flask(__name__, static_folder='static', static_url_path='/static')
Bootstra... |
%sql
-- describe database new_schema
CREATE DATABASE IF NOT EXISTS new_schema COMMENT 'This is <your_new_schema> database' |
import pytest
import os
from selenium import webdriver
from nerodia.browser import Browser
TEST_APP_URL = "https://www.saucedemo.com"
@pytest.fixture
def browser(request):
caps = {
"browserName": "Chrome",
"sauce:options": {
"browserName": "Chrome",
"platformName": "Window... |
#!/usr/bin/env python3
"""
Script permettant de crée nos modeles
"""
__author__ = "Casa de Crypto"
__build__ = "Casa de Crypto"
__copyright__ = "Copyleft 2018 - Casa de Crypto"
__license__ = "GPL"
__title__ = "Machine Learning pour la prediction du cours du Bitcoin"
__version__ = "1.0.0"
__mainta... |
#!/usr/bin/env python
# coding: utf-8
# In[10]:
from sklearn.preprocessing import LabelEncoder
# In[11]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# In[12]:
#importing the dataset
dataset = pd.read_csv("Dataset.csv")
from sklearn.preprocessing import LabelEncoder
le = LabelE... |
from IBMQuantumExperience import IBMQuantumExperience
from IBMQuantumExperience import ApiError # noqa
import helper
import sys
import os
import Qconfig
from pprint import pprint
verbose = False
if 'CK_IBM_VERBOSE' in os.environ:
_verb = int(os.environ['CK_IBM_VERBOSE'])
if (_verb > 0): verbose = True
# to... |
class Solution(object):
def openLock(self, deadends, target):
def neighbors(key):
lst = []
for i in range(4):
x = int(key[i])
for d in (-1, 1):
y = (x + d) % 10
val = key[:i] + str(y) + key[i+1:]
... |
import glob
import argparse
import re
import collections
import itertools
import pandas as pd
import pathlib
parser = argparse.ArgumentParser()
REGEX_DICT = {
"CLB": "\| CLB LUTs\*\s+\|.*?\|.*?\|.*?\|\s+(?P<CLB>.*?)\s+\|",
"DSP": "\| DSPs\s+\|.*?\|.*?\|.*?\|\s+(?P<DSP>.*?)\s+\|",
"CYC": "Design ran for (?... |
import os
import boto3
s3_resource = boto3.resource("s3", region_name="us-east-1")
def upload_objects():
try:
bucket_name = "<<Bucket-Name>>"
root_path = 'C:/<<Path-of-the-folder>>'
my_bucket = s3_resource.Bucket(bucket_name)
for path, subdirs, files in os.walk(root_path):
... |
# Generated by Django 3.1.2 on 2020-10-29 20:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('s4in', '0010_projects_shortdescription'),
]
operations = [
migrations.AddField(
model_name='projects',
name='date',
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('forms',... |
# ch19_29.py
from tkinter import * # Import tkinter
import random
# 傳回球的隨機顏色
def getColor():
colorlist = ['red', 'green', 'blue', 'aqua', 'gold', 'purple']
return random.choice(colorlist)
# 定義Ball類別
class Ball:
def __init__(self):
self.x = width / 2 # 發球的x軸座標
self.y =... |
#!/usr/bin/python
import os
import sys
import re
class haproxy():
__Excute = None
def __init__(self):
self.__Excute = os.system
def haproxy_install(self):
self.__Excute("rpm -ivh resource/cache/haproxy/haproxy-1.5.4-4.el7_1.x86_64.rpm") # this block should use popen but don't have t... |
def memoize(original_function):
memo = {}
def wrapper(top, v):
key = tuple([top, len(v)])
if key not in memo:
memo[key] = original_function(top, v)
#uncomment the following lines to see how many times the grid gets filled
... |
import ROOT
import QFramework
import CommonAnalysisHelpers
def addAlgorithms(visitor,config):
unfoldingConfig = QFramework.TQFolder()
unfoldingConfig.importTagsWithoutPrefix(config, "unfolding.")
# unfoldingConfig.printTags()
unfoldingCuts = CommonAnalysisHelpers.analyze.loadCuts(unfoldingConfig)
... |
import struct
import socket
import select
import re
import json
Format = 'iii'
HOST = '127.0.0.1'
output_ports = {}
input_ports = []
def configParser(filename):
'''Read the config file and construct the routing table'''
lines = []
table = {}
file = open(filename, 'r')
for line in file.readl... |
from socket import *
ip_port=('127.0.0.1',9000)
bufsize=1024
tcp_client=socket(AF_INET,SOCK_DGRAM)
while True:
msg=input("请输入时间格式: ").strip()
tcp_client.sendto(msg.encode('utf-8'),ip_port)
data=tcp_client.recv(bufsize) |
# Generated by Django 3.0.5 on 2020-05-03 18:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('project_first_app', '0004_auto_20200503_1905'),
]
operations = [
migrations.RemoveField(
model_name='owner',
name='email',
... |
from __future__ import print_function
import random
adjectives = ('complete', 'modern', 'self-service', 'integrated', 'end-to-end')
ci_cd = ('continuous testing', 'continuous integration', 'continuous deployment', 'continuous improvement', 'DevOps')
adverbs = ('remarkably', 'enormously', 'substantially', 'significantl... |
import time,os,psycopg2
from flask import Flask
app = Flask(__name__)
# KUBERNETES otomatik olarak HOSTNAME'i container'ın environment'ına enjekte eder
hostname = os.environ['HOSTNAME']
# Postgresql bağlantı bilgilerini env'den alalım
postgre_hostname=os.environ['POSTGRE_HOSTNAME']
postgre_port=os.environ['POSTGRE_PO... |
import turtle
from generator.shapes import *
class GeometricShapes:
__GENERATORS__ = [
Triangle, Circle, Heptagon, Octagon, Hexagon, Square, Star,
Nonagon, Pentagon
]
def __init__(self, destination, size, animation=False):
turtle.colormode(255)
# the canvas substract a ... |
from enum import Enum
from PyQt5.QtCore import QTimer, QTime
from PyQt5.QtWidgets import QLCDNumber
class TimerObject(QLCDNumber):
def __init__(self):
super().__init__()
self.timer = QTimer()
self.timer.setInterval(1000)
self.timer.timeout.connect(self.increment)
self.upda... |
# -*- coding: utf-8 -*-
from pysped.xml_sped import *
from pysped.nfe.manual_300 import ESQUEMA_ATUAL
import os
DIRNAME = os.path.dirname(__file__)
class InfInutEnviado(XMLNFe):
def __init__(self):
super(InfInutEnviado, self).__init__()
self.Id = TagCaracter(nome=u'infInut', codigo=u'DP03',... |
"""
A Pythagorean triplet is a set of three natural numbers,
a < b < c, for which, a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which
a + b + c = 1000.
Find the product abc.
"""
def pythagorean_loop():
product = 0
for c in range(1, 1000):
for b in... |
import mysql.connector
PW_FILE = '../.pw'
DB_USER = 'samyong'
DB_NAME = 'scala_chatter'
USER_TABLE = 'seed_user_details'
FOLLOWER_TABLE = 'seed_user_followers'
FOLLOWING_TABLE = 'seed_user_friends'
TWEET_TABLE = 'seed_user_tweets'
CONNECTION_USER_TABLE = 'seed_connection_details'
pw = [s for s in open(PW_FILE)][0].st... |
import configparser
import os
basedir = os.path.abspath(os.path.dirname(__file__))
# ref: https://www.blog.pythonlibrary.org/2013/10/25/python-101-an-intro-to-configparser/
class UtilsConfig(object):
def __init__(self):
self.config = configparser.ConfigParser()
self.config.read('utils.cfg')
... |
"""This script tests the cli methods to get samples in status-db"""
from datetime import datetime
from cg.store import Store
def test_get_sample_bad_sample(invoke_cli, disk_store: Store):
"""Test to get a sample using a non-existing sample-id """
# GIVEN an empty database
# WHEN getting a sample
db_... |
""" Exceptions
"""
from typing import Dict
from fastapi import HTTPException
def bad_request(errors: Dict[str, str], code='validation_error'):
""" Return HTTP 400 error
"""
raise HTTPException(status_code=400, detail={
'code': code,
'reason': errors,
})
def business_error(errors: Di... |
from flask import request, redirect, render_template, url_for
from app import app
import locale
locale.setlocale(locale.LC_TIME, "sp") # swedish
import openpyxl
from datetime import datetime, timedelta
import calendar
#import numpy
def cerradas():
#File Log
FILEPATH_LOG = open(r'C:\Users\usr1CR\.PyCharmCE2018.... |
import subprocess
import time
from Profitability import check_proditability
def init_miner(config):
old_result = check_proditability(config.gpu)
cmd = command(config, old_result)
p = subprocess.Popen(cmd) # something long running
run_miner_prof_check(cmd, old_result, config, p)
def run_miner_prof_c... |
from __future__ import unicode_literals
from django.apps import AppConfig
class CargafilesConfig(AppConfig):
name = 'cargafiles'
|
from kafka import KafkaProducer
from elasticsearch import Elasticsearch
from kafka import KafkaConsumer
import time
import json
print("Batch Script Running")
time.sleep(35)
consumer = KafkaConsumer('new-listings-topic', group_id='listing-indexer', bootstrap_servers=['kafka:9092'])
es = Elasticsearch(['es'])
fixtures... |
import json
import os
import sys
import psycopg2
from imaging import OmeroConstants, OmeroUtil
from imaging.OmeroProperties import OmeroProperties
class RetrieveAndSerializeOmeroIds:
omeroProperties = None
outFolder = None
drTag = None
dsList = None
def __init__(self, omeroDevPropetiesFile, out... |
from django.test import SimpleTestCase
from django.urls import reverse, resolve
from listings.views import listing, search
class TestUrls(SimpleTestCase):
def test_search_url_is_resolved(self):
url = reverse('search')
self.assertEqual(resolve(url).func, search) |
'''
Created on 10-Aug-2018
@author: srinivasan
'''
from collections import defaultdict
import datetime
import gzip
from io import BytesIO
import logging
from jinja2.environment import Environment
from scrapy import signals
from scrapy.exceptions import NotConfigured
from scrapy.mail import MailSender
from scrapy.util... |
#
# @lc app=leetcode id=105 lang=python3
#
# [105] Construct Binary Tree from Preorder and Inorder Traversal
#
import TreeNode
from typing import List
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.rig... |
def constant_current(t):
"""Constant current function"""
# output has to have same shape and type as t
return 0 * t + 1
|
# -*- coding=utf-8
'''
Created on 2016年9月23日
听牌规则
@author: zhaol
'''
from difang.majiang2.ai.ting import MTing
from difang.majiang2.player.hand.hand import MHand
from difang.majiang2.table.table_config_define import MTDefine
from difang.majiang2.tile.tile import MTile
from difang.majiang2.ting_rule.ting_rule import MTi... |
import xlwings as xw
file_path = '/Users/chenhaolin/PycharmProjects/SRT/发改委/NDRC/FILES/test_xls.xls'
wb = xw.Book(file_path)
sheet = wb.sheets[0]
RANGE = sheet.range('A1').expand('table')
row_count = RANGE.rows.count
col_count = RANGE.columns.count
print(str(row_count) + ' ' + str(col_count))
print(RANGE.rows)
for r... |
#########################
# 定义类,属性、方法、私有属性和方法
#########################
class Car:
"""一辆汽车"""
__code = "2123120FJJ" # private的类变量
_motor = "牛逼的要死" # protected的类变量
country = "德国" # public的类属型
# 构造方法
def __init__(self, make, year):
self.make = make # 对象属性
self.year = year
... |
import logging
import os
from quasimodo.parts_of_facts import PartsOfFacts
from quasimodo.data_structures.submodule_interface import SubmoduleInterface
from quasimodo.assertion_fusion.trainer import Trainer
from quasimodo.parameters_reader import ParametersReader
save_weights = True
parameters_reader = ParametersR... |
from django.db import models
from django.db.models import fields
import graphene
from graphql_jwt.decorators import login_required
from graphene_django import DjangoObjectType
from .models import Deal
#debug
from .tests.deals_data import mock_data
DEALS_PER_QUERY = 8
class FreeDeal(DjangoObjectType):
class Meta:... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('barkochba', '0003_story_order_number'),
]
operations = [
migrations.DeleteModel(
name='Person',
),
... |
# $Id$
##
## This file is part of pyFormex 0.8.5 Sun Nov 6 17:27:05 CET 2011
## pyFormex is a tool for generating, manipulating and transforming 3D
## geometrical models by sequences of mathematical operations.
## Home page: http://pyformex.org
## Project page: https://savannah.nongnu.org/projects/pyformex/
... |
def who_is_there(lis):
if "bear" in lis:
print("There's a bear")
if "lion" in lis:
print("There's a lion")
if "daisy" in lis or "iris" in lis:
print("There are flowers")
if "daisy" in lis and "iris" in lis:
print("There are at least two flowers")
if "donkey" in lis:
... |
stock = [
{'name': 'Xiaomi', 'stock': 5, 'price': 65000.0, 'recomend': [
'Xiaomi', 'iPhone XS', 'Samsung', 'OnePlus']},
{'name': 'iPhone XS', 'stock': 8, 'price': 50000.0, 'discount': 50},
{'name': 'OnePlus', 'stock': 20, 'price': 38000.0},
]
print(type(stock))
print(type(stock[0]))
# выводит из ... |
from django.db import models
class LetsEncrypt(models.Model):
url = models.CharField(max_length=255)
text = models.CharField(max_length=255)
def save(self, *args, **kwargs):
self.pk = 1
super().save(*args, **kwargs)
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'sqlite_main_window.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SqliteMainWindow(object):
def setupUi(self, SqliteMainWin... |
# -*- coding utf-8 -*-
from decimal import Decimal
from django.db import models
class Plan(models.Model):
name = models.CharField(max_length=100)
minutes = models.IntegerField(default=0)
data = models.IntegerField(default=0)
sms = models.IntegerField(default=0)
value = models.DecimalField(max_digi... |
# Copyright (c) 2015-2021, Manfred Moitzi
# License: MIT License
import pytest
import math
import ezdxf
from ezdxf.entities import Hatch, BoundaryPathType, EdgeType
from ezdxf.lldxf.tagwriter import TagCollector, Tags
from ezdxf.lldxf import const
from ezdxf.math import Vec3
@pytest.fixture
def hatch():
return H... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Utilities for analyzing Enron email data"""
import sys
import logging
__author__ = "Pujaa Rajan"
__email__ = "pujaa.rajan@gmail.com"
def logger():
"""
Create and format logger that logs to file and console
@return None:
"""
logger = logging.getLo... |
import sys
from common import *
def convert_to_abc(directory_path):
subprocess_arguments = [sys.executable, "xml2abc\\xml2abc.py"]
for file_name in os.listdir(directory_path):
if file_name.endswith(".musicxml"):
subprocess_arguments.append(os.path.join(directory_path, file_name))
su... |
from data_batcher import SantanderDataObject
import tensorflow as tf
import numpy as np
class SantanderVanillaModel(object):
def __init__(self,FLAGS):
self.FLAGS=FLAGS
self.dataObject=SantanderDataObject(self.FLAGS.batch_size,self.FLAGS.test_size)
with tf.variable_scope("SantanderModel",in... |
from unittest import TestCase
import boto3
from moto import mock_ec2
from altimeter.aws.resource.ec2.volume import EBSVolumeResourceSpec
from altimeter.aws.scan.aws_accessor import AWSAccessor
from altimeter.core.graph.links import LinkCollection, ResourceLink, SimpleLink
from altimeter.core.resource.resource import ... |
from wxpy import Bot, embed # 微信机器人
import os
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
os.chdir(r'.\PythonLearn\src\images') # 创建工作路径
bot = Bot()
myself = bot.self # 机器人账号自身
# bot.file_helper.send('Hello from w... |
#!/usr/bin/env python
from tthAnalysis.HiggsToTauTau.safe_root import ROOT
from tthAnalysis.HiggsToTauTau.common import logging, SmartFormatter
from tthAnalysis.HiggsToTauTau.configs.EvtYieldHistManager_cfi import * # EvtYieldHistManager_201*
import logging
import argparse
import os
import hashlib
# Credit to: https... |
class PluginAlreadyRegistered(Exception):
pass
class PluginNotRegistered(Exception):
pass
class AppAllreadyRegistered(Exception):
pass
class NotImplemented(Exception):
pass
class SubClassNeededError(Exception):
pass
class MissingFormError(Exception):
pass
class NoHomeFound(Exception):
... |
to_do = ''
def add_task(date, start_time, duration, attendees, curr_list):
global to_do
curr_list = date + '\n' + start_time + '\n' + duration + '\n' + attendees + '\n' + "NEW:" + '\n'
to_do += curr_list
def add_event(date, time, location, curr_list):
global to_do
curr_list = '\n' + date + '\n' + time + '\n' + ... |
"""
Plot fitted GSMF and original data
"""
import json
import sys
import numpy as np
from scipy.stats import binned_statistic
from matplotlib import cm
import matplotlib.pyplot as plt
from methods import piecewise_linear
from methods import mass_bins, binned_weighted_quantile
exec(open("./obs_data_sfs.py").read())
... |
from django.db import models
from common.attrs import get_attr_values
from common.constants import FALSE
from common.models import BaseModel
class SystemRoles(BaseModel):
sys_role_id = models.AutoField(primary_key=True, verbose_name='系统角色标识')
sys_role_name = models.CharField(max_length=50, verbose_name='系统角色... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from common import manage_province_city_district
from common import database
from common import prepare_data
from calculate import... |
from binance.client import Client
from datetime import datetime as dt
from api_data import api, secret
from Allert import allert_buy, allert_sell
import time
client = Client(api, secret)
def buy_signal(tiker, period):
"""проверка 1 час свечей на наличие сигнала на покупку"""
while True:
# запуск пров... |
import math
# noinspection PyPackageRequirements
from typing import Tuple
import numpy as np
# noinspection PyPackageRequirements
import cv2
from Application.Frame.global_variables import JobInitStateReturn
from Application.Frame.port import Port
from Application.Frame.transferJobPorts import get_port_from_... |
import unittest
from lib.ui.login_page import LoginPage
from lib.utils import create_driver
from selenium.webdriver.common.keys import Keys
import pytest
class TestComponents(unittest.TestCase):
def setUp(self):
self.driver = create_driver.get_driver_instance()
self.login = LoginPage(self.driver)
... |
import cv2
import numpy as np
class matches(object):
def __init__(self,img1,img2,K,params):
self.img1 = img1
self.img2 = img2
self.params = params
self.matches = self._getMatches()
self.matchPoints = self._sortMatchPoints()
self.K = K
self.P = np.hstack((np.eye(3), np.zeros((3, 1))))
def _getMat... |
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
%matplotlib inline
import os
import gc
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score, f1_score
import seaborn as sns
from google.colab import drive
drive.mount('/content/drive')
data_fer = pd.read_cs... |
class Node(object):
def __init__(self, name):
self.name = str(name)
def getName(self):
return self.name
def __str__(self):
return self.name
class Edge(object):
def __init__(self, src, dest):
self.src = src
self.dest = dest
def getSource(self):
return ... |
import re
pattern = re.compile("<>")
#for i, line in enumerate(open('test.txt')):
# for match in re.finditer(pattern, line):
# print 'Found on line %s: %s' % (i+1, match.groups())
def word_frequencies(file_list):
"""
Returns a dictionary with the frequencies
of the annotations occurring on fil... |
from OpenAPI.Data.final_data.tenant_data import *
@ddt.ddt
class test_case(unittest.TestCase):
# 每个测试用例执行之前做操作
def setUp(self):
pass
# 每个测试用例执行之后做操作
def tearDown(self):
pass
# 所有测试执行之前
@classmethod
def setUpClass(cls):
# 删除所有租客(只清空1001房间的租客)
del_all_tenan... |
#!/usr/bin/env python3
"""
Display some information like pie charts...etc... in order to analyse the
results of the evaluation part of the algorithm.
"""
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import yaml
import numpy as np
import preprocessing as pp
# Constants
... |
from collections import defaultdict
from django.conf import settings
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.paginator import EmptyPage, Pa... |
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report,confusion_matrix
cancer= load_breast_cancer()
X = cancer['data']
y = c... |
# -*- coding:utf-8 -*-
__author__ = 'yyp'
__date__ = '2018-4-4 23:46'
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower()
i = 0
j = len(s) - 1
while i < j:
if not self._is_alphanumeric(s[i]):
... |
from .models import *
from django.shortcuts import render, get_object_or_404
class EventService:
def add_events(self, list_of_events):
for event in list_of_events['events']:
ticket_classes = list(filter(lambda x : x['on_sale_status']=="AVAILABLE", event['ticket_classes']))
if len(ticket_classes) == 0:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__date__ = '2018/4/3 21:24'
__author__ = 'ooo'
import numpy as np
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
class FPNet(nn.Module):
def __init__(self, indepth, outdepth, stages):
super(FPNet, self).__init__()
self.... |
import copy
from datetime import datetime
from common import finished, next_configs, process_results, build_path
from utils import *
ALGORITHM_NAME = "Breadth First Search (BFS)"
def bfs(level, testall):
initial_time = datetime.now()
smap = level.smap
first_node = Node(level.st... |
# Generated by Django 2.1.15 on 2020-08-23 06:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('watcher', '0002_auto_20200819_1642'),
]
operations = [
migrations.CreateModel(
name='Floor',
... |
## Conjuntos, como manipular e sua aplicação ##
# Para criar um conjunto uriliza a "{}"
conjunto = {1, 2, 3, 4, 2, 4} # O conjunto não imprime valores que estão duplicados
print(type(conjunto))
print(conjunto)
conjunto.add(5) # Incorpora elemento ao conjunto
print(conjunto)
conjunto.discard(2) # Remove elemento ao ... |
"""Write a Python program to calculate the hypotenuse of a right angled triangle."""
import math
def hypo(h,base):
return math.hypot(h, base)
print(hypo(10,2)) |
from graphene import ObjectType, String, ID, Float, Field, Boolean
class Position(ObjectType):
dec = Float()
ra = Float()
dec_dot = Float()
ra_dot = Float()
epoch = String()
class Magnitude(ObjectType):
min_magnitude = Float()
max_magnitude = Float()
filter = String() # from bandpas... |
from sklearn.linear_model import Ridge, Lasso, LinearRegression, RidgeCV
from sklearn.model_selection import cross_validate, cross_val_predict, cross_val_score, KFold
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler
from sklearn.preprocess... |
# Created by jongwonkim on 25/06/2017.
import os
import logging
import json
import re
from src.dynamodb.intents import DbIntents
log = logging.getLogger()
log.setLevel(logging.DEBUG)
db_intents = DbIntents(os.environ['INTENTS_TABLE'])
def compose_validate_response(event):
event['intents']['current_intent'] = '... |
# -*- coding: utf-8 -*-
# @Time : 2020/9/16 0:25
# @Author : MA Ziqing
# @FileName: sql_cli.py.py
#
# import os
# import sys
# from sqlalchemy import create_engine
# from sqlalchemy.orm import sessionmaker
# from sqlbase.sql_table_base import QualityIndicator, OutputDB, Result1, Result2
#
#
# class DataBaseSqlClien... |
"""
Contains i/o-related functions.
Public Functions:
- build_dict_string -- converts a dictionary into a string
equivalent (i.e., the literal representation of the dictionary
in code).
- clear_screen -- clears the screen (if supported by the console).
- del_from_list -- delet... |
#! /usr/bin/env python3
from argparse import ArgumentParser, Namespace
import pathlib
import sys
from lib.app import App
from lib.config import ApplicationConfig, load_config
def main(opts: Namespace) -> int:
config: ApplicationConfig = load_config(opts.config)
app = App(config)
app.setup_routes()
... |
import sys
from time import sleep
import pygame
from settings import Settings
from game_stats import GameStats
from scoreboard import Scoreboard
from button import Button
from ship import Ship
from bullet import Bullet
from alien import Alien
class AlienInvasion:
"""Overall class to manage game assets and behav... |
# The following comments couldn't be translated into the new config version:
# Test storing OtherThing as well
# Configuration file for PrePoolInputTest
import FWCore.ParameterSet.Config as cms
process = cms.Process("TESTBOTHFILES")
process.load("FWCore.Framework.test.cmsExceptionsFatal_cff")
process.OtherThing = ... |
"""
Alright. Here is the meat of the program.
This looks overwhelming, being a 400+ line file,
but the vast majority of it is just creating and sending
very repetitive embedded messages to run communications with the user.
"""
import discord
from discord.ext import commands
import datetime
import random # for embeds
... |
from flask_wtf import Form
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import Required
class NameForm(Form):
username = StringField('Username', validators=[Required()])
password = PasswordField('Password', validators=[Required()])
submit = SubmitField('Submit') |
import pylab
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def f1(t, x, y, z): return y*(z-1+x**2)+gamma*x
def f2(t, x, y, z): return x*(3*z+1-x**2)+gamma*y
def f3(t, x, y, z): return -2*z*(alpha+x*y)
gamma=0.03
alpha=0.02
x_initial=-0.67
y_initial=0.
z_in... |
# Generated by Django 3.2.2 on 2021-05-25 11:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0005_alter_userprofile_profile_picture'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
... |
first_name = "sruthi" #1.created a variable first_name to store first name
last_name = "VANGARA" #2.created a variable last_name to store last name
print("Hello",first_name.upper(),last_name.lower()) #3.using string function upper() to convert first_name into upper case and function lower() to convert last_name int... |
from flask import Flask
from flask import request,render_template, Response,request
from Camera import Camera
import time
app = Flask(__name__)
frame = None
def gen():
"""Video streaming generator function."""
while True:
#frame = Camera.get_frame()
#print("public frame frame type:"+str(type(fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.