text
stringlengths
38
1.54M
import pandas as pd import numpy as np import math class ErlangC: def __init__( self, lmbd: float, # mean arrival rate of customers into the system s_bar: float, # Expected customer service time n_agents: int, # number of agents ): self.lmbd = lmbd ...
import pytest import sys, os try : import Queue except: import queue as Queue # Adds App, Config directory to sys path for testing path = os.path.abspath(__file__) app = path[0:path.find("test")] + "app" config = path[0:path.find("test")] + "config" sys.path.append(app) sys.path.append(config) from Subscript...
import glob import xarray as xr import numpy as np import pandas as pd from scipy import stats RUTA = '/home/users/vg140344/datos/data/fogt/' #lista = xr.open_mfdataset(RUTA + "correlations/seasonal*_SPoV_enso*.nc4", chunks=None) #file = RUTA + "seasonal_correlations_SPoV_enso_polar.nc4" #correlations = xr.open_dataset...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # def partition(head, x): # dummy = t = ListNode(next=head) # small = st = ListNode() # large = lt = ListNode() # while t.next: # if t.next.val < x: # st.next = t.next # ...
import random import string import pygame PANEL_width = 1000 PANEL_highly = 800 FONT_PX = 15 pygame.init() winSur = pygame.display.set_mode((PANEL_width,PANEL_highly)) font = pygame.font.SysFont("msyh.tss",25) bg_suface = pygame.Surface((PANEL_width,PANEL_highly),flags = pygame.SRCALPHA) pygame.Surface.co...
import sqlite3 def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d global conn def connect(): global conn conn = sqlite3.connect('./zf.db', check_same_thread=False) conn.row_factory = dict_factory def query(sql, *args...
from datetime import datetime from flask_bcrypt import Bcrypt from flask_sqlalchemy import SQLAlchemy bcrypt = Bcrypt() db = SQLAlchemy() class User(db.Model): """User Model.""" __tablename__ = 'users' id = db.Column( db.Integer, primary_key=True) username = db.Column( db.Text, nul...
from datetime import datetime from os import path def writing_to_file(n): with open(n, 'w') as file: file.write('Done!') # задание № 1 # создать функцию которая распечатает n раз слово privet - n передается как параметр функции def greetings(n): word = 'privet' if n == 0: return for ...
# -*- coding:utf8 -*- """Tweet operate classes. """ import datetime from twinkerer import utils TWITTER_URL_BASE = 'https://twitter.com' TWEET_HTML_TEMPLATE = u''' .. raw:: html <div class="twinker"> <p class="twinker_header">{tweet_title}:</p> <p class="twinker_body">{tweet_body}</p> <p class="twinker_...
# coding: utf-8 # flake8: noqa from __future__ import absolute_import # import models into model package from swagger_server.models.all_info import AllInfo from swagger_server.models.all_info_car import AllInfoCar from swagger_server.models.charge_perc import ChargePerc from swagger_server.models.charger import Charge...
species( label = '[CH2]C(C)C([O])CCCC(11275)', structure = SMILES('[CH2]C(C)C([O])CCCC'), E0 = (17.8534,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([2750,2770,2790,2810,2830,2850,1425,1437.5,1450,1225,1250,1275,1270,1305,1340,700,750,800,300,350,400,1380,1383.33,1386.67,1390,370,373.333...
#!/usr/bin/env python """ Remove duplicated string from unsorted linked list """ import sys sys.path.append("../") from llist import * def rm_dups(head): if head == None: return head values = [] n = head while True: if n == None: return head if n.data in values: ...
from tgboost import tgb import pandas as pd train = pd.read_csv('../../train.csv') train = train.sample(frac=1.0, axis=0) # shuffle the data train.fillna(-999, inplace=True) val = train.iloc[0:5000] train = train.iloc[5000:] train_y = train.label.values train_X = train.drop('label', axis=1).values val_y = val.labe...
arr = input() arr = arr[1:len(arr)-1] arr = list(map(int,arr.split(","))) k = int(input()) if k in arr or sum(arr) == k: print(0) else: arr.sort(reverse=True) _min1 = abs(arr[0] - k) for i in range(0, len(arr)-1): _tem1 = abs(arr[i]-k) _min1 = min(_min1,_tem1) tem1 = arr[0] for i...
import discord import asyncio import datetime import os import re import urllib import sys, traceback import requests, time from discord.utils import get client = discord.Client() url='' botOwner = "266640111897149440" @client.event async def on_ready(): print('Logged in as') print(client.user....
from flask_sqlalchemy import SQLAlchemy from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from marshmallow import Schema, fields, ValidationError from passlib.apps import custom_app_context as pwd_context db = SQLAlchemy() class User(db.Model): ''' Create a table for the users. ''' ...
month = int(input('월을 입력하세요 : ')) if month >= 3 and month <= 5 : print('%d월은 봄입니다.' % month) if month >= 6 and month <= 8 : print('%d월은 여름입니다.' % month) if month >= 9 and month <= 11 : print('%d월은 가을입니다.' % month) if month == 12 or month == 1 or month == 2 : print('%d월은 겨울입니다.' % month)
#coding=gbk from os import path as ospath from ConfigParser import ConfigParser CONF = None class myConfig(object): def __init__(self): self.conf = ConfigParser() self.conf.read('config.ini') def getStatus(self): return self.conf.get('service', 'status') def getPort(s...
# Filters edge_tuple for resolved tuples with h2 - h1 = 2 import pymongo as pm import time import csv ## # @param edge_id ID of edge to extract info about # return (ip1_id,ip2_id,hop_diff) def get_ip12(edge_id): edge = c_edges.find_one({"edge":str(edge_id)}) return (int(edge['ip1']),int(edge['ip2']),int(edge['l...
size=3 for i in range(1,size+1): print ("-"*(2*(size-i)),end="") s=chr(96+size) for j in range(1,i): s+=("-"+chr(96+size-j)) s2= s[::-1] print (s+s2[1::],end="") print ("-"*(2*(size-i))) for i in range(size-1,0,-1): print ("-"*(2*(size-i)),end="") s=chr(96+size) for j in range(1,i): s+=("-...
# -*- coding: utf-8 -*- from django.contrib import admin from data.models import Idol, Skill, SkillValue, Cartoon # Register your models here. class IdolAdmin(admin.ModelAdmin): list_display = ( 'idol_id', 'name', 'type', 'rarity', 'cost', 'offense', 'defen...
import os import sys import re import time import logging import hashlib import threading from configparser import ConfigParser from pathlib import Path from contextlib import contextmanager from datetime import timedelta from typing import NamedTuple, List from docopt import docopt from natural.date import compress as...
import numpy as np from scipy.optimize import linprog import matplotlib.pyplot as plt def nash_equilibrium(A): #Поиск минимума матрицы А min_value = abs(np.amin(A)) + 1 #Делаем матрицу положительной A += min_value #Подготовка столбцов ограничений для ЗЛП z = np.ones(A.shape[0]) b_1 = -np.one...
class Solution: def getFolderNames(self, names): from collections import defaultdict memo = defaultdict(int) res = [] for n in names: if memo[n] > 0: while n+'('+ str(memo[n]) +')' in memo.keys(): memo[n]+=1 res.append(n...
# #-*- coding: utf-8 -*- # from __future__ import unicode_literals # from django.db import models # from django.contrib.sites.models import * # from django.utils.translation import ugettext, ugettext_lazy as _ # from settings import MEDIA_ROOT # from mezzanine.pages.models import Page # from mezzanine.core.models im...
# IMPORTS import datetime import subprocess import sys import os # import time from datetime import datetime from genDipoles import buildSphere from numpy import * # Init formatted output file file_output = open('outputExcelParsed.txt', 'w') # Execute command and yield output as it is received def execute(cmd): p...
#!/usr/bin/env # coding: utf-8 # Open Issue: Class cant run as thread: https://github.com/r9y9/pylibfreenect2/issues/25 # Based on: https://github.com/r9y9/pylibfreenect2/blob/master/examples/multiframe_listener.py LIBFREENECT2_LIBRARY_PATH = '/home/vigitia/freenect2/lib/libfreenect2.so' import numpy as np import c...
# 什么叫变量 """ 变量就是一个存储数据的时候当前数据所在的内存地址的名字 num1 = 10 目的:为了快速找到数据 """ # 定义变量 """ 变量名 = 值 (赋值,程序是先计算等号右边的数值,然后把值赋值给变量里) 有命名规则 :数字,字母,下划线组成 :不能数字开头 :不能使用内置关键字 共计33个关键字 严格区分大小写 :A != a """ # 命名习惯 """ 见名知意 大驼峰...
import pymysql from util.myutil import release class Dbutil: def __init__(self,**kwargs): # 获取数据库连接参数 # 建立与数据库的连接 host = kwargs.get('host','localhost') port = kwargs.get('port',3306) user = kwargs.get('user','root') password = kwargs.get('password','123456') ...
from astropy.io import fits from astropy.wcs import WCS from regions import write_ds9 from regions import PixCoord, LinePixelRegion from multiprocessing import Pool import matplotlib.pyplot as plt from glob import glob import numpy as np import pandas as pd import os from pathlib import Path def block_array(arr, nrow...
from django.http import Http404,HttpResponse, HttpResponseRedirect from django.template.loader import get_template from django.template import Context from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required import ...
import my_module.util as tools import numpy as np _unitLoc = 'unit/' def collect(location): data = tools.floatParseCSVfile(location) data = tools.transpose(data) return data class classHandler: def __init__(self, fileName): self.fileName = fileName temp
from interfaces import IIndividual, IPopulation from parameters import * from genomes import * from operator import attrgetter from utils import rand_probability import copy class Movement: def __init__(self, empty=False): self.genes = [] if not empty: for i in range(3): ...
# Module: sockets # Date: 26th June 2006 # Author: James Mills, prologic at shortcircuit dot net dot au """Sockets Test Suite""" import unittest from time import sleep from circuits import Component from circuits.net.sockets import * def wait(): sleep(0.1) class Client(Component): channel = "clien...
# --coding:utf-8-- from rest_framework import routers from .user import UserAPIView from .goods import GoodsAPIView from .active import ActiveAPIView,ActiveGoodsAPIView # 声明api路由 api_router = routers.DefaultRouter() # 向api路由中注册ViewSet api_router.register('users',UserAPIView) api_router.register('goods',GoodsAPIView) ...
#!/usr/bin/python3 def isNumber(string): numbers = "0123456789" ops = "-+*/" num = 0 op = 0 char = 0 for ch in string: if ch in numbers: num += 1 elif ch in ops: op += 1 elif ch == ".": continue else: char +=1 i...
__author__ = 'mjohnpayne' # Blast CI proteins from unnaligned contigs against Pm proteins # if protein hits = duplicated protein # if protein doesn't hit highly = new protein from Bio.Blast import NCBIWWW from Bio.Blast import NCBIXML from Bio.Blast.Applications import NcbiblastpCommandline as blastp from Bio import ...
""" Django settings for shopping_junction project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings...
m , n = map(int,input().split()) data = [] for i in range(m) : dt= input() if dt not in data : data.append(dt) if len(data) < 8 : print("unsatisfactory") else : print("satisfactory")
import math from typing import Any, List, Mapping, Type, Optional, Callable import ray from ray.rllib.core.rl_module.rl_module import RLModule, ModuleID from ray.rllib.core.rl_trainer.rl_trainer import ( RLTrainer, ParamOptimizerPairs, Optimizer, ) from ray.rllib.core.rl_trainer.tf.tf_rl_trainer import Tf...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^register$', views.register), url(r'^login$', views.login), url(r'^books$', views.books), url(r'^logout$', views.logout), url(r'^books/add$', views.booksadd), url(r'^books/(?P<book_id>\d+)$',...
from GO4BehaviouralPatterns.ChainOfResponsibility.CoinHandlerBase import CoinHandlerBase class FiveCentHandler(CoinHandlerBase): def __init__(self): pass def handle_coin(self, coin): if coin.get_weight() == 5 and coin.get_diameter() == 5: print ("Captured 5 Cent") elif sel...
#-*- coding:utf-8 _*- """ -------------------------------------------------------------------- @function: @time: 2018-01-29 author:baoquan3 @version: @modify: -------------------------------------------------------------------- """ import sys import hashlib import redis from Mapper1 import UserContribute import...
class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ newnums = sorted(nums) if len(newnums) == 1: return [newnums] else: alllist = [] for i in range(len(newnums)): ...
from ucloud.core import auth def test_verify_ac(): d = { "Action": "CreateUHostInstance", "CPU": 2, "ChargeType": "Month", "DiskSpace": 10, "ImageId": "f43736e1-65a5-4bea-ad2e-8a46e18883c2", "LoginMode": "Password", "Memory": 2048, "Name": "Host01", ...
from django.contrib import admin from .models import Loyal from .models import Offer from .models import Domain from .models import Staff # Register your models here. class LoyalAdmin(admin.ModelAdmin): list_display=['Name','Contact','Email','Last'] class OfferAdmin(admin.ModelAdmin): list_display=['Category'...
# 2020-8-28 # 脑袋犹如静止,思维停滞 class Solution: def maxCoins(self, piles): piles.sort() ret = 0 first_and_second = piles[len(piles) // 3: ] for i in range(0, len(first_and_second), 2): ret += first_and_second[i] return ret # s = Solution() # piles = [2,4,1,2,7,8] ...
'''问题1 编写一个程序,查找所有可以被7整除但不是5的倍数的数字。在2000到3200之间(均包括在内)。所获得的数字应以逗号分隔的顺序打印在一行上。 提示: 考虑使用范围(#begin,#end)方法''' # list1 = [] # for i in range(2000,3201): # if i%7 ==0 and i%5 !=0: # list1.append(i) # for i in list1: # print(i,end=',') '''问题2 编写一个程序,可以计算给定数字的阶乘。结果应以逗号分隔的顺序打印在一行上。 假设将以下输入提供给程序:8 然后,输出应为...
import sys import re import cPickle as pickle from utils import timeit import glob import ntpath import pymongo from urlunshort import resolve import csv import ast from utils import timeout, TimeoutError, timeit, unshorten_url import requests import logging """ expand each url see that it has domain in orgs What twee...
''' Created on May 15, 2017 @author: Nate ''' import numpy as np import matplotlib.pyplot as plt import random def barOf(list): return sum(list) / len(list) def sampleStandardDeviation(list): sum = 0 xBar = barOf(list) for i in list: sum += (i - xBar) ** 2 return np.sqrt(sum / (len(list) ...
# Generated by Django 2.2 on 2019-04-17 12:59 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('users', '0005_auto_20190417_1459'), ('requets', '0008_auto_20190417_1408'), ] operations...
import numpy as np import pandas as pd import random df_sampleDB = pd.DataFrame(columns=['name', 'birth', 'sex', 'district', 'grade', 'regist', 'lastlogin', 'logincnt', 'cartcnt', 'ordercnt', 'orderqty', 'orderprice', 'couponcnt', 'couponused', 'refund']) # 데이터 프레임 생성 Lastname, Firstname = '김이박최정강조윤장임한오서신권황안송전홍', '시림서...
import torch from torch.autograd import Variable from .certificate import Certificate def optimize_isotropic_dds( model: torch.nn.Module, batch: torch.Tensor, certificate: Certificate, learning_rate: float, sig_0: torch.Tensor, iterations: int, samples: int, device: str = 'cuda:0' ) -...
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import datasets as ds import tensorflow as tf import Utils as myutils def load_dataset(verbose=False): data = ds.load_boston() if(verbose): for key in data: print('{0} : {1}'.format(key, type(da...
from shinra_error import ShinraError def get_title(html: str) -> str: st = html.find("<title>") + len("<title>") ed = html.find("</title>") if st == -1 or ed == -1: raise ShinraError("Title Not found") text = html[st:ed] ext = text.find(" - Wikipedia Dump") if ext != -1: return...
import json from functools import wraps from django.utils.safestring import mark_safe from django.http import HttpResponse, HttpResponseNotAllowed, Http404 from django.http import HttpResponseForbidden, HttpResponseBadRequest def ajax_view(only_POST=False, only_authenticated=False, **jsonargs): """ Decorator...
import serial import cv2 import numpy as np from .commander import Commander from .processor import Processor def nothing(x): pass class App(object): def __init__(self, port='/dev/cu.HC-05-DevB', baud=9600, cam=0): self.commander = Commander(port, baud) print('Commander initialized.') ...
items = ['LOL', 'AOV', 'Guitar'] print(items) items.append('PUBG') print(items) i = 0 replacing_item = 'DXD' items[i] = replacing_item print(items)
from ..structures import Dataset2 from .. import formats from .. import utils ############################################################################### class BBMRI2(Dataset2): """ The BBMRI complete genomics sequencing set. Provides functionality to query the genetic variants in the study. ...
import time import schedule from plyer import notification from src.notifier import Notifier from src.utils.configurer import config def job(notifier: Notifier, system_notifier: notification, delay: int = 2): """ Job to check if a delivery slot gets available for the default selected address in your bigbasket...
#!/usr/bin/python3 import argparse import sys import yaml import textwrap from string import Template def parse_arguments(): argParse = argparse.ArgumentParser() argParse.add_argument("-s", "--speed", help="REQUIRED: The speed of your weapon", type=int, required=True) argParse.add_argument("-i", "--input", help=...
from src.messages import errors class Error(Exception): def __str__(self): if Exception.__str__(self) == '': return self.__class__.__name__ return Exception.__str__(self) class BadRequest(Error): pass class Unauthorized(Error): pass class Forbidden(Error): pass clas...
"""Tornado Webserver staff. This module based on Tornado whicn is a Python web framework and asynchronous networking library. """ import os import tornado.ioloop import tornado.web import tornado.wsgi import utils from crawler import Admin, Crawler # This tells tornado where to find the template files settings = ...
#while문을 사용해 1부터 1000까지의 자연수 중 3의 배수의 합을 구해 보자. # result = 0 # i = 1 # while i <= 1000: # if i % 3 == 0: # result += i # i += 1 # print(result) #while문을 사용하여 다음과 같이 별(*)을 표시하는 프로그램을 작성해 보자. # * # ** # *** # **** # ***** # i = 0 # while True: # i += 1 # if i > 5: break # p...
import os import glob from chwall.utils import get_logger import gettext # Uncomment the following line during development. # Please, be cautious to NOT commit the following line uncommented. # gettext.bindtextdomain("chwall", "./locale") gettext.textdomain("chwall") _ = gettext.gettext logger = get_logger(__name__)...
# # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it wil...
#coding:utf-8 import threading import time '''在add(), remove()方法中添加获取和释放锁是为了体现rlock与lock的区别,在这里省去也可以''' class Box(object): lock = threading.RLock() def __init__(self): self.total_items = 0 def execute(self, n): Box.lock.acquire() self.total_items += n Box.lock.release()...
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * clr.AddReference("RevitNodes") import Revit clr.ImportExtensions(Revit.Elements) clr.ImportExtensions(Revit.GeometryConversion) objinstances = UnwrapElement(IN[0]) vectorlist = list() for item in objinstances: try: vectorlist.append(item.Facin...
from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.timezone import now class UserModel(AbstractUser): email = models.EmailField(verbose_name='邮箱', blank=True, null=True, default='') gender = models.CharField(choices=(('male', '男'), ('female', '女')), default='mal...
"""Main codrspace views""" import requests from datetime import datetime from StringIO import StringIO from zipfile import ZipFile from django.http import Http404, HttpResponse from django.shortcuts import render, redirect, get_object_or_404 from django.utils import simplejson from django.core.urlresolvers import rev...
import pytest from magma.config import config as magma_config from magma.util import reset_global_context @pytest.fixture(autouse=True) def riscv_mini_test(): magma_config.compile_dir = 'normal' reset_global_context()
import math import numpy as np import torch from torch import nn from torch.nn import Conv2d, BatchNorm2d, PReLU, Sequential, Module from models.encoders.helpers import get_blocks, bottleneck_IR, bottleneck_IR_SE, _upsample_add from models.stylegan2.model import EqualLinear,ScaledLeakyReLU,EqualConv2d class GradualS...
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import ode def fun(t, x): y=np.zeros((4, 1)) bet,eps,ro,gam,sigma,wa,taw,mu=0.6,0.084,0.95,0.1,0.0714,0.0588, 9.1324e-4,6.8493e-5 a=np.array([bet,eps,ro,gam,sigma,wa,taw,mu]) #x=np.array([S,E,I,C]) y[0]=(a[7]+a[5])-(a[0]*x[2]+a[2]*a[0]*x[3]+...
from distutils.core import setup import py2exe requires = [] setup( name='kiya', version='0.1', packages=['kiya'], requires=requires, console=['kiya/base.py'], options={ 'py2exe': { 'packages': [], 'includes': ['cairo', 'pygtk', ...
##General Calls import time import serial ##Pubnub Calls from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub ##Pubnub Configuration pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-c3...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # use the cgi library import cgi # enable debugging #import cgitb #cgitb.enable() # use internal sqlite3 database import sqlite3 #Define Main Function def main(): # use the cgi interface to get POSTED values fs = cgi.FieldStorage() logid = fs.getvalue("LOGID...
import logging from abc import ABC class LoggingClass(ABC): def __init__(self): self.logger: logging.Logger = logging.getLogger(self.logger_name) @property def logger_name(self) -> str: return self.__create_logger_name_from_class_name() def __create_logger_name_from_class_name(self) ...
from __future__ import print_function import urllib import boto3 import zipfile import json #-------- aws variables ----------- s3_client= boto3.client('s3') lambda_client = boto3.client('lambda') #-------- functions begin--------- def lambda_handler(event, context): # Get the object from the event and show its ...
import argparse import io from nltk.translate.bleu_score import corpus_bleu import sys def main(): parser = argparse.ArgumentParser() parser.add_argument("--input", required=False, type=str) parser.add_argument("--test", required=True, type=str) parser.add_argument("--order", type=int, default=4) ...
from django.conf.urls import patterns, include, url from deal import views urlpatterns = patterns('', url(r'^$', views.index,{'type': '0'}, name='deal.index'), url(r'^index/(\d+)/$', views.index,name='deal.index'), url(r'^rank_deal_type', views.rank_deal_type, name='deal.rank_deal_type'), url(r'^rank...
# -*- coding: utf-8 -*- from BaseObject import BaseObject # BaseStage(id, name, < teams = [], competitionId > ) class BaseStage(BaseObject): def set_up(self, **kwargs): self.stype = kwargs.get('stype') self.fixtures = [] self.teams = set() self.data['finished'] = False ...
""" Copyright (c) 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wri...
import argparse import time from max_sat import MaxSatClause, MaxSat from genetic_algorithm import MaxSatGeneticAlgorithm if __name__ == '__main__': parser = argparse.ArgumentParser(description='SATMAX genetic algorithm.') parser.add_argument('-question', help='Question number', type=int, required=True) pa...
#-*- coding:utf-8 -*- # python 进阶 list 元素字符串格式化 将首字母大写 def format_name(s): return s[:1].upper()+s[1:].lower() print map(format_name, ['adam', 'LISA', 'barT'])
def note(): """ >>> magic_str = "abra cadabra" >>> count_chars(magic_str) {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1} """ def count_chars(my_str): """get a string in a param and return a dic were every char in the string (not space) is a key and the times it appears in the string is the valu...
from collections import namedtuple from datetime import timedelta import json from django.contrib.auth.models import User from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import...
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from django.core.validators import validate_slug, validate_email from .models import Image from .models import Clusters class ImageForm(forms.ModelForm): class Meta: model = Image fields = '_...
#Program to print multiplication table of a given number using while loop num = int(input("Enter the number ")) i=1 while i<=10: a = num * i print(f"{num} X {i} = {num*i}") i=i+1
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/3/21 12:56 # @Author : Fred Yangxiaofei # @File : paid_write_redis.py # @Role : 用于提醒,如:将要过期的电信线路 import json from libs.database import model_to_dict from libs.database import db_session from libs.redis_connect import redis_conn from bi...
############################################################### # # Skeleton top job options for DQHistogramMerge_trf # #============================================================== #hack: we are forced to use athena (as a dummy) within the current PyJobTransformsCore theApp.EvtMax=1 # merge and/or rename monitorin...
import os import logging from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler from googleapiclient import discovery from google.oauth2 import service_account from datetime import datetime # Initializes your app with your bot token and socket mode handler app = App(token=os.environ.ge...
import bpy decimals = 0 scale = 1000 obj = bpy.context.active_object.data verts = [] faces = [] for v in obj.vertices: x = round(v.co.x * scale, decimals) y = round(v.co.z * scale, decimals) z = round(-v.co.y * scale, decimals) if decimals == 0: x = int(x) y = int(y) z = int(z)...
from django.db import models # Create your models here. class Notes(models.Model): Notes_Title = models.CharField(max_length=30) Notes_Desc = models.TextField() time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Notes_Title
#!/usr/bin/python #coding:utf-8 # https://a244.hateblo.jp/entry/2018/06/02/224659 #python ocr_api_sample.py import os import base64 import json from requests import Request, Session import requests import json import base64 # 画像はbase64でエンコードする必要があるため API_KEY = os.environ["GOOGLE_VISION_API"] def text_detection(im...
# 오셀로 함수 = 하나 돌 놓을 때마다 돌 다 뒤집는 함수 def Othello(y, x, dol): dy = [-1, -1, 0, 1, 1, 1, 0, -1] dx = [0, 1, 1, 1, 0, -1, -1, -1] for i in range(8): Y = dy[i] X = dx[i] # 상대방 돌을 내 돌로 바꾸는 리스트 생성 dol_change = [] while True: # 주변으로 이동 못할 때 or 돌이 없을 때 ...
import os import pandas as pd import datetime import shutil parent_dir = os.getcwd() # if there is a data folder, delete it and its content try: shutil.rmtree('data') except: pass # make a data folder and go into it dataFolder = 'data' os.makedirs(dataFolder) os.chdir(dataFolder) # add property file foldernam...
import subprocess def split_asts(project, giant_ast_file, n_per_file): """ Divide the list of ASTs into sub-files, to make it easier to process them with Ben's pipeline. The sub-files will be placed in the project folder, and also put into a tar file. Parameters ---------- project : stri...
import sqlite3 import random class BankingSystem: def __init__(self): self.conn = sqlite3.connect('card.s3db') self.cur = self.conn.cursor() # self.cur.execute('DROP TABLE card') self.cur.execute('CREATE TABLE card (id INTEGER PRIMARY KEY AUTOINCREMENT, ' ...
import sqlite3 import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # open a database connection conn = sqlite3.connect("source/m4_survey_data.sqlite") # print how many rows are there in the table named 'master' QUERY = """SELECT COUNT(*) FROM master""" # tripe quota marks can...
class Circle: def __init__(self, radius): # instance variable self.radius = radius self.pi = 3.14 class Area(Circle): def findArea(self): return f"Area: {round(self.pi * self.get_radius() * self.get_radius())}" # # s class Circumference(Circle): def findCircum(self): retu...