index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
993,900 | afd01cac2bed20d34cf345338ef18826b08abfee | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 18:35:13 2019
@author: abhinav
"""
#Linear Regression Model
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as seabornInstance
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
... |
993,901 | 60afe4851e38e2debb6296f6992280d295d5250b | # -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if len(s)==0: return -1
dic = {}
for i in s:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
for i in s:
if dic[i]==1:
... |
993,902 | 3c78e5e47f8bc4ddbb36fe5f12ab21a6425b4a35 | #! /usr/bin/env python
import rospy
import pymap3d as pm
from sensor_msgs.msg import NavSatFix
from nav_msgs.msg import Odometry
from geodetic_to_enu_conversion_pkg.msg import Gps
def gps_callback(msg):
global datum_lat
global datum_lon
global i
if i==0:
datum_lat = msg.latitude
datum_... |
993,903 | 888e138ab9f77621222bdc0fc424c4bcc4df920f | bind = '127.0.0.1:8000'
workers = 3
user = 'amplua'
timeout = 120 |
993,904 | 81b7db4420021de023cd6c4033041d3e79f6498f | #
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Apply copyright and licensing to all source files present in a project.
This is to comply with OpenChain certification;
https://github.com/OpenChain-Project/Curriculum/blob/master/guides/reusing_software.md#2-include-a-cop... |
993,905 | 58fc2a36f449f88a3b1d8d1fd58199bd303abded | import argparse, codecs
def manipulate_data(golds, hyps):
# log.info("Lemma acc, Lemma Levenshtein, morph acc, morph F1")
count = 0
morph_acc = 0
f1_precision_scores = 0
f1_precision_counts = 0
f1_recall_scores = 0
f1_recall_counts = 0
for r, o in zip(golds, hyps):
#log.debug... |
993,906 | 45f79179d3c9e2ec08624cdc4ded0e298cb6e4a4 | """
There are 100 chairs arranged in a circle.
These chairs are numbered sequentially from One to One Hundred.
At some point in time, the person in chair #1 will be
told to leave the room. The person in chair #2 will
be skipped, and the person in chair #3 will be told to
leave. This pattern of skipping one person an... |
993,907 | c4397fb934504ba4177ab6448264d491b12b9e29 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.ShopScoreResultInfo import ShopScoreResultInfo
class ShopDataDetail(object):
def __init__(self):
self._city_name = None
self._county_name = None
self.... |
993,908 | cc4d62f71b28100a5510ac105f7320e71c13c6a7 | def abc050_b():
_ = int(input())
T = list(map(int, input().split()))
M = int(input())
Query = [tuple(map(int, input().split())) for _ in range(M)]
tot = sum(T)
for p, x in Query:
ans = tot - T[p-1] + x
print(ans)
abc050_b() |
993,909 | 49781a6050eb6b5767b23c56f938ecd30cac0d80 | import asyncio
import json
import logging
from aiohttp import web
from prometheus_client import Summary
from prometheus_client import Histogram
from prometheus_async.aio import time
REQ_TIME = Summary("cancel_req_time", "time spent with cancel endpoint")
REQ_HISTOGRAM_TIME = Histogram("cancel_req_histogram", "Histog... |
993,910 | 7aaed8b8811b21660642769f982afae5dd813180 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
import nltk
#nltk.download("stopwords")
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import re
import sys
word_array=[]
def cleantxt(word_array,index): # printing the tri-gram
if(index==0 and len(word_array)>=3):
print("%s\t... |
993,911 | 7b556f18a55b454a8748866f317ef0ee6c08750b | class person:
def __init__(self, name, age):
self.name = name
self.age = age
def cridentiald(self):
with open("cridentials.txt",'a') as f:
f.writelines(self.name + "\n")
f.writelines(str(self.age))
f.close()
def cridentiald2(self... |
993,912 | 4a694c9227049b68c0af44d9ff435d58e1dfd0a1 | from qiskit import QuantumCircuit, execute, Aer
from qiskitt.visualization import plot_histogram
circuit = QuantumCircuit(1,1)
circuit.h(0)
circuit.measure([0], [0])
circuit.draw()
from qiskit.visualization import plot_bloch_multivector
backend = Aer.get_backend9'statevector_simulator')
result = execute(circuit, backe... |
993,913 | 7180d45d75d60ddffa6f03347078049410558633 | from flask import Flask, request, Response, json
from db import select_stats
from functions import is_mutant
app = Flask(__name__)
@app.route('/')
def home():
return 'Home'
@app.route('/mutant/', methods=['POST'])
def mutant():
json_data = request.json
dna = json_data["dna"]
board = []
for i i... |
993,914 | f599df5da86cf45e4426a2eeb6c392b10249fd85 | import RPi.GPIO as GPIO
import boto3
import cv2
from PIL import Image
import io
import time
import os
import argparse
import numpy as np
import sys
from threading import Thread
import importlib.util
from botocore.exceptions import ClientError
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18... |
993,915 | 574effb6839583a07e4ad584fd01d1da142d1cf8 |
def difference(nums):
nums.sort()
x = len(nums)
return nums[x-1]-nums[0]
|
993,916 | 0a990daafcb7789510a5197241d853b77de00422 | import unittest
import requests
class testPUT(unittest.TestCase):
def testPostTournament(self):
load = {'start_date':'01-01-2020', 'name': 'tournament1', 'city': 'krakow', 'location': 'ulica Pokątna'}
r = requests.post('http://77.55.192.26:2137/api/tournament', json = load)
self.assertEqual... |
993,917 | 26278c110b1a2e5674e930cf88e651adf9e1e299 | #!flask/bin/python
from trs import app
app.run(debug=True,host='0.0.0.0',port=8081)
|
993,918 | f76ad912bf3b77f21f563103dbbc36800a587041 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft and contributors. 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 ... |
993,919 | 88f947ccb201da27597a9591c9ebe2794c34c40e | """Setup file to generate a distribution of njord
usage: python setup.py sdist
python setup.py install
"""
from setuptools import setup
setup(name = 'gitcheck',
version = '0.5',
description = 'Check multiple git repository in one pass',
long_description = "README.md",
author = '... |
993,920 | 92d062a8556a211d090e242438ece870c7509ee2 | # 394. Decode String
# Given an encoded string, return its decoded string.
# The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
# You may assume that the input string is always valid; No ex... |
993,921 | 5f93a77eab6da8f486f09e10b536721d9695f5a5 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import json
import pymysql
import requests
import time
from selenium import webdriver
from fake_useragent import UserAgent
__author__ = "xin nix"
# 导入:
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative i... |
993,922 | a7f33e2ad905fad11e3cc4c43d693c598b6d86a1 | from django.shortcuts import render, redirect
from django.conf import settings
import requests
from requests.auth import HTTPBasicAuth
import json
from products import utils
from orders.models import Order
from django.urls import reverse
from cart.views import view_cart
# Create your views here.
klarna_un = settings.... |
993,923 | aa4a7c1799595d4aa8375f96913f9c54c1b8c8a3 | # -*- coding: utf-8 -*-
"""
Algoritmo de Dijkstra (com lista de adjascencias)
Autores:
Edsger Dijkstra
Colaborador:
Péricles Lopes Machado (pericles.raskolnikoff@gmail.com)
Tipo:
graphs
Descrição:
O Algoritmo de Dijsktra é um algoritmo em grafos clássico que determina a
menor distância de um deter... |
993,924 | 2c0e7c5379c9d94d0d2a846dc90ea3c7af3fefbe | from comet_ml import Experiment
import os
from torch.utils.data import DataLoader
import json
import glob
import torch
from tqdm import tqdm
import pandas as pd
import numpy as np
import torch.nn as nn
import argparse
from sklearn import metrics
from preprocess import get_raw_data, get_labels, get_tokenized_inputs, g... |
993,925 | 7d07305d369a5358e58e4f8556521b49f687d6fb | number = input()
limit = input()
x = 0
sum = 0
cnt = 0
while x < limit:
if(x % number == 0):
sum = sum+x
cnt = cnt+1
x = x+1
avg = sum/cnt
print(avg)
|
993,926 | 23a9c803c85ca7ac75becc248597f112d61a1c5c | import sys
sys.stdin = open("4861.txt", "r")
T = int(input())
for tc in range(1, T+1):
print("#%d" %(tc), end=" ")
a, b = map(int, input().split())
li = []
for _ in range(a):
li.append(str(input()))
result = []
count = 0
for y in range(len(li)):
for x in range(len(li[0])):... |
993,927 | a46b201fc831e8efe46cddefce94a452aeecd736 | n = int(raw_input())
a = map(int, raw_input().split())
z = dict()
for q in a:
if q not in z:
z[q] = 0
z[q] += 1
ans = 0
for (v, q) in z.items():
if v != 0:
if q > 2:
ans = -1
break
if q == 2:
ans += 1
print ans |
993,928 | 025cb0b757f95d651e7e9abef86f5a55e5cb47fe | from django.conf.urls import url, include
from .views import (CubesCategoryPriceAPIView,
CubesCategoryFiltersAPIView,
CubesCategoryAPIView,
CubesCategoryNodeInputsAPIView,
CubesCategoryNodeOutputsAPIView,
CubesCategoryN... |
993,929 | 8bf59a72782d25bb7382292af4220afbe6949f18 | from django import forms
from django.forms import Textarea
from questions.models import Case
from common.models import Comment
from questions.models import UploadFile
from knowledge_base.models import KB_Item
class KnowledgebaseForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(Knowledgebas... |
993,930 | 161466bb53c4d2c4458785bf32fe03ce398818b2 | """
program: basic_list_exception
Author: Ondrea Li
Last date modfied: 06/20/20
The purpose of this program is to write the function to input
and print user input as a list.
"""
# this function will get one input and return it
def get_input():
"""
Use reST style
:param enter_number: represent... |
993,931 | 5db2c821fbbc3e8717079f3e064ccc497ac2b2fa | # http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html |
993,932 | cf0265a10bc1f8f0a98bcf14bad46b9a31df1cc5 | from django.urls import include, path
app_name = 'users'
urlpatterns = [
# path('')
] |
993,933 | 40389dd43b0670412d504568090a06181970ea73 | '''
Copyright (C) 2019 Naoki Akai.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this file,
You can obtain one at https://mozilla.org/MPL/2.0/.
'''
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import math
from numpy.rand... |
993,934 | 838d9ba8338eaf797ec2081f2b47ca16d60265f9 | from django.db import models
from Babies.models import Baby
# Create your models here.
class Event(models.Model):
event_type= models.IntegerField(default=1)
baby_id= models.ForeignKey(Baby, on_delete=models.PROTECT,related_name="events")
note= models.CharField(max_length=500)
timestamp= models.DateTimeField(auto_n... |
993,935 | 922e6079c01853d1f242acdeeaf1605d981a07ab | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
@Time : 2021/5/14 20:21
@Auth : 可优
@File : serializers.py
@IDE : PyCharm
@Motto: ABC(Always Be Coding)
@Email: keyou100@qq.com
@Company: 湖南省零檬信息技术有限公司
@Copyright: 柠檬班
-------------------------------------------------
"""
fro... |
993,936 | b5da3828b72d2586eefb2a89bb437dcb1f95bcc6 | from __future__ import division
import numpy as np
from numpy import fft
import time
import pycuda.autoinit
import pycuda.driver as drv
from pycuda.compiler import SourceModule
import pycuda.gpuarray as gpuarray
import skcuda.fft as cu_fft
from skcuda import misc
from pycuda import cumath
REAL_DTYPE = np.f... |
993,937 | f0cb2327a7e3bd386d9a39124a29be3c21a60a20 | # This file is part of pyrerp
# Copyright (C) 2012 Nathaniel Smith <njs@pobox.com>
# See file COPYING for license information.
# How to compute incremental std dev:
# http://mathcentral.uregina.ca/QQ/database/QQ.09.02/carlos1.html
import numpy as np
from numpy.linalg import solve, inv
from scipy import stats, spars... |
993,938 | 83c718d48e254e1b94aff96cc70cce88a9278d6a | import random
from firebase import firebase
### TAXI
# int pos_x, pos_y;
# int axis; --> str from axisList
# str direction;
axisList = ['Horizontal', 'Vertical']
# taxiList[i] = Taxi ID Tag
# NOTE: Taxis are automatically added to taxiList upon initialization
taxiList = []
taxiCoords = []
class Tax... |
993,939 | 7e7984241a1a0d4731c09eab7f358092bec020f2 | import numpy as np
import pandas as pd
from scipy.interpolate import *
import math
import matplotlib.pyplot as plt
#fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
#layer_z = 0.4
def partition_steps(path,nominal_step = 1, dev_factor=0):
#finds places where there is a change in extruder temperature
f = (p... |
993,940 | ff69c68c197fcc4ef9c664e82bbcdccbdebf0e8e | import duden
from psycopg2.extras import execute_values
import psycopg2
ktype = 'duden'
from time import sleep
from random import randint
import constants as const
from translations.database_handler import connect
import json
def get_word_url(term):
res = duden.search(term, return_words=False)
print(f"found {... |
993,941 | cd8609c63ade90751b627cbee6cf2cfed420085d | with open('input.txt', 'r') as f:
d = f.read().splitlines()
def part1():
i = 0
prev = int(d[0].strip())
for line in d[1:]:
value = int(line.strip())
if value > prev:
i += 1
prev = value
print(i)
def part2():
result = 0
def getWindow(... |
993,942 | 4fa58c5a29c563a0ae78df39cfd2961800e1a68d | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .resnet import ResNet
from .utils import Conv2dWithNorm, UpSample2d
class FPN(nn.Module):
def __init__(
self,
bottom_up,
input_size,
out_channels,
num_classes=0,
in_features=[],
... |
993,943 | d036d659de058034f34be0851bbf8547248fb4cb | import json
from django.test import TestCase
from django.urls import reverse
from rest_framework.authtoken.models import Token
from .models import CustomerModel
def create_user():
customer = CustomerModel.objects.create_user(username='menooa2015@gmail.com',
first... |
993,944 | 48c13065825b2fd055f23a034661e6ba374cb00b | import numpy as np
import matplotlib.pyplot as plt
from numpy import pi , sin
from numpy.fft import fft
from scipy.signal import square
##1 --
fo = 120
fe = 8000
t = np.linspace(0,1,fe+1)
signal = sin(2*pi*fo*t) + (1/3)* sin(2*pi*fo*t*3) + (1/5)*sin(2*pi*fo*t*5) + (1/7)*sin(2*pi*fo*t*7) + (1/9)*sin(2*pi*fo*t*9) ... |
993,945 | 41c64c94ee1e1cbd9f18c39b7603d481c01aa13b | from .manager import SQLiteManager, connect
|
993,946 | b53deeb9357cc276b773f4da9a7e425113f288dc | #1. Description
'''
Click though rate prediction using logistic regression.
Please download the data from https://www.kaggle.com/c/avazu-ctr-prediction/
manually (registration required) and place `CTR_train` file in `datasets` directory.
Only part of the data is used, because it takes too large memory for one VE card.... |
993,947 | 7004ed0fbfb9641e85a7295d6b7b241bb88f58a5 | import cv2
import os
import numpy as np
eigenface = cv2.face.EigenFaceRecognizer_create()
fisherface = cv2.face.FisherFaceRecognizer_create()
lbph = cv2.face.LBPHFaceRecognizer_create()
def getImagemComId():
caminhos = [os.path.join('fotos', f) for f in os.listdir('fotos')]
faces = []
ids = []
for caminh... |
993,948 | 8277b287060246fde64dd575520129ebd1037336 |
"""
Pattern name - SingleTon (Mono state pattern)
Pattern type - Creational Design Pattern
"""
# Solution - 2
class Borg(object):
_shared = {}
def __init__(self):
self.__dict__ = self._shared
class SingleTon(Borg):
def __init__(self, arg):
Borg.__init__(self)
self.val = arg
... |
993,949 | d88665969e9b1053e17daaa9c8b89e61189fd8f4 | animales = ['perro', 'gato', 'tortuga']
for animal in animales:
print("Un " + animal + " es una excelente mascota.")
print("\nCualquiera de estos animales sería una excelente mascota.")
|
993,950 | 17a303281c94023d5d33893267a4e7f5951cf595 | ############################
# Libraries imports #
############################
from datetime import datetime
import time
import calendar
import json
import math
import os, sys
import socket
import traceback
import urllib2 as urllib
##############################################################################
... |
993,951 | 85db6f5c90bb39d794755709be064046469d43dc | from .producer import producer
import os
class ftree_producer(producer):
name = "ftree_producer"
basecommand = "python3 prepareEventVariablesFriendTree.py"
wz_modules = "CMGTools.TTHAnalysis.tools.nanoAOD.wzsm_modules"
jobname = "happyTreeFriend"
def add_more_options(self, parser):
self.parser = pars... |
993,952 | c073cfb2e35293b730128a03cff7fd4dbe696d5c | import pymysql
# see https://github.com/PyMySQL/PyMySQL/issues/790
pymysql.version_info = (1, 4, 6, 'final', 0)
pymysql.install_as_MySQLdb()
|
993,953 | f1746e3b69cfcb3128c6eb8122115faa0ed5e948 | from rest_framework import viewsets
from resume.models import personal_info, Skill, Education, Achievement
from resume.serializers import personal_infoSerializer, SkillSerializer, EducationSerializer, AchievementSerializer
class personal_infoViewSet(viewsets.ModelViewSet):
queryset = personal_info.objects.all()
ser... |
993,954 | a0b3ed3145193cac1140e49962456552fa76d507 | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from google.appengine.ext import ndb
from common.waterfall import failure_type
from gae_libs.gitiles.cached_gitiles_repository import CachedGitilesRepositor... |
993,955 | 27a768a17fae78262ec96cc692447297855f23f7 | import os
import platform
import sys
import time
import mysql.connector
class User:
def __init__(self):
self.name = None
self.login = None
self.password = None
self.age = None
self.min_age = 10
self.max_age = 150
self.entering_system()
@staticmethod
... |
993,956 | 3295a8653b3c2f407a71e6a97033a0d030901de0 | import discord, asyncio, sys, traceback, checks, asyncpg, useful, credentialsFile
from discord.ext import commands
def getPrefix(bot, message):
prefixes = ["traa!","valtarithegreat!","tt!","tt?"]
return commands.when_mentioned_or(*prefixes)(bot, message)
async def run():
description = "/r/Traa community h... |
993,957 | 001eb264038c4141bc1c7db41580fbda64b10372 | import PIL
import matplotlib.pyplot as plt # single use of plt is commented out
import os.path
import PIL.ImageDraw
def redlogo(original_image,red,template):
""" Rounds the corner of a PIL.Image
original_image must be a PIL.Image
Returns a new PIL.Image with rounded corners, whe... |
993,958 | f2944e50601c9b451b4e303dcc8ecd2b3de1983b | # # -*- coding: utf-8 -*-
# import caffe
# import caffe.proto.caffe_pb2 as caffe_pb2
# from caffe import layers as L, params as P
# import numpy as np
# from utils import conv2d, depthwise_conv2d, bottleneck,heartmap,subnet,deconv_relu
#
# from utils import get_npy, decode_npy_model, decode_pth_model
# import os
# os.e... |
993,959 | d0138e451a25e1b67810b4a7efae176aed743c07 | from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def home_view(request, *args, **kwargs):
print(request.user)
# return HttpResponse("<h1>Welcome Sandesh !!!!</h1>")
my_context = {"name": "I am in Home page", "list": [8, 9, 10, "Abc"]}
return render(requ... |
993,960 | a16cccec4570cced3e6bcbd755a50bbd88f0c716 | from datetime import datetime
from signature import signature
class Bank(object):
def __init__(self, number, type):
self.__number = str(number)
self.__type = type
self.__out = False
self.__signed_in = True
self.__out_log = {}
self.__out_info = {}
self.__retu... |
993,961 | 2e03ed0c2d390aafb378dcc2c1074d0589c2b096 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 22 15:31:04 2021
@author: 70037165
"""
from pulp import *
import pandas as pd
#LpProblem, LpMinimize, LpVariable, lpSum
# Assign spreadsheet filename: file
file = r'C:\Users\70037165\Desktop\SKU Rationalization\SSC for Python.xlsx'
cost_df = pd.read_excel... |
993,962 | 25993ab3cb1b0020932eec54820da0ef5a438c94 | # Generated by Django 3.0.8 on 2021-01-06 23:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('kit', '0008_auto_20210106_2300'),
]
operations = [
migrations.AlterField(
model_name='kit_info'... |
993,963 | 9064e9e82a3ee9f90411135705be0a6b560466fd | #! /usr/bin/env python
#
def r8_li ( x ):
#*****************************************************************************80
#
## R8_LI evaluates the logarithmic integral for an R8 argument.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 25 April 2016
#
# Author:
#
# ... |
993,964 | 1f329fe2a08be5b59dfb868e067207281b6c369c | from moodle import (
__version__,
Auth,
Core,
Mod,
Tool,
Moodle,
)
def test_version():
assert __version__ == '0.14.2'
def test_moodle(moodle: Moodle):
assert isinstance(moodle, Moodle)
assert isinstance(moodle.auth, Auth)
assert isinstance(moodle.core, Core)
assert isinst... |
993,965 | 262c59dc7f53f7b2e92556fa70bd13dd31b20023 | import os
def getfiles(extension):
return [f for f in os.listdir() if f.endswith(extension)]
def writefile(handle, string):
with open(handle, 'w+') as f:
f.write(string)
# Convert Jupyter notebooks to HTML
files = getfiles('.ipynb')
for f in files:
os.system(f"jupyter nbconvert --to html {f}")
... |
993,966 | 7792300008d73347f0d1f65bb51fa7fdb53b4680 | import curses
import pickle
import string # Serialization module for python
class Document:
"""Pages are presumed to have dimensions of 80 wide by 20 tall."""
def __init__(self, filename=None):
self.filename = filename if filename else "binary.bindoc"
self.pages = []
self.... |
993,967 | db6379b741a540836cc00b10aad2cbd691f13d84 | import random
import time
import datetime
import sys
import math
import os
from collections import OrderedDict
from torch import autograd
from torch.autograd import Variable
import torch
import torch.nn as nn
from visdom import Visdom
import numpy as np
import SimpleITK as sitk
def save_numpy(tensor, name):
array... |
993,968 | 4182a2e71f8d328d34e4d2269dcd556fff85555f | ###############################################################################
# Euler 219 - Skew-cost Coding
# Kelvin Blaser 2014.12.31 Happy New Years! Good riddance 2014.
#
# Think about a minimum cost coding of size n-1. To get a prefix-free coding of
# length n, pick one of the strings and add a 0... |
993,969 | a1134167f3b900eb92f8219cc2cfa990d782dbfe | # Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
# If target is not found in the array, return [-1, -1].
# Follow up: Could you write an algorithm with O(log n) runtime complexity?
# Example 1:
# Input: nums = [5,7,7,8,8,10], target = 8
# Ou... |
993,970 | 53770160b3b8b7742aa39d57be85850f7d97610e | from django.conf import settings
from django.contrib.staticfiles.finders import find
from django.contrib.staticfiles.storage import staticfiles_storage, StaticFilesStorage, HashedFilesMixin
from django.utils.safestring import mark_safe
class InlineStaticService:
def get_inline_static(self, name: str) -> str:
... |
993,971 | d4141f52479300a8017e3499ffd3281f6a3235f3 | # Generated by Django 2.2.9 on 2020-05-21 07:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0004_auto_20200520_1753'),
]
operations = [
migrations.AlterField(
model_name='notificac... |
993,972 | 7444e75277332b5acca5a04da91ec718bf5dfcf6 | # spiral.py
# COMP9444, CSE, UNSW
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
class PolarNet(torch.nn.Module):
def __init__(self, num_hid):
super(PolarNet, self).__init__()
self.in_to_hid = nn.Linear(in_features=2,out_features=num_hid,bias=True) #the first layer
#sel... |
993,973 | 18e490b935de3d312b1ccc8fc5c37ad4a4545aba | #!/usr/bin/python
# delete_versions.py
import argparse
from blackduck import Client
from blackduck.Client import HubSession
from blackduck.Authentication import BearerAuth, CookieAuth
import csv
import logging
import sys
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] {%(module)s:%(lineno)d} %... |
993,974 | 817ecc738291a1129d72ad5dffb59c8908ef5d60 | import os, sys, re
from datetime import date
from optparse import OptionParser
from xml.dom.minidom import parse, parseString
import xml.etree.ElementTree as ET
import markup
from markup import oneliner
FILENAME = "filterstats.html"
def write_new_file() :
title = "Filtered Simulation efficiency statistics"... |
993,975 | 142e30f7eda097b0ca2fd8f738b767744dc58c1d | db_path ="sqlite:////home/mdiannna/StartupWeekendBucharest/BookMyEvent/database.db" |
993,976 | 41c451369c5ae04f4ebe16326ba41bc43b616fe4 | #!/usr/bin/env python
import math
import motor_interface
import numpy as np
import rospy
import time
from eraserbot.srv import ImageSrv, ImageSrvResponse, StateSrv, StateSrvResponse
from geometry_msgs.msg import TwistStamped, Vector3
class Controller():
def __init__(self):
#rospy.init_node("Controller")
... |
993,977 | 0ba42df509f06a8454628656a5da29cb6b2d6d9c | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 3 21:47:08 2016
@author: nam
"""
import mmRef;
class TrainService():
def __init__(self, trainLine, servcName, newTimetable, initPaxOnTrain, pcPaxRem, paxRem):
self.name = servcName;
self.line = trainLine;
self.timetable = newTimet... |
993,978 | 7f0d733b8de1756e9c863afe04c6af053015c290 | # Generated by Django 2.1.5 on 2019-01-23 06:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mapdata', '0002_auto_20190123_0010'),
]
operations = [
migrations.CreateModel(
name='Literacy',... |
993,979 | 0771ebf65935628b754f1cf4b79ce1bacb21bb58 | """
Write a Python function that takes a number as a parameter and check the
number is prime or not.
Note : A prime number (or a prime) is a natural number greater than 1 and that
has no positive divisors other than 1 and itself.
"""
def func(nums):
if nums < 100:
for i in range(2 , nums):
if ... |
993,980 | bce27e0073f93bd01c44788a890e57ee1a616c37 | from hashlib import md5
from django.utils.functional import cached_property
from web.models.post import Post
from django.core.paginator import Paginator
from django.shortcuts import render
from django.core.cache import cache
from web.models.comment import Comment
from web.helpers.composer import get_posts_by_cid
from d... |
993,981 | d7e8656bb6a9e22298e82020474010a20b1adf2d | # Generated by Django 2.2 on 2020-03-22 15:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('session', '0020_auto_20200314_1603'),
]
operations = [
migrations.AddField(
model_name='gig',
name='type',
... |
993,982 | b5bf4d45ec532819db9b1bc96aafec58907e74a1 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 14 14:33:44 2020
@author: wenninger
"""
from argparse import ArgumentParser
import matplotlib.pyplot as plt
import numpy as np
import scipy.constants as const
import os
import sys
sys.path.insert(0, '../Helper')
from Cooper_Pair_Tunnelling_Current... |
993,983 | 95f95cb7909dc39645281e60db52b9e9201e9b98 | # -*- coding: utf-8 -*-
s = raw_input()
t = raw_input()
import string
lower = string.lowercase
upper = lower.upper()
class mydict(dict):
def __missing__(self, key):
self[key] = 0
return self[key]
ds = mydict()
dt = mydict()
for i in s:
ds[i] += 1
for i in t:
dt[i] += 1
cnt1 = 0
cnt2 = 0
for key in... |
993,984 | 53b00e3b96be6ce40f8a938dc91481a982b96b45 | import json
import logging
import os
import sys
from Utils import Utils
payment_plans = [] #payment plans data
debts_with_Is_payment_field = [] # debts objects linked to payment plans
debts_with_payment_plans ={} # dic to hold debtId along with payment plans details
logger = logging.getLogger(__name__)
logger.setLeve... |
993,985 | 3fb4a522861fca51b2f54d48c9cc9c28120280aa | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: exercise12
Description :
Author : burt
date: 2018/11/7
-------------------------------------------------
Change Activity:
2018/11/7:
---------------------------------------------... |
993,986 | cdc13ea21e7687b9d16d5f470f28b3f402076c7d | #!/usr/bin/env python
# coding: utf-8
# ### ques1
# In[1]:
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
# ### ques5
# In[8]:
a=input("enter a string\n")
len(a)
# ### ques6
# In[10]:
a=input("enter a string\n")
count=0
for char in a:
... |
993,987 | 35b1096faafbc615f312a4f5ba1096fe7f234aea | #6. Escribe una funci�n de Python que tome una lista de palabras y devuelva la longitud de la m�s larga.
def funcion(lista):
cadena=lista[0]
tamaño=len(lista[0])
for palabra in lista:
if tamaño <=len(palabra):
cadena = palabra
tamaño = len(palabra)
else:
... |
993,988 | 89b243884a9de98afcc9f1d0bec14237ea0dda44 | import common
data = common.gen_rand_list(6, 1, 100)
print data
def msort(l, u):
if l >= u:
return [data[l]]
m = int((l + u) / 2)
msort(l, m)
msort(m + 1, u)
merge(l, m, u)
def merge(l, m, u):
i = l
j = m + 1
#print l, m, u, data[l:m+1], data[m+1: u+1]
while(i != j and j != u + 1):
if data[i] >= data... |
993,989 | fbe3783103b9593904515e67818404020568ade3 | from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.sites.shortcuts import get_current_site
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string
fr... |
993,990 | 20b9c1570457e181907684785c4d8388d816ec84 | #!/usr/bin/env python
"""Kegboard daemon.
The kegboard daemon is the primary interface between a kegboard devices and a
kegbot system. The process is responsible for several tasks, including:
- discovering kegboards available locally
- connecting to the kegbot core and registering the individual boards
- accum... |
993,991 | 9eb367bc220e09cdae4f2cd2583295a5b8d25f02 | from lib.recordset import DB
from classes.logger import log
class User:
user_id = None
first_name = None
last_name = None
username = None
language_code = None
def __init__(self, user_id, first_name, last_name, username, language_code):
self.user_id = user_id
self.first_name = ... |
993,992 | 7324ca1e8025b34815f0447ad89c0becd406a8df | import sys
from Views import PrimeiraWindow
from Controller.controllerView import *
class MeuApp(QtWidgets.QMainWindow, PrimeiraWindow.Ui_MainWindow):
def __init__(self, parent=None):
super(MeuApp, self).__init__(parent)
# parametros
self.controler = ControllerView()
# métodos_Ex... |
993,993 | 4184f6815e8024cbfe231495d20bed9465758b2f | import os
from collections import namedtuple
import re
import csv
from pathlib import Path
def _is_file(path_dir, child):
return os.path.isfile(os.path.join(path_dir, child)) and (child != "__init__.py") and (child.split(".")[1] == "py")
def _is_directory(path_dir, directory):
return directory != "__pycache_... |
993,994 | dc4d8090736cab5e4931f5ebaf7ab2e5696f6cde | # -*- coding: utf-8 -*-
import itchat as IC
from itchat import auto_login as login
print ("itchat Start!")
login (hotReload=True)
IC.send('Test 中文(全角字符utf-8),发给自己', toUserName='wzk.py')
|
993,995 | 6c869ef538761daa80444aa2a5578142961a46f5 | # DAILY CODE MODE
# symbol = "*"
# n = 4
#
# print(symbol + " : " + " ".join([str(x) for x in range(n)]))
# answer = []
# for i in range(n + 1):
# answer.append([str(i) + " : "])
# for j in range(n + 1):
# if symbol == "+":
# answer[i].append(str(i + j))
# elif symbol == "-":
# ... |
993,996 | 9c545de16979be59db3eef171e06ed4d09b85343 | def find_power_sum(n):
sum_=0
num_list=list(str(n))
for x in num_list:
sum_+=int(x)**5
if sum_==n:
return True
summ=0
for x in range(2,1000000):
if find_power_sum(x):
summ+=x
print(f'Sum: {summ}') |
993,997 | d449e5fab869ef4fa970a24dde301475a27cc4dd | # -*- coding: utf-8 -*-
import os
import json
import requests
from flod_common.session.utils import unsign_auth_token
USERS_URL = os.environ.get('USERS_URL', 'http://localhost:4000')
USERS_VERSION = os.environ.get('USERS_VERSION', 'v1')
def is_super_admin(cookies=None):
if cookies:
if 'auth_token' in ... |
993,998 | 8301e7ce2e1b44989a75c14492a00ff05929be7d | # coding:utf-8
import sys
import time,datetime
import os
import commands
import re
#根据各自业务判断是否需要处理,跟输出目录比较是否处理过也可在此处进行
def is_need_process(file_path):
is_need_process = False
if file_path.endswith(".hdf"):
is_need_process = True
return is_need_process
#获取需要处理的文件
def get_files(input_path):
i... |
993,999 | 356735db66870ffa21bbabafa2996b0107a30d48 | # -*- coding: utf-8 -*-
"""
@author: Quoc-Tuan Truong <tuantq.vnu@gmail.com>
"""
from cornac.utils import tryimport
def test_tryimport():
dummy = tryimport('this_module_could_not_exist_bla_bla')
try:
dummy.some_attribute
except ImportError:
assert True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.