text stringlengths 8 6.05M |
|---|
import sys
sys.path.append("..")
import datetime
import os
from os.path import join
import torch.utils.data as data
import argparse
import torch
from data import CelebA
from helpers import Progressbar
from on_manifold.model import Classifier
import torch.optim as optim
import torch.nn.functional as F
def parse(args=N... |
# Generated by Django 2.1.3 on 2018-12-02 15:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photos', '0006_auto_20181127_0838'),
]
operations = [
migrations.AlterField(
model_name='photo',
name='license',
... |
#Receba um número N. Calcule e mostre a série 1 + 1/1! + 1/2! + ... + 1/N!
n=int(input('digite um valor: '))
s=int(1)
c=int(1)
print(f'{s}+')
while c<=n:
f=c
cf=1
while cf<c:
f*=cf
cf+=1
print(f'1/{f} = {1/f} +')
s+=1/f
c+=1
print(f'a serie é {s}') |
#Caleb Lewandowski
#February 1, 2021
#Module 5.3 Assignment
#Set up connection.
from pymongo import MongoClient
url="mongodb+srv://admin:admin@cluster0.lwbyv.mongodb.net/pytech"
client = MongoClient(url)
db = client.pytech
students = db.students
#Display all student data.
print("-- DISPLAYING STUDENTS DOCUMENTS FROM ... |
# Generated by Django 2.0.4 on 2018-04-15 15:07
import django.contrib.auth.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20180415_1326'),
]
operations = [
migrations.AlterModelManagers(
name='cust... |
import os
import logging
from flask import Flask, flash, request, jsonify
from werkzeug.utils import secure_filename
from service.formula_detection import detect_formula
from service.face_detection import detect_faces
UPLOAD_FOLDER = "/tmp/pepper_uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
ALLOWED_EXTENSIONS ... |
'''
The following file contains the code for Moore majority voting algorithm.
It returns the majority element in an array(i.e element occuring more than n/2 times in the array). It is
also capable of returning the frequency of the majority element.
Incase of no such element, it returns -1
'''
class BoyerMooreMajorit... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# stock_simu.py
'''
refer:
https://stackoverflow.com/questions/34952669/how-to-get-python-compound-interest-calculator-to-give-the-correct-answer
'''
import numpy as np
def calculater_bymyself ():
#==== need to input to your environment
#print ('original = 10.0\nr... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def addOneRow(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type d: int
:rtype:... |
'''
This script will be used to generate the response of a boom crane on an
oscillating floating body in an ocean described by the Pierson-Moskowitz
spectrum
TODO: Fix the Non-'pure_sine' heave response for the Floating body module
'''
from timeit import default_timer as timer
import sys
sys.path.append('/Users/Danie... |
import json
from unittest.mock import Mock, patch
import pytest
from googleapiclient.errors import HttpError
from sso.samlidp.models import SamlApplication
from sso.samlidp.management.commands.sync_with_google import Command, http_retry
from sso.tests.factories.user import AccessProfileFactory, UserFactory
def bui... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import run, CalledProcessError, TimeoutExpired
import os
import sys
import json
from json.decoder import JSONDecodeError
"""
PENSER À SYNCHRONISER CES CONSTANTES AVEC SETUP.SH
"""
# Clé SSH de Gitly
SSH_KEY = "./gitly_ssh.key"
# Dossier pour conserver le... |
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from rest_framework.authtoken import views
admin.autodiscover()
#from books import views
urlpatterns = patterns('books.views',
#url(r'^$', 'ui_in... |
import random
def solution(board, nums):
for i in range(len(board)):
for j in range(len(board)):
for k in range(len(nums)):
if(board[i][j] == nums[k]):
board[i][j] = "a"
bingo = 0
cross_cnt1 = 0
cross_cnt2 = 0
for i in range(len(board)):
... |
from McM_suffix_tree_build import built_tree
from tandem_repeat_finder import find_tandem_repeats
from util import analyse
from matplotlib import pyplot as plt
import random
def test_tamdem_repeats_complexity():
_map = ['a', 'g', 't', 'c']
def args_generator(n):
_str = ''.join([_map[random... |
# Generated by Django 2.2.4 on 2019-11-27 06:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('QualiaII', '0008_tblapc_ventas'),
]
operations = [
migrations.CreateModel(
name='tblBalances',
fields=[
... |
# class UserTest(SeleniumTest):
#
# def test_user_creation(self):
# # the user start to open the home page and click on the signup button
#
# # a form appears with all necessary information (dynamic)
#
# # he fill up all the information:
# # - email
# # - password
#
# ... |
# import credentials
from random import randint
import time
import numpy as np
# import tflearn
# import tensorflow as tf
import random
import array
import json
responses = ["Hello", "Moshi Moshi", "Ohayouuuuuuuuuuuuu"]
# rand = randint(0,2)
# USER
good_responses = ["good", "all right"]
how_old_responses = ["how old ... |
from mininet.topo import Topo
class LoopTopo(Topo):
def __init__(self):
Topo.__init__(self)
s1=self.addSwitch("s1")
s2=self.addSwitch("s2")
s3=self.addSwitch("s3")
h1=self.addHost("h1")
h2=self.addHost("h2")
h3=self.addHost("h3")
self.addLink(s1,h1)... |
import torch
from torch import nn
from collections.abc import Iterable
from pixelflow.distributions import Distribution
from pixelflow.transforms import Transform
class InverseFlow(Distribution):
"""
Base class for InverseFlow.
Inverse flows use the forward transforms to transform noise to samples.
Th... |
import imp
import logging
import os
import subprocess
import sys
import traceback
import yaml
import aj
from aj.api import *
from aj.util import *
@public
class PluginProvider(object):
"""
A base class for plugin locator
"""
def provide(self):
"""
Should return a list of found plugin... |
#! /usr/bin/env python
import math
from atsim.potentials import EAMPotential, Potential
from atsim.potentials.eam_tabulation import TABEAM_EAMTabulation
def makeFunc(a, b, r_e, c):
# Creates functions of the form used for density function.
# Functional form also forms components of pair potential.
def f... |
#returns the help text for available bot commands
import commands.advancedhelp as ah
#from discordclient import client
import discord
ABILITY_COMMAND = '!ability'
def getResponseMessage(msg, client):
#first check if the user wants advanced help, if not return other message
helpMessage = None
msg = msg.content
... |
"""
作者 xupeng
邮箱 874582705@qq.com / 15601598009@163.com
github主页 https://github.com/xupeng1206
"""
from flask import Flask, request
from .restful.processors import BaseRequestProcessor, BaseResponseProcessor, FlangerStaticProcessor, \
FlangerSwaggerProcessor
from .restful.utils import extract_cl... |
/Users/rasmuslevinsson/anaconda3/lib/python3.6/_dummy_thread.py |
# -*- coding: utf-8 -*-
import scrapy
class WikipediaSpiderSpider(scrapy.Spider):
name = 'wikipedia_spider'
allowed_domains = ['ja.wikipedia.org']
start_urls = ['https://ja.wikipedia.org/wiki/Wikipedia:ウィキポータル']
def parse(self, response):
pass
#for post in response.css('#mw-content-text'):
... |
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
# our index route will handle rendering our form
@app.route('/')
def index():
return render_template("index.html")
# this route will handle our form submission
# notice how we defined which HTTP methods are allowed by this route
@app.... |
"""SlurmSpawner implementation"""
import signal
import errno
import pwd
import os
import getpass
import time
import pipes
from subprocess import Popen, call
import subprocess
from string import Template
from tornado import gen
from jupyterhub.spawner import Spawner
from traitlets import (
Instance, Integer, Unico... |
from sklearn.linear_model import LogisticRegression
import pandas as pd
import numpy as np
from sklearn.utils import shuffle
def cv_error(estimator, dataset, datalabel, cv=1):
dataset = pd.DataFrame(dataset)
datalabel = pd.DataFrame(datalabel)
length = len(datalabel) / cv
left = 0
r... |
# -*- coding: utf8 -*-
import os
import sys
import third.file_util as file_util
import third.str_util as str_util
def do_publish_ci():
print "do_publish_ci() ..."
if len(sys.argv) != 12:
print "arguments error."
return False
try:
ident = sys.... |
# -*- coding: utf-8 -*-
# Renyi Hou. 23/6/2017
题目:
Given an integer array with even length, where different numbers in this array represent different kinds of candies.
Each number means one candy of the corresponding kind.
You need to distribute these candies equally in number to brother and sister.
Return the maxi... |
"""The application's model objects"""
import os.path
from pkg_resources import resource_listdir, resource_stream
import mongo
from mongo import Base
from dimension import Dimension
from dataset import Dataset
from classifier import Classifier
from entry import Entry
from entity import Entity
from account import Accou... |
#温度转换
TempStr = input("请输入摄氏度或者华氏度:")
if TempStr[-1] in ["F","f"]:
C = (eval(TempStr[0:-1])-32)/1.8
print("转换后的摄氏度为{;.2f}C".format(C))
if TempStr[-1] in ["C","c"]:
F = eval(TempStr[0:-1])*1.8 + 32
print("转换后的华氏度为{:.2f}F".format(F))
else:
print("请检查输入的温度格式")
|
from keras import Model, optimizers, initializers
from keras.layers import Input, Dense, Activation
from keras.layers.normalization import BatchNormalization
from keras.utils import to_categorical
from keras.datasets import fashion_mnist
import matplotlib.pyplot as plt
# パラメータ + ハイパーパラメータ
img_shape = (28 * 28, )
hidde... |
# Generated by Django 2.1.8 on 2019-05-22 06:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bbs', '0002_question_question_desc'),
]
operations = [
migrations.AlterField(
model_name='choice',
name='choice_text... |
import random
class Number_Guessing_Game(object):
def __init__(self):
self.minimum_number = 0
self.maximum_number = 100
self.guesses = 0
self.maximum_guesses = 10
self.game()
def game(self):
correct_number = random.randint(self.minimum_number, self.maximum_numb... |
from django.contrib import admin
from .models import Project, ProjectUser
class ProjectAdmin(admin.ModelAdmin):
search_fields = ['title', 'organisation']
list_display = ('title', 'description', 'state', 'is_government', 'created_at', 'updated_at', 'organisation')
fields = ('title', 'description', 'state'... |
# -*- coding: utf-8 -*-
from zope.component import getMultiAdapter
from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
from zope.interface import implementer
from zope.i18n import translate
from plone.app.layout.navigation.interfaces import INavtreeStrategy
from plone.app.layout.navigation.nav... |
print('WE, THE PEOPLE OF INDIA,\r')
print("\thaving solemnly resolved to constitute India into a SOVEREIGN,\r")
print("\t\tSOCIALIST, SECULAR, DEMOCRATIC REPUBLIC\r")
print("\t\tand to secure to all its citizens\r")
|
import os
import sys
import logging
import time
import datetime
import re
import click
from collections import Counter
from csv import DictReader as CSV_DictReader
from openpyxl import Workbook
from echoclean.xlsx_dictreader import DictReader as XLSX_DictReader
from echoclean.ruleset import Ruleset
logger = logging.... |
import yara
def yaraScan(email):
matches = []
rules = yara.compile(filepaths={ #compilar un conjunto de reglas
'namespace1':'rules/testRule1.ya',
'namespace2':'rules/testRule2.ya'
})
reglas = rules.match(data = email) #datos a analizar
for match in reglas: #las reglas que se c... |
# @Title: 二叉树的层次遍历 II (Binary Tree Level Order Traversal II)
# @Author: 2464512446@qq.com
# @Date: 2019-06-26 10:42:41
# @Runtime: 56 ms
# @Memory: 13.4 MB
#
# @lc app=leetcode.cn id=107 lang=python3
#
# [107] 二叉树的层次遍历 II
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__... |
# Generated by Django 3.1 on 2021-02-02 19:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0017_usernames'),
]
operations = [
migrations.AddField(
model_name='profile',
name='watched_tags',
... |
# -*- coding: utf-8 -*-
import time
from datetime import datetime
def strtime_to_datetime(timestr):
"""
:param timestr: {str}'2016-02-25 20:21:04.242'
:return: {datetime}2016-02-25 20:21:04.242000
"""
local_datetime = datetime.strptime(timestr, "%Y-%m-%d %H:%M:%S")
return local_datetime
def ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from z3 import *
solver = Solver()
s = [BitVec('v%02d' % i, 8) for i in range(20)]
LOBYTE_off_606018_0 = 0
LOBYTE_off_606020_0 = 0
BYTE2_off_606020_0 = 0
BYTE1_off_606028_0 = 0x60
off_606038 = 0x90
BYTE1_off_606038 = 0x60
BYTE2_off_606038 = 0x60
BYTE3_off_606038 = 0x90
... |
import pyautogui as pag
import time
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
print(filename)
timeDelay = int(input("If you want a delay, enter the number of seconds for the delay : ").split()[0])
if timeDelay < 1:
timeDelay = 1
time.s... |
click("1372231007417.png")
sleep(2)
type("http://www.google.com" + Key.ENTER)
sleep(2)
region = find("1372241137761.png");
region.highlight();
wait(3);
new_region = Region(region.x, region.y, region.w + 300, region.h);
new_region.highlight();
wait(3);
logo = new_region.find("1372240980244.png")
click(logo) |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import logout as logout_user
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
#from .form import *
#from .models import Far... |
#!/usr/bin/env python
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--noMultiThreading", dest="noMultiThreading", default = False, action="store_true", help="noMultiThreading?")
parser.add_option("--selectWeight", dest="selectWeight", default=None, ... |
# tests all wallet operations with single node
import _lib
import _transfers
import _wallet
import _blocks
import re
import time
import random
import blocksbasic
import startnode
import transactions
datadir = ""
def allowgrouprun():
return False
def aftertest(testfilter):
global datadir
if datadir ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('reimbursements', '0006_reimbursement_trip_time'),
]
operations = [
migrations.AddField(
model_name='reimbursemen... |
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr)//2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = 0
j = 0
k = 0
while i < len(left_half) and j < len(right_half):
if left_half[i] <... |
"""
This is a utility file to retrieve image features from a pre-trained
Inception V3 Convolutional Neural Network and store them in pickle files.
The process takes around 1 hour to run on a normal desktop.
"""
import cv2
import glob
import pickle
from keras.layers import Input
from keras.models import Model
from k... |
# @Title: 字符的最短距离 (Shortest Distance to a Character)
# @Author: 2464512446@qq.com
# @Date: 2019-10-22 14:50:56
# @Runtime: 32 ms
# @Memory: 11.4 MB
class Solution(object):
"""
本质是以字符C为原点,计算每个字符离字符C有多远。左右各计算一次,取最小值
"""
def shortestToChar(self, S, C):
prev = float('-inf') # 负无穷
ans = []... |
from skimage.draw import circle # Для рисования окружностей
def draw_circle(arr, x, y, r, color = [255, 0, 0]):
try:
rr, cc = circle(y, x, r)
arr[rr, cc] = color
except:
print("Wrong circle!")
|
#!/usr/bin/env python3
# coding: utf-8
# In[269]:
from task import Task
# In[270]:
tasks = {}
# ## 0. Squared simple
#
# Write a function that computes the square value of all integers of a matrix.
#
# `square_matrix_simple(matrix=[])`
#
# * matrix is a 2 dimensional array
# * Returns a new matrix:
# * Same si... |
import math
import os
import random
import re
import sys
def appendAndDelete(s, t, k):
if len(s) + len(t) < k:
return "Yes"
n = len(s) if len(t) > len(s) else len(t)
for x in range(n):
if s[x] == t[x]:
continue
else:
break
moves = len(s) + len(t) - (2 * ... |
#Function to calculate number of 1's in binary representation of a number
def count_ones(n):
count=0 #Initializing count to store number of 1's
while(n>0): #Iterating till the number is greater than 0 (has atleast one '1' in its representation)
count=count + (n & 1) #'AND' t... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 00:15:43 2020
@author: asuri
"""
import numpy as np
import modern_robotics as mr
def GetTrajectoryForZeroJointTorqueAndFtip(time_in_secs, thetalist0, dthetalist0, g, Mlist, Glist, Slist, dt, intRes):
time_steps = int(time_in_secs/dt)
#Zero torque ... |
# By starting at the top of the triangle below and moving to adjacent numbers on the row below,
# the maximum total from top to bottom is 23.
# 3
# 7 4
# 2 4 6
# 8 5 9 3
# That is, 3 + 7 + 4 + 9 = 23.
# Find the maximum total from top to bottom of the triangle below:
# 75
# 95 64
#... |
#!/usr/bin/env python
import time
import Matrix.GPIO as GPIO
def main():
try:
led = 7
GPIO.setmode(GPIO.BOARD)
GPIO.setup(led, GPIO.OUT)
print "Light on"
GPIO.output(led, GPIO.HIGH)
time.sleep(1)
print "Light off"
GPIO.output(led, GPIO.LOW)
excep... |
from ED6ScenarioHelper import *
def main():
# 格兰赛尔
CreateScenaFile(
FileName = 'T4155 ._SN',
MapName = 'Grancel',
Location = 'T4155.x',
MapIndex = 1,
MapDefaultBGM = "ed60084",
Flags = 0,
... |
__author__ = 'ishant'
from django import forms
class ToolForm(forms.Form):
name = forms.FileField()
class FileForm(forms.Form):
file = forms.FileField()
class IntForm(forms.Form):
int_field = forms.IntegerField()
class FloatForm(forms.Form):
float_field = forms.FloatField()
class StringForm(forms.... |
from .bed_management_views import *
from .cultural_operations_views import *
from .authentication_views import *
from .alerts_views import *
from .vegetables_views import *
from .garden_management_views import *
from .vegetables_views import *
from .export_data_views import *
from .history_views import *
from .garden_s... |
import os
import transaction
from onegov.core.utils import Bunch
from onegov.org import OrgApp
from tests.shared import Client
def test_allowed_application_id(org_app):
# little bobby tables!
assert not org_app.is_allowed_application_id(
"Robert'); DROP TABLE Students; --"
)
assert not org_ap... |
import scipy.stats as stats
from csv import DictReader
# Reads from a csv file in the format value,frequency
# A confidence interval for the variance and std. deviation are found
# The data must be normally distributed because S^2(n-1)/var^2 ~ chi2 with n-1 d.f. iff the data is normal
def read_data(filename="data.csv... |
# Generated by Django 2.1.5 on 2019-02-08 01:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shelf', '0004_remove_book_authors'),
('library', '0001_initial'),
]
operations = [
migrations.Remov... |
from m5 import fatal
import m5.objects
from textwrap import TextWrapper
#add options for number of ROB entries, IQ entries, and number of physical
#floating point registers
def addHW3Opts(parser):
parser.add_option('--nr_entries', type="int", default=192)
parser.add_option('--ni_entries', type="int", default=64)
pa... |
from flask import request
from flask_restful import Resource
from http import HTTPStatus
from schemas.reservation import ReservationSchema_A, ReservationSchema_B, ReservationSchema_C, ReservationSchema_D
from models.reservation import Reservation_A, Reservation_B, Reservation_C, Reservation_D
from flask_jwt_extended im... |
# Generated by Django 3.0.1 on 2020-01-11 04:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('library_app', '0004_auto_20200111_0235'),
]
operations = [
migrations.RemoveField(
model_name='album',
name='public',
... |
from pymongo import MongoClient
from pymongo.errors import DuplicateKeyError
from mastodon import Mastodon
import requests
import config
class NekoArchiver:
def __init__(self):
self.__con = MongoClient()
self.__db = self.__con[config.DATABASE_NAME]
self.toots = self.__db[config.TOOTS_COLLE... |
"""Sorting components: peak waveform features."""
import numpy as np
from spikeinterface.core.job_tools import fix_job_kwargs
from spikeinterface.core import get_channel_distances
from spikeinterface.sortingcomponents.peak_localization import LocalizeCenterOfMass, LocalizeMonopolarTriangulation
from spikeinterface.sor... |
import bisect
# Complete the triplets function below.
def triplets(a, b, c):
a_sorted = sorted(set(a))
b_set = set(b)
c_sorted = sorted(set(c))
num_triplets = 0
for value in b_set:
index_lower = bisect.bisect_right(a_sorted, value)
index_higher = bisect.bisect_right(c_sorted, value)
... |
def d(x,y):
return abs(x-y) > 1
def filtra(it, func):
try:
primeiro = next(it)
while True:
atual = next(it)
if func(atual, primeiro):
return atual
else:
atual = next(it)
except StopIteration:
return... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from roi_pooling.modules.roi_pool import _RoIPooling
from roi_align.modules.roi_align import RoIAlign
from .operations import PRIMITIVES, MixedOp
from .boxes_handling import *
class NASGCN(nn.Module):
def __init_... |
def display(name,id):
print("Name: ",name," -> ID: ",id)
a = "Mehedi Amin"
b = "105-10-200"
display(a,b)
def sum (a,b):
d = a+b
return d
a = 5
b = 6
c = sum(a,b)
print(c)
|
import re
pattern = r"\d+"
string = "This is 100yen."
print(re.search(pattern, string))
words = [
"oragee", "ocotorber", "octpus", "order", "banana", "baby", "busy"
]
pattern = r"oc.*"
print(pattern)
for word in words:
if re.match(pattern, word):
print("-", word)
pattern = r"(\d{4})/(\d{1,2})/(\d{1,... |
import networkz.algorithms.traversal.depth_first_search
from networkz.algorithms.traversal.depth_first_search import *
import networkz.algorithms.traversal.breadth_first_search
from networkz.algorithms.traversal.breadth_first_search import *
|
import pandas as pd
from constants import *
df = pd.read_csv("weather.csv", encoding='windows-1250', squeeze=True)
df_sort = df.sort_values(by=['Kod stacji', 'Rok', 'Miesiac', 'Dzien'])
df_city = df_sort.loc[df_sort['Nazwa stacji'] == CITY]
df_city_chosen = df_city.iloc[:, [5, 6, 7, 11, 12]]
df_city_chosen.to_csv(DEST... |
from selectable.base import ModelLookup
from selectable.registry import registry
from cities.models import Region
class RegionLookup(ModelLookup):
model = Region
search_fields = ('name__icontains', )
filters = {'country__code': "CA", }
def get_item_value(self, item):
return item.name
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 20:39:00 2020
@author: MARCOS TIEPPO
"""
import os
import numpy as np
from math import sqrt
#Define working directory
os.chdir('C:/working_directory')
#Open file with slope values for one model
f=open("slope_values_for_one_model.txt","r")
lines2=f.read... |
import pygame
pygame.display.Info() |
import numpy as np
import scipy
import math
from scipy.signal import convolve2d as conv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def estimateT(Jgdx, Jgdy, x, y, window_size):
T = np.zeros((window_size[0],window_size[1],3))
left = math.floor(x-window_size[1]/2)
top = math.floor(y-wi... |
def greet(name):
print('Hi' name, 'how are you doing?')
print(' - Python')
|
""" The nodes used in the service registry browser tree. """
# Enthought library imports.
from envisage.api import IExtensionPoint, IServiceRegistry
from traits.api import Any, Dict, HasTraits, Instance, Int, List
from traits.api import Property, Str, Undefined
from traitsui.api import TreeNode
# fixme: non-api impo... |
#!/usr/bin/env python
# coding: utf-8
# ### Author: Akshay Ijantkar
# ### Team: Aqua Wizards
# ### Project: Surfers Bible
# * https://launchschool.com/books/sql/read/table_relationships
# # Import Libraries:
# 0 1 * * * /usr/bin/python3 /home/ubuntu/pop_db_sch_ss/Daily_Scheduler_Swell_Pollution_Astro_News_API.py >>... |
def matchTwistAngle(twistAttribute, ikJoints, targetJoints):
currentVector = []
targetVector = []
currentVector = calculateTwistVector(ikJoints[0], ikJoints[1], ikJoints[len(ikJoints)-1])
targetVector = calculateTwistVector(targetJoints[0], targetJoints[1], targetJoints[len(targetJoints)-1])
... |
#Choose F->C or C-F conversion
direction = str(raw_input('Enter "F" for Fahrenheit to Celsius, Enter "C" for Celsius to Fahrenheit\n'))
if direction == 'F':
try:
f = float(raw_input('Fahrenheit?\n'))
print f,'Fahrenheit equals',(f-32)*(.5556), 'degrees Celsius.'
except:
print 'Inv... |
import webapp2 # what handles going to a browser
from page import Page
#master class
class MainHandler(webapp2.RequestHandler):
#unique ti framework...
#THIS FUNCTION RUNS FIRST!! CATALYST
def get(self):
#start writing the code
if self.request.GET:
info = self.request.GET... |
from django.db import models
# Create your model
class ContactsTable(models.Model):
name=models.CharField(max_length=256)
family=models.CharField(max_length=256)
job=models.CharField(max_length=10)
def __str__(self):
return self.name
class PhonesTable(models.Model):
contacts=models.Forei... |
import pandas as pd
from autumn.core.db import Database
from autumn.core.utils.utils import create_date_index
from autumn.settings.constants import COVID_BASE_DATETIME
from .fetch import COVID_MYS_DIRPATH, COVID_MYS_VAC_CSV
FILTER_COL = {
"partial_5_11",
"full_5_11",
"booster_5_11",
"partial_12_17",
... |
def equal_rows(matrix):
rows = [sum(element) for element in matrix]
return len(set(rows)) == 1
def equal_columns(matrix):
columns = list(zip(*matrix))
return len(set(map(sum, columns))) == 1
def equal_diagonals(matrix):
diagonal = [elem[index] for index, elem in enumerate(matrix)]
reversal_d... |
import os
import re
import json
import spacy
import codecs
from collections import Counter
def main():
lyrics = {}
with open('corpus_data/newlyrics.json') as lyric_file:
corpus = json.loads(lyric_file.read().encode('utf-8'))
nlp = spacy.load('en_core_web_sm')
corpus = {artist:[el for el in songl... |
#!/usr/bin/python
"""
Script to anonymize QIF data by randomizing it's input.
For development and demonstration purposes only.
"""
import sys
from os import urandom
from random import random, choice
from binascii import hexlify
UNIQUES = set()
FAKE_ACCOUNTS = [
('Counterparty 1', 'LU11 1111 1234 0001 0000'),
... |
# Use words.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
for line in fh:
text=line.rstrip().upper()
print text
|
"""This module contains the parser/generators (or coders/encoders if you
prefer) for the classes/datatypes that are used in iCalendar:
###########################################################################
# This module defines these property value data types and property parameters
4.2 Defined property paramete... |
from django.apps import AppConfig
class StatuslogConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'statuslog'
|
from django.shortcuts import render, redirect, HttpResponse, reverse
from django.contrib import messages
from models import Book
# Create your views here.
def new_book(request):
book = Book.objects.create_book(request.POST)
context = {
"books": Book.objects.all(),
"user": request.session['user']
}
if book['cr... |
from ED6ScenarioHelper import *
def main():
# 艾利兹街道
CreateScenaFile(
FileName = 'T0100 ._SN',
MapName = 'rolent',
Location = 'T0100.x',
MapIndex = 1,
MapDefaultBGM = "ed60010",
Flags = 0,
... |
idx = 1
while idx <= 10:
print(idx ** 2)
idx += 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.