index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
13,900 | 75981e44eaca2378dec5a5e928e51602616eda8d | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import logging
import aiohttp
import asyncio
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
from operator import itemgetter
from collections import OrderedDict
def extract_chapters(chapters_url, html):
"""
通用解析小说目录
:param c... |
13,901 | dbced9badaf5fe104f6b1552731d8e852aa05fc4 | import sys
from Data_Processing_Unit.models import *
from Public_Data_Acquisition_Unit.mongo_models import *
from dotmap import DotMap
import json
from bson import ObjectId
import datetime
class Mongo_Serializer(object):
SUPPORTED_MODELS = [Keybase_Response_TMS,Trends]
def __init__(self):
pass
d... |
13,902 | 0793d29eddf863f13768df45dc473b42c5a9998c | import functools
import time
import code
import warnings
import math
def timethis(func=None, *, n_iter=100):
if func is None:
return lambda func: timethis(func, n_iter=n_iter)
@functools.wraps(func)
def inner(*args, **kwargs):
print(func.__name__, end=" ... ")
acc = float('inf')
... |
13,903 | 840f213a75f01912feae8fb8fcd2e3f00b7e1408 | from datetime import datetime
from bleuio_lib.bleuio_funcs import BleuIo
# from serial import SerialException
from time import sleep
my_dongle = BleuIo()
my_dongle.start_daemon()
print(
"Connected to dongle\n\n"
"Welcome to the Bluetooth device Scan and Store example!\n\n"
)
# Set the dongle in central rol... |
13,904 | af0079a4dc4bcbe1294a472df50d7712585eeca9 | import numpy as np
from load_data import load_data
from veltman_format import teams
class PlayCallGame():
def __init__(self):
self.start()
def start(self):
data = load_data('formatted_veltman_pbp_small.pkl', False)
self.train_set_x, self.train_set_y = data[0]
self.test_set_x, self.test_set_y = da... |
13,905 | 83ae465e5e0013ecf6b4e3b57fe6ee9c6d0a2900 | import configparser
import difflib
import logging
import os
from pathlib import Path
import pytoml as toml
from .validate import validate_config
from .vendorized.readme.rst import render
import io
log = logging.getLogger(__name__)
class ConfigError(ValueError):
pass
metadata_list_fields = {
'classifiers',
... |
13,906 | b8e531662f9b5c43832b9a721505d2b8cff0357d | # Generated by Django 2.0.4 on 2018-05-11 15:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agents', '0002_auto_20180511_1256'),
]
operations = [
migrations.AlterField(
model_name='ag',
name='policy_ID',
... |
13,907 | dccd8c8fba715e9f0d4602563ba4f3a7b6750148 | import os
import json
import boto3
import uuid
print("PLEASE CONFIGURE A TEST USER WITH setup_user.py")
print("This script simulates an illegal write into a DynamoDB table caused by a faulty group policy")
print("Incident: Admin user attempts to write into patient table")
print("Response: Updated record rollbacks and ... |
13,908 | abb01e70838d7a318a657e60e610a86a2dcc7584 | from typing import List
from fastapi import Depends, FastAPI, HTTPException
from starlette.responses import RedirectResponse
from sqlalchemy.orm import Session
import crud, models, schemas
from database import SessionLocal, engine
# creates database tables
models.Base.metadata.create_all(bind=engine)
app = FastAPI()... |
13,909 | fa703992ea8db534856c1d623875148be9a369ca | # Write a function called make_shirt() that accepts a size and the
# text of a message that should be printed on the shirt. The function should print
# a sentence summarizing the size of the shirt and the message printed on it.
# Call the function once using positional arguments to make a shirt. Call the
# function a s... |
13,910 | cd80cccc843df8b58c47299845096b812568ce3a | # -*- coding: utf-8 -*-
from apt_pkg import __init__
from cwr.validation.common import Validation, ValidationStatus, ASValidationStatus
"""
Base classes for implementing validation rules.
"""
__author__ = 'Yaroslav O. Golub'
__license__ = 'MIT'
__status__ = 'Development'
class ValidationTransaction(Validation):
... |
13,911 | 2306fdd0864a3342918988e279cc190e2eb85899 | import Parser.ConditionParser as condParser
import Parser.ParserUtils as utils
from Lexers.Lexer import Lexer
from Lexers.tokens import *
from Model.Rule import Rule
from Model.Action import Action
def parse_from_lexer(lexer, symbol_table, engine, passed_token):
rotated = False
while True:
if passed_t... |
13,912 | a562cfe06a0d08ea14ed13150e7d9db5cf23694d | # -*- coding: utf-8 -*-
"""
Created on Mon May 7 14:28:31 2018
@author: Administrator
"""
from copy import deepcopy
from sklearn import datasets
from FeatureEvaluate import CartGini
from FeatureEvaluate import gini
from FeatureEvaluate import SE
from FeatureEvaluate import SETwo
from sklearn.preprocessing import Labe... |
13,913 | f46230a123b5f91517fb530063de7b9eeb54e4f6 | import sys
from tkinter import *
from docxtpl import DocxTemplate
from test import *
from PyQt5 import QtCore, QtGui, QtWidgets
from test import Ui_MainWindow
class MyWin(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
... |
13,914 | 780f100b81554f845d984010937089489cc21fcf | '''
Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não
atingiram a maioridade e quantas já são maiores (considerar 21 anos para maioridade).
'''
print("=========== desafio 054============")
import datetime
maiores = 0
menores = 0
for x in range(1, 8):
print(x,... |
13,915 | 690f2cfccd80742cd0dec5f2926bf825e08ac037 |
from subprocess import check_call
import sys
import os
# Get path of this file
basePath = os.path.dirname(os.path.abspath(__file__))
managePath = os.path.join(basePath, "manage.py")
check_call([
sys.executable,
managePath,
"runserver",
"--settings=wwustc.dev-settings"
])
|
13,916 | f3c8e321abb1b9478cf7774807ff3fadfbcada84 | import socket
import os
import json
from dotenv import load_dotenv
from pynput import mouse
from signal import signal, SIGINT
from sys import exit
from multiprocessing import Process
load_dotenv()
size = width, height = 1280, 800
MAX = 32500
def handler(signal_received, frame):
global run_code
# Handle any c... |
13,917 | 5432886d87b2aade8528f6c472ce71696cb040f1 | from django.contrib.sites.models import _simple_domain_name_validator
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import pgettext_lazy
from . import AuthenticationBackends
from decimal import Decimal
from django.core.validators import ... |
13,918 | 96f7e5cafce64cafd9393bbf32aec739a9927b63 | # Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
13,919 | 2940fe4d84c3fab1559922640842652ac2be6f7e | import mock
import time
from unittest import TestCase
from Alarm.Alarm import Alarm
from Alarm.AlarmState.AlarmState import AlarmState
from Alarm.AlarmState.Triggered import Triggered
from Alarm.AlarmState.Idle import Idle
class TestTriggered(TestCase):
def setUp(self):
self.alarm = Alarm([], None, None... |
13,920 | c313d3df532b0e9a000c6c0c666fdcebe13c2a80 | # -*- coding: utf-8 -*-
""" 实现线性搜索 """
# 算法核心思想:从表的一端开始,顺序扫描数组,依次将扫描到的数组元素和目标值相比较,若当前数组元素与目标值相等,则查找成功;
# 若扫描结束后,仍未找到数组元素等于目标值的结点,则查找失败
# 算法介绍网站:https://zh.wikipedia.org/wiki/%E7%BA%BF%E6%80%A7%E6%90%9C%E7%B4%A2
def linear_search(lists, target):
""" 实现线性搜索
Args:
lists: list
待... |
13,921 | 26b23e0bc083f5ae04912972a7b2c521d95e7633 | #!/usr/bin/env python3
#IMPORTING LIBRARIES
import urllib.request as ur
from bs4 import BeautifulSoup
from nltk.tokenize import sent_tokenize
import numpy as np
#WEBBSITE TO SCRAP
website="http://www.cricbuzz.com/cricket-match/live-scores"
#GETTING SOURCE CODE
web_data=ur.urlopen(website)
source_code=web_data.read()... |
13,922 | 616cd62921f2772e5390c6185ab39f2ff74ca718 | import unittest
from path import path
import clld
class Tests(unittest.TestCase):
def test_parsed_args(self):
from clld.scripts.util import parsed_args
parsed_args(args=[path(clld.__file__).dirname().joinpath('tests', 'test.ini')])
|
13,923 | ce91c3470b1aa825783875baba4ad62848902b64 | ##
# Represents the physical view of the DFS.
##
import os.path
import shutil
import dfs_state
import error as err
from base import Base
from lock import Lock
shareFolderPath = os.path.expanduser("~/Share/")
saveStateName = '.state'
class PhysicalView(Base):
def __init__(self, dfs):
Base.__init__(self, ... |
13,924 | a6fad21a27b81ccec33fd3f5ee500d41d4ce3f1c | from behave import *
use_step_matcher("parse")
@given('Exists a user "{username}" with password "{password}"')
def step_impl(context, username, password):
from django.contrib.auth.models import User
User.objects.create_user(username=username, email='user@example.com', password=password)
@given('I login as u... |
13,925 | 053df4fc50440077a054ccb81b44f8016b24d02b | # Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров.
# Программа должна принимать значения ... |
13,926 | e2e2d5b1c3f3554ae9cb77efff6410403c28d0c6 | from collections import Counter
import numpy as np
import plotly.graph_objects as go
from model_operations import extract_ids
def summary_report(shape_values, feature_names, class_names, merge=False):
"""
Summary report
:param class_names:
:param shape_values:
:param feature_names:
:param me... |
13,927 | 38f61009fd83cb3ed73421a9617cbc52fbcfccfe | from game.adventure.campaign import Campaign
from game.adventure.room import Room
from game.adventure.item import Item
from game.adventure.character import Character
from game.adventure.generators.rooms import random_room
class DeepDungeon(Campaign):
name = "The Deep Dungeon"
def __init__(self, console):
... |
13,928 | 2919c52c9922a862e197c9c34c9757f3f8cbdc51 | '''
Constant string values used for home environment setup
'''
MANAGED_FILES = [ ".bash_aliases", ".gdbinit", ".gitignore", ".gitconfig", ".vimrc", "Documents/colors.modal.ls", "Documents/colors.template", ".ssh/config", ".config/git"]
LOCAL = ".local"
LOCO_BIN = "/".join([LOCAL, "bin"])
CLONE_URI = "ssh://git@git... |
13,929 | b34e02f404756bc982644e4879accd0cd455e607 | #Create a function that returns True if the given string has any of the following: Only letters and no numbers.
#Only numbers and no letters.
#If a string has both numbers and letters or contains characters that don't fit into any category, return False.
def csAlphanumericRestriction(input_str):
return input_s... |
13,930 | 8e38d4dad1b433b684ccff507ac0db607d48e45c | import numpy as np
from thimbles.thimblesdb import Base, ThimblesTable
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import re... |
13,931 | 884471eafad56b84b2d8fe97572f33d7a2ceb79a | from .ensemble import *
from .plots import *
|
13,932 | 7dd087cb91a6423d4f4a11708f9c0a4c31339315 | class AccessControlList():
accessControlList = None
def __init__(self, accessControlList):
self.accessControlList = {}
def add(self, ivleid, level):
self.accessControlList[ivleid] = level
def remove(self, ivleid):
if ivleid in self.accessControlList:
... |
13,933 | af49a7c88e714fcb2e9ab30c9b3ca39b7388e3bc | from .ocean import *
from .city import *
from .country import *
from .division import *
from .subdivision import *
from .altname import *
|
13,934 | b7d73c913e9ada7ff21a72fcf508b71aa108c86a | from django.apps import AppConfig
class CanteenAppConfig(AppConfig):
name = 'canteen_app'
|
13,935 | f696bf92ab9a00211fa6f61edbb5b0c844ea657e | from os import listdir
import random
import numpy as np
TEST_DATA_PERCENTAGE = 30
class DataGenerator:
def __init__(self, neg_reviews_dir_path, pos_reviews_dir_path):
self.neg_reviews_dir_path = neg_reviews_dir_path
self.pos_reviews_dir_path = pos_reviews_dir_path
self.neg_reviews_files ... |
13,936 | 4c40c1cab37766e58082cbe82977c566cf2e1699 | # ##### BEGIN MIT LICENSE BLOCK #####
#
# Copyright (c) 2012 Matt Ebb
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use,... |
13,937 | 5ab097add7af5ffccd4bb62c83d24df94111b52c | from pydantic import BaseModel
class IUser(BaseModel):
uid: int = None
name: str = None
dp: str = None
dpName: str = None
pos: int = None
posName: str = None
role: int = None
roleName: str = None
class IUserInDB(IUser):
password: str
DICUSERINFO = dict() |
13,938 | 884817d2ea92b10e30b61b5ae747185e6aab1a17 | from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from products.models import Book
from .cart import Cart
from .forms import CartAddProductForm
from discount.forms import CouponApplyForm
from django.contrib import messages
from django.urls imp... |
13,939 | dc571ed0d58bfc0d18c91070c8a120d84ef430b6 |
def Actors_In_View(actorsinview, livingactors, position, viewdistance, role):
for Actor in livingactors:
if role == 'predator' and Actor.role == 'plant':
continue
else:
xcheck = Actor.position[0] - position[0]
ycheck = Actor.position[1] - position[1]
... |
13,940 | 14718985e75317991848ce9b757bc77982b1d97c | import math #brings in the basic python math used in the rest of the program
yFunction = str(input("f(x)="))#asks for a function
xValue = int(input("where does your approximation start? "))#asks where the method begins
rePeat = int(input("how many times should I approximate? "))#asks how many times the process should ... |
13,941 | 7dd663caf1dde61ca1a75e7362300f9f9c1fe4b9 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 5 16:03:26 2017
https://www.python.org/doc/essays/graphs/
The problem with this implementation is that it always goes A->B-> and so on while there could be A->C connection directly
This is DEFINITELY not find the shortest path
@author: User
"""
graph = {'A': [... |
13,942 | ca446e098975aa361e21c6e9b69e6c2749897a7a | # encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib64/python2.6/site-packages/PyQt4/QtGui.so
# by generator 1.136
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
class QTextOption(): # skipped bases: <type 'sip.simplewrapper'>
# no doc
def alignment(self, *args, **kwargs): # real signature unknow... |
13,943 | 29ee13b0be6582088694cdcdd600fdc235488f33 | # -*- coding: utf-8 -*-
"""This module defines functions for fetching and parsing files in the PDB
for the Chemical Compound Dictionary (CCD_).
.. _CCD: https://www.wwpdb.org/data/ccd
"""
from prody import LOGGER, PY3K
from prody.utilities import openURL, isListLike
from prody.proteins.starfile import parseSTARLin... |
13,944 | bbe7f021fbcd0da0dc5836d59b979d977d5cb32b | #!/usr/bin/python
import unittest
import string
import time
import psutil
import datetime as dt
import heapq
import collections
'''
Given a list of scores of different students, return the average score of each student's top five scores in the order of each student's id.
Each entry items[i] has items[i][0] the student'... |
13,945 | 1f94ca734b62c9144b4b78593bd14cea1cf278c7 | # Generated by Django 3.1.7 on 2021-03-05 04:06
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('assignme... |
13,946 | 227dd1f9a8eb39bc3a8237f90b71da34e99fa8d7 | #!/usr/bin/env python3
from math import ceil
from .data_conversion import IntConverter
class ByteData:
def __init__(self, data=b'', converter=None):
if converter is None:
self._bytes = bytearray(data)
else:
self._bytes = converter.decode(data)
def __eq__(self, other):... |
13,947 | fa752545a47b46aafb4e3bf27bfa8fd2a548a498 | import simplejson
import urllib
import openerp
from openerp import http
from openerp.http import request
import openerp.addons.web.controllers.main as webmain
from openerp.addons.web.http import SessionExpiredException
from werkzeug.exceptions import BadRequest
import werkzeug.utils
import requests
url_return=''
resou... |
13,948 | fb2114239ffa16578cdbfb61eac7c3d5a500beae | """
70. 単語ベクトルの和による特徴量Permalink
問題50で構築した学習データ,検証データ,評価データを行列・ベクトルに変換したい.
例えば,学習データについて,すべての事例xiの特徴ベクトルxiを並べた行列Xと,正解ラベルを並べた行列(ベクトル)Yを作成したい.
X=⎛⎝⎜⎜⎜⎜x1x2…xn⎞⎠⎟⎟⎟⎟∈ℝn×d,Y=⎛⎝⎜⎜⎜⎜y1y2…yn⎞⎠⎟⎟⎟⎟∈ℕn
ここで,nは学習データの事例数であり,xi∈ℝdとyi∈ℕはそれぞれ,i∈{1,…,n}番目の事例の特徴量ベクトルと正解ラベルを表す.
なお,今回は「ビジネス」「科学技術」「エンターテイメント」「健康」の4カテゴリ分類である.
ℕ<4で4未満の自然数(... |
13,949 | 1563ca18bc4f5b5425e3806ec9b720c2325351af | import random
import hashlib
import time
import socket
def tHeader(tgt):
start = time.time()
t = str(random.getrandbits(64)).encode('utf-8')
val = hashlib.sha256(t).hexdigest()
nonce = 0
while int(val,16)>int(tgt,16):
temp = int(val,16) + nonce
val = ... |
13,950 | b6eaff509c685fc390f3ba50b4856e9916df8c2a | import pygame
pygame.init()
class Adjacent:
def __init__(self,square):
self.square = square
self.astar_distance = square.objective_distance |
13,951 | 3b28b5bfe5b12747fa91bc3752e72db3ff882d99 | from . import all_et
from . import all_el
|
13,952 | 7619c67841e3186ce311624e01301e53be20ad16 | import cnn
from PIL import Image
def main():
# Фотография для анализа:
path = 'pics/cat_man.jpg'
img = Image.open(path)
# Загружаем нейронную сеть:
ml = cnn.load_cnn_model()
# Делаем предикт фотографии:
result = cnn.img_analyze(img, ml)
print(result)
if __name__ == '__... |
13,953 | a6e91f97f77919bb5486898adba79321997b78fb | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class StudyAccountInfo(object):
def __init__(self):
self._alipay_card_no = None
self._card_type = None
self._study_id = None
@property
def alipay_card_no(self):
... |
13,954 | 9cb2c4ca2bc5955cfc390a43b4fdb08082f18785 | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class BasicDetails(models.Model):
Auth_Id = models.TextField(primary_key=True,max_length=12)
User = models.OneToOneField(User,on_delete=models.CASCADE,null=True)
Asha_Worker = models.CharField(max_l... |
13,955 | 27e8ad56a7a416b1e1bd2c9c120f7a8243e9f9fb | zbior = set()
while True:
komenda = input("Podaj liczbę, ewentualnie [w]yjdz")
if komenda == "w":
break
zbior.add(int(komenda))
zbior2 = set()
for liczba in zbior:
if liczba % 2 == 0 and liczba < 101:
zbior2.add(liczba)
zbior3 = zbior & zbior2
print(zbior3)
print(len(zbior3))
|
13,956 | ac94d8e9023e8245c6d0d83b39fe99dacb1dd39c | #find largest among 3 numbers
a=int(input("enter the number a:"))
b=int(input("enter the number b:"))
c=int(input("enter the number c:"))
if(a>b):
print("a is largest number")
elif(b>c):
print("b is largest number")
else:
print("c is largest number") |
13,957 | 8fc9f145ef20ca90a6364612c108bd4fe25d93ee | from setuptools import setup
setup(
name='pythonml',
version='1.0',
description='Learning ML along with Python',
author='Alex Kolomiytsev',
author_email='alexander.kolomiytsev@gmail.com',
packages='pythonml',
install_requires=['numpy', 'sklearn', 'scipy']
) |
13,958 | ceb8d66188d758a57a465f2122e02487ecac0f1e | #/usr/bin/python
import time
from sms_reader import SmsReader
reader = SmsReader()
global messages
if __name__ == "__main__":
while True:
reader.update()
if len(reader.new_sms) > 0:
messages = reader.new_sms
print messages
reader.new_sms = []
time.slee... |
13,959 | c3b92252cf3d7a9cc015915d3cad36730ea4c14e | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.ShopSummaryQueryResponse import ShopSummaryQueryResponse
class AlipayOfflineMarketShopSummaryBatchqueryResponse(AlipayResponse):
def __init__(self):
supe... |
13,960 | 8c519d15b9079ae84cd8757de2a9e1d0b921378f | """
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluat... |
13,961 | 82d9c32f5fc9e176a2b1d51f335cb8fe2e0c49a7 | #!/usr/bin/env python3
import colors as c
print(c.clear)
print(c.green + 'Welcome to Blakes Note Pad!')
print(c.red + '#!/usr/bin/env python3')
|
13,962 | 54762fdb35cb386ce6eef0d902219de4fb53447c | #!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/right-view-of-binary-tree/1
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inOrder(root):
if root == None:
return
inOrder(root.left)
print(root.data, end=" "... |
13,963 | 4396b971a0c5c3fdee54d5b60977b83bb5f9c6b6 |
''' Purpose: print a requested phrase a requested number of times
'''
# get phrase to be repeated
reply = input( "Enter phrase to be printed: " )
phrase = reply.strip()
# get number of times to repeat the phrase
reply = input( "Enter number of times to print the phrase: " )
nbr_of_times = int( reply )
# print th... |
13,964 | fa0cd8f25090122a968f0e43dcc2c66dd79c6d0c | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# coding by xiaoming
'''
当你的才华还撑不起你的野心时,那你就应该静下心来学习
当你的能力还驾驭不了你的目标时,那就应该沉下心来历练
'''
'''
random()
获取0~1之间的随机小数包含0不包含1
格式:random.random()
返回值:浮点数
choice()
随机获取列表中的值
格式:random.choice(序列)
返回值:序列中的某个值
shuffle()
随机打乱序列
格式:random.shuffle(序列)
返回值:打乱顺序的序列
randrange()
获取指定范围内指定间... |
13,965 | 7f09c6dbf0716d3df7e2a9a9f634b38fd7b7e120 | from itertools import permutations
def char_has_twin(index: int, string: str) -> bool:
if index >= len(string) - 1:
return False
else:
return string[index] == string[index + 1]
def str_has_twins(string: str) -> bool:
return any(char_has_twin(index, string) for index in range(len(string))... |
13,966 | 8b2bdaabae9703abddf94969328cc143d25b8145 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
browser.get('https://gabrielecirulli.github.io/2048/')
htmlElem = browser.find_element_by_tag_name('html')
while True:
htmlElem.send_keys(Keys.UP)
htmlElem.send_keys(Keys.RIGHT)
htmlElem.send_keys... |
13,967 | e6412ab9efcf524c13eb92caacded28bc8af8ba4 | from rest_framework import serializers
from .models import AdvertPost, Services, StudioProfile, CreativeProfile, Review, Booking, User
from django import forms
from django.contrib.auth import authenticate
# Studio
class UserSerializer(serializers.ModelSerializer):
# user objects
email = forms.EmailField(max... |
13,968 | 4a7e81f4acd67b33a024e8d1553c8890c1958bd5 | import math
def raizCuadrada(listaNumeros):
"""
la funcion devuelve una lista con la raiz cuadrada
de los elementos numericos pasados por parametros en
otra lista
>>> lista=[]
>>> for i in [4, 9, 16]:
... lista.append(i)
>>> raizCuadrada(lista)
[2.0, 3.0, 4.0]
"""
return [math.sqrt(n) for n in listaN... |
13,969 | 56da46b4deaaafc1e6385cad6af11ac4c42f3e02 | # AST443 Lab 0 Data Analysis for part 4.3
# September 7, 2018
# Imports
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from astropy.io import fits
from scipy import stats
from scipy.stats import norm
# Load Lab constants
info = {}
for line in open('inputs.txt'):
li=li... |
13,970 | 4cfe584bc57992df1d684de0e7c6289e914fca24 | import src.config.waypoints as wp
from src.track.track import Track
from src.ui.main_view import MainView
class App:
def __init__(self, headless_mode=False):
self.headless_mode = headless_mode
# Init tracks
self.reinvent_2018 = Track(name="Reinvent 2018", waypoints=wp.REINVENT_2018, trac... |
13,971 | 06f1ad02a1ab34fc944dd3aeb4345e7eef5bad5d | from influxdb import InfluxDBClient
from influxdb.client import InfluxDBClientError
import sched
import time
import random
import sys
def parse_args():
import optparse
usage="%prog [options] ts_relay_file_name.\nNote: requires exactly one filename"
parser = optparse.OptionParser(usage=usage)
parser.a... |
13,972 | 6a27464f24615df8679a39e810b9332e789d2e60 | import serial
ser=serial.Serial("COM21")
while True:
a=input("please type your cmd here, q for quit, e for remote quit.")
print(a)
if a=='q':
break
ser.write(a.encode())
|
13,973 | 191ef34ce0a07167678d0d20e1498ee11c77ffe8 | import yaml
import json
import sys
INPUT_NAME = sys.argv[1]
if INPUT_NAME[-5:] != ".yaml":
print("FIle is not yaml")
sys.exit(1)
OUTPUT_NAME = INPUT_NAME[:-5] + ".json"
print("Outputing to %s" % OUTPUT_NAME)
with open(INPUT_NAME) as input:
with open(OUTPUT_NAME, 'w') as output:
o = yaml.load(input... |
13,974 | 3623d3fdef2b1907c2de5975b4394b4a7f98194b |
from typing import get_args
class Node:
def __init__(self):
self.nodes = [None]*26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = Node()
def get_index_of_letter(self, value):
return ord(value.lower()) - ord('a')
def getNode():
return... |
13,975 | e37b75537a3c3ba4e82ff9279c6679f738c6bc5a | """
Robert Graham (rpgraham84@gmail.com)
Project Euler
Multiples of 3 and 5
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Answer:
233168
"""
def problem_1():
re... |
13,976 | cf502f6036c3639314f62b56571e35f928fe45af | # FPL Model -- shortened
import pandas as pd
import requests, json
# requests is a python library that provides useful methods for api requests and webscraping
r = requests.get('https://fantasy.premierleague.com/drf/bootstrap-static')
data = r.json()['elements']
pd.set_option('display.max_columns', 60)
pd.options.d... |
13,977 | d7c684ff41c1b4dfeab48e42a9a3951cc1661378 | import miscut
from .scheduleimport import ScheduleImport
|
13,978 | 77037096ed17579026e14c9c3e91091baf527a13 |
import sys
sys.path.append("/netpool/work/gpu-3/users/malyalasa/New_folder")
from tensorflow.keras import layers
from tensorflow.keras import models
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.regularizers import l1,l1_l2,l2
from tensorflow.python.keras.regularizers import L1
from ... |
13,979 | 943abcfe93b4340db238a1f0cd7d83c89096056c | from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import os
import os.path as osp
import shutil
from PIL import Image
import cv2
from .iotools import mkdir_if_missing
def read_labels(label_path,index_file):
"""to write"""
got_img = False
labels = 0
if no... |
13,980 | afc57de39cb11b59be949e07f166b9b5bf8e3d85 | from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
class Command(BaseCommand):
help = "Sends an email through the framework to an address specified on the command line."
args = "<email email...>"
can_import_settings = True
def handle(self, *args, **kwar... |
13,981 | aa333354f05b1604a27fd42b618c3db7a746d3d4 | import numpy as np
import matplotlib.pyplot as plt
import sys
import glob
from os import path
for mask in sys.argv[1:]:
for file in glob.glob(mask):
fname = path.split(file.split('.')[0])[1]
data = np.loadtxt(file, skiprows=1)
titles = open(file, 'r').readline().split()[1:]
nums = ... |
13,982 | 1f842c98a6257ddba5c16285daf3e693386fb4d8 | def produce(c):
print("--3、启动生成器,开始执行生成器consumer--")
c.send(None) # 3、启动生成器,开始执行生成器consumer
print("--6、继续往下执行--")
n = 0
while n < 5:
n += 1
print("[Producer]: producing {} ..".format(n))
print("--7、第{}次唤醒生成器,从yield位置继续往下执行!--".format(n + 1))
r = c.send(n) # 第二次唤醒生成器... |
13,983 | 4646e19bf3b3a8bd5c42d2e9857406ee4d3687a5 | from scipy.optimize import minimize
from scipy.spatial.distance import directed_hausdorff
import matplotlib.pyplot as plt
import numpy as np
import math
from aeropy.CST_2D import CST
from aeropy.CST_2D.fitting import fitting_shape_coefficients, shape_parameter_study
directory = './'
filename = 'naca641212_upper.txt'
... |
13,984 | 773d49ff3a79f308724d9203316b0d01403271dd | """
ColorHelper utils
Copyright (c) 2015 - 2017 Isaac Muse <isaacmuse@gmail.com>
License: MIT
"""
import re
import decimal
from . import csscolors, pantone, ral
from .rgba import RGBA, round_int, clamp
FLOAT_TRIM_RE = re.compile(r'^(?P<keep>\d+)(?P<trash>\.0+|(?P<keep2>\.\d*[1-9])0+)$')
COLOR_PARTS = {
"percent"... |
13,985 | 49268ac88699b24de8bad24b4a14f5d270d8b349 | #!/usr/bin/python3.4
# -*- coding=utf-8 -*-
import crypt
import os
def decrypto_hash(hashpassword, passwd_dict_file):
hashpassword_list = hashpassword.split('$')
salt = '$'+ hashpassword_list[1] + '$' + hashpassword_list[2] + '$'
#读取盐
#$1$f6y4$1Lev506HhZ0LE.IR6jRB.0
#$1$f6y4$
#print(salt)
passwds = open(passw... |
13,986 | d706c14a42f7dc8b14e7811e4b7da8f9dc7e69ad | #This file is based on:
#https://swf.com.tw/?p=1188
#https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python3
import serial
import serial.tools.list_ports
comlist = serial.tools.list_ports.comports()
connected = []
for element in comlist:
connected.append(element.device)
print("Co... |
13,987 | d21587473fa545b82691e8ab6bd2ddf3d7d8bc4c | from tri import *
T = [7, 5, 1, 2, 4, 3]
print(tri_bulle(T))
T = [3, 7, 1, 2, 2, 3]
print(tri_bulle(T))
|
13,988 | 8e6e4a0350519e35267692f52a717c9d8d424900 | import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from sklearn import metrics
# Initialize network parameters.
def init_network(model, method='kaiming', exclude='embedding', seed=123):
for name, w in model.named_parameters():
if exclude not in name:
... |
13,989 | e9d9b5c16d47f26faffec3cf56965d97e04997fc | from django.shortcuts import render
from django.views.generic import TemplateView
from ..models import Principal, Shipper
from django.shortcuts import redirect
from django.urls import reverse, reverse_lazy
from django.db.models import Q
from django.contrib import messages
from django.contrib.auth.decorators import log... |
13,990 | c35f52d5888313ab271f5d780bad6f981f3c754f | salario = float(input("Digite o valor do seu salário: "))
despesas = float(input("Digite o valor das suas despesas: "))
sobra = salario - despesas
poupanca = 1000000 / sobra
num_arredondado = poupanca + 1
anos = num_arredondado / 12
meses = num_arredondado % 12
print(f"Você se tornará um milionário em {anos:.00f} anos ... |
13,991 | f11386ab35818fda8ab812517c26e413c9aea182 | # Generated by Django 2.1 on 2018-09-18 12:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('train_ticket', '0004_auto_20180914_2109'),
]
operations = [
migrations.AddField(
model_name='stations',
name='station_... |
13,992 | b855cd3fb0d07388c15091d9f7f4719f3e5c9085 | mile_distances = [1.0, 6.5, 17.4, 2.4, 9]
kilometer_distances = list(map(lambda x: x * 1.6, mile_distances))
print(kilometer_distances)
# [1.6, 10.4, 27.84, 3.84, 14.4] |
13,993 | 3b676e2a0d42459808502848ed1ebf452b062d78 | N=int(input())
divisions=[]
for i in range(1,N//2+2):
if N % i == 0 :
divisions.append((i,N//i))
print(divisions)
results=[]
for divs in divisions:
results.append(abs(divs[0]-divs[1]))
print(min(results))
|
13,994 | 91e5e92053f386328d698280a7f30dfa7f2eaa3c | import serial
import time
import datetime
import os
import mysql.connector as mariadb
import array
import struct as struct
import logging
from struct import *
# Track status of each servo
actuatorStatus = False
motorStatus = False
# Serial objects that control serial communication with HASP and the Arduino. To be used... |
13,995 | d39c77b9a080ef63061f0e788f815994aa364de7 | with open("small_vocab_en") as xh:
with open('small_vocab_fr') as yh:
with open("en_fr","w") as zh:
#Read first file
xlines = xh.readlines()
#Read second file
ylines = yh.readlines()
#Combine content of both lists
#combine = list(zip(ylines,xlines))
#Write to third file
... |
13,996 | 2add66cf1b6e24819653f1f9808aaa5e173dd5ba | from .dbscan import DBSCAN
__all__ = ["DBSCAN"]
|
13,997 | 7909734a02706017f8efc723ad6854ac99e32a88 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 9 00:17:28 2016
@author: Andres Mendez Vazquez
@ Licencense BSD 3
"""
#import matplotlib.pyplot as plt
import numpy as np
from KFamily import KFamily
def DataGeneration(cov, mean, number):
# Give me a series of pts with N
x,y = np.random.multivariate_normal(... |
13,998 | 2d72ae8b619aa69f7d28625292be95e2d1fa1abb | import json
import logging
import sys
from logging.handlers import RotatingFileHandler
from os.path import join, exists
from shutil import rmtree
def get_domain():
from .core.models import Configuration
return Configuration.get('domain', 'company.com')
def get_menu_links():
from .core.models import Con... |
13,999 | 5efd5032e24861e52800fa1f6d419a527cc103dd | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from AllList import ObverseList_285 as ObverseList
from AllList import ReverseList_285 as ReverseList
def mul(a,b):
if a== 0 or b == 0:
return 0
c = ObverseList[(ReverseList[a]+ReverseList[b])%255]
return c
def div(a,b):
if a== 0:
return 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.