index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
13,200 | 9645174931e3b0f375243fe065b3f8dc8a688650 | import os
from pepys_import.core.formats.rep_line import REPLine
from pepys_import.core.formats import unit_registry
from pepys_import.core.validators import constants
from pepys_import.file.importer import Importer
class ReplayImporter(Importer):
def __init__(
self,
name="Replay File Format Impo... |
13,201 | 097f5ec9fc7179a40c6196832142a16e06f452a2 | import web
import application.models.model_datos as model_datos
render = web.template.render('application/views/', base='master2')
class Insert:
def __init__(self):
pass
def GET(self):
return render.insert()
def POST(self):
formulario = web.input()
id = formulario['... |
13,202 | 1c125c576daa4508ec8a97bb2a3f12e4ff96bbe5 | #from functions_ import addNumbers,subtractNumbers
#addNumbers(12,45)
#from function3 import add3numbers
#add3numbers(12,56,99)
#function that reverses all the words in a sentence which contains a particular letter.
def reverse(string1,b):
words=string1.split(' ')
for i in words:
if b in i:
... |
13,203 | f099cec6fc072abb093d1e9d4bcec4b5af685868 | from django.conf.urls import url, include
from product.views.v1 import product as views
product_urls = [
url(
r'^products/', include(
[
url(
r'^$',
views.ProductListAPIView.as_view(),
name='product-list'
... |
13,204 | cf9c07fed57236230f2357c94715e121083b6510 | from flask import render_template, make_response
from flask_restful import Resource
from flask_login import login_required
class Json(Resource):
@login_required
def get(self):
headers = {'Content-Type': 'text/html'}
return make_response(render_template('json.html'), 200, headers)
|
13,205 | 3b673dfafbee9c6a8fa1c176228d4e4cffd04330 | ''' Initial brute force solution:
Runtime = 40ms, faster than 95.69%
Memory = 12.8MB, less than 50.81%
'''
class Solution(object):
def isPalindrome(self, x):
strX = str(x)
strInvertedX = strX[::-1]
return (strInvertedX == strX) |
13,206 | c8fd7662aa9608cca581b63520092c41f4cd4386 | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
dic = {}
for i in range(len(nums)):
if nums[i] not in dic.keys():
dic[nums[i]] = 1
else:
return nums[i]
|
13,207 | 188fd3d9658c2791edd606f269a310011c19cee0 | """Tools so trivial that tracebacks should not descend into them
We define the ``__unittest`` symbol in their module namespace so unittest will
skip them when printing tracebacks, just as it does for their corresponding
methods in ``unittest`` proper.
"""
import re
import unittest
__all__ = ['ok_', 'eq_'... |
13,208 | ea05f13b8f0ddd09371200765ab76ae6c7f7455a | from __future__ import absolute_import
import functools
from web3.iban import Iban
from web3.utils.string import (
force_text,
coerce_args_to_text,
coerce_return_to_text,
)
from web3.utils.address import (
is_address,
is_strict_address,
)
from web3.utils.types import (
is_array,
is_string... |
13,209 | 4b4950825db71cc82863c85d6f7593734f58208a | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2020 - 2021 Louis Richard
#
# 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 with... |
13,210 | 136949a39d222885c706c82916daad924d5d6826 | from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from matplotlib import pyplot as plt
import numpy as np
#1. ์ ์ ๋ ๋ฐ์ดํฐ ์ธํ
x_train = np.array([1,2,3,4,5,6,7,8,9,10])
y_train = np.array([1,2,3,4,5,6,7,8,9,10])
x_pred = np.array([11,12,13])
#2. ๋ชจ๋ธ ๊ตฌ์ฑ
model = Sequential()
model.add... |
13,211 | 887d31f184b912035d15d576e744bb9c0d884785 | # Generated by Django 2.2.3 on 2019-07-15 13:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bim360', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='conteudo',
name='identity',
... |
13,212 | 0a8b80a5ddb9c6c06a3dda5e775854f4a4ae2c1c | import sys
def Palindrome(Number) :
temp = Number
Reverse = 0
while Number > 0 :
Reminder = Number % 10
Reverse = (Reverse*10) + Reminder
Number = Number // 10
if temp == Reverse :
return True
else :
return False
def Factorial(Number):
sum = 1
... |
13,213 | 1114557034301cacf162e69682d31f01969047a1 | __author__ = 'adekola'
def approve_lyrics():
"""this method is called by an admin user to approve the lyrics of a song"""
pass
def song_has_lyrics():
"""This method is called to check if a song already has lyrics so as to avoid duplicity of lyrics"""
pass
def lyrics_note_is_same_as_original():
... |
13,214 | b6e9802b001f148b582dbdafb7a56e33709b7046 | import os
import sys
from PIL import Image
from shutil import copyfile
import imagehash
class utility:
labels = ['None',
'amusement',
'awe',
'contentment',
'anger',
'disgust',
'excitement',
'fear',
's... |
13,215 | 184b3f182aee061a11e0e1be9d4a24776c79ffee | # 19723756=ไบ้ณไน้ฃๅๆฆ, 3779629=ไบ้ณไนๆฐๆญๆฆ, 2884035=็ฝๆๅๅๆญๆฒๆฆ, 3778678=ไบ้ณไน็ญๆญๆฆ
# ่ฏ่ฎบ
# https://music.163.com/weapi/v1/resource/comments/A_PL_0_19723756?csrf_token=
import re
from selenium import webdriver
import selenium.webdriver.support.ui as ui
# from lxml import etree
# driver = webdriver.PhantomJS(executable_path=r'C:\liux\... |
13,216 | f2011d2b12a66c9d3074060516c801fbebdb4d23 | from django.conf.urls import url
from . import views
urlpatterns = [
url('^$', views.PersonList.as_view(), name='person_list'),
url('^(?P<slug>.*)/$', views.PersonDetail.as_view(), name='person_detail'),
]
|
13,217 | 49ca9e08320df3109f9c981f0f40df1686256baa | """
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4... |
13,218 | 07a3d8a605571c28c031ff30ecaed3b981d84cfe | import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# from selenium.webdriver.common.keys import Keys
# from selenium.webdriver.common.by import By
# from selenium.webdriver.support.ui import WebDriverWait
# from selenium.webdriver.support import expected_conditions as... |
13,219 | 4301debbadc126fb74411f7650c5553e3d234791 | import os
import sys
import pickle
import shutil
progPath = os.path.dirname(sys.argv[0])
progPath = os.path.dirname(os.path.dirname(progPath))
pDir = progPath + "\\loc.pickle"
dst = sys.argv[-1]
if os.path.exists(pDir):
p = open(pDir, "rb")
temppath = pickle.load(p)
p.close()
os.remove(pDir)
folde... |
13,220 | 9fba24402cfc98e6b67cf257885243eeecff242b | # https://www.acmicpc.net/problem/1296
# readline์ ์ฌ์ฉํ๊ธฐ ์ํด importํฉ๋๋ค.
from sys import stdin
# ์ฒซ์งธ ์ค์ ์ค๋ฏผ์์ ์์ด ์ด๋ฆ์ ์
๋ ฅํฉ๋๋ค.
# ๋งจ ๋์ \n์ ๋ผ์ด์ค๋๋ค.
ohminsik = stdin.readline().rstrip()
# ๋์งธ ์ค์๋ ์ข์ํ๋ ์ฌ์์ ์ N์ ์
๋ ฅํฉ๋๋ค.
# 50๋ณด๋ค ์๊ฑฐ๋ ๊ฐ์ ์์ฐ์์
๋๋ค.
# ์ ์ํ์ผ๋ก ๋ณํํฉ๋๋ค.
N = int(stdin.readline())
# ์ฑ๊ณตํ ํ๋ฅ ์ด ๊ฐ์ฅ ๋์ ์ฌ์๋ค์ ์ด๋ฆ๋ค์ ์ ์ฅํ ๋ฆฌ์คํธ ๋ณ์๋ฅผ ์ ์ธํฉ๋๋ค.
selec... |
13,221 | 02001f7beba29169bbe177c3a0021a307e85444a | def libras_para_kg(x):
kilo= float(libra)/2.204600
return round(kilo,7)
|
13,222 | 8ab33f46a750aa5a9f51fa07bbc9ac19767ca8eb | from rex.core import StrVal, FloatVal, Error
from rex.instrument.interface import Assessment
from rex.db import get_db
__all__ = ('DemoAssessment',)
class DemoAssessment(Assessment):
@classmethod
def get_by_uid(cls, uid, user=None):
db = get_db()
with db:
data = db.produce('/asse... |
13,223 | e88d13cf3695db489c4ac4754c0c6ec3bc5c67bb | for _ in range(int(input())):
if _ % 2 == 0:
print(input())
else:
input()
|
13,224 | 229f2d251512ddee56f78fe853411719a05dd514 | # Pesquisa Operacional - 2018/1
# Engenharia de Sistemas UFMG
# Artur Mello - 2013030392
# Hernane Braga Pereira - 2014112627
import gurobipy as grb
import pandas as pd
from plot_results import *
filename = "bebidas.csv"
data_csv = pd.read_csv(filename)
data = pd.DataFrame(data_csv)
# Fรณrmula geral: C ... |
13,225 | d34f14cf5ffa70b9d4bacf51ef4a41e8c41d533c | responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
# Prompt for the person's name and response.
name = input("\nWhat is your name? ")
response = input("Which are your favorite tacos? ")
# Store the response in the dictionary.
responses['name']... |
13,226 | e681385c6f55c8e91b8d319c7ce0e04528a13c45 | # task_1
a = 0
while a < 100:
print("dennis omoding")
a += 1
print(a)
|
13,227 | f4ba47a74da7b06e9d9c9c0a1b5e1267a733eca2 | from app import app
import csv
import os.path
def get_hackers():
hackers = []
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(BASE_DIR, "attendees.csv")
with open(file_path) as csvfile:
attendees = csv.reader(csvfile, delimiter=',')
count = 0
for ... |
13,228 | fc357997ff28ab0d43f27ff60f7fb20da6e949af | n = int(input())
li_a = list(map(int, input().split()))
dic_a = {}
for a in li_a:
dic_a[a] = dic_a.get(a, 0) + 1
q = int(input())
li_bc = list()
for i in range(q):
li_bc.append(tuple(map(int, input().split())))
answer = sum(li_a)
for l in li_bc:
b = l[0]
c = l[1]
diff = (c - b) * dic_a.get(b, ... |
13,229 | 77b74c1717ba54372adf062f4e5cb99ec71827d2 | from model.Circle import Circle
from model.Is_Member import Is_Member
from DAO.TagDao import TagDao
from DAO.UserProfileDao import UserProfileDao
class CircleDao:
def __init__(self, baseConnection):
kb = baseConnection
self.connection = kb.getDB()
def has_tag(self, user_id, tag_id):
... |
13,230 | f0c418e17980da37cdc754492de31c28b035d042 | import graphene
from .validator import Validator
from .utils.formatting import format_extra_arguments, format_graphene_arguments
from .utils.security import enforce_custom_auth_decorator
from django.forms.models import model_to_dict
class MutationBase(graphene.Mutation):
# Default field to return from the mutati... |
13,231 | 9e26862991f7a6a677f19547dfb23b62e8b9c6b7 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... |
13,232 | 50f671f35863921229c4eabf6f2186f3bb0109fd | import numpy as np
import pandas as pd
import datetime
from pathlib import Path
import csv
class Loader:
def __init__(self, log_drive, file_prefix, date_format='%Y-%m-%d', time_format='%H:%M:%S', quiet=True):
self.log_drive = log_drive
self.file_prefix = file_prefix
self.date_format = dat... |
13,233 | 7e56a29cc790668a8d3509dbbca6637280236f63 | #!/usr/bin/python3
"""This module performs math on matrices"""
def matrix_divided(matrix, div):
"""This method divides each element in a matrix
Args:
matrix (list or lists): the matrix
div (int): the number to divide each element by
Attributes:
err_1 (str): error message 1
... |
13,234 | c6cdc2880c0a5aace4b3726e125e8c0872c34267 | #Username: chefteerth ## https://www.codechef.com/users/chefteerth
#Question URL: https://www.codechef.com/PCO12020/problems/LOTR1
# Problem Name: Lord of the Rings
# Problem Code: LOTR1
# Programming Lang: Python3
# 1<= x <= M
# 1<= y <= N
test = int(input())
ans_lst = []
p =0
while p < test:
x_lst = []
no_of... |
13,235 | 75851bc9421c527665023142a062be2dc998f73a | # 8 10 6 2 4
# 8 6 10 2 4
# 8 6 2 10 4
# 8 6 2 4 10
# 6 8 2 4 10
# 6 2 8 4 10
# 6 2 4 8 10
# 2 6 4 8 10
# 2 4 6 8 10
list = [ 8, 10, 6, 2, 4 ]
print('BEFORE: ', list)
# We need 5 - 1 comparison
swapped = True
while swapped:
swapped = False
for i in range(len(list) ... |
13,236 | aa91a942dd93444cf55fb35e62ee59dfd0c54d06 | from django.http import HttpResponse
from django.urls import path, include, re_path
from django.conf import settings
index_file = (settings.BASE_DIR/"front" / "index.html").read_bytes()
urlpatterns = [
path('api/', include('api.urls')),
re_path(r'^.*', lambda x:HttpResponse(index_file)),
]
handler404 = 'api.... |
13,237 | d4db423614576901ccdfcbdfd7613debb2822612 | import string
import random
from datetime import datetime
def random_string(length:int) -> str:
chars=string.printable
return ''.join(random.choice(chars) for _ in range(length))
def random_date(start:datetime=datetime.min, end:datetime=datetime.max) -> datetime:
# Get a random amount of seconds between `... |
13,238 | f42fc434474956d386dcede3fb73e5ca6dded10a | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'FruitType'
db.create_table(u'fruit_fruittype', (
... |
13,239 | 3d03fd8d5b4fddb83cc8217a0bfd8d90f13bcec3 | def common_prefix(a,b):
i = 0
for i, (x, y) in enumerate(zip(a,b)):
if x!=y: break
return a[:i]
a=input()
b=input()
c=common_prefix(a,b)
print (c)
|
13,240 | 08e6715db563b44c49eaff9a4256d3c179cff16a | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# This script is inspired by the debian package python-chardet
import os
import glob
from distutils.core import setup
data_files = []
def get_debian_version():
f=open('debian/changelog', 'r')
line=f.readline()
f.close()
version=line.split()[1].replace('(','... |
13,241 | 9b67b747bd495b2807f478ab1fcdb933158f91fb | import hashlib
is_valid = False
number = 0
while is_valid == False:
m = hashlib.md5()
m.update('iwrupvqb')
m.update(str(number))
if m.hexdigest()[0:6] == '000000':
print m.hexdigest()
print number
is_valid = True
number += 1 |
13,242 | 8387f9900993c6c7b90012109072038d2f91945e | # !/usr/bin/env python
# -*- encoding: utf-8 -*-
# @author: Lodgeinwh
# @file: Ghost Age.py
# @time: 2019/04/25 23:26:13
# @contact: lodgeinwh@gmail.com
# @version: 1.0
def checkio(opacity):
fab = [0, 1]
while fab[-1] < 10000:
fab.append(fab[-1] + fab[-2])
age = 0
result = 10000
while opac... |
13,243 | 9f3ac7d1330f481a191b6a6abffea84dce593209 | import serial
import serial.tools.list_ports
import platform
import logging
import py3lib.QuLogger
import numpy as np
ft232_name_in = "0403:6001"
arduino_name_in = "2341:0043"
#ft232_name_in_mac = "0403:6001"
#ft232_name_in_win = "VID_0403+PID_6001"
#ft232_name_in_win = "USB VID:PID=2341:0043" #Arduino Uno
manual_comp... |
13,244 | 764911d7b12bcbde0d0a498fb712e5dca069d800 | #!/usr/bin/python3
"""100-my-int"""
class MyInt(int):
"""MyInt"""
def __new__(cls, value):
"""new"""
return super(MyInt, cls).__new__(cls, value)
def __eq__(self, other):
"""equal"""
return super(MyInt, self).__ne__(other)
def __ne__(self, other):
... |
13,245 | 09d11245fc3614f2ab43f3b5759f5b5bc9308124 | import time
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data.dataloader import DataLoader
from torch.autograd import Variable
from data.parser import parse_mnist
from data.dataset import MNISTDataset
from data.transforms import MNISTTransform
from model ... |
13,246 | f43cdd3b142969874df363a4fc436266680cb958 | import sqlalchemy as db
from flask import Flask, abort
import json
import decimal
import datetime
username = "kristensohm"
password = ""
dbname = "MIS5400"
servername = "gidferd.database.windows.net"
driver = "{ODBC Driver 17 for SQL Server}"
engine = db.create_engine(f'mssql+pyodbc://{username}:{password}@{servername... |
13,247 | 8829323b6eddaa4d6be3fab6852d9083cfb54343 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Alex Wang
# Import config file setting
import src.alex_cfg.cfg_basic as cfg_basic
# Set logger
from src.alex_misc.alex_logging import create_logger
logger_data = create_logger(logger_name=__name__, fmt='%(message)s')
def data_df(capture, filter_str, value_lis... |
13,248 | fd41940b1530a8e4dd616777f42594ee473a03d4 |
import os
import time
import requests
import sys
def retrieve_html(): #retrive html
for year in range(2013,2019): #go for each and every year,month
for month in range(1,13):
if(month<10):
url='http://en.tutiempo.net/climate/0{}-{}/ws-421820.html'.format(month
... |
13,249 | 53e242bcbe47088285ab9d7eed0034767eb64b77 | from django.contrib import admin
from django.contrib.auth.models import *
from experiments.models import *
admin.site.register(Experimenter)
admin.site.register(All_Company)
admin.site.register(All_Laboratory)
'''
class User_LaboratoryAdmin(admin.ModelAdmin):
list_display = ('lab', 'user', 'validated')
raw_id... |
13,250 | ece0ff2954da3465b14a63b2bcb6b76a2b89a874 | from manimlib.imports import *
"""
TODO:
[ ] fix arrow head size
auto scale according to size?
have a default size, but, if the arrow size is too short, then shrink the head
[ ] slide the point according to the gradient
"""
class ParaboloidPlot(SpecialThreeDScene):
CONFIG = {
"three_d_axes_config": {
"num_... |
13,251 | 8790328c1a8f86c14af27df8ad9df9121d61762a | #!/usr/bin/env python
import urllib, urllib2
import cookielib
import os
from data_parser import WSDCDataParser, DataParseError
import json
import sys
import time
import sqlite3 as lite
import re
import httplib
DEBUG=True
class Counter:
def __init__(self, initval=0):
self.counter=initval
def inc(self):
s... |
13,252 | 5835407981dfffda82ff228341b3d831955a4529 | # art
"""
art.py -- contains ASCII art for Blind Auction project
"""
logo = '''
___________
\ /
)_______(
|"""""""|_.-._,.---------.,_.-._
| | | | | | ''-.
... |
13,253 | 8ef72d90316b4c6fbeedb052a1b4bc6c7ca67f41 | from user.ui import display_message, get_string
def menu_selection_exists(menu, selection):
return menu.is_valid(selection)
def is_valid_bool(true,false,selection):
if selection == true:
return True
elif selection == false:
return True
else:
return False
def is_int(test_int):
try:
good_int = int(test_... |
13,254 | b24d06b7fd7a43bb5f4fd4b022ee274ef2924550 | from __future__ import print_function
import sys
from pyspark import SparkContext
from pyspark.sql.types import *
from pyspark.sql import SparkSession
if __name__ == "__main__":
sc = SparkContext("local","dfexercise")
session = SparkSession(sc)
schema = StructType([StructField("month",Str... |
13,255 | b67a1e4f6cca7e91a63a6cfdd3fd50384a581b0a | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
import datetime, uuid
# Create your models here.
#Custom User
class User(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uui... |
13,256 | cbfefedc32653e9197b211ce4770df1df79c684b | from flask import render_template, redirect, url_for, request, abort
from models.Elector import Elector
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def login_post():
username = request.json['usuario']
password = request.json['contraseรฑa']
if username is None or password is None:
print... |
13,257 | 731963011d9a9c76f3d911d6c7d225e0cb0b22b7 | #!/usr/bin/python3
from dancerPDF import DancerPDF
class Modern(DancerPDF):
def __init__(self):
DancerPDF.__init__(self)
self.titleFontFamily = "Helvetica-Bold"
self.titleFontSize = 32
self.sectionFontFamily = "Helvetica-Bold"
self.creditsFontFamily = "Helvetica"
self.creditsFontSize = 1... |
13,258 | f9505fbd1ab0060f9f61d3d034e0cd607d1fee57 | import requests
from twilio.rest import Client
# sudo virtualenv -p python3 sms
account_sid = 'AC94505d002df1d9467c6028dbb47c0117' # auth_sid
auth_token = '2ed09a15c3e81673508b015e3b312757' # auth_token
client = Client(account_sid, auth_token)
message_body = '11Hi there'
number_to_text = '+380970568565'
twilio_numbe... |
13,259 | 3e2649fb139ab0037fc9c7ab2f0d64690fb5ae8e | import keras
import tensorflow
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout
from keras.optimizers import SGD
def load_data_set():
(x_train, y_train), (x_test, y_test) = mnist.load_data()... |
13,260 | 3c9b605ba29dfcf9343be7d5af9b5e4ba154d742 | import six
import time
from datetime import datetime, timedelta
def _local_date(string):
dt = datetime.strptime(string[0:25], '%a, %d %b %Y %H:%M:%S')
return dt + timedelta(hours=6) + timedelta(seconds=_local_time_offset())
def _local_time_offset():
"""Return offset of local zone from GMT"""
if time.l... |
13,261 | d1fbcf5b153c4b7d85160a3950f350bec5479571 | import torch
class MSE(torch.nn.Module):
def __init__(self, model):
super(MSE, self).__init__()
self.model = model
self.hidden_features = torch.nn.Sequential(
*list(model.children())[:]
)
def forward(self, x):
return self.model(x)
def forward_da(self... |
13,262 | b17a2c7ea3faf256274f0f96603642801c1f7931 | import glob
def doTheThing(lang):
path = 'D:\\SteamLibrary\\steamapps\\common\\dota 2 beta\\game\\dota_addons\\pathfinder\\pf_localizations\\' + lang
output = open(
'D:\\SteamLibrary\\steamapps\\common\\dota 2 beta\\game\\dota_addons\\pathfinder\\resource\\addon_' + lang.lower() + '.txt', 'w+', enco... |
13,263 | ea17f96b9805e8044afe8125636c63d0a60a1230 | from dataclasses import dataclass
from enum import Enum
class TokenType(Enum):
NUMBER = 0
PLUS = 1
MINUS = 2
MULTIPLY = 3
DIVIDE = 4
LPAREN = 5
RPAREN = 6
LETTER = 7
POWER = 8
SIN = 9
COS = 10
EXP = 11
SQRT = 12
LBRACKET = 13
RBRACKET = 14
@dataclass
class... |
13,264 | 67562db745c4aef34c300f41f06e1ae187bbce96 | #!/usr/bin/env python
# encoding: utf-8
'''
@author: leafcool
@license: (C) Copyright 2013-2020, Node Supply Chain Manager Corporation Limited.
@contact: leafcool@live.com
@software: leafcool
@file: test.py
@time: 2021/6/10 16:42
@desc:
'''
# code is far away from bugs with the god animal protecting
"""
I lo... |
13,265 | d2ebeb15c53461b827ec559caf70f62d113a2254 | from .shareable_content_xblock import ShareContentXBlock
|
13,266 | 22ee2ceecf1abff035d95d58f2e528b223f49c8a | #!/usr/bin/env python
# -*- coding: utf-8 -*
import os
from codecs import open
from setuptools import find_packages, setup
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
with open('requirements.txt') as f:
install_requires = f.read().splitl... |
13,267 | cd1fd3f312be93bf111bf1aacbdb8fded807f6f6 | import requests
import zipfile
import os
data_url = 'https://www.kaggle.com/c/dstl-satellite-imagery-feature-detection/download/'
data_path = "/Volumes/external/data/"
files = {
"sample_submission.csv.zip" : "sample_submission.csv.zip",
"grid_sizes.csv.zip" : "grid_sizes.csv.zip",
#sixteen_band is 7 GB
... |
13,268 | d60d8ce4dcea7c72bcc2bebe048e043cd4a0286d | def decorator(func):
def decorated(text):
new_args = '<b>' + text + '</b>'
return func(new_args)
return decorated
def hello(text):
print(text)
c = decorator(hello)
print(c)
c('you')
|
13,269 | 4446cc0ec293d53c197e65f5551f20f461c8f05b | import random
import pygame
from spaceshooter import BLACK, WIDTH, HEIGHT, POWERUP_TIME
from spaceshooter.asset import player_img, explosion_anime, powerup_images, missile_img, bullet_img, meteor_images
from spaceshooter.sound import shooting_sound, missile_sound
class Explosion(pygame.sprite.Sprite):
def __ini... |
13,270 | b23535b97fa10828841c44d1561a47c7b1660834 | import os, getpass
if getpass.getuser() == "samuel":
ironclust_path = "/home/samuel/Documents/SpikeInterface/ironclust/"
os.environ["IRONCLUST_PATH"] = ironclust_path
import unittest
import pytest
from spikeinterface.sorters import IronClustSorter
from spikeinterface.sorters.tests.common_tests import SorterC... |
13,271 | 99f97c93b528eb136f9c029e8d72e1e85baec09d | # Build a web crawler
import string
index = {}
graph = {}
def get_next_target(page):
"""Return starting and ending positions of next url in 'page'"""
start_link = page.find('<a href=')
if start_link == -1:
return None,0
url_start = page.find('"',start_link)
url_end = page.find('"',url_start+1)
url= page[url_s... |
13,272 | 52501f88894bf20e0f51f3a3ff0bc4c43dee6b4d | class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
diff = {}
for i in range(len(A)):
if A[i] != B[i]:
diff[i] = A[i]
if len(diff) == 2:
i,j = diff.keys()
A = list(... |
13,273 | 8f506925cb913815b8112b01d66f51a898e74079 | import logging
import communication
logger = logging.getLogger(__name__)
class Client:
def __init__(self, communication_module):
self._communication_module = communication_module
self._process = None
def create_commincation_moduel(self, node_decoder):
communication_module = commun... |
13,274 | fe68ca05a50d3f7daf96b837de78784080dfe5e8 | import numpy as np
print(np.linalg.det(np.array([[31, 22], [22, 31]])))
|
13,275 | dddf1c0f2113e3000cbf58caa4ce3756e4a03f92 | from django.db import models
from datetime import datetime
# Create your models here.
class topProjects(models.Model):
icon = models.CharField(max_length=500, blank=True)
title = models.CharField(max_length=50)
description = models.CharField(max_length=200)
site = models.URLField(max_length=300)
clas... |
13,276 | af789b870a8058bb62960f82cde3f1bcaa96ff49 | # coding: utf-8
from __future__ import absolute_import
from swagger_server.models.evidence import Evidence
from . import BaseTestCase
from six import BytesIO
from flask import json
class TestEvidenceController(BaseTestCase):
""" EvidenceController integration test stubs """
def test_get_evidence(self):
... |
13,277 | b75b68b1ae80c0d8a4828c78373c6327f00f2104 | from __future__ import division
import six
from keras.models import Model
from keras.layers import (
Input,
Activation,
Dense,
Flatten
)
from keras.layers.convolutional import Conv2D,MaxPooling2D,AveragePooling2D
from keras.layers import Activation
from keras.layers.merge import add
from keras.layers.n... |
13,278 | 051c5cfb5fe5c7eb813c007fa236c054ca07cb0c | ## It would be really helpful to know what type of music everyone likes before
## throwing this festival.
## Lucky for us we've got the data to find out!
## We should be able to tell what music people like by figuring out what music they're buying.
## Write a query that returns the BillingCity,total number of ... |
13,279 | 3851806b5d6c3eb94439d2a57b028cf9fe2b457a | weight = 0.5
input = 0.5
goal_prediction = 0.8
for iteration in range(20):
pred = input * weight
error = (pred - goal_prediction) ** 2
direction_and_amount = (pred - goal_prediction) * input
weight = weight - direction_and_amount
print("Error:" + str(error) + " prediction:" + str(pred))
|
13,280 | 2b652a7cd3ce8d1ebba96384a4787c1a503d9ac4 | # -*- coding: utf-8 -*-
'''
ๆฌๆไปถๅ็
ง https://mongoengine-odm.readthedocs.io/tutorial.htmๆฅ็ผๅ
'''
from mongoengine import Document, StringField, ReferenceField, ListField, EmbeddedDocument, EmbeddedDocumentField, \
CASCADE
class User(Document):
email = StringField(required=True)
first_name = StringField(max_... |
13,281 | b09f00152a3de0b0021e2777f374e25265a53380 | #!/usr/env python
# Many-to-Many Relationships
'''
Many to Many
Sometimes we need to model a relationship that is many-to-many
We need to add a 'connection' table with two foreign keys
There is usually no seperate primary value
To do this we build a 'Junction Table' to combine the two tables
This will give us a table ... |
13,282 | 3cf2df56fde67ac7738b263d4f56dbc3a541ffe2 | # //////////////// DEPTH FIRST SEARCH //////////////////////////
# //
# // Title: DEPTH FIRST SEARCH for graph
# // Course: CS 577 Spring 2021
# //
# // @author Zhuoyan Xu
# // Email: zxu444@wisc.edu
# //
class mygraph:
def __init__(self, numNode):
self.adjList = {}
self.todo = []
self.tra... |
13,283 | 15c9c26992ae703d6165706e9fdb94a7fd44a8c6 | S=input();
K=input();
i = 0;
for i in range(len(S)) :
if int(S[i]) > 1 :
print(S[i]);
break;
elif i + 1 >= int(K) :
print(1);
break;
|
13,284 | 9518adf44d0bf170db2c84a2e4b70d0487fb389f | """
PCA is a popular machine learning algorithm useful for dimension reduction and
information compression. It works by projecting the original data into a lower
dimensional (k) space while preserving as much information as possible (largest
variances) in the projected dimensions. The projection can be realized using
... |
13,285 | f5a4c616eae1a4f0d466dbab4f3954403ee26e4d | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 21:38:35 2017
@author: wei
"""
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
time_steps = [1, 2, 4, 8, 16, 32, 64]
solver_types = ["RK4", "RK5", "RK"]
data = loadtxt("RK4_64... |
13,286 | 7c50ae78298ffdb29ea2d89e630bd8572185c2e1 | import pandas as pd
import webbrowser
import pyautogui
import time
# Reading the file
import datetime
import calendar
def findDay(tdate):
born = datetime.datetime.strptime(tdate, '%Y-%m-%d').weekday()
return calendar.day_name[born]
tdate = datetime.date.today()
# printing todays date
print('Current date: ... |
13,287 | b2cb234e676f3e8d4ee71c47d710b1d5f47a9142 | # Generated by Django 3.0.5 on 2021-05-26 17:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profileApp', '0011_auto_20210526_2305'),
]
operations = [
migrations.AlterField(
model_name='usermodel',
name='age',... |
13,288 | 0932ddf7b8135eb4c033012eb3fc81bf8bbdf04e | #!python3.5
# For command aliases prior to 3.2 - https://bugs.python.org/issue25299
#
# https://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/
import sys
import re
import json
import subprocess
import requests
import errno
import os
from velstor.restapi import Session
from velstor.vsh.vsh_parser im... |
13,289 | 09e32a639a39d4424f60677bed2daa1a4e33721d | from django.contrib.auth.models import User
from rest_framework import viewsets
from django.core import serializers
from studio_app.models import *
from studio_app.serializers import *
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
|
13,290 | e4fb48012d3aeaa07b23577a1fe9e1a69498a87c | from django.shortcuts import render
# Create your views here.
import random
from django.http import HttpResponse
from .models import ScrumyGoals, GoalStatus
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from .forms import SignupForm, CreateGoalForm
def index(request):
for... |
13,291 | b7c3d24948b21f3beb2ad32284e638c7df84c3fe | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Identi... |
13,292 | 5615ab3ca410f92c4013695268f38a5e5eb7abe1 | import struct
import cffi
import dataType
class CDataMaker:
__ffi = cffi.FFI()
def __checkIsSigned(self, dataTypeName):
if 'unsigned' in dataTypeName or dataTypeName == 'char':
return False
return True
def castToCDataType(self, byteSequence, dataTypeName):
cDataType =... |
13,293 | 06a1008281483e4e621f1a70daf5900e79ddd33e | from django.conf.urls import url, include
from django.contrib import admin
from . import views
app_name = "inventories"
urlpatterns = [
url(r'^$', views.inventory_list, name="inventory_list"),
url(r'^/(?P<inventory>[a-zA-Z0-9_.-]+)$', views.generic_view, name="inventory_detail"),
url(r'^/(?P<inventory>[a-... |
13,294 | 606fc199fbead2a0382089452d85b254e3f5202c | import matplotlib.pyplot as plt
import numpy as np
from uncertainties import ufloat
import scipy.constants as const
import matplotlib as mpl
mpl.use('pgf')
import matplotlib.pyplot as plt
mpl.rcParams.update({
'font.family': 'serif',
'text.usetex': True,
'pgf.rcfonts': False,
'pgf.texsystem': 'lualatex',
'pgf.preamble... |
13,295 | c52006129e0d9f24ed70d5b99043e3144f6a0196 | import requests
from Tools import requests_tools as rt, geoloc_commercial_db, web_mapping_services, network_measurer, geo_distance_calculator
import re
from bs4 import BeautifulSoup
import socket
import pyprind
import settings, strings
import json
import pyprind
def crawl_planetlab():
'''
crawl l... |
13,296 | 2de4513a7874408f01a0e77f42f51675c2114d0d | from tqdm import tqdm
import torch
import torch.nn as nn
from trainer.eval import eval_net
from pathlib import Path
import os
# trong mแปi phase, lฦฐu lแบกi best model ฤแป lร m training cho phase tiแบฟp theo.
def train(net: torch.nn, data_train, train_loader, criterion, optimizer, writer, epochs, pre_epoch, n_channels,
... |
13,297 | 8641c7baf93e8990d1744e41b34d6f6ec0ba41ce | from .ctc_loss import sequence_ctc_loss_with_logits
from .axe_loss import sequence_axe_loss_with_logits |
13,298 | a7b5dcdefb344bfdb9f2481e009a270214b4d3fb | #!/usr/bin/env python2.7
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Li... |
13,299 | 19889965be0281e89e246a65c330a0f3cff56edd | # Lint as: python3
"""Quadruped toe position sensor."""
from typing import Any, Callable, Sequence, Text, Tuple, Type, Union
import gin
import gym
import numpy as np
from pybullet_envs.minitaur.envs_v2.sensors import sensor
from pybullet_envs.minitaur.envs_v2.utilities import noise_generators
def _convert_to_np_ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.