text stringlengths 38 1.54M |
|---|
# convert from png to jpg
# png - RGBA
# jpg - RGB
from PIL import Image
# current image
blue_png = Image.open('C:\\Users\\svfarande\\onedrive\\Documents\\Study '
'MAterial\\Python\\PyCharm Projects\\PyBootCamp\\Images\\blue_color.png')
blue_jpg = blue_png.convert('RGB')
# new image
blue_jpg.s... |
from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
from dateutil import parser
import datetime
import TakeTest, Feedback, CreateTest, login, Test
import csv
import os
import shelve
#Note for later self: check if a test name with the same name exists when creating a test. Maybe also ad... |
from .location import Location
from .playlist_user import PlaylistUser
from .playlist import Playlist
from .user import User
|
# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError, Warning
class AccountTaxTemplate(models.Model):
_inherit = 'account.tax.template'
l10n_pe_edi_tax_code = fields.Selection(selection=[
('1000', 'IGV - VAT - Impuesto General a la... |
from flask_restx import fields
from weakref import WeakSet
class AnyNotNullField(fields.Raw):
__schema_type__ = 'any'
def format(self, value):
if not isinstance(value, WeakSet):
return value
class ForbiddenField(fields.Raw):
__schema_type__ = 'any'
def format(self, value):
... |
from tkinter import *
from tkinter import Menu
import ScrolledText
import tkinter.messagebox
import tkinter.filedialog
root=Tk(className="Project Laminus")
def dummy():
print ("I am a Dummy Command,I will be removed in the next step")
def open_file():
f = tkinter.askopenfile(defaultextension=".txt", filet... |
import os.path
import random
import hashlib
from datetime import datetime
SALT = "abc123"
def add_salt(string):
return f"{string}{SALT}"
def user_exists(username):
if os.path.isfile(f"{username}.txt"):
return True
else:
return False
def generate_tokens(seed):
tokens = []
token... |
#!/usr/bin/python
import time
import subprocess
import sys
try:
c = open("/home/pi/Watchman/useGprs.txt","r")
status = c.read()
status = status.strip()
c.close()
except Exception as e:
sys.exit()
if status == '1':
time.sleep(10)
subprocess.call(['sudo','/home/pi/Watchman/activateGprs.py'])
|
#!/usr/bin/python
from platform import python_version
import time
if python_version().split(".")[0] == "2":
print("Running in Python 2")
t1 = raw_input("Starting time (hours:minutes): ")
t2 = raw_input("Ending time (hours:minutes): ")
else:
print("Running in Python 3")
t1 = input("Starting time (hours:minutes): ... |
from typing import List, Dict
from random import randint
class Solution:
def __init__(self, nums: List[int]):
self.indexes: Dict[List[int]] = {}
for i, num in enumerate(nums):
if num not in self.indexes:
self.indexes = [i]
else:
self.indexes... |
from django.test import TestCase
from django.urls import reverse, resolve
from chat.views import Inbox,cost_chat,UserSearch,Directs,SendDirect,Inbox_cost,Daliy_Tip
class Test_url(TestCase):
def test_Inbox(self):
url = reverse('chat:Inbox')
self.assertEqual(resolve(url).func, Inbox)
... |
document = open('mbox-short.txt')
hours= dict()
for line in document:
if line.startswith('From'):
line = line.split()
if len(line) >= 4:
hour = line[5]
hour = hour.split(':')
hour = hour[0]
hours [hour] = hours.get(hour, 0) + 1
count = list()
for ho, t... |
class Solution:
def matrixMultiplication(self, n, arr):
dp = [[float("inf")] * n for i in range(n)]
for i in range(n):
dp[i][i] = 0
for l in range(2, n):
for i in range(1, n - l + 1):
j = i + l - 1
for k in range(i, j):
... |
import datetime
rok_urodzenia = int(input("PODAJ ROK URODZENIA"))
aktualny_rok = datetime.datetime.now().year
wynik = aktualny_rok - rok_urodzenia
if wynik >=18:
print ("Jesteś pełnoletni!")
else:
print("Nie jesteś pełnoletni!") |
from CSVinfo import *
class MotherboardData:
'''
This class contains only static methods. Methods name are descriptive of their function.
Additional required information, wherever necessary, has been specified.
'''
def get_motherboard_price(row):
price = MotherboardData.extract_num_data(row... |
from django.shortcuts import render, HttpResponse, redirect, reverse
from django.views.generic import View
from apps.user.models import User
import re
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
from django.conf import settings
from django.core... |
sum = 0
while True:
number = input("Enter the item price or press q to quit : ")
if number != 'q':
sum += int(number)
print(f"Order total so far {sum}")
else:
print(f"Your bill total is {sum}")
print("Thanks for shopping")
break |
from typing import MutableMapping
from django.shortcuts import render
from django.http import HttpResponse
from .models import city
def index(request):
citys = city.objects.all()
return render(request,'index.html',{'citys':citys}) |
# Copyright (c) The Diem Core Contributors
# SPDX-License-Identifier: Apache-2.0
swagger_template = {
"swagger": "",
"openapi": "3.0.0",
"components": {
"securitySchemes": {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
import statsmodels.formula.api as sm
data = pd.read_excel(".\\Data\\Folds5x2_pp.xlsx")
col = data.columns
for i in range(0, 4):
train_data = data[[col[i], col[-1]]]
clf = sm.ols(formula=col[-1]+'~ ' + col[... |
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = socket.gethostname()
clientport = 12346
s.bind((host, clientport))
while True:
data, addr = s.recvfrom(1024)
print addr[1] |
import numpy as np
import matplotlib.pyplot as plt
import sklearn.metrics.pairwise
from sklearn.ensemble import GradientBoostingClassifier
from sklearn import metrics
from active_learning.core import ActiveLearner, MAL1, MismatchFirstFarthestTraversal, LargestNeighborhood
def target_func(X):
y = np.zeros(len(X))
... |
from datetime import datetime, timedelta
from google.appengine.api import mail
from handlers.base import BaseHandler
from models.forum_subscription import ForumSubscription
from models.topic import Topic
class SendMailForumSubscribersCron(BaseHandler):
def get(self):
day_ago = datetime.now() - timedelta(d... |
import wx
class Frame(wx.Frame):
#add title variable
def __init__(self, title):
#title = title variable
wx.Frame.__init__(self, None, \
title = title, size = (300,200))
self.Center()
panel = wx.Panel(self)
button = wx.Button(panel,label = "Exit... |
import sys
import cx_Oracle
import getpass
import random
import string
import datetime
#converts date number into corresponding month for easy visualisation when output at the end.
monthdic ={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
def validity(s... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
VGG16 model for chainer 1.8
"""
import chainer
import chainer.functions as F
import chainer.links as L
import os, sys
import numpy as np
shared = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(shared)
from ..functions import power_normaliz... |
# Generated by Django 3.2.4 on 2021-07-14 11:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('team', '0002_alter_team_created_by'),
]
operations = [
migrations.AddField(
model_name='team',
name='bank_account',
... |
from django.db import models
# Create your models here.
class User(models.Model):
def __str__(self):
return self.id
pid = models.CharField(max_length=32, primary_key=True)
id = models.CharField(max_length=20, null=False, unique=True)
|
import torch
from torchvision import models
from torchvision import transforms
import os
import numpy as np
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torchvision import datasets
import shutil
import time
import configparser
import requests
import json
import random
#Krishna
import urll... |
import math
def N(dim, maxsum=None):
total = dim
if dim == 1:
while maxsum == None or total <= maxsum:
try:
yield tuple([total])
except GeneratorExit:
return
total += 1
else: # dim >= 2
while maxsum == None or total <= maxsum:
for tup in N(dim - 1, total - 1):
newTuple = [t for t in tup]... |
#!/usr/local/bin/python3
#
# See https://theweeklychallenge.org/blog/perl-weekly-challenge-149
#
#
# Run as: python ch-1.py < input-file
#
def digit_sum (number):
sum = 0
base = 10
while number > 0:
sum = sum + number % base
number = number // base
return sum
fib = {... |
from django.conf import settings
from django.conf.urls import static
from django.contrib import admin
from django.urls import path
admin.autodiscover()
urlpatterns = [
path("admin/", admin.site.urls),
]
urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
# -*- coding:utf-8 -*-
import os,urllib2
def downloadBAT():
url='https://raw.githubusercontent.com/wkcn/SYSULAB/master/AddENV.bat'
try:
content = urllib2.urlopen(url).read()
f = open("AddENV.bat", "w")
f.write(content)
f.close()
return True
except Exception, e:
... |
# Generated by Django 3.1.1 on 2020-10-16 13:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('product', '0004_auto_20201013_1856'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='size',
),... |
#!/usr/bin/env python
# coding: utf-8
# In[20]:
def divisorsSum(n):
ret = 0
for i in range(1, n-1):
if n%i == 0:
ret += i
return ret
# In[21]:
N = 28123
abundants = []
for i in range(1,N+1):
if divisorsSum(i) > i:
abundants.append(i)
# In[22]:
sumOfAbundantsSet = s... |
#!/usr/bin/env python3
import sys
import os
import pystache
lines=open(sys.argv[1]).read()
out_file = open(os.path.splitext(sys.argv[1])[0], "w")
tags = {}
args = sys.argv[2:]
while len(args) > 0:
key = args.pop(0)
tags[key] = args.pop(0)
lines = pystache.render(lines, tags)
out_file.write(lines)
out_file.c... |
# using stack, visit all vertice
def dfs(g, start):
visited = {key: 0 for key in graph.keys()}
stk = [start]
nodes = []
while stk:
node = stk.pop()
for adjacent in g[node]:
if visited[adjacent] == 0 and adjacent not in stk:
stk.append(adjacent)
visi... |
import sys
sys.path.append("..")
import astral.client.gameclient as gc
import astral.client.local as local
import physics
class UMMOMob(local.Mob):
template = "UMMOMob"
def init(self):
super(UMMOMob,self).init()
self.prediction_func = physics.actor_move
self.add_property(loca... |
import tkinter
def getWordList():
f= open('Words','r')
array = []
i = 0
for line in f:
if(line != '\n'):
array.append(line[:-1])
else:
continue
groupedArray = []
for word in array:
if(i%2 == 0):
groupedArray.append([word])
elif(i%2 == 1):
groupedArray[-1].append... |
import numpy as np
from scipy.stats import ks_2samp
from typing import Callable, Dict, Optional, Tuple, Union
from alibi_detect.cd.base import BaseUnivariateDrift
from alibi_detect.utils.warnings import deprecated_alias
class KSDrift(BaseUnivariateDrift):
@deprecated_alias(preprocess_x_ref='preprocess_at_init')
... |
class Pycharm:
def execute(self):
print("Compiling.")
print("Running.")
class VScode:
def execute(self):
print("Spell Check.")
print("Convention Check.")
print("Compiling.")
print("Running.")
class Laptop:
def code(self, ide):
ide.execute()
if ... |
from django.conf.urls import patterns, url
from cave import views
urlpatterns = patterns('',
url(r'^$', views.home, name='home'),
url(r'^populate/', views.populate, name='populate'),
url(r'^testcave/', views.testcave, name='testcave'),
url(r'^home/', views.home, name='home'),
url(r'^voirCave/', ... |
# -*- coding: utf-8 -*-
"""
MAS480 Mathematics and AI
Homework 3 - Module for Sampling and Comparing result
20180127 Woojin Kim
"""
import numpy as np
import pandas as pd
def sampling(g, initial_point, length, num, printable = True):
all_samples = []
while num > 0:
current_state = g.get_state(in... |
'''
//参考英文网站热评第一。这题可以用快慢指针的思想去做,有点类似于检测是否为环形链表那道题
//如果给定的数字最后会一直循环重复,那么快的指针(值)一定会追上慢的指针(值),也就是
//两者一定会相等。如果没有循环重复,那么最后快慢指针也会相等,且都等于1。
'''
# 快慢指针方法
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
def get_digits(num):
output = 0
... |
string_variable = "Today is the "
number_variable = 22
month_variable = " day of the month"
output_variable = string_variable + str(number_variable) + month_variable
print(output_variable) |
import pickle
c=0
def agregar(dic):
x = input("Pregunta: ")
y = input("Respuesta: ")
dic[x] = y
def cargar_datos():
try:
with open("parcial.dat", "a") as f:
return pickle.load(f)
except (OSError, IOError) as e:
return dict()
def guardar_datos(dic):
... |
# Keyboard Service
from service.language import Language
class Keyboard():
"""
Keyboard Service. Provides a keyboard model and methods based on key layout
and language configurations.
"""
# fingers
LEFT_PINKY = 'LP'
LEFT_RING = 'LR'
LEFT_MIDDLE = 'LM'
LEFT_INDEX = 'LI'
LEFT_THUMB = 'LT'
THUMB = 'T'... |
__author__ = 'socialmoneydev'
from utils.requestor import Requestor
from models.jsonBase import JsonBase
from account import Account
from externalaccount import ExternalAccount
from models.customeraddress import CustomerAddress
from models.customerphone import CustomerPhone
from models.customeridonly import CustomerId... |
#!/usr/bin/python
'''
File name: multiple_btree_timing_ltarchive.py
Prepared by: MCL
Date created: 16/8/2017
Date last modified: 2/11/2017
Python Version: 2.7
This script compares the run time of PostgreSQL queries with a positional
and a instrumental selection, 4 cases are compared:
(... |
#!/usr/bin/env python
import sys
sys.path.append("/home2/data/Projects/CWAS/share/lib/surfwrap")
import os
from os import path as op
import numpy as np
import nibabel as nib
from pandas import read_csv
from newsurf import *
from rpy2 import robjects
from rpy2.robjects.packages import importr
# Plots each of the app... |
# import os
# import sys
# source_path = os.path.dirname(os.path.abspath(sys.argv[0])) + "/basenji/source"
# source_path2 = os.path.dirname(os.path.abspath(sys.argv[0])) + "/basenji/basenji"
# source_path3 = os.path.dirname(os.path.abspath(sys.argv[0])) + "/3Dpredictor/source"
# source_path4 = os.path.dirname(os.path.a... |
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
"""
Basic thread handling exercise:
Use the Thread class to create and run more than 10 threads which print their name and a random
number they receive as argument. The number of threads must be received from the command line.
e.g. Hello, I'm Thread-96 and I received the number 42
"""
from random im... |
import warnings
warnings.filterwarnings("ignore", category = FutureWarning)
import keras
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, regularizers
from keras.layers import Activation
from keras.layers import Dropout
import matplotlib.pyplot as plt
from utils import *
def ge... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Template(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
content = models.TextField()
class EmailSent(models.Model):
conten... |
import csv
import math
import pandas as pd
# Load a CSV file
def load_csv():
dataset = list()
with open('Diabetes.csv', 'r') as file:
data = csv.reader(file)
next(data, None)
for row in data:
dataset.append(row)
for column in range(len(dataset[0])):
... |
import Mission
import time
class SeriesMission(Mission.Mission):
def __init__(self, missions):
Mission.Mission.__init__(self) # Critical line in every mission
self.missions = missions # List of missions to run
self.started = [False] * len(self.missions) # List representing
# whi... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 16:21:19 2019
@author: D
"""
def main():
EmailBook=open('C:\\Users\\D\\Documents\\Python\\EmailBook.txt','rb')
TelBook=open('C:\\Users\\D\\Documents\\Python\\TelBook.txt','rb')
# EmailBook.readline()
# TelBook.readline()
linesEmailBook=EmailBook.re... |
# -*- coding: UTF-8 -*-
import time
import config_params
def query_set_from_table(typ):
""" typ value must 'tpl' or 'asrep' """
# for keys: need `rpt`, `secu`, `y`, `q`, `fp`, `stdtyp` and assure whether `ctyp` is equivalent on both sides.
# for query data: `active` is True
# to two records: must ma... |
# Author : Md. Shahedul Islam Shahed
# Language : python 3.5
# Concise : Calculates aspect ratio and dimensions
import argparse
import math
def main():
parser = argparse.ArgumentParser(description="Get aspect dimensions (lenth and width).")
parser.add_argument('-d', '--diag-len', dest='diag_len', metavar='LE... |
from mutagen import flac
import MySQLdb as mariadb
import os
import sys
def getArtistID(album_artist, conn):
album_artist = album_artist.replace("'", "''")
cursor = conn.cursor()
sql = "SELECT artistid FROM artist WHERE artistname='{}';".format(album_artist)
cursor.execute(sql)
row = cursor.fetcho... |
from .models import Place
from .serializers import PlacePutSerializer
from rest_framework.viewsets import ModelViewSet
from django_filters import rest_framework as filters
from django.db.models import Count, F
# from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.generics import (
List... |
"""
Builds FHIR Organization resources (https://www.hl7.org/fhir/organization.html)
from rows of tabular sequencing center data.
"""
from kf_lib_data_ingest.common.concept_schema import CONCEPT
from kf_model_fhir.ingest_plugin.shared import join
class SequencingCenter:
class_name = "sequencing_center"
resour... |
# coding:utf-8
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.jinja_env.variable_start_string = '%%'
app.jinja_env.variable_end_string = '%%'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:ditto9689a@localhost:3306/newslistdb'
app.config['SQLALCHEMY_TRACK_MODIFICATI... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
depth_l = []
depth_r = []
def returnD... |
import ast
import re
import random
from models.transition_matrix import TransitionMatrix
class TextGenerator:
def __init__(self, file_path, song_length=50):
lyrics_file = open(file_path, "r")
lyrics_dict = ast.literal_eval(lyrics_file.read())
lyrics_file.close()
all_lyrics = ""
... |
"""isort:skip_file"""
get_ipython().magic('config InlineBackend.figure_format = "retina"')
import os
import logging
import warnings
import matplotlib.pyplot as plt
# Remove when Theano is updated
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)... |
#Matriz de correlación
import librosa
import librosa.display
import matplotlib.pyplot as plt
import sys
audioname = ("example2.wav")
y, sr = librosa.load(audioname)
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=12)
# Find nearest neighbors in MFCC space
R1 = librosa.segment.recurrence_matrix(mfcc)
# Or fix the nu... |
'''
Query Kowalski searching for counterparts to FRBs
Author: Igor Andreoni
'''
import numpy as np
import json
from collections import OrderedDict
import pdb
from astropy.time import Time
from astropy.table import Table, unique
from astropy.io import ascii
import matplotlib.pyplot as plt
from astropy import units as ... |
import os
import shutil
import time
import ujson
from HTMLParser import HTMLParser
from base64 import b64decode
import bencode
from django.conf import settings
from django.core.management.base import BaseCommand
from html2bbcode.parser import HTML2BBCode
from WhatManager2.manage_torrent import add_torrent
from WhatMa... |
import os
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.animation import Animation
from human_interfaces.base import HumanInterfaceBase
class RPS... |
import socket, time, json,threading
import package.settings.setting
import copy
# 用于将三个字段序列化
def messages_to_json(type, router_table, ip_mapping, receiver):
message = dict()
message['type'] = type
# 判断,只发送存活节点的信息
router_Names = []
for name in receiver:
if name in router_table[p... |
import random
import string
from datetime import timedelta
from django.conf import settings
from django.utils.timezone import localtime, now
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from care.facility.models.patient import PatientMobileOTP
from care.utils.sms.sendSM... |
# Generated by Django 3.1.7 on 2021-05-30 11:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('settings', '0004_auto_20210530_1458'),
]
operations = [
migrations.CreateModel(
name='Subjects'... |
import re
from utils.Logger import *
from utils.Helper import Helper
from youtubesearchpython import VideosSearch
import re
helper = Helper()
async def YouTubeSearch(songName, maxresults=1):
try:
if songName in ["", None]:
return None
urls = helper.getUrls(songName)
song_url ... |
from django.db import models
from paciente.models import MyUser
from django.conf import settings
from datetime import datetime
class Humor(models.Model):
email = models.ForeignKey(MyUser, on_delete=models.CASCADE)
dia = models.DateField(auto_now=True... |
# Import libraries
import numpy as np
from flask import Flask, request, jsonify
import pickle
from sklearn.externals import joblib
app = Flask(__name__)
# Load the model
model = joblib.load(open('./linreg_model.pkl','rb'))
@app.route('/api',methods=['POST'])
def predict():
# Get the data from the POST request.
... |
import scrapy
import search_url
class AmazonSpider(scrapy.Spider):
"""docstring for AmazonSpider"""
name = "products"
start_urls = []
start_urls.append(search_url.get_search_url(raw_input("Enter the keyword\n")))
def parse(self, response):
for product in response.css("ul.s-result-list"):... |
import requests
url = 'http://127.0.0.1:5000/getsetu'
def getSetu():
req = requests.get(url)
return req.json() |
import sys
import os
import csv
import argparse
from datetime import timedelta,date,datetime
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from py_db import db
db = db('personal')
key_file = os.getcwd()+"/un_pw.csv"
key_list = {}
with open(key_file, 'rU') as f:
... |
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from apiclient import errors
# If modifying these scopes, delete the file token.json.
class Gmail:
SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
S... |
#!/usr/bin/env python
import numpy as np
import pandas as pd
# load data
data = np.loadtxt(open("/home/chs/Desktop/Sonar/Data/drape_result/Result_0.csv"), delimiter=",")
''' Calibrate delta_z '''
# Init
beta = np.ones(3) # c(a) = b0 + b1a +b2a^2
alpha = 0.2 # learing rate
tol_l = 0.01
# Normalize data
max_x = data[:... |
# Generated by Django 3.1.7 on 2021-04-08 09:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app_matrice', '0010_society_user'),
]
operations = [
migrations.RemoveField(
model_name='society',
name='user'... |
import os
from typing import Tuple, Callable
import gym
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from tensorlib import rl
from tensorlib.rl.utils.replay.replay import TransitionReplayBuffer
from tensorlib.rl.utils.replay.sampler import StepSampler
from tensorlib.utils.logx import... |
"""
Рассмотрим все целочисленные комбинации a^b для 2 ≤ a ≤ 5 и 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
Если их расположить в порядке возрастания, исключив повторения, мы
получим следующую последовательность из 15 разли... |
def hello():
print('Hello people!!')
hello()
def greetings(name, salute):
print(f'Good {salute} Mr. {name}')
greetings('Benedict', 'morning')
greetings('Alabi', 'afternoon')
greetings('Tope', 'night')
def add(num1, num2):
summation = num1 + num2
print(summation)
add(5, 6)
add(15, 7)
add(11, 10)
#... |
#Extract_Hydro_Params.py
#Ryan Spies
#ryan.spies@amec.com
#AMEC
#Description: extracts SAC-SMA/UNITHG/LAG-K parameters values
#from CHPS configuration .xml files located in the Config->ModuleConfigFiles
#directory and ouputs a .csv file with all parameters
# NOTE: this script differs from the extract_hydro_par... |
# -*- coding: utf-8 -*-
"""
剑指 Offer 47. 礼物的最大价值
在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物?
示例 1:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 12
解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物
提示:
0 < grid.length <= 200
0 < grid[0].length <= 200
"""
f... |
#! python3
# mapIt.py - Launches a map in the browser using an address from the
# command line or clipboard.
# Ok lets look at another protocol http
import webbrowser, sys
if len(sys.argv) > 1:
# Get address from command line.
address = ' '.join(sys.argv[1:])
webbrowser.open('https://www.googl... |
#!/usr/bin/python
import boto3
from botocore.client import Config
import sys
from json import loads
from kafka import KafkaConsumer
from botocore.client import ClientError
import base64
if len(sys.argv) != 4:
print('Usage: ' + sys.argv[0] + ' <bucket> <filename> <kafka endpoint>')
sys.exit(1)
# endpoint and k... |
Calculator2 = open('ninestimetable.txt', 'w')
for C in range(-10,10):
cal = '%d\n' %(C*9)
Calculator2.write(cal)
Calculator2.close()
print ('Write = Successful')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class Condition(object):
def __init__(self):
self._field_name = None
self._field_value = None
self._operator = None
@property
def field_name(self):
return self.... |
import tornado.web
from handlers.base_handler import BaseHandler, refresh_user_cookie_callback
from models.course import Course
from models.user import User
import logging
class ProfileHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
self.refresh_current_user_cookie()
self.rend... |
import os
import argparse
import tensorflow as tf
from extract_data import extract_data
from progressbar import ProgressBar
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
def graph_eval(dataset_loc, input_graph_def, graph, input_node, output_node, batchsize):
input_graph_def.ParseFromString(tf.gfile.GFile(graph, "rb"... |
import random
import string
import time
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
... |
import h5py
import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import os
import numpy as np
# main_path_m = "/data-x/g10/zhangjie/3D/datasets/modelnet40_npy/"
# main_path_s = "/data-x/g10/zhangjie/3D/datasets/shapenet_npy/"
# main_path_m = "/data-x/g10/zhangjie/3D/datasets/model... |
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from only.gl import colors
from only.gl.scene import Scene
class MyScene(Scene):
def init_model(self):
self.x = 0.0
self.y = -0.5
self.z = 0.0
self.color = colors.GREEN
def draw(self):
# Draw ... |
from django.test import TestCase
from django.contrib.auth.models import AnonymousUser
from kawaz.core.personas.tests.factories import PersonaFactory
from .factories import ProductFactory
class ProductCreatePermissionTestCase(TestCase):
def setUp(self):
self.product = ProductFactory()
self.user = Pe... |
import numpy as np
import matplotlib.pyplot as plt
import emoji
import pandas as pd
from keras.utils.np_utils import to_categorical
df_train = pd.read_csv('data/train_emoji.csv', header=None)
df_test = pd.read_csv('data/tesss.csv', header=None)
X_train = df_train[0]
Y_train = df_train[1]
X_test = df_test[0]
... |
from abc import ABC,abstractmethod
from collections import namedtuple
Customer=namedtuple('Customer','name fidelity')
class LineItem:
def __init__(self,product,quantity,price):
self.product=product
self.quantity=quantity
self.price=price
def total(self):
return self.price*self.quantity
class Order:
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.