index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
9,300
f5a474cdc8aa22322b252b980c0334a9db21bd5c
# -*- coding: utf-8 -*- """ Created on Thu Nov 8 17:14:14 2018 @author: Winry """ import pandas as pd # 显示所有的列 pd.set_option('display.max_columns', None) # 读取数据 file_name = "data_11_8.csv" file_open = open(file_name) df = pd.read_csv(file_open) file_open.close() Newtaxiout_time = df['Newtaxiout_time'] time = df['t...
9,301
244191087fcab2a6f03bf024708484b9838731ed
import sys import pygame import os import random import subprocess FPS, NEWENEMYSPAWN, fst_spawn, not_paused, coins, enemies_count, killed, score = 50, 30, 2000, True, 0, 0, 0, 0 MiniG_rate, EnemyG_rate, MetalM_rate = 1, 5, 15 WEAPONS_LIST = ['Green laser gun', 'Purple laser gun', 'Plasma gun'] def load_i...
9,302
2d48a343ca7f0f8ba7de8b520aad71d774d9b4ba
# Copyright (c) 2016 EMC Corporation # 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 requir...
9,303
b7687240413441e1d3ed0085e5953f8089cbf4c9
# Generated by Django 2.1.7 on 2020-01-09 08:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('goods', '0004_auto_20200109_0713'), ] operations = [ migrations.AlterField( model_name='banner', name='show_type', ...
9,304
a9ea3db019435733b5782d69450942373bb828e5
def calc(*numbers): sum=0 for n in numbers: sum=sum+n*n return sum print(calc(*[1,2,3]))
9,305
e99cf5a7058db984b323af1375003e4e21e36612
import random from connectfour.agents.monte_carlo import Node, MTCS from connectfour.agents.agent import Agent MAX_DEPTH = 3 class MonteCarloAgent(Agent): def __init__(self, name): super().__init__(name) def get_move(self, board): best_move = self.find_best_move(board) return self._...
9,306
9e814e3f1162e248c5d778c2df9960b199854a27
n = int(input('Informe um numero: ')) print('----------------') print('{} x {:2} = {:2}'.format(n, 1, 1*n)) print('{} x {:2} = {:2}'.format(n, 2, 2*n)) print('{} x {:2} = {:2}'.format(n, 3, 3*n)) print('{} x {:2} = {:2}'.format(n, 4, 4*n)) print('{} x {:2} = {:2}'.format(n, 5, 5*n)) print('{} x {:2} = {:2}'.format(n, 6...
9,307
1cb320cf57823511b0398adce097b770b2131eb6
import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ecommerce.settings.development') application = get_asgi_application()
9,308
88d0ced41a8f176a8a12bba6406b4162ea6dfc52
import sqlite3 # cur.execute('CREATE TABLE admin(username TEXT,password TEXT)') # conn.commit() # cur.execute("INSERT INTO admin VALUES('nilesh','nilesh')") # conn.commit() def verif_admin(username, password): try: conn = sqlite3.connect('SuperMarket.db') cur = conn.cursor() print(usernam...
9,309
7e29220752b4a52be34cdf0c734695d1052d0414
''' Handprint module for handling credentials. Authors ------- Michael Hucka <mhucka@caltech.edu> -- Caltech Library Copyright --------- Copyright (c) 2018-2022 by the California Institute of Technology. This code is open-source software released under a 3-clause BSD license. Please see the file "LICENSE" for mor...
9,310
a75691af17f6d1effd469d5c2ded340c71521ee1
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.views import LoginView from django.shortcuts import render from django.views import View from django.views.generic import CreateView from resume.forms import NewResumeForm from vacancy.forms import NewVacancyForm class MenuView(View): ...
9,311
ca7b3b5df860d3c3fb0953857ad950affdcc671d
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('location', '0005_auto_20170303_1625'), ] operations = [ migrations.RemoveField( ...
9,312
499baaa8c739c1bd846edc944e510542d76bbed5
from collections import deque def my_queue(n=5): return deque([],n) pass if __name__ == '__main__': mq = my_queue() for i in range(10): mq.append(i) print((i, list(mq))) """Queue size does not go beyond n int, this outputs: (0, [0]) (1, [0, 1]) (2, [0, 1, 2]) (3, ...
9,313
d2754099adebdb4bd2b028fdf9015571ad773754
""" 챕터: day4 주제: 반복문(for문) 문제: 1에서 100까지 합을 구하여 출력하시오. 작성자: 한현수 작성일: 2018.9.20. """ result = 0 for i in range(101): result += i print(result)
9,314
3c7280bbd23bd3472915da0760efbfd03bfe995d
# # -*- coding:utf-8 -*- import sys reload(sys) sys.setdefaultencoding( "utf-8" ) import urllib import urllib2 import cookielib from excel import * from user import * List=[] cookie = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) postdata = urllib.urlencode({'zjh':user(0),'mm...
9,315
757a69f9ceaa3434c6d9f8b1fcdbadd991190f29
# encoding = utf-8 import hmac import time from hashlib import sha1 def get_signature(now_): # 签名由clientId,grantType,source,timestamp四个参数生成 h = hmac.new( key='d1b964811afb40118a12068ff74a12f4'.encode('utf-8'), digestmod=sha1) grant_type = 'password' client_id = 'c3cef7c66a1843f8b3a9e6a...
9,316
f276e33cde2e043fc8f81403e499544aa816a639
class Member: not_allowed_name = ["Shit", "Hell", "Baloot"] users_num = 0 def __init__(self, first_name, middle_name, last_name, gender): self.fname = first_name self.mname = middle_name self.lname = last_name self.gender = gender Member.users_num += 1 @classm...
9,317
9d190face528d1a237f4c92bfb94a399f61a5af2
import csv import Feature_extraction as urlfeature import trainer as tr import warnings warnings.filterwarnings("ignore") def resultwriter(feature, output_dest): flag = True with open(output_dest, 'w') as f: for item in feature: w = csv.DictWriter(f, item[1].keys()) if flag: ...
9,318
282bccf20cfb114e31c5465c110819796bf81bc0
from types import * class Tokenizer: def __init__(self, buf): self.buf = buf self.index = 0 def token(self): return self.buf[self.index] def move(self, value): self.index += value def skip_whitespaces(self): while self.index < len(self.buf) and self.token()....
9,319
9fff345dedcfc7051a258bc471acf07aece95bcf
import sys from photo_dl.request import request from photo_dl.request import MultiRequest class Jav_ink: def __init__(self): self.parser_name = 'jav_ink' self.domain = 'https://www.jav.ink' self.album_flag = {} @staticmethod def category2albums(category_url): category_url ...
9,320
e714755d660ba809f7958cad4f0b9f95b0a0ffdc
from django.apps import AppConfig class SmashbotspainConfig(AppConfig): name = 'smashbotspain'
9,321
795bd22fb805069b342915638c52900ea52a4939
from UI.Window import Window class PolygonApplication: def __init__(self): self.window = Window("Détermination des périmètre, surface et centre de gravité d'un polygone") self.window.addMouseClickListener(self.window.onClick) def start(self): self.window.show()
9,322
bffd211a2d2dc3dd9b596f69909be7f0437ab0c8
import nltk tw_dict = {'created_at':[], 'id':[], 'id_str':[], 'full_text':[], 'entities':[], 'source':[], 'user':[], 'lang':[]} def Preprocessing(instancia): # Remove caracteres indesejados. instancia = re...
9,323
842f8b4de0378a2c83d22f3fd54ba4857d249597
PRECISAO = 3 MAX_ITER = 20 def gauss_jacobi(entrada,*valores_iniciais): tamanho = len(entrada[0]) variaveis = [*valores_iniciais[:tamanho]] variaveism1 = [None] * (tamanho-1) for _ in range(0,MAX_ITER): print(variaveis) for linha in range(tamanho-1): soma = 0 for coluna in range(...
9,324
9bd6da909baeb859153e3833f0f43d8cbcb66200
# coding=utf-8 import sys if len(sys.argv) == 2: filepath = sys.argv[1] pRead = open(filepath,'r')#wordlist.txt pWrite = open("..\\pro\\hmmsdef.mmf",'w') time = 0 for line in pRead: if line != '\n': line = line[0: len(line) - 1] #去除最后的\n if line == "sil ": ...
9,325
65bfb59a255b42854eec8b55b28711737cfc46c2
#basic API start from flask import Flask, jsonify, abort, request from cruiseItem import cruiseItem from sqlalchemy import create_engine from json import dumps db_connect = create_engine('sqlite:///Carnivorecruise.sqlite') app = Flask(__name__) app.json_encoder.default = lambda self, o: o.to_joson() app.app_c...
9,326
f9310aa6c26ec10041dac272fa17ac21f74c21ac
# -*- coding: utf-8 -*- from wordcloud import WordCloud, ImageColorGenerator import numpy as np from PIL import Image def word2cloud(text: str, mask_image: Image=None): if mask_image == None: wc = WordCloud(font_path='simhei.ttf', width=800, height=600, mode='RGBA', background_color=...
9,327
f23bc0c277967d8e7a94a49c5a81ed5fb75d36cc
from mpi4py import MPI import matplotlib from tmm import coh_tmm import pandas as pd import os from numpy import pi from scipy.interpolate import interp1d from joblib import Parallel, delayed import numpy as np import glob import matplotlib.pyplot as plt import pickle as pkl import seaborn as sns from scipy.optimize im...
9,328
83bbb6433d1577be869bf840bdd42aa86e415da6
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): headline = "Hello world from a variable!" # headline de la izq es el nombre de la variable en la vista # headline de la der es el nombre de la variable en el server return render_template("index.html", headline...
9,329
1158ab95ac67d62459284267a8cc9f587daf89b1
from zipfile import ZipFile import reference_new_stdds import reader import os def runall(path): print("==========================") """get the current path """ abs_file_path = os.path.abspath(__file__) parent_dir = os.path.dirname(abs_file_path) parent_dir = os.path.dirname(parent_dir) """ ...
9,330
39fb8d9f93be1e6c1ed2a425d14061737d643ab6
from .hailjwt import JWTClient, get_domain, authenticated_users_only __all__ = [ 'JWTClient', 'get_domain', 'authenticated_users_only' ]
9,331
94348aed0585024c70062e9201fb41aae2122625
# NumPy(Numerical Python) 是 Python 语言的一个扩展程序库, # 支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。
9,332
13e89e13f88ac306a62be3390f5292665f128a4d
#encoding: utf-8 """ Desc: Author: Makoto OKITA Date: 2016/09/03 """ import numpy as np import chainer from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils from chainer import Link, Chain, ChainList import chainer.functions as F import chainer.links as L import itertools ...
9,333
1983340b3ce7ba8b631ba090871bea1ef7044943
import sys from pypsi.pipes import ThreadLocalStream from pypsi.shell import Shell from pypsi.core import pypsi_print from nose.tools import * class PypsiTestShell(Shell): pass class TestShellBootstrap(object): def setUp(self): self.real_stdout = sys.stdout self.real_stderr = sys.stderr ...
9,334
88d8d04dd7117daed0e976f3abc52c5d7bf18434
import logging import os from os.path import exists, abspath, join, dirname from os import mkdir os.environ["MKL_NUM_THREADS"] = "1" os.environ["MP_NUM_THREADS"] = "1" from smallab.runner_implementations.multiprocessing_runner import MultiprocessingRunner from plannin_experiment import PlanningExperiment mpl_logger ...
9,335
ccb3ec8e367881710c437e7ae53082a1bb0137e5
from pylab import * import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook import random import time from scipy.misc import imread from scipy.misc import imresize import matplotlib.image as mpimg import os from scipy.ndimage import filters import urllib import sys from PIL import Image fro...
9,336
8e71ea23d04199e8fb54099c404c5a4e9af6c4b1
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import stats import datetime #takes in a sorted data frame holding the actuals, the predicted values (sorted descending) and the percentile of each obsevation #and returns a new dataframe with all of the appropriate calculations ...
9,337
c0c8f40e43f1c27f8efa47cfc366c6076b77b9c9
import sys minus = "-" plus = "+" divis = "/" multi = "*" power = "^" unary = "-" br_op = "(" br_cl = ")" operations = [power, divis, multi, minus, plus] digits = ['1','2','3','4','5','6','7','8','9','0','.'] def find_close_pos(the_string): open_count = 0 close_count = 0 for i in range(len(the_string)): if the...
9,338
2027904401e5be7b1c95eebec3a1e6a88c25660c
from Socket import Socket import threading class Server(Socket): def __init__(self): super(Server, self).__init__() print("server listening") self.users = [] def set_up(self): self.bind(("192.168.0.109", 1337)) self.listen(0) self.accept_sockets() def sen...
9,339
00ed68c68d51c5019fde0c489cd133be3d6985c3
# -*- coding: utf-8 -*- """ Created on Fri Aug 21 12:39:59 2015 @author: user Needs to be run after the basic analysis which loads all the data into workspace """ import pandas as pd import numpy as np import matplotlib.pyplot as plt def AverageLeftRight(EyeData): #Take the average of two eyes to get more accurate gaz...
9,340
56e8cdec854b3b7a2f925e70d7d59a73b76f9952
from collections import defaultdict from mask import Mask from utils import bits_to_decimal def get_program(filename): program = [] mask = None with open(filename, 'r') as f: for line in f: line = line[:-1] if 'mask' in line: if mask is not None: ...
9,341
39475626b7e3e0f4c8143b300c002a2eb50cc23a
"""Gaussian mixture model, with Stochastic EM algorithm.""" import numpy as np from sklearn.mixture.gaussian_mixture import _estimate_gaussian_parameters, _compute_precision_cholesky from Core.gllim import MyGMM class SEMGaussianMixture(MyGMM): """Remarque : on utilise la variable Y pour les observations, au li...
9,342
f1fdba1c07a29aa22ee8d0dcbd6f902aa2e8b4c2
from django.shortcuts import render, HttpResponse, redirect from ..login.models import * from ..dashboard.models import * def display(request, id): context = { 'job': Job.objects.get(id=int(id)) } return render(request, 'handy_helper_exam/display.html', context)
9,343
df19aa720993c2385a6d025cf7ec8f3935ee4191
#################################################################### # a COM client coded in Python: talk to MS-Word via its COM object # model; uses either dynamic dispatch (run-time lookup/binding), # or the static and faster type-library dispatch if makepy.py has # been run; install the windows win32all extensions...
9,344
c4898f3298c2febed476f99fe08bc5386527a47e
""" Convert file containing histograms into the response function """ import h5py import wx import numpy as np import matplotlib.pyplot as plt ############################################################################# # Select the file cantoning histograms, # which will be converted to response function app = wx.A...
9,345
7cd6a8a106c21e8e377666d584e19d30c607b7d2
# import os,sys # BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # sys.path.append(BASE_DIR) from lib import common from conf import settings import random import pickle import os import xlrd import time class Base: def save(self): file_path=r'%s/%s' %(self.DB_PATH,self.id) p...
9,346
f4e287f5fce05e039c54f1108f6e73020b8d3d8f
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2015 RAPP # 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 app...
9,347
796fada5dcd45ace8240760ac7e9bad41953ab56
""" Chess state handling model. """ from concurrent.futures import ThreadPoolExecutor from itertools import count from json import dumps from .base_board import BaseBoard, NoBoard from .table_board import TableBoard from .table_game import TableGame __all__ = ['Board', 'NoBoard'] class Board(BaseBoard): """ ...
9,348
d4b432735a112ccb293bf2f40929846b4ce34cd0
#!/usr/bin/python # -*- coding: utf-8 -*- import optparse import logging from pyspark import SparkContext from pyspark import SparkConf logger = logging.getLogger(__name__) def create_context(appName): """ Creates Spark HiveContext """ logger.info("Creating Spark context - may take some while") ...
9,349
1cd82883e9a73cfbe067d58c30659b9b2e5bf473
data=[1,4,2,3,6,8,9,7] def partition(data,l,h): i=l j=h pivot=data[l] while(i<j): while(data[i]<=pivot and i<=h-1): i=i+1 while(data[j]>pivot and j>=l+1): j=j-1 if(i<j): data[i],dat...
9,350
a325feba1c2bb588321429a045133d6eede9e8cf
#!/usr/bin/python # pymd2mc.xyzfile """ """ __author__ = 'Mateusz Lis' __version__= '0.1' from optparse import OptionParser import sys from time import time from constants import R, T from energyCalc import EnergyCalculator from latticeProjector import LatticeProjectorSimple from lattices import HexLattice from ...
9,351
8e5d05d925d47a85ad7c211f26af7951be048d32
import cv2 import numpy as np import show_imgs as si IMG_PATH = "../sample_imgs" def blur(): image = cv2.imread(IMG_PATH + "/jjang.jpg") kernel_sizes = [(1, 1), (3, 3), (5, 5), (7, 7), (7, 1), (1, 7)] filter_imgs = {} blur_imgs = {} for ksize in kernel_sizes: title = f"ksize: {ksize}" ...
9,352
86c1aee21639958f707f99bc2468e952ad6c1859
from app import config from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker engine = create_engine(config.DB_URI) Session = scoped_session(sessionmaker(bind=engine))
9,353
1eeb7a539f43e9fb013494e2aa0d81b4eab0ae1a
import csv from sys import argv import re import sys datasave=[] if len(argv) is not 3: #stop usage if not correct input print('Usage: python dna.py data.csv sequence.txt') sys.exit() #open CSV file and save with open (argv[1],'r') as csv_file: datafile = csv.reader(csv_file) line_count = 0 for ...
9,354
1257b90781a213ca8e07f67a33b8e847d0525653
from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length=40) content = models.TextField() date_published = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCA...
9,355
80bf208f1d658b639d650af8208a744ed2dd258f
import functools import requests import time import argparse class TracePoint: classes = [] funcs = [] flow = [] @staticmethod def clear(): TracePoint.classes = [] TracePoint.funcs = [] TracePoint.flow = [] def __init__(self, cls, func, t): if cls not ...
9,356
3e4771d074218fb0a77332ee61a4cc49f1c301b7
# SPDX-License-Identifier: Apache-2.0 # Copyright (C) 2020 ifm electronic gmbh # # THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. # """ This module provides the recording control GUI service for the nexxT framework. """ import logging from pathlib import Path from nexxT.Qt.QtCore import Qt, QStorageInf...
9,357
59233cd45000cd6d6ad0876eb3812599392d7c05
# -*- coding:utf-8 -*- __author__ = 'leandro' from datetime import * from PyQt4 import QtGui, QtCore from baseDatos.ventas.venta import NotaCredito from gui import CRUDWidget,MdiWidget from ventanas import Ui_vtnDevolucionDeCliente, Ui_vtnReintegroCliente, Ui_vtnVentaContado from baseDatos.obraSocial import ObraSoc...
9,358
4efd22d132accd0f5945a0c911b73b67654b92e4
from django.urls import path from .views import FirstModelView urlpatterns = [ path('firstModel', FirstModelView.as_view()) ]
9,359
5f1cbe1019f218d2aad616ea8bbe760ea760534c
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys # Add gumpy path sys.path.append('../shared') from gumpy import signal import numpy as np def preprocess_data(data, sample_rate=160, ac_freq=60, hp_freq=0.5, bp_low=2, bp_high=60, notch=False, hp_filter=False, bp_filter=False, artifact_rem...
9,360
ae775e25179546156485e15d05491e010cf5daca
# encoding=utf8 from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.common.exceptions import NoSuchElementException, ElementNotVisibleException from selenium.webdriver.support.select import Select import time import threading import random import ...
9,361
1b1b646a75fe2ff8d54e66d025b60bde0c9ed2d6
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # ### Bài tập 1. # - <ins>Yêu cầu</ins>: Ý tưởng cơ bản của thuật toán ``Support Vector Machine`` (``SVM``) là gì? Ý tưởng của thuật toán biên mềm (``soft margin``) ``SVM``. Nêu ý nghĩa của siêu tham số ``C`` trong bà...
9,362
c889fd081eb606dca08fade03aa0a4d32319f98d
import requests import json URL = 'https://www.sms4india.com/api/v1/sendCampaign' # get request def sendPostRequest(reqUrl, apiKey, secretKey, useType, phoneNo, senderId, textMessage): req_params = { 'apikey':EON386947EGSUZ4VEMIL8AWQX8RQW6UH, 'secret':FB2K25JVMFPEM310, 'usetype':useType, 'p...
9,363
bf3e7f1aa9fd20b69e751da9ac8970c88b1144eb
""" Test the OOD-detection capabilities of models by scaling a random feature for all sample in the data set. """ # STD import os import pickle from copy import deepcopy from collections import defaultdict import argparse from typing import Tuple, Dict, List # EXT import numpy as np from tqdm import tqdm import torch...
9,364
28532fe798b6a764bec7ea511ba9e66a1d096b6f
#!/usr/bin/python import argparse import contextlib import os.path import shutil import subprocess import sys import tempfile from Bio import SeqIO BOOTSTRAP_MODES = 'a', # Some utilities @contextlib.contextmanager def sequences_in_format(sequences, fmt='fasta', **kwargs): with tempfile.NamedTemporaryFile(**kwa...
9,365
7f7adc367e4f3b8ee721e42f5d5d0770f40828c9
from setuptools import setup import os.path # Get the long description from the README file with open('README.rst') as f: long_description = f.read() setup(name='logging_exceptions', version='0.1.8', py_modules=['logging_exceptions'], author="Bernhard C. Thiel", author_email="thiel@tbi.un...
9,366
ae27f97b5633309d85b9492e1a0f268847c24cd5
import random import numpy as np import matplotlib.pyplot as plt import torchvision def plot_image(img, ax, title): ax.imshow(np.transpose(img, (1,2,0)) , interpolation='nearest') ax.set_title(title, fontsize=20) def to_numpy(image, vsc): return torchvision.utils.make_grid( image.view(1, vsc.c...
9,367
60c3f6775d5112ff178bd3774c776819573887bb
import smtplib import os from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from datetime import datetime from threading import Thread FROM = os.getenv('EMAIL_FROM') TO = os.getenv('EMAIL_TO') HOST = os.getenv('EMAIL_HOST') PORT = os.getenv('EMAIL_PORT') PASSWORD = os.getenv('EMAIL_PAS...
9,368
6b6b734c136f3c4ed5b2789ab384bab9a9ea7b58
# Generated by Django 3.0.5 on 2020-05-02 18:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('weatherData', '0001_initial'), ] operations = [ migrations.AddField( model_name='city', name='username', ...
9,369
da218e6d9ee311eefb8e9ae4dac5053793eb5514
""" Class for manage tables in Storage and Big Query """ # pylint: disable=invalid-name, too-many-locals, too-many-branches, too-many-arguments,line-too-long,R0801,consider-using-f-string from pathlib import Path import json from copy import deepcopy import textwrap import inspect from io import StringIO from loguru i...
9,370
5d97a2afed26ec4826c8bce30c84863d21f86001
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_security import SQLAlchemySessionUserDatastore, Security app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("config.py", silent=True) db = SQLAlchemy(app) from .blueprints.cart.views import cart_blueprint from .bluepr...
9,371
d28571214805df766c2cc2f45a6b5bea88d7ac18
#!/usr/bin/env python from setuptools import setup, find_packages #if sys.argv[-1] == 'publish': # os.system('python setup.py sdist upload') # sys.exit() with open('bace/__init__.py') as fid: for line in fid: if line.startswith('__version__'): VERSION = line.strip().split()[-1][1:-1] ...
9,372
4ad4cf46be735c6ac26b5b0953d4c2458f37496a
import os, shutil, cv2 from PIL import Image INP_DIR = '/dataset/test_set_A_full' # Lọc thư mục data test ra thành 3 thư mục: None, Square (1:1), và phần còn lại (đã được crop ngay chính giữa) # Trả về path dẫn đến 3 thư mục nói trên def pre_proc(INP_DIR): INP_DIR = INP_DIR + '/' NONE_DIR = os.path.dirname(I...
9,373
02a1f84e72b412636d86b9bdb59856ae8c309255
''' Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. '...
9,374
601d32bf30aa454bbc7d31d6ce4b7296cef0fdfe
"""Largest product in a series Problem 8 The four adjacent digits in the 1000-digit number that have the greatest product are 9 x 9 x 8 x 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 125406987471585238...
9,375
438fe1ccf265706e202d7cc6044e57590f29801f
import pytest from eth_utils import encode_hex, remove_0x_prefix from ethereum.tester import keys import os import json from microraiden.client.client import CHANNEL_MANAGER_ABI_NAME, TOKEN_ABI_NAME from microraiden.crypto import privkey_to_addr @pytest.fixture def contracts_relative_path(): return 'data/contrac...
9,376
9d2c0d59b0b2b4e4fca942e648059738053c53d0
from setuptools import setup, find_packages import sys, os version = '0.1' setup( name='ckanext-MYEXTENSION', version=version, description="description", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='ldhspace', author...
9,377
8fbfa53be826b45b53b530a1766f6a68c61f5be9
from tkinter import * class Menuutje: def __init__(self, master): menu = Menu(master) master.config(menu=menu) subMenu = Menu(menu) menu.add_cascade(label="File", menu=subMenu) subMenu.add_command(label="New Game...", command=self.doNothing) subMenu.add_command(la...
9,378
467327b98ab99bdad429943c701c751be4f67940
import json import sys from copy import deepcopy from argparse import ArgumentParser # TODO: Ord category's IDs after deletion def return_cat_name(json_coco, category): """Return the category name of a category ID Arguments: json_coco {dict} -- json dict file from coco file category {int} --...
9,379
0f257d199ad0285d8619647434451841144af66d
#Tom Healy #Adapted from Chris Albon https://chrisalbon.com/machine_learning/linear_regression/linear_regression_using_scikit-learn/ #Load the libraries we will need #This is just to play round with Linear regression more that anything else from sklearn.linear_model import LinearRegression from sklearn.datasets import ...
9,380
17a442a85b910ff47c2f3f01242b7f64a6237146
from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential, Model from keras.applications import InceptionV3 from keras.callbacks import ModelCheckpoint from keras.optimizers import SGD from keras.layers import Flatten,Dense,Dropout from keras.preprocessing.image import img_to_a...
9,381
d23700f03e8498a5ff3d1d03d8808048ba79a56b
import os from os import listdir from openpyxl import load_workbook, Workbook ROOT_PATH = os.getcwd() # print(f'ROOT_PATH : {ROOT_PATH}') CUR_PATH = os.path.dirname(os.path.abspath(__file__)) # print(f'CUR_PATH : {CUR_PATH}') path = f'{ROOT_PATH}/xlsx_files' files = listdir(path) result_xlsx = Workbook() result_sheet...
9,382
4e04e748a97c59a26a394b049c15d96476b98517
# Generated by Django 2.2.16 on 2020-10-27 14:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('trades', '0001_initial'), ] operations = [ migrations.AddField( model_name='orderinfo', name='nonce_str', ...
9,383
aaeca18f3771a6032c0fe51b75502f730c888888
import FWCore.ParameterSet.Config as cms source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( '/store/user/skaplan/noreplica/ADDdiPhoton/sherpa/mgg750-2000_Ms3000/sherpaevents_10_1_Kji.root', '/store/user/skaplan/noreplica/ADDdiPhoton/sherpa/mgg750-2000_Ms3000/sherpaevents_1_1_oTR.r...
9,384
e6694403eecf2c4511c1fce959b5939f5f457bb8
v1 = 3+4*2 print(v1) v2 = (2+6)*2 print(v2) v3 = 2**3**2 print(v3) v4 = 20+80/2 print(v4)
9,385
9d7bc2d93b855fbd22a4707a6237ac51069beb53
""" 进程对象属性 """ from multiprocessing import Process import time def tm(): for i in range(3): print(time.ctime()) time.sleep(2) p = Process(target=tm,name='Tarena') # 设置子进程随父进程退出 p.daemon = True p.start() print("Name:",p.name) # 进程名称 print("PID:",p.pid) # 进程PID print("is alive:",p.is_alive()) #...
9,386
3d742505d480493fbc729e7a0febdcab3a7dc041
from __future__ import annotations from typing import Generator, Optional from collections import Counter from itertools import zip_longest from re import finditer codon_table = """UUU F CUU L AUU I GUU V UUC F CUC L AUC I GUC V UUA L CUA L AUA I GUA V UUG L CUG L ...
9,387
1a28aea824752d18cbd462693f8f8980dba4974e
import re BASICPATTERN = '[!/](%s)\s{,1}(.*)' # example "/animefind baka" -> (animefind, baka) # returns compiled BASICPATTERN for each given string def basicRegex(strings): if not isinstance(strings,list): return [] ans = [] for string in strings: pattern = re.compile(BASICPATTERN % st...
9,388
07e068dbc1ba1bcb85121ee49f2f9337cae188ba
#!/usr/bin/env python3 """ brightness an image""" import tensorflow as tf def change_brightness(image, max_delta): """brightness an image""" img = tf.image.adjust_brightness(image, max_delta) return img
9,389
475cb57ce5fda0d0389bfa1b9b227a2147e1abde
#------------------------------------------------------------ # Copyright 2016 Congduc Pham, University of Pau, France. # # Congduc.Pham@univ-pau.fr # # This file is part of the low-cost LoRa gateway developped at University of Pau # # This program is free software: you can redistribute it and/or modify # it under the...
9,390
8fd020e7f1854d29cf903f86d91a3a9ffa9d08d3
/home/rip-acer-vn7-591g-1/catkin_ws/devel_cb/.private/nmea_navsat_driver/lib/python2.7/dist-packages/libnmea_navsat_driver/__init__.py
9,391
763f552329a0d38900e08081a1017b33cd882868
import random tree_age = 1 state = "alive" value = 1 age_display = "Your tree have an age of: {}".format(tree_age) state_display = "Your tree is {}.".format(state) def tree_state(x): if x <= 19: state = "alive" return state elif x <= 49: rand = random.randrange(tree_...
9,392
32d830f00a9d33b8f7f438c14b522ef186001bf3
/usr/local/python-3.6/lib/python3.6/abc.py
9,393
ab6450ee9038e0c58ca8becf6d2518d5e00b9c90
"""Generic utilities module""" from . import average from . import extract_ocean_scalar from . import git from . import gmeantools from . import merge from . import netcdf from . import xrtools __all__ = [ "average", "extract_ocean_scalar", "git", "gmeantools", "merge", "netcdf", "xrtools"...
9,394
ca403e8820a3e34e0eb11b2fdd5d0fc77e3ffdc4
# File for the information gain feature selection algorithm import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_selection import mutual_info_classif # The function which will be called def get_features(raw_data, raw_ids): """ Calculate the in...
9,395
7c9b68b2d32d8e435f332d4412ea1ba899607ec4
"""Derivation of variable ``co2s``.""" import dask.array as da import iris import numpy as np import stratify from ._baseclass import DerivedVariableBase def _get_first_unmasked_data(array, axis): """Get first unmasked value of an array along an axis.""" mask = da.ma.getmaskarray(array) numerical_mask = ...
9,396
8771f71a69f3afdc5de4d38db6efe61b553ae880
import cartopy.crs as ccrs import cartopy.feature as cfeature import numpy as np import matplotlib.pyplot as plt import netCDF4 import xarray as xr import metpy from datetime import datetime import datetime as dt from metpy.units import units import scipy.ndimage as ndimage from metpy.plots import USCOUNTIES...
9,397
dc2deb7d4c9cc126a6d80435fe9dbc16d6ac8941
config_prefix = "<" config_suported_types = ["PNG", "GIF", "JPEG"] config_pattern = "^[A-Za-z0-9_]*$" config_max_storage = int(1E9) config_max_name_length = 20 config_message_by_line = 2 config_max_message_length = 2000 config_max_emote_length = 8*int(1E6) config_pong = """ ,;;;!!!!!;;. :!!!!!!!!!!!!!!; ...
9,398
f2ac9904aaa4c12ef2954b88c37ffd0c97aadf5a
''' Problem 24 A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 ...
9,399
a2626b384d0b7320ee9bf7cd75b11925ccc00666
import itertools def sevens_in_a_row(arr,n): in_a_row={} for iteration in arr: if arr[iteration]==arr[iteration+1]: print blaaa def main(): n=3 arr=['1','1','1','2','3','-4'] print (sevens_in_a_row(arr,n)) if __name__== '__main__': main()