text stringlengths 38 1.54M |
|---|
# Generated by Django 2.2.7 on 2019-12-09 11:25
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('peop... |
'''
生成表格文件
'''
import xlwt
def writeform(x,y,z):
workbook = xlwt.Workbook(encoding = 'utf-8')
worksheet = workbook.add_sheet("频谱",cell_overwrite_ok=True)
for i in range(y):
worksheet.write(i,z,x[i])
workbook.save("C:\\Users\\yujiaoliang\\Desktop\\result.xls")
if __name__ == "__main_... |
import argparse
import math
import os
import numpy as np
from pathlib import Path
parser = argparse.ArgumentParser(description='Train Data info')
parser.add_argument('--path', default='example')
args = parser.parse_args()
f_train = open(args.path + "/Shoes_train.txt", "w+")
f_test = open(args.path + "/... |
#!/usr/bin/env python
"""
Example application for the 'blessed' Terminal library for python.
It is also an experiment in functional programming.
"""
from __future__ import division, print_function
# std imports
from random import randrange
from functools import partial
from collections import namedtuple
# local
fro... |
from pymongo import MongoClient
import datetime
import time
import re
client = MongoClient('localhost', 27017)
mestrado = client['mestrado']
news = client['news']
collections = ['oantagonista']
for collection in collections:
len_collection = mestrado[collection].count_documents({})
index = 0
# process c... |
from eccodes.high_level.gribfile import *
from eccodes import *
from ForecastError import ForecastError
from Bitmap import Bitmap
from TimeInterpolator import TimeInterpolator
import numpy as np
from matplotlib import pyplot as plt
from settings import *
f = open(SOURCE + "tmpsfc_00.grib2")
gid1 = codes_grib_new_fro... |
### twilio for zelsy
# (805)262-9284
from twilio.rest import Client
# Your Account SID from twilio.com/console
account_sid = "ACe9dcc22c9db899868a627562292d7c4b"
# Your Auth Token from twilio.com/console
auth_token = "0071b3cf8c984f389f9eb1e1b631806b"
client = Client(account_sid, auth_token)
message = ... |
from random import choice as c
student_names = ['Malcolm', 'Ian', 'Chase', 'Tab', 'Mike', 'Joe']
def generate_team(lst):
lst2 = lst[:]
team_a = []
team_b = []
counter = 0
for name in lst:
if counter % 2 == 0:
person = c(lst)
team_a.append(person)
lst2.re... |
from Cryptodome.PublicKey import RSA
key = RSA.generate(2048)
private_key = key.export_key()
file_out = open("private.pem", "wb")
file_out.write(private_key)
file_out.close()
public_key = key.publickey().export_key()
file_out = open("receiver.pem", "wb")
file_out.write(public_key)
file_out.close()
|
import os
from pathlib import Path
from appdirs import user_data_dir
class EnvManager:
"""Stashes environment variables in a file and
retrieves them in (a different process) with get_environ
with failover to os.environ
"""
app_env_dir = Path(user_data_dir("NEBULO"))
app_env = app_env_dir / ... |
#Meeri Seiman
#Kodutöö 1
print ("Tere, maailm!")
aasta = "2020"
liblikas = "teelehemosaiikliblikas"
lause_keskosa = "aastaliblikas"
lause = ['aasta','liblikas', 'lause_keskosa' ]
print("".join(lause))
import math
valueA = 4
valueB = 5
valueC = 8
aExp = valueA ** 2
bExp = valueB ** 2
cExp = val... |
import random
import time
import pytest
from faker import Faker
from ui_test.page.main_page import MainPage
faker = Faker(locale='zh-CN')
class TestCalendarWeb:
web = None
def setup_class(self):
self.web = MainPage()
def teardown_class(self):
self.web.quit()
@pytest.mark.parametri... |
from urllib import request
import re
import logging
# <div class="column_list ">
# <div style="background-image:url(http://img.blog.csdn.net/20151123174942067)" class="column_bg"></div>
# <a href="/column/details/postgresql.html" class="column_list_link" target="_blank">
# <div class="column_c">
# ... |
from minimax import *
from tablero import *
def test_busqueda():
#Datos de entrada
tablero = Tablero(6,7)
tablero.crear_tablero()
m = Minimax(tablero, [4,5,6])
tablero = [[1.0, 1.0, 2.0, 1.0, 2.0, 1.0, 1],
[2.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1],
[0.0, 2.0, 2.0, 0.0, 0... |
# -*- coding: utf-8
from __future__ import unicode_literals
import json
from django import VERSION as DJANGO_VERSION
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient, APITestCase, APIRequestFactory
from shop.models.defaults.cart im... |
import pygame as pg
from settings import *
class BitString(pg.sprite.Sprite):
def __init__(self, player):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((WIDTH/3, ARENA_BORDER/2-10))
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH/2
self.player = play... |
import pytest
# Run with:
# py.test test_string_comparision.py
def test_string_comparison():
str1 = u"Hello from the left hand side!"
str2 = u"Hello from the right hand side!"
assert str1 == str2
|
"""
CEASIOMpy: Conceptual Aircraft Design Software
Developed by CFS ENGINEERING, 1015 Lausanne, Switzerland
Functions used to help the cration of SUMO file
Python version: >=3.6
| Author: Aidan Jungo
| Creation: 2021-02-25
| Last modifiction: 2021-02-26
TODO:
*
"""
#=========================================... |
from django.db import models
from django.contrib.auth.models import User
from erp_test import settings
from erp_test.users.models import Group, Label
from erp_test.misc.helper import is_core, is_coord, get_page_owner, get_file_path
import os
# Create your models here.
#The choices may be cup level but if any thing bet... |
#i have created this file
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request,'index.html')
def analyze(request):
djtext=request.POST.get('text','default')
removepunc=request.POST.get('removepunc','off')
fullcaps=request.POST.get('fullcaps'... |
import cv2
import numpy as np
import os
import glob
import csv
import argparse
import math
from scipy.cluster.vq import *
k=3
l=6
no_of_centroids=int((math.pow(k,l-1)-1)/(k-1))
centroids=np.zeros((no_of_centroids,k,128),"float32")
def go(deslist,n):
BOW = cv2.BOWKMeansTrainer(k)
if(n>=no_of_centroids):
return
if... |
from django import forms
import datetime
from .models import Item
class ItemForm(forms.ModelForm):
date_received = forms.DateField(widget=forms.SelectDateWidget(),initial=datetime.datetime.now)
class Meta:
model = Item
fields = [
'name',
'item_id',
'catego... |
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pickle
import sys
import time
from pystorm.PyDriver import bddriver as bd
import driver_util
from driver_util import s_to_ns, ns_to_s
np.random.seed(0)
#########################################
# user parameters
collec... |
from __future__ import print_function
import os
import unittest
import pytraj as pt
from pytraj.utils import eq, aa_eq
class Testtleap_wrapper(unittest.TestCase):
def test_tleap(self):
from pytraj.testing import amberhome
if amberhome and os.path.exists(amberhome + '/bin/tleap'):
fro... |
# Generated by Django 3.2.9 on 2021-11-02 01:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('watchlist', '0002_auto_20211102_0024'),
]
operations = [
migrations.AlterField(
model_name='platform',
name='about',... |
# Build a function that accepts array. Return a new array with all values except the first, adding 7 to each. Do not alter the original array.
def addSevenToMost(arr):
new_arr = []
for i in range(1, len(arr)):
new_arr.append(arr[i]+7)
return new_arr
# Test Cases
print(addSevenToMost([1,2,3,-4,-5... |
"""Models for users app."""
from tortoise import Tortoise, fields, models
from tortoise.contrib.pydantic import pydantic_model_creator
from .base import AbstractUser
class User(AbstractUser):
"""The User model."""
full_name = fields.CharField(max_length=100, null=True)
phone_number = fields.CharField(m... |
# import the necessary packages
import argparse
import cv2
import os # path
if __name__=="__main__":
# local python directory path
python_dir = os.path.dirname(os.path.abspath(__file__))
# local project directory path
project_dir = os.path.dirname(python_dir)
ap = argparse.ArgumentParser(... |
import errno
import json
import os
import shutil
import unittest
from collections import Counter
from WikiPageInfo.html_parser import WikiParser
from WikiPageInfo.utils import save_wiki_page_info
class RemoveDuplicatesTesting(unittest.TestCase):
def test_html_parser(self):
dom_string_1 = "<html><title>ti... |
# Spiral name
import turtle # Set up turtle graphics
t=turtle.Pen()
turtle.bgcolor("black")
colors=["red", "green", "blue", "yellow"]
#Ask the user his name
your_name=turtle.textinput("Enter your name", "What is your name? ")
#Draw a spiral name on the screen, written 100 times
f... |
# -*- coding: utf-8 -*-
import numpy as np
from matchernet import utils
class Regularization:
def __init__(self):
self.lambd = 0.1
self.d_lambda = 1.0
self.lambda_factor = 1.6
self.lambda_max = 1e10
self.lambda_min = 1e-6
def on_diverge(self):
... |
#!/usr/bin/env python
# coding: utf-8
# ## 1. Load libraries and data: データ/ライブラリの読み込み
# In[31]:
get_ipython().run_line_magic('matplotlib', 'inline')
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
# set pandas options
pd.set... |
# -*- mode: python -*-
block_cipher = None
hiddenimports = [
'bandmat.full',
'pkg_resources.py2_warn',
'sklearn.neighbors.typedefs',
'sklearn.neighbors.quad_tree',
'sklearn.tree',
'sklearn.tree._utils',
'sklearn.utils._cython_blas',
]
kwiiyatta_a = Analysis(['kwiiyatta\\convert_voice.py'... |
import sqlite3
import datetime
import telebot
import logging
import time
class Ternwoyazh:
def Connect(self):
self.connect = sqlite3.connect("DB_All_For_Complect.db")
self.cursor = self.connect.cursor()
def CloseConnect(self):
self.connect.close()
def _DataFrom... |
import numpy as np
from shapely.geometry import Point, MultiPoint
from shapely.geometry.polygon import Polygon
from math import log
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import pickle
import shapely
from queue import Queue
from obstacles import Obstacles
from RRT import RRT
from replan... |
from unittest import TestCase
from timing import Timespan
class TestTimespan(TestCase):
def test_str(self):
span = Timespan()
self.assertEqual(span.__str__(), f"{str(span.start)} - {str(span.end)} ({str(span.duration())})") |
from application import Garage, Reports, Truck, FixedValues, UpdatedValues, Report
fixedValues = FixedValues(10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10)
initialUpdatedValues = UpdatedValues(0, "", 0, "", 0, "", 0, "")
secondUpdatedValues = UpdatedValues(1, "", 2, "tire break", 1, "", 1, "")
garage = Garage(... |
from django.contrib import admin
from django.urls import path, include
from home import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name="saketh"),
path('123', views.home, name="homepage")
]
|
def f1():
x = 10
def f11():
return x
def f12(n):
nonlocal x
x = n
return f11, f12
getx, setx = f1()
print(getx())
setx(18)
print(getx()) |
from __future__ import division
import sys
import math
import random
from coloring_greedy import *
import time
cg = ColoringGreedy(filename=None, lra=True, cells=25)
tstart = time.time()
cg.cg()
tend = time.time()
print "State: " + cg.state
if cg.state == "NOT SOLVED":
print "Remaining nodes: " + str([i for i in cg... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Bauyrzhan Ospan"
__copyright__ = "Copyright 2018, Cleverest Technologies"
__version__ = "1.0.1"
__maintainer__ = "Bauyrzhan Ospan"
__email__ = "bospan@cleverest.tech"
__status__ = "Development"
import gevent.monkey
gevent.monkey.patch_all()
import requests... |
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
import bs4
import requests
import pandas as pd
data = pd.read_csv('Book2.csv')
X = data['key'].values
print(X)
def fun2(para):
res=requests.get(para)
soup=bs4.Beautifu... |
# Copyright 2021 The TensorFlow Authors. 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 applica... |
class Triangle():
def __init__(self,base,height):
self.base = base
self.height = height
def getArea(self):
print(self.base*self.height/2,"is area of triangle")
class Square(Triangle):
def __init__(self,side):
self.side = side
Triangle.__in... |
import random
import string
words=["mali","yaren","merve","burak","dilan","goken","ut ku","ut-ku"]
def get_valid_word():
word = random.choice(words).upper()
while ' ' in word or '-' in word:
word = random.choice(words).upper()
return word
def hangman():
lives=6
word = get_valid_word()
... |
from Utils import plotData
from GaussianBoundary import *
import matplotlib.pyplot as plt
import numpy as np
import math
from conicDistances import getEDistance,car2pol
yaxis = np.linspace(-10,10,50)
xaxis = np.linspace(-10,10,50)
x,y = np.meshgrid(xaxis,yaxis)
@np.vectorize
def func(m,n):
return getEDistance([10... |
#!/usr/bin/env python2
# Siggi - Feature Hashing for Labeled Graphs
# (c) 2015, 2017 Konrad Rieck (konrad@mlsec.org)
import argparse
from multiprocessing import Pool
import siggi
import utils
# Parse arguments
parser = argparse.ArgumentParser(
description='Siggi - Feature Hashing for Labeled Graphs.',
format... |
import math
from enum import Enum
import cv2
import numpy
from sorcery import assigned_names
def rotate_image(image, angle, center=None, scale=1.0):
"""
:param image:
:type image:
:param angle:
:type angle:
:param center:
:type center:
:param scale:
:type scale:
:return:
... |
import os
import sys
from types import ModuleType
import invoke as inv
from . import __version__
from . import tasks
OPTIONS = """
bash Start a bash shell
tasks List all available tasks
run Execute the "run" task or start a bash shell"""
MESSAGE = """Usage: jarbas-tasks COMMAND
Execute a jarbas stand... |
#!/usr/bin/python
import sqlite3
import insert
conn = sqlite3.connect('tables.db')
cursor = conn.cursor()
# 创建表teacher、student、course、sc、mc
cursor.execute('create table teacher(Tno char(10) primary key, Tpassword char(20), Tname char(20), Tsex char(2), Tbrith date, Tdept char(20), Ttele char(11), Temail char(... |
###--------------------------------------------------------------------------###
# Author: Robert Ranney
# File: reconstruction_error_plot.py
# Description: plots reconstruction error for nmf on post data frame, this
# should probably not be run on my machine since it will take
# forever
# Us... |
import os
from sqlalchemy_utils import database_exists, create_database
from django.core.management.base import BaseCommand
from dotenv import load_dotenv
load_dotenv()
class Command(BaseCommand):
help = 'Create DB'
def handle(self, *args, **options):
username = os.getenv("username")
passwor... |
import heapq
import sys
n, m = map(int, sys.stdin.readline().split())
cnt = [0] * (n + 1)
info = [[] for _ in range(n + 1)]
result = []
for _ in range(m):
n1, n2 = map(int, sys.stdin.readline().split())
info[n1].append(n2)
cnt[n2] += 1
h = []
for i in range(1, len(cnt)):
if cnt[i] == 0:
h... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible
from spirit.managers.topic_notifications import TopicNotificationQuerySet... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/6/11 6:09 下午
# @Author : Johny Zheng
# @Site :
# @File : config.py
# @Software: PyCharm
# Running based on python3.6.2 environment
import logging
import configparser
import sys
import json
logging.basicConfig(level=logging.INFO)
class GlobalV... |
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append('/Users/miller/Documents/workspace/caffe/python')
import caffe
import gflags
from conf import *
from processor import *
gflags.DEFINE_string('db_path', '', 'db path')
gflags.DEFINE_string('alg_path', '', 'server.cfg')
gfl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.MerchantModel import MerchantModel
from alipay.aop.api.domain.MerchantModel import MerchantModel
class AlipayCommerceIotMdeviceprodQueryResponse(AlipayResponse):
... |
from cmd import Cmd
class HelloWorld(Cmd):
"""Simple command processor example."""
def do_greet(self, args):
"""Says hello. If you provide a name, it will greet you with it."""
if len(args) == 0:
name = 'Stranger'
else:
name = args
print "Hello, %s" ... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
def exception(message, LineProgram=None, place=None, exitProgram = True):
"""
Printeja una excepció i fa exit si cal
:param message: El missatge a printejar
:param LineProgram: La línia on el programa ha fallat (opcional)
:param place: El lloc/fitxer on... |
import nltk
from nltk.corpus import treebank
import os
import pickle
#this sets the default encoding to utf-8. the train_set contains characters which are not ASCII. So setting the default encoding to "utf-8"
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
#populate the train_Sent list with all the rows in tr... |
from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import current_user, login_required
from . import db
from .models import Setting
main = Blueprint('main', __name__)
@main.route('/')
def index():
if current_user.is_authenticated:
return redirect(url_for('mai... |
import numpy as np
from PIL import Image
from os import listdir
from os.path import isfile, join, exists
print("will convert image to array/matrix")
def load_data(name_of_data):
directory = 'images/' + name_of_data
if exists(directory):
onlyfiles = [f for f in listdir(directory) if isfile(join(dir... |
import random
from scipy.sparse import csr_matrix, bmat
import numpy as np
import _pickle as pkl
import util
class Cluster:
def __init__(self, initial_centroid: np.ndarray):
self.centroid = initial_centroid
self.members = set()
def __str__(self):
return "Centroid: %s\nMembers: %s" % (... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/tf/user/ros/poppy_ws/src/poppy_ros/poppy_torso_control/msg/Trajectory.msg"
services_str = "/tf/user/ros/poppy_ws/src/poppy_ros/poppy_torso_control/srv/PlanMovement.srv;/tf/user/ros/poppy_ws/src/poppy_ros/poppy_torso_control/srv/GetEndEffectorPos.srv;... |
import subprocess
from pyngrok import ngrok
def clone_github_private_repo(email: str, name: str) -> None:
private_repo_commands = f'sh scripts/private_repo_clone.sh {email} {name}'
subprocess.call(private_repo_commands.split())
def connect_ngork():
url = ngrok.connect(port=9000)
return url
if __n... |
import pandas as pd
import numpy as np
import csv
import random
import math
import time
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScale... |
__author__ = 'jidziak'
from html.parser import HTMLParser
from urllib.request import urlopen
from urllib import parse
# We are going to create a class called LinkParser that inherits some
# methods from HTMLParser which is why it is passed into the definition
class LinkParser(HTMLParser):
# This is a function th... |
#!/usr/bin/env python
import ROOT
ROOT.gROOT.SetBatch(True)
ROOT.PyConfig.IgnoreCommandLineOptions = True
import sys
import os
path = sys.argv[-1]
TreeName="sf/t"
filelist=['evVarFriend_DYJetsToLL_M50_HT100to200_ext.root','evVarFriend_QCD_HT300to500.root','evVarFriend_TBar_tWch_noFullyHad_ext.root',
'evVarFr... |
import math
import timeit
import random
import sympy
import warnings
from random import randint, seed
import sys
from ecpy.curves import Curve, Point
from Crypto.Hash import SHA3_256,SHA256,HMAC
import requests
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Util.Padding import pad
from Crypto.Util.... |
from django.shortcuts import render
from rest_framework import generics
from bookreview.serializers import AuthorSerializer
from bookreview.models import Author
def index_view(request):
"""
Ensure the user can only see their own profiles.
"""
response = {
'authors': Author.objects.all(),
... |
import matplotlib.pyplot as plt
import copy
import graphClass as gc
import numpy as np
from fractions import Fraction
# INPUT HERE
# what level affine carpet would you like:
precarpet_level = 2
# how large would you like the center hole to be:
sideOfCenterHole = 1/2
# the above two are the only parameters, since sid... |
days_per_year = 365
hours_per_day = 24
minutes_per_hour = 60
minutes_per_year = days_per_year * hours_per_day * minutes_per_hour
print(minutes_per_year)
|
import numpy as np
# Creating a rank 1 Array
arr = np.array([1, 2, 3])
print("Array with Rank 1: ", arr)
arr_1 = np.array([])
print(arr_1)
# Creating a rank 2 Array
list_1 = [1, 2, 3]
print(list_1)
list_2 = [4, 5,6]
print(list_2)
arr = np.array([list_1, list_2])
print("Array with Rank 2: \n", arr)
# Creating an arr... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.display_mentee, name='mentee')
]
|
# Kivy libs import
# Python libs import
# Personal libs import
#Class of a task
class CodeTyp:
# columns used in the csv, in the right order
_dtb_columns = ["codetype_id", "codetype_name"]
# name of the dtb table for this object
_dtb_table = "codetyp"
# Object(s) which must be inclu... |
"""
This type stub file was generated by pyright.
"""
import vtkmodules.vtkCommonCore as __vtkmodules_vtkCommonCore
class vtkCellTypes(__vtkmodules_vtkCommonCore.vtkObject):
"""
vtkCellTypes - object provides direct access to cells in vtkCellArray
and type information
Superclass: vtkObject
... |
"""tour selection field
Revision ID: b7c9c8536ad6
Revises: 93dc6938b735
Create Date: 2020-09-25 21:49:39.947649
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b7c9c8536ad6'
down_revision = '93dc6938b735'
branch_labels = None
depends_on = None
def upgrade():... |
print (" We gaan voor 5 dagen insecten vangen en aan het eind optellen")
#De waarden hieronder worden dadelijk overschreven.
dag = 1
insect = 0
#Zolang het 5 of onder de 5 dagen zit gaat hij door
while dag <= 5 :
insect += int(input("Hoeveel insecten heb je gevangen vandaag? "))
#De insecten per dag worden bij elka... |
# 15596: 정수 N개의 합
# https://www.acmicpc.net/problem/15596
def solve(a: list) -> int:
return sum(a)
|
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
n = int(input())
words = []
for _ in range(n):
w = input().strip()
if w in words:
print('No')
sys.exit(0)
if len(words) == 0:
words.append(w)
continue
if words[-1][-1] != w[0]:
print('No')
... |
#!/usr/bin/python3
""" Loads, adds, and saves arguments to a Python list stored in JSON. """
import json
import sys
load = __import__('8-load_from_json_file').load_from_json_file
save = __import__('7-save_to_json_file').save_to_json_file
args = sys.argv[1:]
with open("add_item.json", "a") as f:
try:
l = loa... |
# coding: utf8
import cache_file
def translation_search_in_cache(txt, end_lang):
res = {
'result': False,
'text': ''
}
try:
res['text'] = cache_file.translations[end_lang][txt]
res['result'] = True
print('used translation cache')
except Exception:
pass... |
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.contrib.auth.models import UserManager as DjangoUserManager
from django.contrib.postgres.fields import CICharField
from django.core import validators
from django.db import models
from django.utils.tran... |
# Generated by Django 2.2.5 on 2019-09-14 21:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0005_brand_logo'),
]
operations = [
migrations.AddField(
model_name='category',
name='icon',
... |
#!/usr/bin/env python
"""
Module to check if the DB works
===============================
Runs multiple checks to see if the database was correctly setup.
"""
import argparse
import logging
from orion.core.cli.checks.creation import CreationStage
from orion.core.cli.checks.operations import OperationsStage
from orio... |
def store_file(file_name):
"""
This is a function to retrieve information from the file provided by the user.
"""
lst = []
# Read through the file line by line
with open(file_name, 'r') as f:
for line in f:
# If it starts with a % or if it's an empty line (weird formatti... |
import pickle
import dlib
import cv2
test_path = "D:\\hog_object_detect\\ku.jpg"
img = cv2.imread(test_path)
detector = dlib.simple_object_detector("detector.svm")
boxes = detector(img)
box= boxes[0]
(x,y,xb,yb) = [box.left(),box.top(),box.right(),box.bottom()]
cv_image = cv2.imread("D:\\hog_object_detect\\ku.jpg")
... |
class Stack:
"""First In First Out (FIFO) data structure"""
def __init__(self):
self.__holder = []
def is_empty(self):
return self.__holder == []
def push(self, element):
self.__holder.append(element)
return True
def pop(self):
if not self.is... |
1. Let _buffer_ be ? ValidateSharedIntegerTypedArray(_typedArray_).
1. Let _i_ be ? ValidateAtomicAccess(_typedArray_, _index_).
1. Let _arrayTypeName_ be _typedArray_.[[TypedArrayName]].
1. If _typedArray_.[[ContentType]] is ~BigInt~, then
1. Let _expected_ be ? ToBigInt(_expe... |
from math import acos, degrees
while True:
a, b, c = map(int, input().split())
if a == b == c == 0:
break
tocheck = ((a ** 2) + (b ** 2) == (c ** 2) or
(b ** 2) + (c ** 2) == (a ** 2) or
(c ** 2) + (a ** 2) == (b ** 2))
print('right' if tocheck else 'wrong') |
import json
import logging
import requests
from urlparse import urlparse, parse_qs
from django.conf import settings
from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
from open_fa... |
from rest_framework import serializers
from api.models import Mood
from .models import Profile
class UserSerializer(serializers.ModelSerializer):
moods = serializers.PrimaryKeyRelatedField(many=True, queryset=Mood.objects.all())
class Meta:
model = Profile
fields = ['id', 'username', 'moods', ... |
#!/usr/bin/env python3
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
import argparse
import ssl
import atexit
import time
import logging
class vm_module:
# loggerフォーマットメソッド
def logger_format():
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
... |
from conans import ConanFile, CMake, tools
class taskflowConan(ConanFile):
name = "taskflow"
version = "2.2.0"
license = "MIT"
author = "Edgar Edgar@AnotherFoxGuy.com"
url = "https://github.com/AnotherFoxGuy/conan-taskflow"
description = "A fast C++ header-only library to help you quickly writ... |
#!~/anaconda3/bin/python
#RPG starter project
def showInstructions():
# print a main menu and Commands
print('''
RPG Game
========
Get to the garden with a key and a potion.
Avoid the monsters!
Commands:
go [direction]
get [item]
''')
def showStatus():
#print the player's current showStatus
... |
# -*- coding: utf-8 -*-
from SOAPpy import SOAPProxy
url = 'http://services.xmethods.net:80/soap/servlet/rpcrouter'
namespace = 'urn:xmethods-Temperature'
server = SOAPProxy(url, namespace)
server.getTemp('27502')
|
from django.shortcuts import render
from codetests.models import CodeTests,CodeQnsList
from models import TestAttempt,Answer,UserLock,UserLockDelete
import os,time
from codejam import settings
import time,datetime
from django.utils.timezone import is_naive
from django.utils.cache import add_never_cache_headers
from dja... |
#! /usr/bin/env/python
import time as t1
class Log_Parsing:
log_file = "" # input file
processed_log_file = "" # intermediate after pre-processing input
final_file = "" # final result file
def get_files(self):
"""Asks user to input a raw .tsv log file and pre-processes it to store in an intermediate .c... |
from .forms import UserCreationFormWithEmail, ProfileForm, EmailForm
from django.views.generic import CreateView
from django.views.generic.edit import UpdateView
from django.views.generic.base import TemplateView
from django.urls import reverse_lazy
from django import forms
from .models import Profile
from core.models ... |
'''
2019 인제대학교 영재교육원 정보과학반 사사과정
Excel 파일 입출력 및 원하는 값에 따른 출력
작성자 : 2019 정보과학반 조교 당현아
'''
from openpyxl import load_workbook
import pandas as pd
find_column = 0
# Output all contents of file.
excel_file = pd.read_excel('test.xlsx', sheet_name='Sheet1')
print(excel_file)
load_wb = load_workbook('test.xlsx'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.