text stringlengths 38 1.54M |
|---|
N, M, d = [int(_) for _ in input().split()]
t = 0
from itertools import product
def calc0(N, M, d):
E = list(range(N))
t = 0
for xs in product(*([E] * M)):
r = sum(abs(xs[i]-xs[i+1]) == d for i in range(M-1))
t += r
return t, N**M, t/N**M
def calc(N, M, d):
if d == 0:
k =... |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
from utils import get_media
from accounting.views import *
urlpatterns = patterns('',
(r'^$', index),
(r'^static/(.+)$', get_media),
(r'^orders... |
from functions import *
from pymsgbox import *
'''
@param1: EmailId of the COURSE
@param2: Password of the COURSE email
@param3: Name of the Course
@param4: CourseID itself
'''
makingOfGroups('groups@nptel.iitm.ac.in', '12345group67890', 'Intro to DB Systems', 'noc20-cs24')
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from scipy.misc import imread
from keras.preprocessing import image
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
... |
import fugashi
# The Tagger object holds state about the dictionary.
tagger = fugashi.Tagger()
file = open("C:/Users/Anna-Maria/Desktop/SENIOR CAPSTONE/Computer Science/model trees/mixed.txt","r", encoding="utf-8")
text = file.readlines() # opening and reading the file with sentences line by line
# this is the lis... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadLayer(nn.Module):
def __init__(self, in_dim, out_dim, num_heads, attn_drop_out, feat_embed_size, layer, merge='cat'):
super(MultiHeadLayer, self).__init__()
self.heads = nn.ModuleList()
for i in range(num_he... |
def genPrimes():
last = 1
primes = []
while True:
last += 1
if not any(last % p == 0 for p in primes):
primes.append(last)
yield last
|
from django.urls import path,include
from .views import get_user_liked_Question_View, get_user_liked_Answer_View, get_user_liked_replies_View, ReportIssueView, getNotification,getProfessionList ,getUsersList,getQuesList
urlpatterns = [
path('liked_Question/', get_user_liked_Question_View.as_view(), name="LikedQu... |
# there must be views
from wsgi_app import App
app = App()
# sample view with routing:
'''
@app.route('/', method=['GET', 'POST'])
def index(headers):
return 'Home page'
'''
|
# example of a bimodal data sample
from matplotlib import pyplot
from numpy.random import normal
from numpy import hstack
# generate a sample
sample1 = normal(loc=20, scale=5, size=300)
sample2 = normal(loc=40, scale=5, size=700)
sample = hstack((sample1, sample2))
# plot the histogram
pyplot.hist(sample, bins=50)
pypl... |
'''
Given an integer array nums and an integer k, return the number of subarrays of nums where the least common multiple of the subarray's elements is k.
A subarray is a contiguous non-empty sequence of elements within an array.
The least common multiple of an array is the smallest positive integer that is divisible ... |
# vim: sw=4:ts=4:et:ai
import itertools
from eulertools import fibonacci
def main():
return sum([i for i in itertools.takewhile(lambda x: x <= 4000000, fibonacci()) if i % 2 == 0])
if __name__ == '__main__':
print("Result: %i" % main())
|
'''
This file will read a log file and produce an CSV file with the data
'''
import csv
import argparse
from decimal import Decimal, getcontext
# Set precission to two digital positions
getcontext().prec = 2
US_LOCATIONS = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA',
'HI', 'ID', 'IL', ... |
# -*- coding:utf-8 -*-
import cv2
import numpy as np
from cal_rect_xy import cal_rect_xy
def Crop_cnt(frame, cnt, color, wh_ratio): # 裁剪轮廓凸包
"""
:param frame:
:param cnt:
:return: CropThing 返回经过 旋转裁剪 后的图片
"""
print(" def Crop_cnt(frame, cnt, color, wh_ratio): >>>")
hull = cv2.convexHull(... |
import gdspy
import numpy as np
from resonator_coaxmon import*
class Coaxmon:
def __init__(self, center, r1, r2, r3, R4, outer_ground, arc):
self.center = center
self.R1 = r1*R4
self.R2 = r2*R4
self.R3 = r3*R4
self.R4 = R4
self.freq = 7e9
self.outer_ground = ... |
# coding: utf-8
# In[29]:
import os
import csv
import numpy as np
import matplotlib.pyplot as plt
# In[30]:
alpha = 0.00
beta = 0.65
scenario='case2'
output_folder = '../output/%s-%.2f-%.2f'%(scenario,alpha,beta)
# In[31]:
n_plans = 16
n_agents = 4000
epos_iterations = 40
# In[32]:
hist = [0]*n_plans
pl... |
import socket
import struct
import sys
import netifaces as ni
def myAddress(interface = 'enp0s3'):#retorna o endereco do script q esta sendo usado
ni.ifaddresses(interface)
ip = ni.ifaddresses(interface)[ni.AF_INET][0]['addr']
return ip
try:
expression = input("Entre com alguma expressao para ser ... |
from django.urls import path
from django.views.generic import TemplateView
from . import views
urlpatterns = [
path('',views.index,name = 'inputIndex'),
path('pdf/',views.html_to_pdf_view,name = 'ipdf'),
path('chart/',views.charts,name = 'charts'),
path('in/',views.datainput,name = 'get_input'),
path('get/',view... |
#
# Copyright (c) 2010-2016, Fabric Software Inc. All rights reserved.
#
ext.add_cpp_quoted_include('CString.hpp')
ext.add_func('CStringParams', 'const char *', ['char const *', 'char const * const &'])\
.add_test("""
report("CxxCStringParams('value', 'constRef') = " + CxxCStringParams('value', Make_CxxCharConstPtr... |
""" projectconfigdialog
ProjectConfigDialog Class - GUI implementation
Elements of this class are referenced in ProjectConfig
"""
from Tkinter import *
from constants import *
import tkMessageBox
import tkFileDialog
import os
import pickle
import shutil
from tkMessageBox import *
from PIL import Image, ImageTk
... |
from typing import Callable
class SegmentTree:
def __init__(self, arr, operator: Callable, ide_ele):
"""
arr: 元の配列
operator: 関数
ide_ele: 単位元
"""
n = len(arr)
num = 1 << (n - 1).bit_length() # n以上の最小の2べき
# bit_lengthの繰り上がりと最小の2べきの更新が1ずれている
se... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 10:13:25 2018
@author: NTPU
"""
form time import sleep
form mcpi.minecraft import Minecraft
thomas = Minecraft.create()
block=[46+,46]
r = choice(block)
myID = thomas.getPlayerEntityId("Thomas0217")
x,y,z=thomas.entity.getTilePos(myID)
thomas.setBlock(x,... |
# Generated by Django 2.2.11 on 2020-03-22 20:02
from django.db import migrations, models
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('contentPages', '0007_delete_resourceitempreview'),
]
operations = [
migrations.AlterField(
model_nam... |
#!/usr/bin/env python3
import serial
import re
import time
if __name__ == '__main__':
light_control_state = 'off'
serial_com = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
serial_com.flush()
while True:
if light_control_state == 'on':
light_control_state = 'off'
if light_... |
from PIL import Image
strip = Image.open("2019-01-19.gif")
strip.load()
strip.show()
width, height = strip.size # Get dimensions
panelW = 360
midX = width/2
cpyRt = 20
left0 = midX - panelW/2 - cpyRt
for i in range(3):
left = left0 + (panelW + cpyRt) * i
top = 0
right = left + panelW + cpyRt
right =... |
# -*- coding: utf-8 -*-
# Control keys
#
# NOTE: these Control key definitions are intended only to provide
# mnemonic names for the ASCII control codes. They cannot be used
# to define menu hotkeys, etc., which require scan codes.
kbCtrlA = 0x0001
kbCtrlB = 0x0002
kbCtrlC = 0x0003
kbCtrlD = 0x0004
kbCtrlE = 0x00... |
#-*- coding:UTF-8 -*-
from unittest import TestCase
import unittest
from selenium import webdriver
from helpers.supportPage import supportPage
from helpers.championsPage import championsPage
class SeleniumTest(TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.supportPage = suppor... |
#!/usr/bin/env python3
import logging
import pika
import json
import os
import couchdb
UPDATED_TWEET_QUEUE = 'updated_tweets'
COUCHDB_TWEET_DATABASE = 'tweets'
logging.basicConfig(level=logging.DEBUG)
def do_consume(ch, method, properties, body):
"""Consume a tweet from RabbitMQ."""
message = json.loads(bo... |
#!/usr/bin/env python3
"""sum_double
Given two int values, return their sum.
Unless the two values are the same, then return double their sum.
sum_double(1, 2) → 3
sum_double(3, 2) → 5
sum_double(2, 2) → 8
source: https://codingbat.com/prob/p141905
"""
def sum_double(a: int, b: int) -> int:
"""Sum Double.
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 06:20:42 2019
@author: berna
"""
#Grafico dell'angolo per la diffusione con 1 riflessione interna
import numpy as np
from matplotlib import pyplot as plt
n=4./3
deg = 180./np.pi
x = np.linspace(0.083, 1.8, 200)
def diffusion(x):
return (4*np.arcsin(n... |
import os
from warnings import warn
from __main__ import ctk
from __main__ import qt
from __main__ import slicer
from __main__ import vtk
from . import __slicer_module__, postgresDatabase
try:
import ConfigParser as cParser
import logging
import logging.handlers
except ImportError:
print "External mo... |
import json
csv_file = open('sample.csv', 'r')
jason_dump = open('json_dump.json', 'w+')
file_data =[]
jason_data = []
for line in csv_file:
line = line.strip('\n')
file_data.append(line.split(','))
for e in file_data[1:]:
payload = {'verificationLevel': int(e[0]), 'userID': int(e[1])}
jason_data.app... |
from django.shortcuts import render
# Create your views here.
from rest_framework import viewsets
from django.core import serializers
from .serializers import UserSerializer, ActivityPeriodSerializer, TimelineSerializer
from .models import User, ActivityPeriod
from django.http import JsonResponse
from django.views.g... |
### Masks out mangrove and planted forest pixels from WHRC biomass 2000 raster so that
### only non-mangrove, non-planted forest pixels are left of the WHRC biomass 2000 raster
import datetime
import rasterio
import os
from shutil import copyfile
import sys
sys.path.append('../')
import constants_and_names as cn
impor... |
n = int(input('Enter the number: '))
fact = 1
for i in range(1,n+1):
fact *= i
print(fact)
#------using recursive function-------
def fact(f,n):
f = f * n
return f
n = int(input('Enter the number: '))
f = 1
for i in range(1,n+1):
f = fact(f,i)
print(f) |
#!/bin/python
t = int(raw_input().strip())
for _ in range(t):
delete = 0
s = list(raw_input().strip())
for i in range(0, len(s)- 1):
if s[i] == s[i+1]:
delete += 1
print delete
|
# -*- coding: utf-8 -*-
"""
main_window.py -- GUI main window.
"""
# This software is distributed under the FreeBSD License.
# See the accompanying file LICENSE for details.
#
# Copyright 2011 Benjamin Hepp
import sys, os, random
import numpy
import logging
from PyQt4.QtCore import *
from PyQt4.QtGui import *
logg... |
import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#Enter your credentials
your_email = 'enter_your_email_here@gmail.com'
your_password = 'enter_your_password_here'
smtp_protocol = 'smtp.gmail.com' # This is unique as per email service of your... |
import datetime
import os
import shutil
import numpy as np
def makedir(dirname):
"""Safely creates a new directory.
"""
if not os.path.exists(dirname):
os.makedirs(dirname)
def rmdir(dirname):
"""Deletes a non-empty directory.
"""
answer = ""
while answer not in ["y", "n"]:
... |
from .HALResponse import HALResponse
from .MomentResponse import MomentResponse
from .ApiIndexResponse import ApiIndexResponse |
import threading
from subprocess import Popen, PIPE
import time
def popenAndCall(onExit, *popenArgs, **popenKWArgs):
"""
Runs a subprocess.Popen, and then calls the function onExit when the
subprocess completes.
Use it exactly the way you'd normally use subprocess.Popen, except include a
callable... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 1 14:32:38 2020
@author: Ashima
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the superReducedString function below.
def superReducedString(string):
string_list = list(string)
flag = True
while len(string_list) > ... |
import time
import matplotlib
import pandas as pd
matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
from sklearn import manifold
from sklearn.decomposition import PCA
SNP_Raw = np.load('SNP_Raw.npy').transpose()
Nation_Raw = np.load('Nation_Raw.npy', allow_pickle=True)
starttime =... |
#
# @lc app=leetcode id=877 lang=python3
#
# [877] Stone Game
#
# It is the same as 486.
# @lc code=start
class Solution:
def stoneGame(self, piles: List[int]) -> bool:
return self.helper(0, len(piles) - 1, piles, {})
def helper(self, left, right, piles, cache):
if left == right:
... |
import argparse
from flask import Flask, request, jsonify
from speech_engine import YandexSpeechEngine, GoogleSpeechEngine
parser = argparse.ArgumentParser(description='Speaker')
parser.add_argument('-p', '--port', type=int, default=8080,
help='port to use')
app = Flask(__name__)
gse = GoogleS... |
import os
from flask_platform import app
def main():
app.run(host='0.0.0.0',port=5000)
return
if __name__=="__main__":
main()
|
#!/usr/bin/env python
import yaml
import multiprocessing
import twitterneo4j.variables as variables
def configure(config_yaml_file):
#
# Read the config
#
config_yaml = open(config_yaml_file, "r")
config = yaml.load(config_yaml)
config_yaml.close()
# Required Configuration
variables... |
#Student Name:Wentao Wu; Student ID#:112524704
class Node:
def __init__(self):
print("init node")
def evaluate(self):
return 0
def execute(self):
return 0
class BlockNode(Node):
def __init__(self,sl):
self.statementList = sl
def evaluate(self):
for state... |
from .base import SimpleService
class GlusterdService(SimpleService):
name = 'glusterd'
systemd_unit = 'glusterd'
restartable = True
async def after_start(self):
# the glustereventsd daemon is started via the
# ctdb.shared.volume.mount method. See comment there
# to know why... |
"""API Views"""
from rest_framework import generics
from orders.api.serializers import OrderSerializer
class OrderCreateAPIView(generics.CreateAPIView):
"""As documentation explains"""
serializer_class = OrderSerializer
|
from django.test import TestCase
import datetime
from django.utils import timezone
from tplatform.models import Article, Author, Tag, Type
from django.core.urlresolvers import reverse
class DataSetUp(TestCase):
@classmethod
def setUpTestData(cls):
# Tags and Types
Tag.objects.create(name = 'someTag')
Tag.obje... |
'''
Created on 29 mai 2016
@author: PASTOR Robert
Manage the display mode, either weekly or monthly
'''
class DisplayMode(object):
monthlyMode = "monthly"
weeklyMode = "weekly"
defaultMode = weeklyMode
displayMode = defaultMode
week_number = 0
month_number = 0
year = 0
... |
# Title: Mathematical Algorithms Basics in Python
# Date: Oct/06/2015, Tuesday - Current
# Author: Minwoo Bae (minubae.nyc@gmail.com)
# Reference: http://wphooper.com/teaching/2015-fall-308/python/Numbers.html
import math
# 01) Find Divisors of a Natural Number P
# Write a Python function print_divisor(p) which take... |
import sys
from os.path import dirname,abspath
project_path =dirname(dirname(abspath(__file__)))
sys.path.append(project_path+"\\project1")
from calculator import add
print(add(4,5)) |
import logging
import fmcapi
import time
def test__phys_interfaces(fmc):
logging.info(
"Test PhysicalInterface. get, put PhysicalInterface Objects. Requires registered device"
)
sz1 = fmcapi.SecurityZones(fmc=fmc)
sz1.name = "SZ-OUTSIDE1"
sz1.post()
time.sleep(1)
sz2 = fmcapi.Sec... |
#%%
from typing import List, Tuple, Dict, Union
import pandas as pd
df = pd.read_csv('../../data/processed.csv.gz', index_col="Id")
pd.set_option('display.max_colwidth', 999)
# %% ************ getting ners
import spacy
#%%
import pickle
spacy.prefer_gpu()
nlp = spacy.load("en_core_web_lg")
banned_ner = {('FAC', 'FAH... |
"""ModelAdmin for MailingList"""
from datetime import datetime
from django.contrib import admin
from django.urls import path
from django.utils.encoding import smart_str
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext_lazy as _
from django.http... |
from django.shortcuts import render_to_response
from django.template import RequestContext
def _printError(request, errormsg):
context = {'errormsg' : errormsg}
return render_to_response('errormsg.html', context, context_instance = RequestContext(request))
def _printMessage(request, message):
context = {'... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.utils.timezone
import modelcluster.fields
import wagtail.core.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0005_make_filter_spec_unique'),
(... |
# coding: utf-8
#
# Copyright 2014 The Oppia Authors. 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 requi... |
# Generated by Django 2.0.6 on 2020-09-11 09:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='TAddress',
... |
word = input("que dice el don: ")
print("\n"*69)
letters = list(word)
guess_arr = []
wrong_counter = 1
side = 0
import sys
from random import randint
#array for hangman
brojon = [" ---|\n",
" o\n",
" |\n",
" /","|","\\","\n",
" |\n",
" /"," ","\\","\n"... |
class Kobe:
def __init__(self, text, value, row_b, row_e, col_b, col_e, trans, write=None, variable=None):
self.text = text
self.value = value
self.row_b = row_b
self.row_e = row_e
self.col_b = col_b
self.col_e = col_e
self.trans = trans
self.write = write
self.variable = variable
... |
import numpy as np
import streamlit as st
import math
import csv
from PIL import Image
import pandas as pd
def app():
options = ["Sin", "Cos", "Tan"]
choice = st.radio("Choose the Operation", options)
if choice == "Sin":
multi_sin = ["simple Sin" , "arc Sin" , "hyperbolic Sin"]
... |
config = {
"zone_dir": "../../private-circles/zonefiles",
"intermediate_dir": "snakemake-output",
"build_dir": "../../publishable-circles",
"input_dir": "../../private-circles"
} # find snakemake-output/ -type f | grep .err | sed 's/^.\{17\}//' | xargs -n 1 sh -c 'cp snakemake-output/$1 ../../publishabl... |
#!/usr/bin/python3
import fileinput
f=fileinput.input()
T=int(f.readline())
for case in range(T):
N=int(f.readline())
if N==0:
print("Case #"+str(case+1)+":","INSOMNIA")
continue
curr=N
mset=set(str(N))
while len(mset)<10:
curr+=N
mset.update(str(curr))
print("Case #"+str... |
import os
config_file = "%s%s.leaprc" % (os.environ['HOME'], os.sep)
config_directory = "%s%s.leap" % (os.environ['HOME'], os.sep)
|
#!/usr/bin/env python3
import argparse
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
from pkcs1_breaker import *
_TESTKEY = b"""\
-----BEGIN PRIVATE KEY-----
MIIB5gIBADANBgkqhkiG... |
# -*- coding: utf-8 -*-
BOT_NAME = 'getStockList'
SPIDER_MODULES = ['getStockList.spiders']
NEWSPIDER_MODULE = 'getStockList.spiders'
ITEM_PIPELINES = {'getStockList.pipelines.MongoDBPipeline': 1000, }
DOWNLOADER_MIDDLEWARES = {
'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware' : None,
'ge... |
# Write a Python code that takes the degree as input from the user and convert it into radian
# importing math
import math
print("Convert the degree to radian")
# initializing value
degree = int(input("Enter the degree : "))
radian = degree*(math.pi/180)
print(radian)
|
import sys
import os
import csv
import subprocess
import jsonschema
import json
from datetime import time, datetime, timedelta
import itertools
from itertools import cycle
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as md
import matplotlib as mpl
from matplotlib.pyplot import cm
import nu... |
from utility import dataset_function as reader
import pandas as pd
import numpy as np
from sklearn.base import TransformerMixin
from sacred import Experiment
def fill_categorical_features(data):
for column in data.columns:
nunique_value = data[column].nunique()
if nunique_value < 10:
d... |
import openpyxl # 酱酱的注释,看仔细喽,这是一个函数库openpyxl ,用pip install安装
import re
def Exceldivide(file_dir):
wb = openpyxl.load_workbook(file_dir) # 打开原有的excel表
sheet = wb.get_sheet_by_name('Sheet1')
tuple(sheet['A1':'C3'])
wb.create_sheet('Sheet2') # 新建一个表
sheet2 = wb.get_sheet_by_name('Sheet2')
tup... |
class HashTable():
def __init__(self, capacity):
self._capacity = capacity
self._data = [None for i in range(capacity)]
def hash(self, str_val):
val = 0
for i in range(len(str_val)):
val += (i+1) * ord(str_val[i])
return val % self._capacity
def insert(s... |
# Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
# The solution set must not contain duplicate subsets. Return the solution in any order.
# Example 1:
# Input: nums = [1,2,2]
# Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
# Example 2:
# Input: nums = [0]
# Outp... |
# -*- coding: utf-8 -*-
import xlrd
from django.conf import settings
from budgetelem.models import Document
import sys
import unicodedata
sys.setrecursionlimit(200)
class ExcelParser(object):
def read_excel(self, excel_name):
if excel_name.unit == '1':
unit_koef = 1
elif excel_nam... |
# Can be used to flatten nested lists of any depth.
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
|
import json
import os
import getpass
from cryptography.fernet import Fernet
from common import *
def check_config(config_path=os.path.join(BASE_DIR, "config.json")):
if os.path.exists(config_path):
logger.debug("Config file exists")
else:
logger.info("A config does not exist, please make one")... |
# s=int(input()) #s=7
# print(s+2) #s+2=9
# print(s%2) #s%2=1 -- остаток
# print(s+2-(s%2)) #s+2-1
s = int(input())
print(s + 2 - (s % 2))
|
from bs4 import BeautifulSoup
html = """
<html><body>
<ul>
<li><a href="http://www.naver.com">naver</a></li>
<li><a href="http://www.daum.net">daum</a></li>
<li><a href="http://www.daum.com">daum</a></li>
<li><a href="http://www.goolgle.com">google</a></li>
<li><a href="http... |
#!/Users/bernardo.branco/Documents/Personal/Projects/sidewake/venv/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
#!/usr/bin/python
import os
import json
import base64
import io
import re
import uuid
import time
import shutil
import argparse
import shelve
import sys
import glob
import subprocess
import socket
from pyDes import *
cur_dir = os.path.dirname(os.path.realpath(__file__))
package_type = None
if os.path.exists('/etc... |
import re
import unittest
class Solver(object):
def __init__(self, ):
pass
def solve(self, inputs):
pass
TEST_DATA='''
/*0*/ test("d3d4e3e4d9h7h9j3j4j7j9,f4f6g4g5g6h5h6", "5,3")
/*1*/ test("a1,s19", "0,0")
/*2*/ test("a1a2b1b2,r18r19s18s19", "1,1")
/*3*/ test("b1d1b2d2e2f2b5d5e5f5b6d6,b3d3b... |
def multtable(start, stop, number):
"""
Print multiplication table for <number>
from <start> to including <stop>
"""
for i in range(start, stop+1):
print(f"{i} x {number} = {i*number}")
def powertable(power, stop):
"""
Prints the powers of i from 1 to
including <stop> using <po... |
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as signal
import statistics
import math
import plot
def densitygraph(star_file,window,save_file):
star_table=np.loadtxt(star_file, delimiter=' ')
starTranspose=star_table.transpose()
newStar=np.append(starTranspose,[np.zeros(len(star_table))], ... |
from pylab import *
import sys
import pymc
from pymc import Metropolis
import cosmolopy
from McMc import mcmc
from astropy.io import fits
from McMc import cosmo_utils
import scipy
import pickle
#### run in a shell
#xterm -e python ~/Python/Boss/McMc/mcmc_launcher.py olambdacdm LyaDR11_HPlanck1s_obh2Planck1s &
#xterm ... |
import os
import sys
script_dir = os.path.dirname(os.path.realpath(__file__))
results_dir = script_dir + "/results"
results_files = os.listdir(results_dir)
if len(results_files) <= 1: # There may be 1 file which is just a .gitkeep file
print('Found no test results in the results folder ' + results_dir + ' ... cou... |
# Generated by Django 2.0 on 2018-01-09 23:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('progress', '0003_auto_20180108_2046'),
]
operations = [
migrations.AlterField(
model_name='trainday',
name='mood',
... |
#!/usr/bin/env python
# filterdaemon.py
# This background process creates indexes files for threads and filters.
#
import sys
import os
import pyinotify
import threading
import datetime
import time
import email.parser
import threads
import headers
import users
from cabinet import DatetimeCabinet
import maildir
# Th... |
import time
from termenu.app import AppMenu
def leave():
print("Leave...")
AppMenu.quit()
def go():
def back():
print("Going back.")
AppMenu.back()
def there():
ret = AppMenu.show("Where's there?",
"Spain France Albania".split() + [("Quit", AppMenu.quit)],
... |
from django.db import models
class Address(models.Model):
id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
street_address = models.CharField(db_column='Street_Address', max_length=300) # Field name made lowercase.
upazilla_city_corporation = models.CharField(db_col... |
# /models.py
from django.db import models
from level0.contacts.models import Entity, Person
class Job(models.Model):
"""
A job experience to be listed on the resume
"""
company =
title = models.CharField(max_length=250)
start_date =
end_date =
city =
state =
d... |
#!/usr/bin/env python
# ref: https://gist.github.com/gregorynicholas/3152237
'''
Module that runs pylint on all python scripts found in a directory tree.
'''
import os
import sys
def check(module):
'''
apply pylint to the file specified if it is a *.py file
'''
if module[-3:] == ".py":
print(... |
print("-----------------currency-----------------")
import random
MAX_INCREASE = 0.1 # 10%
MAX_DECREASE = 0.05 # 5%
MIN_PRICE = 0.01
MAX_PRICE = 1000.0
INITIAL_PRICE = 10.0
count=0
price = INITIAL_PRICE
print("starting price ${:,.2f}".format(price))
while price >= MIN_PRICE and price <= MAX_PRICE:
priceChange = 0... |
import re
from container import Row
class FormatSpecifierCannotProcessError(Exception):
pass
class FormatSpecifierFactory():
_fox_sports_regex = re.compile("(\d+)\.\s(.+)\s\((\w+)\s-\s(\w+)\).+(\d+)")
def __init__(self):
pass
def get_format_specifier(self, fs):
"""
Gets a ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program is dis... |
from setuptools import setup, Extension
import os
exec(open('openctm/version.py').read())
long_description = ''
if os.path.exists('README.md'):
with open('README.md', 'r') as f:
long_description = f.read()
setup(
name='python-openctm',
version=__version__,
description='Python Interface for th... |
import tensorflow as tf
from tensorflow.python.framework import ops
from .backprojecting_op import backproject_grad
'''
@tf.RegisterShape("Backproject")
def _backproject_shape(op):
"""Shape function for the Backproject op.
"""
dims_data = op.inputs[0].get_shape().as_list()
batch_size = dims_data[0]
channels ... |
import pandas as pd
import numpy as np
import os
import datetime
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='arguments')
parser.add_argument('data_folder', type=str, help='folder to save data')
parser.add_argument('ticker_name', type=str, default='BTC-USD'... |
# rraman and 3d dimenssion - plus
#! /usr/bin/env python
import numpy as np
import pylab
from scipy.optimize import leastsq
def lorentzian(x,p):
numerator = (p[0]**2 )
denominator = ( x - (p[1]) )**2 + p[0]**2
y = p[2]*(numerator/denominator)
return y
def gaussian(x,p):
c = p[0] / 2 / np.sqrt(2*... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.