index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
9,000 | 5044b8bc8cabd7762df6a0327828df4546ab8d96 | import cv2
import imutils
import detect
def detectByPathVideo(path, writer):
video = cv2.VideoCapture(path)
check, frame = video.read()
if check == False:
print('Video Not Found. Please Enter a Valid Path (Full path of Video Should be Provided).')
return
print('Detecting p... |
9,001 | f5e57c95e2c86aeb83872b29324b0b73a41caa47 | #!/usr/bin/python
from PyQt4 import QtCore, QtGui
import sys
import json
import re
from Interface_Recommended_Results import obtain_list
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(co... |
9,002 | 06161b1f45e435d0273dd193229ad2ecfd46c625 | from ob import *
if __name__ == "__main__":
# Game starts
print('New game!')
# Deal
deck = Deck()
deck.shuffle()
players = deck.deal()
# Bid
auction = Auction(players)
auction.bid()
# Play
tricks = Tricks(auction)
tricks.play()
|
9,003 | a139042d0c6fa4941b7149a33b0a48018e9f511b | from django.contrib.auth.models import User
from django.core import validators
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import Group
from django.conf import settings
@receiver(post_save, sender=settings.AUTH_USER_... |
9,004 | 39bc90f34cccebe9a8b1475e396caa1c14f6b2df | import unittest
import sys
from tests.jep_pipe import jep_pipe
from tests.jep_pipe import build_java_process_cmd
import jep
@unittest.skipIf(sys.platform.startswith("win"), "subprocess complications on Windows")
class TestSharedModules(unittest.TestCase):
def setUp(self):
pass
def test_shared_module... |
9,005 | 531d1cab3d0860de38f8d1fefee28f10fc018bdb | from django.shortcuts import get_object_or_404, render
from django.http import Http404
from django.urls import reverse
# Create your views here.
from django.template import loader
from django.http import HttpResponse, HttpResponseRedirect
from .models import Categories, News, SalesSentences
from .models_gfl import Info... |
9,006 | 094e7c150456888389c764d4dd7bf3c9a87a022c | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
import json
import requests
import time
import logging
import numpy as np
from matplotlib import path
from geometry_msgs.msg import PoseWithCovarianceStamped
from std_msgs.msg import String
from people_msgs.msg import People
import rsb
import sys
# -busy stat... |
9,007 | 2e8d39d6d72672de8e4eac8295b90d68b1dff938 | '''
A linear regression learning algorithm example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
from __future__ import print_function
import tensorflow as tf
import argparse
import numpy
rng = numpy.random
#"python tf_cnn_benchmarks.py --device... |
9,008 | 2876c9f8db0395143b165b855b22e364e3cc8121 | import sys
a = 3
b = 4
c = 5.66
d = 8.0
e = complex(c,d)
f = complex(float(a),float(b))
print("a is type:",type(a))
print("c is type:",type(c))
print("e is type:",type(e))
print(a + b)
print(d / c)
print(b / a)
#2个除约成整型
print(b // a)
print(e)
print(e + f)
print(sys.float_info) |
9,009 | de4e14a4fa8520c1aae60805084224337dd9620c | # -*- coding:utf-8 -*-
#随机森林调参
#RandomizedSearchCV 随机最佳
#GridSearchCV 地毯式最佳
import pandas as pd
features = pd.read_csv('data/temps_extended.csv')
features = pd.get_dummies(features)
labels = features['actual']
features = features.drop('actual', axis = 1)
feature_list = list(features.columns)
import numpy as np... |
9,010 | d8ba2557e20920eaadd2fd35f0ebdf1b4a5b33da | """Unit tests for misc. ticket functions."""
from pdm_utils.classes import bundle
from pdm_utils.classes import genome
from pdm_utils.classes import ticket
from pdm_utils.classes import eval
from pdm_utils.functions import tickets
from pdm_utils.constants import constants
import unittest
class TestTicketFunctions... |
9,011 | fcf4cb5c47e4aa51d97b633ecdfec65246e82bd8 | from tkinter import *
from tkinter.scrolledtext import ScrolledText
def load():
with open(filename.get()) as file:
# delete every between line 1 char 0 to END
# INSERT is the current insertion point
contents.delete('1.0', END)
contents.insert(INSERT, file.read())
def save():
with open(filename.g... |
9,012 | 6f53702d9265a7fc57d2ec2e47dc35a0bc7a9f87 | from pydub import AudioSegment
import sys
import tensorflow as tf
import numpy as np
from adwtmk.audio import Audio
from adwtmk.encoder import *
from adwtmk.decoder import *
class DAE(object):
def __init__(self,model_name):
self.model_name = model_name
self.process = 0
self.loss = 0
... |
9,013 | 8aacc8dbfdd70d24689ae17b9c29b1ffc80fb231 |
from Models.AdminPageModel import AdminPageModel
class StudentDebtsController:
def __init__(self, master, model, view):
self._master = master
self._model = model
self._view = view
def BackToAdminPage(self):
from Views.AdminPage import AdminPage
self._master.switch_fra... |
9,014 | e221b840239b6e9af735238760fd1157f333c1a4 |
def filter_long_words(word_lng, words_list):
return [word for word in words_list if len(word) > word_lng]
assert filter_long_words(5, ['piwo', 'wino', 'czasopisma', 'ubrania', 'napoje']) == ['czasopisma', 'ubrania', 'napoje']
|
9,015 | e307bcc28526081141f1f2204c225d8e5f0100a8 | # Generated by Django 3.0.3 on 2020-04-24 14:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('HMS', '0009_auto_20200329_0911'),
]
operations = [
migrations.CreateModel(
name='mess_timetable',
fields=[
... |
9,016 | 5d568c5ac9040ad93749c27bd6fe1a956e7456f7 | #!/usr/bin/env python3
# crits_ldap.py
# This connects to an LDAP server and pulls data about all users.
# Then, it either updates existing targets in CRITS or creates a new entry.
import json
import sys
import datetime
import logging
import logging.config
from configparser import ConfigParser
from ldap3 import Serve... |
9,017 | 4bdff51a4e277889f4d54d4ace7a0f5384e74f1e | import argparse, os, joblib, json, torch
import pandas as pd
from utils import regression, dataset, lstm
PREDICT_X_SKIP_COLS = ["date", "weight", "ts_id", "resp", "resp_1", "resp_2", "resp_3", "resp_4"]
X_COLS = ["resp_1", "resp_2", "resp_3", "resp_4"]
Y_OUTPUT_COLS = ["date", "ts_id"]
Y_COL = ["resp"]
METRICS_INFO = ... |
9,018 | da062dfe494b363c8ef3ec9f19af912736aaf77b | """DogGroom URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
9,019 | 5961c593b46a8d3a0f7c62d862cce9a2814e42f4 | from typing import List
import uvicorn
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from . import crud, models, schemas
from .database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
def get_db():
db = SessionLocal()
try:
... |
9,020 | 644d0a0d88f1a051e004d271359dcc3df855bd77 | speak = 'speak'
def hacker():
try:
raise speak # go to hacker's except
print 'not reached'
except speak:
print 'Hello world!'
raise speak # go to primate's except
def primate():
try:
hacker()
print 'not reached'
except speak:
... |
9,021 | 265c594b12ea45a2dda12e1157e5ea040f4d6ce4 | from Logic.ProperLogic.helper_classes.reducer import MaxReducer
from Logic.ProperLogic.misc_helpers import log_error
import torch
from itertools import count
import logging
logging.basicConfig(level=logging.INFO)
class Cluster:
metric = 2
def __init__(self, cluster_id, embeddings=None, embeddings_ids=None,... |
9,022 | 14ce803e3deb529b489c150c7ecc702118448acb | from typing import Union, Tuple
import numpy as np
from UQpy.utilities.kernels.baseclass.GrassmannianKernel import GrassmannianKernel
class ProjectionKernel(GrassmannianKernel):
def __init__(self, kernel_parameter: Union[int, float] = None):
"""
:param kernel_parameter: Number of independent p-... |
9,023 | 485729398b51bebd16f38800c6100289b7b0b347 |
import sys
if sys.hexversion < 0x03000000:
from .foo import foo
|
9,024 | d7e24730ce9f2835d55d3995abec2a7d00eb05ef | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the
# Pystacho Project (https://github.com/aruderman/pystacho/).
# Copyright (c) 2021, Francisco Fernandez, Benjamin Marcologno, Andrés Ruderman
# License: MIT
# Full Text: https://github.com/aruderman/pystacho/blob/master/LICENSE
# ===... |
9,025 | 4830da6bee6b19a5e5a82a73d2f3b220ca59d28b | from .linked_list import LinkedList
class Queue:
def __init__(self):
self.list = LinkedList()
def enqueue(self, value):
self.list.insert_last(value)
def dequeue(self):
element = self.list.get_head()
self.list.remove_first()
return element
def front(self):
... |
9,026 | 4bbd97942023370e053ccf4b5c1496c7247c7bf2 | #!/usr/bin/env python
# encoding: utf-8
from rest_client import PY2
from tornado.testing import gen_test
from tornado.web import Application, RequestHandler
from .server import AsyncRESTTestCase
class Handler(RequestHandler):
if PY2:
S = '\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82 \xd0\xbc\xd0\xb8\x... |
9,027 | 63391b31d1746f9b3583df5353ae160a430943a9 | a, b = input().split()
def test_input_text(expected_result, actual_result):
assert expected_result == actual_result, \
f'expected {expected_result}, got {actual_result}'
test_input_text(a,b)
|
9,028 | c8f899958ce19e7e2bf1307a685e65873695f140 | from utils import *
import math
class State:
"This class represents the search state that will be used for ARA* search"
def __init__(self, x, y, theta, parent=None, parent_action=None, g=float('inf'), h=float('inf')):
self.x = x
self.y = y
self.theta = theta % (2*math.pi)
self.g... |
9,029 | 5ed91b98ece3ac9525e9d2c42db9c9d9912d5ed2 | import random
'''
通用文件头,浏览器访问时随机选择
'''
user_agent = [
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
"Mozilla/5.... |
9,030 | 8262d8b5bbb156eccae021c1c9333d3cd1a6260f | import requests, csv, configuration
headers = {'Authorization': f'Bearer {configuration.CARRIERX_API_TOKEN}'}
url = f'{configuration.BASE_CARRIERX_API_URL}/core/v2/calls/call_drs'
date = configuration.DATE
i = 1
params = {
'limit': '1',
'order': 'date_stop asc',
'filter': f'date_stop ge {date}'
}
r = requests.get(url... |
9,031 | a14c23398bbf42832a285d29c1b80aefc5fdaf6c | import numpy as np
import cv2
import datetime
import random
# from random import randint
import time
import logging
def GetDateTimeString():
dt = str(datetime.datetime.now()).split(".")[0]
clean = dt.replace(" ","_").replace(":","_")
return clean
def GetBackground(bgNumber):
# bgImage = './backgrounds... |
9,032 | 5ec2ac3e0d66026da1b0c957d10c95e95c201f8f | '''
Useful constants.
Inspired by pyatspi:
http://live.gnome.org/GAP/PythonATSPI
@author: Eitan Isaacson
@copyright: Copyright (c) 2008, Eitan Isaacson
@license: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the ... |
9,033 | bde37f3b41c810ab465de5e0ae374703af9f01f3 | # -*- coding: utf-8 -*-
def create_map(rows):
maze = []
for row in rows:
row = row[:-1]
subarr = []
for i in row:
subarr.append(i)
maze.append(subarr)
return maze
def print_map(chart):
for subarr in chart:
print(subarr)
def find_start(chart):
... |
9,034 | dd4892c5a0b675d1c97fb91a5ca8115801a2bbca |
import sys
import datetime
training = False if (sys.argv[1]=='0') else True
def read_file(filename):
with open(filename) as f:
aux = [str(x) for x in f.readline().split()]
array = []
for line in f: # read rest of lines
s=line.split()
array2=[s[0]] + [float(x) for x in s[1:]]
ar... |
9,035 | eb8aec947cc1eeeb56b3884286b46ec7468dcc23 | import requests
from app.main.model.location import Location
from app.main.util.db_util import save_changes
key = 'a544aecdde85a1f52a56292f77ecde6e'
def save_location(ip_addr):
try:
existing_location = Location.query.filter_by(ip=ip_addr).first()
if existing_location:
location_data = ... |
9,036 | 70de2bed00aabe3805c3a19da004713d4109568a | ##Extras
def permissao():
editor = False
for row in session.auth.user_groups:
grupo = session.auth.user_groups[row]
if (grupo == "gerenciador") or (grupo == "administrador"):
editor = True
return editor |
9,037 | 57ab0421d5234caf7a97ce93908cd07e23f53a0b | import copy
import time
import random
from twisted.python import log, failure
from twisted.internet import defer, error, protocol, reactor
from twisted.protocols import basic, policies
from pn.util import url
from pn.core import stream as stream_mod
try:
from collections import deque
except ImportError:
class dequ... |
9,038 | b0f0bcfb5739d46de54cbe46614e82bf5a2d13fb | """
* author - kajol
* date - 12/24/2020
* time - 1:24 PM
* package - com.bridgelabz.basicprograms
* Title - Print a table of the powers of 2 that are less than or equal to 2^N
"""
try:
number = int(input("Enter number: "))
#print power of 2 within given range
if number < 31:
for num... |
9,039 | d3b55863c6e3a1b6cbdcec37db81ee42b769938d | from setuptools import setup
import sys
if not sys.version_info >= (3, 6, 0):
msg = 'Unsupported version %s' % sys.version
raise Exception(msg)
def get_version(filename):
import ast
version = None
with open(filename) as f:
for line in f:
if line.startswith('__version__'):
... |
9,040 | c2ba60a321eff63f6321831093d7254f6939549b | #encoding:utf-8
x="There are %d types of peopel."%10
#定义字符串变量x,将10以%d方式输出
binary="binary"
do_not="don't"
#定义字符串变量binary和do_not
y="Those who know %s and those who %s."%(binary,do_not)
#使用binary和do_not定义字符串变量y
print x
print y
#打印以上两个变量
print "I said:%r"%x
print "I also said:%r."%y
#用%r的格式输出以上两个变量
hilarious=False
joke_... |
9,041 | 8675deb69eae04a722073432eaf69ce3d24a11ad |
# coding: utf-8
from mrcnn import utils
import numpy as np
import os
import skimage
class SlicesDataset(utils.Dataset):
""" Extension of maskrcnn dataset class to be used with our provided data. """
def load_slices(self, dataset_dir, n_images, n_patches, channels = ["base"]):
"""Load a ... |
9,042 | 39312ec60c9ef1c9c95cf4206b6d0bbdb0aedf94 | from rest_framework import serializers
from .models import SensorValue
class SensorValueSerializer(serializers.ModelSerializer):
timestamp = serializers.DateTimeField(required=False)
class Meta:
model = SensorValue
fields = ("id", "timestamp", "sensor_type", "value")
|
9,043 | 93baa6ba14d06661731dce3e34ea93d49c06001b | my_func = lambda x, y: x**y
|
9,044 | f73cbc25152a63bb6552e2cd8272c67a1f4277ba | def main():
a, b = map(int, input().split())
diff = abs(max(b, a) - min(a, b))
if diff % 2 != 0:
print("IMPOSSIBLE")
else:
bigger = max(a, b)
ans = bigger - (diff//2)
print(ans)
if __name__ == "__main__":
main()
|
9,045 | 1dec7a997b0bef3226fb17e4039b053c7a2e457e | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-03 19:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mybus', '0007_auto_20160104_0053'),
]
operations = [
migrations.RemoveField(... |
9,046 | fd6a32652b845b2a6d6d8934c0dde91afdddd9f3 | from django import urls
from django.urls import path
from genius.views import (home, Class_create, Class_Update, Class_Delete, Class_Detail, Classes, Add_name,
Student_Main, Student_Create, Student_Update, Student_Delete, Student_Detail, Search)
app_name = 'genius'
urlpatterns = [
path('... |
9,047 | 8c17f2c770c24bbf8c73628c6740c0b866e6b1c0 | from liver_tumor_segmentation.CGBS_Net import *
from liver_tumor_segmentation.loss import *
from keras.optimizers import *
from liver_tumor_segmentation.CGBS_data_generator import *
from keras.callbacks import *
import os
from keras.callbacks import ReduceLROnPlateau
from keras import losses
from configuration... |
9,048 | 8a2cf1d550a593beae579104413b424e007d511f | '''
"MAIN" module
All operations are added to the defaultgraph.
Network functions are found in module network_functions_2
Display graph in tensorboard by opening a new terminal and write "tensorboard --logdir=tensorbaord/debug/01/" where
the last number depends on which directory the current graph is saved in (see l... |
9,049 | 8b49aa63cc6e4490b7b22cd304dbba132962c870 | from abc import abstractmethod
from suzieq.shared.sq_plugin import SqPlugin
class InventoryAsyncPlugin(SqPlugin):
"""Plugins which inherit this class will have methods 'run'
Once the controller check that the object inherit this class, it launches
a new task executing the run method.
"""
async d... |
9,050 | 3b1b3cab1fa197f75812ca5b1f044909914212c0 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import seaborn as sns
# In[2]:
df = pd.read_csv("ipl_matches.csv")
df.head()
# In[3]:
## -----data cleaning------
## remove unwanted columns
columns_to_remove = ['mid','batsman','bowler','striker','non-striker']
df.drop(la... |
9,051 | 80a397b0974e41c4669f07638b5b38830b58cb37 | import pytest
import mock
from awx.main.models import (
UnifiedJob,
WorkflowJob,
WorkflowJobNode,
Job
)
def test_unified_job_workflow_attributes():
with mock.patch('django.db.ConnectionRouter.db_for_write'):
job = UnifiedJob(id=1, name="job-1", launch_type="workflow")
job.unified_... |
9,052 | c2c51dcd05c21e91e591de25fc2de034c88c48a1 | #!/usr/bin/env python
from django import template
from django.conf import settings
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def website_title():
return settings.WEBSITE_TITLE
def split_page(result_obj):
"""
分页模块,后台传入一个分页结果集就可以
:param result_obj:
... |
9,053 | 70325d0e5eb9dcd7a065f83eaf14647bc30bd7f3 |
#----------- writing our for loop
""" number = [1,2,3,4,5]
friends = ['ahmet', 'mehmet','ayşe']
# for n in number:
# print(n)
# for n in friends:
# print(n)
def my_for_loop(my_iterable):
my_iterator = iter(my_iterable)
while True:
try:
print(next(my_iterator))
except StopI... |
9,054 | 93eafb5b23bac513fc5dcc177a4e8a080b2a49b4 | #-*-coding:utf-8 -*-
import subprocess
def get_audio(text):
stat = subprocess.call(['./tts', text])
if stat == 0:
return "Success"
else:
print "Failed"
if __name__ == '__main__':
text = "我是聊天机器人"
get_audio(text) |
9,055 | b28bada020ac593783ac62994bb45311ebb78813 | """
测试用例
"""
import unittest
import jsonpath
import requests
from apiunittest.lib.loadIni import LoadIni
from apiunittest.keyword.keyword import Keyword
from apiunittest.lib.log import logger
from ddt import ddt, file_data
@ddt
class ApiTest(unittest.TestCase):
@classmethod
def setUpClass... |
9,056 | 2e571e3412bf9f3a42bf87976ea9a5ec68d5815c | import requests
from bs4 import BeautifulSoup
import urllib.request
url='http://www.dytt8.net/'
user={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
html=urllib.request.urlopen(url)
html.encoding='utf-8'
soup=BeautifulSoup(... |
9,057 | cf931da4c06e16fe6f6da5eb1826d8b7a59c1f7b | # Copyright 2013 Rackspace Hosting Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
9,058 | df60d3b829c5702385f59fdefaea04f569fb7db2 | #!/usr/bin/python
# Original code found at:
# https://github.com/zzeromin/raspberrypi/tree/master/i2c_lcd
# requires I2C_LCD_driver.py
import I2C_LCD_driver
from time import *
import os
mylcd = I2C_LCD_driver.lcd()
mylcd.lcd_clear()
mylcd.lcd_display_string("RAS Hi-Pi shutdown", 1)
mylcd.lcd_display_string(" See yo... |
9,059 | 1a166a08c835caa8dd308d59227051751aff7c0f |
# coding=utf-8
from numpy import *
""" 1
函数loadDataSet()创建了一些实验样本。 该函数返回的第一个变量是进行词条切分后的文档集合, 这些文档来自斑点犬爱好者留言
板。 这些留言文本被切分成一系列的词条集合, 标点符号从文本中去掉,
loadDataSet( )函数返回的第二个
变量是一个类别标签的集合。 这里有两类, 侮辱性和非侮辱性。 这些文本的类别由人工标注, 这些标注信息用于训练程序以便自动检测侮辱性留言
"""
def loadDataSet():
postingList=[['my', 'dog', 'has', 'flea', 'problems', ... |
9,060 | 0c297e6f79682896e98c7a2933a4da6d9af7d7fe | #juego trivia hecho por mayu xD
print('¡hola! te invito a jugar mi juego trivia, trataremos temas como termux xd y entre otras cosas')
n1 = input('\n por favor dime como te llamas:')
print('\nmucho gusto', n1, ',empecemos')
puntaje = 0
print('me puedes decir con que comando en linux puedo listar la informacion de ... |
9,061 | 035de226c2d2ee85cb7e319de35fb09b21bc523d | from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from analyze import views
#from lecture import views
urlpatterns = patterns('',
url(r'^$', 'analyze.views.analyze', name='analyze'),
)
|
9,062 | 24187284ff3e03cf79b8545415005c71f9355ddc | flags =[]
sourcefiles:str = []
headerfiles:str = []
mainfile:str = ""
outfilename = "a.out"
assemblyfilename = "a.asm"
includedfilenames = []
class Variables:
size:bytes
name:str
class cstruct:
structname:string
def claprocessor():
print(sys.argv)
i=0
for stri in sys.argv:
if stri.... |
9,063 | 3240310653930662dcc4d79646b1a75c2994cda7 | #coding: utf-8
#/usr/bin/python
__author__='julia sayapina'
### Use db_reset.py to drop the db and recreate it, then use 'migrate' --> 'createsuperuser' --> 'makemigrations' --> 'migrate' as usual.
### This will create the DB structure as it has to be from django
### Then use test_db_fullfill.py to fullfill the db wit... |
9,064 | 6aa74826f9ca0803fa8c1d5af1d4cec4980e2ce6 | import numpy as np
from scipy.stats import multivariate_normal
from functions.io_data import read_data, write_data
np.random.seed(0)
class IsingModel():
def __init__(self, image, J, rate, sigma):
self.width = image.shape[0]
self.height = image.shape[1]
self._J = J
self._rate = rat... |
9,065 | a8d13c3fbf6051eba392bcdd6dcb3e946696585f | import itertools
def zbits(n,k):
zeros = "0" * k
ones = "1" * (n-k)
binary = ones+zeros
string = {''.join(i) for i in itertools.permutations(binary, n)}
return(string)
assert zbits(4, 3) == {'0100', '0001', '0010', '1000'}
assert zbits(4, 1) == {'0111', '1011', '1101', '1110'}
assert zbits(5, 4)... |
9,066 | 68bade5767d4f418bcae07485a179df5e47e652c | DEBUG = True
ADMINS = frozenset(["briandowe@gmail.com"]) |
9,067 | e92a738d3233450b255605619dafadd4d829604b | #!/usr/bin/python3
from optparse import OptionParser
from urllib import request, parse
from urllib.error import URLError, HTTPError
import ssl
import re
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context.options &= ssl.CERT_NONE
class Settings:
SINGLETON = None
def __init__(self):
self.... |
9,068 | 4774c1f4eafc0132bab0073b60c4bcad6b69380d | import shlex
class MockSOLR(object):
class MockHits(list):
@property
def hits(self):
return len(self)
@property
def docs(self):
return self
def __init__(self):
self.db = {}
def add(self, objects):
for o in objects:
o['... |
9,069 | 8020bac94de3e68193c9891a628a48c537c5afa0 | from menu_sun_integration.application.adapters.customer_adapter import CustomerAdapter
from menu_sun_integration.infrastructure.brf.builders.brf_base_builder import BRFBaseBuilder
from menu_sun_integration.infrastructure.brf.translators.brf_customer_translator import BRFCustomerTranslator
class BRFCustomerBuilder(BRF... |
9,070 | 4b3de2d817aa6f8b92d513bcdba612362becefdc | #!/usr/bin/env python
from bumblebee.motion import *
from simulation.path import *
from simulation.settings import *
import tf.transformations
from geometry_msgs.msg import TransformStamped,Transform,Quaternion,Vector3
from bumblebee.baseTypes import basicGraph,slidingGraph
from simulation.dataset import stereo_simul... |
9,071 | 97720baab961d50ceae832d52350b9871c552c84 | n,k=map(int,input().split())
k_list=[]
for i in range(k):
l,r=map(int,input().split())
k_list.append([l,r])
dp=[0]*(n+1)
dp[1]=1
dpsum=[0]*(n+1)
dpsum[1]=1
for i in range(1,n):
dpsum[i]=dp[i]+dpsum[i-1]
for j in range(k):
l,r=k_list[j]
li=i+l
ri=i+r+1
if li<=n:
... |
9,072 | 9f6e5c219f7b668720b5379dde912ff22ef434d1 | #!/usr/bin/env python3
import json
import sqlite3
import sys
from scorelib import *
#from .scorelib import *
from collections import defaultdict
def __map2list(mp):
if len(mp.keys()) == 0:
return []
lst = [None] * max(mp.keys())
for idx in mp.keys():
lst[idx-1] = mp[idx]
return lst
d... |
9,073 | c1f432ff70b21064f36cf9651f8cff9c69361d5c | # from django.contrib.auth import forms
# class UserRegister(froms.M):
# class Meta:
# fields = []
|
9,074 | d88485e37d4df4cb0c8d79124d4c9c9ba18d124e | #!/usr/bin/python
from Tkinter import *
root = Tk()
root.title("Simple Graph")
root.resizable(0,0)
points = []
spline = 0
tag1 = "theline"
def point(event):
c.create_oval(event.x, event.y, event.x+1, event.y+1, fill="black", width="10.0")
points.append(event.x)
points.append(event.y)
print(event.x)
print(ev... |
9,075 | a5e693a79211570f2d27575657496992f8fee164 | import random
def less(i1, i2):
return i1[0] * i2[1] < i2[0] * i1[1]
def equal(i1, i2):
return i1[0] * i2[1] == i2[0] * i1[1]
def more(i1, i2):
return i1[0] * i2[1] > i2[0] * i1[1]
def partition(x, l, r, pivot):
il = l
ir = l
for i in range(l, r):
if x[i] < pivot and ir < r:
... |
9,076 | 0fdbdfe98496ebedb112c85b79836292ffa3a5a9 | """
If you are using MultiScript Editor make sure to set PYTHONPATH to Winexs' editor.
You can use set PYTHONPATH=c:/users/username/myscripts
Set paths according to your project!
"""
CHROME_WEBDRIVER = 'c:/users/username/project/chromedriver.exe'
WEBSITE_PDF_CONVERTER = 'https://www.ilovepdf.com/merge_pdf'
PDF_FILES ... |
9,077 | 7f131e17f4fbd7d6b333a51dae557ddb07c30046 | #!/usr/bin/env python
# -*-coding:utf-8-*-
# Author:SemaseMing <blog.v-api.cn>
# Email: admin@v-api.cn
# Time: 2016-10-19 11:56
import gevent
def foo():
print('Running in foo')
gevent.sleep(0)
print('Explicit context switch to foo ageni')
def bar():
print('Explicit context to bar')
gevent.sleep... |
9,078 | b9e78629fe094d933fdc0ffa2f9d9d1880e78c12 | import pandas as pd
import numpy as np
import sys
#Best Mean Test
if len(sys.argv) <= 3:
print("Not enough args usage: anova.py <*.csv> <rv1,rv2> <target to beat>")
print("ex: best-mean.py testdata.csv nicdrop 95000")
print("<rv> is response variable")
exit()
target_to_beat = int(sys.argv[3]) #factors
rv = sys.ar... |
9,079 | ad09880b9e06a129b9623be2a086ebcc8dc55c2c | """Module containing class `Station`."""
from zoneinfo import ZoneInfo
import datetime
from vesper.util.named import Named
class Station(Named):
"""Recording station."""
def __init__(
self, name, long_name, time_zone_name,
latitude=None, longitude=None, elevation=None... |
9,080 | dab5e7ee1d14cba485cbaece1354ec8d686ca4ab | # coding=utf-8
while True:
a,b=input().split()
a=float(a)
b=float(b)
if b==0:
print("error")
else:
c=a/b+0.5
c=int(c)
print(c) |
9,081 | 480e595c54da7426951d750187712fecdcb6d8c7 | ## SOLVED
## the possible way of solving this is to make a scoring of the hand
## of each player, by encoding the category of winning and the cards
import csv
value = ['2','3','4','5','6','7','8','9','T','J','Q','K','A']
val_order = {k:v for v,k in enumerate(value)}
def compute():
poker_hand = load_data()
ans... |
9,082 | c0e94a0d20397ebbbdddf726307b19b6c5c85ae6 | # -*- coding: utf-8 -*-
import graphviz
import fa_util
class Graph:
def draw(self, directory, filename, rules, start_state, accept_states):
g = graphviz.Digraph(format="svg", graph_attr={'rankdir': 'LR'})
self.add_start_edge(g, start_state)
edges = {}
for rule in rules:
... |
9,083 | 599da0f045ab5c2b3f568def3d89452b56cac029 | #!/usr/bin/env python
'''
Generate tree search dot file
'''
import copy
# Colors supported by graphviz, in some pleasing order
colors = {
"fa": "brown",
"fb": "brown1",
"ea": "cadetblue",
"eb": "cadetblue1",
"pa": "orange",
"pb": "orange4"
}
curId = 1
capAset = 4
capBset = 7
goal = 2
de... |
9,084 | 6fdc9b2091652b05d6c1207d2f78b75c880fadda | __author__ = 'Administrator'
class People:
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
pass
print("%s is eating..." % self.name)
def sleep(self):
print("%s is sleeping..." % self.name)
def talk(self):
print("%s is talki... |
9,085 | 7de06772a1024a81193ac69a1110ad2e8b7f64ac | # Given an integer, convert it to a roman numeral.
# Input is guaranteed to be within the range from 1 to 3999.
class Solution:
# @param {integer} num
# @return {string}
def intToRoman(self, num):
normalDic = {
1000: 'M',
500: 'D',
100: 'C',
50: 'L',... |
9,086 | f78f8f560b7eb70232658be762e2058535a68122 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 11 11:11:32 2017
@author: lindseykitchell
"""
import pandas as pd
import numpy as np
from scipy.stats.stats import pearsonr
import matplotlib.pylab as plt
import glob
import os
pwd = os.getcwd()
df_dict = {}
subj_list = []
for file in glob.glob(pwd + "/*spectrum.json")... |
9,087 | 58bd14d240242ed58dcff35fe91cebeae4899478 | """
time: X * Y
space: worst case X * Y
"""
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
Y = len(grid)
X = len(grid[0])
def dfs(y, x):
if y < 0 or x < 0 or y > Y-1 or x > X-1:
... |
9,088 | de665735f02c7569ab382fdc3e910d5d3ac05bb5 | import enter
import loginout
import roleinfo
import zhanyi
import package
#import matrix |
9,089 | eff8b6a282ac73a116587e7ed04f386927c9f826 | import torch
import torch.nn as nn
class MLPNet(nn.Module):
def __init__(self, num_classes):
super(MLPNet, self).__init__()
self.fc1 = nn.Linear(32 * 32 * 3, 512)
self.fc2 = nn.Linear(512, num_classes)
def forward(self, x):
x = x.view(x.size(0), -1)
x = self.fc1(x)
... |
9,090 | 3c01ca27a5eef877b606b93b04ffe6f73168cd6b | #Embedded file name: c:/depot/games/branches/release/EVE-TRANQUILITY/eve/client/script/paperDoll/SkinRaytracing.py
import trinity
import blue
import telemetry
import ctypes
import math
import time
import geo2
import struct
import itertools
import weakref
import uthread
import paperDoll as PD
import log
import random
my... |
9,091 | dc51ca86a49dbec6f714753782494f21d4b1591d | import numpy as np
import pandas as pd
import logging
import matplotlib.pyplot as plt
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler, RobustScaler
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline, make_pipeline
f... |
9,092 | 8f960ad465d0a7bf48752db35c73169be6da27d8 | from numpy import array, zeros, arange, concatenate, searchsorted, where, unique
from pyNastran.bdf.fieldWriter import print_card_8
from pyNastran.bdf.bdfInterface.assign_type import (integer, integer_or_blank,
double_or_blank, integer_double_or_blank, blank)
class PBAR(object):
type = 'PBAR'
def __init_... |
9,093 | ecbcd023b8fec5763c6ff7f4cd0999426fae4a50 | from Receiver import Receiver
import time
import Image
class Sender:
ACK = []
size = None
windowSize = None
tableOfFrames = []
ChosenSumAlgorithm = None
def __init__(self, receiver):
self.receiver = receiver
pass
def send_frame(self, frame):
self.receiver.receiver_... |
9,094 | 879bb8d67c0e1e8b125ac5994fcb142e3366c9d8 | import logging
import datetime
import numpy as np
def log_players(game_map):
logging.debug("------Players Info------")
for player in game_map.all_players():
logging.debug("-----Player ID: {}-----".format(player.id))
for ship in player.all_ships():
logging.debug("----Ship ID: {}----"... |
9,095 | e748261d1e5fd7921a022afefe5a5bea1fbfc67c | ##Arithmatic Progression
a = int(input ('Enter first number: '))
d = int(input('Enter common difference: '))
n = int(input('Number of term: '))
tn = a
while tn <= a + (n - 1) * d:
print(tn, end=" ")
tn += d
|
9,096 | 874668d5f3ea61b6aabde7b784078b431961a9c9 | #!/usr/bin/python3
"""HAWK GUI interface Selenium test: tests hawk GUI with Selenium using firefox or chrome"""
import argparse, re, hawk_test_driver, hawk_test_ssh, hawk_test_results
### MAIN
# Command line argument parsing
parser = argparse.ArgumentParser(description='HAWK GUI interface Selenium test')
parser.add_... |
9,097 | 65ff3b5137c94890c3293a2ae3f57dee1f60a54c | import cv2
import dlib
import faceBlendCommon as face
from matplotlib import pyplot as plt
from scipy.spatial import distance as dist
import numpy as np
import cmapy
import math
def eye_aspect_ratio(eye):
A = dist.euclidean(eye[1], eye[5])
B = dist.euclidean(eye[2], eye[4])
C = dist.euclidean(eye[0], eye[... |
9,098 | 48a970b35aa7fd677828f5d7bd5f1dcf24511b01 | short_train <- read.csv('short_train.csv', header=TRUE)
#delete unnecessary columns
short_train[1] <- NULL
#remove ngrams containing @user_
regexp <- "@[a-zA-Z0-9_]*"
gsubtry <- gsub(pattern = regexp, replacement = "", x = short_train$Tweet)
#merge gsubtry back into short_train, rename as Tweet
short_train_clean <- ... |
9,099 | b2fecadbd99edb89379f82a935aa1622f043eeac | #!/usr/bin/env python3
print(sum([row[lineNumber * 3 % len(row)] == '#' for lineNumber, row in enumerate(open('input.txt').read().splitlines())])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.