index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
7,200 | b69e3f5e57adc8e89b6ff22fb4a10d2539e13ca3 |
import json
import datetime
import requests
import pymysql
import pymongo
def insert_category(conn):
"""将商品的种类插入数据库 """
# 商品种类的 id 和对应的名称
categories_dict = {
66: "手机",
327: "腕表配饰",
65: "电脑办公",
67: "相机单反",
217: "平板数码",
179: "运动户外",
255: "家电家居",
... |
7,201 | 30c24b9a4738c1952fc5d36a4bc36d8d3576ed3b | from django.db import models
from django.utils.translation import ugettext_lazy as _
from apps.sources.models.mixins.page_numbers import PageNumbersMixin
from apps.sources.models.source import Source
PIECE_TYPES = (('essay', 'Essay'),)
TYPE_MAX_LENGTH: int = 10
class Piece(Source, PageNumbersMixin):
"""A piece ... |
7,202 | 3cc473f6bb4b2e1dd806edb8b096a6118fe7056a | # This file is part of the printrun suite.
#
# printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# printrun is distributed in ... |
7,203 | c96ebfe41b778e85e954e2b7d6de4b078e72c81f | # The Minion Game
# Kevin and Stuart want to play the 'The Minion Game'.
# Your task is to determine the winner of the game and their score.
"""
Game Rules
Both players are given the same string, S.
Both players have to make substrings using the letters of the string S.
Stuart has to make words starting with consonant... |
7,204 | a9e0659c6a18ffc954079845b7d0de04c46a78c9 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... |
7,205 | 5aecd021297fee4407d6b529c24afb3c6398f7ba | """
@File : jump.py
@copyright : GG
@Coder: Leslie_s
@Date: 2020/1/26
"""
import requests
from lxml import html
import pandas as pd
import time
import pandas as pd
import datetime
import re
import json
headers = {
'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,appl... |
7,206 | 6a1f58af26bbc4d584ffd699c512ef433ffb80d8 | from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://192.168.1.248:9079/#/")
lanuage = driver.find_element_by_class_name("el-dropdown-trigger-text")
print(type(lanuage))
print(lanuage.text)
try:
driver.find_element_by_class_name("el-dropdown-trigger-text").text =="中文"
print("符合要求")
... |
7,207 | cd322f9771f1ac90931a7229ffd5effd1cae1a54 | print("hello world")
print("welcome to london") |
7,208 | e886b88a0b7e8c06772fe8a9554cab1bfe9e94a7 | '''
runSPP.py - wrap spp peak caller
========================================
:Tags: Python
Purpose
-------
Runs the spp peak caller.
The workflow follows the tutorial at:
http://compbio.med.harvard.edu/Supplements/ChIP-seq/tutorial.html
Usage
-----
Documentation
-------------
Requirements:
* spp >= ?
* snow >... |
7,209 | 72abba6fa40441ab172bccb9065aaa0af5fefd64 | import requests
import json
import pyttsx
engine = pyttsx.init()
engine.say('Hello from Eliq.')
engine.runAndWait()
power_value = 0
power_value_int = 0
prompt=0
Eliq_just_NOW ={}
accesstoken = "xxxxxxxxxxxxxxxxxxxxxx"
#Say warning for power use over this limmit in Watts
level_warning = 2000
Eliq_request_string = (... |
7,210 | 54002bc7e2a1991d2405acbe1d399e8803ac5582 | ##
# hunt_and_kill.py
# 05 Oct 2021
# Generates a maze using the hunt and kill algorithm
# S
from sys import argv
from enum import Enum
import random
# Cardinal directions, can be OR'd and AND'd
DIRS = {
'N': 1 << 0,
'E': 1 << 1,
'S': 1 << 2,
'W': 1 << 3
}
O_DIRS = {
'N': 'S',
... |
7,211 | 5a0a8205977e59ff59a5d334a487cf96eee514d2 | from flask import render_template
from database import db
from api import app
from models import create_models
# Create a URL route in application for "/"
@app.route('/')
def home():
return render_template('home.html')
# If in stand alone mode, run the application
if __name__ == '__main__':
db.connect()
c... |
7,212 | 5ca990bdcbe9378747e438015beb46760b1e987b | import vigra
import os
import sys
import time
import json
from simpleference.inference.inference import run_inference_n5
# from simpleference.backends.pytorch import PyTorchPredict
from simpleference.backends.pytorch import InfernoPredict
from simpleference.backends.pytorch.preprocess import preprocess
def single_g... |
7,213 | f5d285b3a82151b5d7efdcd07d56cc5aaaac5836 | import sys
import requests
def ggwave(message: str, protocolId: int = 1, sampleRate: float = 48000, volume: int = 50, payloadLength: int = -1):
url = 'https://ggwave-to-file.ggerganov.com/'
params = {
'm': message, # message to encode
'p': protocolId, # transmission protocol to use
... |
7,214 | 3f3db7e8813f49fe0265e110236b6dc4fed6cd1b | import inspect
import json
import os
import re
import urllib.request
from functools import wraps
from ..errors import NotFoundError
class API:
def __init__(self, base_url, version=1):
self.BASE = base_url or 'https://api.starlist.pro/v{}'.format(version)
self.PROFILE = self.BASE + '/player'
... |
7,215 | fe13b57484e0f0796164fda99c0d759238a67153 | from population import Population
class REvolution:
def __init__(self, original_ind, combine_params, mutate_params, fitness, pop_params, method):
self.population = Population(1, fitness, pop_params)
self.combine_params = combine_params
self.mutate_params = mutate_params
self.fitnes... |
7,216 | 2730b2a1016f306936dcac3c3b44a3fd7194bac6 | #
# LeetCode
# ver.Python
#
# Created by GGlifer
#
# Open Source
"""
21. Merge Two Sorted Lists
"""
from typing import List
import sys
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoList... |
7,217 | b7f6207fe6c013a964258255445004c3f4e0adbb | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class CacheDecorator:
def __init__(self):
self.cache = {}
self.func = None
def cachedFunc(self, *args):
if args not in self.cache:
print("Ergebnis berechnet")
self.cache[args] = self.func(*args)
else:... |
7,218 | 999c19fd760ffc482a15f5a14e188d416fcc5f21 | from django import template
from apps.account.models import User, Follow, RequestFollow
from apps.post.models import Post
register = template.Library()
@register.inclusion_tag('user/user_list.html')
def user_list():
"""show user name list"""
users = User.objects.all()
return {"users": users}
# @regist... |
7,219 | 9690366a88a87951f5c51902118888cce8159ffc | from SPARQLWrapper import SPARQLWrapper, JSON
sparql = SPARQLWrapper(
'http://localhost:3030/ds/query'
)
#Pizzas
def get_response_pizzas():
sparql.setQuery('''
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX saidi: <http://www.semanticweb.org/japor/ontologies/2021/5/Pizzas... |
7,220 | a336434abc526357db0536955885cf076ee60f59 | # import tensorflow as tf
# from tensorflow.examples.tutorials.mnist import input_data
# mnist = input_data.read_data_sets('/tmp/data/',one_hot=True)
# def build_CNN_clasifier(x):
# x_image = tf.reshape (x, [-1,28,28,1])
#
# #layer1
# w_conv1 = tf.Variable(tf.truncated_normal(shape = [5,5,1,32],stddev= ... |
7,221 | 44175d2559f9c7d6171b6e45d24719d50dc80fb7 | import cv2
import numpy as np
# THRESHOLDING FUNCTION IMPLEMENTATION
def thresholding(img):
# visualizing image in HSV parameters
imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# the values for lowerWhite and upperWhite are found by tweaking the HSV min/max params in the
# trackbar by running ColorPick... |
7,222 | 51a4d8f1be7009b69f0b69bdd51a0077256304a9 | # -*- coding: utf-8 -*-
{
'name': 'Islamic Datepicker',
'category': 'Extra Tools',
'author': 'Mostafa Mohamed',
'website': 'https://eg.linkedin.com/in/mostafa-mohammed-449a8786',
'price': 25.00,
'currency': 'EUR',
'version': '9.0.1.0.1',
'depends': ['base','web'],
'data': [
'... |
7,223 | 4bd2923381cd3ead9a5605363a86f41b3743bf27 |
def largestVar(s: str):
freq = {i:0 for i in range(26)}
for i in range(len(s)):
freq[(int) (chr(i) - 'a')] += 1
max_var = 0
for a in range(26):
for b in range(26):
left_a = freq[a]
left_b = freq[b]
|
7,224 | 12d59697d5c2ec69d019c64dac762385c8c0cb66 | import sys
import networkx as nx
import bcube.generator_bcube as bcube
import dcell.generate_dcell as dcell
import fat_tree.generate_fat_tree as fatTree
import cayley_graphs.generate_bubble_sort as bubbleSort
import cayley_graphs.generate_hypercube as hypercube
import cayley_graphs.generate_pancake as pancake
import ca... |
7,225 | f28b47e1b07011ce9d0708331f68d7f16195c567 | """
contains generic code for use in main menus. currently this is a function which turns dictionaries of functions
into a menu. I envision any further menu functions being stored here so don't expect it to run like a pipeline but
rather like a suite of individual menus.
TODO - refactor spider selection function as je... |
7,226 | 73082ed2824ee65f7f4cbac47b9ebad19cec4196 | class State(object):
def __init__(self, stateName, stateLevel):
self.stateName = stateName;
self.stateLevel = stateLevel;
|
7,227 | d00873c3ee72b55cb5b74f78a98de61a25b3cc21 | __doc__
def fizz_buzz(num1, num2, end_range):
if not (
isinstance(num1, int) and isinstance(num2, int) and isinstance(end_range, int)
) or (num1 < 0 or num2 < 0 or end_range < 0):
return "Input should be a positive integer"
# I'm storing the result to test the returned value aka a list of... |
7,228 | cd89c9eaea9d331288fd07f1968ef9dce89b4a4b | class Port(object):
def __init__(self,mac):
self.mac = mac
|
7,229 | 3073850890eb7a61fb5200c5ab87c802cafe50bb | def reorderAssetsByTypes(nodePath, colorNode=True, alignNode=True):
node = hou.pwd()
def getNaskCasting():
path = "E:/WIP/Work/casting-nask.csv"
file = open(path, "r")
fileText = file.readlines()
file.close()
fileText.pop(0)
assetDic = {}
for line ... |
7,230 | e68588dff0e54fa03dbb1c629c39d8312a0df26d | input = open('in.txt')
output = open('out.py', 'w+')
def opstr(op):
if op == 'RSHIFT': return '>>'
if op == 'LSHIFT': return '<<'
if op == 'OR': return '|'
if op == 'AND': return '&'
if op == 'NOT': return '~'
raise RuntimeError('Unknown {0}'.format(op))
def funstr(fun):
return '{0}_fn'.f... |
7,231 | 28c4c09b81d63785750cee36a8efd77760cac451 |
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import tarfile
import tensorflow as tf
from IPython.display import display, Image
from scipy import ndimage
from sklearn.linear_model import LogisticRegression
from six.moves.urllib.request import u... |
7,232 | d1864f454b1909196fd9a6e2279b23f4c4148917 | # MEDIUM
# TLE if decrement divisor only
# Bit manipulation.
# input: 100 / 3
# times = 0
# 3 << 0 = 3
# 3 << 1 = 6
# 3 << 2 = 12
# 3 << 3 = 24
# 3 << 4 = 48
# 3 << 5 = 96
# 3 << 6 = 192 => greater than dividend 100 => stop here
# times -=1 becaus... |
7,233 | 65c0d940bacc2d016121812c435cc60f3fc1ba90 | #!usr/bin/env python
#-*- coding:utf-8 -*-
# this model is for decision tree
# objective: To cluster different service
# JialongLi 2017/03/18
import re
import os
import sys
import pickle
import copy
import random
import pydotplus
USER_NUM = 1000
reload(sys)
sys.setdefaultencoding( "utf-8" )
from ... |
7,234 | 5dc201f743705d6a57dfb61ec2cc2a827db0ba25 | # -*- coding:utf-8 -*-
# Classe com os dados de um cliente que entra no sistema simulado.
class Client:
def __init__(self, id, color):
# Identificador do cliente, usada para o teste de correção.
self.id = id
# Tempo de chegada ao servidor (fila 1 e fila 2)
self.arrival = {}
... |
7,235 | c5e003d625d7798eaf4ef5bca28f6311edccb316 | #!/usr/bin/env python3
# This is a tool to export the WA framework answers to a XLSX file
#
# This code is only for use in Well-Architected labs
# *** NOT FOR PRODUCTION USE ***
#
# Licensed under the Apache 2.0 and MITnoAttr License.
#
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Lice... |
7,236 | df3208a00f7a5dd1ddd76542ac0de85762cc45ab | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
try:
import Image
except ImportError:
from PIL import Image
import sys
sys.path.append(os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, 'DropPy.Common')))
from file_tools import get_file_paths_from_director... |
7,237 | 14345a8c4e20d84dfc87476d890f59530a8f4d96 | class Book:
"""Class that defines book model."""
def __init__(self, title, authors, pub_year):
self.title = title
self.authors = authors
self.pub_year = pub_year
|
7,238 | 15eb205e6bd36844fdfc8c05efbc3a3d584c122d | import os , sys , time
print("""
███████████████████████████████
█ █
█═╬═════════════════════════╬═█
█ ║░░░░░░░░░░░░░░░░░░░░░░░░░║ █
█ ║░░░░Wi-fi Fucker Tool░░░░║ █
█ ║░░░░░░░░░░░░░░░░░░░░░░░░░║ █
█ ║░░░░░coded by arda6░░░░░░║ █
█ ║░░░░░░░░░░░░░░░░░... |
7,239 | 7d65e4e925e90d6b013ae2c059cde58538884d22 |
two_digit_number=input("Type a two digit number: ")
first_digit=two_digit_number[0]
second_digit=two_digit_number[1]
print(int(first_digit)+int(second_digit)) |
7,240 | 07095bc815f5342b66ef4ca74b769321f3ef2ec5 | '''
Calculations used by algorithms
All calculations for training shall have a standard API that takes in `batch` from algorithm.sample() method and return np array for calculation.
`batch` is a dict containing keys to any data type you wish, e.g. {rewards: np.array([...])}
'''
from slm_lab.lib import logger, util
impo... |
7,241 | fe83b45bdc5970d63deab66b26b16752cd8ad8ef | from zope import schema
from zope import interface
from zope import component
from raptus.mailcone.rules_regex import _
from raptus.mailcone.rules import interfaces
class IRegexItem(interfaces.IConditionItem):
""" Interface for regex match filter
"""
regex = schema.TextLine(title=_('Regex'),
... |
7,242 | 742b655ee6aad2575f67e7329ed7a14c4fb6aa06 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import random
PATH = "C:\\Program Files (x86)\\chromedriver.exe"
destination = "https://news.ycombinator.com/"
class hackernewsUpvoter():
def __init__(self, username, password, website):
self.driver = webdriver.Chro... |
7,243 | 85b8ffe1bca879acd86251e4662b33648b713588 | from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
class UserManager(BaseUserManager):
#Necesar pentru a scoate username de la required
def create_user(self, email, password, **kwargs):
user = self.model(email=email, **kwargs)
user.set_password(... |
7,244 | 002f65fd77ce5043d1a0495ed13c15e3b4d2fb76 | #!/usr/bin/env python3
import asyncio
import bs4
import itertools
import logging
import sys
import os
import zipfile
from asyncio import TimeoutError
from aiohttp import ClientSession, ClientConnectionError
from aiohttp.client_exceptions import ContentTypeError, ServerDisconnectedError
from bs4 import BeautifulSoup
... |
7,245 | eabc81cacacc40d55234b60927b17069980a08f8 | #!/usr/bin/env python
# https://github.com/git/git/blob/master/Documentation/githooks.txt#L181
# This hook is called by 'git push' and can be used to prevent a push from taking
# place. The hook is called with two parameters which provide the name and
# location of the destination remote, if a named remote is not bei... |
7,246 | 7901a2bd4ae1070c8263d3cd97351b01ffbf7bb1 | from .facebook import *
|
7,247 | f66f79cd4132b23c082149a3a1d887f661fd7ee5 | from fgpio import GPIO
import boards
|
7,248 | 52e43f795c864340734de2640e3c1a70b05e8ea0 | # -*- coding:utf-8 -*-
import json
from datetime import datetime
from math import ceil, floor
from os.path import abspath, join, pardir
from struct import pack
from .global_settings import (
DEBUG, DEBUG_POLY_STOP, INPUT_JSON_FILE_NAME, INVALID_ZONE_ID, NR_BYTES_H, NR_BYTES_I, NR_SHORTCUTS_PER_LAT,
NR_SHORTCUT... |
7,249 | 381b59ab9fa85561932a9bfb9ab8cef635901a35 | #!/usr/bin/env python
from collections import defaultdict
from cluster.common import Cluster
from cluster.tools import print_table
def check_status(args):
""" Print node details
:param args: Arguments from argparse
:type args: argparse.Namespace
"""
cluster = Cluster(jobs_qstat=True, nodes=True,... |
7,250 | 71ab4ada4062ecde1463f2a766b5951860d0f2fb | from django.test import TestCase
from .models import Seller, Product
from rest_framework.test import APIClient
import json
class SellerModelTests(TestCase):
def test_class_str(self):
seller = Seller()
seller.name = "Bruna"
self.assertEquals(seller.__str__(), "Bruna")
def test_to_dic... |
7,251 | abb08956f55fd1e8af27ce12fa94a4137d7d908e | g7=int(input())
h7=g7/2
i=g7-1
print(int(h7*i))
|
7,252 | d48f02d8d5469b966f109e8652f25352bc9b3b80 | from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from .models import Attendance, Holidays
#I think the update forms are not required here. They might be required in the profiles app. For this app, update attendance option can be available to the staff and faculty... |
7,253 | 70cb5673a13967247b6da1fa5948000db39a92c8 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 5 11:56:41 2017
@author: cgao
"""
from beautifultable import BeautifulTable
#1. 新旧税率Bracket
def tax_calculator(taxable_income, bracket, rate):
bracket2 = bracket[1:]
bracket2.append(float('Inf'))
bracket3 = [y-x for x,y in zip(brack... |
7,254 | 75023c7600fcceda0dc225992e7c433291b1a190 | '''
THROW with or without parameters
Which of the following is true about the THROW statement?
Answer the question
50XP
Possible Answers
- The THROW statement without parameters should be placed within a CATCH block.
- The THROW statement with parameters can only be placed within a CATCH block.
- The... |
7,255 | 9021fa440561461ee179f333aa04a155d06c6e86 |
from xai.brain.wordbase.nouns._teleconference import _TELECONFERENCE
#calss header
class _TELECONFERENCES(_TELECONFERENCE, ):
def __init__(self,):
_TELECONFERENCE.__init__(self)
self.name = "TELECONFERENCES"
self.specie = 'nouns'
self.basic = "teleconference"
self.jsondata = {}
|
7,256 | 6f6f57ff317d7e3c6e6ae4d450c6fdf0e22eb4eb | from django.db.models import Sum, Count
from django.db.models.functions import Coalesce
from django.utils.timezone import localtime
from .models import Quote, Vote
import pygal
from pygal.style import Style
style = Style(
background='transparent',
plot_background='transparent',
foreground='#3d3d3d',
foreground_s... |
7,257 | b8b50ef021c4b25edbab355e1db5d62d3c5a28ad | import logging
import os
import logzero
from gunicorn.glogging import Logger
_log_level = os.environ.get("LOG_LEVEL", "info").upper()
log_level = getattr(logging, _log_level)
log_format = "%(color)s[%(levelname)1.1s %(asctime)s %(name)s]%(end_color)s %(message)s"
formatter = logzero.LogFormatter(fmt=log_format)
logg... |
7,258 | fde4c10e2ed0ed38d683a220e2985c3f3f336601 | #! /usr/bin/env python
import sys
import socket
def handle_connection(sock):
do_close = False
while 1:
try:
data = sock.recv(4096)
if not data: # closed! stop monitoring this socket.
do_close = True
break
print 'd... |
7,259 | 13e7484a80e4e45ee911f15837b9d82a1ef4d0b1 | from django.db import models
#Precisa existir uma conversao ticker -> ticker_id mais facil, ou definir como trabalhar com o ticker.name,
#na maioria dos casos só tenho o nome do ticker, nao o id.
class User(models.Model):
""" Usuario que pode operar ativos """
name = models.CharField(max_length=200)
... |
7,260 | e4f7e0c40edde4aac6ba0a7529a2e028a09689ae | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# menuScrnTxt.py
# Created on Mon Mar 8 16:17:50 2021
# @author: jcj52436999
# menuScrnTxt.py-2021-03-08-1641-just noting a general restart in efforts here
import sys
def printTest2():
if 0 == 0 :
print(" ")
print("# jcj-jcj-jcj- TOP START OF... |
7,261 | 237f5e2e37187e26b5628032e37d3a525ef72b9a | """
Mount /sys/fs/cgroup Option
"""
from typing import Callable
import click
def cgroup_mount_option(command: Callable[..., None]) -> Callable[..., None]:
"""
Option for choosing to mount `/sys/fs/cgroup` into the container.
"""
function = click.option(
'--mount-sys-fs-cgroup/--no-mount-sys-... |
7,262 | 73e4346007acae769b94a55ef53a48a9d3325002 | class Node:
def __init__ (self, val):
self.childleft = None
self.childright = None
self.nodedata = val
root = Node("Kaif")
root.childleft = Node("name")
root.childright = Node("!")
root.childleft.childleft = Node("My")
root.childleft.childright = Node("is")
message = input(... |
7,263 | d763485e417900044d7ce3a63ef7ec2def115f05 | from kafka import KafkaProducer
import json
msg_count = 50
producer = KafkaProducer(bootstrap_servers=['localhost:9092'])
for i in range(0,msg_count):
msg = {'id': i+20, 'payload': 'Here is test message {}'.format(i+20)}
sent = producer.send('test-topic2', bytes(json.dumps(msg), 'utf-8')) |
7,264 | 443bf59bc3c5ed2114f0c276aa7134ff5bf7fb64 | import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div(
children=[
html.Label('Dropdowm'),
dcc.Dropdown(
id='my-dropdown',
options=[
{'label': 'İstanbul', 'value': 34}, # seçeneleri dict tu... |
7,265 | 1ae8d78c6581d35cd82194e2565e7a11edda1487 | from django.urls import path, include
from .views import StatusAPIView, StateAPIView, LogAPIView
urlpatterns = [
path('status/', StatusAPIView.as_view(), name='status'),
path('log/', LogAPIView.as_view(), name='log'),
path('state/', StateAPIView.as_view(), name='state'),
]
|
7,266 | 9a5ba88a61f5c27c0bc7b980fa9d865b52cbbb20 | from .submit import *
from .fck import * |
7,267 | 4b672ad420bb67b8e2726102939ed6d369683150 | from telethon import events
from var import Var
from pathlib import Path
from ub.config import Config
import re, logging, inspect, sys, json, os
from asyncio import create_subprocess_shell as asyncsubshell, subprocess as asyncsub
from os import remove
from time import gmtime, strftime
from traceback import format_exc
f... |
7,268 | 7e287eca041cf27d99292a331604fef9e9f90fc2 | #Nianzu Wang
#Email: wangn89@gmail.com
#for_while.py: demonstrates some fun things with for and while loops
def starsFor(x):
array = range(x, 0, -1)
array2 = range(1, x)
for num in array2:
print "*" * num
for num in array:
print "*" * num
def starsWhile(n):
a = 1
while a < n:
... |
7,269 | 05f143e28ff9c7397376ad598529c1dfb7528ee3 | #!/usr/bin/env python
# coding: utf-8
# Predicting Surviving the Sinking of the Titanic
# -----------------------------------------------
#
#
# This represents my first attempt at training up some classifiers for the titanic dataset.
# In[ ]:
# data analysis and wrangling
import pandas as pd
import numpy as np
i... |
7,270 | 3af78dcc0bb0b6f253af01d2945ad6ada02ca7a0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Vertex():
def __init__(self, key):
self.id = key
self.connections = {}
def add_neighbor(self, nbr, weight=0):
self.connections[nbr] = weight
def get_connections(self):
return self.connections.keys()
def get_id(sel... |
7,271 | 21e83369c4100c41885e9ee8a8d7310556bfe51d | from src.MultiValueDictApp import MultiValueDictApp
def main():
app = MultiValueDictApp()
print("Welcome to Multivalue Dictionary App")
print("COMMANDS and format:")
print("KEYS")
print("MEMBERS key")
print("ADD key value")
print("REMOVE key value")
print("REMOVEALL key")
print("CLE... |
7,272 | 36ce0de4cb760632959392a9f982532436bd37b0 | # -*- coding: utf-8 -*-
"""overview.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/examples/style_transfer/overview.ipynb
##### Copyright 2019 The TensorFlow Authors.
"""
#@tit... |
7,273 | 901f87752026673c41a70655e987ecc2d5cb369f | #include os
#include math
output_file = 'output/mvnt'
def file_writeout(srvN, pos);
with open(output_file, 'a') as f:
f.write(srvN, ' to ', pos)
return 0
class leg(legN):
def __init__(legN):
srvHY = 'srv' + legN + 'HY'
srvHX = 'srv' + legN + 'HX'
srvEY = 'srv' + le... |
7,274 | 6492f1eda79fd3116058f29647dc5f09e903f637 | ##
## Originally created by https://www.reddit.com/user/AlekseyP
## Seen at: https://www.reddit.com/r/technology/comments/43fi39/i_set_up_my_raspberry_pi_to_automatically_tweet
##
#!/usr/bin/python
import os
import sys
import csv
import datetime
import time
import twitter
#Configuration
# Twitter
ACCESS_TOKEN=""
ACCE... |
7,275 | a10403d7809b97c1bcdfa73224b8c365519cc456 | a = ['a','b','c','d','e']
print(';'.join(a))
|
7,276 | a9c0251b3422457b2c0089b70308a70b09cfa0e0 | # Copyright (C) 2014 Abhay Vardhan. All Rights Reserved.
"""
Author: abhay.vardhan@gmail.com
We have not yet added tests which exercise the HTTP GET directly.
"""
__author__ = 'abhay'
from nose.tools import *
import test_data
import search_index
class TestClass:
def setUp(self):
search_index.buildIndex(tes... |
7,277 | 5b0252dd862fe1e46c0c1df41935db16ae691dff | from django.db import models
# Create your models here.
class Products(models.Model):
title = models.CharField(max_length=255)
year = models.IntegerField(default=0)
feature = models.CharField(max_length=30)
usage_status = models.CharField(max_length=25)
kms_driven = models.CharField(max_length=10)... |
7,278 | 46dc9917d9b3a7caf8d7ba5024b17d3b755fc5db | def sort_descending(numbers):
numbers.sort(reverse=True)
|
7,279 | 1446268583bf9fa3375319eae3c21cf47f47faca | from convert_data2 import array_rule
from convert_data2 import array_packet
import tensorflow as tf
import numpy as np
train_x, train_y = array_packet()
x_input, input_ip = array_rule()
n_nodes_hl1 = 210
n_nodes_hl2 = 210
n_nodes_hl3 = 210
n_classes = 2
batch_size = 500
hm_epochs = 20
x = tf.placeholder('float')
y ... |
7,280 | 421837698b7fc188c84a3221271f11a40d1625d9 |
from logupload import *
log = LogUpload()
log.uploadLogs(4) |
7,281 | 34a8fc38ed875e1c564f535348dc0d5d88c76ab1 | # 1로 만들기
import sys
N = int(sys.stdin.readline())
dp_table = [0 for _ in range(10**6 + 1)]
dp_table[2], dp_table[3] = 1, 1
for i in range(4,N+1):
two_per = 10**6
three_per = 10**6
if i % 3 ==0:
three_per = dp_table[i//3] + 1
if i % 2 ==0:
two_per = dp_table[i//2] + 1
minus = dp_tabl... |
7,282 | 41aebc4ee9cb058c3351029773be05cdc4f84ffa |
##outcome: Hello, my name is B-max
print("Hello", end="")
print(", my name ", end="")
print("is B-max", end="")
print()
##outcome: ****************************************
for i in range(40):
print('*', end="")
print()
##outcome: x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*
for i in range(20):
print("x*", en... |
7,283 | 8fcc2a13fd5a803e2d755a567c78c8274bd88aad | import json
import time
from typing import Dict
import threading
"""
Note: każdy request uruchamia osobny wątek.
Przegląd: `top -H -p <process_id>`
"""
from flask import Flask, jsonify, request
app = Flask(__name__)
# https://www.tutorialspoint.com/flask/flask_http_methods.htm
# ładowanie konfiguracji aplika... |
7,284 | cf4170760fe6210d8b06f179484258f4ae3f8796 | #!/usr/bin/python3
from datetime import datetime
import time
import smbus
SENSOR_DATA_FORMAT = "Speed: {} km/h\nSteering: {}\nThrottle: {}\nTemperature: {} C"
class SensorDataFrame:
def __init__(self, data):
self.speed, self.steering, self.throttle, self.temp = data
self.timestamp = datetime.now... |
7,285 | 9339d3bc0c3005880b1c8d1c9914d6e28d39dbbd | from django import template
import ast
register = template.Library()
@register.simple_tag()
def multiplication(value, arg, *args, **kwargs):
return value * arg
@register.filter
def in_category(things, category):
return things.filter(category=category)
@register.simple_tag()
def division(value, arg, *args, ... |
7,286 | ff081a5ff46ab37dc5a144fb4616c06ef3bca490 | n, a, b = map(int, input().split())
cl = list(map(int, input().split()))
for i in range(n):
if cl[i] == a + b:
print(i + 1)
|
7,287 | 37d5696c402737bfafe21b20b90a49e2753fdc4f | import pandas as pd
import os
import openpyxl
from collections import defaultdict,deque
# 調節用パラメータ
filename = 'kaito7.xlsx' # 入力ファイル名
Output = 'output7.xlsx' # 出力ディレクトリ
wb = openpyxl.load_workbook(filename)
sheets = wb.sheetnames
days = []
names = []
dict = defaultdict(dict)
for sheet in sheets:
sh = wb[sheet]
... |
7,288 | 6dda23cc5d0083e72520b0664b6550ccb48e4b4f | from count_freqs import *
from eval_gene_tagger import *
'''
Using gene.train gene.counts prediction file to evaluate the performance
Usage: python viterbi.py gene.counts gene.dev gene_dev.p1.out
'''
if __name__ == "__main__":
#if len(sys.argv)!=2: # Expect exactly one argument: the training data file
# ... |
7,289 | 2cdee8799678e8ead21a0f81c42eb7ce209cfec7 |
class thrs:
def __init__(self, input_wave):
from numpy import mod, array, sqrt, dot,median,convolve
self.D0 = 20
self.last_det = 0
self.mu = 0.6
self.a_up = 0.2
self.a_down = 0.6
self.z_cumulative = 10
self.n_max = max(input_wave[:1000])
self... |
7,290 | 30f02b956af68960804f0cb57695bdbf8510bc43 | Album,artist,year,songs="More Mayhem","Imelda May",2001,((1,"pulling the rug"),(2,"psycho"),(3,"mayhem"),(4,"kentisch town waltz"))
for song in songs:
track,title=song
print(" track number {}\t, title {}".format(track,title)) |
7,291 | 938c4325480608b904bfbe0b11c081166aad694b | # 체크는 오른쪽+아래로만 체크합니다.
def check22(y, x, board) :
dirs = [[0,1], [1,0], [1,1]]
ret = [(y,x)]
for d in dirs :
dy, dx = y+d[0], x+d[1]
if not ( (0<=dy<len(board)) and (0<=dx<len(board[0])) and board[dy][dx]!='0' and board[y][x]==board[dy][dx] ) :
return False
else... |
7,292 | b233d212f3a6c453786dc54b2d43578e1faae417 |
import json
from flask import current_app, request, jsonify, make_response
from flask_cors import cross_origin
from alerta.auth.utils import is_authorized, create_token, get_customer
from alerta.utils.api import absolute_url, deepmerge
from . import auth
try:
import saml2
import saml2.entity
import saml... |
7,293 | 0fb8a9b1073446a62b46a802da69b66e78533c2a | sheik=['a','e','i','o','u','A','E','I','O','U']
s=raw_input()
if(s in sheik):
print('Vowel')
elif(s!=sheik):
print('Consonant')
else:
print('invalid')
|
7,294 | 43196258b61801799b8d6b7d23f5816d84cb5dff | import csv
import os
with open("sample.csv") as rf:
csv_reader=csv.DictReader(rf)
with open("sample1.csv","w") as wf:
csv_headers=['fname','lname','email']
if os.path.isfile('sample1.csv'):
q=input("File already exists. Do you want to overwrite?")
if q.lower()=='yes':... |
7,295 | d058c3df8513e07e4ff7035aa5c5885819e43687 | from modeller import *
from modeller.automodel import *
# This part was within the script loop_modelling_2
# Here is is in a separate file for loop_modelling_3 so the script can be run in parallel
class MyLoop(dopehr_loopmodel):
def select_atoms(self):
# Here only the second loop atoms are allowed to move s... |
7,296 | c05994471d6608b5e48b71d253304a43100d583f | import numpy as np
import scipy
class node(object):
"""docstring for node"""
def __init__(self, feature_idx):
super(node, self).__init__()
self.children = None
self.j = feature_idx
self.c = None
self.vals = None
class decisionTree(object):
"""docstring for decisionTree"""
def __init__(self, arg):
sup... |
7,297 | c8f2df1471a9581d245d52437470b6c67b341ece | class Solution:
def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
def squareSum(r1: int, c1: int, r2: int, c2: int) -> int:
return prefixSum[r2 + 1][c2 + 1] - prefixSum[r1][c2 + 1] - prefixSum[r2 + 1][c1] + prefixSum[r1][c1]
m = len(mat)
n = len(mat[0])
... |
7,298 | 965bb4c8e7d6650dab7f002645dceacab59a0c5c | import FWCore.ParameterSet.Config as cms
maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
readFiles = cms.untracked.vstring()
secFiles = cms.untracked.vstring()
source = cms.Source ("PoolSource",fileNames = readFiles, secondaryFileNames = secFiles)
readFiles.extend( [
'/store/mc/Summer12_DR53X... |
7,299 | 5b860144a592505fea3a8849f5f5429a39ab9053 | #!/usr/bin/env python
"""
mahjong.playerhand
"""
from collections import Counter
from melds import (DiscardedBy, Chow, Pung, Kong)
from shanten import (
count_shanten_13_orphans,
count_shanten_seven_pairs,
count_shanten_std)
import tiles
from walls import TileWallAgent
class PlayerHand:
"""Player's... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.