text stringlengths 8 6.05M |
|---|
"""
Django settings for source project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... |
MODULE_NAME = 'manual'
MODULE_FUNCTIONS = { }
# this is empty, it only needs to be here so you can enable it, the contractor module dosen't actually send anything to subcontractor
|
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = 'benchmarks',
ext_modules = cythonize("*.py", language_level=3, annotate=True),
)
|
'''
author: juzicode
address: www.juzicode.com
公众号: 桔子code/juzicode
date: 2020.7.15
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: 桔子code/juzicode\n')
import os,time,sys
import subprocess
print('执行 dir')
ret = subprocess.run('dir', shell=True,capture_output=True)
print('args:',ret.args)
prin... |
"""
GUI module for Tic Tac Toe game
"""
import pygame
import math
from typing import Callable, Tuple, Optional
from dataclasses import dataclass, field
from pygame.font import Font
from .ttt_board import *
# Init pygame
pygame.init()
# GUI constants
GUI_WIDTH = 400
GUI_HEIGHT = 500
BAR_WIDTH = 5
# Colour constant... |
import gzip
import json
import mysql.connector
import re
import time
def current_milli_time():
return round(time.time() * 1000)
with open('../config-server.mjs', 'r') as f:
j = f.read()
# remove comments and ESM stuff
j = j.replace('export default ', '')
j = re.sub(r"(// [^\n]+)", '', j)
conf... |
print("This is the goodbye file")
print("change for committing both files")
|
{
PDBConst.Name: "mapbillfinanceevent",
PDBConst.Columns: [
{
PDBConst.Name: "Bill",
PDBConst.Attributes: ["int", "not null"]
},
{
PDBConst.Name: "Event",
PDBConst.Attributes: ["int", "not null"]
}],
PDBConst.PrimaryKey: ["Bill", "Event"]
}
|
###########################
# 6.0002 Problem Set 1a: Space Cows
# Name:
# Collaborators:
# Time:
from ps1_partition import get_partitions
import time
import copy
#================================
# Part A: Transporting Space Cows
#================================
# Problem 1
def load_cows(filename)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 00:09:41 2020
@author: damengjin
"""
# Load Model Using Pickle
import pandas as pd
import pickle
#load the dataset:
df_new = pd.read_csv('Documents/MSBA/CS5224/PSP Project/df_new.csv', index_col=None)
# load the model from disk
SVDpp_val = pick... |
from PagSeguroLib.singleton import Singleton
from PagSeguroLib.domain.PagSeguroAccountCredentials import PagSeguroAccountCredentials
class PagSeguroConfig(Singleton):
config = None
data = {}
@classmethod
def init(cls, data):
if cls.config == None:
cls.config = PagSeguroCon... |
from orun.test import TestCase
from orun.apps import apps
from orun.db import connection
class FixturesTest(TestCase):
fixtures = (
(
'admin_fixtures', (
)
),
(
'admin', (
'templates.xml',
),
),
)
|
#!/usr/bin/python
import time, sys, os
import numpy as np
import scipy.io as sio
import NeuralNetwork
from batchCD1 import batchCD1
## We want a Restricted Boltzmann Machine (RBM) which is a type of
## neural network. Specifically, we want the 4-layer model described
## in (Hinton, Osindero, Teh, 2006).
nn = Neura... |
from flask import Flask
import os
app = Flask(__name__)
@app.route("/")
def hello():
print ("==== root ====")
return "Hello World!"
if __name__ == "__main__":
HOST = os.environ.get('SERVER_HOST', 'localhost')
try:
PORT = int(os.environ.get('SERVER_PORT', '5555'))
except Valu... |
from onegov.core.security import Private
from onegov.org import OrgApp, _
from onegov.org.forms import ResourceRecipientForm
from onegov.org.layout import ResourceRecipientsLayout
from onegov.org.layout import ResourceRecipientsFormLayout
from onegov.org.models import ResourceRecipient, ResourceRecipientCollection
from... |
import re
import os
def main():
data = {
'Device Settings': {
'RAID': None,
'Volume Size': None,
'NIC Virtualization Mode': {}
},
'iDRAC Settings': {
'Enable IPv4': None,
'Enable DHCP': None,
'Static IP Address': None,... |
#
# Script to download a sample of DR10
#
import fitsio
import numpy as np
import seaborn as sns
from redshift_utils import load_sdss_fluxes_clean_split
import urllib, os, sys
def download_spec_file(plate, mjd, fiberid, redownload=False):
""" grabs the spec file given plate, mjd and fiber id """
spec_url_templ... |
{
W3Const.w3UIBody: {
W3Const.w3PropType: W3Const.w3TypePanel,
W3Const.w3PropSubUI: [
"uidHeader",
"uidMain",
"uidFooter"
],
W3Const.w3PropDefaultPage: "uidPageLogin",
W3Const.w3PropDefaultErrorPage: "uidPageError",
W3Const.w3PropDe... |
#!/usr/bin/python
import sublime
import sublime_plugin
def openNewDocAndFill(context):
pass
def getLineText(view):
regionStr = ""
sels = view.sel()
for a in sels:
line = view.line(a)
regionStr += view.substr(line)
return regionStr
def getLineRegion(view):
sels = view.sel()
for a in... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
Functions for enriching timeseries data.
Includes transformations which operate in the time domain, and ones which
operate in the frequency domain. Organization of this module and basic set
of functionality are inspired by Wen et al.'s review, "Timeseries data
Augm... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 20:24:23 2018
@author: shams
"""
# -*- coding: utf-8 -*-
"""
this file is for local evaluation of the models trained on HPC
"""
# importing libraries
import pandas as pd
import numpy as np
import numpy as np
import pandas as pd
from keras.preprocessing import sequenc... |
import math
import torch
import torch.nn as nn
class PositionEncoding(nn.Module):
def __init__(self, n_filters=128, max_len=500):
super(PositionEncoding, self).__init__()
pe = torch.zeros(max_len, n_filters)
position = torch.arange(0, max_len).float().unsqueeze(1)
div_term = t... |
##
#
#
#
# sayheya@qq.com
# 2019-05-29
BLOOM_REDIS_URI = 'redis://10.0.0.48:6379/6'
BIT_SIZE = 1 << 31 # size
BLOCK_NUM = 1 # redis block num to store
BLOOM_KEY_NAME = 'bloom_for_hanzo_%(no)s' # redis bloom key name
TEST_BLOOM_KEY_NAME = 'test_bloom_for_hanzo_%(no)s' # redis bloom key name
|
from django.shortcuts import render
from django.shortcuts import HttpResponse
# Create your views here.
from django.template import loader
from django.urls import NoReverseMatch, reverse
from django.views.decorators.cache import never_cache
from django.shortcuts import HttpResponseRedirect, render_to_response
from dj... |
"""
作者 xupeng
邮箱 874582705@qq.com / 15601598009@163.com
github主页 https://github.com/xupeng1206
"""
import os
import shutil
os.system('python setup.py bdist_wheel')
shutil.rmtree('./build/', ignore_errors=True)
shutil.rmtree('./Flanger.egg-info/', ignore_errors=True)
os.system('pip install -U dist/... |
"""JupyterLab Metadata Service Server"""
import os
def start():
"""Start JupyterLab Metadata Service Server Start
Returns:
dict -- A dictionary with the node command that will start the
Metadata Service Server
"""
path = os.path.dirname(os.path.abspath(__file__))
return ... |
import os
import cv2
count = 0
for file in os.scandir('./project/team/filtered_img'):
print(file)
path = os.path.abspath(file)
jpg = cv2.imread(path)
jpg = cv2.resize(jpg, (1280,720))
# cv2.imshow('jpg', jpg)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
cv2.imwrite('./project/team... |
#! /usr/bin/python3
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
imp... |
import os
from flask import (
Flask, flash, render_template,
redirect, request, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
if os.path.exists("env.py"):
import env
app = Flask(__name__)
ap... |
#####################################################################################
#
# software: Python 2.7
# file: constellation2x2.py, meaning that digital step is 2
# author: Aleksandar Vukovic
# mail: va183034m@student.etf.bg.ac.rs
#
####################################################################... |
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db import models
from django.template.defaultfilters import truncatewords_html
from django.utils.safestring import mark_safe
fr... |
from django.conf.urls import re_path
from djoser import views as djoser_views
from rest_framework_jwt import views as jwt_views
from user import views
urlpatterns = [
# Views are defined in Djoser, but we're assigning custom paths.
re_path(r'^view/$', djoser_views.UserView.as_view(), name='user-view'),
re_p... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 15:40:59 2021
@author: Gustavo
@mail: gustavogodoy85@gmail.com
"""
# =============================================================================
# costo_camion.py enumerate
# =============================================================================
import csv
... |
__all__ = [
"__version__",
"Endpoint", "Entry", "Fetcher",
"Filter", "RequiresPythonFilter", "VersionFilter",
"FlatHTMLRepository", "LocalDirectoryRepository", "SimpleRepository",
"guess_encoding", "match_egg_info_version",
]
from .endpoints import Endpoint
from .entries import Entry
from .fetchers... |
import uuid, subprocess, os, shutil, json, requests, time
from datetime import datetime
import portality.models as models
from portality.core import app
from xml.etree import ElementTree as ET
from lxml import etree
class callers(object):
def __init__(self,scraperdir=False,storagedir=False,speciesdi... |
import redis
class Base(object):
def __init__(self):
self.r = redis.StrictRedis(host='localhost', port=6379, db=0)
class StringTest(object):
def __init__(self):
# redis.Redis()兼容老版本,redis.StrictRedis()不考虑兼容性
# self.r = redis.Redis(host='localhost', port=6379, db=0)
self.r = r... |
from operator import attrgetter
from six.moves import map
from portia_api.jsonapi.serializers import JsonApiSerializer
from portia_orm.base import AUTO_PK
from portia_orm.exceptions import ProtectedError
from portia_orm.models import (Project, Schema, Field, Extractor, Spider,
Sample, I... |
from game_engine.table import Table
import pytest
# Tests that table is made with two empty seats
# Also test that blind init
def test_init_two_users():
# Blinds are set to 10 and 20
table = Table(2, (10, 20))
assert table._small_blind == 10
assert table._big_blind == 20
assert len(table._seats) ... |
#!/usr/bin/env python
#!-*-coding:utf-8 -*-
# Time :2020/5/14 13:00
# Author : zhoudong
# File : g_tool.py
"""
该文件放一些工具函数
"""
import numpy as np
import itertools
myfloat = np.float32
# 多元高斯组件,每个目标保存,方便计算
class GmphdComponent:
def __init__(self, weight, loc, cov):
"""
:param weight: 权值
... |
"""
Given a 32-bit signed integer, reverse digits of an integer.
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
string = str(x)
if x >= 0:
rstring = string[::-1]
else:
rstring = '-' + string[:0:-1]
... |
from StringIO import StringIO
from textwrap import dedent
from twitter.checkstyle.iterators import diff_lines
class Blob(object):
def __init__(self, blob):
self._blob = blob
self.hexsha = 'ignore me'
@property
def data_stream(self):
return StringIO(self._blob)
def make_blob(stmt):
return Blob(... |
from django.contrib.auth import get_user_model
from rest_framework import serializers
from webapp.models import Article, Tag
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = '__all__'
class UserSerializer(serializers.ModelSerializer):
url = serializers.Hyper... |
import time
def init():
""" initial state """
if not exists("1450617504600.png"):
exit()
click("1450617512741.png")
wait("1450617981095.png")
click("1450617981095.png")
def backHome():
""" back to city select activity """
while not exists("1450618092142.png"):
click("145061... |
import os
import sys
import warnings
# _ROOT = os.path.abspath(os.path.dirname(__file__))
#
#
# def get_data_path(path):
# return os.path.join(_ROOT, 'data', path)
# Setup warnings to simpler one line warning
def warning_on_one_line(message, category, filename, lineno, file=None, line=None):
filename = ... |
#from uccal import Modules
from uccal import Students
#print Modules.addModule("big big big cal", "my big calendar")
#Modules.deleteModule("jeromakay.com_s4gob184n9742hvbvbo4d32t7g@group.calendar.google.com")
#Modules.updateModule("jeromakay.com_csjh4188v45j5pclojlt6784ck@group.calendar.google.com", "even way huge big... |
from flask_wtf import FlaskForm
from wtforms import (
BooleanField,
DateTimeField,
IntegerField,
PasswordField,
RadioField,
SelectField,
StringField,
TextAreaField,
ValidationError,
SubmitField
)
from wtforms.validators import InputRequired, Email, Length, Optional
class Backup... |
import requests
from bs4 import BeautifulSoup as bs
import re
from urllib.request import urlopen
for pages in range(1,10):
url = "https://shop.adidas.co.kr/PF020201.action?command=LIST&ALL=ALL&S_CTGR_CD=01001001&CONR_CD=10&S_ORDER_BY=1&S_PAGECNT=100&PAGE_CUR={}&S_SIZE=&S_TECH=&S_COLOR=&S_COLOR2=&CATG_CHK=&CATG... |
#欧拉函数的定义:小于或等于n的正整数中与n互质的个数
def Oula():
n=int(input("请输入一个数:"))
count=0
for b in range(1,n+1):
if(n%b==0):
continue
else:
count=count+1
print("求得欧拉结果φ(n)=",count)
Oula()
|
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User as DjangoUser
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils.translation import ugettext as _
fr... |
def prime_digit(number): #defines the function with a parameter of a number
prime_numbers = []
if isinstance (number, int): #a condition where the value being input is an integer
if number>1: #this block sets a condition that if a number is greater than 1 for numbers in the range which begins with 2 it will b... |
# Generated by Django 2.1.2 on 2019-02-02 16:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('review', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='review',
name='user_name',
),... |
import re
gpid = re.compile('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}')
idfa = re.compile('[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}')
ifile = open('tpr_inactive_maids.txt','r')
tenMB = 10*1000*1000
limit = int(tenMB/37) - 100
gpidindex = 0
idfaindex = 0
gpidcount = 0
idfacount ... |
import unittest
def zeroMatrix(M):
if not M or not M[0]:
return M
m, n = len(M), len(M[0])
zeroCol = [False] * n
zeroRow = [False] * m
for r in range(m):
for c in range(n):
if M[r][c] == 0:
zeroRow[r] = zeroCol[c] = True
for r in range(m):
... |
from myhdl import *
class Add_shift_top(object):
def __init__(self):
DATA_WIDTH = 65536
ACTIVE_LOW = bool(0)
self.even_odd = Signal(bool(0))
self.fwd_inv = Signal(bool(0))
self.din_sam = Signal(intbv(0, min = -DATA_WIDTH, max = DATA_WIDTH))
self.dout_sam = Signal(intbv(0, min = -DATA_WIDTH, max = DATA_W... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 阶乘
def factorial(num):
s = 1
if num == 0:
return s
else:
nums = [i + 1 for i in range(num)]
for i in nums:
s *= i
return s
# 杨辉三角队列
def triangles(rows):
n = 0
while n < rows:
# l = []
# f... |
import os, sys, time
# force run on CPU?
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
caffe_root = os.path.dirname(os.path.abspath(__file__))+'/../../'
sys.path.insert(0, caffe_root+'python')
#os.environ['GLOG_minloglevel'] = '2'
import numpy as np
np.set_printoptions(linewidth=200)
import cv2
import caffe
if not os.p... |
import cv2
import numpy as np
img = cv2.imread("1.jpg") # Reading image.
shape = img.shape # Gets the dimensions of the image.
print('Shape =', shape)
cv2.line(img, (50, 50), (430, 802), (255, 0, 0), thickness=2)
# Draws a line on 1st arg, from 1st point (2nd arg) to 2nd point # (3rd arg) in the color of ... |
"""
Project version mutations
"""
from dataclasses import dataclass
from typing import Optional
from typeguard import typechecked
from ...helpers import Compatible, format_result
from .queries import (GQL_UPDATE_PROPERTIES_IN_PROJECT_VERSION)
@dataclass
class MutationsProjectVersion:
"""
Set of ProjectVers... |
import os
reclen = 20
f = open("cities","r+b")
size = os.path.getsize("cities")
print("Size Of The File Is : ",size)
record = int(size/reclen)
print("No Of Records Are : ",record)
city = input("Enter City Name : ")
city = city.encode()
newcity = input("Enter Renamed Name : ")
newcity = newcity + (reclen-len(newcity... |
class Singleton(object):
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
singleton = Singleton()
another_singleton = Singleton()
print singleton is another_singleton
singleton.only_one_var = "I'm only one... |
from django.db import models
#from filefieldtools import upload_to
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
pdf = models.FileField(upload_to='books/pdfs/')
cover = models.ImageField(upload_to='books/covers/', null=True, blank=True)
... |
import pandas as pd
def preprocess():
"""#######( read )########"""
raw1 = pd.read_excel("./static/Classification.xlsx")
print(len(raw1))
raw1.head()
print(raw1.Classification.value_counts())
"""#########( clean )##########"""
raw1_p = ""
for i in raw1.LONGDESC:
raw1_p = raw1_p... |
import threading,time
class FileWriter(threading.Thread):
def __init__(self,fileName, num):
threading.Thread.__init__(self,name="fileWriter"+bytes(num))
self.__fileName__=fileName;
self.__num__=num
def run(self):
for i in range(10):
output = open(self.__... |
'''
author: juzicode
address: www.juzicode.com
公众号: juzicode/桔子code
date: 2020.6.11
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: juzicode/桔子code\n')
print('格式化符号对齐控制')
a = 100
print('整数100 16进制左侧补0显示:a=%08x'%(a))
b = 3.1415925
print('浮点数3.1415925 保留小数点后2位显示:b=%.2f'%(b))
|
# removes all predicted Terminators with bitscores higher than 30
# writes file of predicted terminators of certain length (default 100)
# writes files for embedding the terminator sequences in (500 before and after predicted terminator)
import argparse
import os.path
import math
#####################################... |
import unittest
from mlpnn.Structure.Neuron import Neuron
from mlpnn.Structure.Synapse import Synapse
class LayerTest(unittest.TestCase):
def test_synapse_creation(self):
neuron1 = Neuron(1)
neuron2 = Neuron(2)
synapse = Synapse(neuron1, neuron2, initial_weight=0.5)
self.assertE... |
print('Test Jenkins of Integration')
print('Secondary Modification Test')
print('xintianjia')
print('gaizhenghaode')
print('自动构建定时任务') |
from __future__ import unicode_literals
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import model_selection, naive_bayes, svm
from sklearn.metrics import accuracy_score
from os.path import dirname, abspath ,join
import matplotlib.pyplot as plt
import p... |
"""Script for identifying wavelength regions containing interstellar features"""
import apoNN.src.data as apoData
import apoNN.src.utils as apoUtils
import apoNN.src.vectors as vectors
import apoNN.src.fitters as fitters
import apoNN.src.evaluators as evaluators
import apoNN.src.occam as occam_utils
import numpy as np... |
def merge_sort(arr):
if len(arr) <= 1:
return arr
midpoint = int(len(arr) / 2)
left = merge_sort(arr[:midpoint])
right = merge_sort(arr[midpoint:])
return merge(left, right)
def merge(left, right):
i = 0
j = 0
new_array = []
while i < len(left) and j < len(rig... |
#!/usr/bin/env python3
##
## EPITECH PROJECT, 2020
## 107transfer
## File description:
## maths python
##
import sys
import error
import function
def main():
if "-h" in sys.argv or "--help" in sys.argv:
error.usage()
return 0
error.all_error(len(sys.argv))
num = function.func_in_tab(1)
... |
# 실습
# Conv1d로 코딩
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape, y_train.shape) # (60000, 28, 28), (60000,) <- 흑백
print(x_test.shape, y_test.shape) # (10000, 28, 28), (10000,)
x_tr... |
#!/usr/bin/env python
# coding: utf-8
### Extraction of topics from Wikipedia pages ###
import sys
import os
import numpy as np
import networkx as nx
import requests
import pandas as pd
import csv
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import time
import community
from fonctions import *
### Par... |
import pytest
import transaction
from datetime import datetime, timedelta, date
from webob.multidict import MultiDict
from onegov.activity import ActivityCollection
from onegov.activity import AttendeeCollection
from onegov.activity import BookingCollection
from onegov.activity import InvoiceCollection
from onegov.a... |
from fact import fact
fact(6)
print(fact) |
from django.test import TestCase
from posts.models import Group
class GroupModelTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
Group.objects.create(
title='Название сообщества',
slug='test-group',
description='Описание'
)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
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... |
import arxiv
import json
result = arxiv.query(query="cs", max_chunk_results=10, iterative=True)
print('[')
for paper in result():
# json_str = json.dumps(paper, indent=2)
json_str = json.dumps(paper)
print(json_str.replace('true', 'True').replace('null', 'None'))
print(', ')
print(']')
|
import zmq
from random import random
from time import time, sleep
def get_random(lo=0, hi=1):
start = time()
sleep(lo + random() * (hi - lo))
return time() - start
ctx = zmq.Context.instance()
sock = ctx.socket(zmq.REP)
sock.bind('ipc:///tmp/random')
while True:
lo, hi = sock.recv_json()
sock.send... |
def decorated_patterns(wrapping_functions, patterns):
"""
Used to wrap entire URL patterns in a decorator
adapted from: https://gist.github.com/1378003
"""
if not isinstance(wrapping_functions, (list, tuple)):
wrapping_functions = (wrapping_functions, )
return [_wrap_resolver(wrapping_... |
#!/usr/bin/python
# coding=utf-8
""" """
import argparse
import os, sys
from .pipeline_tools import make_perfect_path
def create_VOC_dirs(dir_name):
dir_name_ = make_perfect_path(dir_name)
# print(dir_name_)
# print(type(dir_name_))
if not os.path.exists(dir_name_):
os.system("mkdir " + dir_name_)
os.system(... |
from enum import Enum
from pydantic import BaseModel
from typing import List, Optional
class ErrorMessage(BaseModel):
detail: str
class MilkEnum(str, Enum):
none = 'none'
skim = 'skim'
semi = 'semi'
whole = 'whole'
class Milk(BaseModel):
id: int
name: MilkEnum
class Config:
... |
"""
File: algorithms.py
Algorithms configured for profiling.
"""
def selectionSort(lyst, profiler):
i = 0
while i < len(lyst) - 1:
minIndex = i
j = i + 1
while j < len(lyst) - 1:
profiler.comparison()
if lyst[j] < lyst[minIndex]:
minIndex = j
j += 1
if i != minIndex:
swap(lyst, minIndex, i, p... |
from inspect import getmembers
from wtforms.validators import DataRequired
from onegov.form.fields import UploadField
from onegov.form.validators import StrictOptional
from typing import overload, Any, Literal, TypeVar, TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Collection, Iterator
from on... |
r"""
Logging objects (:mod: `qiita_db.logger`)
====================================
..currentmodule:: qiita_db.logger
This module provides objects for recording log information
Classes
-------
..autosummary::
:toctree: generated/
LogEntry
"""
# -------------------------------------------------------------... |
# Apprentissage de l'objet
#Une liste est un objet
l = [1,2,3,4]
print(l)
# on peut appliquer des méthode sur l'objet
l.append(1)
print(l)
print(type(l)) |
import os
import cv2 as cv
import random
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
shuffle_data = True
PATH_TO_FILES = '/home/young-joo/Desktop/Dataset/'
JUMPSUIT = PATH_TO_FILES + 'bbox_Jumpsuit.txt'
DRESS = PATH_TO_FILES + 'bbox_Dress.txt'
#Save into a list
def return_lists(JU... |
def f (x):
y = x - (x ** 2) * 0.01
return y
a, b = map (int, input ().split ())
e = float (input ())
if f (a) == 0: print (a)
elif f (b) == 0: print (b)
else:
flag = 0
while b - a > e:
c = (a + b) / 2
if f (c) == 0:
flag = 1
break
elif f (c) * f (a) > 0:... |
from django.contrib import admin
from .models import Plat, PlatConstante, PlatOrganisation
@admin.register(PlatConstante)
class PlatAdmin(admin.ModelAdmin):
list_display = ('id','mx_plat','mx_plat_matin','mx_plat_midi','mx_plat_midi')
@admin.register(Plat)
class PlatAdmin(admin.ModelAdmin):
list_display = ('id','i... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 17 18:00:10 2020
@author: vicma
"""
import json
from time import sleep
from kafka import KafkaConsumer
if __name__ == '__main__':
parsed_topic_name = 'parsed_recipes'
# Notify if a recipe has more than 200 calories
calories_threshold = 200
consumer = K... |
from articles import views
from django.urls import path
from django.conf.urls import url, include
urlpatterns = [
url(r'^add$', views.addArticle),
url(r'^edit/pass/(?P<pk>\d+)$', views.editPassArticle),
url(r'^edit/(?P<pk>\d+)$', views.editArticle),
url(r'^search/(?P<username>\w{0,50})/$', views.search... |
str=input()
pos,word=[i for i in input().split(" ")]
l=list(str)
l[pos]=word
print(str)
|
"""Alter AnswerRule column default NOT NULL
Revision ID: 12b6ae6ce692
Revises: 4fecacd2f5e8
Create Date: 2018-11-27 00:48:32.750384
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '12b6ae6ce692'
down_revision = '4fecacd2f5e8... |
"""
Django settings for vss project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
import... |
"""
Test for Pendulum class.
"""
import nose.tools as nt
import numpy as np
from math import pi, sqrt
from pendulum import NotSolvedError
from pendulum import Pendulum
def test_pendulum():
"""Check if pendulum call gives derivatives."""
test_pend = Pendulum(L=2.2)
test_dth, test_dom = test_pend(0, (pi/4, ... |
import re
from nmmd.base import Dispatcher, try_delegation
class RegexDispatcher(Dispatcher):
@try_delegation
def prepare(self):
data = []
for invoc, method in self.registry:
args, kwargs = self.loads(invoc)
rgx = re.compile(*args, **kwargs)
data.append((r... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import classification_report,accuracy_score,confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.preprocessing import Stand... |
from abc import abstractmethod
class ServiceBase:
@abstractmethod
def info(self):
pass
|
import random
from characters import BaseCharacer
from formulas import mentor_successful_interaction
from widgets import Popup
class Mentor(BaseCharacer):
MENTORS_COUNT = 4
def __init__(self, location, locations, *groups):
super(Mentor, self).__init__(location, *groups)
self.locations = loca... |
# Proyecto compilador Python
# Maquina Virtual de Fight Compilers 2016
# Hecho por Jaime Neri y Mike Grimaldo
#!env/bin/python
import simplejson
import sys
import pprint
import os
import logging
logging.basicConfig(filename='Execution_log.log',level=logging.DEBUG)
file1 = "ejemplos/dimensionada.txt"
file2 = "ejempl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.