index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
3,200 | 7c004cb0c9eefa5e88f5085fb3b2878db98d2b20 | """
This class runs the RL Training
"""
from __future__ import division
import logging
import numpy as np
from data.data_provider import DataProvider
from episode.episode import Episode
from tracker import TrainingTracker
from tqdm import tqdm
class RLTrainer(object):
"""
Creates RL training object
"""
... |
3,201 | 120021e44f6df9745db35ea2f38f25acecca9252 | # Copyright 2014 Rackspace Hosting
# 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 r... |
3,202 | 09aedd6cab0b8c6a05bbee5b336fcd38aea1f7b9 | # animation2.py
# multiple-shot cannonball animation
from math import sqrt, sin, cos, radians, degrees
from graphics import *
from projectile import Projectile
from button import Button
class Launcher:
def __init__(self, win):
"""Create inital launcher with angle 45 degrees and velocity 40
win i... |
3,203 | 4fbe4d474e10e08eafee3bcc6173f8cd6b797dde | def swap(a,b):
print(a,b)
a=input("enter a value 1 : ")
b=input("enter b value 2 : ")
a,b=b,a
print("the vaalues after swaping the variables are below:")
print("the value of a is : ",a)
print("the value of b is : ",b)
|
3,204 | 501614f9c7df3c862c9951ea343964b6ed47e74a | import requests
import json
base_url = f"https://api.telegram.org/bot"
def get_url(url):
response = requests.get(url)
content = response.content.decode("utf8")
return content
def get_json_from_url(url):
content = get_url(url)
js = json.loads(content)
return js
def get_updates(TOKEN):
... |
3,205 | 63182a8708729606f96794cddb163f707252ba61 | from people.models import Medium, Profile, Staff, Instructor, Student, Alumni, Donation, Address, Award, Reference, Experience, Skill, Education, ImporterUsers
from anonymizer import Anonymizer
class MediumAnonymizer(Anonymizer):
model = Medium
attributes = [
('medium_id', "integer"),
('descr... |
3,206 | d2e8c95dc144aa83128cc815ad145982f64b1819 | #!/usr/bin/env python
from math import factorial
F = [factorial(i) for i in range(10)]
#F[9] * 8 = 2903040 > this means no 8 digit numbers
#F[9] * 7 = 2540160 < this is the maximum that I could think of
total = 0
for i in xrange(10, 2540160):
if sum([F[int(d)] for d in str(i)]) == i:
total = total + i
p... |
3,207 | 4193fa992d06890afb660c072842cf1b85a43774 | import glob
import logging
import os
import sqlite3
from aiogram import Bot, Dispatcher, executor, types
TOKEN = '1772334389:AAE5wv8gssOFOgxQjQwKk7rUSKQHr6NTjus'
logging.basicConfig(level=logging.INFO)
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
path1 = 'C:\\Users\\const\\PycharmProjects\\t'
conn = sqlite3.connect('... |
3,208 | d04506e67071abf36d43a828d90fbe0f14230103 | # filename: cycle_break.py
# for i in range(1, 101):
# if i % 3 == 0 and i % 8 == 0:
# print(i)
# break
num = 1
while num <= 100:
if num % 4 == 0 and num % 6 == 0:
print(num)
break
num += 1 |
3,209 | e7699bb3f6080c78517f11445e2c48a0e40f3332 | class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.minheap = []
self.maxheap = []
def addNum(self, num: int) -> None:
heapq.heappush (self.maxheap ,-heapq.heappushpop(self.minheap , num) )
if len(self.maxheap) > len... |
3,210 | af7af5d1048d2b0968e831aad89d5baf30cab608 | '''
Copyright (c) 2021, Štěpán Beneš
The purpose of this script it to take the 5 BSE and 5 SE hand-picked prototype
images and turn them into the same shape and format as the rest of the data.
Prototype images are resized to 768x768, the info bar is cropped off. Afterwards
the images are normalized to float32 in ran... |
3,211 | 007cce815f3ad4e47593ff00ff2e73d5d9961d9e | #!/usr/bin/env python
# Copyright (c) 2019, University of Stuttgart
# All rights reserved.
#
# Permission to use, copy, modify, and distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright
# notice and this permission notice appear in all copies.
#
# THE ... |
3,212 | 0a3e0eeda14e42bfff7797b3c42a0aebd9a72ade | import numpy as np
print(np.random.binomial(10,0.5,1)) |
3,213 | 80be5f49a179eebc4915bf734a8e362cc2f2ef7c | #
# @lc app=leetcode id=14 lang=python3
#
# [14] Longest Common Prefix
#
# https://leetcode.com/problems/longest-common-prefix/description/
#
# algorithms
# Easy (34.95%)
# Likes: 2372
# Dislikes: 1797
# Total Accepted: 718.5K
# Total Submissions: 2M
# Testcase Example: '["flower","flow","flight"]'
#
# Write a f... |
3,214 | f7f96b19bdc20f732566709a7801002fe49d49eb | '''
Character class
'''
import pygame
from time import sleep
class Character:
def __init__(self, screen, side_length, border_width, valid_points, start_point, end_point, current_position, a_colour, na_colour,\
keys=None, k_colour=None):
self.screen = screen # pygame screen
self.side_length = side_length # ... |
3,215 | b5949b40d731178bdbab776af8877921dcdfbf15 | class _ProtectedClass:
pass
class MyClass:
pass
class OtherClass(MyClass):
pass
def _protected_fun() -> MyClass:
return variable # noqa: F821
def my_fun() -> MyClass:
return variable # noqa: F821
def my_fun2() -> MyClass:
return variable # noqa: F821
variable: MyClass
variable_wit... |
3,216 | 4f19eed272c12be137df92bfd3c72e978408c974 | #!/usr/bin/python3
__author__ = "yang.dd"
"""
example 090
"""
# list
# 新建list
testList = [10086, "中国移动", [1, 2, 3, 4]]
# 访问列表长度
print("list len: ", len(testList))
# 切片
print("切片(slice):", testList[1:])
# 追加
print("追加一个元素")
testList.append("i'm new here!");
print("list len: ", len(testLi... |
3,217 | daa287eeb967d47c9a8420beccf531d9c157e925 | from setuptools import setup
setup(name='discord-ext-menus',
author='TierGamerpy',
url='https://github.com/TierGamerpy/discord-ext-menus',
version= 0.1,
packages=['discord.ext.menus'],
description='An extension module to make reaction based menus with discord.py',
install_requires=['... |
3,218 | 4c43c181dbba1680e036750a2a2ea1185bbe91da | from django.shortcuts import render
from rest_framework import generics
from rest_framework import mixins
from django.contrib.auth.models import User
from rest_framework import permissions
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.request import Req... |
3,219 | c8dc143c09aa7f677167a4942ae1c4a0fbf75128 | from django import forms
from .models import GetInTouch
class GetInTouchForm(forms.ModelForm):
class Meta:
model = GetInTouch
fields = '__all__' |
3,220 | 3eaced9609c7adfa5457d7dcad8b2dfaeb697b16 | ##############################################
# Binary Tree #
# by Vishal Nirmal #
# #
# A Binary Tree ADT implementation. #
##############################################
class BinaryTree:
def __init_... |
3,221 | 56c5c515de8490f2e3516563e037c375aba03667 | #!/usr/bin/python
# ~~~~~============== HOW TO RUN ==============~~~~~
# 1) Configure things in CONFIGURATION section
# 2) Change permissions: chmod +x bot.py
# 3) Run in loop: while true; do ./bot.py; sleep 1; done
from __future__ import print_function
import sys
import socket
import json
import time
# ~~~~~==... |
3,222 | 59596c69df6a2c453fd147a9c8a2c7d47ed79fb3 | # Generated by Django 2.1.2 on 2018-10-26 12:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0007_auto_20181010_0852'),
('accounts', '0004_playercards'),
]
operations = [
migrations.RenameModel(
old_name='PlayerCa... |
3,223 | 18689741a33e6d17e694ee0619a1f36d8d178cbb | from django.shortcuts import *
from shop.models import *
from django.db import transaction
from django.core.exceptions import *
@transaction.atomic
def computers(request):
ctx = {}
computer = Computer.objects.all()
ctx['brand'] = Brand.objects.all()
if request.method == 'POST':
if request.POST['computer_i... |
3,224 | 4989db28db0f823a54ff0942fbc40fc4640da38f | #!/usr/bin/python
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
3,225 | 098488fd10bcf81c4efa198a44d2ff87e4f8c130 | # 約分して、互いに素な(1,3) (3,1)のようなペアを作りカウントする
# 正のグループと負のグループを別々に管理
# 正のグループの相手が負のグループに存在した場合、
# どちらかのグループから好きなだけ選ぶか、どちらも選ばないかしかない
# 誰ともペアにならなかったグループの個数を全て足してP個だとして、2^P通りを掛ける
# (0,0)については、その中から1つ選ぶか、選ばないかしかない
import sys
readline = sys.stdin.readline
N = int(readline())
import math
zeropair = 0
zeroa = 0
zerob = 0
from coll... |
3,226 | 7d6196268b85861e76efaa53e14976f2eae09405 | import pandas as pd
df1 = pd.read_csv('Tweets1.csv', names=['tweet'])
df2 = pd.read_csv('Tweets2.csv', names=['tweet'])
df3 = pd.read_csv('Tweets3.csv', names=['tweet'])
df = pd.concat([df1,df2,df3], axis=0, join='outer', ignore_index=False, keys=None,levels=None, names=None, verify_integrity=False, copy=True)... |
3,227 | 72ce7c48c9d1a7bcdbaead12648d03970663a11e | import tornado.web
import tornado.escape
from torcms.core.base_handler import BaseHandler
from owslib.csw import CatalogueServiceWeb
from owslib.fes import PropertyIsEqualTo, PropertyIsLike, BBox
class DirectorySearchHandler(BaseHandler):
def initialize(self):
super(DirectorySearchHandler, self).initializ... |
3,228 | bae4eb94d561f7aa810718840ff7c2de52cb0d6f | import os
import unittest
import json
from flask_sqlalchemy import SQLAlchemy
from app import create_app
from models import *
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
# auth tokens should be updated before running tests,
# make sure update the tokens in setup.sh
# read the README to kno... |
3,229 | 53cf6e97c3b71b1063d5b6bce5aa444933b69809 | from dagster import job, op
@op
def do_something():
return "foo"
@job
def do_it_all():
do_something()
|
3,230 | 9cc64edc81ab39b0ab2cd47661c9809545b03ac6 | '''
Twitter settings
Input your app credentials below
https://apps.twitter.com
'''
# consumer key
CONSUMER_KEY = ''
# consumer secret
CONSUMER_SECRET = ''
'''
App settings
'''
# Where to save tokens (JSON)
TOKENS_PATH = '/tmp/twitter-tokens.json'
# Redirect-back to URL after authenticated (optional)
REDIRECT_TO = ''... |
3,231 | 8bd5eff12e68f7145676f5e089b51376a82ab489 | _base_ = "../model.py"
model = dict(
type="ImageClassifier",
task="classification",
pretrained=None,
backbone=dict(),
head=dict(in_channels=-1, loss=dict(type="CrossEntropyLoss", loss_weight=1.0), topk=(1, 5)),
)
checkpoint_config = dict(type="CheckpointHookWithValResults")
|
3,232 | 36257340ebbc6bd2c7fa5995511b2c859f58f8e5 | from keras.layers import Dense, Activation, Dropout
from keras.utils.visualize_util import plot
from keras.models import Sequential
from emotions import FER2013Dataset
_deep_models = {}
def deep_model(model_name):
def wrapper(cls):
_deep_models[model_name] = cls
return cls
return wrapper
... |
3,233 | cc99811321083147540a00e8029b792c8afc2ada | import json
import requests
import random
import boto3
from email.parser import BytesParser, Parser
from email.policy import default
##################################
endpoint = 'https://5295t8jcs0.execute-api.us-east-1.amazonaws.com/Prod'
##################################
def get_msg_body(msg):
type = msg.get_... |
3,234 | 8f311e15c15fe3309218dfaed5eefa4a8fc3f453 | # GERALDO AMELIO DE LIMA JUNIOR
# UNIFIP - Patos
# 05 de março de 2020
# Questão 08 - Escreva um programa que leia um valor inteiro e calcule o seu cubo.
n = int(input('Digite um numero:'))
t = n*3
print('O triplo de {} vale {}.'.format(n, t))
|
3,235 | d443e9054481984d5372343170254268dca8a3b1 | #!/usr/local/bin/python3
import time, json, os, sqlite3, uuid, json, base64, sys
import requests as http
import numpy as np
from os.path import isfile, join
from datetime import date, datetime
from argparse import ArgumentParser
PRINTER_IP = ""
FRAMERATE = 30
TIMELAPSE_DURATION = 60
TIMELAPSE_PATH = "timelapses"
DATA... |
3,236 | 33ec822f6149a57244edf6d8d99a5b3726600c2e | 'Attempts to use <http://countergram.com/software/pytidylib>.'
try:
import tidylib
def tidy(html):
html, errors = tidylib.tidy_document(html, options={'force-output': True,
'output-xhtml': True, 'tidy-mark': False})
return html
except ImportError:
def tidy(html):
return html
|
3,237 | 14761cc2593556f58a7dc4e499db71456d7c7048 | import numpy as np
import cv2
from matplotlib import pyplot as plt
from matplotlib import cm
import imageio
# # Backpack values
# fx = 7190.247 # lense focal length
# baseline = 174.945 # distance in mm between the two cameras (values from middlebury)
# units = 0.001 # depth units... |
3,238 | 4572e243f75ad92c04f5cdc0b454df7389183a6a | import urllib.request
def get_html(url):
"""
Returns the html of url or None if status code is not 200
"""
req = urllib.request.Request(
url,
headers={
'User-Agent': 'Python Learning Program',
'From': 'hklee310@gmail.com'
}
)
resp = urllib.reques... |
3,239 | f100757fcb1bef334f9f8eacae83af551d2bac5b | from chalicelib.utilities import *
def Error(app):
@app.route('/errors', cors=True, methods=['POST'])
@printError
def errors():
request = app.current_request
data = request.json_body
print(data)
return data |
3,240 | 082e3350c5827ff2ca909084f2d6a206ae21a7e6 | #!/usr/bin/env python
# coding=utf-8
operators = ['-', '~', '++', '--', '*', '!', '/', '*', '%', '+', '-',
'>', '>=', '<', '<=', '==', '!=', '&&', '||', '=']
types = ['int ', 'double ', 'float ', 'char ']
toDelete = types + ['struct ']
toRepleace = [('printf(', 'print('), ('++', ' += 1'), ('--', ' -= 1')... |
3,241 | f253816d08407950caad28f1ce630ac2b099aa70 | # coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# 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 applicab... |
3,242 | 69721dca0f5d8396e330696cde52bfabad33c895 | from sikuli import *
import logging
import myTools
from datetime import date
import reports_Compare
#---------------------------------------------------#
def fSet_BillDate(pMonth):
#---------------------------------------------------#
if pMonth == 13:
pMonth = 12
logging.debug('- change bill dat... |
3,243 | 9c935e9ef298484d565256a420b867e800c3df55 | """ Contains different comparator classes for model output data structures.
"""
import copy
def tuple_to_string(tuptup):
""" Converts a tuple to its string representation. Uses different separators (;, /, |) for
different depths of the representation.
Parameters
----------
tuptup : list
... |
3,244 | a7a219e9ea5cdec004ef936958994ed1f5a96103 | import xlrd
def get_rosters_from_excel(django_file):
workbook = xlrd.open_workbook(file_contents=django_file.read())
worksheet = workbook.sheet_by_name('Match_Rosters')
num_rows = worksheet.nrows - 1
cur_row = -1
rosters = []
while cur_row < num_rows:
cur_row += 1
if workshe... |
3,245 | e7060658ae1838b0870b2a3adb61c9f8d78c93c7 | #!/usr/bin/env python3
import sys
all_neighbors_coord = []
for i in range(-1, 2):
for j in range(-1, 2):
for k in range(-1, 2):
if i != 0 or j != 0 or k != 0:
all_neighbors_coord.append((i, j, k))
def add_coord(c1, c2):
return (c1[0] + c2[0], c1[1] + c2[1], c1[2] + c2[2])
... |
3,246 | e28cca2273e1c3ad4b8a955843e7dfb45c00694c | # -*- coding:utf-8 -*-
import math
r = float(input())
print("{0:f} {1:f}".format(r*r*math.pi,2*r*math.pi)) |
3,247 | 1d314a04625cfadf574f122b95577c1e677a8b35 | #! /usr/bin/env python
from thor.tree import TreeNode
class Solution(object):
def postorder_traversal(self, root: TreeNode):
if not root:
return []
else:
return self.postorder_traversal(root.left) + self.postorder_traversal(root.right) + [root.val]
|
3,248 | f680503488a2780624b28e49b045aad75506d8c5 | class SensorReadings:
def __init__(self, sense_hat):
self.temprerature_humidity_sensor = sense_hat.get_temperature_from_humidity()
self.temperature_pressure_sensor = sense_hat.get_temperature_from_pressure()
self.humidity = sense_hat.get_humidity()
self.pressure = sense_hat.get_pressure()
def prin... |
3,249 | b791afec1c9fb214d1f3b4ec0ec67f905d96aabf | # link https://deeplizard.com/learn/video/QK_PP_2KgGE
import gym
import numpy as np
import random
import time
from IPython.display import clear_output
# setup the env
env = gym.make("FrozenLake8x8-v0", is_slippery=False)
observation = env.reset()
# setup the q-table
action_space_size = env.action_space.n
state_space_... |
3,250 | d0a6bfb729a150863303621a136ae80e96ae32d0 | from tilBackend.celery import app
import smtplib
import email
import ssl
#librerias pruebas
from celery.task.schedules import crontab
from celery.decorators import periodic_task
from celery.utils.log import get_task_logger
from celery import Celery
@app.task
def correo():
try:
port = 587
smtp_serve... |
3,251 | 8dae8a89d08bc522f9a5fdde8aeb9e322fafcbec | import pymongo
import os,sys
import re
from db_User import *
from db_Event import *
class ClassRoom:
# 链接本地客户端
__myclient = pymongo.MongoClient("mongodb://localhost:27017")
# 创建数据库
__mydb = __myclient["MMKeyDB"]
# 创建新的集合
__mycol = __mydb["ClassRoom"]
# 判断是否输入id或是输入name,如果有输入则转译
def ... |
3,252 | 049950bd4bbf7903218bb8fb3a4c91492d6af17b | # Copyright 2015 gRPC authors.
#
# 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... |
3,253 | 55df8d13ddf28f7b0477329bee743471a0780f24 | import os
from app_web import sg
from sendgrid.helpers.mail import *
import pdfkit
from models.user import User
from models.expense import Expense
from models.statement import Statement
from models.category import Category
import tempfile
import subprocess
from .aws_uploader import upload_image_to_s3
import datetime
fr... |
3,254 | b09d0806dfc6f4badfd9f2ac9c3f6d17d3df8e8c | from features.steps.web.test_home_page import *
from features.steps.mobile.test_home_page import *
from features.steps.web.test_login_page import * |
3,255 | 4e98ebd040297cb9472368478452bc484e0aaa04 | water = 400
milk = 540
coffee = 120
cups = 9
money = 550
def buying():
global water
global coffee
global cups
global milk
global money
choice_coffee = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:")
if choice_coffee == "1":
... |
3,256 | 9543992e1b115f83640a07c4d4372be0fb465199 | # Reddit API feed
import praw
import sys
import os
def main():
if os.getenv("REDDIT_CLIENT_ID") is None:
print "Set your Reddit environment variables:"
print "REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET"
sys.exit()
client_id = os.environ['REDDIT_CLIENT_ID']
client_secret = os.environ... |
3,257 | 29dc940292a6805aabfa5bed22bb75d31140c83f | def check_bit4(input):
mas=0b1000
desired=input & mas
if desired>0:
return "om"
else :
return "off"
|
3,258 | 846a42a997539a45576d3ecbe0bd290e00b55935 | from output.models.sun_data.ctype.content_type.content_type00401m.content_type00401m_xsd.content_type00401m import (
A1,
A,
)
__all__ = [
"A1",
"A",
]
|
3,259 | 4c42bad4197b51be0e9d18307c7b954a29281fe1 | #Exercise 5
#Define with names stair1, stair2, and stair3 (from bottom up to top), and insert within the building model, the 3 stair models of the building. |
3,260 | 6829f7bcbc1b12500795eec19829ff077502e270 | import os
import math
def get_datas():
filename = None
while True:
filename = input('Please enter filename:')
if not filename.strip():
print('Filename is empty!')
continue
if not os.path.exists(filename):
print('File is not exists!')
conti... |
3,261 | 50fa8852f74f4d2428fb238a86dd1feedb210877 | # Umut Cakan Computer Science S006742
# Fibonacci list. First and second terms are static.
fib_list = [0, 1]
# Current index.
CURRENT_INDEX = 2
# Function for the checking input is a Fibonacci number or not.
def check_fibonacci_number():
global CURRENT_INDEX
# Get the fibonacci numbers that are less or equal ... |
3,262 | 8981d53641d22430efb2dd43401fab562b8a95ed | import socket
comms_socket1 = socket.socket()
comms_socket2 = socket.socket()
comms_socket1.bind(("120.79.26.97",55000))
comms_socket2.bind(("120.79.26.97",55001))
comms_socket1.listen()
user1,address1 = comms_socket1.accept()
comms_socket2.listen()
user2,address2 = comms_socket2.accept()
while True:
send_date = ... |
3,263 | 1c0f194bbdc6f7e3e4feb114e521aa958f11e83e | from typing import List
from pydantic import BaseModel
class BinBase(BaseModel):
name: str = None
title: str = None
class BinCreate(BinBase):
owner_id: int
password: str
class Bin(BinBase):
id: int
# TODO: token?
class Config():
orm_mode = True
class UserBase(BaseModel):
... |
3,264 | 5261ae90a67e2df8dd1c679a8046ee3e0cbc6221 | '''
Module for handling configurable portions of tools
'''
from json import load
default_file_loc = 'config.json'
config = None
def loadConfiguration(fileloc):
'''Loads configuration from file location'''
global config
with open(fileloc, 'r') as file_:
conf = load(file_)
if config is None:
... |
3,265 | 838279b4f8d9e656c2f90ff06eaff3bd9c12bbef | import pygame
from math import sqrt, sin, cos
from numpy import arctan
from os import path
# try these colors or create your own!
# each valid color is 3-tuple with values in range [0, 255]
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
WHITEGRAY = (192, 192, 192)
RED = (255, 0, 0)
MIDRED = (192, 0, 0)
DARKRED = (128, 0, 0... |
3,266 | 624027373f53f62ededc40bfc859f28b5a83ca04 | #!/use/bin/python
import os, sys
from io import BytesIO
from pathlib import Path
from flask_config import app
from flask import send_file
from PyPDF2 import PdfFileReader, PdfFileWriter
def rotate_pdf(working_dir, filename, rotation):
os.chdir(working_dir)
output_name = 'pages'
rotate_pdf_pages(filename, rotati... |
3,267 | 1fc1d2e1a7d18b1ef8ee6396210afe47a63ab09f | import sys
import os
from pyparsing import *
import csv
def parse_cave_details(details):
##########################################################################
# Define the Bretz Grammar.
# Sample cave description:
# Boring Caverns SE1/4 NW1/4 sec. 16, T. 37 N., R. 10 W., Pulaski County ... |
3,268 | 4524dd5f5cddd475ca39fea7ec94fa3c1df6bd2e | from sharpie import Sharpie
class SharpieSet():
def __init__(self):
self.sharpies = []
self.usable_sharpies = []
self.usable_sharpies_count = 0
def add_sharpie(self, sharpie: Sharpie):
self.sharpies.append(sharpie)
def count_usable(self):
for i in self.sharpies:
... |
3,269 | 846682072a125c76fc9ffa011109abce7c3bb5d7 | from bs4 import BeautifulSoup, CData
import requests,sys,csv,json,os, urllib.request, re
import json
url2 = "http://ufm.edu/Estudios"
def estudios(Minisoup):
print("2.Estudios")
#now navigate to /Estudios (better if you obtain href from the DOM)
try:
html_content = requests.get(url2).text
except:
print(... |
3,270 | 446c438b79f9957289fa85f21516c13d67e2cfaf | from mesa import Model
from mesa.space import SingleGrid
from mesa.time import BaseScheduler, RandomActivation, SimultaneousActivation
from pdpython_model.fixed_model.agents import PDAgent
from mesa.datacollection import DataCollector
class PDModel(Model):
schedule_types = {"Sequential": BaseScheduler,
... |
3,271 | 2fb95fa2b7062085f31c6b1dbb8c1336c3871e93 | #
# PySNMP MIB module CISCO-L2NAT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-L2NAT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:47:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
3,272 | ceab21e41adf171e99e6c3c8541c418d82db6168 | class Figure:
area = 0
def __new__(cls, *args):
if cls is Figure:
return None
return object.__new__(cls)
def add_area(self, other):
if isinstance(other, Figure):
return self.area + other.area
else:
raise ValueError("Should pass Figure as... |
3,273 | 5a5b2d0ade5b66981218b4ecf15a2253b7d665f9 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Script for converting the new csv files to the desirable json format
'''
import codecs
import json
import re
def creeper():
'''
Settings for creeper file
'''
ccPrefix = False
inFilename = u'creeper.csv'
outFilename = u'Creeper.json'
mappingFil... |
3,274 | d8ea396ff8514cc10e02072ea478f0276584153d | def heapify(lst, index, heap_size):
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and lst[left_index] > lst[largest]:
largest = left_index
if right_index < heap_size and lst[right_index] > lst[largest]:
largest = right_index
if... |
3,275 | 860908126d473e6c4ed070992a1b518683fd4c27 | ###############################################################
## File Name: 11_exercise.py
## File Type: Python File
## Author: surge55
## Course: Python 4 Everybody
## Chapter: Chapter 11 - Regular Expressions
## Excercise: n/a
## Description: Code walkthrough from book
## Other References: associated files... |
3,276 | 8cd234c2ec1b36abd992cc1a46147376cc241ede | def non_dupulicates_lette(word):
text = list(word);
print(text)
i=0
for i in range(len(text)):
for k in text:
print(c)
def has_dupulicates(word):
d= dict()
for c in word:
if c not in d:
d[c]=1
else:
d[c]+=1
... |
3,277 | dee7b12862d02837fbb0f2310b136dd768ca7bab | import time
import pickle
class BayesNetClassifier:
def __init__(self, train_file, out_file):
self.train_file = train_file
self.out_file = out_file
self.word_count_loc = {}
self.word_probs = {}
self.l_probs = {}
self.word_counts = {}
self.common_wo... |
3,278 | 86177dfa9b8bed5916703edcc16ea4d01cbabf84 | import tkinter as tk
import random
import numpy as np
import copy
import time
#################################################################################
#
# Données de partie
NbSimulation = 20000
Data = [ [1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0... |
3,279 | 4b3664153940b064b424bd77de473a6409437f88 | import sys
'''
Given a string, does the string contain an equal number of uppercase and
lowercase letters? Ignore whitespace, numbers, and punctuation. Return the
string “true” if balanced or the string “false” if not balanced.
'''
for line in sys.stdin:
lower = 0
upper = 0
# Count number of lowercase a... |
3,280 | 8cec6778f530cb06e4f6cb2e6e9b6cb192d20f97 | # Generated by Django 3.2.6 on 2021-10-10 17:17
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
3,281 | bf8f7b51b685f0e9131cb4d8a0bfc16ee5ad1263 | import os
from flask import Flask,request
from flask_restful import Resource,Api,reqparse
from flask_jwt import JWT,jwt_required
from resources.Users import UserRegister
from security import authenticate,identity
from resources.items import Item, ItemList
from resources.stores import Store, StoreList
app = Flask(__nam... |
3,282 | ae3198e68d9479605327b729c01fb15eae87ab98 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_visual_coding_2p_analysis
----------------------------------
Tests for `visual_coding_2p_analysis` module.
"""
import pytest
@pytest.fixture
def decorated_example():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
... |
3,283 | 9dbadb2421b04961e8e813831d06abc1ff301566 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class JiayuanItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
person_id = scrapy.Field(... |
3,284 | 9a539fd3ce4e3ff75af82407150ab4b550b255c1 | class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
if(n % 4 != 0):
return True;
return False;
"""main():
sol = Solution();
sol.canWinNim(4);
"""
|
3,285 | 39b07f1a515787e80a1fb822e67e19e2301b894a | import pynucastro as pyna
rl = pyna.ReacLibLibrary()
h_burn = rl.linking_nuclei(["h1", "he4",
"c12", "c13",
"n13", "n14", "n15",
"o14", "o15", "o16","o17","o18",
"f17", "f18","f19",
... |
3,286 | 682495fec200ddad5a68f06bb0ec24e59036e66b | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#######################
# Iterative solution
#######################
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return h... |
3,287 | fbab5826f47163cf82b534d311eae572c5fcd128 | import re
import pandas as pd
import pandas.io.formats.excel
from configparser import ConfigParser
from datetime import datetime
from termcolor import cprint
import os
import shutil
from openpyxl import load_workbook
import numpy as np
class pairtron():
def affiliation_cleaner(self, affiliation):
# print(... |
3,288 | 8bbc929e2ff2321b97195031fa675fbdab269fcb | """
SUMMARY
Auxiliary functions, provided here to avoid clutter
"""
"""
Transforms a point (P = [x, y]) using the x, y intervals (Δxy = [Δx, Δy]) into the corresponding discrete point (D = [xd, yd])
loc_min = [x_min, y_min]
"""
def discretize_location(P, loc_min, Δxy):
x_from_start = P[0] - loc_min[0]
y_from... |
3,289 | e99c158e54fd86b00e4e045e7fb28d961089800d | import os
import hashlib
import argparse
def hashfile(path, blocksize=65536):
afile = open(path, 'rb')
hasher = hashlib.md5()
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
afile.close()
return hasher.hexdigest()
def make_duplic... |
3,290 | a8f2d527e9824d3986f4bb49c3cc75fd0d999bf7 | from .personal_questions import *
from .survey_questions import *
|
3,291 | 55986f6c2dafe650704660142cf85640e763b26d | #case1
print("My name is Jia-Chi. \nI have an older sister. \nI prefer Coke.\nMy favorite song is \"Amazing Grace\"")
#case2
print('''Liang, Jia-Chi
1
Coke
Amazing Grace''')
|
3,292 | 6ec39aa712c8abe610418e410883ff168d73126d | from sys import stdin
Read = stdin.readline
INF = int(1e9)
n, m = map(int, Read().split())
graph = [[INF] * (n+1) for _ in range(n+1)]
for i in range(1, n+1):
for j in range(1, n+1):
if i == j:
graph[i][j] = 0
for _ in range(m):
a, b = map(int, Read().split())
graph[a][b] = 1
for k i... |
3,293 | d2f77afd0d282b1fa4859c5368c9d2c745a5625e | #!/usr/bin/python
#
# Copyright 2017 Steven Watanabe
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
from MockProgram import *
command('strip', '-S', '-x', input_file('bin/darwin-4.2.1/release/target-os-darwin/t... |
3,294 | 7413c06a990894c34ee5174d84f0e3bd20abf51f | import sys
import numpy as np
####################################################################################################
### These functions all perform QA checks on input files.
### These should catch many errors, but is not exhaustive.
#####################################################################... |
3,295 | d7c4bee7245dab1cbb90ee68b8e99994ce7dd219 | class Solution:
# @param num, a list of integer
# @return an integer
def longestConsecutive(self, num):
sted = {}
n = len(num)
for item in num:
if item in sted:
continue
sted[item] = item
if item-1 in sted:
sted[item... |
3,296 | 0aec3fbc9f4b9f33aee021fa417c43f0feb0e3d1 | import math
import time
t1 = time.time()
# n(3n-1)/2
def isPentagon(item):
num = math.floor(math.sqrt(item*2//3))+1
if num*(3*num-1)//2 == item:
return True
return False
# n(2n-1)
def isHexagon(item):
num = math.floor(math.sqrt(item//2))+1
if num*(2*num-1) == item:
return True
... |
3,297 | 0d14534b210b13ede4a687e418d05d756d221950 | from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy.settings import CrawlerSettings
from scrapy import log, signals
from spiders.songspk_spider import SongsPKSpider
from scrapy.xlib.pydispatch import dispatcher
def stop_reactor():
reactor.stop()
dispatcher.connect(stop_reactor, sig... |
3,298 | 8650e0f1e7f2ac42c3c78191f79810f5befc9f41 | import pygame, states, events
from settings import all as settings
import gui
def handleInput(world, event):
if event == events.btnSelectOn or event == events.btnEscapeOn:
bwd(world)
if event%10 == 0:
world.sounds['uiaction'].play(0)
# world.shouldRedraw = True
def bwd(world):
if wor... |
3,299 | f2786e445bdf66cf6bb66f4cde4c7b2bf819d8aa |
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import itertools
# Save a nice dark grey as a variable
almost_black = '#262626'
import matplotlib
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
sns.set()
get_ipython().magic('matplotlib inline')
# I... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.